jayanth-2005 commited on
Commit
34c2ee5
Β·
verified Β·
1 Parent(s): 8a8fe0b

Upload 5 files

Browse files
src/pages/2_Outdoor.py ADDED
@@ -0,0 +1,157 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datetime import datetime
2
+ import os
3
+ import tempfile
4
+ import requests
5
+ from database import save_submission
6
+ import streamlit as st
7
+
8
+ st.set_page_config(page_title="Outdoor Game Submission", layout="wide")
9
+
10
+ if "authenticated" not in st.session_state or not st.session_state.authenticated:
11
+ st.error("πŸ” Please log in to access this page.")
12
+ st.stop()
13
+
14
+ st.title("🌳 Contribute an Outdoor Game")
15
+ category = "Outdoor"
16
+
17
+ # Use a shared uploads folder in a safe temp directory
18
+ upload_dir = os.path.join(tempfile.gettempdir(), "uploads")
19
+
20
+ # Ensure uploads folder exists
21
+ os.makedirs(upload_dir, exist_ok=True)
22
+
23
+ # Location Detection
24
+ def get_ip_location():
25
+ try:
26
+ import urllib3
27
+ urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
28
+ response = requests.get("https://ipinfo.io/json", verify=False)
29
+ data = response.json()
30
+ loc = data.get("loc")
31
+ if loc:
32
+ lat_str, lon_str = loc.split(",")
33
+ return float(lat_str), float(lon_str)
34
+ except:
35
+ pass
36
+ return None, None
37
+
38
+ # Get or set lat/lon
39
+ if "user_lat" not in st.session_state or "user_lon" not in st.session_state:
40
+ st.session_state["user_lat"], st.session_state["user_lon"] = get_ip_location()
41
+
42
+ lat = st.session_state.get("user_lat")
43
+ lon = st.session_state.get("user_lon")
44
+
45
+ # Show location info
46
+ st.subheader("πŸ“ Location Info")
47
+ if lat and lon:
48
+ st.success(f"πŸ“ Location detected: Latitude {lat:.4f}, Longitude {lon:.4f}")
49
+ else:
50
+ st.warning("⚠️ Location could not be detected.")
51
+
52
+ st.subheader("πŸ‘€ Game Details")
53
+ title = st.text_input("Game Title*", help="Enter the name of the game")
54
+ description = st.text_area("Game Description*", help="Explain how to play the game")
55
+ player_count = st.text_input("Number of Players", help="How many players are needed?")
56
+ age_group = st.selectbox("Age Group", ["All Ages", "Children", "Teenagers", "Adults"])
57
+ equipment = st.text_input("Required Equipment", help="List any equipment needed to play")
58
+
59
+ st.subheader("🧹 Select Input Type")
60
+ input_type = st.radio(
61
+ "Choose how you'd like to submit your contribution:",
62
+ ["πŸ“ Text", "🎹 Audio", "πŸ“Έ Photo", "🎩 Video"],
63
+ horizontal=True
64
+ )
65
+
66
+ title = description = None
67
+ audio_file = image_file = video_file = None
68
+
69
+ # Input handling
70
+ if input_type == "🎹 Audio":
71
+ audio_file = st.file_uploader("Upload Audio", type=["mp3", "wav"])
72
+ elif input_type == "πŸ“Έ Photo":
73
+ image_file = st.file_uploader("Upload Image", type=["jpg", "jpeg", "png"])
74
+ elif input_type == "🎩 Video":
75
+ video_file = st.file_uploader("Upload Video", type=["mp4", "mov"])
76
+
77
+ if (
78
+ input_type == "πŸ“ Text"
79
+ or (input_type == "🎹 Audio" and audio_file)
80
+ or (input_type == "πŸ“Έ Photo" and image_file)
81
+ or (input_type == "🎩 Video" and video_file)
82
+ ):
83
+ st.markdown("### πŸ‡ Add Game Details")
84
+ title = st.text_input("Game Title")
85
+ description = st.text_area("Short Description")
86
+
87
+ if st.button("βœ… Submit"):
88
+ if not title or not description:
89
+ st.error("Please fill all required fields.")
90
+ elif not st.session_state.get('name'):
91
+ st.error("Please log in to submit a game.")
92
+ else:
93
+ # Save uploaded files uniquely
94
+ timestamp = datetime.now().strftime("%Y%m%d%H%M%S")
95
+ audio_path = image_path = video_path = None
96
+
97
+ if audio_file:
98
+ audio_path = os.path.join(upload_dir, f"{timestamp}_{audio_file.name}")
99
+ with open(audio_path, "wb") as f:
100
+ f.write(audio_file.getbuffer())
101
+ if image_file:
102
+ image_path = os.path.join(upload_dir, f"{timestamp}_{image_file.name}")
103
+ with open(image_path, "wb") as f:
104
+ f.write(image_file.getbuffer())
105
+ if video_file:
106
+ video_path = os.path.join(upload_dir, f"{timestamp}_{video_file.name}")
107
+ with open(video_path, "wb") as f:
108
+ f.write(video_file.getbuffer())
109
+
110
+ # Save submission to database
111
+ name = st.session_state.get('name', '')
112
+ email = st.session_state.get('email', '')
113
+
114
+ save_submission(
115
+ category=category,
116
+ name=name,
117
+ email=email,
118
+ title=title,
119
+ description=description,
120
+ input_type=input_type,
121
+ audio_path=audio_path,
122
+ image_path=image_path,
123
+ video_path=video_path,
124
+ lat=lat,
125
+ lon=lon
126
+ )
127
+
128
+ st.success("πŸŽ‰ Game submitted successfully!")
129
+ st.experimental_rerun()
130
+
131
+ # Show Recent Submissions
132
+ st.markdown("---")
133
+ st.subheader("πŸ“Œ Recent Submissions")
134
+
135
+ from database import get_all_submissions
136
+ all_submissions = get_all_submissions()
137
+ # Filter submissions for this category
138
+ submissions = [s for s in all_submissions if s['category'] == category]
139
+
140
+ for submission in submissions:
141
+ title = submission['title']
142
+ name = submission['name']
143
+ description = submission['description']
144
+ timestamp = submission['timestamp']
145
+ audio = submission['audio_url']
146
+ image = submission['image_url']
147
+ video = submission['video_url']
148
+ video = submission[8]
149
+
150
+ with st.expander(f"πŸ”Ή {title} by {name} ({timestamp[:19]})"):
151
+ st.write(description)
152
+ if image and os.path.exists(image):
153
+ st.image(image, caption="πŸ“Έ Image")
154
+ if audio and os.path.exists(audio):
155
+ st.audio(audio)
156
+ if video and os.path.exists(video):
157
+ st.video(video)
src/pages/3_Traditional.py ADDED
@@ -0,0 +1,156 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datetime import datetime
2
+ import os
3
+ import tempfile
4
+ import requests
5
+ from database import save_submission
6
+ import streamlit as st
7
+
8
+ st.set_page_config(page_title="Traditional Game Submission", layout="wide")
9
+
10
+ if "authenticated" not in st.session_state or not st.session_state.authenticated:
11
+ st.error("πŸ” Please log in to access this page.")
12
+ st.stop()
13
+
14
+ # Change these for each file:
15
+ st.title("πŸͺ€ Contribute a Traditional Game")
16
+ category = "Traditional"
17
+
18
+ # Use a shared uploads folder in a safe temp directory
19
+ upload_dir = os.path.join(tempfile.gettempdir(), "uploads")
20
+
21
+ # Ensure uploads folder exists
22
+ os.makedirs(upload_dir, exist_ok=True)
23
+
24
+ # Location Detection
25
+ def get_ip_location():
26
+ try:
27
+ import urllib3
28
+ urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
29
+ response = requests.get("https://ipinfo.io/json", verify=False)
30
+ data = response.json()
31
+ loc = data.get("loc")
32
+ if loc:
33
+ lat_str, lon_str = loc.split(",")
34
+ return float(lat_str), float(lon_str)
35
+ except:
36
+ pass
37
+ return None, None
38
+
39
+ # Get or set lat/lon
40
+ if "user_lat" not in st.session_state or "user_lon" not in st.session_state:
41
+ st.session_state["user_lat"], st.session_state["user_lon"] = get_ip_location()
42
+
43
+ lat = st.session_state.get("user_lat")
44
+ lon = st.session_state.get("user_lon")
45
+
46
+ # Show location info
47
+ st.subheader("πŸ“ Location Info")
48
+ if lat and lon:
49
+ st.success(f"πŸ“ Location detected: Latitude {lat:.4f}, Longitude {lon:.4f}")
50
+ else:
51
+ st.warning("⚠️ Location could not be detected.")
52
+
53
+ st.subheader("πŸ‘€ Game Details")
54
+ title = st.text_input("Game Title*", help="Enter the name of the game")
55
+ description = st.text_area("Game Description*", help="Explain how to play the game")
56
+ player_count = st.text_input("Number of Players", help="How many players are needed?")
57
+ age_group = st.selectbox("Age Group", ["All Ages", "Children", "Teenagers", "Adults"])
58
+ equipment = st.text_input("Required Equipment", help="List any equipment needed to play")
59
+
60
+ st.subheader("🧹 Select Input Type")
61
+ input_type = st.radio(
62
+ "Choose how you'd like to submit your contribution:",
63
+ ["πŸ“ Text", "🎹 Audio", "πŸ“Έ Photo", "🎩 Video"],
64
+ horizontal=True
65
+ )
66
+
67
+ audio_file = image_file = video_file = None
68
+ audio_path = image_path = video_path = None
69
+
70
+ # Input handling
71
+ if input_type == "🎹 Audio":
72
+ audio_file = st.file_uploader("Upload Audio", type=["mp3", "wav"])
73
+ elif input_type == "πŸ“Έ Photo":
74
+ image_file = st.file_uploader("Upload Image", type=["jpg", "jpeg", "png"])
75
+ elif input_type == "🎩 Video":
76
+ video_file = st.file_uploader("Upload Video", type=["mp4", "mov"])
77
+
78
+ # Submit button
79
+ if st.button("πŸ“€ Submit Game"):
80
+ if not title or not description:
81
+ st.error("⚠️ Please fill in all required fields!")
82
+ else:
83
+ try:
84
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
85
+
86
+ # Handle file uploads
87
+ if audio_file:
88
+ audio_path = os.path.join(upload_dir, f"{timestamp}_{audio_file.name}")
89
+ with open(audio_path, "wb") as f:
90
+ f.write(audio_file.getbuffer())
91
+ if image_file:
92
+ image_path = os.path.join(upload_dir, f"{timestamp}_{image_file.name}")
93
+ with open(image_path, "wb") as f:
94
+ f.write(image_file.getbuffer())
95
+ if video_file:
96
+ video_path = os.path.join(upload_dir, f"{timestamp}_{video_file.name}")
97
+ with open(video_path, "wb") as f:
98
+ f.write(video_file.getbuffer())
99
+
100
+ # Use stored location from session state
101
+ lat = st.session_state.get("user_lat")
102
+ lon = st.session_state.get("user_lon")
103
+
104
+ # Prepare submission data
105
+ submission_data = {
106
+ 'name': st.session_state.get('name', ''), # Use logged-in username
107
+ 'title': title,
108
+ 'description': description,
109
+ 'category': category,
110
+ 'player_count': player_count,
111
+ 'age_group': age_group,
112
+ 'equipment_needed': equipment,
113
+ 'input_type': input_type,
114
+ 'audio_url': audio_path if audio_file else None,
115
+ 'image_url': image_path if image_file else None,
116
+ 'video_url': video_path if video_file else None,
117
+ 'lat': lat,
118
+ 'lon': lon
119
+ }
120
+
121
+ # Save to database
122
+ if save_submission(submission_data):
123
+ st.success("πŸŽ‰ Game submitted successfully!")
124
+ # Clear the form
125
+ st.experimental_rerun()
126
+ else:
127
+ st.error("Failed to save the game. Please try again.")
128
+ except Exception as e:
129
+ st.error(f"Error: {str(e)}")
130
+
131
+ # Show Recent Submissions
132
+ st.markdown("---")
133
+ st.subheader("πŸ“Œ Recent Submissions")
134
+
135
+ from database import get_all_submissions
136
+ all_submissions = get_all_submissions()
137
+ # Filter submissions for this category
138
+ submissions = [s for s in all_submissions if s['category'] == category]
139
+
140
+ for submission in submissions:
141
+ title = submission['title']
142
+ name = submission['name']
143
+ description = submission['description']
144
+ timestamp = submission['timestamp']
145
+ audio = submission['audio_url']
146
+ image = submission['image_url']
147
+ video = submission['video_url']
148
+
149
+ with st.expander(f"πŸ”Ή {title} by {name} ({timestamp[:19]})"):
150
+ st.write(description)
151
+ if image and os.path.exists(image):
152
+ st.image(image, caption="πŸ“Έ Image")
153
+ if audio and os.path.exists(audio):
154
+ st.audio(audio)
155
+ if video and os.path.exists(video):
156
+ st.video(video)
src/pages/4_Martial_Arts.py ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datetime import datetime
2
+ import os
3
+ import tempfile
4
+ import requests
5
+ from database import save_submission
6
+ import streamlit as st
7
+
8
+ st.set_page_config(page_title="Martial Arts Game Submission", layout="wide")
9
+
10
+ if "authenticated" not in st.session_state or not st.session_state.authenticated:
11
+ st.error("πŸ” Please log in to access this page.")
12
+ st.stop()
13
+
14
+ # Change these for each file:
15
+ st.title("πŸ₯‹ Contribute a Martial Art")
16
+ category = "Martial Arts"
17
+
18
+ # Use a shared uploads folder in a safe temp directory
19
+ upload_dir = os.path.join(tempfile.gettempdir(), "uploads")
20
+
21
+ # Ensure uploads folder exists
22
+ os.makedirs(upload_dir, exist_ok=True)
23
+
24
+ # Location Detection
25
+ def get_ip_location():
26
+ try:
27
+ import urllib3
28
+ urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
29
+ response = requests.get("https://ipinfo.io/json", verify=False)
30
+ data = response.json()
31
+ loc = data.get("loc")
32
+ if loc:
33
+ lat_str, lon_str = loc.split(",")
34
+ return float(lat_str), float(lon_str)
35
+ except:
36
+ pass
37
+ return None, None
38
+
39
+ # Get or set lat/lon
40
+ if "user_lat" not in st.session_state or "user_lon" not in st.session_state:
41
+ st.session_state["user_lat"], st.session_state["user_lon"] = get_ip_location()
42
+
43
+ lat = st.session_state.get("user_lat")
44
+ lon = st.session_state.get("user_lon")
45
+
46
+ # Show location info
47
+ st.subheader("πŸ“ Location Info")
48
+ if lat and lon:
49
+ st.success(f"πŸ“ Location detected: Latitude {lat:.4f}, Longitude {lon:.4f}")
50
+ else:
51
+ st.warning("⚠️ Location could not be detected.")
52
+
53
+ with st.form("martial_arts_form"):
54
+ st.subheader("πŸ‘€ Game Details")
55
+ title = st.text_input("Game Title*", help="Enter the name of the game")
56
+ description = st.text_area("Game Description*", help="Explain how to play the game")
57
+ player_count = st.text_input("Number of Players", help="How many players are needed?")
58
+ age_group = st.selectbox("Age Group", ["All Ages", "Children", "Teenagers", "Adults"])
59
+ equipment = st.text_input("Required Equipment", help="List any equipment needed to play")
60
+
61
+ st.subheader("🧹 Select Input Type")
62
+ input_type = st.radio(
63
+ "Choose how you'd like to submit your contribution:",
64
+ ["πŸ“ Text", "🎹 Audio", "πŸ“Έ Photo", "🎩 Video"],
65
+ horizontal=True
66
+ )
67
+
68
+ # Submit button at the end of the form
69
+ submit_button = st.form_submit_button("πŸ“€ Submit Game")
70
+
71
+ audio_file = image_file = video_file = None
72
+ audio_path = image_path = video_path = None
73
+
74
+ # Input handling
75
+ if input_type == "🎹 Audio":
76
+ audio_file = st.file_uploader("Upload Audio", type=["mp3", "wav"])
77
+ elif input_type == "πŸ“Έ Photo":
78
+ image_file = st.file_uploader("Upload Image", type=["jpg", "jpeg", "png"])
79
+ elif input_type == "🎩 Video":
80
+ video_file = st.file_uploader("Upload Video", type=["mp4", "mov"])
81
+
82
+ # Handle form submission
83
+ if submit_button:
84
+ if not title or not description:
85
+ st.error("⚠️ Please fill in all required fields!")
86
+ else:
87
+ try:
88
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
89
+
90
+ # Handle file uploads
91
+ if audio_file:
92
+ audio_path = os.path.join(upload_dir, f"{timestamp}_{audio_file.name}")
93
+ with open(audio_path, "wb") as f:
94
+ f.write(audio_file.getbuffer())
95
+ if image_file:
96
+ image_path = os.path.join(upload_dir, f"{timestamp}_{image_file.name}")
97
+ with open(image_path, "wb") as f:
98
+ f.write(image_file.getbuffer())
99
+ if video_file:
100
+ video_path = os.path.join(upload_dir, f"{timestamp}_{video_file.name}")
101
+ with open(video_path, "wb") as f:
102
+ f.write(video_file.getbuffer())
103
+
104
+ # Prepare submission data
105
+ submission_data = {
106
+ 'name': st.session_state.username, # Use logged-in username
107
+ 'title': title,
108
+ 'description': description,
109
+ 'category': category,
110
+ 'player_count': player_count,
111
+ 'age_group': age_group,
112
+ 'equipment_needed': equipment,
113
+ 'input_type': input_type,
114
+ 'audio_url': audio_path if audio_file else None,
115
+ 'image_url': image_path if image_file else None,
116
+ 'video_url': video_path if video_file else None,
117
+ 'lat': 0.0,
118
+ 'lon': 0.0
119
+ }
120
+
121
+ # Save to database
122
+ if save_submission(submission_data):
123
+ st.success("πŸŽ‰ Game submitted successfully!")
124
+ # Reset form by clearing the state
125
+ for key in st.session_state.keys():
126
+ if key not in ['authenticated', 'username']:
127
+ del st.session_state[key]
128
+ else:
129
+ st.error("Failed to save the game. Please try again.")
130
+ except Exception as e:
131
+ st.error(f"Error: {str(e)}")
src/pages/5_Upload_history.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ from datetime import datetime
3
+ from utils.database import get_user_submissions
4
+
5
+ st.set_page_config(page_title="Upload History", layout="wide")
6
+
7
+ if "authenticated" not in st.session_state or not st.session_state.authenticated:
8
+ st.error("πŸ” Please log in to access this page.")
9
+ st.stop()
10
+
11
+ st.title("πŸ•‘ Recent Game Uploads")
12
+
13
+ # Get the user's username from session state
14
+ username = st.session_state.get("username")
15
+
16
+ if username:
17
+ # Get user's submissions
18
+ submissions = get_user_submissions(username)
19
+
20
+ # Debug information
21
+ st.write("Debug Info:")
22
+ st.write(f"Looking for submissions for user: {username}")
23
+ st.write(f"Number of submissions found: {len(submissions) if submissions else 0}")
24
+
25
+ # Display submissions
26
+ if submissions and len(submissions) > 0:
27
+ for submission in submissions:
28
+ try:
29
+ title = submission.get('title', 'Untitled')
30
+ description = submission.get('description', 'No description')
31
+ category = submission.get('category', 'Unknown')
32
+ timestamp = submission.get('timestamp', '')
33
+ player_count = submission.get('player_count', 'Unknown')
34
+ age_group = submission.get('age_group', 'Unknown')
35
+ equipment = submission.get('equipment_needed', '')
36
+
37
+ # Format timestamp
38
+ try:
39
+ dt = datetime.strptime(timestamp, '%Y-%m-%d %H:%M:%S')
40
+ display_time = dt.strftime('%Y-%m-%d %H:%M')
41
+ except:
42
+ display_time = timestamp
43
+
44
+ with st.expander(f"🎯 {title} β€’ {display_time} β€’ [{category}]"):
45
+ st.write(f"**Players:** {player_count}")
46
+ st.write(f"**Age Group:** {age_group}")
47
+ st.write(f"**Category:** {category}")
48
+ if equipment:
49
+ st.write(f"**Equipment:** {equipment}")
50
+ st.write("**Description:**")
51
+ st.write(description)
52
+ except Exception as e:
53
+ st.error(f"Error displaying submission: {e}")
54
+ else:
55
+ st.info("You have not uploaded any games yet.")
56
+ else:
57
+ st.warning("User not found in session. Please log in again.")
src/pages/AI_Sport_Analyser.py ADDED
@@ -0,0 +1,217 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import requests
3
+ import base64
4
+ from PIL import Image
5
+ import io
6
+
7
+ # πŸ” Hardcoded API Key
8
+ API_KEY = "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" # ← Replace this with your actual OpenRouter API key
9
+
10
+ # Configure Streamlit page
11
+ st.set_page_config(
12
+ page_title="Sports Analysis AI Assistant", page_icon="⚽", layout="wide"
13
+ )
14
+ # Title and description
15
+ st.title("πŸ† Sports Analysis AI Assistant")
16
+ st.markdown(
17
+ "Upload an image of a sport and get detailed information about the game, rules, equipment, and history!"
18
+ )
19
+
20
+ st.sidebar.markdown("### About")
21
+ st.sidebar.markdown(
22
+ "This app uses OpenRouter API with open-source vision models to analyze sports images."
23
+ )
24
+ st.sidebar.markdown(
25
+ "**Model**: meta-llama/llama-3.2-11b-vision-instruct:free (Open Source)"
26
+ )
27
+
28
+
29
+ # Function to encode image to base64
30
+ def encode_image(image):
31
+ if image.mode in ("RGBA", "P"):
32
+ image = image.convert("RGB")
33
+ buffered = io.BytesIO()
34
+ image.save(buffered, format="JPEG", quality=85)
35
+ return base64.b64encode(buffered.getvalue()).decode()
36
+
37
+
38
+ # Function to analyze image using OpenRouter API
39
+ def analyze_sport_image(image):
40
+ base64_image = encode_image(image)
41
+
42
+ url = "https://openrouter.ai/api/v1/chat/completions"
43
+ headers = {"Authorization": f"Bearer {API_KEY}", "Content-Type": "application/json"}
44
+
45
+ prompt = """
46
+ Analyze this image and provide detailed information about the sport being played. Please structure your response as follows:
47
+ **SPORT IDENTIFIED:** [Name of the sport]
48
+ **RULES:**
49
+ - Provide 5-7 key rules of this sport
50
+ - Include scoring system
51
+ - Mention any important regulations
52
+ **EQUIPMENT:**
53
+ - List all essential equipment needed
54
+ - Mention optional equipment
55
+ - Include field/court specifications if relevant
56
+ **HISTORY:**
57
+ - Origin and development of the sport
58
+ - Key historical milestones
59
+ - How it evolved to modern form
60
+ - Notable facts about its global spread
61
+ **ADDITIONAL INFO:**
62
+ - Popular variations or formats
63
+ - Major tournaments or competitions
64
+ - Interesting facts about the sport
65
+ """
66
+
67
+ payload = {
68
+ "model": "meta-llama/llama-3.2-11b-vision-instruct:free",
69
+ "messages": [
70
+ {
71
+ "role": "user",
72
+ "content": [
73
+ {"type": "text", "text": prompt},
74
+ {
75
+ "type": "image_url",
76
+ "image_url": {"url": f"data:image/jpeg;base64,{base64_image}"},
77
+ },
78
+ ],
79
+ }
80
+ ],
81
+ "max_tokens": 1500,
82
+ "temperature": 0.7,
83
+ }
84
+
85
+ try:
86
+ response = requests.post(url, headers=headers, json=payload)
87
+ response.raise_for_status()
88
+ result = response.json()
89
+ return result["choices"][0]["message"]["content"]
90
+ except Exception as e:
91
+ st.error(f"❌ Error: {str(e)}")
92
+ return None
93
+
94
+
95
+ # Main app logic
96
+ uploaded_file = st.file_uploader(
97
+ "Choose an image of a sport",
98
+ type=["png", "jpg", "jpeg"],
99
+ help="Upload an image showing people playing a sport",
100
+ )
101
+
102
+ if uploaded_file is not None:
103
+ if (
104
+ "current_image" not in st.session_state
105
+ or st.session_state.current_image != uploaded_file.name
106
+ ):
107
+ st.session_state.current_image = uploaded_file.name
108
+ if "analysis_result" in st.session_state:
109
+ del st.session_state.analysis_result
110
+
111
+ col1, col2 = st.columns([1, 2])
112
+
113
+ with col1:
114
+ try:
115
+ image = Image.open(uploaded_file)
116
+ max_size = 2048
117
+ if image.width > max_size or image.height > max_size:
118
+ image.thumbnail((max_size, max_size), Image.Resampling.LANCZOS)
119
+ st.info(f"Image resized to {image.width}x{image.height} for processing")
120
+ st.image(image, caption="Uploaded Image", use_container_width=True)
121
+ st.caption(f"Image size: {image.width}x{image.height} pixels")
122
+
123
+ if st.button("πŸ” Analyze Sport", type="primary"):
124
+ with st.spinner("Analyzing image..."):
125
+ result = analyze_sport_image(image)
126
+ if result:
127
+ st.session_state.analysis_result = result
128
+ st.success("βœ… Analysis completed!")
129
+ else:
130
+ st.error("❌ Failed to analyze the image. Try another image.")
131
+
132
+ except Exception as e:
133
+ st.error(f"Error loading image: {str(e)}")
134
+ st.info("Please try uploading a different image file.")
135
+
136
+ with col2:
137
+ if "analysis_result" in st.session_state:
138
+ st.markdown("### πŸ“Š Analysis Results")
139
+ st.markdown(st.session_state.analysis_result)
140
+ else:
141
+ st.info("πŸ‘ˆ Upload an image and click 'Analyze Sport' to get started!")
142
+
143
+ # Footer tips
144
+ st.markdown("---")
145
+ st.markdown("### πŸ’‘ Tips for best results:")
146
+ st.markdown("- Use clear, well-lit images")
147
+ st.markdown("- Ensure the sport activity is clearly visible")
148
+ st.markdown("- Images with players in action work best")
149
+ st.markdown("- Avoid blurry or distant shots")
150
+
151
+ # Supported sports
152
+ st.markdown("### πŸƒβ€β™‚οΈ Sports this AI can analyze:")
153
+ sports_grid = st.columns(4)
154
+
155
+ with sports_grid[0]:
156
+ st.markdown("**Ball Sports**")
157
+ st.markdown("β€’ Football/Soccer")
158
+ st.markdown("β€’ Basketball")
159
+ st.markdown("β€’ Tennis")
160
+ st.markdown("β€’ Volleyball")
161
+
162
+ with sports_grid[1]:
163
+ st.markdown("**Racquet Sports**")
164
+ st.markdown("β€’ Badminton")
165
+ st.markdown("β€’ Table Tennis")
166
+ st.markdown("β€’ Squash")
167
+ st.markdown("β€’ Tennis")
168
+
169
+ with sports_grid[2]:
170
+ st.markdown("**Field Sports**")
171
+ st.markdown("β€’ Cricket")
172
+ st.markdown("β€’ Baseball")
173
+ st.markdown("β€’ Rugby")
174
+ st.markdown("β€’ Hockey")
175
+
176
+ with sports_grid[3]:
177
+ st.markdown("**Others**")
178
+ st.markdown("β€’ Swimming")
179
+ st.markdown("β€’ Athletics")
180
+ st.markdown("β€’ Gymnastics")
181
+ st.markdown("β€’ Boxing")
182
+
183
+ # Footer
184
+ st.markdown("---")
185
+ st.markdown("### πŸ”§ Technical Details")
186
+ st.markdown("- **API**: OpenRouter")
187
+ st.markdown("- **Model**: Meta LLaMA 3.2 11B Vision (Free)")
188
+ st.markdown("- **Framework**: Streamlit")
189
+ st.markdown("- **Open Source**: Yes, completely free to use!")
190
+
191
+ # Styling
192
+ st.markdown(
193
+ """
194
+ <style>
195
+ .stApp {
196
+ max-width: 1200px;
197
+ margin: 0 auto;
198
+ }
199
+ .stButton > button {
200
+ width: 100%;
201
+ background-color: #FF4B4B;
202
+ color: white;
203
+ border: none;
204
+ padding: 0.5rem;
205
+ border-radius: 0.5rem;
206
+ font-weight: bold;
207
+ }
208
+ .stButton > button:hover {
209
+ background-color: #FF6B6B;
210
+ }
211
+ .stFileUploader > div > div {
212
+ text-align: center;
213
+ }
214
+ </style>
215
+ """,
216
+ unsafe_allow_html=True,
217
+ )