Conversations : le transcript lisible d'une conversation (texte seul, pièces jointes en lien)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
369f2e0a44
commit
116488ddd4
3 files changed
+139
No files matched your search
Whitespace-only changes.
@@ -0,0 +1,80 @@
|
||||
"""Le transcript lisible d'une conversation pompée (transcript.md) : du texte seul, jamais le HTML d'un mail ; les images
|
||||
en ligne, les autres pièces jointes en lien, vers attachments/. Les messages sont déjà sous leur forme locale (pomper.py)."""
|
||||
import re
|
||||
import urllib.parse
|
||||
from datetime import datetime, timezone
|
||||
from html.parser import HTMLParser
|
||||
|
||||
BLOCS = {"p", "div", "li", "tr", "blockquote", "h1", "h2", "h3", "h4", "h5", "h6"}
|
||||
|
||||
|
||||
class _Texte(HTMLParser):
|
||||
def __init__(self):
|
||||
super().__init__(convert_charrefs=True)
|
||||
self.morceaux, self._cache = [], 0
|
||||
|
||||
def handle_starttag(self, tag, attrs):
|
||||
if tag in ("script", "style"):
|
||||
self._cache += 1
|
||||
elif tag == "br":
|
||||
self.morceaux.append("\n")
|
||||
elif tag in BLOCS:
|
||||
self.morceaux.append("\n\n")
|
||||
|
||||
def handle_endtag(self, tag):
|
||||
if tag in ("script", "style"):
|
||||
self._cache = max(0, self._cache - 1)
|
||||
elif tag in BLOCS:
|
||||
self.morceaux.append("\n\n")
|
||||
|
||||
def handle_data(self, data):
|
||||
if not self._cache:
|
||||
self.morceaux.append(data)
|
||||
|
||||
|
||||
def texte(contenu_html: str) -> str:
|
||||
"""Le HTML d'un message en texte : balises retirées, entités décodées, paragraphes gardés."""
|
||||
p = _Texte()
|
||||
p.feed(contenu_html or "")
|
||||
p.close()
|
||||
t = re.sub(r"[ \t]*\n[ \t]*", "\n", "".join(p.morceaux))
|
||||
return re.sub(r"\n{3,}", "\n\n", t).strip()
|
||||
|
||||
|
||||
def _heure(t: str) -> str:
|
||||
return datetime.fromisoformat(t).astimezone(timezone.utc).strftime("%Y-%m-%d %H:%M") + " UTC"
|
||||
|
||||
|
||||
def _nom(personne: dict | None) -> str:
|
||||
return " ".join(x for x in ((personne or {}).get("first_name"), (personne or {}).get("last_name")) if x)
|
||||
|
||||
|
||||
def _pieces(pieces: list[dict]) -> list[str]:
|
||||
lignes = []
|
||||
for a in pieces:
|
||||
cible = urllib.parse.quote(a.get("url") or "")
|
||||
image = (a.get("content_type") or "").startswith("image/") and a.get("content_type") != "image/svg+xml"
|
||||
lignes.append(f"{'!' * image}[{a.get('name')}]({cible})")
|
||||
return lignes
|
||||
|
||||
|
||||
def transcript(conversation: dict, messages: list[dict]) -> str:
|
||||
c = conversation.get("contact") or {}
|
||||
contact = " ".join(x for x in (_nom(c), c.get("email")) if x)
|
||||
morceaux = [f"# {conversation.get('subject') or '(sans sujet)'} (#{conversation.get('reference_number')})",
|
||||
f"Contact : {contact} · Boîte : {conversation.get('inbox_name')} · Statut : {conversation.get('status')}"
|
||||
f" · Créée : {_heure(conversation['created_at'])}"]
|
||||
for m in messages:
|
||||
corps = (m.get("text_content") or "").strip() or texte(m.get("content"))
|
||||
if m.get("type") == "activity":
|
||||
morceaux.append(f"*{_heure(m['created_at'])} — {corps}*")
|
||||
continue
|
||||
client = m.get("sender_type") == "contact"
|
||||
role = "note privée" if m.get("private") else "client" if client else "agent"
|
||||
auteur = _nom(m.get("author")) or ("Client" if client else "Agent")
|
||||
morceaux.append(f"## {_heure(m['created_at'])} — {auteur} ({role})")
|
||||
if corps:
|
||||
morceaux.append(corps)
|
||||
if lignes := _pieces(m.get("attachments") or []):
|
||||
morceaux.append("\n".join(lignes))
|
||||
return "\n\n".join(morceaux) + "\n"
|
||||
@@ -0,0 +1,59 @@
|
||||
import unittest
|
||||
|
||||
from conversations.transcript import texte, transcript
|
||||
|
||||
CONV = {"subject": "Saut", "reference_number": "42", "inbox_name": "Support", "status": "Open",
|
||||
"created_at": "2026-11-18T08:00:00Z", "contact": {"first_name": "Jean", "last_name": "Dupont", "email": "j@x.ch"}}
|
||||
|
||||
|
||||
def piece(nom, type_):
|
||||
return {"name": nom, "content_type": type_, "size": 3, "url": f"attachments/{nom}", "uuid": "u-" + nom}
|
||||
|
||||
|
||||
def msg(heure, type_="incoming", expediteur="contact", prive=False, contenu="<p>Bonjour</p>", pieces=(), auteur=None):
|
||||
return {"created_at": f"2026-11-18T{heure}:00Z", "type": type_, "sender_type": expediteur, "private": prive,
|
||||
"content": contenu, "text_content": "", "attachments": list(pieces), "author": auteur}
|
||||
|
||||
|
||||
MESSAGES = [
|
||||
msg("08:00", pieces=[piece("photo 1.jpg", "image/jpeg"), piece("r.pdf", "application/pdf")],
|
||||
auteur={"first_name": "Jean", "last_name": "Dupont"}),
|
||||
msg("08:05", type_="activity", expediteur="agent", contenu="Assigned to Max"),
|
||||
msg("08:10", type_="outgoing", expediteur="agent", prive=True, contenu="<p>À vérifier</p>",
|
||||
auteur={"first_name": "Max", "last_name": ""}),
|
||||
]
|
||||
|
||||
|
||||
class TestTexte(unittest.TestCase):
|
||||
def test_paragraphes_et_entites(self):
|
||||
self.assertEqual(texte("<p>Bonjour & merci</p><p>L1<br>L2</p>"), "Bonjour\xa0& merci\n\nL1\nL2")
|
||||
|
||||
def test_script_et_style_retires(self):
|
||||
self.assertEqual(texte("<style>p{}</style><script>x()</script><div>ok</div>"), "ok")
|
||||
|
||||
def test_balise_echappee_reste_du_texte(self): # l'app échappe à l'affichage, pas ici
|
||||
self.assertEqual(texte("<script>"), "<script>")
|
||||
|
||||
|
||||
class TestTranscript(unittest.TestCase):
|
||||
def test_entete(self):
|
||||
self.assertTrue(transcript(CONV, MESSAGES).startswith(
|
||||
"# Saut (#42)\n\nContact : Jean Dupont j@x.ch · Boîte : Support · Statut : Open · Créée : 2026-11-18 08:00 UTC\n"))
|
||||
|
||||
def test_messages(self):
|
||||
t = transcript(CONV, MESSAGES)
|
||||
self.assertIn("## 2026-11-18 08:00 UTC — Jean Dupont (client)\n\nBonjour", t)
|
||||
self.assertIn("", t)
|
||||
self.assertIn("[r.pdf](attachments/r.pdf)", t)
|
||||
self.assertIn("*2026-11-18 08:05 UTC — Assigned to Max*", t)
|
||||
self.assertIn("## 2026-11-18 08:10 UTC — Max (note privée)\n\nÀ vérifier", t)
|
||||
|
||||
def test_auteur_absent(self):
|
||||
self.assertIn("— Client (client)", transcript(CONV, [msg("09:00")]))
|
||||
|
||||
def test_svg_en_lien(self): # un svg est un lien, jamais une image en ligne
|
||||
self.assertNotIn("![", transcript(CONV, [msg("09:00", pieces=[piece("a.svg", "image/svg+xml")])]))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user