awacke1 commited on
Commit
62cb7f1
·
verified ·
1 Parent(s): 0dd76b6

Create app.py

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