import json import os import logging from typing import Dict logger = logging.getLogger(__name__) PROMPTS_FILE = "data/prompts.json" DEFAULT_SYSTEM_PROMPT = """You are an expert JEE/NEET educator creating Telegram channel posts. STRICT FORMATTING RULES: 1. Use text for bold headers and section titles 2. Use text for italics (sparingly) 3. Write formulas in plain text using Unicode: × ÷ Δ α β π √ ≈ ≠ ≤ ≥ Example: Kp = Kc × (RT)^Δn ← correct Never use: $Kp = Kc(RT)^{\\Delta n}$ or backticks for formulas 4. Use • for bullet points 5. Do NOT use: ##headers, LaTeX, markdown tables, code blocks 6. Keep output under 3800 characters """ DEFAULT_TEMPLATES = { "pyq_question": "Generate a realistic Previous Year Question (PYQ) style MCQ for {exam} {year} on the topic \"{chapter}\" from {subject}.", "formula_sheet": "Generate a concise 'Formula and Concept Cheat Sheet' for {exam} on the chapter \"{chapter}\" ({subject}).", "short_notes": "Create 'Rapid Revision Notes' for {exam} on \"{chapter}\" from {subject}.", "motivational": "Write a short, powerful motivational message for an exam aspirant studying {subject}. Topic: {chapter}", "concept_recap": "Explain one non-obvious, crucial concept from \"{chapter}\" ({subject}) that often appears in {exam}.", "mnemonic": "Create a catchy mnemonic or memory trick to remember a complex set of facts/formulas in \"{chapter}\" ({subject}).", "mock_question": "Generate a high-yield 'Mock Challenge' MCQ for {exam} on \"{chapter}\" ({subject}).", "mcq_session": """Generate exactly 10 high-quality multiple-choice questions (MCQs) for {exam} on the chapter "{chapter}" ({subject}). IMPORTANT: Return the response ONLY as a JSON array of objects. Do not include any conversational text. Format: [ {{ "question": "Full question text...", "options": ["Option A", "Option B", "Option C", "Option D"], "correct_index": 0, "explanation": "Why is this the correct answer?" }}, ... ] Ensure questions vary in difficulty and cover the entire chapter. """ } class TemplateManager: def __init__(self): self.data = { "system_prompt": DEFAULT_SYSTEM_PROMPT, "templates": DEFAULT_TEMPLATES.copy() } self.load_prompts() def load_prompts(self): """Load prompts from Gist (remote) or JSON file (local).""" # 1. Try to pull from Gist first from content.remote_storage import pull_from_gist remote_data = pull_from_gist(os.path.basename(PROMPTS_FILE)) if remote_data: if "system_prompt" in remote_data: self.data["system_prompt"] = remote_data["system_prompt"] if "templates" in remote_data: self.data["templates"].update(remote_data["templates"]) logger.info(f"[OK] Prompts loaded from Gist") # Save locally self._save_local() return # 2. Fallback to local file if not os.path.exists(PROMPTS_FILE): return try: with open(PROMPTS_FILE, "r") as f: loaded_data = json.load(f) if "system_prompt" in loaded_data: self.data["system_prompt"] = loaded_data["system_prompt"] if "templates" in loaded_data: self.data["templates"].update(loaded_data["templates"]) logger.info(f"[OK] Prompts loaded from {PROMPTS_FILE}") except Exception as e: logger.error(f"Error loading prompts: {e}") def _save_local(self): """Internal helper to save prompts to local file.""" try: os.makedirs(os.path.dirname(PROMPTS_FILE), exist_ok=True) with open(PROMPTS_FILE, "w") as f: json.dump(self.data, f, indent=2) except Exception as e: logger.error(f"[LOCAL PROMPT SAVE ERROR] {e}") def save_prompts(self, data: dict) -> bool: """Save prompts locally and to GitHub Gist.""" self.data = data self._save_local() # Push to Gist from content.remote_storage import push_to_gist push_to_gist(os.path.basename(PROMPTS_FILE), data) return True def get_template(self, content_type: str) -> str: return self.data.get("templates", {}).get(content_type, DEFAULT_TEMPLATES.get(content_type, "")) @property def system_prompt(self) -> str: return self.data.get("system_prompt", "") template_manager = TemplateManager()