Telegram-Bot / content /syllabus_manager.py
H3y-sam's picture
Upload 54 files
94b42f2 verified
Raw History Blame Contribute Delete
4.26 kB
import json
import os
import logging
from typing import List, Dict
logger = logging.getLogger(__name__)
SYLLABUS_FILE = "data/syllabus.json"
class SyllabusManager:
def __init__(self):
self.syllabus = {}
self.load_syllabus()
# Map channel focus strings to JSON keys
self.focus_map = {
"JEE Main": "JEE_MAINS_2026",
"JEE Advanced": "JEE_ADVANCED_2026",
"NEET": "NEET_UG_2026"
}
def load_syllabus(self):
"""Loads the comprehensive syllabus JSON from data/syllabus.json."""
if not os.path.exists(SYLLABUS_FILE):
logger.error(f"Syllabus file NOT FOUND: {SYLLABUS_FILE}")
return
try:
with open(SYLLABUS_FILE, "r") as f:
self.syllabus = json.load(f)
logger.info(f"[OK] Syllabus loaded successfully from {SYLLABUS_FILE}")
except Exception as e:
logger.error(f"Error loading syllabus: {e}")
def save_syllabus(self, syllabus_data: dict) -> bool:
"""Saves a new syllabus dictionary to the data/syllabus.json file."""
try:
os.makedirs(os.path.dirname(SYLLABUS_FILE), exist_ok=True)
with open(SYLLABUS_FILE, "w") as f:
json.dump(syllabus_data, f, indent=2)
self.syllabus = syllabus_data
logger.info(f"[OK] Syllabus saved successfully to {SYLLABUS_FILE}")
return True
except Exception as e:
logger.error(f"Error saving syllabus: {e}")
return False
def get_chapters(self, exam_focus_list: List[str], subject: str) -> List[str]:
"""
Retrieves a flattened list of all chapters/topics for a given subject
across multiple exam focuses (e.g., both JEE Main and Advanced).
"""
all_topics = set()
# Normalize subject names to match JSON keys
subject_map = {
"maths": "Mathematics",
"biology": "Biology",
"physics": "Physics",
"chemistry": "Chemistry"
}
subject = subject_map.get(subject.lower(), subject.title())
for focus in exam_focus_list:
json_key = self.focus_map.get(focus)
if not json_key or json_key not in self.syllabus:
continue
exam_data = self.syllabus[json_key]
# Navigate to the subject block
subjects_block = exam_data.get("Subjects", {})
# Subject names in JSON are properly capitalized (Physics, Chemistry, etc.)
subject_key = next((k for k in subjects_block.keys() if k.lower() == subject.lower()), None)
if not subject_key:
continue
subj_data = subjects_block[subject_key]
# Extract topics recursively from any nested structure
all_topics.update(self._extract_topics(subj_data))
flattened = sorted(list(all_topics))
if not flattened:
logger.warning(f"No topics found for focus {exam_focus_list} and subject {subject}")
return ["General"]
return flattened
def _extract_topics(self, data) -> List[str]:
"""Recursively extracts string topics from nested dictionaries and lists."""
topics = []
if isinstance(data, list):
topics.extend([str(item) for item in data])
elif isinstance(data, dict):
for val in data.values():
topics.extend(self._extract_topics(val))
return topics
def get_all_subjects(self, exam_focus: str) -> List[str]:
"""Returns the list of subjects available for a specific exam (e.g., biology for NEET)."""
json_key = self.focus_map.get(exam_focus)
if not json_key or json_key not in self.syllabus:
return ["physics", "chemistry", "maths"]
subjects = self.syllabus[json_key].get("Subjects", {}).keys()
return [s.lower() for s in subjects]
# Singleton instance for the bot
syllabus_manager = SyllabusManager()