awacke1's picture
Create app.py
1e77d79 verified
raw
history blame
2.18 kB
import streamlit as st
import os
import random
# ๐Ÿ–ผ๏ธ 1. Display two columns, each with a random image from the directory
def display_images(image_dir):
"""๐Ÿ–ผ๏ธ Function 1: Displays two random images side by side for voting."""
col1, col2 = st.columns(2)
# ๐Ÿ—‚๏ธ Load random images from directory
images = os.listdir(image_dir)
# ๐Ÿ“ธ Randomly select two images
image1 = random.choice(images)
image2 = random.choice(images)
with col1:
st.image(os.path.join(image_dir, image1))
if st.button(f"Upvote {image1}"):
handle_vote(image1)
with col2:
st.image(os.path.join(image_dir, image2))
if st.button(f"Upvote {image2}"):
handle_vote(image2)
# ๐ŸŽฏ 2. Handle the voting logic and store the history
def handle_vote(image_name):
"""๐ŸŽฏ Function 2: Handles voting and stores vote history."""
# โœ… Save the upvote to session state or database
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]}")
# ๐Ÿ“Š 3. Sidebar to show vote history
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!")
# โš™๏ธ 4. Main function to structure app execution
def main():
"""โš™๏ธ Function 4: Main function to run the app."""
st.title("Image Voting App")
# ๐ŸŽจ Set up the sidebar for vote history
show_vote_history()
# ๐Ÿ–ผ๏ธ Display images for voting
image_dir = './images' # Set your directory path with images
display_images(image_dir)
# ๐Ÿš€ 5. Run the app
if __name__ == "__main__":
main()