awacke1 commited on
Commit
396d416
·
verified ·
1 Parent(s): 70e8b84

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +189 -0
app.py ADDED
@@ -0,0 +1,189 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # Your existing quotes list
12
+ quotes = [
13
+ {"Number": 1, "Quote Topic": "Stages of Life 🌱", "Quote": "Every age unfolds a new lesson. Life's chapters evolve, each teaching us anew."},
14
+ # ... (rest of the quotes)
15
+ {"Number": 100, "Quote Topic": "Love ❤️", "Quote": "Through love, we find connection, unity, and the essence of existence."}
16
+ ]
17
+
18
+ # Function to generate a short user hash
19
+ def generate_user_hash():
20
+ if 'user_hash' not in st.session_state:
21
+ session_id = str(random.getrandbits(128))
22
+ hash_object = hashlib.md5(session_id.encode())
23
+ st.session_state['user_hash'] = hash_object.hexdigest()[:8]
24
+ return st.session_state['user_hash']
25
+
26
+ # Function to load vote history from file
27
+ def load_vote_history():
28
+ try:
29
+ with open('vote_history.json', 'r') as f:
30
+ return json.load(f)
31
+ except FileNotFoundError:
32
+ return {'images': {}, 'users': {}, 'words': {}}
33
+
34
+ # Function to save vote history to file
35
+ def save_vote_history(history):
36
+ with open('vote_history.json', 'w') as f:
37
+ json.dump(history, f)
38
+
39
+ # Function to update vote history in Markdown file
40
+ def update_history_md(image_name, user_hash):
41
+ with open('history.md', 'a') as f:
42
+ f.write(f"- {datetime.now().strftime('%Y-%m-%d %H:%M:%S')} - User {user_hash} voted for {image_name}\n")
43
+
44
+ # Function to extract words from file name
45
+ def extract_words(filename):
46
+ words = re.findall(r'\w+', filename.lower())
47
+ return [word for word in words if len(word) > 2]
48
+
49
+ # Function to update word counts
50
+ def update_word_counts(history, image_name):
51
+ words = extract_words(image_name)
52
+ for word in words:
53
+ if word not in history['words']:
54
+ history['words'][word] = 0
55
+ history['words'][word] += 1
56
+
57
+ # Function to display images
58
+ def display_images(image_dir):
59
+ col1, col2 = st.columns(2)
60
+ valid_extensions = ('.png', '.jpg', '.jpeg', '.gif', '.bmp', '.tiff', '.webp')
61
+ images = [f for f in os.listdir(image_dir) if f.lower().endswith(valid_extensions)]
62
+
63
+ if len(images) < 2:
64
+ st.error("Not enough images in the directory.")
65
+ return
66
+
67
+ image1, image2 = random.sample(images, 2)
68
+ with col1:
69
+ st.image(os.path.join(image_dir, image1))
70
+ if st.button(f"Upvote {image1}", key=f"upvote_{image1}"):
71
+ handle_vote(image1)
72
+
73
+ with col2:
74
+ st.image(os.path.join(image_dir, image2))
75
+ if st.button(f"Upvote {image2}", key=f"upvote_{image2}"):
76
+ handle_vote(image2)
77
+
78
+ # Function to handle voting
79
+ def handle_vote(image_name):
80
+ user_hash = generate_user_hash()
81
+ vote_history = load_vote_history()
82
+
83
+ if image_name not in vote_history['images']:
84
+ vote_history['images'][image_name] = {'votes': 0, 'users': {}}
85
+
86
+ if user_hash not in vote_history['users']:
87
+ vote_history['users'][user_hash] = 0
88
+
89
+ vote_history['images'][image_name]['votes'] += 1
90
+ if user_hash not in vote_history['images'][image_name]['users']:
91
+ vote_history['images'][image_name]['users'][user_hash] = 0
92
+ vote_history['images'][image_name]['users'][user_hash] += 1
93
+ vote_history['users'][user_hash] += 1
94
+
95
+ update_word_counts(vote_history, image_name)
96
+ save_vote_history(vote_history)
97
+ update_history_md(image_name, user_hash)
98
+ st.success(f"Upvoted {image_name}! Total votes: {vote_history['images'][image_name]['votes']}")
99
+
100
+ # Reset the timer when a vote is cast
101
+ st.session_state.last_interaction = time.time()
102
+
103
+ # Function to show vote history and user stats in sidebar
104
+ def show_vote_history():
105
+ st.sidebar.title("Vote History")
106
+ vote_history = load_vote_history()
107
+
108
+ # Sort users by total votes
109
+ sorted_users = sorted(vote_history['users'].items(), key=lambda x: x[1], reverse=True)
110
+
111
+ st.sidebar.subheader("User Vote Totals")
112
+ for user_hash, votes in sorted_users:
113
+ st.sidebar.write(f"User {user_hash}: {votes} votes")
114
+
115
+ # Sort images by vote count
116
+ sorted_images = sorted(vote_history['images'].items(), key=lambda x: x[1]['votes'], reverse=True)
117
+
118
+ st.sidebar.subheader("Image Vote Totals")
119
+ for i, (image_name, data) in enumerate(sorted_images):
120
+ votes = data['votes']
121
+ st.sidebar.write(f"{image_name}: {votes} votes")
122
+
123
+ # Display top 3 images
124
+ if i < 3:
125
+ st.sidebar.image(os.path.join('.', image_name), caption=f"#{i+1}: {image_name}", width=150)
126
+
127
+ # Display top 3 words
128
+ st.sidebar.subheader("Top 3 Words in Voted Images")
129
+ top_words = sorted(vote_history['words'].items(), key=lambda x: x[1], reverse=True)[:3]
130
+ for word, count in top_words:
131
+ st.sidebar.write(f"{word}: {count} occurrences")
132
+
133
+ # Function to display a random quote
134
+ def display_random_quote():
135
+ quote = random.choice(quotes)
136
+ st.markdown(f"### {quote['Number']}. {quote['Quote Topic']}")
137
+ st.markdown(quote['Quote'])
138
+
139
+ # Main function
140
+ def main():
141
+ st.title("Image Voting App with Quotes")
142
+
143
+ # Initialize session state variables
144
+ if 'last_interaction' not in st.session_state:
145
+ st.session_state.last_interaction = time.time()
146
+ if 'auto_repeat' not in st.session_state:
147
+ st.session_state.auto_repeat = "On"
148
+
149
+ # Set up the sidebar for vote history and user stats
150
+ show_vote_history()
151
+
152
+ # Display images for voting
153
+ image_dir = '.' # Current directory where the app is running
154
+ display_images(image_dir)
155
+
156
+ # Display user hash
157
+ st.sidebar.subheader("Your User ID")
158
+ st.sidebar.write(generate_user_hash())
159
+
160
+ # Add refresh rate slider
161
+ refresh_rate = st.sidebar.slider("Refresh rate (seconds)", 0, 120, 30,
162
+ help="Set to 0 for no auto-refresh")
163
+
164
+ # AutoRepeat radio button
165
+ st.session_state.auto_repeat = st.sidebar.radio("🔄 AutoRepeat", ["On", "Off"], horizontal=True)
166
+
167
+ # Display random quote
168
+ st.subheader("Quote of the Moment")
169
+ display_random_quote()
170
+
171
+ # Check if it's time to refresh
172
+ if refresh_rate > 0 and st.session_state.auto_repeat == "On":
173
+ time_since_last_interaction = time.time() - st.session_state.last_interaction
174
+ if time_since_last_interaction >= refresh_rate:
175
+ st.session_state.last_interaction = time.time()
176
+ st.experimental_rerun()
177
+ else:
178
+ # Display countdown
179
+ time_left = int(refresh_rate - time_since_last_interaction)
180
+ st.write(f"Time until next refresh: {time_left} seconds")
181
+
182
+ # Manual refresh button
183
+ if st.button("Refresh Now"):
184
+ st.session_state.last_interaction = time.time()
185
+ st.experimental_rerun()
186
+
187
+ # Run the app
188
+ if __name__ == "__main__":
189
+ main()