Telegram-Bot / content /generator.py
H3y-sam's picture
Update content/generator.py
d08a10a verified
Raw History Blame Contribute Delete
25.3 kB
import logging
import random
import traceback
import asyncio
import json
import re
import httpx
from datetime import datetime
from config import (
GEMINI_MODEL, GEMINI_MAX_TOKENS,
GEMINI_TEMPERATURE, SUBJECT_ROTATION, GEMINI_API_KEY
)
from content.config_manager import config_manager
from content.syllabus_manager import syllabus_manager
from content.template_manager import template_manager
from content.history import pick_fresh_chapter, archive_weekly_post
logger = logging.getLogger(__name__)
# Initialize Gemini Client check
if not GEMINI_API_KEY:
logger.warning("⚠️ GEMINI_API_KEY is missing! Bot will not be able to generate content. Add it to .env file.")
else:
logger.info("βœ… Gemini API configured and ready")
# ─────────────────────────────────────────────
# Helpers
# ─────────────────────────────────────────────
def _clean_markdown(text: str) -> str:
"""Convert Gemini output to Telegram HTML format."""
if not text:
return ""
import html as html_lib
import re
# 1. Unescape any HTML entities first
text = html_lib.unescape(text)
# 2. Strip code fences wrapping whole response
text = re.sub(r'^```(?:json|python|markdown)?\s*\n?', '', text, flags=re.MULTILINE)
text = re.sub(r'\n?```$', '', text, flags=re.MULTILINE).strip()
# 3. Escape HTML special chars BEFORE adding our own tags
text = text.replace('&', '&')
text = text.replace('<', '&lt;')
text = text.replace('>', '&gt;')
# Restore permitted HTML tags that Gemini might have generated (since prompt asks for <b>)
allowed_tags = ['b', 'i', 'code', 'u', 's', 'pre', 'strong', 'em']
for tag in allowed_tags:
text = re.sub(rf'&lt;({tag})&gt;', rf'<\1>', text, flags=re.IGNORECASE)
text = re.sub(rf'&lt;/({tag})&gt;', rf'</\1>', text, flags=re.IGNORECASE)
# 4. Convert **bold** or *bold* β†’ <b>bold</b>
text = re.sub(r'\*\*(.+?)\*\*', r'<b>\1</b>', text, flags=re.DOTALL)
text = re.sub(r'\*([^\*\n]+?)\*', r'<b>\1</b>', text)
# 5. Convert _italic_ β†’ <i>italic</i>
text = re.sub(r'_([^_\n]+?)_', r'<i>\1</i>', text)
# 6. Convert `code` β†’ <code>code</code>
text = re.sub(r'`([^`]+?)`', r'<code>\1</code>', text)
# 7. Convert ## Headers β†’ <b>Header</b>
text = re.sub(r'^#{1,3}\s+(.+)$', r'<b>\1</b>', text, flags=re.MULTILINE)
# 8. Remove $...$ math delimiters, keep formula text plain
text = re.sub(r'\$\$(.+?)\$\$', lambda m: m.group(1).strip(), text, flags=re.DOTALL)
text = re.sub(r'\$([^\$\n]+?)\$', lambda m: m.group(1).strip(), text)
# 9. Truncate
if len(text) > 4000:
text = text[:3997] + "..."
return text
def _today() -> str:
return datetime.now().strftime("%A")
async def _call_llm(prompt: str, system_prompt: str = None) -> str:
"""Wrapper for Gemini API using httpx."""
max_retries = 5 # More retries to handle transient 503 spikes
if not GEMINI_API_KEY:
raise Exception("GEMINI_API_KEY is missing from config/env. Add it to .env file.")
# Use GEMINI_MODEL from config (not a hardcoded alias that may degrade)
model = GEMINI_MODEL
url = f"https://generativelanguage.googleapis.com/v1beta/models/{model}:generateContent"
headers = {
"Content-Type": "application/json",
"X-goog-api-key": GEMINI_API_KEY
}
sys_prompt = system_prompt if system_prompt else template_manager.system_prompt
payload = {
"contents": [
{
"parts": [
{"text": prompt}
]
}
],
"systemInstruction": {
"parts": [
{"text": sys_prompt}
]
},
"generationConfig": {
"temperature": GEMINI_TEMPERATURE,
"maxOutputTokens": GEMINI_MAX_TOKENS
}
}
last_error = None
for attempt in range(max_retries):
try:
async with httpx.AsyncClient(timeout=60.0) as client_http:
resp = await client_http.post(url, headers=headers, json=payload)
# 429 Rate Limit β€” wait and retry
if resp.status_code == 429:
wait_time = 10 * (attempt + 1)
logger.warning(f"[Gemini] Rate limit (429). Retrying in {wait_time}s... (Attempt {attempt+1}/{max_retries})")
await asyncio.sleep(wait_time)
continue
# 503 Service Unavailable β€” model under high load, use exponential backoff
if resp.status_code == 503:
wait_time = min(5 * (2 ** attempt), 60) # 5s, 10s, 20s, 40s, 60s
logger.warning(f"[Gemini] Server overloaded (503). Retrying in {wait_time}s... (Attempt {attempt+1}/{max_retries})")
await asyncio.sleep(wait_time)
continue
if resp.status_code != 200:
logger.error(f"[Gemini] HTTP Error {resp.status_code}: {resp.text[:200]}")
resp.raise_for_status()
data = resp.json()
# Extract text from response
try:
content = data['candidates'][0]['content']['parts'][0]['text'].strip()
except (KeyError, IndexError) as parse_err:
logger.error(f"[Gemini] Response parse error: {parse_err}. Response data: {data}")
last_error = Exception(f"Failed to parse Gemini response: {data}")
await asyncio.sleep(2)
continue
if not content:
last_error = Exception("Gemini returned empty response")
await asyncio.sleep(2)
continue
logger.info("[Gemini] βœ… Content generated successfully")
return _clean_markdown(content)
except Exception as e:
last_error = e
logger.error(f"[Gemini] API error on attempt {attempt+1}: {e}")
await asyncio.sleep(3)
raise Exception(f"[Gemini] Failed after {max_retries} attempts: {last_error}")
def _channel_subjects(channel_key: str) -> list:
"""Return subjects active for this channel on today's rotation, filtered by syllabus availability."""
channel_cfg = config_manager.channels.get(channel_key, {})
exam_focus = channel_cfg.get("exam_focus", ["JEE Main"])
# Get all subjects available in the syllabus for this exam
all_syllabus_subjects = set()
for focus in exam_focus:
all_syllabus_subjects.update(syllabus_manager.get_all_subjects(focus))
ch_subjects = set(channel_cfg.get("subjects", list(all_syllabus_subjects)))
day_subjects = set(SUBJECT_ROTATION.get(_today(), list(all_syllabus_subjects)))
active = list(ch_subjects & day_subjects)
return active if active else list(ch_subjects)
def _pick(channel_key: str, content_type: str) -> tuple:
"""Pick a non-repeating (subject, chapter) pair for this channel + content type."""
subjects = _channel_subjects(channel_key)
subject = random.choice(subjects)
chapter = pick_fresh_chapter(channel_key, content_type, subject)
return subject, chapter
def _footer(channel_key: str, tag_key: str) -> str:
cfg = config_manager.channels.get(channel_key, {})
hashtag = cfg.get("hashtags", {}).get(tag_key, "")
footer_text = (
"─────────────────────\n"
"πŸ‘ React | πŸ“Œ Save | πŸ“’ Share\n"
"πŸš€ @xcrazylearners"
)
if hashtag:
return f"\n\n{hashtag}\n{footer_text}"
else:
return f"\n\n{footer_text}"
def _exam(channel_key: str) -> str:
exams = config_manager.channels.get(channel_key, {}).get("exam_focus", ["JEE Main"])
return random.choice(exams)
def _difficulty_context(channel_key: str) -> str:
"""Returns a difficulty instruction based on the channel's target exams."""
cfg = config_manager.channels.get(channel_key, {})
exams = cfg.get("exam_focus", [])
# Class 9/10 focus
if any(ex in ["Class 9", "Class 10", "NTSE", "Foundation"] for ex in exams):
return "Difficulty: Foundation/School Level. Focus on basic concepts, definitions, and clear logic. Avoid extremely complex calculus or advanced topics."
# JEE Advanced focus
if "JEE Advanced" in exams:
return "Difficulty: Advanced/Hard. Use multi-concept problems, challenging numericals, and tricky logic. Focus on deep understanding."
# JEE Main / NEET focus (default for competitive)
return "Difficulty: Competitive (JEE Main/NEET level). Focus on accuracy, speed-based patterns, and standard competitive concepts."
# ─────────────────────────────────────────────
# 1. PYQ QUESTION (QUIZ MODE)
# ─────────────────────────────────────────────
import html
def _parse_quiz(text: str) -> dict:
"""Extracts quiz components from the AI-generated text."""
try:
import html
text = html.unescape(text)
# Question: everything between QUESTION: and (A)
q_match = re.search(r'❓\s*\*?QUESTION:?\*?(.*?)(?=\([A-D]\)|\*\(A\))', text, re.DOTALL | re.IGNORECASE)
if not q_match:
q_match = re.search(r'QUESTION:?(.*?)(?=\([A-D]\)|\*\(A\))', text, re.DOTALL | re.IGNORECASE)
question = q_match.group(1).strip() if q_match else ""
question = re.sub(r'[*_~`]', '', question) # Remove markdown formatting
if len(question) > 297:
question = question[:297] + "..."
# Options
options = []
for label in ["(A)", "(B)", "(C)", "(D)"]:
escaped_label = label.replace('(', r'\(').replace(')', r'\)')
next_label = r'\([B-D]\)' if label != "(D)" else r'(?:βœ…|ANSWER|πŸ’‘)'
pattern = r'(?:\*?)?' + escaped_label + r'(?:\*?)?(.*?)(?=(?:\*?)?' + next_label + ')'
opt_match = re.search(pattern, text, re.DOTALL | re.IGNORECASE)
if opt_match:
opt_text = opt_match.group(1).strip()
opt_text = re.sub(r'[*_~`]', '', opt_text) # Remove markdown formatting
options.append(opt_text[:100])
# Deduplicate options
unique_opts = []
for o in options:
while o in unique_opts:
o += " "
unique_opts.append(o)
options = unique_opts
if len(options) < 2:
return None
# Correct Answer
ans_match = re.search(r'ANSWER:\s*\*?\(([A-D])\)', text, re.IGNORECASE)
if not ans_match:
ans_match = re.search(r'ANSWER:\s*\*?([A-D])\b', text, re.IGNORECASE)
correct_letter = ans_match.group(1).upper() if ans_match else "A"
correct_index = {"A": 0, "B": 1, "C": 2, "D": 3}.get(correct_letter, 0)
correct_index = correct_index % len(options)
# Explanation
exp_match = re.search(r'πŸ’‘\s*\*?EXPLANATION:?\*?(.*?)(?=🎯|$)', text, re.DOTALL | re.IGNORECASE)
if not exp_match:
exp_match = re.search(r'EXPLANATION:?(.*?)(?=🎯|$)', text, re.DOTALL | re.IGNORECASE)
explanation = exp_match.group(1).strip() if exp_match else ""
explanation = re.sub(r'[*_~`]', '', explanation) # Remove markdown formatting
if len(explanation) > 197:
explanation = explanation[:197] + "..."
return {
"question": question,
"options": options,
"correct_index": correct_index,
"explanation": explanation,
"full_text": text
}
except Exception as e:
logger.error(f"Quiz parsing failed: {e}")
return None
async def generate_pyq_question(channel_key: str) -> dict:
subject, chapter = _pick(channel_key, "pyq_question")
exam = _exam(channel_key)
year = random.randint(2015, 2023)
template = template_manager.get_template("pyq_question")
diff_text = _difficulty_context(channel_key)
prompt = template.format(
exam=exam, year=year, chapter=chapter,
subject=subject.title()
) + f"\n\n{diff_text}"
raw_text = await _call_llm(prompt)
if not raw_text:
return {"error": "⚠️ Content temporarily unavailable."}
quiz_data = _parse_quiz(raw_text)
if not quiz_data:
# Fallback to plain text if parsing fails
return {"text": raw_text + _footer(channel_key, "pyq")}
# Return structured dict for the dispatcher
return {
"text": raw_text + _footer(channel_key, "pyq"),
"quiz": quiz_data,
"type": "quiz"
}
# ─────────────────────────────────────────────
# 2. FORMULA SHEET
# ─────────────────────────────────────────────
async def generate_formula_sheet(channel_key: str) -> str:
subject, chapter = _pick(channel_key, "formula_sheet")
exam = _exam(channel_key)
template = template_manager.get_template("formula_sheet")
prompt = template.format(exam=exam, chapter=chapter, subject=subject.title())
text = await _call_llm(prompt)
text = (text or "⚠️ Content temporarily unavailable.")
# Archive for Weekly PDF
if text != "⚠️ Content temporarily unavailable.":
archive_weekly_post(channel_key, "formula_sheet", subject, chapter, text)
return text + _footer(channel_key, "formula")
# ─────────────────────────────────────────────
# 3. SHORT NOTES
# ─────────────────────────────────────────────
async def generate_short_notes(channel_key: str) -> str:
subject, chapter = _pick(channel_key, "short_notes")
exam = _exam(channel_key)
template = template_manager.get_template("short_notes")
prompt = template.format(exam=exam, chapter=chapter, subject=subject.title())
text = await _call_llm(prompt)
text = (text or "⚠️ Content temporarily unavailable.")
# Archive for Weekly PDF
if text != "⚠️ Content temporarily unavailable.":
archive_weekly_post(channel_key, "short_notes", subject, chapter, text)
return text + _footer(channel_key, "notes")
# ─────────────────────────────────────────────
# 4. MNEMONIC
# ─────────────────────────────────────────────
async def generate_mnemonic(channel_key: str) -> str:
subject, chapter = _pick(channel_key, "mnemonic")
template = template_manager.get_template("mnemonic")
prompt = template.format(chapter=chapter, subject=subject.title())
text = await _call_llm(prompt)
return (text or "⚠️ Content temporarily unavailable.") + _footer(channel_key, "mnemonic")
# ─────────────────────────────────────────────
# 5. CONCEPT RECAP
# ─────────────────────────────────────────────
async def generate_concept_recap(channel_key: str) -> str:
subject, chapter = _pick(channel_key, "concept_recap")
exam = _exam(channel_key)
template = template_manager.get_template("concept_recap")
prompt = template.format(exam=exam, chapter=chapter, subject=subject.title())
text = await _call_llm(prompt)
return (text or "⚠️ Content temporarily unavailable.") + _footer(channel_key, "recap")
# ─────────────────────────────────────────────
# 6. MOCK MCQ
# ─────────────────────────────────────────────
async def generate_mock_question(channel_key: str) -> str:
subject, chapter = _pick(channel_key, "mock_question")
exam = _exam(channel_key)
template = template_manager.get_template("mock_question")
diff_text = _difficulty_context(channel_key)
prompt = template.format(exam=exam, chapter=chapter, subject=subject.title()) + f"\n\n{diff_text}"
text = await _call_llm(prompt)
return (text or "⚠️ Content temporarily unavailable.") + _footer(channel_key, "mock")
# ─────────────────────────────────────────────
# 7. MOTIVATIONAL
# ─────────────────────────────────────────────
async def generate_motivational(channel_key: str) -> str:
exam = _exam(channel_key)
# Pick a random subject and chapter to make the message specific
subjects = _channel_subjects(channel_key)
subject = random.choice(subjects)
chapter = pick_fresh_chapter(channel_key, "motivational", subject)
template = template_manager.get_template("motivational")
prompt = template.format(exam=exam, subject=subject.title(), chapter=chapter)
text = await _call_llm(prompt)
cfg = config_manager.channels.get(channel_key, {})
footer = cfg.get("footer", "")
return (text or "πŸŒ™ Rest well! See you tomorrow πŸ’ͺ") + (f"\n\n{footer}" if footer else "")
# ─────────────────────────────────────────────
# 8. MCQ POLL SESSION (10 polls, chapter-wise)
# ─────────────────────────────────────────────
def _parse_mcq_json(text: str) -> list:
"""Extract and repair a JSON array of MCQ dicts from the Gemini response."""
if not text: return []
# 1. Basic Cleaning
clean = text.strip()
if clean.startswith("```"):
clean = re.sub(r'^```(?:json)?\s*', '', clean, flags=re.MULTILINE)
clean = re.sub(r'\s*```\s*$', '', clean, flags=re.MULTILINE).strip()
# 2. Slice to array bounds if possible
start = clean.find('[')
if start == -1: return []
# Try to find the last ']' - but if it's truncated, we might need to repair it
end = clean.rfind(']')
candidate = clean[start:]
if end != -1:
candidate = clean[start:end + 1]
# 3. Progressive Repair Strategy
try:
return json.loads(candidate)
except json.JSONDecodeError:
# AI truncated mid-object? Let's try to fix it.
# Strategy: Remove everything after the last valid "}," and add "]"
last_comma = candidate.rfind('},')
if last_comma != -1:
try:
return json.loads(candidate[:last_comma + 1] + "]")
except: pass
# Try finding the last "}" and closing the array
last_brace = candidate.rfind('}')
if last_brace != -1:
try:
return json.loads(candidate[:last_brace + 1] + "]")
except: pass
return []
async def generate_mcq_session(channel_key: str) -> dict:
"""Generate 10 MCQ Telegram quiz polls for a single chapter."""
subject, chapter = _pick(channel_key, "mcq_session")
exam = _exam(channel_key)
template = template_manager.get_template("mcq_session")
diff_text = _difficulty_context(channel_key)
prompt = template.format(exam=exam, chapter=chapter, subject=subject.title()) + f"\n\n{diff_text}"
raw = await _call_llm(prompt)
if not raw:
return {"error": "⚠️ MCQ Session content temporarily unavailable."}
questions = _parse_mcq_json(raw)
MIN_MCQ = 3 # Accept sessions with at least 3 valid questions
if not questions or len(questions) < MIN_MCQ:
logger.warning(f"MCQ session got only {len(questions)} questions (need {MIN_MCQ}) β€” retrying once")
# --- One automatic retry before giving up ---
raw2 = await _call_llm(prompt)
if raw2:
questions = _parse_mcq_json(raw2)
if not questions or len(questions) < MIN_MCQ:
logger.error(f"MCQ session still only {len(questions)} questions after retry β€” giving up")
return {"error": "⚠️ Could not generate enough MCQs right now. Please retry."}
# Clamp to exactly 10
questions = questions[:10]
# Sanitise each question for Telegram limits
clean = []
import html
for q in questions:
raw_opts = q.get("options", [])
if not isinstance(raw_opts, list): continue
# Convert to Markdown V2 and remove formatting symbols for clean display
opts = [html.unescape(re.sub(r'[*_~`<>]', '', str(o)))[:100] for o in raw_opts]
# Deduplicate
unique_opts = []
for o in opts:
while o in unique_opts:
o += " "
unique_opts.append(o)
if len(unique_opts) < 2:
continue
question_text = html.unescape(re.sub(r'[*_~`<>]', '', str(q.get("question", ""))))[:300]
explanation = html.unescape(re.sub(r'[*_~`<>]', '', str(q.get("explanation", ""))))[:197]
clean.append({
"question": question_text,
"options": unique_opts[:4],
"correct_index": int(q.get("correct_index", 0)) % len(unique_opts[:4]),
"explanation": explanation,
})
return {
"type": "mcq_session",
"subject": subject,
"chapter": chapter,
"exam": exam,
"questions": clean,
}
# ─────────────────────────────────────────────
# DISPATCHER
# ─────────────────────────────────────────────
CONTENT_GENERATORS = {
"pyq_question": generate_pyq_question,
"formula_sheet": generate_formula_sheet,
"short_notes": generate_short_notes,
"mnemonic": generate_mnemonic,
"concept_recap": generate_concept_recap,
"mock_question": generate_mock_question,
"motivational": generate_motivational,
"mcq_session": generate_mcq_session,
}
CONTENT_LABELS = {
"pyq_question": "πŸ“… Daily PYQ Question",
"formula_sheet": "πŸ“ Formula Sheet",
"short_notes": "πŸ“ Short Notes",
"mnemonic": "🧠 Memory Tricks",
"concept_recap": "πŸŒ… Concept Recap",
"mock_question": "🎯 Daily Mock",
"motivational": "πŸŒ™ Night Motivation",
"mcq_session": "πŸ§ͺ MCQ Poll Session",
}
async def generate_generic_ai_post(content_type: str, channel_key: str) -> dict:
"""Fallback generator for user-defined custom content types."""
prompt_template = template_manager.data["templates"].get(content_type)
if not prompt_template:
return {"text": f"❌ No prompt template found for custom type: `{content_type}`"}
subject, chapter = _pick(channel_key, content_type)
exam = _exam(channel_key)
year = datetime.now().year
try:
full_prompt = prompt_template.format(exam=exam, subject=subject, chapter=chapter, year=year)
except KeyError as e:
# Fallback if user uses a placeholder we don't have
full_prompt = prompt_template
logger.warning(f"Template for {content_type} has unknown placeholder {e}")
text = await _call_llm(full_prompt)
if not text:
return {"error": "Gemini failed to generate text."}
return {
"text": _clean_markdown(text) + _footer(channel_key, content_type)
}
async def generate_content(content_type: str, channel_key: str) -> str:
gen = CONTENT_GENERATORS.get(content_type)
if not gen:
# Try generic generator for custom types
return await generate_generic_ai_post(content_type, channel_key)
return await gen(channel_key)