Spaces:
Running
Running
Update app.py (#2)
Browse files- Update app.py (3995452dcc15752e5db60a44565cba322210868b)
app.py
CHANGED
|
@@ -1,170 +1,170 @@
|
|
| 1 |
-
import os
|
| 2 |
-
import pandas as pd
|
| 3 |
-
import streamlit as st
|
| 4 |
-
import random
|
| 5 |
-
import requests
|
| 6 |
-
import plotly.express as px
|
| 7 |
-
from transformers import pipeline # Hugging Face Transformers for AI models
|
| 8 |
-
|
| 9 |
-
# Groq API Endpoint and Key (Replace with your actual endpoint and API Key)
|
| 10 |
-
GROQ_API_KEY = "sk_9VSobViSwaWOpFGSWP5lWGdyb3FYIneUIyae233sZflxIOo1TW7m"
|
| 11 |
-
GROQ_API_URL = "https://api.groq.com/v1/query" # Example URL (you'll need to update based on the API documentation)
|
| 12 |
-
|
| 13 |
-
# File to store leaderboard data
|
| 14 |
-
LEADERBOARD_FILE = "leaderboard
|
| 15 |
-
|
| 16 |
-
# Define questions for multiple topics
|
| 17 |
-
questions_db = {
|
| 18 |
-
"Geography": [
|
| 19 |
-
("What is the capital of France?", "Paris"),
|
| 20 |
-
("What is the capital of Japan?", "Tokyo"),
|
| 21 |
-
("What is the largest country in the world by land area?", "Russia"),
|
| 22 |
-
("What is the capital of Australia?", "Canberra"),
|
| 23 |
-
("Which continent is the Sahara Desert located in?", "Africa")
|
| 24 |
-
],
|
| 25 |
-
"Science": [
|
| 26 |
-
("What is the chemical symbol for water?", "H2O"),
|
| 27 |
-
("What planet is known as the Red Planet?", "Mars"),
|
| 28 |
-
("Who developed the theory of relativity?", "Albert Einstein"),
|
| 29 |
-
("What is the speed of light?", "299792458 m/s"),
|
| 30 |
-
("What is the powerhouse of the cell?", "Mitochondria")
|
| 31 |
-
],
|
| 32 |
-
"Math": [
|
| 33 |
-
("What is the square root of 64?", "8"),
|
| 34 |
-
("What is 5 * 12?", "60"),
|
| 35 |
-
("What is 100 / 4?", "25"),
|
| 36 |
-
("What is the value of pi to two decimal places?", "3.14"),
|
| 37 |
-
("What is 15 + 7?", "22")
|
| 38 |
-
],
|
| 39 |
-
"IPL": [ # IPL questions added
|
| 40 |
-
("Which IPL team won the 2020 IPL season?", "Mumbai Indians"),
|
| 41 |
-
("Who is the all-time highest run-scorer in IPL history?", "Virat Kohli"),
|
| 42 |
-
("Who won the IPL 2023 season?", "Gujarat Titans"),
|
| 43 |
-
("Which IPL player has the most wickets?", "Dwayne Bravo"),
|
| 44 |
-
("Which team has won the maximum number of IPL titles?", "Mumbai Indians"),
|
| 45 |
-
("Who is known as the 'Captain Cool' in IPL?", "MS Dhoni"),
|
| 46 |
-
("Which IPL franchise has the lowest win percentage?", "Royal Challengers Bangalore"),
|
| 47 |
-
("Who hit the most sixes in IPL 2021?", "Chris Gayle"),
|
| 48 |
-
("Which bowler has the most hat-tricks in IPL history?", "Shane Warne"),
|
| 49 |
-
("Which team is known for its yellow jersey?", "Chennai Super Kings")
|
| 50 |
-
]
|
| 51 |
-
}
|
| 52 |
-
|
| 53 |
-
# Function to load the leaderboard from the CSV file
|
| 54 |
-
def load_leaderboard():
|
| 55 |
-
if os.path.exists(LEADERBOARD_FILE):
|
| 56 |
-
try:
|
| 57 |
-
leaderboard_df = pd.read_csv(LEADERBOARD_FILE, names=['name', 'score', 'question', 'answer', 'correct', 'topic'], header=0)
|
| 58 |
-
return leaderboard_df
|
| 59 |
-
except pd.errors.ParserError:
|
| 60 |
-
st.error("Error reading the leaderboard CSV. Please check the file for formatting issues.")
|
| 61 |
-
return pd.DataFrame(columns=['name', 'score', 'question', 'answer', 'correct', 'topic'])
|
| 62 |
-
else:
|
| 63 |
-
return pd.DataFrame(columns=['name', 'score', 'question', 'answer', 'correct', 'topic'])
|
| 64 |
-
|
| 65 |
-
# Function to save the leaderboard to the CSV file
|
| 66 |
-
def save_leaderboard(leaderboard_df):
|
| 67 |
-
leaderboard_df.to_csv(LEADERBOARD_FILE, index=False)
|
| 68 |
-
|
| 69 |
-
# Function to display detailed winner charts
|
| 70 |
-
def display_winner_charts(leaderboard_df):
|
| 71 |
-
if not leaderboard_df.empty:
|
| 72 |
-
# Top Winners (By Score)
|
| 73 |
-
top_winners = leaderboard_df.sort_values(by='score', ascending=False).head(10)
|
| 74 |
-
st.subheader("Top 10 Winners")
|
| 75 |
-
fig_top_winners = px.bar(top_winners, x='name', y='score', title="Top 10 Winners", color='score', color_continuous_scale='Viridis')
|
| 76 |
-
st.plotly_chart(fig_top_winners)
|
| 77 |
-
|
| 78 |
-
# Topic-wise Winners (Average Score Per Topic)
|
| 79 |
-
topic_performance = leaderboard_df.groupby('topic')['score'].mean().reset_index()
|
| 80 |
-
st.subheader("Average Score Per Topic")
|
| 81 |
-
fig_topic_performance = px.bar(topic_performance, x='topic', y='score', title="Average Score Per Topic", color='score', color_continuous_scale='Blues')
|
| 82 |
-
st.plotly_chart(fig_topic_performance)
|
| 83 |
-
|
| 84 |
-
# Correct Answers Breakdown
|
| 85 |
-
correct_counts = leaderboard_df['correct'].value_counts()
|
| 86 |
-
st.subheader("Correct vs Incorrect Answers Breakdown")
|
| 87 |
-
fig_correctness = px.pie(names=correct_counts.index, values=correct_counts.values, title="Correctness Breakdown")
|
| 88 |
-
st.plotly_chart(fig_correctness)
|
| 89 |
-
|
| 90 |
-
# Score Distribution Over Time (Assumes each game play is a new row in leaderboard)
|
| 91 |
-
leaderboard_df['date'] = pd.to_datetime(leaderboard_df['score']) # Assuming the leaderboard stores the date or round of the game
|
| 92 |
-
st.subheader("Score Distribution Over Time")
|
| 93 |
-
fig_score_trend = px.line(leaderboard_df, x='date', y='score', title="Score Trend Over Time", line_group='name')
|
| 94 |
-
st.plotly_chart(fig_score_trend)
|
| 95 |
-
else:
|
| 96 |
-
st.write("No data available to generate charts.")
|
| 97 |
-
|
| 98 |
-
# Function to handle the game logic (dynamic number of questions based on user choice)
|
| 99 |
-
def start_game():
|
| 100 |
-
# Get selected topic
|
| 101 |
-
topic = st.selectbox("Choose a Topic", list(questions_db.keys()))
|
| 102 |
-
num_questions = st.selectbox("Select the number of questions", [5, 10, 15, 20])
|
| 103 |
-
|
| 104 |
-
if 'questions' not in st.session_state or st.session_state['topic'] != topic or len(st.session_state['questions']) != num_questions:
|
| 105 |
-
# Store selected questions in session state for consistency during game
|
| 106 |
-
st.session_state['topic'] = topic
|
| 107 |
-
st.session_state['questions'] = random.sample(questions_db[topic], num_questions)
|
| 108 |
-
|
| 109 |
-
# Show questions
|
| 110 |
-
questions = st.session_state['questions']
|
| 111 |
-
st.subheader(f"Playing Quiz on: {topic}")
|
| 112 |
-
|
| 113 |
-
# Get player's name
|
| 114 |
-
username = st.text_input("Enter your name:")
|
| 115 |
-
|
| 116 |
-
if username:
|
| 117 |
-
# Store answers in session state
|
| 118 |
-
if 'answers' not in st.session_state:
|
| 119 |
-
st.session_state['answers'] = [""] * len(questions) # Initialize answers list
|
| 120 |
-
|
| 121 |
-
score = 0
|
| 122 |
-
# Show text inputs for each question
|
| 123 |
-
for i, (question, correct_answer) in enumerate(questions):
|
| 124 |
-
st.session_state['answers'][i] = st.text_input(f"Question {i+1}: {question}", value=st.session_state['answers'][i], key=f"q{i}")
|
| 125 |
-
|
| 126 |
-
# Submit button after all answers are entered
|
| 127 |
-
submit_button = st.button("Submit Answers")
|
| 128 |
-
|
| 129 |
-
if submit_button:
|
| 130 |
-
answers = st.session_state['answers']
|
| 131 |
-
# Check answers and calculate score
|
| 132 |
-
for i, (question, correct_answer) in enumerate(questions):
|
| 133 |
-
user_answer = answers[i].strip().lower()
|
| 134 |
-
correct_answer_normalized = correct_answer.strip().lower()
|
| 135 |
-
if user_answer == correct_answer_normalized:
|
| 136 |
-
score += 10
|
| 137 |
-
|
| 138 |
-
st.success(f"Game Over! Your final score is {score}")
|
| 139 |
-
|
| 140 |
-
# Save the result to leaderboard
|
| 141 |
-
leaderboard_df = load_leaderboard()
|
| 142 |
-
new_row = pd.DataFrame({
|
| 143 |
-
'name': [username],
|
| 144 |
-
'score': [score],
|
| 145 |
-
'question': [', '.join([q[0] for q in questions])],
|
| 146 |
-
'answer': [', '.join(answers)],
|
| 147 |
-
'correct': [', '.join(['Yes' if answers[i].strip().lower() == questions[i][1].lower() else 'No' for i in range(len(answers))])],
|
| 148 |
-
'topic': [topic]
|
| 149 |
-
})
|
| 150 |
-
|
| 151 |
-
leaderboard_df = pd.concat([leaderboard_df, new_row], ignore_index=True)
|
| 152 |
-
leaderboard_df = leaderboard_df.sort_values(by='score', ascending=False).reset_index(drop=True)
|
| 153 |
-
save_leaderboard(leaderboard_df)
|
| 154 |
-
|
| 155 |
-
# Main function to handle Streamlit app
|
| 156 |
-
def main():
|
| 157 |
-
st.title('Kahoot-like Game')
|
| 158 |
-
|
| 159 |
-
mode = st.sidebar.selectbox("Select Mode", ["Game", "Dashboard"])
|
| 160 |
-
|
| 161 |
-
if mode == "Game":
|
| 162 |
-
start_game()
|
| 163 |
-
|
| 164 |
-
elif mode == "Dashboard":
|
| 165 |
-
leaderboard_df = load_leaderboard()
|
| 166 |
-
display_winner_charts(leaderboard_df)
|
| 167 |
-
|
| 168 |
-
# Ensure the main function is called when running the app
|
| 169 |
-
if __name__ == "__main__":
|
| 170 |
-
main()
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import pandas as pd
|
| 3 |
+
import streamlit as st
|
| 4 |
+
import random
|
| 5 |
+
import requests
|
| 6 |
+
import plotly.express as px
|
| 7 |
+
from transformers import pipeline # Hugging Face Transformers for AI models
|
| 8 |
+
|
| 9 |
+
# Groq API Endpoint and Key (Replace with your actual endpoint and API Key)
|
| 10 |
+
GROQ_API_KEY = "sk_9VSobViSwaWOpFGSWP5lWGdyb3FYIneUIyae233sZflxIOo1TW7m"
|
| 11 |
+
GROQ_API_URL = "https://api.groq.com/v1/query" # Example URL (you'll need to update based on the API documentation)
|
| 12 |
+
|
| 13 |
+
# File to store leaderboard data
|
| 14 |
+
LEADERBOARD_FILE = "leaderboard"
|
| 15 |
+
|
| 16 |
+
# Define questions for multiple topics
|
| 17 |
+
questions_db = {
|
| 18 |
+
"Geography": [
|
| 19 |
+
("What is the capital of France?", "Paris"),
|
| 20 |
+
("What is the capital of Japan?", "Tokyo"),
|
| 21 |
+
("What is the largest country in the world by land area?", "Russia"),
|
| 22 |
+
("What is the capital of Australia?", "Canberra"),
|
| 23 |
+
("Which continent is the Sahara Desert located in?", "Africa")
|
| 24 |
+
],
|
| 25 |
+
"Science": [
|
| 26 |
+
("What is the chemical symbol for water?", "H2O"),
|
| 27 |
+
("What planet is known as the Red Planet?", "Mars"),
|
| 28 |
+
("Who developed the theory of relativity?", "Albert Einstein"),
|
| 29 |
+
("What is the speed of light?", "299792458 m/s"),
|
| 30 |
+
("What is the powerhouse of the cell?", "Mitochondria")
|
| 31 |
+
],
|
| 32 |
+
"Math": [
|
| 33 |
+
("What is the square root of 64?", "8"),
|
| 34 |
+
("What is 5 * 12?", "60"),
|
| 35 |
+
("What is 100 / 4?", "25"),
|
| 36 |
+
("What is the value of pi to two decimal places?", "3.14"),
|
| 37 |
+
("What is 15 + 7?", "22")
|
| 38 |
+
],
|
| 39 |
+
"IPL": [ # IPL questions added
|
| 40 |
+
("Which IPL team won the 2020 IPL season?", "Mumbai Indians"),
|
| 41 |
+
("Who is the all-time highest run-scorer in IPL history?", "Virat Kohli"),
|
| 42 |
+
("Who won the IPL 2023 season?", "Gujarat Titans"),
|
| 43 |
+
("Which IPL player has the most wickets?", "Dwayne Bravo"),
|
| 44 |
+
("Which team has won the maximum number of IPL titles?", "Mumbai Indians"),
|
| 45 |
+
("Who is known as the 'Captain Cool' in IPL?", "MS Dhoni"),
|
| 46 |
+
("Which IPL franchise has the lowest win percentage?", "Royal Challengers Bangalore"),
|
| 47 |
+
("Who hit the most sixes in IPL 2021?", "Chris Gayle"),
|
| 48 |
+
("Which bowler has the most hat-tricks in IPL history?", "Shane Warne"),
|
| 49 |
+
("Which team is known for its yellow jersey?", "Chennai Super Kings")
|
| 50 |
+
]
|
| 51 |
+
}
|
| 52 |
+
|
| 53 |
+
# Function to load the leaderboard from the CSV file
|
| 54 |
+
def load_leaderboard():
|
| 55 |
+
if os.path.exists(LEADERBOARD_FILE):
|
| 56 |
+
try:
|
| 57 |
+
leaderboard_df = pd.read_csv(LEADERBOARD_FILE, names=['name', 'score', 'question', 'answer', 'correct', 'topic'], header=0)
|
| 58 |
+
return leaderboard_df
|
| 59 |
+
except pd.errors.ParserError:
|
| 60 |
+
st.error("Error reading the leaderboard CSV. Please check the file for formatting issues.")
|
| 61 |
+
return pd.DataFrame(columns=['name', 'score', 'question', 'answer', 'correct', 'topic'])
|
| 62 |
+
else:
|
| 63 |
+
return pd.DataFrame(columns=['name', 'score', 'question', 'answer', 'correct', 'topic'])
|
| 64 |
+
|
| 65 |
+
# Function to save the leaderboard to the CSV file
|
| 66 |
+
def save_leaderboard(leaderboard_df):
|
| 67 |
+
leaderboard_df.to_csv(LEADERBOARD_FILE, index=False)
|
| 68 |
+
|
| 69 |
+
# Function to display detailed winner charts
|
| 70 |
+
def display_winner_charts(leaderboard_df):
|
| 71 |
+
if not leaderboard_df.empty:
|
| 72 |
+
# Top Winners (By Score)
|
| 73 |
+
top_winners = leaderboard_df.sort_values(by='score', ascending=False).head(10)
|
| 74 |
+
st.subheader("Top 10 Winners")
|
| 75 |
+
fig_top_winners = px.bar(top_winners, x='name', y='score', title="Top 10 Winners", color='score', color_continuous_scale='Viridis')
|
| 76 |
+
st.plotly_chart(fig_top_winners)
|
| 77 |
+
|
| 78 |
+
# Topic-wise Winners (Average Score Per Topic)
|
| 79 |
+
topic_performance = leaderboard_df.groupby('topic')['score'].mean().reset_index()
|
| 80 |
+
st.subheader("Average Score Per Topic")
|
| 81 |
+
fig_topic_performance = px.bar(topic_performance, x='topic', y='score', title="Average Score Per Topic", color='score', color_continuous_scale='Blues')
|
| 82 |
+
st.plotly_chart(fig_topic_performance)
|
| 83 |
+
|
| 84 |
+
# Correct Answers Breakdown
|
| 85 |
+
correct_counts = leaderboard_df['correct'].value_counts()
|
| 86 |
+
st.subheader("Correct vs Incorrect Answers Breakdown")
|
| 87 |
+
fig_correctness = px.pie(names=correct_counts.index, values=correct_counts.values, title="Correctness Breakdown")
|
| 88 |
+
st.plotly_chart(fig_correctness)
|
| 89 |
+
|
| 90 |
+
# Score Distribution Over Time (Assumes each game play is a new row in leaderboard)
|
| 91 |
+
leaderboard_df['date'] = pd.to_datetime(leaderboard_df['score']) # Assuming the leaderboard stores the date or round of the game
|
| 92 |
+
st.subheader("Score Distribution Over Time")
|
| 93 |
+
fig_score_trend = px.line(leaderboard_df, x='date', y='score', title="Score Trend Over Time", line_group='name')
|
| 94 |
+
st.plotly_chart(fig_score_trend)
|
| 95 |
+
else:
|
| 96 |
+
st.write("No data available to generate charts.")
|
| 97 |
+
|
| 98 |
+
# Function to handle the game logic (dynamic number of questions based on user choice)
|
| 99 |
+
def start_game():
|
| 100 |
+
# Get selected topic
|
| 101 |
+
topic = st.selectbox("Choose a Topic", list(questions_db.keys()))
|
| 102 |
+
num_questions = st.selectbox("Select the number of questions", [5, 10, 15, 20])
|
| 103 |
+
|
| 104 |
+
if 'questions' not in st.session_state or st.session_state['topic'] != topic or len(st.session_state['questions']) != num_questions:
|
| 105 |
+
# Store selected questions in session state for consistency during game
|
| 106 |
+
st.session_state['topic'] = topic
|
| 107 |
+
st.session_state['questions'] = random.sample(questions_db[topic], num_questions)
|
| 108 |
+
|
| 109 |
+
# Show questions
|
| 110 |
+
questions = st.session_state['questions']
|
| 111 |
+
st.subheader(f"Playing Quiz on: {topic}")
|
| 112 |
+
|
| 113 |
+
# Get player's name
|
| 114 |
+
username = st.text_input("Enter your name:")
|
| 115 |
+
|
| 116 |
+
if username:
|
| 117 |
+
# Store answers in session state
|
| 118 |
+
if 'answers' not in st.session_state:
|
| 119 |
+
st.session_state['answers'] = [""] * len(questions) # Initialize answers list
|
| 120 |
+
|
| 121 |
+
score = 0
|
| 122 |
+
# Show text inputs for each question
|
| 123 |
+
for i, (question, correct_answer) in enumerate(questions):
|
| 124 |
+
st.session_state['answers'][i] = st.text_input(f"Question {i+1}: {question}", value=st.session_state['answers'][i], key=f"q{i}")
|
| 125 |
+
|
| 126 |
+
# Submit button after all answers are entered
|
| 127 |
+
submit_button = st.button("Submit Answers")
|
| 128 |
+
|
| 129 |
+
if submit_button:
|
| 130 |
+
answers = st.session_state['answers']
|
| 131 |
+
# Check answers and calculate score
|
| 132 |
+
for i, (question, correct_answer) in enumerate(questions):
|
| 133 |
+
user_answer = answers[i].strip().lower()
|
| 134 |
+
correct_answer_normalized = correct_answer.strip().lower()
|
| 135 |
+
if user_answer == correct_answer_normalized:
|
| 136 |
+
score += 10
|
| 137 |
+
|
| 138 |
+
st.success(f"Game Over! Your final score is {score}")
|
| 139 |
+
|
| 140 |
+
# Save the result to leaderboard
|
| 141 |
+
leaderboard_df = load_leaderboard()
|
| 142 |
+
new_row = pd.DataFrame({
|
| 143 |
+
'name': [username],
|
| 144 |
+
'score': [score],
|
| 145 |
+
'question': [', '.join([q[0] for q in questions])],
|
| 146 |
+
'answer': [', '.join(answers)],
|
| 147 |
+
'correct': [', '.join(['Yes' if answers[i].strip().lower() == questions[i][1].lower() else 'No' for i in range(len(answers))])],
|
| 148 |
+
'topic': [topic]
|
| 149 |
+
})
|
| 150 |
+
|
| 151 |
+
leaderboard_df = pd.concat([leaderboard_df, new_row], ignore_index=True)
|
| 152 |
+
leaderboard_df = leaderboard_df.sort_values(by='score', ascending=False).reset_index(drop=True)
|
| 153 |
+
save_leaderboard(leaderboard_df)
|
| 154 |
+
|
| 155 |
+
# Main function to handle Streamlit app
|
| 156 |
+
def main():
|
| 157 |
+
st.title('Kahoot-like Game')
|
| 158 |
+
|
| 159 |
+
mode = st.sidebar.selectbox("Select Mode", ["Game", "Dashboard"])
|
| 160 |
+
|
| 161 |
+
if mode == "Game":
|
| 162 |
+
start_game()
|
| 163 |
+
|
| 164 |
+
elif mode == "Dashboard":
|
| 165 |
+
leaderboard_df = load_leaderboard()
|
| 166 |
+
display_winner_charts(leaderboard_df)
|
| 167 |
+
|
| 168 |
+
# Ensure the main function is called when running the app
|
| 169 |
+
if __name__ == "__main__":
|
| 170 |
+
main()
|