Spaces:
Sleeping
Sleeping
fix: cascata modelli rifatta (Llama spariti da Groq) + strip blocchi think
Browse files
README.md
CHANGED
|
@@ -1,81 +1,105 @@
|
|
| 1 |
-
---
|
| 2 |
-
title: IG Comment Gen
|
| 3 |
-
emoji: 💬
|
| 4 |
-
colorFrom: indigo
|
| 5 |
-
colorTo: pink
|
| 6 |
-
sdk: docker
|
| 7 |
-
app_port: 7860
|
| 8 |
-
pinned: false
|
| 9 |
-
license: mit
|
| 10 |
-
short_description: AI-generated Instagram comments (Italian, fitness niche)
|
| 11 |
-
---
|
| 12 |
-
|
| 13 |
-
# IG Comment Gen
|
| 14 |
-
|
| 15 |
-
Space che genera un singolo commento breve e naturale per un post Instagram, dato:
|
| 16 |
-
- `caption` del post
|
| 17 |
-
- `media_type` (`photo` / `video` / `reel` / `carousel` / `igtv`)
|
| 18 |
-
- `target_username` (opzionale, per personalizzare)
|
| 19 |
-
- `hint` (opzionale, contesto di tono/nicchia)
|
| 20 |
-
- `language` (default: Italian)
|
| 21 |
-
|
| 22 |
-
Chiamato da `instagram-bot-custom` (GramAddict) come sostituto della vecchia integrazione Gemini in `ai_comment.py`.
|
| 23 |
-
|
| 24 |
-
## Backend
|
| 25 |
-
|
| 26 |
-
Usa **Groq API** direttamente (`api.groq.com/openai/v1`, OpenAI-compat) con cascata modelli:
|
| 27 |
-
|
| 28 |
-
1. `
|
| 29 |
-
2. `
|
| 30 |
-
3. `
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
``
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
``
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
title: IG Comment Gen
|
| 3 |
+
emoji: 💬
|
| 4 |
+
colorFrom: indigo
|
| 5 |
+
colorTo: pink
|
| 6 |
+
sdk: docker
|
| 7 |
+
app_port: 7860
|
| 8 |
+
pinned: false
|
| 9 |
+
license: mit
|
| 10 |
+
short_description: AI-generated Instagram comments (Italian, fitness niche)
|
| 11 |
+
---
|
| 12 |
+
|
| 13 |
+
# IG Comment Gen
|
| 14 |
+
|
| 15 |
+
Space che genera un singolo commento breve e naturale per un post Instagram, dato:
|
| 16 |
+
- `caption` del post
|
| 17 |
+
- `media_type` (`photo` / `video` / `reel` / `carousel` / `igtv`)
|
| 18 |
+
- `target_username` (opzionale, per personalizzare)
|
| 19 |
+
- `hint` (opzionale, contesto di tono/nicchia)
|
| 20 |
+
- `language` (default: Italian)
|
| 21 |
+
|
| 22 |
+
Chiamato da `instagram-bot-custom` (GramAddict) come sostituto della vecchia integrazione Gemini in `ai_comment.py`.
|
| 23 |
+
|
| 24 |
+
## Backend
|
| 25 |
+
|
| 26 |
+
Usa **Groq API** direttamente (`api.groq.com/openai/v1`, OpenAI-compat) con cascata modelli:
|
| 27 |
+
|
| 28 |
+
1. `openai/gpt-oss-120b` — primary
|
| 29 |
+
2. `qwen/qwen3.6-27b` — fallback, ottimo italiano
|
| 30 |
+
3. `openai/gpt-oss-20b` — fallback leggero
|
| 31 |
+
|
| 32 |
+
Tutti rispondono sotto **0.15s**.
|
| 33 |
+
|
| 34 |
+
> **Attenzione ai nomi dei modelli.** Il catalogo Groq cambia: il 19/08/2026 i
|
| 35 |
+
> Llama (`llama-3.3-70b-versatile`, `llama-3.1-8b-instant`) sono spariti con
|
| 36 |
+
> 404 `model_not_found` e `gemma2-9b-it` è stata decommissionata, lasciando lo
|
| 37 |
+
> Space muto. Se ricompaiono errori 404/400 sui modelli, controlla il catalogo
|
| 38 |
+
> con `GET /openai/v1/models` e aggiorna `MODEL_CASCADE`.
|
| 39 |
+
|
| 40 |
+
Sono tutti modelli **reasoning**: vanno chiamati con `reasoning_effort`,
|
| 41 |
+
altrimenti scrivono il ragionamento dentro `content` (Qwen usa
|
| 42 |
+
`<think>…</think>`) o lasciano `content` vuoto. Il valore giusto cambia da
|
| 43 |
+
modello a modello (`none` per Qwen, `low` per gpt-oss), quindi ogni voce di
|
| 44 |
+
`MODEL_CASCADE` porta i suoi `params`. Come rete di sicurezza i sanitize
|
| 45 |
+
rimuovono comunque i blocchi `<think>`.
|
| 46 |
+
|
| 47 |
+
Free tier Groq: quota giornaliera generosa, ampiamente sufficiente per un bot IG.
|
| 48 |
+
|
| 49 |
+
Se tutti falliscono, l'endpoint risponde `{ "comment": null }` e il bot ricade sul suo `comments_list.txt`.
|
| 50 |
+
|
| 51 |
+
## Secrets richiesti (HF Space Settings → Repository secrets)
|
| 52 |
+
|
| 53 |
+
| Nome | Obbligatorio | Descrizione |
|
| 54 |
+
|---|---|---|
|
| 55 |
+
| `GROQ_API_KEY` | ✅ | Groq API key (free tier). Crea su https://console.groq.com/keys. |
|
| 56 |
+
| `SPACE_API_KEY` | ❌ | Se settato, l'endpoint `/api/generate` richiede header `Authorization: Bearer <SPACE_API_KEY>`. Senza, l'endpoint è aperto (comodo per test iniziale). |
|
| 57 |
+
|
| 58 |
+
## API
|
| 59 |
+
|
| 60 |
+
### Endpoint
|
| 61 |
+
|
| 62 |
+
| Endpoint | Cosa fa |
|
| 63 |
+
|---|---|
|
| 64 |
+
| `POST /api/generate` | commento sotto a un post |
|
| 65 |
+
| `POST /api/generate_dm` | DM di apertura dopo il follow-back |
|
| 66 |
+
| `POST /api/answer_question` | risposta a una domanda ricevuta nel box domande delle storie |
|
| 67 |
+
| `GET /api/health` | stato, backend e modelli in cascata |
|
| 68 |
+
|
| 69 |
+
### `POST /api/generate`
|
| 70 |
+
|
| 71 |
+
```json
|
| 72 |
+
{
|
| 73 |
+
"caption": "3 anni di allenamento continuo, ecco i risultati...",
|
| 74 |
+
"media_type": "reel",
|
| 75 |
+
"target_username": "il.pump.quotidiano",
|
| 76 |
+
"hint": "coach fitness, tono cameratesco",
|
| 77 |
+
"language": "Italian"
|
| 78 |
+
}
|
| 79 |
+
```
|
| 80 |
+
|
| 81 |
+
Response:
|
| 82 |
+
|
| 83 |
+
```json
|
| 84 |
+
{
|
| 85 |
+
"comment": "3 anni di costanza si vedono tutti in questo confronto",
|
| 86 |
+
"model_used": "openai/gpt-oss-120b:fastest",
|
| 87 |
+
"latency_ms": 612,
|
| 88 |
+
"attempts": 1
|
| 89 |
+
}
|
| 90 |
+
```
|
| 91 |
+
|
| 92 |
+
Errori (`400`/`401`/`503`): `{ "comment": null, "error": "..." }`.
|
| 93 |
+
|
| 94 |
+
## Uso locale (test)
|
| 95 |
+
|
| 96 |
+
```bash
|
| 97 |
+
export HF_TOKEN=hf_xxx
|
| 98 |
+
pip install -r requirements.txt
|
| 99 |
+
python app.py
|
| 100 |
+
# UI Gradio su http://localhost:7860, API su http://localhost:7860/api/generate
|
| 101 |
+
```
|
| 102 |
+
|
| 103 |
+
## Regole del prompt
|
| 104 |
+
|
| 105 |
+
14 regole assertive che replicano lo stile che serve al bot (no emoji, no #, no !, no first-person, no complimenti generici). Vedi `app.py` → `_build_prompt`.
|
app.py
CHANGED
|
@@ -1,946 +1,990 @@
|
|
| 1 |
-
"""
|
| 2 |
-
IG Comment Gen - HuggingFace Space
|
| 3 |
-
|
| 4 |
-
Genera un commento breve, naturale, in italiano per un post Instagram,
|
| 5 |
-
usando l'API Groq (OpenAI-compatible) direttamente. NON usa piu' HF Inference
|
| 6 |
-
Providers perche' il free tier PRO non include credit Inference (solo ZeroGPU),
|
| 7 |
-
quindi ogni chiamata dava 402 Payment Required.
|
| 8 |
-
|
| 9 |
-
Backend cascade (Groq,
|
| 10 |
-
1.
|
| 11 |
-
2.
|
| 12 |
-
3.
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
import
|
| 26 |
-
|
| 27 |
-
import
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
import
|
| 31 |
-
from
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
#
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
#
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
def
|
| 161 |
-
"""
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
#
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
""
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
"""
|
| 197 |
-
if not
|
| 198 |
-
return
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
|
| 298 |
-
|
| 299 |
-
|
| 300 |
-
|
| 301 |
-
|
| 302 |
-
|
| 303 |
-
|
| 304 |
-
|
| 305 |
-
|
| 306 |
-
|
| 307 |
-
|
| 308 |
-
|
| 309 |
-
|
| 310 |
-
"
|
| 311 |
-
|
| 312 |
-
"
|
| 313 |
-
|
| 314 |
-
|
| 315 |
-
|
| 316 |
-
|
| 317 |
-
|
| 318 |
-
|
| 319 |
-
|
| 320 |
-
|
| 321 |
-
|
| 322 |
-
|
| 323 |
-
|
| 324 |
-
|
| 325 |
-
|
| 326 |
-
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
|
| 330 |
-
|
| 331 |
-
|
| 332 |
-
|
| 333 |
-
|
| 334 |
-
|
| 335 |
-
|
| 336 |
-
|
| 337 |
-
|
| 338 |
-
|
| 339 |
-
|
| 340 |
-
|
| 341 |
-
|
| 342 |
-
|
| 343 |
-
|
| 344 |
-
|
| 345 |
-
|
| 346 |
-
|
| 347 |
-
|
| 348 |
-
|
| 349 |
-
|
| 350 |
-
|
| 351 |
-
|
| 352 |
-
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
|
| 356 |
-
|
| 357 |
-
|
| 358 |
-
|
| 359 |
-
|
| 360 |
-
|
| 361 |
-
|
| 362 |
-
|
| 363 |
-
|
| 364 |
-
|
| 365 |
-
|
| 366 |
-
|
| 367 |
-
|
| 368 |
-
|
| 369 |
-
|
| 370 |
-
|
| 371 |
-
|
| 372 |
-
|
| 373 |
-
|
| 374 |
-
|
| 375 |
-
|
| 376 |
-
|
| 377 |
-
|
| 378 |
-
|
| 379 |
-
|
| 380 |
-
|
| 381 |
-
|
| 382 |
-
|
| 383 |
-
|
| 384 |
-
|
| 385 |
-
|
| 386 |
-
|
| 387 |
-
|
| 388 |
-
|
| 389 |
-
|
| 390 |
-
|
| 391 |
-
|
| 392 |
-
|
| 393 |
-
|
| 394 |
-
|
| 395 |
-
|
| 396 |
-
|
| 397 |
-
|
| 398 |
-
|
| 399 |
-
|
| 400 |
-
|
| 401 |
-
|
| 402 |
-
|
| 403 |
-
f"
|
| 404 |
-
|
| 405 |
-
|
| 406 |
-
|
| 407 |
-
|
| 408 |
-
|
| 409 |
-
|
| 410 |
-
|
| 411 |
-
|
| 412 |
-
|
| 413 |
-
|
| 414 |
-
|
| 415 |
-
|
| 416 |
-
|
| 417 |
-
|
| 418 |
-
|
| 419 |
-
|
| 420 |
-
|
| 421 |
-
|
| 422 |
-
|
| 423 |
-
|
| 424 |
-
|
| 425 |
-
"""
|
| 426 |
-
|
| 427 |
-
|
| 428 |
-
|
| 429 |
-
|
| 430 |
-
|
| 431 |
-
|
| 432 |
-
|
| 433 |
-
|
| 434 |
-
|
| 435 |
-
|
| 436 |
-
|
| 437 |
-
|
| 438 |
-
|
| 439 |
-
|
| 440 |
-
|
| 441 |
-
|
| 442 |
-
|
| 443 |
-
|
| 444 |
-
|
| 445 |
-
|
| 446 |
-
|
| 447 |
-
|
| 448 |
-
|
| 449 |
-
|
| 450 |
-
|
| 451 |
-
|
| 452 |
-
|
| 453 |
-
|
| 454 |
-
|
| 455 |
-
|
| 456 |
-
|
| 457 |
-
|
| 458 |
-
|
| 459 |
-
|
| 460 |
-
|
| 461 |
-
|
| 462 |
-
|
| 463 |
-
|
| 464 |
-
|
| 465 |
-
|
| 466 |
-
|
| 467 |
-
|
| 468 |
-
|
| 469 |
-
|
| 470 |
-
|
| 471 |
-
|
| 472 |
-
|
| 473 |
-
|
| 474 |
-
|
| 475 |
-
|
| 476 |
-
|
| 477 |
-
|
| 478 |
-
|
| 479 |
-
|
| 480 |
-
|
| 481 |
-
|
| 482 |
-
|
| 483 |
-
|
| 484 |
-
|
| 485 |
-
|
| 486 |
-
|
| 487 |
-
|
| 488 |
-
|
| 489 |
-
|
| 490 |
-
|
| 491 |
-
|
| 492 |
-
|
| 493 |
-
|
| 494 |
-
|
| 495 |
-
|
| 496 |
-
|
| 497 |
-
|
| 498 |
-
|
| 499 |
-
|
| 500 |
-
|
| 501 |
-
|
| 502 |
-
|
| 503 |
-
|
| 504 |
-
|
| 505 |
-
|
| 506 |
-
|
| 507 |
-
|
| 508 |
-
|
| 509 |
-
|
| 510 |
-
|
| 511 |
-
|
| 512 |
-
|
| 513 |
-
|
| 514 |
-
|
| 515 |
-
|
| 516 |
-
|
| 517 |
-
|
| 518 |
-
|
| 519 |
-
|
| 520 |
-
|
| 521 |
-
|
| 522 |
-
|
| 523 |
-
|
| 524 |
-
|
| 525 |
-
|
| 526 |
-
|
| 527 |
-
|
| 528 |
-
|
| 529 |
-
|
| 530 |
-
|
| 531 |
-
|
| 532 |
-
|
| 533 |
-
|
| 534 |
-
|
| 535 |
-
|
| 536 |
-
|
| 537 |
-
|
| 538 |
-
|
| 539 |
-
|
| 540 |
-
|
| 541 |
-
|
| 542 |
-
|
| 543 |
-
|
| 544 |
-
|
| 545 |
-
|
| 546 |
-
|
| 547 |
-
|
| 548 |
-
|
| 549 |
-
|
| 550 |
-
|
| 551 |
-
|
| 552 |
-
|
| 553 |
-
|
| 554 |
-
|
| 555 |
-
|
| 556 |
-
|
| 557 |
-
|
| 558 |
-
|
| 559 |
-
|
| 560 |
-
|
| 561 |
-
|
| 562 |
-
|
| 563 |
-
|
| 564 |
-
|
| 565 |
-
|
| 566 |
-
|
| 567 |
-
|
| 568 |
-
|
| 569 |
-
|
| 570 |
-
|
| 571 |
-
|
| 572 |
-
|
| 573 |
-
|
| 574 |
-
|
| 575 |
-
|
| 576 |
-
|
| 577 |
-
|
| 578 |
-
|
| 579 |
-
|
| 580 |
-
|
| 581 |
-
|
| 582 |
-
|
| 583 |
-
|
| 584 |
-
|
| 585 |
-
|
| 586 |
-
|
| 587 |
-
|
| 588 |
-
|
| 589 |
-
|
| 590 |
-
|
| 591 |
-
|
| 592 |
-
|
| 593 |
-
|
| 594 |
-
|
| 595 |
-
|
| 596 |
-
|
| 597 |
-
|
| 598 |
-
|
| 599 |
-
|
| 600 |
-
|
| 601 |
-
|
| 602 |
-
|
| 603 |
-
|
| 604 |
-
|
| 605 |
-
|
| 606 |
-
|
| 607 |
-
|
| 608 |
-
|
| 609 |
-
|
| 610 |
-
|
| 611 |
-
|
| 612 |
-
|
| 613 |
-
|
| 614 |
-
|
| 615 |
-
|
| 616 |
-
|
| 617 |
-
|
| 618 |
-
|
| 619 |
-
|
| 620 |
-
|
| 621 |
-
|
| 622 |
-
|
| 623 |
-
|
| 624 |
-
|
| 625 |
-
|
| 626 |
-
|
| 627 |
-
|
| 628 |
-
|
| 629 |
-
|
| 630 |
-
|
| 631 |
-
|
| 632 |
-
|
| 633 |
-
|
| 634 |
-
|
| 635 |
-
|
| 636 |
-
|
| 637 |
-
|
| 638 |
-
|
| 639 |
-
|
| 640 |
-
|
| 641 |
-
|
| 642 |
-
|
| 643 |
-
|
| 644 |
-
|
| 645 |
-
return
|
| 646 |
-
|
| 647 |
-
|
| 648 |
-
|
| 649 |
-
|
| 650 |
-
|
| 651 |
-
|
| 652 |
-
|
| 653 |
-
|
| 654 |
-
) ->
|
| 655 |
-
"""
|
| 656 |
-
|
| 657 |
-
|
| 658 |
-
|
| 659 |
-
|
| 660 |
-
|
| 661 |
-
|
| 662 |
-
|
| 663 |
-
|
| 664 |
-
|
| 665 |
-
|
| 666 |
-
|
| 667 |
-
|
| 668 |
-
|
| 669 |
-
|
| 670 |
-
|
| 671 |
-
|
| 672 |
-
|
| 673 |
-
|
| 674 |
-
|
| 675 |
-
|
| 676 |
-
|
| 677 |
-
|
| 678 |
-
|
| 679 |
-
|
| 680 |
-
|
| 681 |
-
|
| 682 |
-
|
| 683 |
-
|
| 684 |
-
|
| 685 |
-
|
| 686 |
-
|
| 687 |
-
|
| 688 |
-
|
| 689 |
-
|
| 690 |
-
|
| 691 |
-
|
| 692 |
-
|
| 693 |
-
|
| 694 |
-
|
| 695 |
-
|
| 696 |
-
|
| 697 |
-
|
| 698 |
-
|
| 699 |
-
|
| 700 |
-
|
| 701 |
-
|
| 702 |
-
|
| 703 |
-
|
| 704 |
-
|
| 705 |
-
|
| 706 |
-
|
| 707 |
-
|
| 708 |
-
|
| 709 |
-
|
| 710 |
-
|
| 711 |
-
|
| 712 |
-
|
| 713 |
-
|
| 714 |
-
|
| 715 |
-
|
| 716 |
-
|
| 717 |
-
|
| 718 |
-
|
| 719 |
-
|
| 720 |
-
|
| 721 |
-
|
| 722 |
-
|
| 723 |
-
|
| 724 |
-
|
| 725 |
-
|
| 726 |
-
|
| 727 |
-
|
| 728 |
-
|
| 729 |
-
|
| 730 |
-
|
| 731 |
-
|
| 732 |
-
|
| 733 |
-
|
| 734 |
-
|
| 735 |
-
|
| 736 |
-
|
| 737 |
-
|
| 738 |
-
|
| 739 |
-
|
| 740 |
-
|
| 741 |
-
|
| 742 |
-
|
| 743 |
-
|
| 744 |
-
|
| 745 |
-
|
| 746 |
-
|
| 747 |
-
|
| 748 |
-
|
| 749 |
-
|
| 750 |
-
|
| 751 |
-
|
| 752 |
-
|
| 753 |
-
|
| 754 |
-
|
| 755 |
-
|
| 756 |
-
|
| 757 |
-
|
| 758 |
-
|
| 759 |
-
|
| 760 |
-
|
| 761 |
-
|
| 762 |
-
|
| 763 |
-
|
| 764 |
-
|
| 765 |
-
|
| 766 |
-
|
| 767 |
-
|
| 768 |
-
|
| 769 |
-
|
| 770 |
-
|
| 771 |
-
|
| 772 |
-
|
| 773 |
-
|
| 774 |
-
|
| 775 |
-
|
| 776 |
-
|
| 777 |
-
|
| 778 |
-
|
| 779 |
-
|
| 780 |
-
|
| 781 |
-
|
| 782 |
-
|
| 783 |
-
|
| 784 |
-
|
| 785 |
-
|
| 786 |
-
|
| 787 |
-
|
| 788 |
-
|
| 789 |
-
|
| 790 |
-
|
| 791 |
-
|
| 792 |
-
|
| 793 |
-
|
| 794 |
-
|
| 795 |
-
|
| 796 |
-
|
| 797 |
-
|
| 798 |
-
|
| 799 |
-
|
| 800 |
-
|
| 801 |
-
|
| 802 |
-
|
| 803 |
-
|
| 804 |
-
|
| 805 |
-
|
| 806 |
-
|
| 807 |
-
|
| 808 |
-
|
| 809 |
-
|
| 810 |
-
|
| 811 |
-
|
| 812 |
-
|
| 813 |
-
|
| 814 |
-
|
| 815 |
-
|
| 816 |
-
|
| 817 |
-
|
| 818 |
-
|
| 819 |
-
|
| 820 |
-
|
| 821 |
-
|
| 822 |
-
|
| 823 |
-
|
| 824 |
-
|
| 825 |
-
|
| 826 |
-
|
| 827 |
-
|
| 828 |
-
|
| 829 |
-
|
| 830 |
-
|
| 831 |
-
|
| 832 |
-
|
| 833 |
-
authorization
|
| 834 |
-
|
| 835 |
-
|
| 836 |
-
|
| 837 |
-
|
| 838 |
-
|
| 839 |
-
|
| 840 |
-
|
| 841 |
-
|
| 842 |
-
|
| 843 |
-
|
| 844 |
-
|
| 845 |
-
|
| 846 |
-
|
| 847 |
-
|
| 848 |
-
|
| 849 |
-
|
| 850 |
-
|
| 851 |
-
|
| 852 |
-
|
| 853 |
-
|
| 854 |
-
|
| 855 |
-
|
| 856 |
-
|
| 857 |
-
|
| 858 |
-
|
| 859 |
-
|
| 860 |
-
|
| 861 |
-
|
| 862 |
-
|
| 863 |
-
|
| 864 |
-
|
| 865 |
-
|
| 866 |
-
|
| 867 |
-
|
| 868 |
-
|
| 869 |
-
|
| 870 |
-
|
| 871 |
-
|
| 872 |
-
|
| 873 |
-
|
| 874 |
-
|
| 875 |
-
|
| 876 |
-
|
| 877 |
-
|
| 878 |
-
|
| 879 |
-
|
| 880 |
-
|
| 881 |
-
|
| 882 |
-
|
| 883 |
-
|
| 884 |
-
|
| 885 |
-
|
| 886 |
-
|
| 887 |
-
|
| 888 |
-
|
| 889 |
-
|
| 890 |
-
|
| 891 |
-
|
| 892 |
-
|
| 893 |
-
|
| 894 |
-
|
| 895 |
-
|
| 896 |
-
|
| 897 |
-
|
| 898 |
-
|
| 899 |
-
|
| 900 |
-
|
| 901 |
-
|
| 902 |
-
|
| 903 |
-
|
| 904 |
-
|
| 905 |
-
|
| 906 |
-
|
| 907 |
-
|
| 908 |
-
|
| 909 |
-
|
| 910 |
-
|
| 911 |
-
|
| 912 |
-
|
| 913 |
-
|
| 914 |
-
|
| 915 |
-
|
| 916 |
-
|
| 917 |
-
|
| 918 |
-
|
| 919 |
-
|
| 920 |
-
|
| 921 |
-
|
| 922 |
-
|
| 923 |
-
|
| 924 |
-
|
| 925 |
-
|
| 926 |
-
|
| 927 |
-
|
| 928 |
-
|
| 929 |
-
|
| 930 |
-
"
|
| 931 |
-
|
| 932 |
-
|
| 933 |
-
|
| 934 |
-
|
| 935 |
-
|
| 936 |
-
|
| 937 |
-
|
| 938 |
-
|
| 939 |
-
|
| 940 |
-
|
| 941 |
-
|
| 942 |
-
|
| 943 |
-
|
| 944 |
-
|
| 945 |
-
|
| 946 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
IG Comment Gen - HuggingFace Space
|
| 3 |
+
|
| 4 |
+
Genera un commento breve, naturale, in italiano per un post Instagram,
|
| 5 |
+
usando l'API Groq (OpenAI-compatible) direttamente. NON usa piu' HF Inference
|
| 6 |
+
Providers perche' il free tier PRO non include credit Inference (solo ZeroGPU),
|
| 7 |
+
quindi ogni chiamata dava 402 Payment Required.
|
| 8 |
+
|
| 9 |
+
Backend cascade (Groq, hardware LPU proprietario, tutti sotto 0.15s):
|
| 10 |
+
1. openai/gpt-oss-120b (primary)
|
| 11 |
+
2. qwen/qwen3.6-27b (fallback, ottimo italiano)
|
| 12 |
+
3. openai/gpt-oss-20b (fallback leggero)
|
| 13 |
+
|
| 14 |
+
Sono tutti reasoning-style: vanno chiamati con reasoning_effort, altrimenti
|
| 15 |
+
scrivono il ragionamento dentro `content` o lo lasciano vuoto. Vedi MODEL_CASCADE.
|
| 16 |
+
|
| 17 |
+
Se tutti falliscono, torna comment=None -> il client (bot) ricade sul
|
| 18 |
+
suo file txt di fallback.
|
| 19 |
+
|
| 20 |
+
Auth verso Groq: GROQ_API_KEY nei Secrets dello Space (free tier separato da
|
| 21 |
+
HF). Crea su https://console.groq.com/keys.
|
| 22 |
+
Auth verso questo Space: opzionale SPACE_API_KEY (bearer). Se non settato,
|
| 23 |
+
l'endpoint /api/generate e' aperto (utile in fase di test).
|
| 24 |
+
"""
|
| 25 |
+
from __future__ import annotations
|
| 26 |
+
|
| 27 |
+
import logging
|
| 28 |
+
import os
|
| 29 |
+
import re
|
| 30 |
+
import time
|
| 31 |
+
from typing import Optional
|
| 32 |
+
|
| 33 |
+
import gradio as gr
|
| 34 |
+
from fastapi import FastAPI, Header, HTTPException
|
| 35 |
+
from pydantic import BaseModel, Field
|
| 36 |
+
|
| 37 |
+
# ---------------------------------------------------------------------------
|
| 38 |
+
# Setup
|
| 39 |
+
# ---------------------------------------------------------------------------
|
| 40 |
+
logging.basicConfig(
|
| 41 |
+
level=logging.INFO,
|
| 42 |
+
format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
|
| 43 |
+
)
|
| 44 |
+
logger = logging.getLogger("ig-comment-gen")
|
| 45 |
+
|
| 46 |
+
# Backend: Groq direct (free tier separato da HF, 14400 req/day su Llama 3.3
|
| 47 |
+
# 70B). Precedentemente si usava HF Inference Providers via router.huggingface.co
|
| 48 |
+
# ma il PRO include $0.00 di credit Inference (solo ZeroGPU 40min), quindi
|
| 49 |
+
# ogni chiamata dava 402 Payment Required.
|
| 50 |
+
GROQ_API_KEY = os.environ.get("GROQ_API_KEY", "").strip()
|
| 51 |
+
GROQ_BASE_URL = "https://api.groq.com/openai/v1"
|
| 52 |
+
SPACE_API_KEY = os.environ.get("SPACE_API_KEY", "").strip()
|
| 53 |
+
# HF_TOKEN mantenuto per retro-compat (health check). Non usato da _call_model.
|
| 54 |
+
HF_TOKEN = os.environ.get("HF_TOKEN", "").strip()
|
| 55 |
+
|
| 56 |
+
if not GROQ_API_KEY:
|
| 57 |
+
logger.warning(
|
| 58 |
+
"GROQ_API_KEY non trovato negli env: le chiamate falliranno finche' "
|
| 59 |
+
"non lo setti nei Secrets dello Space."
|
| 60 |
+
)
|
| 61 |
+
|
| 62 |
+
# Cascade di modelli Groq. Nomi ufficiali su console.groq.com/docs/models.
|
| 63 |
+
#
|
| 64 |
+
# [19/08/2026] I Llama (llama-3.3-70b-versatile, llama-3.1-8b-instant) sono
|
| 65 |
+
# spariti dal catalogo Groq (404 model_not_found) e gemma2-9b-it e' stata
|
| 66 |
+
# decommissionata. Cascata rifatta sui modelli attualmente serviti.
|
| 67 |
+
#
|
| 68 |
+
# Tutti quelli rimasti sono reasoning-style: senza il parametro giusto
|
| 69 |
+
# scrivono il ragionamento dentro `content` (Qwen usa <think>...</think>) o
|
| 70 |
+
# lasciano `content` vuoto mettendo tutto in `reasoning`. Il parametro NON e'
|
| 71 |
+
# lo stesso per tutti, quindi ogni voce porta i suoi params.
|
| 72 |
+
# - qwen -> reasoning_effort "none" (disattiva del tutto il thinking)
|
| 73 |
+
# - gpt-oss -> reasoning_effort "low" ("none" non e' accettato)
|
| 74 |
+
# Verificati uno per uno il 19/08/2026: tutti rispondono in <0.15s.
|
| 75 |
+
MODEL_CASCADE = [
|
| 76 |
+
{"model": "openai/gpt-oss-120b", "params": {"reasoning_effort": "low"}},
|
| 77 |
+
{"model": "qwen/qwen3.6-27b", "params": {"reasoning_effort": "none"}},
|
| 78 |
+
{"model": "openai/gpt-oss-20b", "params": {"reasoning_effort": "low"}},
|
| 79 |
+
]
|
| 80 |
+
|
| 81 |
+
# Nomi soli, per l'endpoint /api/health e i log.
|
| 82 |
+
MODEL_NAMES = [m["model"] for m in MODEL_CASCADE]
|
| 83 |
+
|
| 84 |
+
MAX_CAPTION_CHARS = 800
|
| 85 |
+
REQUEST_TIMEOUT_S = 12
|
| 86 |
+
MAX_OUTPUT_TOKENS = 120
|
| 87 |
+
DEFAULT_LANGUAGE = "Italian"
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
# ---------------------------------------------------------------------------
|
| 91 |
+
# Prompting
|
| 92 |
+
# ---------------------------------------------------------------------------
|
| 93 |
+
def _build_prompt(
|
| 94 |
+
caption: str,
|
| 95 |
+
target_username: Optional[str],
|
| 96 |
+
media_type: str,
|
| 97 |
+
hint: Optional[str],
|
| 98 |
+
language: str,
|
| 99 |
+
) -> str:
|
| 100 |
+
"""Prompt con 14 regole rigide, copiato/adattato dal repo di riferimento
|
| 101 |
+
(dzeveckij/instagram-ai-commenter-bot) che sono empiricamente quelle
|
| 102 |
+
che rendono i commenti indistinguibili da un umano."""
|
| 103 |
+
safe_caption = (caption or "").strip()
|
| 104 |
+
if len(safe_caption) > MAX_CAPTION_CHARS:
|
| 105 |
+
safe_caption = safe_caption[:MAX_CAPTION_CHARS] + "…"
|
| 106 |
+
|
| 107 |
+
target_clause = (
|
| 108 |
+
f"by @{target_username}" if target_username else "by an Instagram user"
|
| 109 |
+
)
|
| 110 |
+
caption_clause = (
|
| 111 |
+
f'Post caption: "{safe_caption}"'
|
| 112 |
+
if safe_caption
|
| 113 |
+
else "The post has no caption; comment on the photo/video itself."
|
| 114 |
+
)
|
| 115 |
+
hint_clause = f"Context for tone: {hint}\n\n" if hint else ""
|
| 116 |
+
|
| 117 |
+
rules = f"""Rules (follow ALL):
|
| 118 |
+
1. Write ONE short, relevant comment. 1 sentence ideal, max 2 short.
|
| 119 |
+
2. Sound 100% authentic, like a real follower, NEVER like a bot.
|
| 120 |
+
3. CRITICAL: adapt the comment TO THE SPECIFIC CONTENT of the caption. Do NOT
|
| 121 |
+
force topics that are not there. If the caption is about food/recipe -> comment
|
| 122 |
+
on the dish or ingredient. If about travel/location -> comment on the place or
|
| 123 |
+
atmosphere. If about family/personal moment -> comment empathically on the
|
| 124 |
+
moment. If about pets/animals -> comment on the animal. Only if the caption is
|
| 125 |
+
clearly about training/competition/prep -> use athlete-peer tone (technique,
|
| 126 |
+
muscle, exercise, prep). NEVER assume the topic is fitness/bodybuilding just
|
| 127 |
+
because the account is fitness-related.
|
| 128 |
+
4. Reference at least ONE concrete detail from the caption: a word, a place,
|
| 129 |
+
a number, a name, an ingredient, an action. This proves you actually read it.
|
| 130 |
+
5. ABSOLUTELY NO emojis.
|
| 131 |
+
6. ABSOLUTELY NO hashtags.
|
| 132 |
+
7. ABSOLUTELY NO exclamation marks.
|
| 133 |
+
8. NO generic compliments ("Great post", "Love this", "So inspiring", "Amazing",
|
| 134 |
+
"Bravo", "Bellissimo", "Top", "Grande").
|
| 135 |
+
9. NO questions, do not try to start a conversation.
|
| 136 |
+
10. NO first-person pronouns ("I", "me", "my", "io", "mi", "mio").
|
| 137 |
+
11. NO opinions, NO personal experiences.
|
| 138 |
+
12. Vary tone and phrasing; do not reuse common patterns.
|
| 139 |
+
13. Media type is: {media_type}. If video/reel, you may comment on motion/action
|
| 140 |
+
only if it fits the actual content shown.
|
| 141 |
+
14. Output language: {language}.
|
| 142 |
+
15. Output ONLY the final comment text. No quotes, no prefix, no explanation."""
|
| 143 |
+
|
| 144 |
+
return (
|
| 145 |
+
f"You write engaging human-like Instagram comments.\n"
|
| 146 |
+
f"Write a comment for a post {target_clause}.\n\n"
|
| 147 |
+
f"{caption_clause}\n\n"
|
| 148 |
+
f"{hint_clause}"
|
| 149 |
+
f"{rules}\n"
|
| 150 |
+
)
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
# ---------------------------------------------------------------------------
|
| 154 |
+
# Output validation
|
| 155 |
+
# ---------------------------------------------------------------------------
|
| 156 |
+
|
| 157 |
+
_THINK_RE = re.compile(r"<think>.*?</think>", re.DOTALL | re.IGNORECASE)
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
def _strip_think(text: str) -> str:
|
| 161 |
+
"""Rimuove i blocchi <think>...</think> col loro contenuto.
|
| 162 |
+
|
| 163 |
+
Difesa in profondita': i modelli in cascata sono chiamati con
|
| 164 |
+
reasoning_effort per non emetterli, ma se un giorno il parametro smette di
|
| 165 |
+
funzionare (o si aggiunge un modello che lo ignora) il ragionamento
|
| 166 |
+
finirebbe pubblicato come commento.
|
| 167 |
+
"""
|
| 168 |
+
if not text:
|
| 169 |
+
return ""
|
| 170 |
+
out = _THINK_RE.sub("", text)
|
| 171 |
+
# <think> aperto e mai chiuso: tronca il troncone rimasto
|
| 172 |
+
if "<think>" in out.lower():
|
| 173 |
+
out = out[: out.lower().index("<think>")]
|
| 174 |
+
return out.strip()
|
| 175 |
+
|
| 176 |
+
def _sanitize_output(text: str) -> str:
|
| 177 |
+
"""Rimuove rumore tipico: virgolette wrap, prefissi 'Comment:', HTML,
|
| 178 |
+
newline interni, spazi doppi. Taglia a 220 char."""
|
| 179 |
+
if not text:
|
| 180 |
+
return ""
|
| 181 |
+
t = _strip_think(text)
|
| 182 |
+
t = re.sub(r"<[^>]+>", "", t).strip()
|
| 183 |
+
for q in ('"', "'", "`"):
|
| 184 |
+
if len(t) >= 2 and t.startswith(q) and t.endswith(q):
|
| 185 |
+
t = t[1:-1].strip()
|
| 186 |
+
for prefix in ("Comment:", "comment:", "Output:", "Reply:", "Commento:"):
|
| 187 |
+
if t.lower().startswith(prefix.lower()):
|
| 188 |
+
t = t[len(prefix):].strip()
|
| 189 |
+
t = " ".join(t.split())
|
| 190 |
+
if len(t) > 220:
|
| 191 |
+
t = t[:217].rstrip() + "..."
|
| 192 |
+
return t
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
def _passes_guardrails(text: str) -> bool:
|
| 196 |
+
"""Hard guardrail: no #, no !, no emoji (heuristic su codepoint > U+27BF)."""
|
| 197 |
+
if not text:
|
| 198 |
+
return False
|
| 199 |
+
if any(ch in text for ch in "#!"):
|
| 200 |
+
return False
|
| 201 |
+
if any(ord(ch) > 0x27BF for ch in text):
|
| 202 |
+
return False
|
| 203 |
+
return True
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
# ---------------------------------------------------------------------------
|
| 207 |
+
# Inference
|
| 208 |
+
# ---------------------------------------------------------------------------
|
| 209 |
+
def _get_groq_client():
|
| 210 |
+
"""Lazy import + costruzione del client Groq (OpenAI SDK con base_url override).
|
| 211 |
+
|
| 212 |
+
Cached a livello modulo? No: `openai.OpenAI` e' leggero, creare istanza per
|
| 213 |
+
call e' ok (~1ms). E semplifica il testing (nessuno stato globale da resettare).
|
| 214 |
+
"""
|
| 215 |
+
from openai import OpenAI # lazy import: se openai non e' installato, log warning
|
| 216 |
+
return OpenAI(
|
| 217 |
+
api_key=GROQ_API_KEY,
|
| 218 |
+
base_url=GROQ_BASE_URL,
|
| 219 |
+
timeout=REQUEST_TIMEOUT_S,
|
| 220 |
+
)
|
| 221 |
+
|
| 222 |
+
|
| 223 |
+
def _call_model(spec: dict, prompt: str) -> tuple[Optional[str], bool]:
|
| 224 |
+
"""
|
| 225 |
+
Chiama Groq (OpenAI-compat) sull'endpoint /v1/chat/completions.
|
| 226 |
+
|
| 227 |
+
Args:
|
| 228 |
+
spec: voce di MODEL_CASCADE, {"model": str, "params": dict}. I params
|
| 229 |
+
servono a spegnere il reasoning e cambiano da modello a modello.
|
| 230 |
+
|
| 231 |
+
Returns:
|
| 232 |
+
(text, retryable):
|
| 233 |
+
- text: commento raw o None su errore
|
| 234 |
+
- retryable: True se ha senso provare il prossimo modello
|
| 235 |
+
"""
|
| 236 |
+
if not GROQ_API_KEY:
|
| 237 |
+
return None, False
|
| 238 |
+
model = spec["model"]
|
| 239 |
+
try:
|
| 240 |
+
client = _get_groq_client()
|
| 241 |
+
completion = client.chat.completions.create(
|
| 242 |
+
model=model,
|
| 243 |
+
messages=[{"role": "user", "content": prompt}],
|
| 244 |
+
max_tokens=MAX_OUTPUT_TOKENS,
|
| 245 |
+
temperature=0.9,
|
| 246 |
+
top_p=1.0,
|
| 247 |
+
**spec.get("params", {}),
|
| 248 |
+
)
|
| 249 |
+
except Exception as e:
|
| 250 |
+
err_repr = repr(e).lower()
|
| 251 |
+
# 401 / 403 / bad token -> fatal
|
| 252 |
+
if "401" in err_repr or "unauthorized" in err_repr or "403" in err_repr:
|
| 253 |
+
logger.warning("[%s] auth error: %s", model, e)
|
| 254 |
+
return None, False
|
| 255 |
+
# 402 / payment / credits -> fatal (Groq free tier ha rate-limit ma non
|
| 256 |
+
# billing; questo codice pero' resta se in futuro passiamo a paid).
|
| 257 |
+
if "402" in err_repr or "insufficient" in err_repr or "quota" in err_repr:
|
| 258 |
+
logger.warning("[%s] payment/quota error: %s", model, e)
|
| 259 |
+
return None, False
|
| 260 |
+
# 404 (model deprecato/rimosso) / 429 (rate-limit RPM/TPM) / 5xx / timeout -> retryable
|
| 261 |
+
logger.warning("[%s] error (retryable): %s", model, e)
|
| 262 |
+
return None, True
|
| 263 |
+
|
| 264 |
+
try:
|
| 265 |
+
msg = completion.choices[0].message
|
| 266 |
+
text = getattr(msg, "content", None) or ""
|
| 267 |
+
# Reasoning models (gpt-oss, DeepSeek-R1, ...) mettono la risposta in
|
| 268 |
+
# `reasoning` invece che in `content` e finiscono spesso senza generare
|
| 269 |
+
# il content finale. Se text e' vuoto, trattalo come retryable: sposta
|
| 270 |
+
# al prossimo modello (non-reasoning) invece di considerarlo fatal.
|
| 271 |
+
if not text.strip():
|
| 272 |
+
reasoning = getattr(msg, "reasoning", None) or getattr(
|
| 273 |
+
msg, "reasoning_content", None
|
| 274 |
+
)
|
| 275 |
+
logger.warning(
|
| 276 |
+
"[%s] empty content (finish=%s, has_reasoning=%s)",
|
| 277 |
+
model,
|
| 278 |
+
completion.choices[0].finish_reason,
|
| 279 |
+
bool(reasoning),
|
| 280 |
+
)
|
| 281 |
+
return None, True # retryable: prova il prossimo modello
|
| 282 |
+
except Exception as e:
|
| 283 |
+
logger.warning("[%s] parse error: %s", model, e)
|
| 284 |
+
return None, True
|
| 285 |
+
|
| 286 |
+
return text, False
|
| 287 |
+
|
| 288 |
+
|
| 289 |
+
def generate_comment_core(
|
| 290 |
+
caption: str,
|
| 291 |
+
media_type: str,
|
| 292 |
+
target_username: Optional[str] = None,
|
| 293 |
+
hint: Optional[str] = None,
|
| 294 |
+
language: str = DEFAULT_LANGUAGE,
|
| 295 |
+
) -> dict:
|
| 296 |
+
"""
|
| 297 |
+
Wrapper riusabile (chiamato sia da Gradio UI che da FastAPI endpoint).
|
| 298 |
+
Ritorna dict compatibile con la response API.
|
| 299 |
+
"""
|
| 300 |
+
if not GROQ_API_KEY:
|
| 301 |
+
return {
|
| 302 |
+
"comment": None,
|
| 303 |
+
"model_used": None,
|
| 304 |
+
"latency_ms": 0,
|
| 305 |
+
"attempts": 0,
|
| 306 |
+
"error": "GROQ_API_KEY non configurato nei Secrets dello Space.",
|
| 307 |
+
}
|
| 308 |
+
|
| 309 |
+
prompt = _build_prompt(
|
| 310 |
+
caption=caption or "",
|
| 311 |
+
target_username=target_username or None,
|
| 312 |
+
media_type=str(media_type or "photo").lower(),
|
| 313 |
+
hint=hint or None,
|
| 314 |
+
language=language or DEFAULT_LANGUAGE,
|
| 315 |
+
)
|
| 316 |
+
|
| 317 |
+
started = time.time()
|
| 318 |
+
attempts = 0
|
| 319 |
+
for idx, spec in enumerate(MODEL_CASCADE):
|
| 320 |
+
attempts += 1
|
| 321 |
+
model = spec["model"]
|
| 322 |
+
text, retryable = _call_model(spec, prompt)
|
| 323 |
+
if text:
|
| 324 |
+
cleaned = _sanitize_output(text)
|
| 325 |
+
if _passes_guardrails(cleaned):
|
| 326 |
+
latency_ms = int((time.time() - started) * 1000)
|
| 327 |
+
if idx > 0:
|
| 328 |
+
logger.info(
|
| 329 |
+
"cascade recovered on model %s after %d failure(s)",
|
| 330 |
+
model, idx,
|
| 331 |
+
)
|
| 332 |
+
return {
|
| 333 |
+
"comment": cleaned,
|
| 334 |
+
"model_used": model,
|
| 335 |
+
"latency_ms": latency_ms,
|
| 336 |
+
"attempts": attempts,
|
| 337 |
+
"error": None,
|
| 338 |
+
}
|
| 339 |
+
else:
|
| 340 |
+
logger.info(
|
| 341 |
+
"[%s] output failed guardrails: %r",
|
| 342 |
+
model, cleaned[:60],
|
| 343 |
+
)
|
| 344 |
+
continue
|
| 345 |
+
|
| 346 |
+
if not retryable:
|
| 347 |
+
logger.warning("cascade stopped: fatal error on %s", model)
|
| 348 |
+
break
|
| 349 |
+
|
| 350 |
+
latency_ms = int((time.time() - started) * 1000)
|
| 351 |
+
return {
|
| 352 |
+
"comment": None,
|
| 353 |
+
"model_used": None,
|
| 354 |
+
"latency_ms": latency_ms,
|
| 355 |
+
"attempts": attempts,
|
| 356 |
+
"error": "Tutti i modelli hanno fallito o output non conforme.",
|
| 357 |
+
}
|
| 358 |
+
|
| 359 |
+
|
| 360 |
+
# ---------------------------------------------------------------------------
|
| 361 |
+
# DM generation (feature esclusiva del branch personalcoaching lato bot)
|
| 362 |
+
# ---------------------------------------------------------------------------
|
| 363 |
+
_MAX_BIO_CHARS = 400
|
| 364 |
+
_MAX_CAPTION_CHARS_DM = 600
|
| 365 |
+
_MAX_FULLNAME_CHARS = 80
|
| 366 |
+
_MAX_DM_CHARS = 280
|
| 367 |
+
|
| 368 |
+
|
| 369 |
+
def _truncate_dm(text: Optional[str], limit: int) -> str:
|
| 370 |
+
if not text:
|
| 371 |
+
return ""
|
| 372 |
+
t = text.strip()
|
| 373 |
+
if len(t) > limit:
|
| 374 |
+
return t[:limit].rstrip() + "…"
|
| 375 |
+
return t
|
| 376 |
+
|
| 377 |
+
|
| 378 |
+
def _build_dm_prompt(
|
| 379 |
+
target_username: Optional[str],
|
| 380 |
+
full_name: Optional[str],
|
| 381 |
+
bio: Optional[str],
|
| 382 |
+
last_post_caption: Optional[str],
|
| 383 |
+
hint: Optional[str],
|
| 384 |
+
language: str,
|
| 385 |
+
allow_emoji: bool,
|
| 386 |
+
) -> str:
|
| 387 |
+
"""Prompt per DM di apertura, assertivo per evitare che Llama/Qwen infili
|
| 388 |
+
'Mi chiamo X, sono un coach...', hashtag, CTA hard-sell o emoji a raffica.
|
| 389 |
+
Replica lo stile del vecchio ai_dm.py (Gemini era) ma adattato alla
|
| 390 |
+
catena non-reasoning corrente."""
|
| 391 |
+
name_part = _truncate_dm(full_name, _MAX_FULLNAME_CHARS)
|
| 392 |
+
bio_part = _truncate_dm(bio, _MAX_BIO_CHARS)
|
| 393 |
+
caption_part = _truncate_dm(last_post_caption, _MAX_CAPTION_CHARS_DM)
|
| 394 |
+
|
| 395 |
+
context_lines = []
|
| 396 |
+
if target_username:
|
| 397 |
+
context_lines.append(f"- username: @{target_username}")
|
| 398 |
+
if name_part:
|
| 399 |
+
context_lines.append(f"- nome visualizzato: {name_part}")
|
| 400 |
+
if bio_part:
|
| 401 |
+
context_lines.append(f"- bio: {bio_part}")
|
| 402 |
+
if caption_part:
|
| 403 |
+
context_lines.append(f"- caption del suo ultimo post: {caption_part}")
|
| 404 |
+
context_block = (
|
| 405 |
+
"Profilo del destinatario (USA questi indizi per personalizzare,\n"
|
| 406 |
+
"ma NON fare il pappagallo: non ripetere parole esatte della bio):\n"
|
| 407 |
+
+ "\n".join(context_lines)
|
| 408 |
+
if context_lines
|
| 409 |
+
else "Nessuna informazione sul profilo disponibile: scrivi un DM\n"
|
| 410 |
+
"amichevole generico che ringrazia per il follow e fa una sola\n"
|
| 411 |
+
"domanda aperta sul suo percorso fitness."
|
| 412 |
+
)
|
| 413 |
+
|
| 414 |
+
hint_clause = (
|
| 415 |
+
f"Contesto su CHI scrive (autore del DM): {hint}\n\n" if hint else ""
|
| 416 |
+
)
|
| 417 |
+
|
| 418 |
+
emoji_rule = (
|
| 419 |
+
"5. Puoi usare AL MASSIMO 1 emoji leggera (👋 🙌 💪) e SOLO se calza "
|
| 420 |
+
"naturalmente. Nessuna emoji e' la scelta default migliore."
|
| 421 |
+
if allow_emoji
|
| 422 |
+
else "5. ASSOLUTAMENTE NESSUNA emoji."
|
| 423 |
+
)
|
| 424 |
+
|
| 425 |
+
rules = f"""Regole (rispettarle TUTTE):
|
| 426 |
+
1. Scrivi un DM Instagram di apertura, 2-3 frasi brevi totali, max {_MAX_DM_CHARS} caratteri.
|
| 427 |
+
2. Tono: amichevole, peer-to-peer, mai venditore, mai formale.
|
| 428 |
+
3. Ringrazia in modo naturale per il follow (lui ti ha appena seguito).
|
| 429 |
+
4. Fai UNA SOLA domanda aperta sul suo percorso fitness/sport, basandoti sugli
|
| 430 |
+
indizi del profilo se ci sono. La domanda deve essere semplice e specifica,
|
| 431 |
+
non generica ("come stai?" e' VIETATO).
|
| 432 |
+
{emoji_rule}
|
| 433 |
+
6. ASSOLUTAMENTE NIENTE hashtag.
|
| 434 |
+
7. ASSOLUTAMENTE NIENTE link, niente "DM me", niente "scrivimi per coaching",
|
| 435 |
+
niente menzioni di servizi o prezzi.
|
| 436 |
+
8. NIENTE punti esclamativi multipli ("!!"). Massimo 1 "!" in tutto il DM.
|
| 437 |
+
9. NIENTE template robotici tipo "Ciao [nome], ho visto il tuo profilo e...".
|
| 438 |
+
10. NON menzionare la parola "bot", "automatico", "AI" o simili.
|
| 439 |
+
11. NON ripetere parole della bio in modo letterale.
|
| 440 |
+
12. Lingua di output: {language}.
|
| 441 |
+
13. Output SOLO il testo finale del DM. Niente virgolette, niente prefissi,
|
| 442 |
+
niente spiegazioni, niente firma."""
|
| 443 |
+
|
| 444 |
+
return (
|
| 445 |
+
f"Sei un personal trainer / coach che ha appena ricevuto un nuovo\n"
|
| 446 |
+
f"follower su Instagram e vuole aprire una conversazione sincera in DM.\n\n"
|
| 447 |
+
f"{hint_clause}"
|
| 448 |
+
f"{context_block}\n\n"
|
| 449 |
+
f"{rules}\n"
|
| 450 |
+
)
|
| 451 |
+
|
| 452 |
+
|
| 453 |
+
_DM_LINK_MARKERS = (
|
| 454 |
+
"http://", "https://", "www.", "wa.me", "bit.ly", "linktr.ee", "t.me/",
|
| 455 |
+
)
|
| 456 |
+
_DM_SELL_MARKERS = (
|
| 457 |
+
"coaching online",
|
| 458 |
+
"scrivimi per",
|
| 459 |
+
"contattami per",
|
| 460 |
+
"pacchetto",
|
| 461 |
+
"prezzo",
|
| 462 |
+
"prenota",
|
| 463 |
+
)
|
| 464 |
+
|
| 465 |
+
|
| 466 |
+
def _sanitize_dm(text: str) -> str:
|
| 467 |
+
"""Rimuove tag HTML, wrap quotes, prefissi 'DM:' e collassa whitespace."""
|
| 468 |
+
if not text:
|
| 469 |
+
return ""
|
| 470 |
+
t = _strip_think(text)
|
| 471 |
+
t = re.sub(r"<[^>]+>", "", t).strip()
|
| 472 |
+
for q in ('"', "'", "`"):
|
| 473 |
+
if len(t) >= 2 and t.startswith(q) and t.endswith(q):
|
| 474 |
+
t = t[1:-1].strip()
|
| 475 |
+
for prefix in ("DM:", "dm:", "Message:", "Messaggio:", "Reply:"):
|
| 476 |
+
if t.lower().startswith(prefix.lower()):
|
| 477 |
+
t = t[len(prefix):].strip()
|
| 478 |
+
# normalizza spazi ma preserva newline singolo
|
| 479 |
+
t = re.sub(r"[ \t]+", " ", t).strip()
|
| 480 |
+
if len(t) > _MAX_DM_CHARS:
|
| 481 |
+
t = t[: _MAX_DM_CHARS - 3].rstrip() + "..."
|
| 482 |
+
return t
|
| 483 |
+
|
| 484 |
+
|
| 485 |
+
def _passes_dm_guardrails(text: str, allow_emoji: bool) -> bool:
|
| 486 |
+
if not text:
|
| 487 |
+
return False
|
| 488 |
+
if "#" in text:
|
| 489 |
+
return False
|
| 490 |
+
lower = text.lower()
|
| 491 |
+
if any(m in lower for m in _DM_LINK_MARKERS):
|
| 492 |
+
return False
|
| 493 |
+
if any(m in lower for m in _DM_SELL_MARKERS):
|
| 494 |
+
return False
|
| 495 |
+
if text.count("!") > 1:
|
| 496 |
+
return False
|
| 497 |
+
if not allow_emoji and any(ord(ch) > 0x27BF for ch in text):
|
| 498 |
+
return False
|
| 499 |
+
return True
|
| 500 |
+
|
| 501 |
+
|
| 502 |
+
def generate_dm_core(
|
| 503 |
+
target_username: Optional[str] = None,
|
| 504 |
+
full_name: Optional[str] = None,
|
| 505 |
+
bio: Optional[str] = None,
|
| 506 |
+
last_post_caption: Optional[str] = None,
|
| 507 |
+
hint: Optional[str] = None,
|
| 508 |
+
language: str = DEFAULT_LANGUAGE,
|
| 509 |
+
allow_emoji: bool = True,
|
| 510 |
+
) -> dict:
|
| 511 |
+
"""Wrapper riusabile per DM. Stessa cascata di modelli di generate_comment_core."""
|
| 512 |
+
if not GROQ_API_KEY:
|
| 513 |
+
return {
|
| 514 |
+
"dm": None,
|
| 515 |
+
"model_used": None,
|
| 516 |
+
"latency_ms": 0,
|
| 517 |
+
"attempts": 0,
|
| 518 |
+
"error": "GROQ_API_KEY non configurato nei Secrets dello Space.",
|
| 519 |
+
}
|
| 520 |
+
|
| 521 |
+
prompt = _build_dm_prompt(
|
| 522 |
+
target_username=target_username,
|
| 523 |
+
full_name=full_name,
|
| 524 |
+
bio=bio,
|
| 525 |
+
last_post_caption=last_post_caption,
|
| 526 |
+
hint=hint,
|
| 527 |
+
language=language or DEFAULT_LANGUAGE,
|
| 528 |
+
allow_emoji=allow_emoji,
|
| 529 |
+
)
|
| 530 |
+
|
| 531 |
+
started = time.time()
|
| 532 |
+
attempts = 0
|
| 533 |
+
for idx, spec in enumerate(MODEL_CASCADE):
|
| 534 |
+
attempts += 1
|
| 535 |
+
model = spec["model"]
|
| 536 |
+
text, retryable = _call_model(spec, prompt)
|
| 537 |
+
if text:
|
| 538 |
+
cleaned = _sanitize_dm(text)
|
| 539 |
+
if _passes_dm_guardrails(cleaned, allow_emoji=allow_emoji):
|
| 540 |
+
latency_ms = int((time.time() - started) * 1000)
|
| 541 |
+
if idx > 0:
|
| 542 |
+
logger.info(
|
| 543 |
+
"DM cascade recovered on model %s after %d failure(s)",
|
| 544 |
+
model, idx,
|
| 545 |
+
)
|
| 546 |
+
return {
|
| 547 |
+
"dm": cleaned,
|
| 548 |
+
"model_used": model,
|
| 549 |
+
"latency_ms": latency_ms,
|
| 550 |
+
"attempts": attempts,
|
| 551 |
+
"error": None,
|
| 552 |
+
}
|
| 553 |
+
else:
|
| 554 |
+
logger.info(
|
| 555 |
+
"[%s] DM output failed guardrails: %r", model, cleaned[:60]
|
| 556 |
+
)
|
| 557 |
+
continue
|
| 558 |
+
|
| 559 |
+
if not retryable:
|
| 560 |
+
logger.warning("DM cascade stopped: fatal error on %s", model)
|
| 561 |
+
break
|
| 562 |
+
|
| 563 |
+
latency_ms = int((time.time() - started) * 1000)
|
| 564 |
+
return {
|
| 565 |
+
"dm": None,
|
| 566 |
+
"model_used": None,
|
| 567 |
+
"latency_ms": latency_ms,
|
| 568 |
+
"attempts": attempts,
|
| 569 |
+
"error": "Tutti i modelli hanno fallito o output non conforme.",
|
| 570 |
+
}
|
| 571 |
+
|
| 572 |
+
|
| 573 |
+
# ---------------------------------------------------------------------------
|
| 574 |
+
# Risposte alle domande ricevute nel box domande delle storie
|
| 575 |
+
#
|
| 576 |
+
# Caso d'uso: il coach pubblica uno sticker "fammi una domanda" nelle sue
|
| 577 |
+
# storie, riceve N risposte, e il bot genera la replica da mandare in DM (o da
|
| 578 |
+
# ricondividere come sticker in una nuova storia).
|
| 579 |
+
#
|
| 580 |
+
# Differenza rispetto a generate_dm_core: li' e' un saluto dopo il follow-back
|
| 581 |
+
# e non deve dare contenuto, qui c'e' una domanda vera e la risposta deve
|
| 582 |
+
# essere utile. E' l'unico endpoint dove il modello puo' entrare nel merito.
|
| 583 |
+
# ---------------------------------------------------------------------------
|
| 584 |
+
_MAX_QUESTION_CHARS = 500
|
| 585 |
+
_MAX_ANSWER_CHARS = 500
|
| 586 |
+
|
| 587 |
+
# Se la domanda tocca uno di questi temi, nessun modello puo' rispondere: si
|
| 588 |
+
# rimanda a un professionista. Non e' una regola di prompt (aggirabile), e'
|
| 589 |
+
# un controllo sul testo in ingresso.
|
| 590 |
+
_MEDICAL_MARKERS = (
|
| 591 |
+
"infortun", "ernia", "protrusion", "lesion", "strapp", "tendinit",
|
| 592 |
+
"frattur", "dolore forte", "male al ginocchio", "male alla schiena",
|
| 593 |
+
"anoress", "bulim", "disturbo alimentare", "farmac", "anabolizz",
|
| 594 |
+
"steroid", "testosteron", "trenbolon", "nandrolon", "clenbuter",
|
| 595 |
+
"diabet", "tiroid", "gravidanz", "incinta", "allattamento",
|
| 596 |
+
)
|
| 597 |
+
|
| 598 |
+
|
| 599 |
+
def _looks_medical(question: str) -> bool:
|
| 600 |
+
low = (question or "").lower()
|
| 601 |
+
return any(m in low for m in _MEDICAL_MARKERS)
|
| 602 |
+
|
| 603 |
+
|
| 604 |
+
def _build_answer_prompt(
|
| 605 |
+
question: str,
|
| 606 |
+
asker_username: Optional[str],
|
| 607 |
+
hint: Optional[str],
|
| 608 |
+
language: str,
|
| 609 |
+
max_chars: int,
|
| 610 |
+
) -> str:
|
| 611 |
+
"""Prompt per rispondere a una domanda ricevuta nel box domande."""
|
| 612 |
+
safe_q = (question or "").strip()
|
| 613 |
+
if len(safe_q) > _MAX_QUESTION_CHARS:
|
| 614 |
+
safe_q = safe_q[:_MAX_QUESTION_CHARS] + "…"
|
| 615 |
+
|
| 616 |
+
asker_clause = (
|
| 617 |
+
f"La domanda arriva da @{asker_username}."
|
| 618 |
+
if asker_username
|
| 619 |
+
else "La domanda arriva da un follower."
|
| 620 |
+
)
|
| 621 |
+
hint_clause = f"Contesto su CHI risponde: {hint}\n\n" if hint else ""
|
| 622 |
+
|
| 623 |
+
rules = f"""Regole (rispettarle TUTTE):
|
| 624 |
+
1. Rispondi alla domanda in modo UTILE e concreto. Chi scrive vuole una
|
| 625 |
+
risposta vera, non una frase di circostanza.
|
| 626 |
+
2. Massimo {max_chars} caratteri, 2-4 frasi. E' un messaggio diretto, non un articolo.
|
| 627 |
+
3. Se la domanda e' tecnica (allenamento, esecuzione, alimentazione,
|
| 628 |
+
periodizzazione) da' un'indicazione concreta e verificabile: un principio,
|
| 629 |
+
un numero, un criterio. Niente risposte vaghe tipo "dipende da persona a
|
| 630 |
+
persona" senza aggiungere altro.
|
| 631 |
+
4. Se la risposta dipende davvero da variabili individuali, dillo MA da'
|
| 632 |
+
comunque il criterio generale con cui si decide.
|
| 633 |
+
5. Tono: diretto, competente, da pari a pari. Mai cattedratico, mai paternalista.
|
| 634 |
+
6. NIENTE vendita: non proporre coaching, schede, consulenze, sconti, link,
|
| 635 |
+
"scrivimi in privato". Chi scrive lo sa gia' che fai il coach.
|
| 636 |
+
7. NIENTE hashtag. Al massimo UNA emoji, solo se ci sta davvero.
|
| 637 |
+
8. Massimo un punto esclamativo in tutto il messaggio.
|
| 638 |
+
9. NON inventare dati, studi o numeri che non conosci con certezza.
|
| 639 |
+
10. Se la domanda e' fuori tema (non riguarda allenamento, alimentazione,
|
| 640 |
+
sport o il tuo mondo), rispondi comunque in modo umano e breve.
|
| 641 |
+
11. Lingua di output: {language}.
|
| 642 |
+
12. Output SOLO il testo della risposta. Niente virgolette, niente prefissi,
|
| 643 |
+
niente firma."""
|
| 644 |
+
|
| 645 |
+
return (
|
| 646 |
+
f"Sei un coach che risponde alle domande ricevute nel box domande\n"
|
| 647 |
+
f"delle sue storie Instagram. {asker_clause}\n\n"
|
| 648 |
+
f"{hint_clause}"
|
| 649 |
+
f'Domanda: "{safe_q}"\n\n'
|
| 650 |
+
f"{rules}\n"
|
| 651 |
+
)
|
| 652 |
+
|
| 653 |
+
|
| 654 |
+
def _sanitize_answer(text: str, max_chars: int) -> str:
|
| 655 |
+
"""Come _sanitize_dm ma con cap piu' alto: una risposta tecnica ha bisogno
|
| 656 |
+
di piu' spazio di un saluto."""
|
| 657 |
+
if not text:
|
| 658 |
+
return ""
|
| 659 |
+
t = _strip_think(text)
|
| 660 |
+
t = re.sub(r"<[^>]+>", "", t).strip()
|
| 661 |
+
for q in ('"', "'", "`"):
|
| 662 |
+
if len(t) >= 2 and t.startswith(q) and t.endswith(q):
|
| 663 |
+
t = t[1:-1].strip()
|
| 664 |
+
for prefix in ("Risposta:", "risposta:", "Answer:", "Reply:", "R:"):
|
| 665 |
+
if t.lower().startswith(prefix.lower()):
|
| 666 |
+
t = t[len(prefix):].strip()
|
| 667 |
+
t = re.sub(r"[ \t]+", " ", t).strip()
|
| 668 |
+
if len(t) > max_chars:
|
| 669 |
+
cut = t[: max_chars - 3]
|
| 670 |
+
# taglia sull'ultima frase chiusa, se ce n'e' una ragionevolmente lunga
|
| 671 |
+
last_stop = max(cut.rfind(". "), cut.rfind("? "), cut.rfind("! "))
|
| 672 |
+
t = (cut[: last_stop + 1] if last_stop > max_chars * 0.5 else cut.rstrip() + "...")
|
| 673 |
+
return t
|
| 674 |
+
|
| 675 |
+
|
| 676 |
+
def _passes_answer_guardrails(text: str) -> bool:
|
| 677 |
+
if not text:
|
| 678 |
+
return False
|
| 679 |
+
if "#" in text:
|
| 680 |
+
return False
|
| 681 |
+
low = text.lower()
|
| 682 |
+
if any(m in low for m in _DM_LINK_MARKERS):
|
| 683 |
+
return False
|
| 684 |
+
if any(m in low for m in _DM_SELL_MARKERS):
|
| 685 |
+
return False
|
| 686 |
+
if text.count("!") > 1:
|
| 687 |
+
return False
|
| 688 |
+
return True
|
| 689 |
+
|
| 690 |
+
|
| 691 |
+
def generate_answer_core(
|
| 692 |
+
question: str,
|
| 693 |
+
asker_username: Optional[str] = None,
|
| 694 |
+
hint: Optional[str] = None,
|
| 695 |
+
language: str = DEFAULT_LANGUAGE,
|
| 696 |
+
max_chars: int = _MAX_ANSWER_CHARS,
|
| 697 |
+
) -> dict:
|
| 698 |
+
"""Genera la risposta a una domanda del box domande.
|
| 699 |
+
|
| 700 |
+
Ritorna answer=None anche quando la domanda e' di ambito medico: in quel
|
| 701 |
+
caso `refused` e' True e il client deve lasciar rispondere una persona.
|
| 702 |
+
"""
|
| 703 |
+
if not GROQ_API_KEY:
|
| 704 |
+
return {
|
| 705 |
+
"answer": None, "model_used": None, "latency_ms": 0,
|
| 706 |
+
"attempts": 0, "refused": False,
|
| 707 |
+
"error": "GROQ_API_KEY non configurato nei Secrets dello Space.",
|
| 708 |
+
}
|
| 709 |
+
|
| 710 |
+
if not (question or "").strip():
|
| 711 |
+
return {
|
| 712 |
+
"answer": None, "model_used": None, "latency_ms": 0,
|
| 713 |
+
"attempts": 0, "refused": False, "error": "Domanda vuota.",
|
| 714 |
+
}
|
| 715 |
+
|
| 716 |
+
# Guardia sanitaria: infortuni, farmaci, disturbi alimentari, gravidanza.
|
| 717 |
+
# Una risposta automatica qui puo' fare danno vero.
|
| 718 |
+
if _looks_medical(question):
|
| 719 |
+
logger.info("question refused (medical/sensitive topic)")
|
| 720 |
+
return {
|
| 721 |
+
"answer": None, "model_used": None, "latency_ms": 0,
|
| 722 |
+
"attempts": 0, "refused": True,
|
| 723 |
+
"error": "Domanda su tema medico o sensibile: risponde una persona.",
|
| 724 |
+
}
|
| 725 |
+
|
| 726 |
+
prompt = _build_answer_prompt(
|
| 727 |
+
question=question,
|
| 728 |
+
asker_username=asker_username,
|
| 729 |
+
hint=hint,
|
| 730 |
+
language=language or DEFAULT_LANGUAGE,
|
| 731 |
+
max_chars=max_chars,
|
| 732 |
+
)
|
| 733 |
+
|
| 734 |
+
started = time.time()
|
| 735 |
+
attempts = 0
|
| 736 |
+
for idx, spec in enumerate(MODEL_CASCADE):
|
| 737 |
+
attempts += 1
|
| 738 |
+
model = spec["model"]
|
| 739 |
+
text, retryable = _call_model(spec, prompt)
|
| 740 |
+
if text:
|
| 741 |
+
cleaned = _sanitize_answer(text, max_chars)
|
| 742 |
+
if _passes_answer_guardrails(cleaned):
|
| 743 |
+
if idx > 0:
|
| 744 |
+
logger.info(
|
| 745 |
+
"answer cascade recovered on %s after %d failure(s)",
|
| 746 |
+
model, idx,
|
| 747 |
+
)
|
| 748 |
+
return {
|
| 749 |
+
"answer": cleaned,
|
| 750 |
+
"model_used": model,
|
| 751 |
+
"latency_ms": int((time.time() - started) * 1000),
|
| 752 |
+
"attempts": attempts,
|
| 753 |
+
"refused": False,
|
| 754 |
+
"error": None,
|
| 755 |
+
}
|
| 756 |
+
logger.info("[%s] answer failed guardrails: %r", model, cleaned[:60])
|
| 757 |
+
continue
|
| 758 |
+
|
| 759 |
+
if not retryable:
|
| 760 |
+
logger.warning("answer cascade stopped: fatal error on %s", model)
|
| 761 |
+
break
|
| 762 |
+
|
| 763 |
+
return {
|
| 764 |
+
"answer": None,
|
| 765 |
+
"model_used": None,
|
| 766 |
+
"latency_ms": int((time.time() - started) * 1000),
|
| 767 |
+
"attempts": attempts,
|
| 768 |
+
"refused": False,
|
| 769 |
+
"error": "Tutti i modelli hanno fallito o output non conforme.",
|
| 770 |
+
}
|
| 771 |
+
|
| 772 |
+
|
| 773 |
+
# ---------------------------------------------------------------------------
|
| 774 |
+
# FastAPI
|
| 775 |
+
# ---------------------------------------------------------------------------
|
| 776 |
+
class GenerateRequest(BaseModel):
|
| 777 |
+
caption: str = Field(..., description="Caption del post")
|
| 778 |
+
media_type: str = Field("photo", description="photo|video|reel|carousel|igtv")
|
| 779 |
+
target_username: Optional[str] = Field(None, description="Autore del post")
|
| 780 |
+
hint: Optional[str] = Field(None, description="Contesto di tono / nicchia")
|
| 781 |
+
language: str = Field(DEFAULT_LANGUAGE, description="Lingua output")
|
| 782 |
+
|
| 783 |
+
|
| 784 |
+
class GenerateResponse(BaseModel):
|
| 785 |
+
comment: Optional[str]
|
| 786 |
+
model_used: Optional[str]
|
| 787 |
+
latency_ms: int
|
| 788 |
+
attempts: int
|
| 789 |
+
error: Optional[str] = None
|
| 790 |
+
|
| 791 |
+
|
| 792 |
+
class GenerateDmRequest(BaseModel):
|
| 793 |
+
target_username: Optional[str] = Field(None, description="Destinatario del DM")
|
| 794 |
+
full_name: Optional[str] = Field(None, description="Nome display sul profilo")
|
| 795 |
+
bio: Optional[str] = Field(None, description="Biografia del destinatario")
|
| 796 |
+
last_post_caption: Optional[str] = Field(None, description="Caption ultimo post")
|
| 797 |
+
hint: Optional[str] = Field(None, description="Contesto su chi scrive")
|
| 798 |
+
language: str = Field(DEFAULT_LANGUAGE, description="Lingua output")
|
| 799 |
+
allow_emoji: bool = Field(True, description="Permette al massimo 1 emoji leggera")
|
| 800 |
+
|
| 801 |
+
|
| 802 |
+
class GenerateDmResponse(BaseModel):
|
| 803 |
+
dm: Optional[str]
|
| 804 |
+
model_used: Optional[str]
|
| 805 |
+
latency_ms: int
|
| 806 |
+
attempts: int
|
| 807 |
+
error: Optional[str] = None
|
| 808 |
+
|
| 809 |
+
|
| 810 |
+
class AnswerQuestionRequest(BaseModel):
|
| 811 |
+
question: str = Field(..., description="Domanda ricevuta nel box domande")
|
| 812 |
+
asker_username: Optional[str] = Field(None, description="Chi ha fatto la domanda")
|
| 813 |
+
hint: Optional[str] = Field(None, description="Contesto su chi risponde")
|
| 814 |
+
language: str = Field(DEFAULT_LANGUAGE, description="Lingua output")
|
| 815 |
+
max_chars: int = Field(_MAX_ANSWER_CHARS, ge=100, le=900, description="Cap lunghezza risposta")
|
| 816 |
+
|
| 817 |
+
|
| 818 |
+
class AnswerQuestionResponse(BaseModel):
|
| 819 |
+
answer: Optional[str]
|
| 820 |
+
model_used: Optional[str]
|
| 821 |
+
latency_ms: int
|
| 822 |
+
attempts: int
|
| 823 |
+
refused: bool = False
|
| 824 |
+
error: Optional[str] = None
|
| 825 |
+
|
| 826 |
+
|
| 827 |
+
app = FastAPI(title="IG Comment Gen", version="1.0.0")
|
| 828 |
+
|
| 829 |
+
|
| 830 |
+
def _check_api_key(authorization: Optional[str]) -> None:
|
| 831 |
+
if not SPACE_API_KEY:
|
| 832 |
+
return # endpoint aperto
|
| 833 |
+
if not authorization or not authorization.startswith("Bearer "):
|
| 834 |
+
raise HTTPException(status_code=401, detail="Missing bearer token")
|
| 835 |
+
token = authorization.removeprefix("Bearer ").strip()
|
| 836 |
+
if token != SPACE_API_KEY:
|
| 837 |
+
raise HTTPException(status_code=401, detail="Invalid token")
|
| 838 |
+
|
| 839 |
+
|
| 840 |
+
@app.post("/api/generate", response_model=GenerateResponse)
|
| 841 |
+
def api_generate(
|
| 842 |
+
req: GenerateRequest,
|
| 843 |
+
authorization: Optional[str] = Header(None),
|
| 844 |
+
) -> GenerateResponse:
|
| 845 |
+
_check_api_key(authorization)
|
| 846 |
+
result = generate_comment_core(
|
| 847 |
+
caption=req.caption,
|
| 848 |
+
media_type=req.media_type,
|
| 849 |
+
target_username=req.target_username,
|
| 850 |
+
hint=req.hint,
|
| 851 |
+
language=req.language,
|
| 852 |
+
)
|
| 853 |
+
return GenerateResponse(**result)
|
| 854 |
+
|
| 855 |
+
|
| 856 |
+
@app.post("/api/generate_dm", response_model=GenerateDmResponse)
|
| 857 |
+
def api_generate_dm(
|
| 858 |
+
req: GenerateDmRequest,
|
| 859 |
+
authorization: Optional[str] = Header(None),
|
| 860 |
+
) -> GenerateDmResponse:
|
| 861 |
+
_check_api_key(authorization)
|
| 862 |
+
result = generate_dm_core(
|
| 863 |
+
target_username=req.target_username,
|
| 864 |
+
full_name=req.full_name,
|
| 865 |
+
bio=req.bio,
|
| 866 |
+
last_post_caption=req.last_post_caption,
|
| 867 |
+
hint=req.hint,
|
| 868 |
+
language=req.language,
|
| 869 |
+
allow_emoji=req.allow_emoji,
|
| 870 |
+
)
|
| 871 |
+
return GenerateDmResponse(**result)
|
| 872 |
+
|
| 873 |
+
|
| 874 |
+
@app.post("/api/answer_question", response_model=AnswerQuestionResponse)
|
| 875 |
+
def api_answer_question(
|
| 876 |
+
req: AnswerQuestionRequest,
|
| 877 |
+
authorization: Optional[str] = Header(None),
|
| 878 |
+
) -> AnswerQuestionResponse:
|
| 879 |
+
_check_api_key(authorization)
|
| 880 |
+
result = generate_answer_core(
|
| 881 |
+
question=req.question,
|
| 882 |
+
asker_username=req.asker_username,
|
| 883 |
+
hint=req.hint,
|
| 884 |
+
language=req.language,
|
| 885 |
+
max_chars=req.max_chars,
|
| 886 |
+
)
|
| 887 |
+
return AnswerQuestionResponse(**result)
|
| 888 |
+
|
| 889 |
+
|
| 890 |
+
@app.get("/api/health")
|
| 891 |
+
def health() -> dict:
|
| 892 |
+
return {
|
| 893 |
+
"status": "ok",
|
| 894 |
+
"backend": "groq",
|
| 895 |
+
"groq_api_key_configured": bool(GROQ_API_KEY),
|
| 896 |
+
"space_api_key_enforced": bool(SPACE_API_KEY),
|
| 897 |
+
"models": MODEL_NAMES,
|
| 898 |
+
"endpoints": [
|
| 899 |
+
"/api/generate",
|
| 900 |
+
"/api/generate_dm",
|
| 901 |
+
"/api/answer_question",
|
| 902 |
+
"/api/health",
|
| 903 |
+
],
|
| 904 |
+
}
|
| 905 |
+
|
| 906 |
+
|
| 907 |
+
# ---------------------------------------------------------------------------
|
| 908 |
+
# Gradio UI
|
| 909 |
+
# ---------------------------------------------------------------------------
|
| 910 |
+
def _ui_generate(caption, media_type, target_username, hint, language):
|
| 911 |
+
result = generate_comment_core(
|
| 912 |
+
caption=caption,
|
| 913 |
+
media_type=media_type,
|
| 914 |
+
target_username=target_username,
|
| 915 |
+
hint=hint,
|
| 916 |
+
language=language,
|
| 917 |
+
)
|
| 918 |
+
comment = result.get("comment") or "(nessun commento generato)"
|
| 919 |
+
meta = (
|
| 920 |
+
f"Model: {result.get('model_used') or 'n/a'}\n"
|
| 921 |
+
f"Latency: {result.get('latency_ms')}ms\n"
|
| 922 |
+
f"Attempts: {result.get('attempts')}\n"
|
| 923 |
+
f"Error: {result.get('error') or 'none'}"
|
| 924 |
+
)
|
| 925 |
+
return comment, meta
|
| 926 |
+
|
| 927 |
+
|
| 928 |
+
with gr.Blocks(title="IG Comment Gen", theme=gr.themes.Soft()) as demo:
|
| 929 |
+
gr.Markdown(
|
| 930 |
+
"# 💬 IG Comment Gen\n"
|
| 931 |
+
"Genera un commento breve, naturale, in italiano per un post Instagram. "
|
| 932 |
+
"Usato dal bot GramAddict come sostituto della vecchia integrazione Gemini."
|
| 933 |
+
)
|
| 934 |
+
with gr.Row():
|
| 935 |
+
with gr.Column():
|
| 936 |
+
caption_in = gr.Textbox(
|
| 937 |
+
label="Caption del post",
|
| 938 |
+
lines=5,
|
| 939 |
+
placeholder="3 anni di allenamento continuo, ecco i risultati…",
|
| 940 |
+
)
|
| 941 |
+
media_in = gr.Dropdown(
|
| 942 |
+
choices=["photo", "video", "reel", "carousel", "igtv"],
|
| 943 |
+
value="reel",
|
| 944 |
+
label="Media type",
|
| 945 |
+
)
|
| 946 |
+
username_in = gr.Textbox(
|
| 947 |
+
label="Target username (opzionale)",
|
| 948 |
+
placeholder="il.pump.quotidiano",
|
| 949 |
+
)
|
| 950 |
+
hint_in = gr.Textbox(
|
| 951 |
+
label="Hint di contesto (opzionale)",
|
| 952 |
+
placeholder="coach fitness, tono cameratesco",
|
| 953 |
+
)
|
| 954 |
+
lang_in = gr.Textbox(
|
| 955 |
+
label="Lingua output", value=DEFAULT_LANGUAGE
|
| 956 |
+
)
|
| 957 |
+
btn = gr.Button("Genera commento", variant="primary")
|
| 958 |
+
with gr.Column():
|
| 959 |
+
out_comment = gr.Textbox(label="Commento generato", lines=3)
|
| 960 |
+
out_meta = gr.Textbox(label="Meta", lines=4)
|
| 961 |
+
|
| 962 |
+
btn.click(
|
| 963 |
+
fn=_ui_generate,
|
| 964 |
+
inputs=[caption_in, media_in, username_in, hint_in, lang_in],
|
| 965 |
+
outputs=[out_comment, out_meta],
|
| 966 |
+
)
|
| 967 |
+
|
| 968 |
+
gr.Markdown(
|
| 969 |
+
"### API REST\n"
|
| 970 |
+
"`POST /api/generate` con body JSON `{ caption, media_type, "
|
| 971 |
+
"target_username?, hint?, language? }`.\n"
|
| 972 |
+
"Se `SPACE_API_KEY` e' settato nei Secrets, richiede header "
|
| 973 |
+
"`Authorization: Bearer <SPACE_API_KEY>`.\n\n"
|
| 974 |
+
"`GET /api/health` per verificare che HF_TOKEN sia configurato."
|
| 975 |
+
)
|
| 976 |
+
|
| 977 |
+
|
| 978 |
+
# Mount Gradio dentro FastAPI sulla root: cosi' visiti "/" e vedi la UI,
|
| 979 |
+
# mentre "/api/*" resta libero per gli endpoint REST.
|
| 980 |
+
app = gr.mount_gradio_app(app, demo, path="/")
|
| 981 |
+
|
| 982 |
+
|
| 983 |
+
# Local dev only. Su HF Space (Docker SDK) uvicorn e' avviato dal Dockerfile
|
| 984 |
+
# come `uvicorn app:app --host 0.0.0.0 --port 7860`. Non serve il blocco
|
| 985 |
+
# __main__: se lo eseguissi qui e HF Docker facesse lo stesso ci sarebbero
|
| 986 |
+
# due processi in conflitto.
|
| 987 |
+
if __name__ == "__main__":
|
| 988 |
+
import uvicorn
|
| 989 |
+
port = int(os.environ.get("PORT", 7860))
|
| 990 |
+
uvicorn.run(app, host="0.0.0.0", port=port)
|