91 lines
3.9 KiB
Python
91 lines
3.9 KiB
Python
"""L'essai des brouillons sur l'instance de test (après preparer.py et configurer_ia.py) : une conversation par mail de
|
|
instance-de-test/mails/, « Generate reply » sur chacune, un rapport dans cases/ (hors de git) à faire juger.
|
|
|
|
Vérifie que Mailpit ne reçoit rien pendant la génération : un brouillon ne doit jamais partir.
|
|
|
|
python3 instance-de-test/essayer_brouillons.py [mot de passe System]
|
|
"""
|
|
import datetime
|
|
import html
|
|
import json
|
|
import re
|
|
import sys
|
|
import time
|
|
import urllib.request
|
|
from pathlib import Path
|
|
|
|
from session import connexion, req
|
|
|
|
MAILPIT = "http://127.0.0.1:9125/api/v1/messages"
|
|
ICI = Path(__file__).resolve().parent
|
|
MAILS = ICI / "mails"
|
|
ESSAIS = ["4g", "cible-perdue", "fuseau", "hors-base", "suite"] # « suite » : après l'échange « histoire »
|
|
|
|
|
|
def total_mailpit() -> int:
|
|
with urllib.request.urlopen(MAILPIT, timeout=10) as r:
|
|
return json.loads(r.read())["total"]
|
|
|
|
|
|
def en_html(texte: str) -> str:
|
|
return "".join(f"<p>{html.escape(p).replace(chr(10), '<br>')}</p>" for p in texte.strip().split("\n\n"))
|
|
|
|
|
|
def en_texte(contenu: str) -> str:
|
|
t = re.sub(r"<li>", "- ", re.sub(r"</p>|<br\s*/?>|</li>|</ul>", "\n", contenu))
|
|
return re.sub(r"\n{3,}", "\n\n", html.unescape(re.sub(r"<[^>]+>", "", t))).strip()
|
|
|
|
|
|
def mail(nom: str) -> tuple[str, str]:
|
|
objet, corps = (MAILS / f"{nom}.txt").read_text(encoding="utf-8").split("\n", 1)
|
|
return objet.strip(), corps.strip()
|
|
|
|
|
|
def conversation(boite: int, nom: str, contact: str) -> str:
|
|
objet, corps = mail(nom)
|
|
conv = req("POST", "/api/v1/conversations", {"inbox_id": boite, "contact_email": contact, "first_name": "Client",
|
|
"last_name": nom, "initiator": "contact", "subject": objet,
|
|
"content": en_html(corps)})
|
|
return conv["uuid"]
|
|
|
|
|
|
def main(mot_de_passe: str = "TestAdmin-2026!") -> None:
|
|
connexion(mot_de_passe)
|
|
boite = next(b["id"] for b in req("GET", "/api/v1/inboxes") if b["name"] == "Test")
|
|
avant = total_mailpit()
|
|
# L'échange précédent du contact « suite » : sa question et la réponse de l'agent (elle part dans Mailpit).
|
|
histoire = conversation(boite, "histoire", "client-suite@example.com")
|
|
req("POST", f"/api/v1/conversations/{histoire}/messages",
|
|
{"message": en_html((MAILS / "histoire-reponse.txt").read_text(encoding="utf-8")), "private": False,
|
|
"sender_type": "agent", "to": ["client-suite@example.com"]})
|
|
uuids = {n: conversation(boite, n, "client-suite@example.com" if n == "suite" else f"client-{n}@example.com")
|
|
for n in ESSAIS}
|
|
for _ in range(30): # attendre que la réponse de l'agent soit arrivée dans Mailpit
|
|
if total_mailpit() > avant:
|
|
break
|
|
time.sleep(1)
|
|
reference = total_mailpit()
|
|
|
|
lignes = [f"# Essai des brouillons, {datetime.date.today()}", ""]
|
|
for n in ESSAIS:
|
|
objet, corps = mail(n)
|
|
debut = time.monotonic()
|
|
rep = req("POST", "/api/v1/ai/generate-reply", {"conversation_uuid": uuids[n], "instruction": ""}, timeout=300)
|
|
duree = time.monotonic() - debut
|
|
brouillon = en_texte(rep.get("content") or "") if rep.get("status") == "completed" else json.dumps(rep)
|
|
print(f"{n} : {rep.get('status')} en {duree:.0f} s")
|
|
lignes += [f"## {n} : {objet}", "", f"Durée : {duree:.0f} s ; statut : {rep.get('status')}", "",
|
|
"**Le mail**", "", corps, "", "**Le brouillon**", "", brouillon, ""]
|
|
|
|
time.sleep(5)
|
|
if total_mailpit() != reference:
|
|
sys.exit(f"un message est sorti pendant la génération : Mailpit {reference} → {total_mailpit()}")
|
|
sortie = ICI.parent / "cases" / f"essai-brouillons-{datetime.date.today()}.md"
|
|
sortie.parent.mkdir(exist_ok=True)
|
|
sortie.write_text("\n".join(lignes), encoding="utf-8")
|
|
print(f"Mailpit inchangé pendant la génération ({reference}) ; rapport : {sortie}")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main(*sys.argv[1:2])
|