learn / app.py
SanaAdeel's picture
Update app.py
daa63ec verified
import openai
import streamlit as st
# Fetch the API key from Hugging Face secrets
api_key = st.secrets["AIML_API_KEY"]
# Set up OpenAI API key
openai.api_key = api_key
# Define subject-based video links
video_links = {
"Math": "https://www.youtube.com/watch?v=JT0MmZcJ2Vw", # Math-specific video
"English": "https://www.youtube.com/watch?v=2n4enj6YMnw", # English-specific video
"GK": "https://www.youtube.com/watch?v=F-8KYJpBZTg", # GK-specific video
}
# Function to get a question and options using OpenAI API (updated for version 0.28.0)
def get_question_and_options(subject):
# Construct the prompt based on the subject
prompt = f"Generate a multiple-choice question with 4 options for the subject: {subject}. Make it suitable for kids."
try:
# Make a request to OpenAI's old API (0.28.0 version) using `openai.Completion.create()`
response = openai.Completion.create(
engine="text-davinci-003", # Use engine name instead of model name in older versions
prompt=prompt,
max_tokens=150,
temperature=0.7
)
# Extract the generated question and options from the API response
generated_text = response['choices'][0]['text'].strip()
# Example of the format: "Question: What is 5 + 3? Options: 1. 6 2. 7 3. 8 4. 9 Answer: 8"
question_parts = generated_text.split("Options:")
question = question_parts[0].strip()
options_raw = question_parts[1].strip().split("Answer:")[0].strip()
options = options_raw.split("\n")
# Extract the correct answer
correct_answer = generated_text.split("Answer:")[1].strip()
return {
"question": question,
"options": options,
"correct_answer": correct_answer
}
except Exception as e:
st.error(f"Error generating question: {str(e)}")
return None
# Streamlit UI
st.title("Quiz App with Subject-Based Videos 🎮")
# Ask the user for their age and subject
age = st.number_input("Enter your age", min_value=1, max_value=100, step=1)
subject = st.selectbox("Select a Subject", ["Math", "English", "GK"])
# Get the question and options for the selected subject using the OpenAI API
question_data = get_question_and_options(subject)
# Display the question and options if data is available
if question_data:
st.subheader(question_data["question"])
options = question_data["options"]
# Provide options as radio buttons for the user to select
user_answer = st.radio("Select your answer", options)
# Check if the user selected an answer
if st.button("Submit Answer"):
if user_answer == question_data["correct_answer"]:
st.success("✅ Correct!")
# Play the corresponding subject video
subject_video_link = video_links.get(subject, "https://www.youtube.com/watch?v=DEFAULT_VIDEO")
st.video(subject_video_link)
else:
st.error("❌ Oops! Try again.")
st.info(f"The correct answer was: {question_data['correct_answer']}")
# Optional: Button to reset and ask another question
if st.button("Next Question"):
st.experimental_rerun()