SameerArz's picture
Update app.py
ee16ad4 verified
raw
history blame
7.75 kB
import gradio as gr
from groq import Groq
import os
import json
import random
import sqlite3
# Initialize Groq client
client = Groq(api_key=os.environ["GROQ_API_KEY"])
print("API Key:", os.environ.get("GROQ_API_KEY")) # Debug print
# Define valid_models globally
valid_models = [
"distil-whisper-large-v3-en",
"gemma2-9b-it",
"llama-3.3-70b-versatile",
"llama-3.1-8b-instant",
"llama-guard-3-8b",
"llama3-70b-8192",
"llama3-8b-8192",
"mixtral-8x7b-32768",
"whisper-large-v3",
"whisper-large-v3-turbo",
"qwen-qwq-32b",
"mistral-saba-24b",
"qwen-2.5-coder-32b",
"qwen-2.5-32b",
"deepseek-r1-distill-qwen-32b",
"deepseek-r1-distill-llama-70b-specdec",
"deepseek-r1-distill-llama-70b",
"llama-3.3-70b-specdec",
"llama-3.2-1b-preview",
"llama-3.2-3b-preview",
"llama-3.2-11b-vision-preview",
"llama-3.2-90b-vision-preview"
]
# Initialize or connect to SQLite database for points
conn = sqlite3.connect("student_points.db", check_same_thread=False)
cursor = conn.cursor()
cursor.execute('''CREATE TABLE IF NOT EXISTS points (student_id TEXT, points INTEGER, timestamp TEXT)''')
conn.commit()
def generate_tutor_output(subject, grade, student_input, model):
if model not in valid_models:
model = "mixtral-8x7b-32768" # Fallback model
print(f"Invalid model selected: {model}. Using fallback: mixtral-8x7b-32768")
prompt = f"""
You are an expert tutor in {subject} for a {grade} grade student.
The student has provided the following input: "{student_input}"
Please generate:
1. A fun, engaging lesson (2-3 paragraphs) tailored to a {grade} grader's understanding.
2. A thought-provoking multiple-choice question (with 4 options: a, b, c, d) to test understanding.
3. Constructive feedback on the student's input.
Format your response as a JSON object with keys: "lesson", "question", "options", "correct_answer", "feedback"
"""
try:
completion = client.chat.completions.create(
messages=[
{
"role": "system",
"content": f"You are a fun, creative AI tutor for {grade} graders, expert in {subject}. You explain concepts in a simple, exciting way with relatable examples (like math problems for their age). Your goal is to spark curiosity and help students practice what they learn!",
},
{
"role": "user",
"content": prompt,
}
],
model=model,
max_tokens=1200,
)
return completion.choices[0].message.content
except Exception as e:
print(f"Groq API Error: {str(e)}")
return json.dumps({
"lesson": f"Error: Could not generate lesson. API error: {str(e)}",
"question": "No question available",
"options": [],
"correct_answer": "",
"feedback": "No feedback available due to API error"
})
def check_answer(selected_answer, correct_answer, current_points, student_id="student1"):
if selected_answer == correct_answer:
feedback = "πŸŽ‰ Awesome job! You got it right! Keep rocking it!"
new_points = current_points + 10
else:
feedback = f"πŸ˜… Not quite! The correct answer was '{correct_answer}'. Try again next time!"
new_points = current_points
# Save points to database
cursor.execute("INSERT INTO points (student_id, points, timestamp) VALUES (?, ?, ?)",
(student_id, new_points, "2025-03-08 04:25"))
conn.commit()
return feedback, new_points
def process_output(output):
print(f"Raw API Output: {output}")
try:
parsed = json.loads(output)
# Shuffle options for variety
options_list = list(zip(["a", "b", "c", "d"], parsed["options"]))
random.shuffle(options_list)
options = [f"{k}. {v}" for k, v in options_list]
correct_key = [k for k, v in options_list if v == parsed["correct_answer"]][0]
return (
parsed["lesson"],
parsed["question"],
options,
correct_key,
parsed["feedback"]
)
except Exception as e:
print(f"JSON Parsing Error: {str(e)}")
return (
f"Error parsing response: {str(e)}",
"No question available",
[],
"",
"No feedback available"
)
with gr.Blocks(title="Learn & Practice πŸš€") as demo:
gr.Markdown("# πŸš€ Learn & Practice Zone (Grades 5-10)")
# Input Section
with gr.Row():
with gr.Column(scale=2):
subject = gr.Dropdown(
["Math", "Science", "History", "Geography", "Economics"],
label="Subject",
info="Pick your favorite subject!"
)
grade = gr.Dropdown(
["5th Grade", "6th Grade", "7th Grade", "8th Grade", "9th Grade", "10th Grade"],
label="Your Grade",
info="Select your grade level"
)
model_select = gr.Dropdown(
valid_models,
label="AI Tutor Model",
value="mixtral-8x7b-32768",
info="Choose your AI tutor"
)
student_input = gr.Textbox(
placeholder="What do you want to learn today?",
label="Your Question",
info="Ask anything about the subject!"
)
submit_button = gr.Button("Get Lesson & Practice", variant="primary")
# Output Section
with gr.Column(scale=3):
lesson_output = gr.Markdown(label="Your Lesson")
question_output = gr.Markdown(label="Test Your Skills")
options_output = gr.Radio(label="Choose an Answer", choices=[], visible=False)
feedback_output = gr.Markdown(label="Feedback on Your Question")
answer_feedback = gr.Markdown(label="Answer Feedback")
points = gr.Number(label="Your Points", value=0)
# Instructions
gr.Markdown("""
### How to Play & Learn
1. Pick a subject and your grade.
2. Choose an AI tutor model.
3. Ask a question or topic you’re curious about.
4. Read the fun lesson, then answer the question to test yourself.
5. Earn points for correct answers and keep learning!
""")
def update_interface(subject, grade, student_input, model):
print(f"Selected Model: {model}")
output = generate_tutor_output(subject, grade, student_input, model)
lesson, question, options, correct_answer, feedback = process_output(output)
return (
lesson,
question,
gr.update(choices=options, visible=True),
feedback,
"", # Clear answer feedback
gr.update(value=0) # Reset points for new session
), correct_answer
# State to store correct answer
correct_answer_state = gr.State()
submit_button.click(
fn=update_interface,
inputs=[subject, grade, student_input, model_select],
outputs=[lesson_output, question_output, options_output, feedback_output, answer_feedback, points]
).then(
fn=lambda x: x,
inputs=[gr.State()],
outputs=[correct_answer_state]
)
options_output.change(
fn=check_answer,
inputs=[options_output, correct_answer_state, points],
outputs=[answer_feedback, points]
)
if __name__ == "__main__":
try:
demo.launch(server_name="0.0.0.0", server_port=7860)
finally:
conn.close() # Close database connection on shutdown