Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,65 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
+
import os
|
3 |
+
import random
|
4 |
+
|
5 |
+
# 🖼️ 1. Display two columns, each with a random image from the directory
|
6 |
+
def display_images(image_dir):
|
7 |
+
"""🖼️ Function 1: Displays two random images side by side for voting."""
|
8 |
+
col1, col2 = st.columns(2)
|
9 |
+
|
10 |
+
# 🗂️ Load random images from directory
|
11 |
+
images = os.listdir(image_dir)
|
12 |
+
|
13 |
+
# 📸 Randomly select two images
|
14 |
+
image1 = random.choice(images)
|
15 |
+
image2 = random.choice(images)
|
16 |
+
|
17 |
+
with col1:
|
18 |
+
st.image(os.path.join(image_dir, image1))
|
19 |
+
if st.button(f"Upvote {image1}"):
|
20 |
+
handle_vote(image1)
|
21 |
+
|
22 |
+
with col2:
|
23 |
+
st.image(os.path.join(image_dir, image2))
|
24 |
+
if st.button(f"Upvote {image2}"):
|
25 |
+
handle_vote(image2)
|
26 |
+
|
27 |
+
# 🎯 2. Handle the voting logic and store the history
|
28 |
+
def handle_vote(image_name):
|
29 |
+
"""🎯 Function 2: Handles voting and stores vote history."""
|
30 |
+
# ✅ Save the upvote to session state or database
|
31 |
+
if 'vote_history' not in st.session_state:
|
32 |
+
st.session_state['vote_history'] = {}
|
33 |
+
|
34 |
+
if image_name in st.session_state['vote_history']:
|
35 |
+
st.session_state['vote_history'][image_name] += 1
|
36 |
+
else:
|
37 |
+
st.session_state['vote_history'][image_name] = 1
|
38 |
+
|
39 |
+
st.success(f"Upvoted {image_name}! Total votes: {st.session_state['vote_history'][image_name]}")
|
40 |
+
|
41 |
+
# 📊 3. Sidebar to show vote history
|
42 |
+
def show_vote_history():
|
43 |
+
"""📊 Function 3: Displays the vote history in the sidebar."""
|
44 |
+
st.sidebar.title("Vote History")
|
45 |
+
if 'vote_history' in st.session_state:
|
46 |
+
for image_name, votes in st.session_state['vote_history'].items():
|
47 |
+
st.sidebar.write(f"{image_name}: {votes} votes")
|
48 |
+
else:
|
49 |
+
st.sidebar.write("No votes yet!")
|
50 |
+
|
51 |
+
# ⚙️ 4. Main function to structure app execution
|
52 |
+
def main():
|
53 |
+
"""⚙️ Function 4: Main function to run the app."""
|
54 |
+
st.title("Image Voting App")
|
55 |
+
|
56 |
+
# 🎨 Set up the sidebar for vote history
|
57 |
+
show_vote_history()
|
58 |
+
|
59 |
+
# 🖼️ Display images for voting
|
60 |
+
image_dir = './images' # Set your directory path with images
|
61 |
+
display_images(image_dir)
|
62 |
+
|
63 |
+
# 🚀 5. Run the app
|
64 |
+
if __name__ == "__main__":
|
65 |
+
main()
|