|
import streamlit as st |
|
import os |
|
import random |
|
import hashlib |
|
import json |
|
from datetime import datetime |
|
|
|
|
|
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'] |
|
|
|
|
|
def load_vote_history(): |
|
try: |
|
with open('vote_history.json', 'r') as f: |
|
return json.load(f) |
|
except FileNotFoundError: |
|
return {} |
|
|
|
|
|
def save_vote_history(history): |
|
with open('vote_history.json', 'w') as f: |
|
json.dump(history, f) |
|
|
|
|
|
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") |
|
|
|
|
|
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) |
|
|
|
|
|
def handle_vote(image_name): |
|
user_hash = generate_user_hash() |
|
vote_history = load_vote_history() |
|
|
|
if image_name not in vote_history: |
|
vote_history[image_name] = {'votes': 0, 'users': []} |
|
|
|
if user_hash not in vote_history[image_name]['users']: |
|
vote_history[image_name]['votes'] += 1 |
|
vote_history[image_name]['users'].append(user_hash) |
|
save_vote_history(vote_history) |
|
update_history_md(image_name, user_hash) |
|
st.success(f"Upvoted {image_name}! Total votes: {vote_history[image_name]['votes']}") |
|
else: |
|
st.warning("You've already voted for this image.") |
|
|
|
|
|
def show_vote_history(): |
|
st.sidebar.title("Vote History") |
|
vote_history = load_vote_history() |
|
|
|
|
|
sorted_images = sorted(vote_history.items(), key=lambda x: x[1]['votes'], reverse=True) |
|
|
|
for i, (image_name, data) in enumerate(sorted_images): |
|
votes = data['votes'] |
|
st.sidebar.write(f"{image_name}: {votes} votes") |
|
|
|
|
|
if i < 3: |
|
st.sidebar.image(os.path.join('.', image_name), caption=f"#{i+1}: {image_name}", width=150) |
|
|
|
|
|
def main(): |
|
st.title("Image Voting App") |
|
|
|
|
|
show_vote_history() |
|
|
|
|
|
image_dir = '.' |
|
display_images(image_dir) |
|
|
|
|
|
st.sidebar.write(f"Your User ID: {generate_user_hash()}") |
|
|
|
|
|
if __name__ == "__main__": |
|
main() |