File size: 5,952 Bytes
c56b6d6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
import streamlit as st
import os
import random
import hashlib
import json
from datetime import datetime
from collections import Counter
import re
import time

# Function to generate a short user hash
def generate_user_hash():
    if 'user_hash' not in st.session_state:
        session_id = str(random.getrandbits(128))
        hash_object = hashlib.md5(session_id.encode())
        st.session_state['user_hash'] = hash_object.hexdigest()[:8]
    return st.session_state['user_hash']

# Function to load vote history from file
def load_vote_history():
    try:
        with open('vote_history.json', 'r') as f:
            return json.load(f)
    except FileNotFoundError:
        return {'images': {}, 'users': {}, 'words': {}}

# Function to save vote history to file
def save_vote_history(history):
    with open('vote_history.json', 'w') as f:
        json.dump(history, f)

# Function to update vote history in Markdown file
def update_history_md(image_name, user_hash):
    with open('history.md', 'a') as f:
        f.write(f"- {datetime.now().strftime('%Y-%m-%d %H:%M:%S')} - User {user_hash} voted for {image_name}\n")

# Function to extract words from file name
def extract_words(filename):
    words = re.findall(r'\w+', filename.lower())
    return [word for word in words if len(word) > 2]

# Function to update word counts
def update_word_counts(history, image_name):
    words = extract_words(image_name)
    for word in words:
        if word not in history['words']:
            history['words'][word] = 0
        history['words'][word] += 1

# Function to display images
def display_images(image_dir):
    col1, col2 = st.columns(2)
    valid_extensions = ('.png', '.jpg', '.jpeg', '.gif', '.bmp', '.tiff', '.webp')
    images = [f for f in os.listdir(image_dir) if f.lower().endswith(valid_extensions)]
    
    if len(images) < 2:
        st.error("Not enough images in the directory.")
        return
    
    image1, image2 = random.sample(images, 2)
    with col1:
        st.image(os.path.join(image_dir, image1))
        if st.button(f"Upvote {image1}", key=f"upvote_{image1}"):
            handle_vote(image1)
    
    with col2:
        st.image(os.path.join(image_dir, image2))
        if st.button(f"Upvote {image2}", key=f"upvote_{image2}"):
            handle_vote(image2)

# Function to handle voting
def handle_vote(image_name):
    user_hash = generate_user_hash()
    vote_history = load_vote_history()
    
    if image_name not in vote_history['images']:
        vote_history['images'][image_name] = {'votes': 0, 'users': {}}
    
    if user_hash not in vote_history['users']:
        vote_history['users'][user_hash] = 0
    
    vote_history['images'][image_name]['votes'] += 1
    if user_hash not in vote_history['images'][image_name]['users']:
        vote_history['images'][image_name]['users'][user_hash] = 0
    vote_history['images'][image_name]['users'][user_hash] += 1
    vote_history['users'][user_hash] += 1
    
    update_word_counts(vote_history, image_name)
    save_vote_history(vote_history)
    update_history_md(image_name, user_hash)
    st.success(f"Upvoted {image_name}! Total votes: {vote_history['images'][image_name]['votes']}")
    
    # Reset the timer when a vote is cast
    st.session_state.last_interaction = time.time()

# Function to show vote history and user stats in sidebar
def show_vote_history():
    st.sidebar.title("Vote History")
    vote_history = load_vote_history()
    
    # Sort users by total votes
    sorted_users = sorted(vote_history['users'].items(), key=lambda x: x[1], reverse=True)
    
    st.sidebar.subheader("User Vote Totals")
    for user_hash, votes in sorted_users:
        st.sidebar.write(f"User {user_hash}: {votes} votes")
    
    # Sort images by vote count
    sorted_images = sorted(vote_history['images'].items(), key=lambda x: x[1]['votes'], reverse=True)
    
    st.sidebar.subheader("Image Vote Totals")
    for i, (image_name, data) in enumerate(sorted_images):
        votes = data['votes']
        st.sidebar.write(f"{image_name}: {votes} votes")
        
        # Display top 3 images
        if i < 3:
            st.sidebar.image(os.path.join('.', image_name), caption=f"#{i+1}: {image_name}", width=150)
    
    # Display top 3 words
    st.sidebar.subheader("Top 3 Words in Voted Images")
    top_words = sorted(vote_history['words'].items(), key=lambda x: x[1], reverse=True)[:3]
    for word, count in top_words:
        st.sidebar.write(f"{word}: {count} occurrences")

# Function to add refresh rate slider
def add_refresh_rate_slider():
    st.sidebar.subheader("Refresh Settings")
    refresh_rate = st.sidebar.slider("Refresh rate (seconds)", 0, 120, 30, 
                                     help="Set to 0 for no auto-refresh")
    return refresh_rate

# Main function
def main():
    st.title("Image Voting App")
    
    # Initialize last interaction time if not set
    if 'last_interaction' not in st.session_state:
        st.session_state.last_interaction = time.time()
    
    # Set up the sidebar for vote history and user stats
    show_vote_history()
    
    # Display images for voting
    image_dir = '.'  # Current directory where the app is running
    display_images(image_dir)
    
    # Display user hash
    st.sidebar.subheader("Your User ID")
    st.sidebar.write(generate_user_hash())
    
    # Add refresh rate slider
    refresh_rate = add_refresh_rate_slider()
    
    # Check if it's time to refresh
    if refresh_rate > 0:
        time_since_last_interaction = time.time() - st.session_state.last_interaction
        if time_since_last_interaction >= refresh_rate:
            st.session_state.last_interaction = time.time()
            st.rerun()
    
    # Update last interaction time when the page is interacted with
    if st.button("Refresh Now"):
        st.session_state.last_interaction = time.time()
        st.rerun()

# Run the app
if __name__ == "__main__":
    main()