H3y-sam commited on
Commit
fa22010
Β·
verified Β·
1 Parent(s): 2b35352

Upload 49 files

Browse files
Files changed (11) hide show
  1. Dockerfile +24 -24
  2. README.md +292 -292
  3. bot.py +3 -3
  4. config.py +5 -5
  5. content/doubt_solver.py +123 -119
  6. content/generator.py +521 -516
  7. handlers/commands.py +12 -12
  8. refactor.py +69 -0
  9. requirements.txt +1 -1
  10. verify_gemini.py +30 -0
  11. web_app/dashboard.html +1 -1
Dockerfile CHANGED
@@ -1,24 +1,24 @@
1
- # Use an official Python runtime as a parent image
2
- FROM python:3.11-slim
3
-
4
- # Set the working directory in the container
5
- WORKDIR /app
6
-
7
- # Copy the current directory contents into the container at /app
8
- COPY . /app
9
-
10
- # Install any needed packages specified in requirements.txt
11
- RUN pip install --no-cache-dir -r requirements.txt
12
-
13
- # Create the data directory
14
- RUN mkdir -p data
15
-
16
- # Define environment variables (These will be overwritten by Hugging Face Secrets)
17
- ENV BOT_TOKEN=""
18
- ENV GROQ_API_KEY=""
19
- ENV ADMIN_USER_IDS=""
20
- ENV GIST_ID=""
21
- ENV GIST_TOKEN=""
22
-
23
- # Run bot.py when the container launches
24
- CMD ["python", "bot.py"]
 
1
+ # Use an official Python runtime as a parent image
2
+ FROM python:3.11-slim
3
+
4
+ # Set the working directory in the container
5
+ WORKDIR /app
6
+
7
+ # Copy the current directory contents into the container at /app
8
+ COPY . /app
9
+
10
+ # Install any needed packages specified in requirements.txt
11
+ RUN pip install --no-cache-dir -r requirements.txt
12
+
13
+ # Create the data directory
14
+ RUN mkdir -p data
15
+
16
+ # Define environment variables (These will be overwritten by Hugging Face Secrets)
17
+ ENV BOT_TOKEN=""
18
+ ENV GEMINI_API_KEY=""
19
+ ENV ADMIN_USER_IDS=""
20
+ ENV GIST_ID=""
21
+ ENV GIST_TOKEN=""
22
+
23
+ # Run bot.py when the container launches
24
+ CMD ["python", "bot.py"]
README.md CHANGED
@@ -1,292 +1,292 @@
1
- ---
2
- title: Telegram Bot
3
- emoji: πŸ€–
4
- colorFrom: indigo
5
- colorTo: blue
6
- sdk: docker
7
- app_port: 7860
8
- ---
9
-
10
- # πŸŽ“ JEE & NEET Daily Study Bot β€” CrazyLearners Edition
11
-
12
- > **Fully automated, multi-channel Telegram content bot** powered by **Groq AI (Llama 3.3 70B)**.
13
- > Posts 7 unique study posts/day across multiple channels β€” with repeat prevention, interactive MCQ poll sessions, weekly branded PDF digests, and a web dashboard.
14
-
15
- πŸ”— **Join us:** [t.me/xcrazylearners](https://t.me/xcrazylearners)
16
-
17
- ---
18
-
19
- ## ✨ Feature Overview
20
-
21
- | Feature | Details |
22
- |---------|---------|
23
- | πŸ€– **Groq AI (Llama 3.3 70B)** | Fast, free-tier-friendly AI with zero content filtering for academic topics |
24
- | πŸ“‘ **Multi-channel** | Unlimited channels β€” JEE Main, NEET, JEE Advanced, or custom combos |
25
- | πŸ—“οΈ **7 posts/day** | PYQ, Formula Sheet, Short Notes, Mnemonic, Concept Recap, Mock Question, Motivation |
26
- | πŸ§ͺ **MCQ Poll Sessions** | 10 interactive quiz polls per session with configurable delays |
27
- | πŸ“„ **Weekly PDF Digest** | Branded CrazyLearners PDF every Sunday β€” Short Notes + Formula Sheets compiled |
28
- | 🚫 **Repeat Prevention** | Remembers last 60 topics per channel; always picks a fresh chapter |
29
- | πŸ“Š **Coverage Stats** | See what % of syllabus each channel has covered |
30
- | ⏸️ **Per-channel Control** | Pause/resume individual channels or specific content types |
31
- | 🌐 **Web Dashboard** | Full visual admin UI hosted on Hugging Face Spaces |
32
- | πŸ’¬ **Doubt Solver** | Students can DM the bot or @mention it in groups to get AI answers |
33
- | πŸ“’ **Broadcast** | Admin can push messages to all registered users with rate limiting |
34
- | πŸ”„ **Remote Sync** | History synced to a GitHub Gist for persistence across restarts |
35
-
36
- ---
37
-
38
- ## πŸ“¦ Daily Schedule (per channel, IST)
39
-
40
- | Time | Content Type | Description |
41
- |------|-------------|-------------|
42
- | 7:00 AM | πŸ“… PYQ Question | Previous year MCQ with spoiler answer + explanation |
43
- | 9:00 AM | πŸ“ Formula Sheet | 8–12 key formulas with shortcuts and derivation hints |
44
- | 12:00 PM | πŸ“ Short Notes | 3-minute rapid revision notes |
45
- | 3:00 PM | 🧠 Mnemonic | Memory tricks and visualizations |
46
- | 6:00 PM | πŸŒ… Concept Recap | Evening summary + exam weightage tips |
47
- | 8:00 PM | 🎯 Mock Question | 3 practice MCQs with step-by-step solutions |
48
- | 10:00 PM | πŸŒ™ Motivation | Night motivation + next day's plan |
49
- | 8:00 PM (MCQ channels) | πŸ§ͺ MCQ Poll Session | 10 live quiz polls with configurable delay between each |
50
- | Every Sunday 9:00 PM | πŸ“„ Weekly PDF | Branded PDF of the week's Short Notes + Formula Sheets |
51
-
52
- Each channel gets **different content** tailored to its exam focus and subject rotation.
53
-
54
- ---
55
-
56
- ## βš™οΈ Setup Guide
57
-
58
- ### Step 1 β€” Create your Telegram Bot
59
- 1. Message **@BotFather** β†’ `/newbot`
60
- 2. Copy the **API token**
61
-
62
- ### Step 2 β€” Get Groq API Key
63
- 1. Go to [console.groq.com](https://console.groq.com)
64
- 2. Sign up β†’ **API Keys** β†’ **Create API Key**
65
- 3. Free tier is sufficient (model: `llama-3.3-70b-versatile`)
66
-
67
- ### Step 3 β€” Create Channels & Add Bot as Admin
68
- For each channel:
69
- 1. Create the channel in Telegram
70
- 2. **Channel Settings β†’ Administrators β†’ Add Admin**
71
- 3. Search your bot β†’ grant **Post Messages** permission
72
-
73
- ### Step 4 β€” Get Your Admin User ID
74
- Message **@userinfobot** β†’ copy your numeric ID
75
-
76
- ### Step 5 β€” Configure Environment Variables
77
-
78
- Create a `.env` file (or set in your hosting environment):
79
-
80
- ```env
81
- BOT_TOKEN=7123456789:AAF... # From @BotFather
82
- GROQ_API_KEY=gsk_... # From console.groq.com
83
- ADMIN_USER_IDS=987654321 # Comma-separated for multiple admins
84
- GIST_ID=abc123... # Optional: GitHub Gist ID for remote history sync
85
- GIST_TOKEN=ghp_... # Optional: GitHub Personal Access Token
86
- ```
87
-
88
- ### Step 6 β€” Configure Channels (first run)
89
-
90
- Edit the `DEFAULT_CHANNELS` block in `content/config_manager.py`, or use the **Web Dashboard** after startup:
91
-
92
- ```python
93
- "jee_main": {
94
- "id": "@YourJEEMainChannel",
95
- "label": "JEE Main Daily",
96
- "exam_focus": ["JEE Main"],
97
- "subjects": ["physics", "chemistry", "maths"],
98
- "active": True,
99
- "mcq_poll_enabled": False,
100
- "footer": "🎯 Crack JEE Main 2025!\nπŸ“’ Share with your batch!",
101
- "hashtags": { "pyq": "#JEEMain #PYQ", "formula": "#Formula", ... },
102
- },
103
- ```
104
-
105
- > πŸ’‘ After the first run, all config changes are saved to `data/bot_config.json` and can be edited via the Web Dashboard without touching code.
106
-
107
- ### Step 7 β€” Run
108
-
109
- ```bash
110
- pip install -r requirements.txt
111
- python bot.py
112
- ```
113
-
114
- ---
115
-
116
- ## πŸ› οΈ Admin Commands (DM your bot)
117
-
118
- | Command | What it does |
119
- |---------|-------------|
120
- | `/start` | Admin panel β€” active channels, job count, dashboard link |
121
- | `/help` | Full admin guide |
122
- | `/status` | All scheduled jobs grouped by channel with next run time |
123
- | `/channels` | List channels; tap to pause/resume any channel |
124
- | `/preview` | Interactive: pick channel οΏ½οΏ½οΏ½ pick content type β†’ see AI preview β†’ post now |
125
- | `/preview <channel_key> <type>` | Direct preview, e.g. `/preview jee_main formula_sheet` |
126
- | `/coverage` | Chapter coverage % per channel β€” see how much syllabus has been covered |
127
- | `/stats` | Rich analytics dashboard with progress bars per subject |
128
- | `/mcq_session <channel_key>` | Manually trigger a 10-poll MCQ session |
129
- | `/force_digest <channel_key>` | Immediately generate and send the weekly PDF |
130
- | `/broadcast <message>` | Push a message to all registered users |
131
- | `/set_time <type> <HH:MM>` | Change posting time, e.g. `/set_time short_notes 11:30` |
132
- | `/add_channel <key> <id> <label>` | Register a new channel |
133
- | `/del_channel <key>` | Remove a channel |
134
- | `/healthcheck` | Test all subsystems: Groq API, Scheduler, Gist, User DB, Error Log |
135
-
136
- ---
137
-
138
- ## πŸ§ͺ MCQ Poll Session
139
-
140
- Each session posts **10 quiz polls** to a channel with configurable delays:
141
-
142
- - **Automatic:** Runs daily at 8:00 PM IST for MCQ-enabled channels
143
- - **Manual:** `/mcq_session <channel_key>` or via the inline menu
144
- - **Delay:** Configurable per channel (`mcq_poll_delay_min` / `mcq_poll_delay_max` in seconds)
145
- - Each poll is a native Telegram Quiz Poll with the correct answer and explanation
146
-
147
- ```python
148
- # In config, per channel:
149
- "mcq_poll_enabled": True,
150
- "mcq_poll_delay_min": 60, # seconds between polls
151
- "mcq_poll_delay_max": 90,
152
- ```
153
-
154
- ---
155
-
156
- ## πŸ“„ Weekly PDF Digest (CrazyLearners Branding)
157
-
158
- Every **Sunday at 9:00 PM IST**, the bot:
159
- 1. Compiles all **Short Notes** and **Formula Sheets** posted that week
160
- 2. Generates a branded PDF with:
161
- - Cover page (CrazyLearners purple/teal design)
162
- - Auto-generated Table of Contents
163
- - Subject pill badges + Chapter cards
164
- - Justified body text with sub-heading detection
165
- - Page header/footer with brand name + `t.me/xcrazylearners`
166
- - Back page with CTA (join our community)
167
- 3. Sends the PDF to each active channel with a branded caption
168
-
169
- **Force a digest anytime:** `/force_digest <channel_key>`
170
-
171
- ---
172
-
173
- ## 🚫 Repeat Prevention
174
-
175
- The bot tracks the last **60 topics** per *(channel Γ— content type Γ— subject)* in `data/content_history.json`.
176
-
177
- - Excludes all recently used chapters when picking a new topic
178
- - If all chapters are used, picks from the **oldest half** (least recently used)
179
- - Each channel maintains **independent history**
180
-
181
- **Reset history:** `/coverage` β†’ tap "Reset a channel's history"
182
-
183
- **Remote sync:** If `GIST_ID` and `GIST_TOKEN` are configured, history is synced to a private GitHub Gist so it survives container restarts on Hugging Face Spaces.
184
-
185
- ---
186
-
187
- ## βž• Adding a New Channel
188
-
189
- 1. Create the Telegram channel
190
- 2. Add your bot as Admin with Post Messages permission
191
- 3. Use the bot command: `/add_channel <key> <@channel_id> <Label>`
192
- Example: `/add_channel neet_2 @NEET_MyChannel "NEET Daily 2"`
193
- 4. Or add via the **Web Dashboard β†’ Channel Manager**
194
-
195
- The new channel is automatically scheduled β€” no restart needed.
196
-
197
- ---
198
-
199
- ## 🌐 Web Dashboard
200
-
201
- The bot exposes a Flask/Gradio web dashboard for visual management:
202
-
203
- - **Add/Delete/Toggle Channels**
204
- - **Set posting schedules** (CRON-style)
205
- - **Manage syllabus** (add subjects, chapters)
206
- - **Trigger content** to any channel instantly
207
- - **Edit AI prompts** for each content type
208
-
209
- Dashboard URL: configured in `DEFAULT_SETTINGS["dashboard_url"]`
210
-
211
- ---
212
-
213
- ## πŸš€ Deployment
214
-
215
- ### Hugging Face Spaces (Current)
216
- The bot runs as a Docker Space. Set all env vars in **Settings β†’ Variables and secrets**.
217
-
218
- ### Railway / Render
219
- 1. Push this folder to a GitHub repo
220
- 2. Connect to Railway or Render
221
- 3. Set env vars: `BOT_TOKEN`, `GROQ_API_KEY`, `ADMIN_USER_IDS`
222
- 4. Deploy as a **Background Worker** (no open port needed)
223
-
224
- ### VPS / Self-hosted
225
- ```bash
226
- screen -S jeebot
227
- python bot.py
228
- # Ctrl+A D to detach
229
- ```
230
-
231
- ---
232
-
233
- ## πŸ“ Project Structure
234
-
235
- ```
236
- JEE, NEET & Advance Content Manager/
237
- β”œβ”€β”€ bot.py ← Entry point; starts polling + dashboard server
238
- β”œβ”€β”€ config.py ← Env vars + Groq settings (model, tokens, temp)
239
- β”œβ”€β”€ requirements.txt
240
- β”œβ”€β”€ data/
241
- β”‚ β”œβ”€β”€ bot_config.json ← Auto-saved dynamic config (channels, schedule)
242
- β”‚ β”œβ”€β”€ content_history.json ← Repeat-prevention tracker
243
- β”‚ β”œβ”€β”€ syllabus.json ← Full JEE/NEET syllabus (chapters per subject)
244
- β”‚ β”œβ”€β”€ prompts.json ← Custom AI prompt templates (editable via dashboard)
245
- β”‚ └── digests/ ← Generated weekly PDF files
246
- β”œβ”€β”€ content/
247
- β”‚ β”œβ”€β”€ generator.py ← Groq AI content generation + Markdown sanitizer
248
- β”‚ β”œβ”€β”€ history.py ← Chapter tracker + weekly archive for PDFs
249
- β”‚ β”œβ”€β”€ pdf_generator.py ← Branded CrazyLearners PDF builder (fpdf2)
250
- β”‚ β”œβ”€β”€ config_manager.py ← Dynamic channel/schedule config (JSON-backed)
251
- β”‚ β”œβ”€β”€ syllabus_manager.py ← Syllabus loader with recursive chapter extraction
252
- β”‚ β”œβ”€β”€ template_manager.py ← AI prompt template manager
253
- β”‚ β”œβ”€β”€ doubt_solver.py ← Groq-powered doubt answering for students
254
- β”‚ β”œβ”€β”€ remote_storage.py ← GitHub Gist sync for history persistence
255
- β”‚ └── user_registry.py ← Registered user DB (for broadcast)
256
- β”œβ”€β”€ scheduler/
257
- β”‚ └── job_scheduler.py ← APScheduler: 1 job per (content_type Γ— channel)
258
- β”‚ _safe_send_message with Markdown parse recovery
259
- └── handlers/
260
- β”œβ”€β”€ commands.py ← /start /status /channels /preview /mcq_session etc.
261
- β”œβ”€β”€ callbacks.py ← Inline button actions (pause, preview, post-now)
262
- β”œβ”€β”€ doubt_handler.py ← DM + group @mention doubt handler
263
- └── menu_router.py ← Routes reply-keyboard button taps
264
- ```
265
-
266
- ---
267
-
268
- ## πŸ”§ Key Configuration Constants (`config.py`)
269
-
270
- | Constant | Default | Purpose |
271
- |----------|---------|---------|
272
- | `GROQ_MODEL` | `llama-3.3-70b-versatile` | Groq model for all AI generation |
273
- | `GROQ_MAX_TOKENS` | `3500` | Max tokens per AI response (high enough for 10-MCQ JSON) |
274
- | `GROQ_TEMPERATURE` | `0.7` | Creativity vs consistency balance |
275
- | `HISTORY_DEPTH` | `60` | How many past topics to remember before reuse is allowed |
276
-
277
- ---
278
-
279
- ## πŸ› Known Issues Fixed (v2.0)
280
-
281
- | Bug | Fix |
282
- |-----|-----|
283
- | `Can't parse entities` β€” Telegram Markdown errors | `_clean_markdown()` now strips code blocks before counting `*`/`_` markers; `_safe_send_message()` auto-retries as plain text on parse failure |
284
- | `Message is too long` | Hard 4000-char truncation in `_clean_markdown()` + `_safe_send_message()` |
285
- | `Could not generate enough MCQs` | `GROQ_MAX_TOKENS` raised to 3500; `_parse_mcq_json()` uses `find('[')` + `rfind(']')` instead of greedy regex; auto-retries once before giving up |
286
- | MCQ callback blocking event loop 15 min | `asyncio.create_task()` instead of `await` in callback handler |
287
- | PDF file handle leak | Wrapped `send_document` in `with open(...) as f` |
288
- | `KeyError` on custom content type in `/set_time` | Changed `CONTENT_LABELS[ctype]` β†’ `.get(ctype, ctype)` |
289
- | Broadcast hitting Telegram 429 rate limit | `asyncio.sleep(0.05)` between each send |
290
- | `get_me()` API call on every group message | Cached in `context.bot_data` after first call |
291
- | Archive storing empty date | Uses `datetime.now()` instead of missing env var |
292
- | Preview command crashing on dict response | Handles quiz/text/error dict shapes correctly |
 
1
+ ---
2
+ title: Telegram Bot
3
+ emoji: πŸ€–
4
+ colorFrom: indigo
5
+ colorTo: blue
6
+ sdk: docker
7
+ app_port: 7860
8
+ ---
9
+
10
+ # πŸŽ“ JEE & NEET Daily Study Bot β€” CrazyLearners Edition
11
+
12
+ > **Fully automated, multi-channel Telegram content bot** powered by **Gemini AI (Gemini 2.0 Flash)**.
13
+ > Posts 7 unique study posts/day across multiple channels β€” with repeat prevention, interactive MCQ poll sessions, weekly branded PDF digests, and a web dashboard.
14
+
15
+ πŸ”— **Join us:** [t.me/xcrazylearners](https://t.me/xcrazylearners)
16
+
17
+ ---
18
+
19
+ ## ✨ Feature Overview
20
+
21
+ | Feature | Details |
22
+ |---------|---------|
23
+ | πŸ€– **Gemini AI (Gemini 2.0 Flash)** | Fast, free-tier-friendly AI with zero content filtering for academic topics |
24
+ | πŸ“‘ **Multi-channel** | Unlimited channels β€” JEE Main, NEET, JEE Advanced, or custom combos |
25
+ | πŸ—“οΈ **7 posts/day** | PYQ, Formula Sheet, Short Notes, Mnemonic, Concept Recap, Mock Question, Motivation |
26
+ | πŸ§ͺ **MCQ Poll Sessions** | 10 interactive quiz polls per session with configurable delays |
27
+ | πŸ“„ **Weekly PDF Digest** | Branded CrazyLearners PDF every Sunday β€” Short Notes + Formula Sheets compiled |
28
+ | 🚫 **Repeat Prevention** | Remembers last 60 topics per channel; always picks a fresh chapter |
29
+ | πŸ“Š **Coverage Stats** | See what % of syllabus each channel has covered |
30
+ | ⏸️ **Per-channel Control** | Pause/resume individual channels or specific content types |
31
+ | 🌐 **Web Dashboard** | Full visual admin UI hosted on Hugging Face Spaces |
32
+ | πŸ’¬ **Doubt Solver** | Students can DM the bot or @mention it in groups to get AI answers |
33
+ | πŸ“’ **Broadcast** | Admin can push messages to all registered users with rate limiting |
34
+ | πŸ”„ **Remote Sync** | History synced to a GitHub Gist for persistence across restarts |
35
+
36
+ ---
37
+
38
+ ## πŸ“¦ Daily Schedule (per channel, IST)
39
+
40
+ | Time | Content Type | Description |
41
+ |------|-------------|-------------|
42
+ | 7:00 AM | πŸ“… PYQ Question | Previous year MCQ with spoiler answer + explanation |
43
+ | 9:00 AM | πŸ“ Formula Sheet | 8–12 key formulas with shortcuts and derivation hints |
44
+ | 12:00 PM | πŸ“ Short Notes | 3-minute rapid revision notes |
45
+ | 3:00 PM | 🧠 Mnemonic | Memory tricks and visualizations |
46
+ | 6:00 PM | πŸŒ… Concept Recap | Evening summary + exam weightage tips |
47
+ | 8:00 PM | 🎯 Mock Question | 3 practice MCQs with step-by-step solutions |
48
+ | 10:00 PM | πŸŒ™ Motivation | Night motivation + next day's plan |
49
+ | 8:00 PM (MCQ channels) | πŸ§ͺ MCQ Poll Session | 10 live quiz polls with configurable delay between each |
50
+ | Every Sunday 9:00 PM | πŸ“„ Weekly PDF | Branded PDF of the week's Short Notes + Formula Sheets |
51
+
52
+ Each channel gets **different content** tailored to its exam focus and subject rotation.
53
+
54
+ ---
55
+
56
+ ## βš™οΈ Setup Guide
57
+
58
+ ### Step 1 β€” Create your Telegram Bot
59
+ 1. Message **@BotFather** β†’ `/newbot`
60
+ 2. Copy the **API token**
61
+
62
+ ### Step 2 β€” Get Gemini API Key
63
+ 1. Go to [aistudio.google.com/app/apikey](https://aistudio.google.com/app/apikey)
64
+ 2. Sign up β†’ **API Keys** β†’ **Create API Key**
65
+ 3. Free tier is sufficient (model: `gemini-2.0-flash`)
66
+
67
+ ### Step 3 β€” Create Channels & Add Bot as Admin
68
+ For each channel:
69
+ 1. Create the channel in Telegram
70
+ 2. **Channel Settings β†’ Administrators β†’ Add Admin**
71
+ 3. Search your bot β†’ grant **Post Messages** permission
72
+
73
+ ### Step 4 β€” Get Your Admin User ID
74
+ Message **@userinfobot** β†’ copy your numeric ID
75
+
76
+ ### Step 5 β€” Configure Environment Variables
77
+
78
+ Create a `.env` file (or set in your hosting environment):
79
+
80
+ ```env
81
+ BOT_TOKEN=7123456789:AAF... # From @BotFather
82
+ GEMINI_API_KEY=AIza... # From aistudio.google.com/app/apikey
83
+ ADMIN_USER_IDS=987654321 # Comma-separated for multiple admins
84
+ GIST_ID=abc123... # Optional: GitHub Gist ID for remote history sync
85
+ GIST_TOKEN=ghp_... # Optional: GitHub Personal Access Token
86
+ ```
87
+
88
+ ### Step 6 β€” Configure Channels (first run)
89
+
90
+ Edit the `DEFAULT_CHANNELS` block in `content/config_manager.py`, or use the **Web Dashboard** after startup:
91
+
92
+ ```python
93
+ "jee_main": {
94
+ "id": "@YourJEEMainChannel",
95
+ "label": "JEE Main Daily",
96
+ "exam_focus": ["JEE Main"],
97
+ "subjects": ["physics", "chemistry", "maths"],
98
+ "active": True,
99
+ "mcq_poll_enabled": False,
100
+ "footer": "🎯 Crack JEE Main 2025!\nπŸ“’ Share with your batch!",
101
+ "hashtags": { "pyq": "#JEEMain #PYQ", "formula": "#Formula", ... },
102
+ },
103
+ ```
104
+
105
+ > πŸ’‘ After the first run, all config changes are saved to `data/bot_config.json` and can be edited via the Web Dashboard without touching code.
106
+
107
+ ### Step 7 β€” Run
108
+
109
+ ```bash
110
+ pip install -r requirements.txt
111
+ python bot.py
112
+ ```
113
+
114
+ ---
115
+
116
+ ## πŸ› οΈ Admin Commands (DM your bot)
117
+
118
+ | Command | What it does |
119
+ |---------|-------------|
120
+ | `/start` | Admin panel β€” active channels, job count, dashboard link |
121
+ | `/help` | Full admin guide |
122
+ | `/status` | All scheduled jobs grouped by channel with next run time |
123
+ | `/channels` | List channels; tap to pause/resume any channel |
124
+ | `/preview` | Interactive: pick channel β†’ pick content type β†’ see AI preview β†’ post now |
125
+ | `/preview <channel_key> <type>` | Direct preview, e.g. `/preview jee_main formula_sheet` |
126
+ | `/coverage` | Chapter coverage % per channel β€” see how much syllabus has been covered |
127
+ | `/stats` | Rich analytics dashboard with progress bars per subject |
128
+ | `/mcq_session <channel_key>` | Manually trigger a 10-poll MCQ session |
129
+ | `/force_digest <channel_key>` | Immediately generate and send the weekly PDF |
130
+ | `/broadcast <message>` | Push a message to all registered users |
131
+ | `/set_time <type> <HH:MM>` | Change posting time, e.g. `/set_time short_notes 11:30` |
132
+ | `/add_channel <key> <id> <label>` | Register a new channel |
133
+ | `/del_channel <key>` | Remove a channel |
134
+ | `/healthcheck` | Test all subsystems: Gemini API, Scheduler, Gist, User DB, Error Log |
135
+
136
+ ---
137
+
138
+ ## πŸ§ͺ MCQ Poll Session
139
+
140
+ Each session posts **10 quiz polls** to a channel with configurable delays:
141
+
142
+ - **Automatic:** Runs daily at 8:00 PM IST for MCQ-enabled channels
143
+ - **Manual:** `/mcq_session <channel_key>` or via the inline menu
144
+ - **Delay:** Configurable per channel (`mcq_poll_delay_min` / `mcq_poll_delay_max` in seconds)
145
+ - Each poll is a native Telegram Quiz Poll with the correct answer and explanation
146
+
147
+ ```python
148
+ # In config, per channel:
149
+ "mcq_poll_enabled": True,
150
+ "mcq_poll_delay_min": 60, # seconds between polls
151
+ "mcq_poll_delay_max": 90,
152
+ ```
153
+
154
+ ---
155
+
156
+ ## πŸ“„ Weekly PDF Digest (CrazyLearners Branding)
157
+
158
+ Every **Sunday at 9:00 PM IST**, the bot:
159
+ 1. Compiles all **Short Notes** and **Formula Sheets** posted that week
160
+ 2. Generates a branded PDF with:
161
+ - Cover page (CrazyLearners purple/teal design)
162
+ - Auto-generated Table of Contents
163
+ - Subject pill badges + Chapter cards
164
+ - Justified body text with sub-heading detection
165
+ - Page header/footer with brand name + `t.me/xcrazylearners`
166
+ - Back page with CTA (join our community)
167
+ 3. Sends the PDF to each active channel with a branded caption
168
+
169
+ **Force a digest anytime:** `/force_digest <channel_key>`
170
+
171
+ ---
172
+
173
+ ## 🚫 Repeat Prevention
174
+
175
+ The bot tracks the last **60 topics** per *(channel Γ— content type Γ— subject)* in `data/content_history.json`.
176
+
177
+ - Excludes all recently used chapters when picking a new topic
178
+ - If all chapters are used, picks from the **oldest half** (least recently used)
179
+ - Each channel maintains **independent history**
180
+
181
+ **Reset history:** `/coverage` β†’ tap "Reset a channel's history"
182
+
183
+ **Remote sync:** If `GIST_ID` and `GIST_TOKEN` are configured, history is synced to a private GitHub Gist so it survives container restarts on Hugging Face Spaces.
184
+
185
+ ---
186
+
187
+ ## βž• Adding a New Channel
188
+
189
+ 1. Create the Telegram channel
190
+ 2. Add your bot as Admin with Post Messages permission
191
+ 3. Use the bot command: `/add_channel <key> <@channel_id> <Label>`
192
+ Example: `/add_channel neet_2 @NEET_MyChannel "NEET Daily 2"`
193
+ 4. Or add via the **Web Dashboard β†’ Channel Manager**
194
+
195
+ The new channel is automatically scheduled β€” no restart needed.
196
+
197
+ ---
198
+
199
+ ## 🌐 Web Dashboard
200
+
201
+ The bot exposes a Flask/Gradio web dashboard for visual management:
202
+
203
+ - **Add/Delete/Toggle Channels**
204
+ - **Set posting schedules** (CRON-style)
205
+ - **Manage syllabus** (add subjects, chapters)
206
+ - **Trigger content** to any channel instantly
207
+ - **Edit AI prompts** for each content type
208
+
209
+ Dashboard URL: configured in `DEFAULT_SETTINGS["dashboard_url"]`
210
+
211
+ ---
212
+
213
+ ## πŸš€ Deployment
214
+
215
+ ### Hugging Face Spaces (Current)
216
+ The bot runs as a Docker Space. Set all env vars in **Settings β†’ Variables and secrets**.
217
+
218
+ ### Railway / Render
219
+ 1. Push this folder to a GitHub repo
220
+ 2. Connect to Railway or Render
221
+ 3. Set env vars: `BOT_TOKEN`, `GEMINI_API_KEY`, `ADMIN_USER_IDS`
222
+ 4. Deploy as a **Background Worker** (no open port needed)
223
+
224
+ ### VPS / Self-hosted
225
+ ```bash
226
+ screen -S jeebot
227
+ python bot.py
228
+ # Ctrl+A D to detach
229
+ ```
230
+
231
+ ---
232
+
233
+ ## πŸ“ Project Structure
234
+
235
+ ```
236
+ JEE, NEET & Advance Content Manager/
237
+ β”œβ”€β”€ bot.py ← Entry point; starts polling + dashboard server
238
+ β”œβ”€β”€ config.py ← Env vars + Gemini settings (model, tokens, temp)
239
+ β”œβ”€β”€ requirements.txt
240
+ β”œβ”€β”€ data/
241
+ β”‚ β”œβ”€β”€ bot_config.json ← Auto-saved dynamic config (channels, schedule)
242
+ β”‚ β”œβ”€β”€ content_history.json ← Repeat-prevention tracker
243
+ β”‚ β”œβ”€β”€ syllabus.json ← Full JEE/NEET syllabus (chapters per subject)
244
+ β”‚ β”œβ”€β”€ prompts.json ← Custom AI prompt templates (editable via dashboard)
245
+ β”‚ └── digests/ ← Generated weekly PDF files
246
+ β”œβ”€β”€ content/
247
+ β”‚ β”œβ”€β”€ generator.py ← Gemini AI content generation + Markdown sanitizer
248
+ β”‚ β”œβ”€β”€ history.py ← Chapter tracker + weekly archive for PDFs
249
+ β”‚ β”œβ”€β”€ pdf_generator.py ← Branded CrazyLearners PDF builder (fpdf2)
250
+ β”‚ β”œβ”€β”€ config_manager.py ← Dynamic channel/schedule config (JSON-backed)
251
+ β”‚ β”œβ”€β”€ syllabus_manager.py ← Syllabus loader with recursive chapter extraction
252
+ β”‚ β”œβ”€β”€ template_manager.py ← AI prompt template manager
253
+ β”‚ β”œβ”€β”€ doubt_solver.py ← Gemini-powered doubt answering for students
254
+ β”‚ β”œβ”€β”€ remote_storage.py ← GitHub Gist sync for history persistence
255
+ β”‚ └── user_registry.py ← Registered user DB (for broadcast)
256
+ β”œβ”€β”€ scheduler/
257
+ β”‚ └── job_scheduler.py ← APScheduler: 1 job per (content_type Γ— channel)
258
+ β”‚ _safe_send_message with Markdown parse recovery
259
+ └── handlers/
260
+ β”œβ”€β”€ commands.py ← /start /status /channels /preview /mcq_session etc.
261
+ β”œβ”€β”€ callbacks.py ← Inline button actions (pause, preview, post-now)
262
+ β”œβ”€β”€ doubt_handler.py ← DM + group @mention doubt handler
263
+ └── menu_router.py ← Routes reply-keyboard button taps
264
+ ```
265
+
266
+ ---
267
+
268
+ ## πŸ”§ Key Configuration Constants (`config.py`)
269
+
270
+ | Constant | Default | Purpose |
271
+ |----------|---------|---------|
272
+ | `GEMINI_MODEL` | `gemini-2.0-flash` | Gemini model for all AI generation |
273
+ | `GEMINI_MAX_TOKENS` | `3500` | Max tokens per AI response (high enough for 10-MCQ JSON) |
274
+ | `GEMINI_TEMPERATURE` | `0.7` | Creativity vs consistency balance |
275
+ | `HISTORY_DEPTH` | `60` | How many past topics to remember before reuse is allowed |
276
+
277
+ ---
278
+
279
+ ## πŸ› Known Issues Fixed (v2.0)
280
+
281
+ | Bug | Fix |
282
+ |-----|-----|
283
+ | `Can't parse entities` β€” Telegram Markdown errors | `_clean_markdown()` now strips code blocks before counting `*`/`_` markers; `_safe_send_message()` auto-retries as plain text on parse failure |
284
+ | `Message is too long` | Hard 4000-char truncation in `_clean_markdown()` + `_safe_send_message()` |
285
+ | `Could not generate enough MCQs` | `GEMINI_MAX_TOKENS` raised to 3500; `_parse_mcq_json()` uses `find('[')` + `rfind(']')` instead of greedy regex; auto-retries once before giving up |
286
+ | MCQ callback blocking event loop 15 min | `asyncio.create_task()` instead of `await` in callback handler |
287
+ | PDF file handle leak | Wrapped `send_document` in `with open(...) as f` |
288
+ | `KeyError` on custom content type in `/set_time` | Changed `CONTENT_LABELS[ctype]` β†’ `.get(ctype, ctype)` |
289
+ | Broadcast hitting Telegram 429 rate limit | `asyncio.sleep(0.05)` between each send |
290
+ | `get_me()` API call on every group message | Cached in `context.bot_data` after first call |
291
+ | Archive storing empty date | Uses `datetime.now()` instead of missing env var |
292
+ | Preview command crashing on dict response | Handles quiz/text/error dict shapes correctly |
bot.py CHANGED
@@ -104,7 +104,7 @@ class BotHandler(BaseHTTPRequestHandler):
104
  if path == "/api/health":
105
  import time
106
  from scheduler.job_scheduler import get_all_jobs
107
- from config import GROQ_MODEL
108
 
109
  # Basic subsystem check
110
  scheduler_ok = True
@@ -116,8 +116,8 @@ class BotHandler(BaseHTTPRequestHandler):
116
  "ts": time.strftime("%H:%M:%S"),
117
  "checks": {
118
  "scheduler": {"ok": scheduler_ok, "msg": f"{len(get_all_jobs())} jobs active" if scheduler_ok else "Scheduler error"},
119
- "groq": {"ok": True, "msg": f"Model: {GROQ_MODEL}"},
120
- "telegram": {"ok": True, "msg": "API Online"}
121
  }
122
  })
123
  return
 
104
  if path == "/api/health":
105
  import time
106
  from scheduler.job_scheduler import get_all_jobs
107
+ from config import GEMINI_MODEL
108
 
109
  # Basic subsystem check
110
  scheduler_ok = True
 
116
  "ts": time.strftime("%H:%M:%S"),
117
  "checks": {
118
  "scheduler": {"ok": scheduler_ok, "msg": f"{len(get_all_jobs())} jobs active" if scheduler_ok else "Scheduler error"},
119
+ "gemini": {"ok": True, "msg": f"Model: {GEMINI_MODEL}"},
120
+ "telegram": {"ok": True, "msg": "API Online"}
121
  }
122
  })
123
  return
config.py CHANGED
@@ -8,7 +8,7 @@ load_dotenv()
8
  # ─────────────────────────────────────────────
9
 
10
  BOT_TOKEN = os.getenv("BOT_TOKEN", "YOUR_TELEGRAM_BOT_TOKEN") # From @BotFather
11
- GROQ_API_KEY = os.getenv("GROQ_API_KEY", "YOUR_GROQ_API_KEY") # From Groq Cloud
12
  GIST_ID = os.getenv("GIST_ID", "") # GitHub Gist ID
13
  GIST_TOKEN = os.getenv("GIST_TOKEN", "") # GitHub Personal Access Token
14
 
@@ -46,9 +46,9 @@ SUBJECT_ROTATION = {
46
  }
47
 
48
  # ─────────────────────────────────────────────
49
- # GROQ SETTINGS
50
  # ─────────────────────────────────────────────
51
 
52
- GROQ_MODEL = "llama-3.3-70b-versatile"
53
- GROQ_MAX_TOKENS = 4500 # Increased again: large MCQ sessions with detailed explanations need more room
54
- GROQ_TEMPERATURE = 0.7
 
8
  # ─────────────────────────────────────────────
9
 
10
  BOT_TOKEN = os.getenv("BOT_TOKEN", "YOUR_TELEGRAM_BOT_TOKEN") # From @BotFather
11
+ GEMINI_API_KEY = os.getenv("GEMINI_API_KEY", "YOUR_GEMINI_API_KEY") # From Google AI Studio
12
  GIST_ID = os.getenv("GIST_ID", "") # GitHub Gist ID
13
  GIST_TOKEN = os.getenv("GIST_TOKEN", "") # GitHub Personal Access Token
14
 
 
46
  }
47
 
48
  # ─────────────────────────────────────────────
49
+ # GEMINI SETTINGS
50
  # ─────────────────────────────────────────────
51
 
52
+ GEMINI_MODEL = "gemini-2.0-flash"
53
+ GEMINI_MAX_TOKENS = 4500 # Sufficient for large MCQ sessions with detailed explanations
54
+ GEMINI_TEMPERATURE = 0.7
content/doubt_solver.py CHANGED
@@ -1,119 +1,123 @@
1
- """
2
- AI Doubt Solver
3
- Explains any JEE/NEET question, MCQ, or topic forwarded to the bot.
4
- Works for: DM messages, group @mentions, replies-to-bot messages.
5
- """
6
-
7
- import logging
8
- import re
9
- from groq import AsyncGroq
10
- from config import GROQ_API_KEY, GROQ_MODEL, GROQ_MAX_TOKENS
11
-
12
- logger = logging.getLogger(__name__)
13
- client = AsyncGroq(api_key=GROQ_API_KEY)
14
-
15
- # System prompt that makes the bot act as a JEE/NEET tutor
16
- _SYSTEM_PROMPT = (
17
- "You are an expert JEE and NEET tutor named 'CrazyBot'. "
18
- "Your job is to explain concepts, solve MCQs, and clear doubts for students preparing for JEE Main, "
19
- "JEE Advanced, and NEET-UG. "
20
- "When given a question or MCQ, you MUST:\n"
21
- "1. Identify the topic/concept\n"
22
- "2. Explain the core concept clearly in simple language\n"
23
- "3. Show step-by-step solution if it's a numerical\n"
24
- "4. State the correct answer with full reasoning\n"
25
- "5. Give 1 exam tip related to this concept\n\n"
26
- "Keep responses concise (max 400 words). Use Unicode math symbols (Β², √, Ο€, ΞΌ, Ξ”, ΞΈ). "
27
- "No LaTeX. Format with emojis for readability on Telegram."
28
- )
29
-
30
- _DOUBT_PROMPT_TEMPLATE = """A JEE/NEET student has a doubt. Here is what they sent:
31
-
32
- ---
33
- {content}
34
- ---
35
-
36
- Please explain this clearly. If it's an MCQ, solve it step-by-step and reveal the correct answer.
37
- If it's a concept question, explain it with an example and a JEE/NEET exam tip."""
38
-
39
-
40
- def _extract_text(message) -> str:
41
- """
42
- Extract meaningful text from a Telegram message object.
43
- Handles: plain text, forwarded text, poll questions, captions.
44
- """
45
- parts = []
46
-
47
- # Forwarded message context
48
- if message.forward_origin or message.forward_date:
49
- parts.append("[Forwarded content]")
50
-
51
- # Poll forwarded
52
- if message.poll:
53
- poll = message.poll
54
- parts.append(f"MCQ: {poll.question}")
55
- for i, opt in enumerate(poll.options):
56
- label = chr(65 + i) # A, B, C, D
57
- parts.append(f"({label}) {opt.text}")
58
- return "\n".join(parts)
59
-
60
- # Regular text or caption
61
- text = message.text or message.caption or ""
62
-
63
- # Strip bot mention (@BotName) from group messages
64
- text = re.sub(r'@\w+', '', text).strip()
65
-
66
- if text:
67
- parts.append(text)
68
-
69
- return "\n".join(parts).strip() if parts else ""
70
-
71
-
72
- async def solve_doubt(user_question: str) -> str:
73
- """
74
- Call Groq to explain/solve the student's question.
75
- Returns formatted response string.
76
- """
77
- if not user_question or len(user_question.strip()) < 5:
78
- return (
79
- "πŸ€” *I need a question to answer!*\n\n"
80
- "Please:\n"
81
- "β€’ Type your doubt directly\n"
82
- "β€’ Forward any MCQ or question to me\n"
83
- "β€’ Reply to a question in the group mentioning me\n\n"
84
- "Example: `What is Bernoulli's principle?`"
85
- )
86
-
87
- prompt = _DOUBT_PROMPT_TEMPLATE.format(content=user_question[:2000])
88
-
89
- try:
90
- from content.config_manager import config_manager
91
- s = config_manager.settings
92
- system_prompt = _SYSTEM_PROMPT.replace("CrazyBot", s['bot_name'])
93
-
94
- completion = await client.chat.completions.create(
95
- model=GROQ_MODEL,
96
- messages=[
97
- {"role": "system", "content": system_prompt},
98
- {"role": "user", "content": prompt},
99
- ],
100
- max_tokens=GROQ_MAX_TOKENS,
101
- temperature=0.5,
102
- )
103
- answer = completion.choices[0].message.content
104
- if not answer:
105
- return "⚠️ I couldn't generate a response right now. Please try again."
106
-
107
- # Add helpful footer
108
- answer = answer.strip()
109
- answer += f"\n\n━━━━━━━━━━━━━━\nπŸ”— *[{s['main_channel_name']}]({s['main_channel_url']})* | Ask more doubts anytime!"
110
- return answer
111
-
112
- except Exception as e:
113
- logger.error(f"[DoubtSolver] Groq error: {e}")
114
- from content.config_manager import config_manager
115
- s = config_manager.settings
116
- return (
117
- "⚠️ *Doubt solver is temporarily unavailable.*\n"
118
- f"Please try again in a moment, or check [{s['main_channel_name']}]({s['main_channel_url']}) for help."
119
- )
 
 
 
 
 
1
+ """
2
+ AI Doubt Solver
3
+ Explains any JEE/NEET question, MCQ, or topic forwarded to the bot.
4
+ Works for: DM messages, group @mentions, replies-to-bot messages.
5
+ """
6
+
7
+ import logging
8
+ import re
9
+ import google.generativeai as genai
10
+ from google.generativeai.types import GenerationConfig
11
+ from config import GEMINI_API_KEY, GEMINI_MODEL, GEMINI_MAX_TOKENS
12
+
13
+ logger = logging.getLogger(__name__)
14
+ genai.configure(api_key=GEMINI_API_KEY)
15
+
16
+ # System prompt that makes the bot act as a JEE/NEET tutor
17
+ _SYSTEM_PROMPT = (
18
+ "You are an expert JEE and NEET tutor named 'CrazyBot'. "
19
+ "Your job is to explain concepts, solve MCQs, and clear doubts for students preparing for JEE Main, "
20
+ "JEE Advanced, and NEET-UG. "
21
+ "When given a question or MCQ, you MUST:\n"
22
+ "1. Identify the topic/concept\n"
23
+ "2. Explain the core concept clearly in simple language\n"
24
+ "3. Show step-by-step solution if it's a numerical\n"
25
+ "4. State the correct answer with full reasoning\n"
26
+ "5. Give 1 exam tip related to this concept\n\n"
27
+ "Keep responses concise (max 400 words). Use Unicode math symbols (Β², √, Ο€, ΞΌ, Ξ”, ΞΈ). "
28
+ "No LaTeX. Format with emojis for readability on Telegram."
29
+ )
30
+
31
+ _DOUBT_PROMPT_TEMPLATE = """A JEE/NEET student has a doubt. Here is what they sent:
32
+
33
+ ---
34
+ {content}
35
+ ---
36
+
37
+ Please explain this clearly. If it's an MCQ, solve it step-by-step and reveal the correct answer.
38
+ If it's a concept question, explain it with an example and a JEE/NEET exam tip."""
39
+
40
+
41
+ def _extract_text(message) -> str:
42
+ """
43
+ Extract meaningful text from a Telegram message object.
44
+ Handles: plain text, forwarded text, poll questions, captions.
45
+ """
46
+ parts = []
47
+
48
+ # Forwarded message context
49
+ if message.forward_origin or message.forward_date:
50
+ parts.append("[Forwarded content]")
51
+
52
+ # Poll forwarded
53
+ if message.poll:
54
+ poll = message.poll
55
+ parts.append(f"MCQ: {poll.question}")
56
+ for i, opt in enumerate(poll.options):
57
+ label = chr(65 + i) # A, B, C, D
58
+ parts.append(f"({label}) {opt.text}")
59
+ return "\n".join(parts)
60
+
61
+ # Regular text or caption
62
+ text = message.text or message.caption or ""
63
+
64
+ # Strip bot mention (@BotName) from group messages
65
+ text = re.sub(r'@\w+', '', text).strip()
66
+
67
+ if text:
68
+ parts.append(text)
69
+
70
+ return "\n".join(parts).strip() if parts else ""
71
+
72
+
73
+ async def solve_doubt(user_question: str) -> str:
74
+ """
75
+ Call Gemini to explain/solve the student's question.
76
+ Returns formatted response string.
77
+ """
78
+ if not user_question or len(user_question.strip()) < 5:
79
+ return (
80
+ "πŸ€” *I need a question to answer!*\n\n"
81
+ "Please:\n"
82
+ "β€’ Type your doubt directly\n"
83
+ "β€’ Forward any MCQ or question to me\n"
84
+ "β€’ Reply to a question in the group mentioning me\n\n"
85
+ "Example: `What is Bernoulli's principle?`"
86
+ )
87
+
88
+ prompt = _DOUBT_PROMPT_TEMPLATE.format(content=user_question[:2000])
89
+
90
+ try:
91
+ from content.config_manager import config_manager
92
+ s = config_manager.settings
93
+ system_prompt = _SYSTEM_PROMPT.replace("CrazyBot", s['bot_name'])
94
+
95
+ model = genai.GenerativeModel(
96
+ model_name=GEMINI_MODEL,
97
+ system_instruction=system_prompt
98
+ )
99
+
100
+ response = await model.generate_content_async(
101
+ prompt,
102
+ generation_config=GenerationConfig(
103
+ max_output_tokens=GEMINI_MAX_TOKENS,
104
+ temperature=0.5,
105
+ )
106
+ )
107
+ answer = response.text
108
+ if not answer:
109
+ return "⚠️ I couldn't generate a response right now. Please try again."
110
+
111
+ # Add helpful footer
112
+ answer = answer.strip()
113
+ answer += f"\n\n━━━━━━━━━━━━━━\nπŸ”— *[{s['main_channel_name']}]({s['main_channel_url']})* | Ask more doubts anytime!"
114
+ return answer
115
+
116
+ except Exception as e:
117
+ logger.error(f"[DoubtSolver] Gemini error: {e}")
118
+ from content.config_manager import config_manager
119
+ s = config_manager.settings
120
+ return (
121
+ "⚠️ *Doubt solver is temporarily unavailable.*\n"
122
+ f"Please try again in a moment, or check [{s['main_channel_name']}]({s['main_channel_url']}) for help."
123
+ )
content/generator.py CHANGED
@@ -1,516 +1,521 @@
1
- import logging
2
- import random
3
- import traceback
4
- import asyncio
5
- import json
6
- import re
7
- from datetime import datetime
8
- from groq import AsyncGroq
9
-
10
- from config import (
11
- GROQ_API_KEY, GROQ_MODEL, GROQ_MAX_TOKENS,
12
- GROQ_TEMPERATURE, SUBJECT_ROTATION
13
- )
14
- from content.config_manager import config_manager
15
- from content.syllabus_manager import syllabus_manager
16
- from content.template_manager import template_manager
17
- from content.history import pick_fresh_chapter, archive_weekly_post
18
-
19
- logger = logging.getLogger(__name__)
20
-
21
- # Initialize Groq Client
22
- client = AsyncGroq(api_key=GROQ_API_KEY)
23
-
24
-
25
- # ─────────────────────────────────────────────
26
- # Helpers
27
- # ─────────────────────────────────────────────
28
-
29
- def _clean_markdown(text: str) -> str:
30
- """
31
- Cleanup to prevent Telegram Markdown parse errors.
32
- Handles unclosed code blocks, bold, italic, and inline-code markers.
33
- Also enforces the 4096-character Telegram message limit.
34
- """
35
- if not text:
36
- return ""
37
-
38
- # --- 1. Close unclosed triple-backtick code blocks ---
39
- if text.count("```") % 2 != 0:
40
- text += "\n```"
41
-
42
- # --- 2. Close unclosed inline backtick spans ---
43
- if text.count("`") % 2 != 0:
44
- text += "`"
45
-
46
- # --- 3. Close unclosed bold markers (*) ---
47
- # Only count * that are NOT part of *** or ** patterns
48
- # Simple heuristic: strip code blocks first, then count remaining *
49
- temp = re.sub(r'```.*?```', '', text, flags=re.DOTALL) # remove code blocks
50
- temp = re.sub(r'`[^`]*`', '', temp) # remove inline code
51
- if temp.count("*") % 2 != 0:
52
- text += "*"
53
-
54
- # --- 4. Close unclosed italic underscores (_) outside code spans ---
55
- temp2 = re.sub(r'```.*?```', '', text, flags=re.DOTALL)
56
- temp2 = re.sub(r'`[^`]*`', '', temp2)
57
- if temp2.count("_") % 2 != 0:
58
- text += "\_"
59
-
60
- # --- 5. Truncate to Telegram's 4096-char hard limit ---
61
- if len(text) > 4000:
62
- text = text[:3997] + "..."
63
-
64
- return text
65
-
66
- def _today() -> str:
67
- return datetime.now().strftime("%A")
68
-
69
-
70
- async def _call_groq(prompt: str) -> str:
71
- """Wrapper for Groq API calls with retry logic for rate limits."""
72
- max_retries = 3
73
- base_delay = 2 # Groq is fast, shorter delay
74
-
75
- for attempt in range(max_retries):
76
- try:
77
- completion = await client.chat.completions.create(
78
- model=GROQ_MODEL,
79
- messages=[
80
- {"role": "system", "content": template_manager.system_prompt},
81
- {"role": "user", "content": prompt}
82
- ],
83
- max_tokens=GROQ_MAX_TOKENS,
84
- temperature=GROQ_TEMPERATURE,
85
- )
86
-
87
- content = completion.choices[0].message.content
88
- if not content:
89
- logger.warning(f"Groq returned empty response (Attempt {attempt+1}/{max_retries})")
90
- if attempt < max_retries - 1:
91
- await asyncio.sleep(base_delay * (2 ** attempt))
92
- continue
93
- return None
94
-
95
- return _clean_markdown(content.strip())
96
-
97
- except Exception as e:
98
- err_msg = str(e).lower()
99
- # Groq often returns 429 for rate limits
100
- if "429" in err_msg or "rate_limit" in err_msg:
101
- wait_time = base_delay * (2 ** attempt) + random.uniform(1, 2)
102
- logger.warning(f"Groq Rate Limit (429) hit. Retrying in {wait_time:.1f}s... (Attempt {attempt+1}/{max_retries})")
103
- if attempt < max_retries - 1:
104
- await asyncio.sleep(wait_time)
105
- continue
106
-
107
- logger.error(f"Groq API error: {e}\n{traceback.format_exc()}")
108
- return None
109
-
110
- return None
111
-
112
-
113
- def _channel_subjects(channel_key: str) -> list:
114
- """Return subjects active for this channel on today's rotation, filtered by syllabus availability."""
115
- channel_cfg = config_manager.channels.get(channel_key, {})
116
- exam_focus = channel_cfg.get("exam_focus", ["JEE Main"])
117
-
118
- # Get all subjects available in the syllabus for this exam
119
- all_syllabus_subjects = set()
120
- for focus in exam_focus:
121
- all_syllabus_subjects.update(syllabus_manager.get_all_subjects(focus))
122
-
123
- ch_subjects = set(channel_cfg.get("subjects", list(all_syllabus_subjects)))
124
- day_subjects = set(SUBJECT_ROTATION.get(_today(), list(all_syllabus_subjects)))
125
- active = list(ch_subjects & day_subjects)
126
- return active if active else list(ch_subjects)
127
-
128
-
129
- def _pick(channel_key: str, content_type: str) -> tuple:
130
- """Pick a non-repeating (subject, chapter) pair for this channel + content type."""
131
- subjects = _channel_subjects(channel_key)
132
- subject = random.choice(subjects)
133
- chapter = pick_fresh_chapter(channel_key, content_type, subject)
134
- return subject, chapter
135
-
136
-
137
- def _footer(channel_key: str, tag_key: str) -> str:
138
- cfg = config_manager.channels.get(channel_key, {})
139
- footer = cfg.get("footer", "✨ *Study Hard, Score High!*")
140
- hashtag = cfg.get("hashtags", {}).get(tag_key, "")
141
-
142
- brand = "πŸš€ *Join for more:* @xcrazylearners"
143
- sep = "━━━━━━━━━━━━━━━━━━"
144
-
145
- if hashtag:
146
- return f"\n\n{hashtag}\n{sep}\n{footer}\n{brand}"
147
- else:
148
- return f"\n\n{sep}\n{footer}\n{brand}"
149
-
150
-
151
- def _exam(channel_key: str) -> str:
152
- exams = config_manager.channels.get(channel_key, {}).get("exam_focus", ["JEE Main"])
153
- return random.choice(exams)
154
-
155
- def _difficulty_context(channel_key: str) -> str:
156
- """Returns a difficulty instruction based on the channel's target exams."""
157
- cfg = config_manager.channels.get(channel_key, {})
158
- exams = cfg.get("exam_focus", [])
159
-
160
- # Class 9/10 focus
161
- if any(ex in ["Class 9", "Class 10", "NTSE", "Foundation"] for ex in exams):
162
- return "Difficulty: Foundation/School Level. Focus on basic concepts, definitions, and clear logic. Avoid extremely complex calculus or advanced topics."
163
-
164
- # JEE Advanced focus
165
- if "JEE Advanced" in exams:
166
- return "Difficulty: Advanced/Hard. Use multi-concept problems, challenging numericals, and tricky logic. Focus on deep understanding."
167
-
168
- # JEE Main / NEET focus (default for competitive)
169
- return "Difficulty: Competitive (JEE Main/NEET level). Focus on accuracy, speed-based patterns, and standard competitive concepts."
170
-
171
-
172
- # ─────────────────────────────────────────────
173
- # 1. PYQ QUESTION (QUIZ MODE)
174
- # ─────────────────────────────────────────────
175
-
176
- def _parse_quiz(text: str) -> dict:
177
- """Extracts quiz components from the AI-generated text."""
178
- try:
179
- # Question: Find text between ❓ QUESTION: and (A)
180
- q_start = text.find("❓ QUESTION:") + len("❓ QUESTION:")
181
- q_end = text.find("(A)")
182
- question = text[q_start:q_end].strip()
183
-
184
- # Truncate question for Telegram (300 chars limit)
185
- if len(question) > 297:
186
- question = question[:297] + "..."
187
-
188
- # Options: (A), (B), (C), (D)
189
- options = []
190
- for label in ["(A)", "(B)", "(C)", "(D)"]:
191
- start = text.find(label) + len(label)
192
- # Find the next label or the answer line
193
- next_label = text.find("(B)") if label == "(A)" else (text.find("(C)") if label == "(B)" else (text.find("(D)") if label == "(C)" else text.find("||βœ… ANSWER:")))
194
- opt_text = text[start:next_label].strip()
195
- options.append(opt_text[:100]) # Telegram limit: 100 chars per option
196
-
197
- # Correct Answer Index
198
- ans_line = text.lower().find("answer: (")
199
- correct_letter = text[ans_line + len("answer: (") : ans_line + len("answer: (") + 1].upper()
200
- mapping = {"A": 0, "B": 1, "C": 2, "D": 3}
201
- correct_index = mapping.get(correct_letter, 0)
202
-
203
- # Explanation
204
- e_start = text.find("πŸ’‘ EXPLANATION:") + len("πŸ’‘ EXPLANATION:")
205
- e_end = text.find("🎯 Difficulty:")
206
- explanation = text[e_start:e_end].strip()
207
-
208
- # Truncate explanation for Telegram (200 chars limit)
209
- if len(explanation) > 197:
210
- explanation = explanation[:197] + "..."
211
-
212
- return {
213
- "question": question,
214
- "options": options,
215
- "correct_index": correct_index,
216
- "explanation": explanation,
217
- "full_text": text # Still include the full text for fallback/preview
218
- }
219
- except Exception as e:
220
- logger.error(f"Quiz parsing failed: {e}")
221
- return None
222
-
223
-
224
- async def generate_pyq_question(channel_key: str) -> dict:
225
- subject, chapter = _pick(channel_key, "pyq_question")
226
- exam = _exam(channel_key)
227
- year = random.randint(2015, 2023)
228
-
229
- template = template_manager.get_template("pyq_question")
230
- diff_text = _difficulty_context(channel_key)
231
- prompt = template.format(
232
- exam=exam, year=year, chapter=chapter,
233
- subject=subject.title()
234
- ) + f"\n\n{diff_text}"
235
-
236
- raw_text = await _call_groq(prompt)
237
- if not raw_text:
238
- return {"error": "⚠️ Content temporarily unavailable."}
239
-
240
- quiz_data = _parse_quiz(raw_text)
241
- if not quiz_data:
242
- # Fallback to plain text if parsing fails
243
- return {"text": raw_text + _footer(channel_key, "pyq")}
244
-
245
- # Return structured dict for the dispatcher
246
- return {
247
- "text": raw_text + _footer(channel_key, "pyq"),
248
- "quiz": quiz_data,
249
- "type": "quiz"
250
- }
251
-
252
-
253
- # ─────────────────────────────────────────────
254
- # 2. FORMULA SHEET
255
- # ────────────���────────────────────────────────
256
-
257
- async def generate_formula_sheet(channel_key: str) -> str:
258
- subject, chapter = _pick(channel_key, "formula_sheet")
259
- exam = _exam(channel_key)
260
-
261
- template = template_manager.get_template("formula_sheet")
262
- prompt = template.format(exam=exam, chapter=chapter, subject=subject.title())
263
-
264
- text = await _call_groq(prompt)
265
- text = (text or "⚠️ Content temporarily unavailable.")
266
-
267
- # Archive for Weekly PDF
268
- if text != "⚠️ Content temporarily unavailable.":
269
- archive_weekly_post(channel_key, "formula_sheet", subject, chapter, text)
270
-
271
- return text + _footer(channel_key, "formula")
272
-
273
-
274
- # ─────────────────────────────────────────────
275
- # 3. SHORT NOTES
276
- # ─────────────────────────────────────────────
277
-
278
- async def generate_short_notes(channel_key: str) -> str:
279
- subject, chapter = _pick(channel_key, "short_notes")
280
- exam = _exam(channel_key)
281
-
282
- template = template_manager.get_template("short_notes")
283
- prompt = template.format(exam=exam, chapter=chapter, subject=subject.title())
284
-
285
- text = await _call_groq(prompt)
286
- text = (text or "⚠️ Content temporarily unavailable.")
287
-
288
- # Archive for Weekly PDF
289
- if text != "⚠️ Content temporarily unavailable.":
290
- archive_weekly_post(channel_key, "short_notes", subject, chapter, text)
291
-
292
- return text + _footer(channel_key, "notes")
293
-
294
-
295
- # ─────────────────────────────────────────────
296
- # 4. MNEMONIC
297
- # ─────────────────────────────────────────────
298
-
299
- async def generate_mnemonic(channel_key: str) -> str:
300
- subject, chapter = _pick(channel_key, "mnemonic")
301
-
302
- template = template_manager.get_template("mnemonic")
303
- prompt = template.format(chapter=chapter, subject=subject.title())
304
-
305
- text = await _call_groq(prompt)
306
- return (text or "⚠️ Content temporarily unavailable.") + _footer(channel_key, "mnemonic")
307
-
308
-
309
- # ─────────────────────────────────────────────
310
- # 5. CONCEPT RECAP
311
- # ─────────────────────────────────────────────
312
-
313
- async def generate_concept_recap(channel_key: str) -> str:
314
- subject, chapter = _pick(channel_key, "concept_recap")
315
- exam = _exam(channel_key)
316
-
317
- template = template_manager.get_template("concept_recap")
318
- prompt = template.format(exam=exam, chapter=chapter, subject=subject.title())
319
-
320
- text = await _call_groq(prompt)
321
- return (text or "⚠️ Content temporarily unavailable.") + _footer(channel_key, "recap")
322
-
323
-
324
- # ─────────────────────────────────────────────
325
- # 6. MOCK MCQ
326
- # ─────────────────────────────────────────────
327
-
328
- async def generate_mock_question(channel_key: str) -> str:
329
- subject, chapter = _pick(channel_key, "mock_question")
330
- exam = _exam(channel_key)
331
-
332
- template = template_manager.get_template("mock_question")
333
- diff_text = _difficulty_context(channel_key)
334
- prompt = template.format(exam=exam, chapter=chapter, subject=subject.title()) + f"\n\n{diff_text}"
335
-
336
- text = await _call_groq(prompt)
337
- return (text or "⚠️ Content temporarily unavailable.") + _footer(channel_key, "mock")
338
-
339
-
340
- # ─────────────────────────────────────────────
341
- # 7. MOTIVATIONAL
342
- # ─────────────────────────────────────────────
343
-
344
- async def generate_motivational(channel_key: str) -> str:
345
- exam = _exam(channel_key)
346
-
347
- # Pick a random subject and chapter to make the message specific
348
- subjects = _channel_subjects(channel_key)
349
- subject = random.choice(subjects)
350
- chapter = pick_fresh_chapter(channel_key, "motivational", subject)
351
-
352
- template = template_manager.get_template("motivational")
353
- prompt = template.format(exam=exam, subject=subject.title(), chapter=chapter)
354
-
355
- text = await _call_groq(prompt)
356
- cfg = config_manager.channels.get(channel_key, {})
357
- footer = cfg.get("footer", "")
358
- return (text or "πŸŒ™ Rest well! See you tomorrow πŸ’ͺ") + (f"\n\n{footer}" if footer else "")
359
-
360
-
361
- # ─────────────────────────────────────────────
362
- # 8. MCQ POLL SESSION (10 polls, chapter-wise)
363
- # ────��────────────────────────────────────────
364
-
365
- def _parse_mcq_json(text: str) -> list:
366
- """Extract and repair a JSON array of MCQ dicts from the Groq response."""
367
- if not text: return []
368
-
369
- # 1. Basic Cleaning
370
- clean = text.strip()
371
- if clean.startswith("```"):
372
- clean = re.sub(r'^```(?:json)?\s*', '', clean, flags=re.MULTILINE)
373
- clean = re.sub(r'\s*```\s*$', '', clean, flags=re.MULTILINE).strip()
374
-
375
- # 2. Slice to array bounds if possible
376
- start = clean.find('[')
377
- if start == -1: return []
378
-
379
- # Try to find the last ']' - but if it's truncated, we might need to repair it
380
- end = clean.rfind(']')
381
-
382
- candidate = clean[start:]
383
- if end != -1:
384
- candidate = clean[start:end + 1]
385
-
386
- # 3. Progressive Repair Strategy
387
- try:
388
- return json.loads(candidate)
389
- except json.JSONDecodeError:
390
- # AI truncated mid-object? Let's try to fix it.
391
- # Strategy: Remove everything after the last valid "}," and add "]"
392
- last_comma = candidate.rfind('},')
393
- if last_comma != -1:
394
- try:
395
- return json.loads(candidate[:last_comma + 1] + "]")
396
- except: pass
397
-
398
- # Try finding the last "}" and closing the array
399
- last_brace = candidate.rfind('}')
400
- if last_brace != -1:
401
- try:
402
- return json.loads(candidate[:last_brace + 1] + "]")
403
- except: pass
404
-
405
- return []
406
-
407
-
408
- async def generate_mcq_session(channel_key: str) -> dict:
409
- """Generate 10 MCQ Telegram quiz polls for a single chapter."""
410
- subject, chapter = _pick(channel_key, "mcq_session")
411
- exam = _exam(channel_key)
412
-
413
- template = template_manager.get_template("mcq_session")
414
- diff_text = _difficulty_context(channel_key)
415
- prompt = template.format(exam=exam, chapter=chapter, subject=subject.title()) + f"\n\n{diff_text}"
416
-
417
- raw = await _call_groq(prompt)
418
- if not raw:
419
- return {"error": "⚠️ MCQ Session content temporarily unavailable."}
420
-
421
- questions = _parse_mcq_json(raw)
422
- MIN_MCQ = 3 # Accept sessions with at least 3 valid questions
423
- if not questions or len(questions) < MIN_MCQ:
424
- logger.warning(f"MCQ session got only {len(questions)} questions (need {MIN_MCQ}) β€” retrying once")
425
- # --- One automatic retry before giving up ---
426
- raw2 = await _call_groq(prompt)
427
- if raw2:
428
- questions = _parse_mcq_json(raw2)
429
- if not questions or len(questions) < MIN_MCQ:
430
- logger.error(f"MCQ session still only {len(questions)} questions after retry β€” giving up")
431
- return {"error": "⚠️ Could not generate enough MCQs right now. Please retry."}
432
-
433
- # Clamp to exactly 10
434
- questions = questions[:10]
435
-
436
- # Sanitise each question for Telegram limits
437
- clean = []
438
- for q in questions:
439
- opts = [str(o)[:100] for o in q.get("options", [])]
440
- if len(opts) < 4:
441
- continue # skip malformed
442
- clean.append({
443
- "question": str(q.get("question", ""))[:300],
444
- "options": opts,
445
- "correct_index": int(q.get("correct_index", 0)) % 4,
446
- "explanation": str(q.get("explanation", ""))[:200],
447
- })
448
-
449
- return {
450
- "type": "mcq_session",
451
- "subject": subject,
452
- "chapter": chapter,
453
- "exam": exam,
454
- "questions": clean,
455
- }
456
-
457
-
458
- # ─────────────────────────────────────────────
459
- # DISPATCHER
460
- # ─────────────────────────────────────────────
461
-
462
- CONTENT_GENERATORS = {
463
- "pyq_question": generate_pyq_question,
464
- "formula_sheet": generate_formula_sheet,
465
- "short_notes": generate_short_notes,
466
- "mnemonic": generate_mnemonic,
467
- "concept_recap": generate_concept_recap,
468
- "mock_question": generate_mock_question,
469
- "motivational": generate_motivational,
470
- "mcq_session": generate_mcq_session,
471
- }
472
-
473
- CONTENT_LABELS = {
474
- "pyq_question": "πŸ“… Daily PYQ Question",
475
- "formula_sheet": "πŸ“ Formula Sheet",
476
- "short_notes": "πŸ“ Short Notes",
477
- "mnemonic": "🧠 Memory Tricks",
478
- "concept_recap": "πŸŒ… Concept Recap",
479
- "mock_question": "🎯 Daily Mock",
480
- "motivational": "πŸŒ™ Night Motivation",
481
- "mcq_session": "πŸ§ͺ MCQ Poll Session",
482
- }
483
-
484
-
485
- async def generate_generic_ai_post(content_type: str, channel_key: str) -> dict:
486
- """Fallback generator for user-defined custom content types."""
487
- prompt_template = template_manager.data["templates"].get(content_type)
488
- if not prompt_template:
489
- return {"text": f"❌ No prompt template found for custom type: `{content_type}`"}
490
-
491
- subject, chapter = _pick(channel_key, content_type)
492
- exam = _exam(channel_key)
493
- year = datetime.now().year
494
-
495
- try:
496
- full_prompt = prompt_template.format(exam=exam, subject=subject, chapter=chapter, year=year)
497
- except KeyError as e:
498
- # Fallback if user uses a placeholder we don't have
499
- full_prompt = prompt_template
500
- logger.warning(f"Template for {content_type} has unknown placeholder {e}")
501
-
502
- text = await _call_groq(full_prompt)
503
- if not text:
504
- return {"error": "Groq failed to generate text."}
505
-
506
- return {
507
- "text": _clean_markdown(text) + _footer(channel_key, content_type)
508
- }
509
-
510
-
511
- async def generate_content(content_type: str, channel_key: str) -> str:
512
- gen = CONTENT_GENERATORS.get(content_type)
513
- if not gen:
514
- # Try generic generator for custom types
515
- return await generate_generic_ai_post(content_type, channel_key)
516
- return await gen(channel_key)
 
 
 
 
 
 
1
+ import logging
2
+ import random
3
+ import traceback
4
+ import asyncio
5
+ import json
6
+ import re
7
+ from datetime import datetime
8
+ import google.generativeai as genai
9
+ from google.generativeai.types import GenerationConfig
10
+
11
+ from config import (
12
+ GEMINI_API_KEY, GEMINI_MODEL, GEMINI_MAX_TOKENS,
13
+ GEMINI_TEMPERATURE, SUBJECT_ROTATION
14
+ )
15
+ from content.config_manager import config_manager
16
+ from content.syllabus_manager import syllabus_manager
17
+ from content.template_manager import template_manager
18
+ from content.history import pick_fresh_chapter, archive_weekly_post
19
+
20
+ logger = logging.getLogger(__name__)
21
+
22
+ # Initialize Gemini Client
23
+ genai.configure(api_key=GEMINI_API_KEY)
24
+
25
+
26
+ # ─────────────────────────────────────────────
27
+ # Helpers
28
+ # ─────────────────────────────────────────────
29
+
30
+ def _clean_markdown(text: str) -> str:
31
+ """
32
+ Cleanup to prevent Telegram Markdown parse errors.
33
+ Handles unclosed code blocks, bold, italic, and inline-code markers.
34
+ Also enforces the 4096-character Telegram message limit.
35
+ """
36
+ if not text:
37
+ return ""
38
+
39
+ # --- 1. Close unclosed triple-backtick code blocks ---
40
+ if text.count("```") % 2 != 0:
41
+ text += "\n```"
42
+
43
+ # --- 2. Close unclosed inline backtick spans ---
44
+ if text.count("`") % 2 != 0:
45
+ text += "`"
46
+
47
+ # --- 3. Close unclosed bold markers (*) ---
48
+ # Only count * that are NOT part of *** or ** patterns
49
+ # Simple heuristic: strip code blocks first, then count remaining *
50
+ temp = re.sub(r'```.*?```', '', text, flags=re.DOTALL) # remove code blocks
51
+ temp = re.sub(r'`[^`]*`', '', temp) # remove inline code
52
+ if temp.count("*") % 2 != 0:
53
+ text += "*"
54
+
55
+ # --- 4. Close unclosed italic underscores (_) outside code spans ---
56
+ temp2 = re.sub(r'```.*?```', '', text, flags=re.DOTALL)
57
+ temp2 = re.sub(r'`[^`]*`', '', temp2)
58
+ if temp2.count("_") % 2 != 0:
59
+ text += "\_"
60
+
61
+ # --- 5. Truncate to Telegram's 4096-char hard limit ---
62
+ if len(text) > 4000:
63
+ text = text[:3997] + "..."
64
+
65
+ return text
66
+
67
+ def _today() -> str:
68
+ return datetime.now().strftime("%A")
69
+
70
+
71
+ async def _call_gemini(prompt: str) -> str:
72
+ """Wrapper for Gemini API calls with retry logic for rate limits."""
73
+ max_retries = 3
74
+ base_delay = 2 # Gemini free tier might need some delay on rate limits
75
+
76
+ for attempt in range(max_retries):
77
+ try:
78
+ model = genai.GenerativeModel(
79
+ model_name=GEMINI_MODEL,
80
+ system_instruction=template_manager.system_prompt
81
+ )
82
+ response = await model.generate_content_async(
83
+ prompt,
84
+ generation_config=GenerationConfig(
85
+ max_output_tokens=GEMINI_MAX_TOKENS,
86
+ temperature=GEMINI_TEMPERATURE,
87
+ )
88
+ )
89
+
90
+ content = response.text
91
+ if not content:
92
+ logger.warning(f"Gemini returned empty response (Attempt {attempt+1}/{max_retries})")
93
+ if attempt < max_retries - 1:
94
+ await asyncio.sleep(base_delay * (2 ** attempt))
95
+ continue
96
+ return None
97
+
98
+ return _clean_markdown(content.strip())
99
+
100
+ except Exception as e:
101
+ err_msg = str(e).lower()
102
+ # Handle rate limits
103
+ if "429" in err_msg or "quota" in err_msg or "rate" in err_msg:
104
+ wait_time = base_delay * (2 ** attempt) + 2
105
+ logger.warning(f"Gemini Rate Limit hit. Retrying in {wait_time:.1f}s... (Attempt {attempt+1}/{max_retries})")
106
+ if attempt < max_retries - 1:
107
+ import asyncio
108
+ await asyncio.sleep(wait_time)
109
+ continue
110
+
111
+ logger.error(f"Gemini API error: {e}
112
+ {traceback.format_exc()}")
113
+ return None
114
+
115
+ return None
116
+
117
+
118
+ def _channel_subjects(channel_key: str) -> list:
119
+ """Return subjects active for this channel on today's rotation, filtered by syllabus availability."""
120
+ channel_cfg = config_manager.channels.get(channel_key, {})
121
+ exam_focus = channel_cfg.get("exam_focus", ["JEE Main"])
122
+
123
+ # Get all subjects available in the syllabus for this exam
124
+ all_syllabus_subjects = set()
125
+ for focus in exam_focus:
126
+ all_syllabus_subjects.update(syllabus_manager.get_all_subjects(focus))
127
+
128
+ ch_subjects = set(channel_cfg.get("subjects", list(all_syllabus_subjects)))
129
+ day_subjects = set(SUBJECT_ROTATION.get(_today(), list(all_syllabus_subjects)))
130
+ active = list(ch_subjects & day_subjects)
131
+ return active if active else list(ch_subjects)
132
+
133
+
134
+ def _pick(channel_key: str, content_type: str) -> tuple:
135
+ """Pick a non-repeating (subject, chapter) pair for this channel + content type."""
136
+ subjects = _channel_subjects(channel_key)
137
+ subject = random.choice(subjects)
138
+ chapter = pick_fresh_chapter(channel_key, content_type, subject)
139
+ return subject, chapter
140
+
141
+
142
+ def _footer(channel_key: str, tag_key: str) -> str:
143
+ cfg = config_manager.channels.get(channel_key, {})
144
+ footer = cfg.get("footer", "✨ *Study Hard, Score High!*")
145
+ hashtag = cfg.get("hashtags", {}).get(tag_key, "")
146
+
147
+ brand = "πŸš€ *Join for more:* @xcrazylearners"
148
+ sep = "━━━━━━━━━━━━━━━━━━"
149
+
150
+ if hashtag:
151
+ return f"\n\n{hashtag}\n{sep}\n{footer}\n{brand}"
152
+ else:
153
+ return f"\n\n{sep}\n{footer}\n{brand}"
154
+
155
+
156
+ def _exam(channel_key: str) -> str:
157
+ exams = config_manager.channels.get(channel_key, {}).get("exam_focus", ["JEE Main"])
158
+ return random.choice(exams)
159
+
160
+ def _difficulty_context(channel_key: str) -> str:
161
+ """Returns a difficulty instruction based on the channel's target exams."""
162
+ cfg = config_manager.channels.get(channel_key, {})
163
+ exams = cfg.get("exam_focus", [])
164
+
165
+ # Class 9/10 focus
166
+ if any(ex in ["Class 9", "Class 10", "NTSE", "Foundation"] for ex in exams):
167
+ return "Difficulty: Foundation/School Level. Focus on basic concepts, definitions, and clear logic. Avoid extremely complex calculus or advanced topics."
168
+
169
+ # JEE Advanced focus
170
+ if "JEE Advanced" in exams:
171
+ return "Difficulty: Advanced/Hard. Use multi-concept problems, challenging numericals, and tricky logic. Focus on deep understanding."
172
+
173
+ # JEE Main / NEET focus (default for competitive)
174
+ return "Difficulty: Competitive (JEE Main/NEET level). Focus on accuracy, speed-based patterns, and standard competitive concepts."
175
+
176
+
177
+ # ─────────────────────────────────────────────
178
+ # 1. PYQ QUESTION (QUIZ MODE)
179
+ # ─────────────────────────────────────────────
180
+
181
+ def _parse_quiz(text: str) -> dict:
182
+ """Extracts quiz components from the AI-generated text."""
183
+ try:
184
+ # Question: Find text between ❓ QUESTION: and (A)
185
+ q_start = text.find("❓ QUESTION:") + len("❓ QUESTION:")
186
+ q_end = text.find("(A)")
187
+ question = text[q_start:q_end].strip()
188
+
189
+ # Truncate question for Telegram (300 chars limit)
190
+ if len(question) > 297:
191
+ question = question[:297] + "..."
192
+
193
+ # Options: (A), (B), (C), (D)
194
+ options = []
195
+ for label in ["(A)", "(B)", "(C)", "(D)"]:
196
+ start = text.find(label) + len(label)
197
+ # Find the next label or the answer line
198
+ next_label = text.find("(B)") if label == "(A)" else (text.find("(C)") if label == "(B)" else (text.find("(D)") if label == "(C)" else text.find("||βœ… ANSWER:")))
199
+ opt_text = text[start:next_label].strip()
200
+ options.append(opt_text[:100]) # Telegram limit: 100 chars per option
201
+
202
+ # Correct Answer Index
203
+ ans_line = text.lower().find("answer: (")
204
+ correct_letter = text[ans_line + len("answer: (") : ans_line + len("answer: (") + 1].upper()
205
+ mapping = {"A": 0, "B": 1, "C": 2, "D": 3}
206
+ correct_index = mapping.get(correct_letter, 0)
207
+
208
+ # Explanation
209
+ e_start = text.find("πŸ’‘ EXPLANATION:") + len("πŸ’‘ EXPLANATION:")
210
+ e_end = text.find("🎯 Difficulty:")
211
+ explanation = text[e_start:e_end].strip()
212
+
213
+ # Truncate explanation for Telegram (200 chars limit)
214
+ if len(explanation) > 197:
215
+ explanation = explanation[:197] + "..."
216
+
217
+ return {
218
+ "question": question,
219
+ "options": options,
220
+ "correct_index": correct_index,
221
+ "explanation": explanation,
222
+ "full_text": text # Still include the full text for fallback/preview
223
+ }
224
+ except Exception as e:
225
+ logger.error(f"Quiz parsing failed: {e}")
226
+ return None
227
+
228
+
229
+ async def generate_pyq_question(channel_key: str) -> dict:
230
+ subject, chapter = _pick(channel_key, "pyq_question")
231
+ exam = _exam(channel_key)
232
+ year = random.randint(2015, 2023)
233
+
234
+ template = template_manager.get_template("pyq_question")
235
+ diff_text = _difficulty_context(channel_key)
236
+ prompt = template.format(
237
+ exam=exam, year=year, chapter=chapter,
238
+ subject=subject.title()
239
+ ) + f"\n\n{diff_text}"
240
+
241
+ raw_text = await _call_gemini(prompt)
242
+ if not raw_text:
243
+ return {"error": "⚠️ Content temporarily unavailable."}
244
+
245
+ quiz_data = _parse_quiz(raw_text)
246
+ if not quiz_data:
247
+ # Fallback to plain text if parsing fails
248
+ return {"text": raw_text + _footer(channel_key, "pyq")}
249
+
250
+ # Return structured dict for the dispatcher
251
+ return {
252
+ "text": raw_text + _footer(channel_key, "pyq"),
253
+ "quiz": quiz_data,
254
+ "type": "quiz"
255
+ }
256
+
257
+
258
+ # ─────────────────────────────────────────────
259
+ # 2. FORMULA SHEET
260
+ # ─────────────────────────────────────────────
261
+
262
+ async def generate_formula_sheet(channel_key: str) -> str:
263
+ subject, chapter = _pick(channel_key, "formula_sheet")
264
+ exam = _exam(channel_key)
265
+
266
+ template = template_manager.get_template("formula_sheet")
267
+ prompt = template.format(exam=exam, chapter=chapter, subject=subject.title())
268
+
269
+ text = await _call_gemini(prompt)
270
+ text = (text or "⚠️ Content temporarily unavailable.")
271
+
272
+ # Archive for Weekly PDF
273
+ if text != "⚠️ Content temporarily unavailable.":
274
+ archive_weekly_post(channel_key, "formula_sheet", subject, chapter, text)
275
+
276
+ return text + _footer(channel_key, "formula")
277
+
278
+
279
+ # ─────────────────────────────────────────────
280
+ # 3. SHORT NOTES
281
+ # ─────────────────────────────────────────────
282
+
283
+ async def generate_short_notes(channel_key: str) -> str:
284
+ subject, chapter = _pick(channel_key, "short_notes")
285
+ exam = _exam(channel_key)
286
+
287
+ template = template_manager.get_template("short_notes")
288
+ prompt = template.format(exam=exam, chapter=chapter, subject=subject.title())
289
+
290
+ text = await _call_gemini(prompt)
291
+ text = (text or "⚠️ Content temporarily unavailable.")
292
+
293
+ # Archive for Weekly PDF
294
+ if text != "⚠️ Content temporarily unavailable.":
295
+ archive_weekly_post(channel_key, "short_notes", subject, chapter, text)
296
+
297
+ return text + _footer(channel_key, "notes")
298
+
299
+
300
+ # ─────────────────────────────────────────────
301
+ # 4. MNEMONIC
302
+ # ─────────────────────────────────────────────
303
+
304
+ async def generate_mnemonic(channel_key: str) -> str:
305
+ subject, chapter = _pick(channel_key, "mnemonic")
306
+
307
+ template = template_manager.get_template("mnemonic")
308
+ prompt = template.format(chapter=chapter, subject=subject.title())
309
+
310
+ text = await _call_gemini(prompt)
311
+ return (text or "⚠️ Content temporarily unavailable.") + _footer(channel_key, "mnemonic")
312
+
313
+
314
+ # ─────────────────────────────────────────────
315
+ # 5. CONCEPT RECAP
316
+ # ─────────────────────────────────────────────
317
+
318
+ async def generate_concept_recap(channel_key: str) -> str:
319
+ subject, chapter = _pick(channel_key, "concept_recap")
320
+ exam = _exam(channel_key)
321
+
322
+ template = template_manager.get_template("concept_recap")
323
+ prompt = template.format(exam=exam, chapter=chapter, subject=subject.title())
324
+
325
+ text = await _call_gemini(prompt)
326
+ return (text or "⚠️ Content temporarily unavailable.") + _footer(channel_key, "recap")
327
+
328
+
329
+ # ─────────────────────────────────────────────
330
+ # 6. MOCK MCQ
331
+ # ─────────────────────────────────────────────
332
+
333
+ async def generate_mock_question(channel_key: str) -> str:
334
+ subject, chapter = _pick(channel_key, "mock_question")
335
+ exam = _exam(channel_key)
336
+
337
+ template = template_manager.get_template("mock_question")
338
+ diff_text = _difficulty_context(channel_key)
339
+ prompt = template.format(exam=exam, chapter=chapter, subject=subject.title()) + f"\n\n{diff_text}"
340
+
341
+ text = await _call_gemini(prompt)
342
+ return (text or "⚠️ Content temporarily unavailable.") + _footer(channel_key, "mock")
343
+
344
+
345
+ # ─────────────────────────────────────────────
346
+ # 7. MOTIVATIONAL
347
+ # ─────────────────────────────────────────────
348
+
349
+ async def generate_motivational(channel_key: str) -> str:
350
+ exam = _exam(channel_key)
351
+
352
+ # Pick a random subject and chapter to make the message specific
353
+ subjects = _channel_subjects(channel_key)
354
+ subject = random.choice(subjects)
355
+ chapter = pick_fresh_chapter(channel_key, "motivational", subject)
356
+
357
+ template = template_manager.get_template("motivational")
358
+ prompt = template.format(exam=exam, subject=subject.title(), chapter=chapter)
359
+
360
+ text = await _call_gemini(prompt)
361
+ cfg = config_manager.channels.get(channel_key, {})
362
+ footer = cfg.get("footer", "")
363
+ return (text or "πŸŒ™ Rest well! See you tomorrow πŸ’ͺ") + (f"\n\n{footer}" if footer else "")
364
+
365
+
366
+ # ─────────────────────────────────────────────
367
+ # 8. MCQ POLL SESSION (10 polls, chapter-wise)
368
+ # ─────────────────────────────────────────────
369
+
370
+ def _parse_mcq_json(text: str) -> list:
371
+ """Extract and repair a JSON array of MCQ dicts from the Gemini response."""
372
+ if not text: return []
373
+
374
+ # 1. Basic Cleaning
375
+ clean = text.strip()
376
+ if clean.startswith("```"):
377
+ clean = re.sub(r'^```(?:json)?\s*', '', clean, flags=re.MULTILINE)
378
+ clean = re.sub(r'\s*```\s*$', '', clean, flags=re.MULTILINE).strip()
379
+
380
+ # 2. Slice to array bounds if possible
381
+ start = clean.find('[')
382
+ if start == -1: return []
383
+
384
+ # Try to find the last ']' - but if it's truncated, we might need to repair it
385
+ end = clean.rfind(']')
386
+
387
+ candidate = clean[start:]
388
+ if end != -1:
389
+ candidate = clean[start:end + 1]
390
+
391
+ # 3. Progressive Repair Strategy
392
+ try:
393
+ return json.loads(candidate)
394
+ except json.JSONDecodeError:
395
+ # AI truncated mid-object? Let's try to fix it.
396
+ # Strategy: Remove everything after the last valid "}," and add "]"
397
+ last_comma = candidate.rfind('},')
398
+ if last_comma != -1:
399
+ try:
400
+ return json.loads(candidate[:last_comma + 1] + "]")
401
+ except: pass
402
+
403
+ # Try finding the last "}" and closing the array
404
+ last_brace = candidate.rfind('}')
405
+ if last_brace != -1:
406
+ try:
407
+ return json.loads(candidate[:last_brace + 1] + "]")
408
+ except: pass
409
+
410
+ return []
411
+
412
+
413
+ async def generate_mcq_session(channel_key: str) -> dict:
414
+ """Generate 10 MCQ Telegram quiz polls for a single chapter."""
415
+ subject, chapter = _pick(channel_key, "mcq_session")
416
+ exam = _exam(channel_key)
417
+
418
+ template = template_manager.get_template("mcq_session")
419
+ diff_text = _difficulty_context(channel_key)
420
+ prompt = template.format(exam=exam, chapter=chapter, subject=subject.title()) + f"\n\n{diff_text}"
421
+
422
+ raw = await _call_gemini(prompt)
423
+ if not raw:
424
+ return {"error": "⚠️ MCQ Session content temporarily unavailable."}
425
+
426
+ questions = _parse_mcq_json(raw)
427
+ MIN_MCQ = 3 # Accept sessions with at least 3 valid questions
428
+ if not questions or len(questions) < MIN_MCQ:
429
+ logger.warning(f"MCQ session got only {len(questions)} questions (need {MIN_MCQ}) β€” retrying once")
430
+ # --- One automatic retry before giving up ---
431
+ raw2 = await _call_gemini(prompt)
432
+ if raw2:
433
+ questions = _parse_mcq_json(raw2)
434
+ if not questions or len(questions) < MIN_MCQ:
435
+ logger.error(f"MCQ session still only {len(questions)} questions after retry β€” giving up")
436
+ return {"error": "⚠️ Could not generate enough MCQs right now. Please retry."}
437
+
438
+ # Clamp to exactly 10
439
+ questions = questions[:10]
440
+
441
+ # Sanitise each question for Telegram limits
442
+ clean = []
443
+ for q in questions:
444
+ opts = [str(o)[:100] for o in q.get("options", [])]
445
+ if len(opts) < 4:
446
+ continue # skip malformed
447
+ clean.append({
448
+ "question": str(q.get("question", ""))[:300],
449
+ "options": opts,
450
+ "correct_index": int(q.get("correct_index", 0)) % 4,
451
+ "explanation": str(q.get("explanation", ""))[:200],
452
+ })
453
+
454
+ return {
455
+ "type": "mcq_session",
456
+ "subject": subject,
457
+ "chapter": chapter,
458
+ "exam": exam,
459
+ "questions": clean,
460
+ }
461
+
462
+
463
+ # ─────────────────────────────────────────────
464
+ # DISPATCHER
465
+ # ─────────────────────────────────────────────
466
+
467
+ CONTENT_GENERATORS = {
468
+ "pyq_question": generate_pyq_question,
469
+ "formula_sheet": generate_formula_sheet,
470
+ "short_notes": generate_short_notes,
471
+ "mnemonic": generate_mnemonic,
472
+ "concept_recap": generate_concept_recap,
473
+ "mock_question": generate_mock_question,
474
+ "motivational": generate_motivational,
475
+ "mcq_session": generate_mcq_session,
476
+ }
477
+
478
+ CONTENT_LABELS = {
479
+ "pyq_question": "πŸ“… Daily PYQ Question",
480
+ "formula_sheet": "πŸ“ Formula Sheet",
481
+ "short_notes": "πŸ“ Short Notes",
482
+ "mnemonic": "🧠 Memory Tricks",
483
+ "concept_recap": "πŸŒ… Concept Recap",
484
+ "mock_question": "🎯 Daily Mock",
485
+ "motivational": "πŸŒ™ Night Motivation",
486
+ "mcq_session": "πŸ§ͺ MCQ Poll Session",
487
+ }
488
+
489
+
490
+ async def generate_generic_ai_post(content_type: str, channel_key: str) -> dict:
491
+ """Fallback generator for user-defined custom content types."""
492
+ prompt_template = template_manager.data["templates"].get(content_type)
493
+ if not prompt_template:
494
+ return {"text": f"❌ No prompt template found for custom type: `{content_type}`"}
495
+
496
+ subject, chapter = _pick(channel_key, content_type)
497
+ exam = _exam(channel_key)
498
+ year = datetime.now().year
499
+
500
+ try:
501
+ full_prompt = prompt_template.format(exam=exam, subject=subject, chapter=chapter, year=year)
502
+ except KeyError as e:
503
+ # Fallback if user uses a placeholder we don't have
504
+ full_prompt = prompt_template
505
+ logger.warning(f"Template for {content_type} has unknown placeholder {e}")
506
+
507
+ text = await _call_gemini(full_prompt)
508
+ if not text:
509
+ return {"error": "Gemini failed to generate text."}
510
+
511
+ return {
512
+ "text": _clean_markdown(text) + _footer(channel_key, content_type)
513
+ }
514
+
515
+
516
+ async def generate_content(content_type: str, channel_key: str) -> str:
517
+ gen = CONTENT_GENERATORS.get(content_type)
518
+ if not gen:
519
+ # Try generic generator for custom types
520
+ return await generate_generic_ai_post(content_type, channel_key)
521
+ return await gen(channel_key)
handlers/commands.py CHANGED
@@ -498,21 +498,21 @@ async def healthcheck_command(update: Update, context: ContextTypes.DEFAULT_TYPE
498
  except Exception as e:
499
  results.append(f"❌ *Scheduler:* FAILED β€” `{e}`")
500
 
501
- # ─── 2. Groq API ───
502
  try:
503
- from groq import AsyncGroq
504
- from config import GROQ_API_KEY, GROQ_MODEL
505
- groq_client = AsyncGroq(api_key=GROQ_API_KEY)
506
- test = await groq_client.chat.completions.create(
507
- model=GROQ_MODEL,
508
- messages=[{"role": "user", "content": "Reply with just: OK"}],
509
- max_tokens=5,
510
- temperature=0
511
  )
512
- reply = test.choices[0].message.content.strip()
513
- results.append(f"βœ… *Groq API:* Online β€” Model: `{GROQ_MODEL}` β€” Reply: `{reply}`")
514
  except Exception as e:
515
- results.append(f"❌ *Groq API:* FAILED β€” `{str(e)[:80]}`")
516
 
517
  # ─── 3. Gist / Remote Storage ───
518
  try:
 
498
  except Exception as e:
499
  results.append(f"❌ *Scheduler:* FAILED β€” `{e}`")
500
 
501
+ # ─── 2. Gemini API ───
502
  try:
503
+ import google.generativeai as genai
504
+ from google.generativeai.types import GenerationConfig
505
+ from config import GEMINI_API_KEY, GEMINI_MODEL
506
+ genai.configure(api_key=GEMINI_API_KEY)
507
+ model = genai.GenerativeModel(GEMINI_MODEL)
508
+ test = await model.generate_content_async(
509
+ "Reply with just: OK",
510
+ generation_config=GenerationConfig(max_output_tokens=5, temperature=0.0)
511
  )
512
+ reply = test.text.strip()
513
+ results.append(f"βœ… *Gemini API:* Online β€” Model: `{GEMINI_MODEL}` β€” Reply: `{reply}`")
514
  except Exception as e:
515
+ results.append(f"❌ *Gemini API:* FAILED β€” `{str(e)[:80]}`")
516
 
517
  # ─── 3. Gist / Remote Storage ───
518
  try:
refactor.py ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ import re
3
+
4
+ file = 'content/generator.py'
5
+ with open(file, 'r', encoding='utf-8') as f:
6
+ code = f.read()
7
+
8
+ code = code.replace('from groq import AsyncGroq', 'import google.generativeai as genai\nfrom google.generativeai.types import GenerationConfig')
9
+ code = code.replace('GROQ_API_KEY, GROQ_MODEL, GROQ_MAX_TOKENS,', 'GEMINI_API_KEY, GEMINI_MODEL, GEMINI_MAX_TOKENS,')
10
+ code = code.replace('GROQ_TEMPERATURE, SUBJECT_ROTATION', 'GEMINI_TEMPERATURE, SUBJECT_ROTATION')
11
+ code = code.replace('# Initialize Groq Client\nclient = AsyncGroq(api_key=GROQ_API_KEY)', '# Initialize Gemini Client\ngenai.configure(api_key=GEMINI_API_KEY)')
12
+ code = code.replace('_call_groq', '_call_gemini')
13
+
14
+ old_func_pattern = re.compile(r'async def _call_gemini\(prompt: str\) -> str:.*?(?=\ndef _channel_subjects)', re.DOTALL)
15
+ new_func = """async def _call_gemini(prompt: str) -> str:
16
+ \"\"\"Wrapper for Gemini API calls with retry logic for rate limits.\"\"\"
17
+ max_retries = 3
18
+ base_delay = 2 # Gemini free tier might need some delay on rate limits
19
+
20
+ for attempt in range(max_retries):
21
+ try:
22
+ model = genai.GenerativeModel(
23
+ model_name=GEMINI_MODEL,
24
+ system_instruction=template_manager.system_prompt
25
+ )
26
+ response = await model.generate_content_async(
27
+ prompt,
28
+ generation_config=GenerationConfig(
29
+ max_output_tokens=GEMINI_MAX_TOKENS,
30
+ temperature=GEMINI_TEMPERATURE,
31
+ )
32
+ )
33
+
34
+ content = response.text
35
+ if not content:
36
+ logger.warning(f"Gemini returned empty response (Attempt {attempt+1}/{max_retries})")
37
+ if attempt < max_retries - 1:
38
+ await asyncio.sleep(base_delay * (2 ** attempt))
39
+ continue
40
+ return None
41
+
42
+ return _clean_markdown(content.strip())
43
+
44
+ except Exception as e:
45
+ err_msg = str(e).lower()
46
+ # Handle rate limits
47
+ if "429" in err_msg or "quota" in err_msg or "rate" in err_msg:
48
+ wait_time = base_delay * (2 ** attempt) + 2
49
+ logger.warning(f"Gemini Rate Limit hit. Retrying in {wait_time:.1f}s... (Attempt {attempt+1}/{max_retries})")
50
+ if attempt < max_retries - 1:
51
+ import asyncio
52
+ await asyncio.sleep(wait_time)
53
+ continue
54
+
55
+ logger.error(f"Gemini API error: {e}\\n{traceback.format_exc()}")
56
+ return None
57
+
58
+ return None
59
+
60
+ """
61
+ code = old_func_pattern.sub(new_func, code)
62
+ # Fix remaining Groq terms in logging/comments EXCEPT in imports if any
63
+ code = code.replace('Groq', 'Gemini').replace('groq', 'gemini')
64
+ code = code.replace('import google.geminiativeai as genai', 'import google.generativeai as genai')
65
+ code = code.replace('from google.geminiativeai.types', 'from google.generativeai.types')
66
+
67
+ with open(file, 'w', encoding='utf-8') as f:
68
+ f.write(code)
69
+ print("generator.py refactored!")
requirements.txt CHANGED
@@ -2,6 +2,6 @@ python-telegram-bot>=20.0
2
  apscheduler>=3.10.0
3
  pytz
4
  python-dotenv
5
- groq>=0.9.0
6
  requests
7
  fpdf2>=2.7.0
 
2
  apscheduler>=3.10.0
3
  pytz
4
  python-dotenv
5
+ google-generativeai>=0.5.2
6
  requests
7
  fpdf2>=2.7.0
verify_gemini.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ from dotenv import load_dotenv
4
+
5
+ # Ensure packages are findable
6
+ sys.path.append(os.getcwd())
7
+
8
+ load_dotenv()
9
+
10
+ import asyncio
11
+ from content.generator import generate_content
12
+
13
+ print("Testing content generation with Groq...")
14
+ try:
15
+ # Attempt to generate a PYQ for jee_main
16
+ result = asyncio.run(generate_content("pyq_question", "jee_main"))
17
+ if isinstance(result, dict) and ("error" in result or "⚠️" in str(result)):
18
+ print("❌ Generation failed. Check logs.")
19
+ print(result)
20
+ elif isinstance(result, str) and ("⚠️" in result or "❌" in result):
21
+ print("❌ Generation failed. Check logs.")
22
+ print(result)
23
+ else:
24
+ print("βœ… Groq generation successful!")
25
+ print("-" * 30)
26
+ # Print string or text content of dict
27
+ text_content = result.get("text", str(result)) if isinstance(result, dict) else result
28
+ print(text_content[:300] + "...")
29
+ except Exception as e:
30
+ print(f"❌ Critical error during test: {e}")
web_app/dashboard.html CHANGED
@@ -1340,7 +1340,7 @@ async function runHealthCheck() {
1340
  const iconOk = 'βœ…'; const iconErr = '❌';
1341
  const rows = Object.entries(d.checks).map(([name, r]) => `
1342
  <div class="health-row">
1343
- <div><div class="health-label">${{groq:'πŸ€– Groq AI',scheduler:'πŸ“… Scheduler',telegram:'πŸ“± Telegram API'}[name]||name}</div>
1344
  <div class="health-msg">${r.msg}</div></div>
1345
  <span style="font-size:20px">${r.ok ? iconOk : iconErr}</span>
1346
  </div>`).join('');
 
1340
  const iconOk = 'βœ…'; const iconErr = '❌';
1341
  const rows = Object.entries(d.checks).map(([name, r]) => `
1342
  <div class="health-row">
1343
+ <div><div class="health-label">${{gemini:'πŸ€– Gemini AI',scheduler:'πŸ“… Scheduler',telegram:'πŸ“± Telegram API'}[name]||name}</div>
1344
  <div class="health-msg">${r.msg}</div></div>
1345
  <span style="font-size:20px">${r.ok ? iconOk : iconErr}</span>
1346
  </div>`).join('');