|
import streamlit as st |
|
import os |
|
import random |
|
|
|
|
|
def display_images(image_dir): |
|
"""๐ผ๏ธ Function 1: Displays two random images side by side for voting, filtered to only show image files.""" |
|
|
|
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): |
|
"""๐ฏ Function 2: Handles voting and stores vote history.""" |
|
|
|
if 'vote_history' not in st.session_state: |
|
st.session_state['vote_history'] = {} |
|
|
|
if image_name in st.session_state['vote_history']: |
|
st.session_state['vote_history'][image_name] += 1 |
|
else: |
|
st.session_state['vote_history'][image_name] = 1 |
|
|
|
st.success(f"Upvoted {image_name}! Total votes: {st.session_state['vote_history'][image_name]}") |
|
|
|
|
|
def show_vote_history(): |
|
"""๐ Function 3: Displays the vote history in the sidebar.""" |
|
st.sidebar.title("Vote History") |
|
if 'vote_history' in st.session_state: |
|
for image_name, votes in st.session_state['vote_history'].items(): |
|
st.sidebar.write(f"{image_name}: {votes} votes") |
|
else: |
|
st.sidebar.write("No votes yet!") |
|
|
|
|
|
def main(): |
|
"""โ๏ธ Function 4: Main function to run the app.""" |
|
st.title("Image Voting App") |
|
|
|
|
|
show_vote_history() |
|
|
|
|
|
image_dir = '.' |
|
display_images(image_dir) |
|
|
|
|
|
if __name__ == "__main__": |
|
main() |
|
|