import gradio as gr import requests import os import json # Hugging Face API key ko env var me rakho HF_API_KEY = os.getenv("HF_API_KEY") API_URL = "https://api-inference.huggingface.co/models/koshkosh/quiz-generator" headers = {"Authorization": f"Bearer {HF_API_KEY}"} def generate_quiz(prompt): # 👉 Always ask for structured JSON with 10 questions full_prompt = f""" Generate 10 multiple choice quiz questions about: {prompt}. Return the result strictly in JSON format like this: [ {{ "question": "Your question?", "options": ["A", "B", "C", "D"], "answer": "A" }} ] """ payload = {"inputs": full_prompt} response = requests.post(API_URL, headers=headers, json=payload) try: data = response.json() except Exception: return "⚠️ Error: Model response JSON format me nahi hai." print("🔍 Raw model response:", data) # Debugging ke liye # Model response text ko extract karna text = None if isinstance(data, list) and len(data) > 0 and "generated_text" in data[0]: text = data[0]["generated_text"] elif isinstance(data, dict) and "generated_text" in data: text = data["generated_text"] if not text: # Fallback agar kuch bhi nahi aaya return [ { "question": "Sample Question (Model did not return output)", "options": ["A", "B", "C", "D"], "answer": "A" } ] # Try JSON parsing try: quiz = json.loads(text) return quiz except: return f"⚠️ Model text return kar raha hai, JSON nahi:\n\n{text}" # Gradio UI demo = gr.Interface( fn=generate_quiz, inputs=gr.Textbox(lines=2, placeholder="Type e.g. React ke 10 question do"), outputs="json", # 👈 ab output JSON format me dikhayega title="Quiz Generator", description="Enter a topic and get **10 quiz questions** generated by AI 🚀" ) if __name__ == "__main__": demo.launch()