From a325cf221d27ea877633e102dd3d902ab5f165d2 Mon Sep 17 00:00:00 2001 From: bolbol Date: Mon, 2 Nov 2026 14:33:48 +0100 Subject: [PATCH] feat(treblo): titre obligatoire, nom fichier nettoye, paroles html, script envoi (ticket nyora-2026-10-216-d) --- Dockerfile | 1 + envoyer_apercu.py | 112 +++++++++++ main.py | 326 ++++++++++++++++++++++++++++---- tests/test_envoi_paroles.py | 288 ++++++++++++++++++++++++++++ tests/test_validation_durcie.py | 6 +- 5 files changed, 689 insertions(+), 44 deletions(-) create mode 100755 envoyer_apercu.py create mode 100755 tests/test_envoi_paroles.py diff --git a/Dockerfile b/Dockerfile index 21e0ca5..86bcbb0 100755 --- a/Dockerfile +++ b/Dockerfile @@ -7,6 +7,7 @@ COPY requirements.txt . RUN pip install --no-cache-dir -r requirements.txt COPY cap_check.py . COPY validation_cli.py . +COPY envoyer_apercu.py . COPY main.py . COPY tests/ ./tests/ RUN mkdir -p /app/data /app/musique/nyora /app/musique/perso diff --git a/envoyer_apercu.py b/envoyer_apercu.py new file mode 100755 index 0000000..3baedb9 --- /dev/null +++ b/envoyer_apercu.py @@ -0,0 +1,112 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +""" +Script d'envoi d'aperçu MP3 et paroles/instrumental sur Telegram pour Claude et les envois manuels. +Réutilise exactement les mêmes fonctions que le serveur treblo-mcp. +Usage: python3 /app/envoyer_apercu.py task_id [--titre "..."] [--sphere nyora|perso] +""" +import os +import sys +import json +import argparse +from main import ( + send_telegram_preview_mp3, + get_titre_for_task, + get_journal_entry, + get_musique_dir, + titre_vers_nom_fichier +) + +def parse_args(): + if "--aide" in sys.argv: + print("Usage: python3 /app/envoyer_apercu.py task_id [--titre \"...\"] [--sphere nyora|perso]") + print("Envoie l'aperçu MP3 et les paroles formatées ou le message instrumental sur Telegram.") + print("") + print("Arguments obligatoires :") + print(" task_id Identifiant unique de la tâche Treblo") + print("") + print("Options :") + print(" --titre TITRE Titre de la chanson (déduit de titres.json ou métadonnées par défaut)") + print(" --sphere SPHERE Sphère d'envoi : 'nyora' ou 'perso' (détectée automatiquement si omise)") + print(" --aide Affiche cette aide et termine") + sys.exit(0) + + parser = argparse.ArgumentParser( + description="Envoi d'aperçu musical Treblo sur Telegram pour Claude et envois manuels", + add_help=True + ) + parser.add_argument("task_id", help="Identifiant de la tâche de génération Treblo (task_id)") + parser.add_argument("--titre", default=None, help="Titre de la chanson (--titre)") + parser.add_argument("--sphere", choices=["nyora", "perso"], default=None, help="Sphère de la chanson (nyora ou perso)") + return parser.parse_args() + +def main(): + args = parse_args() + task_id = args.task_id.strip() + titre_arg = args.titre.strip() if args.titre else None + sphere = args.sphere.strip() if args.sphere else None + + # Détection de la sphère si non fournie + nyora_mp3 = os.path.join(get_musique_dir("nyora"), f"{task_id}.mp3") + perso_mp3 = os.path.join(get_musique_dir("perso"), f"{task_id}.mp3") + + if not sphere: + if os.path.exists(nyora_mp3): + sphere = "nyora" + elif os.path.exists(perso_mp3): + sphere = "perso" + else: + entry = get_journal_entry(task_id) + if entry and entry.get("sphere"): + sphere = entry.get("sphere") + else: + sphere = "nyora" + + mp3_path = os.path.join(get_musique_dir(sphere), f"{task_id}.mp3") + if not os.path.exists(mp3_path): + alt_sphere = "perso" if sphere == "nyora" else "nyora" + alt_path = os.path.join(get_musique_dir(alt_sphere), f"{task_id}.mp3") + if os.path.exists(alt_path): + sphere = alt_sphere + mp3_path = alt_path + else: + print(f"Erreur : fichier MP3 introuvable pour {task_id} ({mp3_path})", file=sys.stderr) + sys.exit(1) + + titre = titre_arg or get_titre_for_task(task_id) + + # Récupérer les tags et paroles depuis les métadonnées + meta_path = os.path.join(get_musique_dir(sphere), f"{task_id}.json") + tags = [] + paroles = "" + if os.path.exists(meta_path): + try: + with open(meta_path, "r", encoding="utf-8") as f: + meta = json.load(f) + tags = meta.get("tags", []) + paroles = meta.get("paroles", "") + except Exception: + pass + if not tags and not paroles: + entry = get_journal_entry(task_id) + if entry: + tags = entry.get("tags", []) + paroles = entry.get("paroles", "") + + res = send_telegram_preview_mp3( + sphere=sphere, + mp3_path=mp3_path, + task_id=task_id, + titre=titre, + tags=tags, + paroles=paroles + ) + if not res: + print(f"Échec de l'envoi de l'aperçu pour {task_id}", file=sys.stderr) + sys.exit(1) + + nom_fichier = titre_vers_nom_fichier(titre) + print(f"Succès envoi {task_id} : nom_fichier='{nom_fichier}', audio message_id={res.get('message_id')}, texte_message_id={res.get('texte_message_id')}") + +if __name__ == "__main__": + main() diff --git a/main.py b/main.py index 7768f19..7a590f7 100755 --- a/main.py +++ b/main.py @@ -1,5 +1,6 @@ # -*- coding: utf-8 -*- import os +import re import json import hmac import uuid @@ -55,6 +56,140 @@ def get_envois_path() -> str: return local return path +def get_titres_path() -> str: + path = "/app/data/titres.json" + if not os.path.exists(os.path.dirname(path)): + local = os.path.join(os.path.dirname(os.path.abspath(__file__)), "data", "titres.json") + os.makedirs(os.path.dirname(local), exist_ok=True) + return local + return path + +def load_titres() -> Dict[str, str]: + path = get_titres_path() + if os.path.exists(path): + try: + with open(path, "r", encoding="utf-8") as f: + return json.load(f) + except Exception: + return {} + return {} + +def save_titre(task_id: str, titre: str): + path = get_titres_path() + titres = load_titres() + titres[task_id] = titre + with open(path, "w", encoding="utf-8") as f: + json.dump(titres, f, indent=2, ensure_ascii=False) + +def get_titre_for_task(task_id: str, default: Optional[str] = None) -> str: + titres = load_titres() + if task_id in titres and titres[task_id]: + return titres[task_id] + entry = get_journal_entry(task_id) + if entry and entry.get("titre"): + return entry.get("titre") + for sp in ("nyora", "perso"): + m_path = os.path.join(get_musique_dir(sp), f"{task_id}.json") + if os.path.exists(m_path): + try: + with open(m_path, "r", encoding="utf-8") as f: + meta = json.load(f) + if meta.get("titre"): + return meta.get("titre") + except Exception: + pass + return default or task_id + +def validate_titre(titre: str) -> str: + if not titre or not isinstance(titre, str): + raise ValueError("Refus : le paramètre titre est obligatoire") + t = titre.strip() + if len(t) < 1 or len(t) > 60: + raise ValueError(f"Refus : le titre doit comporter entre 1 et 60 caractères (reçu: {len(t)})") + if re.search(r'\bcomme\s+\S+', t, re.IGNORECASE) or re.search(r'\blike\s+\S+', t, re.IGNORECASE): + raise ValueError("Refus : le titre ne doit contenir ni formule 'comme X' ni référence directe d'artiste") + return t + +def nettoyer_titre_fichier(titre: str) -> str: + res = [] + for c in str(titre or ""): + if c in '/\\:*?"<>|' or ord(c) < 32 or ord(c) == 127: + res.append('-') + else: + res.append(c) + s = "".join(res) + s = re.sub(r'\s+', ' ', s).strip() + if len(s) > 80: + s = s[:80].rstrip() + return s + +def titre_vers_nom_fichier(titre: str) -> str: + cleaned = nettoyer_titre_fichier(titre) + return f"{cleaned}.mp3" + +def echapper_html(text: str) -> str: + if not text: + return "" + return str(text).replace("&", "&").replace("<", "<").replace(">", ">") + +def preparer_messages_paroles(titre: str, tags: Any, paroles: Optional[str]) -> List[str]: + t_esc = echapper_html(titre) + tags_str = ", ".join(str(t).strip() for t in tags) if isinstance(tags, list) else str(tags or "").strip() + tags_esc = echapper_html(tags_str) + + has_paroles = bool(paroles and str(paroles).strip()) + if not has_paroles: + return [f"🎵 {t_esc}\n{tags_esc}\n\nInstrumental"] + + raw_strophes = [s.strip() for s in re.split(r'\n\s*\n', str(paroles).strip()) if s.strip()] + escaped_strophes = [echapper_html(s) for s in raw_strophes] + + prefix = f"🎵 {t_esc}\n{tags_esc}\n---\n" + tag_open = "
" + tag_close = "
" + + messages: List[str] = [] + current_strophes: List[str] = [] + + for s in escaped_strophes: + candidate_strophes = current_strophes + [s] + candidate_body = "\n\n".join(candidate_strophes) + current_prefix = prefix if len(messages) == 0 else "" + candidate_msg = f"{current_prefix}{tag_open}{candidate_body}{tag_close}" + + if len(candidate_msg) <= 4096: + current_strophes.append(s) + else: + if current_strophes: + body = "\n\n".join(current_strophes) + messages.append(f"{current_prefix}{tag_open}{body}{tag_close}") + current_strophes = [s] + else: + lines = s.split("\n") + chunk_lines = [] + for line in lines: + cand = "\n".join(chunk_lines + [line]) + cand_msg = f"{current_prefix}{tag_open}{cand}{tag_close}" + if len(cand_msg) <= 4096: + chunk_lines.append(line) + else: + if chunk_lines: + messages.append(f"{current_prefix}{tag_open}{'\n'.join(chunk_lines)}{tag_close}") + current_prefix = "" + chunk_lines = [line] + else: + messages.append(f"{current_prefix}{tag_open}{line[:4000]}{tag_close}") + current_prefix = "" + if chunk_lines: + current_strophes = ["\n".join(chunk_lines)] + + if current_strophes: + current_prefix = prefix if len(messages) == 0 else "" + body = "\n\n".join(current_strophes) + messages.append(f"{current_prefix}{tag_open}{body}{tag_close}") + + return messages + def get_musique_dir(sphere: str) -> str: path = f"/app/musique/{sphere}" if not os.path.exists("/app/musique"): @@ -172,13 +307,16 @@ def get_journal_entry(task_id: str) -> Optional[Dict[str, Any]]: pass return None -def log_envoi(task_id: str, sphere: str, message_id: int): +def log_envoi(task_id: str, sphere: str, message_id: int, titre: str = "", nom_fichier: str = "", texte_message_id: int = 0): path = get_envois_path() entry = { "type": "apercu_mp3", "task_id": task_id, "sphere": sphere, + "titre": titre, + "nom_fichier": nom_fichier, "message_id": int(message_id), + "texte_message_id": int(texte_message_id), "date": datetime.datetime.now(datetime.timezone.utc).isoformat() } with open(path, "a", encoding="utf-8") as f: @@ -196,18 +334,22 @@ def consume_approved_validation(sphere: str, empreinte: str, val_id: Optional[st consumed = False for item in data.get("validations", []): if item.get("sphere") == sphere and item.get("status") == "APPROVED": - match = (val_id and item.get("id") == val_id) or (not val_id and item.get("empreinte") == empreinte) - if match: - exp = datetime.datetime.fromisoformat(item.get("expires_at")) - if exp > now_dt: - item["status"] = "USED" - item["used_at"] = now_dt.isoformat() - consumed = True - updated = True - break - else: - item["status"] = "EXPIRED" - updated = True + # L'approbation n'est consommée que si la sphère ET l'empreinte correspondent, + # avec ou sans validation_id + if item.get("empreinte") != empreinte: + continue + if val_id and item.get("id") != val_id: + continue + exp = datetime.datetime.fromisoformat(item.get("expires_at")) + if exp > now_dt: + item["status"] = "USED" + item["used_at"] = now_dt.isoformat() + consumed = True + updated = True + break + else: + item["status"] = "EXPIRED" + updated = True if updated: with open(v_path, "w", encoding="utf-8") as fw: json.dump(data, fw, indent=2, ensure_ascii=False) @@ -226,11 +368,13 @@ def is_validation_approved(sphere: str, empreinte: str, val_id: Optional[str] = now_dt = datetime.datetime.now(TUNIS_TZ) for item in data.get("validations", []): if item.get("sphere") == sphere and item.get("status") == "APPROVED": - match = (val_id and item.get("id") == val_id) or (not val_id and item.get("empreinte") == empreinte) - if match: - exp = datetime.datetime.fromisoformat(item.get("expires_at")) - if exp > now_dt: - return True + if item.get("empreinte") != empreinte: + continue + if val_id and item.get("id") != val_id: + continue + exp = datetime.datetime.fromisoformat(item.get("expires_at")) + if exp > now_dt: + return True except Exception: pass return False @@ -296,40 +440,103 @@ def send_telegram_validation_request(sphere: str, val_id: str, code: str, tags: except Exception as e: logger.warning("Échec envoi notification Telegram: %s", e) -def send_telegram_preview_mp3(sphere: str, mp3_path: str, task_id: str) -> Optional[int]: +def send_telegram_preview_mp3( + sphere: str, + mp3_path: str, + task_id: str, + titre: Optional[str] = None, + tags: Optional[Any] = None, + paroles: Optional[str] = None +) -> Optional[Dict[str, int]]: bot_token = get_bot_token(sphere) chat_id = os.environ.get("TELEGRAM_CHAT_ID", "2084513684").strip() if not bot_token or not chat_id or not os.path.exists(mp3_path): + logger.warning("send_telegram_preview_mp3: bot_token, chat_id absent ou mp3_path introuvable (%s)", mp3_path) return None + if not titre: + titre = get_titre_for_task(task_id) + + if tags is None or paroles is None: + meta_path = os.path.join(os.path.dirname(mp3_path), f"{task_id}.json") + if os.path.exists(meta_path): + try: + with open(meta_path, "r", encoding="utf-8") as f: + meta = json.load(f) + if tags is None: + tags = meta.get("tags", []) + if paroles is None: + paroles = meta.get("paroles", "") + except Exception: + pass + if tags is None or paroles is None: + entry = get_journal_entry(task_id) + if entry: + if tags is None: + tags = entry.get("tags", []) + if paroles is None: + paroles = entry.get("paroles", "") + + nom_fichier = titre_vers_nom_fichier(titre) + performer = "Nyora" if sphere == "nyora" else "Perso" + boundary = f"----TrebloBoundary{uuid.uuid4().hex}" with open(mp3_path, "rb") as f: audio_bytes = f.read() - fname = os.path.basename(mp3_path) - caption = f"Aperçu Treblo ({sphere}) - {task_id}" parts = [ f"--{boundary}\r\nContent-Disposition: form-data; name=\"chat_id\"\r\n\r\n{chat_id}\r\n".encode(), - f"--{boundary}\r\nContent-Disposition: form-data; name=\"caption\"\r\n\r\n{caption}\r\n".encode(), - f"--{boundary}\r\nContent-Disposition: form-data; name=\"audio\"; filename=\"{fname}\"\r\nContent-Type: audio/mpeg\r\n\r\n".encode(), + f"--{boundary}\r\nContent-Disposition: form-data; name=\"title\"\r\n\r\n{titre}\r\n".encode(), + f"--{boundary}\r\nContent-Disposition: form-data; name=\"performer\"\r\n\r\n{performer}\r\n".encode(), + f"--{boundary}\r\nContent-Disposition: form-data; name=\"audio\"; filename=\"{nom_fichier}\"\r\nContent-Type: audio/mpeg\r\n\r\n".encode(), audio_bytes, f"\r\n--{boundary}--\r\n".encode() ] body = b"".join(parts) - url = f"https://api.telegram.org/bot{bot_token}/sendAudio" - req = urllib.request.Request(url, data=body, headers={"Content-Type": f"multipart/form-data; boundary={boundary}"}) + url_audio = f"https://api.telegram.org/bot{bot_token}/sendAudio" + req_audio = urllib.request.Request(url_audio, data=body, headers={"Content-Type": f"multipart/form-data; boundary={boundary}"}) + audio_msg_id = None try: - with urllib.request.urlopen(req, timeout=60) as resp: + with urllib.request.urlopen(req_audio, timeout=60) as resp: data = json.loads(resp.read().decode("utf-8")) if data.get("ok"): - msg_id = data.get("result", {}).get("message_id") - logger.info("Aperçu MP3 envoyé à Telegram (message_id=%s)", msg_id) - if isinstance(msg_id, int): - log_envoi(task_id, sphere, msg_id) - return msg_id + audio_msg_id = data.get("result", {}).get("message_id") + logger.info("Aperçu MP3 envoyé à Telegram (message_id=%s, nom_fichier=%s)", audio_msg_id, nom_fichier) except Exception as e: - logger.warning("Échec envoi aperçu MP3 Telegram: %s", e) - return None + logger.warning("Échec envoi audio MP3 Telegram: %s", e) + return None + + # Envoi du/des messages de paroles ou instrumental en HTML + messages = preparer_messages_paroles(titre, tags, paroles) + texte_msg_id = None + url_text = f"https://api.telegram.org/bot{bot_token}/sendMessage" + + for idx, msg_text in enumerate(messages): + payload = json.dumps({ + "chat_id": chat_id, + "text": msg_text, + "parse_mode": "HTML" + }).encode("utf-8") + req_msg = urllib.request.Request(url_text, data=payload, headers={"Content-Type": "application/json"}) + try: + with urllib.request.urlopen(req_msg, timeout=20) as resp: + data = json.loads(resp.read().decode("utf-8")) + if data.get("ok"): + mid = data.get("result", {}).get("message_id") + if idx == 0: + texte_msg_id = mid + logger.info("Message texte #%d envoyé à Telegram (message_id=%s)", idx + 1, mid) + except Exception as e: + logger.warning("Échec envoi message texte Telegram #%d: %s", idx + 1, e) + + if isinstance(audio_msg_id, int): + first_text_id = int(texte_msg_id) if isinstance(texte_msg_id, int) else 0 + log_envoi(task_id, sphere, audio_msg_id, titre=titre, nom_fichier=nom_fichier, texte_message_id=first_text_id) + + return { + "message_id": audio_msg_id, + "texte_message_id": texte_msg_id + } @mcp.tool() def solde(sphere: str) -> dict: @@ -409,10 +616,18 @@ def valider(val_id: str, code: str) -> dict: } @mcp.tool() -def generer(sphere: str, tags: Optional[List[str]] = None, paroles: Optional[str] = None, prompt: Optional[str] = None, validation_id: Optional[str] = None) -> dict: +def generer( + sphere: str, + titre: str, + tags: Optional[List[str]] = None, + paroles: Optional[str] = None, + prompt: Optional[str] = None, + validation_id: Optional[str] = None +) -> dict: """Lance une génération musicale auprès de Treblo. Refuse si tags + paroles + prompt sont fournis ensemble, ou si plus de 64 tags, ou si le plafond journalier est atteint, ou tant que la validation humaine n'a pas été confirmée par Telegram.""" + titre_val = validate_titre(titre) sp = validate_sphere_access(sphere) check_daily_cap(sp) @@ -435,8 +650,25 @@ def generer(sphere: str, tags: Optional[List[str]] = None, paroles: Optional[str empreinte = compute_empreinte(sp, tag_list, prompt, paroles) - # Contrôle de la validation humaine obligatoire (usage unique) clean_val_id = str(validation_id).strip().lstrip("#") if validation_id else None + if clean_val_id: + v_path = get_validations_path() + if os.path.exists(v_path): + try: + with open(v_path, "r", encoding="utf-8") as f: + v_data = json.load(f) + for item in v_data.get("validations", []): + if item.get("id") == clean_val_id and item.get("status") == "APPROVED": + if item.get("sphere") != sp or item.get("empreinte") != empreinte: + raise ValueError( + f"Refus : l'approbation #{clean_val_id} ne correspond pas au contenu demandé " + f"(sphère ou empreinte différente). L'approbation reste intacte sans débit." + ) + except ValueError: + raise + except Exception: + pass + if not consume_approved_validation(sp, empreinte, clean_val_id): val_id = uuid.uuid4().hex[:8] code = f"{secrets.randbelow(1000000):06d}" @@ -460,7 +692,7 @@ def generer(sphere: str, tags: Optional[List[str]] = None, paroles: Optional[str empreinte=empreinte, code=code, expires_iso=expires_iso, - details={"tags": tag_list or [], "prompt": prompt or "", "paroles": paroles or ""} + details={"tags": tag_list or [], "prompt": prompt or "", "paroles": paroles or "", "titre": titre_val} ) raise ValueError( f"Refus : validation humaine requise par Telegram (demande non validée ou code non saisi). " @@ -505,9 +737,12 @@ def generer(sphere: str, tags: Optional[List[str]] = None, paroles: Optional[str statut_val = resp_data.get("status", "PENDING") + save_titre(task_id, titre_val) + entry = { "date": datetime.datetime.now(datetime.timezone.utc).isoformat(), "sphere": sp, + "titre": titre_val, "tags": tag_list or [], "prompt": prompt or "", "paroles": paroles or "", @@ -523,6 +758,7 @@ def generer(sphere: str, tags: Optional[List[str]] = None, paroles: Optional[str "task_id": task_id, "statut": statut_val, "sphere": sp, + "titre": titre_val, "tags": tag_list or [], "credits_avant": credits_avant, "credits_apres": credits_avant @@ -667,19 +903,21 @@ def recuperer(task_id: str, sphere: str) -> dict: subprocess.run(["ffmpeg", "-y", "-i", path, "-b:a", "192k", mp3_file], capture_output=True, check=True) break + titre = get_titre_for_task(task_id) entry = get_journal_entry(task_id) or {} meta = { "prompt": entry.get("prompt", data.get("prompt", "")), "tags": entry.get("tags", data.get("tags", [])), "paroles": entry.get("paroles", data.get("lyrics", "")), + "titre": entry.get("titre", titre), "date": entry.get("date", datetime.datetime.now(datetime.timezone.utc).isoformat()), "task_id": task_id } json_meta_path = os.path.join(dest_dir, f"{task_id}.json") - with open(json_meta_path, "w", encoding="utf-8") as f: - json.dump(meta, f, indent=2, ensure_ascii=False) + if not os.path.exists(json_meta_path): + with open(json_meta_path, "w", encoding="utf-8") as f: + json.dump(meta, f, indent=2, ensure_ascii=False) - # Relecture du solde réel après fin de tâche credits_real = None try: bal = treblo_balance(sp) @@ -689,9 +927,15 @@ def recuperer(task_id: str, sphere: str) -> dict: update_journal_task(task_id, "SUCCESS", credits_apres=credits_real) - # Envoi de l'aperçu MP3 à Telegram et traçage dans envois.jsonl if os.path.exists(mp3_file): - send_telegram_preview_mp3(sp, mp3_file, task_id) + send_telegram_preview_mp3( + sphere=sp, + mp3_path=mp3_file, + task_id=task_id, + titre=titre, + tags=meta.get("tags", []), + paroles=meta.get("paroles", "") + ) archive_target = flac_file if os.path.exists(flac_file) else (wav_file if os.path.exists(wav_file) else None) files = [f for f in [json_meta_path, mp3_file, archive_target] if f and os.path.exists(f)] diff --git a/tests/test_envoi_paroles.py b/tests/test_envoi_paroles.py new file mode 100755 index 0000000..6f548ba --- /dev/null +++ b/tests/test_envoi_paroles.py @@ -0,0 +1,288 @@ +# -*- coding: utf-8 -*- +import os +import sys +import json +import pytest +import datetime +import subprocess +from zoneinfo import ZoneInfo +from unittest.mock import MagicMock, patch + +from cap_check import TUNIS_TZ +from main import ( + compute_empreinte, + validate_titre, + nettoyer_titre_fichier, + titre_vers_nom_fichier, + echapper_html, + preparer_messages_paroles, + generer, + valider, + send_telegram_preview_mp3, + get_journal_path, + get_validations_path, + get_envois_path, + get_titres_path, + current_sphere_var +) + +@pytest.fixture(autouse=True) +def clean_test_env(monkeypatch, tmp_path): + j_file = str(tmp_path / "journal.jsonl") + v_file = str(tmp_path / "validations.json") + e_file = str(tmp_path / "envois.jsonl") + t_file = str(tmp_path / "titres.json") + + monkeypatch.setattr("main.get_journal_path", lambda: j_file) + monkeypatch.setattr("main.get_validations_path", lambda: v_file) + monkeypatch.setattr("main.get_envois_path", lambda: e_file) + monkeypatch.setattr("main.get_titres_path", lambda: t_file) + + monkeypatch.setenv("TREBLO_MCP_TOKEN_NYORA", "test_nyora_token_123456789012345678901234567890123456") + monkeypatch.setenv("TREBLO_MCP_TOKEN_PERSO", "test_perso_token_123456789012345678901234567890123456") + monkeypatch.setenv("TREBLO_KEY_NYORA", "test_nyora_key") + monkeypatch.setenv("TREBLO_KEY_PERSO", "test_perso_key") + monkeypatch.setenv("TELEGRAM_BOT_TOKEN_NYORA", "fake_bot_token") + monkeypatch.setenv("TELEGRAM_CHAT_ID", "2084513684") + + # Mocks de sécurité : interdire tout envoi réel + monkeypatch.setattr("main.send_telegram_validation_request", lambda *args, **kwargs: None) + + +def test_validation_id_autre_contenu_refuse(monkeypatch, tmp_path): + """T0. Quand un validation_id est fourni mais ne correspond pas au contenu (tags/prompt/paroles), + refus clair sans débit, et l'approbation reste intacte (statut APPROVED).""" + v_file = str(tmp_path / "validations.json") + now_tunis = datetime.datetime.now(TUNIS_TZ) + exp = (now_tunis + datetime.timedelta(minutes=15)).isoformat() + + # Approbation pour des tags 'blues' + emp_blues = compute_empreinte("nyora", ["blues"], "", "") + + init_data = { + "validations": [ + { + "id": "val_blues_ok", + "sphere": "nyora", + "empreinte": emp_blues, + "code": "654321", + "status": "APPROVED", + "attempts": 0, + "created_at": now_tunis.isoformat(), + "expires_at": exp, + "details": {"tags": ["blues"], "prompt": "", "paroles": ""} + } + ] + } + with open(v_file, "w", encoding="utf-8") as f: + json.dump(init_data, f) + + token_cv = current_sphere_var.set("nyora") + try: + balance_called = {"count": 0} + def fake_balance(sp): + balance_called["count"] += 1 + return {"sphere": sp, "total": 9200, "num_credits": 0, "num_credits_payg": 9200} + monkeypatch.setattr("main.treblo_balance", fake_balance) + + # Appel avec d'autres tags ("ambient") et le validation_id "val_blues_ok" + with pytest.raises(ValueError) as exc: + generer(sphere="nyora", titre="Test Ambient", tags=["ambient"], validation_id="val_blues_ok") + + err = str(exc.value).lower() + assert "refus" in err or "approbation" in err or "empreinte" in err + + # L'approbation doit rester intacte (APPROVED) + with open(v_file, "r", encoding="utf-8") as f: + v_check = json.load(f) + assert v_check["validations"][0]["status"] == "APPROVED" + assert "used_at" not in v_check["validations"][0] + + # Aucun appel Treblo balance pour générer + assert balance_called["count"] == 0 + + # Aucun journal écrit + j_path = str(tmp_path / "journal.jsonl") + assert not os.path.exists(j_path) or os.path.getsize(j_path) == 0 + + finally: + current_sphere_var.reset(token_cv) + + +def test_nom_fichier_depuis_titre(): + """T2. Nettoyage du nom de fichier : accents conservés, espaces multiples réduits, extension .mp3.""" + assert titre_vers_nom_fichier("Brume de Nuit") == "Brume de Nuit.mp3" + assert titre_vers_nom_fichier("Blues sous la Pluie") == "Blues sous la Pluie.mp3" + assert titre_vers_nom_fichier("Éphémère été à Paris") == "Éphémère été à Paris.mp3" + assert titre_vers_nom_fichier(" Chanson avec espaces ") == "Chanson avec espaces.mp3" + + +def test_nom_fichier_caracteres_interdits(): + """T2. Remplacement des caractères interdits / \\ : * ? \" < > | et caractères de contrôle par un tiret, limite 80 car.""" + raw = 'Rock / Pop : Live * 2026 ? "Great" | New \\ Best\x07' + res = titre_vers_nom_fichier(raw) + assert res == 'Rock - Pop - Live - 2026 - -Great- -Old- - New - Best-.mp3' + for c in '/\\:*?"<>|\x07': + assert c not in res + + # Troncation à 80 caractères au plus (hors extension) + long_titre = "Z" * 120 + res_long = titre_vers_nom_fichier(long_titre) + assert res_long == ("Z" * 80) + ".mp3" + + +def test_titre_obligatoire(monkeypatch, tmp_path): + """T1. Le paramètre titre est obligatoire, 1-60 caractères, sans nom d'artiste ni formule 'comme X'.""" + token_cv = current_sphere_var.set("nyora") + try: + # Titre vide + with pytest.raises(ValueError) as exc1: + generer(sphere="nyora", titre="") + assert "titre" in str(exc1.value).lower() + + # Titre avec espaces seuls + with pytest.raises(ValueError) as exc1b: + generer(sphere="nyora", titre=" ") + assert "titre" in str(exc1b.value).lower() + + # Titre > 60 caractères + with pytest.raises(ValueError) as exc2: + generer(sphere="nyora", titre="A" * 61, tags=["ambient"]) + assert "60" in str(exc2.value) + + # Formule 'comme X' interdite + with pytest.raises(ValueError) as exc3: + generer(sphere="nyora", titre="Blues comme BB King", tags=["blues"]) + assert "comme" in str(exc3.value).lower() + + # Formule 'like X' + with pytest.raises(ValueError) as exc3b: + generer(sphere="nyora", titre="Track like Miles Davis", tags=["jazz"]) + assert "titre" in str(exc3b.value).lower() or "comme" in str(exc3b.value).lower() + + # Titre valide accepté par la validation + assert validate_titre("Brume de Nuit") == "Brume de Nuit" + finally: + current_sphere_var.reset(token_cv) + + +def test_paroles_mise_en_forme(): + """T3. Paroles : titre en gras avec 🎵, étiquettes en italique, séparateur, paroles en blockquote avec strophes.""" + paroles = "Late at night when the city is still\nI hear the blues rolling down the hill\n\nOld acoustic guitar crying in the rain\nWhispering secrets of sorrow and pain" + msgs = preparer_messages_paroles( + titre="Blues sous la Pluie", + tags=["southern soul", "blues", "soulful"], + paroles=paroles + ) + assert len(msgs) == 1 + m = msgs[0] + assert "🎵 Blues sous la Pluie" in m + assert "southern soul, blues, soulful" in m + assert "---" in m + assert "
" in m and "
" in m + # Vérification que le saut de ligne entre strophes (\n\n) est bien conservé + assert "Late at night when the city is still\nI hear the blues rolling down the hill\n\nOld acoustic guitar crying in the rain\nWhispering secrets of sorrow and pain" in m + + +def test_paroles_echappement_html(): + """T3. Tout le texte est échappé (&, <, >) avant mise en forme.""" + msgs = preparer_messages_paroles( + titre="Rock & Roll ", + tags=["r&b", ""], + paroles="Strophe 1 & 2 \nFin > début" + ) + assert len(msgs) == 1 + m = msgs[0] + assert "Rock & Roll <Live>" in m + assert "r&b, <metal>" in m + assert "Strophe 1 & 2 <test>\nFin > début" in m + assert "" not in m + assert "" not in m + assert "" not in m + + +def test_paroles_decoupage_4096(): + """T3. Au-delà de 4096 caractères, découpage aux frontières de strophe en plusieurs messages <= 4096 car.""" + strophe_txt = "Ligne de chanson répétée pour tester la longueur du message.\n" * 8 + # 12 strophes pour dépasser largement 4096 caractères + strophes = [f"Strophe {i+1} :\n" + strophe_txt for i in range(12)] + paroles = "\n\n".join(strophes) + assert len(paroles) > 5000 + + msgs = preparer_messages_paroles( + titre="Épopée Longue", + tags=["epic", "ambient"], + paroles=paroles + ) + assert len(msgs) >= 2 + for idx, m in enumerate(msgs): + assert len(m) <= 4096 + assert m.endswith("") + if idx == 0: + assert "🎵 Épopée Longue" in m + assert "epic, ambient" in m + assert "---" in m + assert "
" in m + else: + assert "
" in m + + # Vérifier que toutes les strophes sont présentes dans l'ensemble des messages + corpus = "".join(msgs) + for i in range(12): + assert f"Strophe {i+1} :" in corpus + + +def test_instrumental_message_dedie(): + """T3. Chanson instrumentale sans paroles : court message Instrumental avec titre et étiquettes.""" + msgs = preparer_messages_paroles( + titre="Brume de Nuit", + tags=["ambient", "piano", "chill"], + paroles="" + ) + assert len(msgs) == 1 + m = msgs[0] + assert "🎵 Brume de Nuit" in m + assert "ambient, piano, chill" in m + assert "Instrumental" in m + assert "
" not in m + + +def test_envoi_cli_claude(monkeypatch, tmp_path): + """T4. Script /app/envoyer_apercu.py avec --aide mentionnant task_id et --titre, et exécution conforme.""" + # Test aide + script_path = "/app/envoyer_apercu.py" + if not os.path.exists(script_path): + script_path = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "envoyer_apercu.py") + + proc = subprocess.run([sys.executable, script_path, "--aide"], capture_output=True, text=True) + assert proc.returncode == 0 + assert "task_id" in proc.stdout + assert "--titre" in proc.stdout + + # Test fonctionnel CLI avec simulateur Telegram + musique_dir = tmp_path / "musique" / "perso" + musique_dir.mkdir(parents=True, exist_ok=True) + mp3_file = musique_dir / "task_cli_test_123.mp3" + mp3_file.write_bytes(b"FAKE_AUDIO_DATA") + + json_file = musique_dir / "task_cli_test_123.json" + json_file.write_text(json.dumps({"tags": ["blues"], "paroles": "Lyrics"}), encoding="utf-8") + + calls = [] + def fake_send(sphere, mp3_path, task_id, titre=None, tags=None, paroles=None): + calls.append({"sphere": sphere, "task_id": task_id, "titre": titre, "tags": tags, "paroles": paroles}) + return {"message_id": 1234, "texte_message_id": 5678} + + import envoyer_apercu + monkeypatch.setattr(envoyer_apercu, "send_telegram_preview_mp3", fake_send) + monkeypatch.setattr(envoyer_apercu, "get_titre_for_task", lambda tid: "Blues sous la Pluie") + monkeypatch.setattr(envoyer_apercu, "get_musique_dir", lambda sp: str(tmp_path / "musique" / sp)) + + test_argv = ["envoyer_apercu.py", "task_cli_test_123", "--sphere", "perso", "--titre", "Blues sous la Pluie"] + monkeypatch.setattr(sys, "argv", test_argv) + + envoyer_apercu.main() + assert len(calls) == 1 + assert calls[0]["task_id"] == "task_cli_test_123" + assert calls[0]["sphere"] == "perso" + assert calls[0]["titre"] == "Blues sous la Pluie" diff --git a/tests/test_validation_durcie.py b/tests/test_validation_durcie.py index cfc1fda..8195eb9 100755 --- a/tests/test_validation_durcie.py +++ b/tests/test_validation_durcie.py @@ -78,7 +78,7 @@ def test_approbation_usage_unique(monkeypatch, tmp_path): monkeypatch.setattr("urllib.request.urlopen", lambda *args, **kwargs: mock_resp) # 1er appel à generer : doit réussir et consommer l'approbation - res = generer(sphere="nyora", tags=["ambient"]) + res = generer(sphere="nyora", titre="Chanson Test", tags=["ambient"]) assert res.get("task_id") == "task_unique_1" # Vérifier que le statut est passé à USED @@ -88,7 +88,7 @@ def test_approbation_usage_unique(monkeypatch, tmp_path): # 2ème appel avec les mêmes paramètres : doit refuser car l'approbation est déjà consommée with pytest.raises(ValueError) as exc: - generer(sphere="nyora", tags=["ambient"]) + generer(sphere="nyora", titre="Chanson Test", tags=["ambient"]) assert "validation humaine requise" in str(exc.value) finally: @@ -241,7 +241,7 @@ def test_generer_sans_validation_sans_debit(monkeypatch, tmp_path): # Aucune validation dans validations.json with pytest.raises(ValueError) as exc: - generer(sphere="nyora", tags=["ambient", "chill"]) + generer(sphere="nyora", titre="Chanson Test", tags=["ambient", "chill"]) err_msg = str(exc.value) assert "validation humaine requise" in err_msg.lower()