TestPrep_Guru / app.py
AneelaFatima's picture
Create app.py
8e0a0ac verified
import os
import gradio as gr # βœ… Must be at the top
from openai import OpenAI
# βœ… Load API key securely from Hugging Face secret
api_key = os.environ.get("GROQ_API_KEY")
if not api_key:
raise ValueError("❌ Missing GROQ_API_KEY. Please add it in the Hugging Face 'Secrets' settings.")
# βœ… Initialize OpenAI client for Groq
client = OpenAI(
api_key=api_key,
base_url="https://api.groq.com/openai/v1"
)
# βœ… Chatbot function
def generate_test_content(subject, chapter, topic, question_type, language):
try:
lang_instruction = "Answer in simple English." if language == "English" else "Answer in simple Urdu."
user_prompt = f"""
You are a test preparation tutor for Pakistani board students of Class 9 and 10.
Prepare content only from the specified syllabus.
Subject: {subject}
Chapter: {chapter}
Topic: {topic}
Question Type: {question_type}
{lang_instruction}
1. Provide test preparation content from the given topic.
2. If MCQs are selected, generate at least 5 MCQs with correct answers.
3. If Short/Long Questions are selected, give proper answers based on syllabus.
4. If Important Topics is selected, list 5 key concepts from this chapter.
Be friendly, encouraging, and never add off-topic material.
"""
response = client.chat.completions.create(
model="llama3-70b-8192",
messages=[
{"role": "system", "content": "You are a helpful exam preparation assistant."},
{"role": "user", "content": user_prompt}
]
)
return response.choices[0].message.content
except Exception as e:
return f"❌ Error: {str(e)}"
# βœ… Gradio interface
interface = gr.Interface(
fn=generate_test_content,
inputs=[
gr.Textbox(label="πŸ“˜ Subject (e.g., Biology)"),
gr.Textbox(label="πŸ”’ Chapter (e.g., Chapter 2)"),
gr.Textbox(label="πŸ“Œ Topic (e.g., Cell Structure)"),
gr.Radio(["MCQs", "Short Questions", "Long Questions", "Important Topics"], label="❓ Question Type"),
gr.Radio(["English", "Urdu"], label="🌐 Language")
],
outputs="text",
title="🧠 TestPrep Guru β€” Syllabus-Based Exam Chatbot",
description="Get MCQs, short/long answers, and important topics based on your syllabus. Perfect for Class 9 & 10 students in Pakistan."
)
# βœ… Required for Hugging Face Spaces
if __name__ == "__main__":
interface.launch(server_name="0.0.0.0", server_port=7860)