File size: 2,476 Bytes
8e0a0ac
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
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)