Spaces:
Running
Running
Upload 50 files
Browse files- config.py +1 -2
- content/generator.py +67 -94
- requirements.txt +0 -1
config.py
CHANGED
|
@@ -8,8 +8,7 @@ load_dotenv()
|
|
| 8 |
# ─────────────────────────────────────────────
|
| 9 |
|
| 10 |
BOT_TOKEN = os.getenv("BOT_TOKEN", "YOUR_TELEGRAM_BOT_TOKEN") # From @BotFather
|
| 11 |
-
|
| 12 |
-
GEMINI_PROXY_URL = os.getenv("GEMINI_PROXY_URL", "").rstrip("/") # Optional Cloudflare worker proxy
|
| 13 |
GIST_ID = os.getenv("GIST_ID", "") # GitHub Gist ID
|
| 14 |
GIST_TOKEN = os.getenv("GIST_TOKEN", "") # GitHub Personal Access Token
|
| 15 |
|
|
|
|
| 8 |
# ─────────────────────────────────────────────
|
| 9 |
|
| 10 |
BOT_TOKEN = os.getenv("BOT_TOKEN", "YOUR_TELEGRAM_BOT_TOKEN") # From @BotFather
|
| 11 |
+
OPENROUTER_API_KEY = os.getenv("OPENROUTER_API_KEY", "") # From openrouter.ai
|
|
|
|
| 12 |
GIST_ID = os.getenv("GIST_ID", "") # GitHub Gist ID
|
| 13 |
GIST_TOKEN = os.getenv("GIST_TOKEN", "") # GitHub Personal Access Token
|
| 14 |
|
content/generator.py
CHANGED
|
@@ -5,12 +5,10 @@ import asyncio
|
|
| 5 |
import json
|
| 6 |
import re
|
| 7 |
from datetime import datetime
|
| 8 |
-
from google import genai
|
| 9 |
-
from google.genai import types
|
| 10 |
|
| 11 |
from config import (
|
| 12 |
-
|
| 13 |
-
GEMINI_TEMPERATURE, SUBJECT_ROTATION,
|
| 14 |
)
|
| 15 |
from content.config_manager import config_manager
|
| 16 |
from content.syllabus_manager import syllabus_manager
|
|
@@ -19,13 +17,9 @@ from content.history import pick_fresh_chapter, archive_weekly_post
|
|
| 19 |
|
| 20 |
logger = logging.getLogger(__name__)
|
| 21 |
|
| 22 |
-
# Initialize
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
client_kwargs["http_options"] = {"base_url": GEMINI_PROXY_URL}
|
| 26 |
-
logger.info(f"🛡️ Using Gemini proxy: {GEMINI_PROXY_URL}")
|
| 27 |
-
|
| 28 |
-
client = genai.Client(**client_kwargs)
|
| 29 |
|
| 30 |
|
| 31 |
# ─────────────────────────────────────────────
|
|
@@ -63,30 +57,15 @@ def _sanitize_for_telegram(text: str) -> str:
|
|
| 63 |
text = re.sub(r'_([^_]+?)_', r'<i>\1</i>', text)
|
| 64 |
|
| 65 |
# 7. Strip LaTeX math: $...$ and $$...$$ → <code>content</code>
|
| 66 |
-
text = re.sub(r'\$\$(.+?)\$\$', r'<code>\1</code>', text
|
| 67 |
-
text = re.sub(r'\$(
|
| 68 |
-
|
| 69 |
-
# 8. Remove horizontal rules (--- / *** / ___) — leave decorative ━ lines intact
|
| 70 |
-
text = re.sub(r'^[-*_]{3,}\s*$', '', text, flags=re.MULTILINE)
|
| 71 |
-
|
| 72 |
-
# 9. Convert markdown bullets (- item or * item at line start) → • item
|
| 73 |
-
text = re.sub(r'^[ \t]*[-*]\s+', '• ', text, flags=re.MULTILINE)
|
| 74 |
-
|
| 75 |
-
# 10. Links [text](url) -> <a href="url">text</a>
|
| 76 |
-
text = re.sub(r'\[([^\]]+)\]\(([^)]+)\)', r'<a href="\2">\1</a>', text)
|
| 77 |
-
|
| 78 |
-
# 11. Collapse 3+ consecutive blank lines to 2
|
| 79 |
-
text = re.sub(r'\n{3,}', '\n\n', text)
|
| 80 |
|
| 81 |
-
return text
|
| 82 |
|
| 83 |
|
| 84 |
def _clean_markdown(text: str) -> str:
|
| 85 |
"""
|
| 86 |
-
|
| 87 |
-
1. Sanitize non-Telegram markdown patterns
|
| 88 |
-
2. Fix unclosed HTML formatting markers
|
| 89 |
-
3. Enforce Telegram's 4096-character limit
|
| 90 |
"""
|
| 91 |
if not text:
|
| 92 |
return ""
|
|
@@ -111,69 +90,63 @@ def _today() -> str:
|
|
| 111 |
return datetime.now().strftime("%A")
|
| 112 |
|
| 113 |
|
| 114 |
-
async def
|
| 115 |
-
"""Wrapper for
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 119 |
last_error = None
|
| 120 |
for attempt in range(max_retries):
|
| 121 |
try:
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
)
|
| 130 |
-
|
|
|
|
|
|
|
| 131 |
|
| 132 |
-
|
|
|
|
| 133 |
if not content:
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
raise last_error
|
| 140 |
-
|
| 141 |
return _clean_markdown(content.strip())
|
| 142 |
-
|
| 143 |
except Exception as e:
|
| 144 |
last_error = e
|
| 145 |
-
|
|
|
|
|
|
|
| 146 |
|
| 147 |
-
|
| 148 |
-
if "limit: 0" in err_msg:
|
| 149 |
-
error_str = "🛑 GEMINI API QUOTA IS 0. The server is likely in a region without Free Tier (e.g., EU). Please enable billing on Google Cloud or use a paid API key."
|
| 150 |
-
logger.error(error_str)
|
| 151 |
-
raise Exception(error_str)
|
| 152 |
-
|
| 153 |
-
# Handle rate limits
|
| 154 |
-
if "429" in err_msg or "quota" in err_msg or "rate" in err_msg or "resource_exhausted" in err_msg:
|
| 155 |
-
wait_time = base_delay * (2 ** attempt) + 5
|
| 156 |
-
|
| 157 |
-
# Try to parse exact wait time from the error message
|
| 158 |
-
match = re.search(r"retry in (\d+(?:\.\d+)?)s", err_msg)
|
| 159 |
-
if match:
|
| 160 |
-
try:
|
| 161 |
-
parsed_wait = float(match.group(1))
|
| 162 |
-
wait_time = max(wait_time, parsed_wait + 2.0)
|
| 163 |
-
except ValueError:
|
| 164 |
-
pass
|
| 165 |
-
|
| 166 |
-
logger.warning(f"Gemini Rate Limit hit. Retrying in {wait_time:.1f}s... (Attempt {attempt+1}/{max_retries})")
|
| 167 |
-
if attempt < max_retries - 1:
|
| 168 |
-
import asyncio
|
| 169 |
-
await asyncio.sleep(wait_time)
|
| 170 |
-
continue
|
| 171 |
-
|
| 172 |
-
logger.error(f"Gemini API error: {e}\n{traceback.format_exc()}")
|
| 173 |
-
if attempt == max_retries - 1:
|
| 174 |
-
raise Exception(f"Gemini API Failed after {max_retries} attempts: {str(e)}")
|
| 175 |
-
|
| 176 |
-
raise last_error
|
| 177 |
|
| 178 |
|
| 179 |
def _channel_subjects(channel_key: str) -> list:
|
|
@@ -320,7 +293,7 @@ async def generate_pyq_question(channel_key: str) -> dict:
|
|
| 320 |
subject=subject.title()
|
| 321 |
) + f"\n\n{diff_text}"
|
| 322 |
|
| 323 |
-
raw_text = await
|
| 324 |
if not raw_text:
|
| 325 |
return {"error": "⚠️ Content temporarily unavailable."}
|
| 326 |
|
|
@@ -348,7 +321,7 @@ async def generate_formula_sheet(channel_key: str) -> str:
|
|
| 348 |
template = template_manager.get_template("formula_sheet")
|
| 349 |
prompt = template.format(exam=exam, chapter=chapter, subject=subject.title())
|
| 350 |
|
| 351 |
-
text = await
|
| 352 |
text = (text or "⚠️ Content temporarily unavailable.")
|
| 353 |
|
| 354 |
# Archive for Weekly PDF
|
|
@@ -369,7 +342,7 @@ async def generate_short_notes(channel_key: str) -> str:
|
|
| 369 |
template = template_manager.get_template("short_notes")
|
| 370 |
prompt = template.format(exam=exam, chapter=chapter, subject=subject.title())
|
| 371 |
|
| 372 |
-
text = await
|
| 373 |
text = (text or "⚠️ Content temporarily unavailable.")
|
| 374 |
|
| 375 |
# Archive for Weekly PDF
|
|
@@ -389,7 +362,7 @@ async def generate_mnemonic(channel_key: str) -> str:
|
|
| 389 |
template = template_manager.get_template("mnemonic")
|
| 390 |
prompt = template.format(chapter=chapter, subject=subject.title())
|
| 391 |
|
| 392 |
-
text = await
|
| 393 |
return (text or "⚠️ Content temporarily unavailable.") + _footer(channel_key, "mnemonic")
|
| 394 |
|
| 395 |
|
|
@@ -404,7 +377,7 @@ async def generate_concept_recap(channel_key: str) -> str:
|
|
| 404 |
template = template_manager.get_template("concept_recap")
|
| 405 |
prompt = template.format(exam=exam, chapter=chapter, subject=subject.title())
|
| 406 |
|
| 407 |
-
text = await
|
| 408 |
return (text or "⚠️ Content temporarily unavailable.") + _footer(channel_key, "recap")
|
| 409 |
|
| 410 |
|
|
@@ -420,7 +393,7 @@ async def generate_mock_question(channel_key: str) -> str:
|
|
| 420 |
diff_text = _difficulty_context(channel_key)
|
| 421 |
prompt = template.format(exam=exam, chapter=chapter, subject=subject.title()) + f"\n\n{diff_text}"
|
| 422 |
|
| 423 |
-
text = await
|
| 424 |
return (text or "⚠️ Content temporarily unavailable.") + _footer(channel_key, "mock")
|
| 425 |
|
| 426 |
|
|
@@ -439,7 +412,7 @@ async def generate_motivational(channel_key: str) -> str:
|
|
| 439 |
template = template_manager.get_template("motivational")
|
| 440 |
prompt = template.format(exam=exam, subject=subject.title(), chapter=chapter)
|
| 441 |
|
| 442 |
-
text = await
|
| 443 |
cfg = config_manager.channels.get(channel_key, {})
|
| 444 |
footer = cfg.get("footer", "")
|
| 445 |
return (text or "🌙 Rest well! See you tomorrow 💪") + (f"\n\n{footer}" if footer else "")
|
|
@@ -501,7 +474,7 @@ async def generate_mcq_session(channel_key: str) -> dict:
|
|
| 501 |
diff_text = _difficulty_context(channel_key)
|
| 502 |
prompt = template.format(exam=exam, chapter=chapter, subject=subject.title()) + f"\n\n{diff_text}"
|
| 503 |
|
| 504 |
-
raw = await
|
| 505 |
if not raw:
|
| 506 |
return {"error": "⚠️ MCQ Session content temporarily unavailable."}
|
| 507 |
|
|
@@ -510,7 +483,7 @@ async def generate_mcq_session(channel_key: str) -> dict:
|
|
| 510 |
if not questions or len(questions) < MIN_MCQ:
|
| 511 |
logger.warning(f"MCQ session got only {len(questions)} questions (need {MIN_MCQ}) — retrying once")
|
| 512 |
# --- One automatic retry before giving up ---
|
| 513 |
-
raw2 = await
|
| 514 |
if raw2:
|
| 515 |
questions = _parse_mcq_json(raw2)
|
| 516 |
if not questions or len(questions) < MIN_MCQ:
|
|
@@ -602,7 +575,7 @@ async def generate_generic_ai_post(content_type: str, channel_key: str) -> dict:
|
|
| 602 |
full_prompt = prompt_template
|
| 603 |
logger.warning(f"Template for {content_type} has unknown placeholder {e}")
|
| 604 |
|
| 605 |
-
text = await
|
| 606 |
if not text:
|
| 607 |
return {"error": "Gemini failed to generate text."}
|
| 608 |
|
|
|
|
| 5 |
import json
|
| 6 |
import re
|
| 7 |
from datetime import datetime
|
|
|
|
|
|
|
| 8 |
|
| 9 |
from config import (
|
| 10 |
+
GEMINI_MODEL, GEMINI_MAX_TOKENS,
|
| 11 |
+
GEMINI_TEMPERATURE, SUBJECT_ROTATION, OPENROUTER_API_KEY
|
| 12 |
)
|
| 13 |
from content.config_manager import config_manager
|
| 14 |
from content.syllabus_manager import syllabus_manager
|
|
|
|
| 17 |
|
| 18 |
logger = logging.getLogger(__name__)
|
| 19 |
|
| 20 |
+
# Initialize OpenRouter Client check
|
| 21 |
+
if not OPENROUTER_API_KEY:
|
| 22 |
+
logger.warning("OPENROUTER_API_KEY is missing! Bot will not be able to generate content.")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
|
| 24 |
|
| 25 |
# ─────────────────────────────────────────────
|
|
|
|
| 57 |
text = re.sub(r'_([^_]+?)_', r'<i>\1</i>', text)
|
| 58 |
|
| 59 |
# 7. Strip LaTeX math: $...$ and $$...$$ → <code>content</code>
|
| 60 |
+
text = re.sub(r'\$\$(.+?)\$\$', r'<code>\1</code>', text)
|
| 61 |
+
text = re.sub(r'\$([^\$]+?)\$', r'<code>\1</code>', text)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 62 |
|
| 63 |
+
return text
|
| 64 |
|
| 65 |
|
| 66 |
def _clean_markdown(text: str) -> str:
|
| 67 |
"""
|
| 68 |
+
Post-processing to fix HTML tags before sending to Telegram.
|
|
|
|
|
|
|
|
|
|
| 69 |
"""
|
| 70 |
if not text:
|
| 71 |
return ""
|
|
|
|
| 90 |
return datetime.now().strftime("%A")
|
| 91 |
|
| 92 |
|
| 93 |
+
async def _call_llm(prompt: str) -> str:
|
| 94 |
+
"""Wrapper for OpenRouter API using httpx."""
|
| 95 |
+
import httpx
|
| 96 |
+
max_retries = 3
|
| 97 |
+
|
| 98 |
+
if not OPENROUTER_API_KEY:
|
| 99 |
+
raise Exception("OPENROUTER_API_KEY is missing from config/env.")
|
| 100 |
+
|
| 101 |
+
url = "https://openrouter.ai/api/v1/chat/completions"
|
| 102 |
+
headers = {
|
| 103 |
+
"Authorization": f"Bearer {OPENROUTER_API_KEY}",
|
| 104 |
+
"HTTP-Referer": "https://t.me/xcrazylearners",
|
| 105 |
+
"X-Title": "JEE NEET Bot",
|
| 106 |
+
"Content-Type": "application/json"
|
| 107 |
+
}
|
| 108 |
+
|
| 109 |
+
payload = {
|
| 110 |
+
"model": "google/gemini-2.0-flash-lite-preview-02-05:free",
|
| 111 |
+
"messages": [
|
| 112 |
+
{"role": "system", "content": template_manager.system_prompt},
|
| 113 |
+
{"role": "user", "content": prompt}
|
| 114 |
+
],
|
| 115 |
+
"temperature": GEMINI_TEMPERATURE
|
| 116 |
+
}
|
| 117 |
+
|
| 118 |
last_error = None
|
| 119 |
for attempt in range(max_retries):
|
| 120 |
try:
|
| 121 |
+
async with httpx.AsyncClient(timeout=60.0) as client_http:
|
| 122 |
+
resp = await client_http.post(url, headers=headers, json=payload)
|
| 123 |
+
|
| 124 |
+
if resp.status_code == 429:
|
| 125 |
+
wait_time = 10 * (attempt + 1)
|
| 126 |
+
logger.warning(f"OpenRouter Rate Limit hit. Retrying in {wait_time}s... (Attempt {attempt+1}/{max_retries})")
|
| 127 |
+
import asyncio
|
| 128 |
+
await asyncio.sleep(wait_time)
|
| 129 |
+
continue
|
| 130 |
+
|
| 131 |
+
resp.raise_for_status()
|
| 132 |
|
| 133 |
+
data = resp.json()
|
| 134 |
+
content = data["choices"][0]["message"]["content"]
|
| 135 |
if not content:
|
| 136 |
+
last_error = Exception("OpenRouter returned empty response")
|
| 137 |
+
import asyncio
|
| 138 |
+
await asyncio.sleep(2)
|
| 139 |
+
continue
|
| 140 |
+
|
|
|
|
|
|
|
| 141 |
return _clean_markdown(content.strip())
|
| 142 |
+
|
| 143 |
except Exception as e:
|
| 144 |
last_error = e
|
| 145 |
+
logger.error(f"OpenRouter API error on attempt {attempt+1}: {e}")
|
| 146 |
+
import asyncio
|
| 147 |
+
await asyncio.sleep(2)
|
| 148 |
|
| 149 |
+
raise Exception(f"OpenRouter API Failed after {max_retries} attempts: {last_error}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 150 |
|
| 151 |
|
| 152 |
def _channel_subjects(channel_key: str) -> list:
|
|
|
|
| 293 |
subject=subject.title()
|
| 294 |
) + f"\n\n{diff_text}"
|
| 295 |
|
| 296 |
+
raw_text = await _call_llm(prompt)
|
| 297 |
if not raw_text:
|
| 298 |
return {"error": "⚠️ Content temporarily unavailable."}
|
| 299 |
|
|
|
|
| 321 |
template = template_manager.get_template("formula_sheet")
|
| 322 |
prompt = template.format(exam=exam, chapter=chapter, subject=subject.title())
|
| 323 |
|
| 324 |
+
text = await _call_llm(prompt)
|
| 325 |
text = (text or "⚠️ Content temporarily unavailable.")
|
| 326 |
|
| 327 |
# Archive for Weekly PDF
|
|
|
|
| 342 |
template = template_manager.get_template("short_notes")
|
| 343 |
prompt = template.format(exam=exam, chapter=chapter, subject=subject.title())
|
| 344 |
|
| 345 |
+
text = await _call_llm(prompt)
|
| 346 |
text = (text or "⚠️ Content temporarily unavailable.")
|
| 347 |
|
| 348 |
# Archive for Weekly PDF
|
|
|
|
| 362 |
template = template_manager.get_template("mnemonic")
|
| 363 |
prompt = template.format(chapter=chapter, subject=subject.title())
|
| 364 |
|
| 365 |
+
text = await _call_llm(prompt)
|
| 366 |
return (text or "⚠️ Content temporarily unavailable.") + _footer(channel_key, "mnemonic")
|
| 367 |
|
| 368 |
|
|
|
|
| 377 |
template = template_manager.get_template("concept_recap")
|
| 378 |
prompt = template.format(exam=exam, chapter=chapter, subject=subject.title())
|
| 379 |
|
| 380 |
+
text = await _call_llm(prompt)
|
| 381 |
return (text or "⚠️ Content temporarily unavailable.") + _footer(channel_key, "recap")
|
| 382 |
|
| 383 |
|
|
|
|
| 393 |
diff_text = _difficulty_context(channel_key)
|
| 394 |
prompt = template.format(exam=exam, chapter=chapter, subject=subject.title()) + f"\n\n{diff_text}"
|
| 395 |
|
| 396 |
+
text = await _call_llm(prompt)
|
| 397 |
return (text or "⚠️ Content temporarily unavailable.") + _footer(channel_key, "mock")
|
| 398 |
|
| 399 |
|
|
|
|
| 412 |
template = template_manager.get_template("motivational")
|
| 413 |
prompt = template.format(exam=exam, subject=subject.title(), chapter=chapter)
|
| 414 |
|
| 415 |
+
text = await _call_llm(prompt)
|
| 416 |
cfg = config_manager.channels.get(channel_key, {})
|
| 417 |
footer = cfg.get("footer", "")
|
| 418 |
return (text or "🌙 Rest well! See you tomorrow 💪") + (f"\n\n{footer}" if footer else "")
|
|
|
|
| 474 |
diff_text = _difficulty_context(channel_key)
|
| 475 |
prompt = template.format(exam=exam, chapter=chapter, subject=subject.title()) + f"\n\n{diff_text}"
|
| 476 |
|
| 477 |
+
raw = await _call_llm(prompt)
|
| 478 |
if not raw:
|
| 479 |
return {"error": "⚠️ MCQ Session content temporarily unavailable."}
|
| 480 |
|
|
|
|
| 483 |
if not questions or len(questions) < MIN_MCQ:
|
| 484 |
logger.warning(f"MCQ session got only {len(questions)} questions (need {MIN_MCQ}) — retrying once")
|
| 485 |
# --- One automatic retry before giving up ---
|
| 486 |
+
raw2 = await _call_llm(prompt)
|
| 487 |
if raw2:
|
| 488 |
questions = _parse_mcq_json(raw2)
|
| 489 |
if not questions or len(questions) < MIN_MCQ:
|
|
|
|
| 575 |
full_prompt = prompt_template
|
| 576 |
logger.warning(f"Template for {content_type} has unknown placeholder {e}")
|
| 577 |
|
| 578 |
+
text = await _call_llm(full_prompt)
|
| 579 |
if not text:
|
| 580 |
return {"error": "Gemini failed to generate text."}
|
| 581 |
|
requirements.txt
CHANGED
|
@@ -2,6 +2,5 @@ python-telegram-bot>=20.0
|
|
| 2 |
apscheduler>=3.10.0
|
| 3 |
pytz
|
| 4 |
python-dotenv
|
| 5 |
-
google-genai
|
| 6 |
requests
|
| 7 |
fpdf2>=2.7.0
|
|
|
|
| 2 |
apscheduler>=3.10.0
|
| 3 |
pytz
|
| 4 |
python-dotenv
|
|
|
|
| 5 |
requests
|
| 6 |
fpdf2>=2.7.0
|