import os import json import logging from datetime import datetime from huggingface_hub import InferenceClient logger = logging.getLogger(__name__) # ── Curriculum Definition ─────────────────────────────────────────────────── CURRICULUM = { "JEE Main": { "Physics": ["Units and Measurements", "Kinematics", "Laws of Motion", "Work, Energy and Power", "Rotational Motion", "Gravitation", "Properties of Solids and Liquids", "Thermodynamics", "Kinetic Theory of Gases", "Oscillations and Waves", "Electrostatics", "Current Electricity", "Magnetic Effects of Current and Magnetism", "Electromagnetic Induction and Alternating Currents", "Electromagnetic Waves", "Optics", "Dual Nature of Matter and Radiation", "Atoms and Nuclei", "Electronic Devices", "Communication Systems"], "Chemistry": ["Some Basic Concepts in Chemistry", "States of Matter", "Atomic Structure", "Chemical Bonding and Molecular Structure", "Chemical Thermodynamics", "Solutions", "Equilibrium", "Redox Reactions and Electrochemistry", "Chemical Kinetics", "Surface Chemistry", "Classification of Elements and Periodicity in Properties", "General Principles and Processes of Isolation of Metals", "Hydrogen", "s-Block Elements", "p-Block Elements", "d- and f-Block Elements", "Coordination Compounds", "Environmental Chemistry", "Purification and Characterisation of Organic Compounds", "Some Basic Principles of Organic Chemistry", "Hydrocarbons", "Organic Compounds Containing Halogens", "Organic Compounds Containing Oxygen", "Organic Compounds Containing Nitrogen", "Polymers", "Biomolecules", "Chemistry in Everyday Life", "Principles Related to Practical Chemistry"], "Mathematics": ["Sets, Relations and Functions", "Complex Numbers and Quadratic Equations", "Matrices and Determinants", "Permutations and Combinations", "Mathematical Induction", "Binomial Theorem and its Simple Applications", "Sequences and Series", "Limit, Continuity and Differentiability", "Integral Calculus", "Differential Equations", "Coordinate Geometry", "Three Dimensional Geometry", "Vector Algebra", "Statistics and Probability", "Trigonometry", "Mathematical Reasoning"] }, "NEET": { "Physics": ["Physical World and Measurement", "Kinematics", "Laws of Motion", "Work, Energy and Power", "Motion of System of Particles and Rigid Body", "Gravitation", "Properties of Bulk Matter", "Thermodynamics", "Behaviour of Perfect Gas and Kinetic Theory", "Oscillations and Waves", "Electrostatics", "Current Electricity", "Magnetic Effects of Current and Magnetism", "Electromagnetic Induction and Alternating Currents", "Electromagnetic Waves", "Optics", "Dual Nature of Matter and Radiation", "Atoms and Nuclei", "Electronic Devices"], "Chemistry": ["Some Basic Concepts of Chemistry", "Structure of Atom", "Classification of Elements and Periodicity in Properties", "Chemical Bonding and Molecular Structure", "States of Matter: Gases and Liquids", "Thermodynamics", "Equilibrium", "Redox Reactions", "Hydrogen", "s-Block Element", "Some p-Block Elements", "Organic Chemistry- Some Basic Principles and Techniques", "Hydrocarbons", "Environmental Chemistry", "Solid State", "Solutions", "Electrochemistry", "Chemical Kinetics", "Surface Chemistry", "General Principles and Processes of Isolation of Elements", "p- Block Elements", "d and f Block Elements", "Coordination Compounds", "Haloalkanes and Haloarenes", "Alcohols, Phenols and Ethers", "Aldehydes, Ketones and Carboxylic Acids", "Organic Compounds Containing Nitrogen", "Biomolecules", "Polymers", "Chemistry in Everyday Life"], "Biology": ["Diversity in Living World", "Structural Organisation in Animals and Plants", "Cell Structure and Function", "Plant Physiology", "Human Physiology", "Reproduction", "Genetics and Evolution", "Biology and Human Welfare", "Biotechnology and Its Applications", "Ecology and Environment"] } } # ── AI Generation Logic ────────────────────────────────────────────────────── def get_exam_countdown(): """Returns a string with days left for JEE/NEET.""" # Example dates - in real app, these would be fetched or updated jee_date = datetime(2027, 1, 20) neet_date = datetime(2027, 5, 5) now = datetime.now() jee_days = (jee_date - now).days neet_days = (neet_date - now).days return f"🚀 JEE Main in {max(0, jee_days)} days | NEET in {max(0, neet_days)} days" def generate_mcqs(stream: str, subject: str, topic: str, difficulty: str = "medium", count: int = 5, pyq_mode: bool = False): """ Generate high-quality MCQs using HuggingFace Inference API. Returns: (list of dicts, status_message) """ logger.info("AI MCQ Generation: %s | %s | %s | %s | PYQ=%s (%d qs)", stream, subject, topic, difficulty, pyq_mode, count) hf_token = os.environ.get("HF_TOKEN") if not hf_token: return [], "❌ HF_TOKEN not set in environment." client = InferenceClient(token=hf_token) source_type = "official Previous Year Questions (PYQ)" if pyq_mode else "syllabus-aligned questions" prompt = f"""Generate {count} {difficulty.upper()} difficulty {source_type} for {stream} on the topic: {topic} (Subject: {subject}). For each question, provide: 1. The question text (q) 2. Four options (opts) 3. Correct option index (ans) [0-3] 4. A short hint (hint) 5. A full detailed solution (explanation) Format: Raw JSON list of objects. """ try: response = client.text_generation( prompt, model="meta-llama/Llama-3.1-8B-Instruct", max_new_tokens=3000, temperature=0.7, ) text = response.strip() # Clean response if model adds markdown if "```json" in text: text = text.split("```json")[1].split("```")[0].strip() elif "```" in text: text = text.split("```")[1].split("```")[0].strip() mcqs = json.loads(text) # Validation valid_mcqs = [] for m in mcqs: if all(k in m for k in ("q", "opts", "ans", "hint", "explanation")): if isinstance(m["opts"], list) and len(m["opts"]) == 4: if 0 <= m["ans"] <= 3: valid_mcqs.append(m) if not valid_mcqs: return [], "❌ AI returned malformed or empty data." return valid_mcqs, f"✨ Successfully generated {len(valid_mcqs)} {difficulty} MCQs!" except Exception as e: logger.error("AI Generation Error: %s", e) return [], f"❌ AI Generation failed: {e}"