awacke1 commited on
Commit
c56b6d6
·
verified ·
1 Parent(s): 7fd33a7

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +169 -0
app.py ADDED
@@ -0,0 +1,169 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import os
3
+ import random
4
+ import hashlib
5
+ import json
6
+ from datetime import datetime
7
+ from collections import Counter
8
+ import re
9
+ import time
10
+
11
+ # Function to generate a short user hash
12
+ def generate_user_hash():
13
+ if 'user_hash' not in st.session_state:
14
+ session_id = str(random.getrandbits(128))
15
+ hash_object = hashlib.md5(session_id.encode())
16
+ st.session_state['user_hash'] = hash_object.hexdigest()[:8]
17
+ return st.session_state['user_hash']
18
+
19
+ # Function to load vote history from file
20
+ def load_vote_history():
21
+ try:
22
+ with open('vote_history.json', 'r') as f:
23
+ return json.load(f)
24
+ except FileNotFoundError:
25
+ return {'images': {}, 'users': {}, 'words': {}}
26
+
27
+ # Function to save vote history to file
28
+ def save_vote_history(history):
29
+ with open('vote_history.json', 'w') as f:
30
+ json.dump(history, f)
31
+
32
+ # Function to update vote history in Markdown file
33
+ def update_history_md(image_name, user_hash):
34
+ with open('history.md', 'a') as f:
35
+ f.write(f"- {datetime.now().strftime('%Y-%m-%d %H:%M:%S')} - User {user_hash} voted for {image_name}\n")
36
+
37
+ # Function to extract words from file name
38
+ def extract_words(filename):
39
+ words = re.findall(r'\w+', filename.lower())
40
+ return [word for word in words if len(word) > 2]
41
+
42
+ # Function to update word counts
43
+ def update_word_counts(history, image_name):
44
+ words = extract_words(image_name)
45
+ for word in words:
46
+ if word not in history['words']:
47
+ history['words'][word] = 0
48
+ history['words'][word] += 1
49
+
50
+ # Function to display images
51
+ def display_images(image_dir):
52
+ col1, col2 = st.columns(2)
53
+ valid_extensions = ('.png', '.jpg', '.jpeg', '.gif', '.bmp', '.tiff', '.webp')
54
+ images = [f for f in os.listdir(image_dir) if f.lower().endswith(valid_extensions)]
55
+
56
+ if len(images) < 2:
57
+ st.error("Not enough images in the directory.")
58
+ return
59
+
60
+ image1, image2 = random.sample(images, 2)
61
+ with col1:
62
+ st.image(os.path.join(image_dir, image1))
63
+ if st.button(f"Upvote {image1}", key=f"upvote_{image1}"):
64
+ handle_vote(image1)
65
+
66
+ with col2:
67
+ st.image(os.path.join(image_dir, image2))
68
+ if st.button(f"Upvote {image2}", key=f"upvote_{image2}"):
69
+ handle_vote(image2)
70
+
71
+ # Function to handle voting
72
+ def handle_vote(image_name):
73
+ user_hash = generate_user_hash()
74
+ vote_history = load_vote_history()
75
+
76
+ if image_name not in vote_history['images']:
77
+ vote_history['images'][image_name] = {'votes': 0, 'users': {}}
78
+
79
+ if user_hash not in vote_history['users']:
80
+ vote_history['users'][user_hash] = 0
81
+
82
+ vote_history['images'][image_name]['votes'] += 1
83
+ if user_hash not in vote_history['images'][image_name]['users']:
84
+ vote_history['images'][image_name]['users'][user_hash] = 0
85
+ vote_history['images'][image_name]['users'][user_hash] += 1
86
+ vote_history['users'][user_hash] += 1
87
+
88
+ update_word_counts(vote_history, image_name)
89
+ save_vote_history(vote_history)
90
+ update_history_md(image_name, user_hash)
91
+ st.success(f"Upvoted {image_name}! Total votes: {vote_history['images'][image_name]['votes']}")
92
+
93
+ # Reset the timer when a vote is cast
94
+ st.session_state.last_interaction = time.time()
95
+
96
+ # Function to show vote history and user stats in sidebar
97
+ def show_vote_history():
98
+ st.sidebar.title("Vote History")
99
+ vote_history = load_vote_history()
100
+
101
+ # Sort users by total votes
102
+ sorted_users = sorted(vote_history['users'].items(), key=lambda x: x[1], reverse=True)
103
+
104
+ st.sidebar.subheader("User Vote Totals")
105
+ for user_hash, votes in sorted_users:
106
+ st.sidebar.write(f"User {user_hash}: {votes} votes")
107
+
108
+ # Sort images by vote count
109
+ sorted_images = sorted(vote_history['images'].items(), key=lambda x: x[1]['votes'], reverse=True)
110
+
111
+ st.sidebar.subheader("Image Vote Totals")
112
+ for i, (image_name, data) in enumerate(sorted_images):
113
+ votes = data['votes']
114
+ st.sidebar.write(f"{image_name}: {votes} votes")
115
+
116
+ # Display top 3 images
117
+ if i < 3:
118
+ st.sidebar.image(os.path.join('.', image_name), caption=f"#{i+1}: {image_name}", width=150)
119
+
120
+ # Display top 3 words
121
+ st.sidebar.subheader("Top 3 Words in Voted Images")
122
+ top_words = sorted(vote_history['words'].items(), key=lambda x: x[1], reverse=True)[:3]
123
+ for word, count in top_words:
124
+ st.sidebar.write(f"{word}: {count} occurrences")
125
+
126
+ # Function to add refresh rate slider
127
+ def add_refresh_rate_slider():
128
+ st.sidebar.subheader("Refresh Settings")
129
+ refresh_rate = st.sidebar.slider("Refresh rate (seconds)", 0, 120, 30,
130
+ help="Set to 0 for no auto-refresh")
131
+ return refresh_rate
132
+
133
+ # Main function
134
+ def main():
135
+ st.title("Image Voting App")
136
+
137
+ # Initialize last interaction time if not set
138
+ if 'last_interaction' not in st.session_state:
139
+ st.session_state.last_interaction = time.time()
140
+
141
+ # Set up the sidebar for vote history and user stats
142
+ show_vote_history()
143
+
144
+ # Display images for voting
145
+ image_dir = '.' # Current directory where the app is running
146
+ display_images(image_dir)
147
+
148
+ # Display user hash
149
+ st.sidebar.subheader("Your User ID")
150
+ st.sidebar.write(generate_user_hash())
151
+
152
+ # Add refresh rate slider
153
+ refresh_rate = add_refresh_rate_slider()
154
+
155
+ # Check if it's time to refresh
156
+ if refresh_rate > 0:
157
+ time_since_last_interaction = time.time() - st.session_state.last_interaction
158
+ if time_since_last_interaction >= refresh_rate:
159
+ st.session_state.last_interaction = time.time()
160
+ st.rerun()
161
+
162
+ # Update last interaction time when the page is interacted with
163
+ if st.button("Refresh Now"):
164
+ st.session_state.last_interaction = time.time()
165
+ st.rerun()
166
+
167
+ # Run the app
168
+ if __name__ == "__main__":
169
+ main()