mattysaints commited on
Commit
c8f4891
·
verified ·
1 Parent(s): f1bf360

fix: cascata modelli rifatta (Llama spariti da Groq) + strip blocchi think

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