H3y-sam commited on
Commit
20e0ed7
Β·
verified Β·
1 Parent(s): add04fc

Upload 54 files

Browse files
content/generator.py CHANGED
@@ -29,88 +29,46 @@ else:
29
  # Helpers
30
  # ─────────────────────────────────────────────
31
 
32
- def _escape_markdown_v2(text: str) -> str:
33
- """
34
- Escape special chars for MarkdownV2 in plain-text segments.
35
- Do NOT run this on text that already has intentional * _ ` formatting.
36
- """
37
  if not text:
38
  return ""
39
- # Only escape chars that break MarkdownV2 parsing
40
- # We deliberately skip * _ ` ~ since we want those for formatting
41
- special_chars = r'[]()>#+-=|{}.!'
42
- for char in special_chars:
43
- text = text.replace(char, f'\\{char}')
44
- return text
45
 
 
 
46
 
47
- def _sanitize_for_telegram(text: str) -> str:
48
- """
49
- Convert Gemini output into clean plain text with only safe
50
- Telegram MarkdownV2 formatting (*bold*, _italic_, `code`).
51
- """
52
- if not text:
53
- return ""
54
 
55
- import html
56
- text = html.unescape(text)
57
-
58
- # 1. Strip code fences wrapping the whole response
59
  text = re.sub(r'^```(?:json|python|markdown)?\s*\n?', '', text, flags=re.MULTILINE)
60
  text = re.sub(r'\n?```$', '', text, flags=re.MULTILINE).strip()
61
 
62
- # 2. Convert HTML bold/italic to MarkdownV2
63
- text = re.sub(r'<b>(.*?)</b>', r'*\1*', text, flags=re.IGNORECASE | re.DOTALL)
64
- text = re.sub(r'<strong>(.*?)</strong>', r'*\1*', text, flags=re.IGNORECASE | re.DOTALL)
65
- text = re.sub(r'<i>(.*?)</i>', r'_\1_', text, flags=re.IGNORECASE | re.DOTALL)
66
- text = re.sub(r'<em>(.*?)</em>', r'_\1_', text, flags=re.IGNORECASE | re.DOTALL)
67
- text = re.sub(r'<code>(.*?)</code>', r'`\1`', text, flags=re.IGNORECASE | re.DOTALL)
68
- text = re.sub(r'<[^>]+>', '', text) # Strip remaining HTML
69
 
70
- # 3. Convert markdown headers β†’ bold (## Heading β†’ *Heading*)
71
- text = re.sub(r'^#{1,3}\s+(.+)$', r'*\1*', text, flags=re.MULTILINE)
 
72
 
73
- # 4. REMOVE math delimiters but keep the formula text readable
74
- # $$ block math $$ β†’ just the formula text (no backticks)
75
- text = re.sub(r'\$\$(.+?)\$\$', lambda m: m.group(1).strip(), text, flags=re.DOTALL)
76
- # $ inline math $ β†’ just the formula text
77
- text = re.sub(r'(?<!\\)\$([^\$\n]+?)\$', lambda m: m.group(1).strip(), text)
78
 
79
- # 5. Normalize bullet points
80
- text = re.sub(r'^\s*[‒·◦○◉●β–ͺβ–Έ]\s*', 'β€’ ', text, flags=re.MULTILINE)
81
-
82
- return text
83
 
 
 
84
 
85
- def _clean_markdown(text: str) -> str:
86
- """
87
- Final pass: sanitize and escape for Telegram MarkdownV2.
88
- """
89
- if not text:
90
- return ""
91
 
92
- text = _sanitize_for_telegram(text)
93
-
94
- # Fix runaway asterisks/underscores
95
- text = re.sub(r'\*{3,}', '**', text)
96
- text = re.sub(r'_{3,}', '__', text)
97
-
98
- # Escape characters that break MarkdownV2 OUTSIDE of formatting tokens
99
- # We process line by line to preserve intentional bold/italic markers
100
- lines = text.split('\n')
101
- clean_lines = []
102
- for line in lines:
103
- # Escape . and ! and - and + that aren't part of formatting
104
- # but preserve * and _ which we use for bold/italic
105
- line = re.sub(r'(?<!\\)([>\#\+\=\|\{\}])', r'\\\1', line)
106
- # Escape standalone dots not in patterns like "..." or decimal numbers
107
- line = re.sub(r'(?<!\d)\.(?!\d)(?!\.)', r'\\.', line)
108
- clean_lines.append(line)
109
- text = '\n'.join(clean_lines)
110
-
111
- # Truncate
112
  if len(text) > 4000:
113
- text = text[:3997] + "\\.\\.\\."
114
 
115
  return text
116
 
 
29
  # Helpers
30
  # ─────────────────────────────────────────────
31
 
32
+ def _clean_markdown(text: str) -> str:
33
+ """Convert Gemini output to Telegram HTML format."""
 
 
 
34
  if not text:
35
  return ""
 
 
 
 
 
 
36
 
37
+ import html as html_lib
38
+ import re
39
 
40
+ # 1. Unescape any HTML entities first
41
+ text = html_lib.unescape(text)
 
 
 
 
 
42
 
43
+ # 2. Strip code fences wrapping whole response
 
 
 
44
  text = re.sub(r'^```(?:json|python|markdown)?\s*\n?', '', text, flags=re.MULTILINE)
45
  text = re.sub(r'\n?```$', '', text, flags=re.MULTILINE).strip()
46
 
47
+ # 3. Escape HTML special chars BEFORE adding our own tags
48
+ text = text.replace('&', '&amp;')
49
+ text = text.replace('<', '&lt;')
50
+ text = text.replace('>', '&gt;')
 
 
 
51
 
52
+ # 4. Convert **bold** or *bold* β†’ <b>bold</b>
53
+ text = re.sub(r'\*\*(.+?)\*\*', r'<b>\1</b>', text, flags=re.DOTALL)
54
+ text = re.sub(r'\*([^\*\n]+?)\*', r'<b>\1</b>', text)
55
 
56
+ # 5. Convert _italic_ β†’ <i>italic</i>
57
+ text = re.sub(r'_([^_\n]+?)_', r'<i>\1</i>', text)
 
 
 
58
 
59
+ # 6. Convert `code` β†’ <code>code</code>
60
+ text = re.sub(r'`([^`]+?)`', r'<code>\1</code>', text)
 
 
61
 
62
+ # 7. Convert ## Headers β†’ <b>Header</b>
63
+ text = re.sub(r'^#{1,3}\s+(.+)$', r'<b>\1</b>', text, flags=re.MULTILINE)
64
 
65
+ # 8. Remove $...$ math delimiters, keep formula text plain
66
+ text = re.sub(r'\$\$(.+?)\$\$', lambda m: m.group(1).strip(), text, flags=re.DOTALL)
67
+ text = re.sub(r'\$([^\$\n]+?)\$', lambda m: m.group(1).strip(), text)
 
 
 
68
 
69
+ # 9. Truncate
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70
  if len(text) > 4000:
71
+ text = text[:3997] + "..."
72
 
73
  return text
74
 
content/template_manager.py CHANGED
@@ -9,23 +9,15 @@ PROMPTS_FILE = "data/prompts.json"
9
 
10
  DEFAULT_SYSTEM_PROMPT = """You are an expert JEE/NEET educator creating Telegram channel posts.
11
 
12
- STRICT FORMATTING RULES β€” follow exactly:
13
- 1. Use *text* for bold (wrap section headers like *🧠 Core Concept:*)
14
- 2. Use _text_ for italic (use sparingly)
15
- 3. Use plain text for formulas β€” NO LaTeX, NO $...$ math notation, NO backticks around formulas
16
- βœ… Write: Kp = Kc Γ— (RT)^Ξ”n
17
- ❌ Never: `Kp = Kc * (R * T)^(delta n_g)` or $Kp = Kc(RT)^{\Delta n}$
18
- 4. Use β€’ for bullet points (actual bullet character)
19
- 5. Do NOT use: ##headers, HTML tags, code blocks (```), or markdown tables
20
- 6. Keep each message under 3800 characters
21
- 7. Use Unicode symbols for math: Γ— Γ· Ξ” Ξ± Ξ² Ξ³ Ο€ √ β‰ˆ β‰  ≀ β‰₯ βˆ‘ ∫ Β°
22
-
23
- OUTPUT FORMAT for short notes / formula sheets:
24
- *[Emoji] Topic Title*
25
-
26
- *[Emoji] Section Name:*
27
- β€’ Point one
28
- β€’ Point two with formula: Kp = Kc Γ— (RT)^Ξ”n
29
  """
30
 
31
  DEFAULT_TEMPLATES = {
 
9
 
10
  DEFAULT_SYSTEM_PROMPT = """You are an expert JEE/NEET educator creating Telegram channel posts.
11
 
12
+ STRICT FORMATTING RULES:
13
+ 1. Use <b>text</b> for bold headers and section titles
14
+ 2. Use <i>text</i> for italics (sparingly)
15
+ 3. Write formulas in plain text using Unicode: Γ— Γ· Ξ” Ξ± Ξ² Ο€ √ β‰ˆ β‰  ≀ β‰₯
16
+ Example: Kp = Kc Γ— (RT)^Ξ”n ← correct
17
+ Never use: $Kp = Kc(RT)^{\\Delta n}$ or backticks for formulas
18
+ 4. Use β€’ for bullet points
19
+ 5. Do NOT use: ##headers, LaTeX, markdown tables, code blocks
20
+ 6. Keep output under 3800 characters
 
 
 
 
 
 
 
 
21
  """
22
 
23
  DEFAULT_TEMPLATES = {
data/prompts.json CHANGED
@@ -1,5 +1,5 @@
1
  {
2
- "system_prompt": "You are an expert JEE/NEET educator creating Telegram channel posts.\n\nSTRICT FORMATTING RULES β€” follow exactly:\n1. Use *text* for bold (wrap section headers like *🧠 Core Concept:*)\n2. Use _text_ for italic (use sparingly)\n3. Use plain text for formulas β€” NO LaTeX, NO $...$ math notation, NO backticks around formulas\n βœ… Write: Kp = Kc Γ— (RT)^Ξ”n\n ❌ Never: `Kp = Kc * (R * T)^(delta n_g)` or $Kp = Kc(RT)^{\\Delta n}$\n4. Use β€’ for bullet points (actual bullet character)\n5. Do NOT use: ##headers, HTML tags, code blocks (```), or markdown tables\n6. Keep each message under 3800 characters\n7. Use Unicode symbols for math: Γ— Γ· Ξ” Ξ± Ξ² Ξ³ Ο€ √ β‰ˆ β‰  ≀ β‰₯ βˆ‘ ∫ Β°\n\nOUTPUT FORMAT for short notes / formula sheets:\n*[Emoji] Topic Title*\n\n*[Emoji] Section Name:*\nβ€’ Point one\nβ€’ Point two with formula: Kp = Kc Γ— (RT)^Ξ”n\n",
3
  "templates": {
4
  "pyq_question": "Generate a realistic Previous Year Question (PYQ) style MCQ for {exam} {year} on the topic \"{chapter}\" from {subject}.\n \n Format EXACTLY like this:\n ━━━━━━━━━━━━━━━━━━━━━\n πŸ“… PYQ Style β€” {exam} {year}\n πŸ“– {subject} | {chapter}\n ━━━━━━━━━━━━━━━━━━━━━\n \n ❓ QUESTION:\n [Write the question concisely - MAX 250 characters]\n \n (A) [Plausible distractor 1]\n (B) [Plausible distractor 2]\n (C) [Plausible distractor 3]\n (D) [Correct answer]\n \n ||βœ… ANSWER: (X) β€” [Correct option text]||\n \n πŸ’‘ EXPLANATION:\n [Short 1-line reason - MAX 180 chars]\n 🎯 Difficulty: [Easy/Medium/Hard]\n πŸ“Œ Key Concept: [Main concept tested]",
5
  "formula_sheet": "Generate a concise Formula and Concept Cheat Sheet for {exam} on the chapter \"{chapter}\" ({subject}).\n\nFormat EXACTLY like this (use Telegram-safe formatting only):\n\nπŸ“ *Formula Sheet β€” {chapter}*\nπŸ“˜ {subject} | {exam}\n━━━━━━━━━━━━━━━━━━\n\n*πŸ”‘ Key Formulas:*\nβ€’ [Formula name]: `formula in plain text`\nβ€’ [Formula name]: `formula in plain text`\n(list 4-6 important formulas)\n\n*⚠️ Common Mistakes:*\nβ€’ [Mistake 1]\nβ€’ [Mistake 2]\n\n*πŸ’‘ Pro-Tip:*\n[One powerful exam trick for this chapter]",
 
1
  {
2
+ "system_prompt": "You are an expert JEE/NEET educator creating Telegram channel posts.\n\nSTRICT FORMATTING RULES:\n1. Use <b>text</b> for bold headers and section titles\n2. Use <i>text</i> for italics (sparingly)\n3. Write formulas in plain text using Unicode: Γ— Γ· Ξ” Ξ± Ξ² Ο€ √ β‰ˆ β‰  ≀ β‰₯\n Example: Kp = Kc Γ— (RT)^Ξ”n ← correct\n Never use: $Kp = Kc(RT)^{\\Delta n}$ or backticks for formulas\n4. Use β€’ for bullet points\n5. Do NOT use: ##headers, LaTeX, markdown tables, code blocks\n6. Keep output under 3800 characters\n",
3
  "templates": {
4
  "pyq_question": "Generate a realistic Previous Year Question (PYQ) style MCQ for {exam} {year} on the topic \"{chapter}\" from {subject}.\n \n Format EXACTLY like this:\n ━━━━━━━━━━━━━━━━━━━━━\n πŸ“… PYQ Style β€” {exam} {year}\n πŸ“– {subject} | {chapter}\n ━━━━━━━━━━━━━━━━━━━━━\n \n ❓ QUESTION:\n [Write the question concisely - MAX 250 characters]\n \n (A) [Plausible distractor 1]\n (B) [Plausible distractor 2]\n (C) [Plausible distractor 3]\n (D) [Correct answer]\n \n ||βœ… ANSWER: (X) β€” [Correct option text]||\n \n πŸ’‘ EXPLANATION:\n [Short 1-line reason - MAX 180 chars]\n 🎯 Difficulty: [Easy/Medium/Hard]\n πŸ“Œ Key Concept: [Main concept tested]",
5
  "formula_sheet": "Generate a concise Formula and Concept Cheat Sheet for {exam} on the chapter \"{chapter}\" ({subject}).\n\nFormat EXACTLY like this (use Telegram-safe formatting only):\n\nπŸ“ *Formula Sheet β€” {chapter}*\nπŸ“˜ {subject} | {exam}\n━━━━━━━━━━━━━━━━━━\n\n*πŸ”‘ Key Formulas:*\nβ€’ [Formula name]: `formula in plain text`\nβ€’ [Formula name]: `formula in plain text`\n(list 4-6 important formulas)\n\n*⚠️ Common Mistakes:*\nβ€’ [Mistake 1]\nβ€’ [Mistake 2]\n\n*πŸ’‘ Pro-Tip:*\n[One powerful exam trick for this chapter]",