Spaces:
Sleeping
Sleeping
| import streamlit as st | |
| from openai import OpenAI | |
| import time | |
| # Replace with your Grok API key, considering Hugging Face's secrets management | |
| grok_api_key = st.secrets["GROK_API_KEY"] | |
| client = OpenAI( | |
| api_key=grok_api_key, | |
| base_url="https://api.x.ai/v1", | |
| ) | |
| def generate_question(topic): | |
| prompt = f"Generate a multiple-choice question about {topic}" | |
| response = client.completions.create( | |
| model="grok-beta", | |
| prompt=prompt, | |
| max_tokens=150, # Limit the response length | |
| n=1, # Generate only 1 response | |
| stop=None, # No specific stop sequence | |
| ) | |
| question = response.choices[0].text.split("\n")[0] | |
| choices = response.choices[0].text.split("\n")[1:] | |
| return question, choices | |
| def game_mode(topic): | |
| st.write("Game Mode: Answer quickly!") | |
| # Start a timer for the game mode (30 seconds per question) | |
| start_time = time.time() | |
| question, choices = generate_question(topic) | |
| st.write(question) | |
| # Use session state to track whether the answer has been submitted | |
| if 'submitted' not in st.session_state: | |
| st.session_state.submitted = False | |
| if not st.session_state.submitted: | |
| answer = st.radio("Select your answer:", choices) | |
| submit_button = st.button("Submit") | |
| if submit_button: | |
| st.session_state.submitted = True | |
| st.write("You selected:", answer) | |
| time_elapsed = time.time() - start_time | |
| st.write(f"Time taken: {int(time_elapsed)} seconds") | |
| if time_elapsed >= 30: | |
| st.warning("Time's up!") | |
| else: | |
| st.success("Good job!") | |
| else: | |
| st.write("You've already submitted your answer.") | |
| def quiz_mode(topic): | |
| st.write("Quiz Mode: Take your time!") | |
| question, choices = generate_question(topic) | |
| st.write(question) | |
| # Use session state to track whether the answer has been submitted | |
| if 'submitted' not in st.session_state: | |
| st.session_state.submitted = False | |
| if not st.session_state.submitted: | |
| answer = st.radio("Select your answer:", choices) | |
| submit_button = st.button("Submit") | |
| if submit_button: | |
| st.session_state.submitted = True | |
| st.write("You selected:", answer) | |
| st.success("Great! On to the next question!") | |
| else: | |
| st.write("You've already submitted your answer.") | |
| def main(): | |
| st.title("Grok-Powered Quiz App") | |
| mode = st.selectbox("Choose the mode", ["Game Mode", "Quiz Mode"]) | |
| topic = st.text_input("Enter a topic:") | |
| if topic: | |
| if mode == "Game Mode": | |
| game_mode(topic) | |
| else: | |
| quiz_mode(topic) | |
| if __name__ == "__main__": | |
| main() | |