Spaces:
Sleeping
Sleeping
| 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) | |