Skip to content

armgit / laya

Public Imported from GitHub
0

Non-autoregressive System 1 decision engine. Typed choice, score and yes/no decisions over any text in a single forward pass, in 100+ languages, with a router that picks the right checkpoint per request.

fix(email): clean Portuguese and Spanish replies, signatures and footers (#200)

Paulo Carinhena7a58ab6fbf7e
diff --git a/laya/email.py b/laya/email.py
index 55127417..e1fd563c 100644
--- a/laya/email.py
+++ b/laya/email.py
@@ -1,21 +1,74 @@
-"""Email utilities for cleaning and structuring email inputs in laya."""
+"""Email utilities for cleaning and structuring email inputs in laya.
+
+The markers below cover English, Portuguese and Spanish mail clients. The Router already sends
+Portuguese and Spanish states to the multilingual checkpoint, but with English-only markers their
+cleaning was a no-op: Gmail's `Em ... escreveu:`, Outlook's `-----Mensagem original-----`, the
+`Atenciosamente` sign-off and the confidentiality footer all reached the model, and the quoted
+history (often a *different* request) weighed on the answer as much as the new message did.
+"""
import re
from typing import Dict, Optional
_QUOTE_HEADERS = [
re.compile(r"^\s*On .{0,300}wrote:\s*$", re.I),
+ # "Em resposta ao que você escreveu:" is body text; a client's attribution always carries a date
+ re.compile(r"^\s*Em (?=.*\d).{0,300}escreveu:\s*$", re.I),
+ re.compile(r"^\s*El (?=.*\d).{0,300}escribi[óo]:\s*$", re.I),
re.compile(r"^\s*-{2,}\s*(Original|Forwarded) Message\s*-{2,}", re.I),
+ re.compile(r"^\s*-{2,}\s*(Mensagem (original|encaminhada)|Mensaje (original|reenviado))\s*-{2,}", re.I),
re.compile(r"^\s*_{8,}\s*$"),
re.compile(r"^\s*From:\s.+$", re.I),
+ # `De:` also opens ordinary Portuguese/Spanish lines ("De: 10/09 a 15/09"), so the Outlook
+ # header is only recognised when it carries an address
+ re.compile(r"^\s*De:\s.*[@<]", re.I),
]
+# Gmail wraps a long attribution line, leaving `[email protected]> escreveu:` alone on the next line.
+# That tail cuts too, and takes the `On/Em/El ...` head it belongs to with it.
+_ATTRIBUTION_TAIL = re.compile(r"^.{0,120}\S@\S+\s+(wrote|escreveu|escribi[óo]):\s*$", re.I)
+_ATTRIBUTION_HEAD = re.compile(r"^\s*(On|Em|El) (?=.*\d)", re.I)
+# Exchange often leaves the address out of Outlook's reply header ("De: Maria Souza"), so a bare `De:`
+# only cuts when the header's own `Enviado:` line, or a dated `Data:`/`Fecha:` line, follows it.
+# `Para:` is not enough: "De: 10/09 / Para: 15/09" is how a leave request reads.
+_HEADER_FROM_NAME = re.compile(r"^\s*De:\s+\S", re.I)
+_HEADER_NEXT = re.compile(r"^\s*(Enviad[oa]( em| el)?:\s|(Data|Fecha):\s.*\d{4})", re.I)
_SIGNATURE_MARKERS = [
re.compile(r"^\s*--\s*$"),
re.compile(r"^\s*(best|kind|warm|many thanks|thanks|thank you|regards|cheers|sincerely)[\w ,!.]*$", re.I),
re.compile(r"^\s*sent from my (iphone|android|mobile|ipad)", re.I),
+ # Portuguese/Spanish sign-offs match only on their own: "Obrigado pelo retorno, mas ..." is a
+ # request, not a signature, so unlike the English marker no trailing words are allowed
+ re.compile(
+ r"^\s*(atenciosamente|att|abraços?|abs|um abraço|cordialmente|grat[oa]|(muito )?obrigad[oa]s?"
+ r"( desde já| pela atenção)?|(com os melhores )?cumprimentos|saudações|"
+ r"(un )?saludos?( cordiales)?|atentamente|(muchas )?gracias( de antemano)?)[\s,!.]*$",
+ re.I,
+ ),
]
+# Mobile and mail-app footers. Only a line that is nothing *but* the footer matches -- "Enviado do meu
+# celular o comprovante ontem." is a request -- and such a line may run to 60 characters, since
+# Samsung's default ("Enviado do meu smartphone Samsung Galaxy.") is longer than a sign-off's 40.
+_DEVICE = (r"iphone|ipad|android|ios|celular|telemóvel|móvil|galaxy|smartphone|samsung|tablet|"
+ r"outlook|yahoo|mail|e-?mail|gmail|windows")
+_DEVICE_FOOTER = re.compile(
+ r"^\s*((enviad[oa] (do|pelo|pela|via|desde|a partir do)( meu| minha| mi)?|sent from( my)?)"
+ r" (%s)( (%s|para|for|no|na|\d+))*|(obter o|get) outlook (para|for) (ios|android))[\s.!]*$"
+ % (_DEVICE, _DEVICE),
+ re.I,
+)
_DISCLAIMER = re.compile(
r"(confidential|intended (solely )?for the (use of the )?(named )?(addressee|recipient)|"
- r"if you (have )?received this (e-?mail|message) in error)",
+ r"if you (have )?received this (e-?mail|message) in error|"
+ # Portuguese/Spanish: tied to "this message/e-mail" rather than the bare word `confidencial`,
+ # which a sender's own request ("preciso do contrato confidencial") uses just as often
+ r"\b(esta|este) (mensagem|e-?mail|mensaje|correo)\b[^.]{0,80}(confidencia|sigilos|privilegiad)|"
+ r"\b(uso exclusivo|exclusivamente|únicamente|unicamente)\b[^.]{0,30}"
+ r"(destinatári|destinatari|pessoa|persona|entidade|entidad)|"
+ r"\b(recebeu|recebido|receber) (esta|este) (mensagem|e-?mail)\b[^.]{0,20} por (engano|erro)|"
+ r"\b(ha recibido|recibió|recibe) (este|esta) (mensaje|correo)\b[^.]{0,20} por error|"
+ # the "think before printing" footer, tied to its environmental ending rather than to
+ # `antes de imprimir`, which a request uses too ("antes de imprimir o boleto, confira o valor")
+ r"\bantes de imprimir\b[^.]{0,100}(meio ambiente|medio ambiente|natureza|planeta|realmente necess)|"
+ r"\b(meio|medio) ambiente\b[^.]{0,30}antes de imprimir)",
re.I,
)
_SENTENCE = re.compile(r"(?<=[.!?])\s+")
@@ -38,15 +91,25 @@ def clean_email_body(body: str, max_chars: int = 3000) -> str:
"""Remove quoted email history, signatures and disclaimers to keep input focused."""
text = (body or "").replace("\r\n", "\n").replace("\r", "\n").replace("\\n", "\n")
lines = []
- for line in text.split("\n"):
+ src = text.split("\n")
+ for i, line in enumerate(src):
if any(p.match(line) for p in _QUOTE_HEADERS) and lines:
break
+ if (lines and _HEADER_FROM_NAME.match(line) and i + 1 < len(src)
+ and _HEADER_NEXT.match(src[i + 1])):
+ break
+ if _ATTRIBUTION_TAIL.match(line) and lines:
+ if _ATTRIBUTION_HEAD.match(lines[-1]):
+ lines.pop()
+ break
if line.lstrip().startswith(">"):
continue
lines.append(line.rstrip())
cut = len(lines)
for i in range(max(1, min(int(len(lines) * 0.6), len(lines) - 8)), len(lines)):
- if len(lines[i].strip()) <= 40 and any(p.match(lines[i]) for p in _SIGNATURE_MARKERS):
+ n = len(lines[i].strip())
+ if (n <= 40 and any(p.match(lines[i]) for p in _SIGNATURE_MARKERS)) or (
+ n <= 60 and _DEVICE_FOOTER.match(lines[i])):
cut = i
break
lines = lines[:cut]
diff --git a/tests/test_email.py b/tests/test_email.py
index 8e3d401a..1e6b282a 100644
--- a/tests/test_email.py
+++ b/tests/test_email.py
@@ -98,6 +98,163 @@ check(
)
check("empty body stays empty", clean_email_body(""), "")
+# --------------------------------------------------------------- Portuguese and Spanish mail
+# With English-only markers none of this was removed, and the quoted history below (a cancellation)
+# reached the model next to the new message (a refund request).
+PT_EMAIL = """Olá equipe,
+
+Fomos cobrados duas vezes na fatura de março. Por favor, estornem a cobrança duplicada hoje.
+
+Atenciosamente,
+João Silva
+Financeiro - ACME Ltda
+
+Enviado do meu iPhone
+
+Esta mensagem pode conter informações confidenciais. Se você recebeu esta mensagem por engano, favor apagá-la.
+
+Em seg., 22 de set. de 2026 às 10:14, Suporte <[email protected]> escreveu:
+> Olá João, recebemos seu chamado de cancelamento do plano Enterprise.
+"""
+check(
+ "pt/full reply keeps only the request",
+ clean_email_body(PT_EMAIL),
+ "Olá equipe,\n\nFomos cobrados duas vezes na fatura de março. "
+ "Por favor, estornem a cobrança duplicada hoje.",
+)
+check(
+ "pt/outlook original-message block is cut",
+ clean_email_body(
+ "Segue o comprovante do pagamento.\n\n-----Mensagem original-----\n"
+ "De: Maria <[email protected]>\nAssunto: cancelar contrato\nQueremos cancelar o contrato."
+ ),
+ "Segue o comprovante do pagamento.",
+)
+check(
+ "pt/outlook header without separator is cut",
+ clean_email_body(
+ "Segue o comprovante.\n\nDe: Maria <[email protected]>\nEnviado: segunda-feira\n"
+ "Assunto: cancelar contrato\nQueremos cancelar o contrato."
+ ),
+ "Segue o comprovante.",
+)
+check(
+ "pt/gmail attribution wrapped over two lines is cut whole",
+ clean_email_body(
+ "O acesso voltou, obrigado.\n\nEm seg., 22 de set. de 2026 às 10:14, Suporte Técnico <\n"
+ "[email protected]> escreveu:\n> texto antigo"
+ ),
+ "O acesso voltou, obrigado.",
+)
+check(
+ "pt/short sign-off is removed",
+ clean_email_body("Bom dia,\nO boleto de março não chegou.\nObrigado,\nAna"),
+ "Bom dia,\nO boleto de março não chegou.",
+)
+check(
+ "es/reply keeps only the request",
+ clean_email_body(
+ "Hola,\nNo puedo acceder a mi cuenta desde ayer.\nSaludos,\nCarlos\n\n"
+ "El lun, 22 sept 2026 a las 10:14, Soporte <[email protected]> escribió:\n> texto anterior"
+ ),
+ "Hola,\nNo puedo acceder a mi cuenta desde ayer.",
+)
+check(
+ "es/disclaimer footer is dropped",
+ clean_email_body(
+ "Necesito la factura de marzo.\n\nSi usted ha recibido este mensaje por error, bórrelo."
+ ),
+ "Necesito la factura de marzo.",
+)
+
+# --------------------------------------------------------------- ...without eating the request
+check(
+ "pt/request mentioning `confidencial` is kept",
+ clean_email_body("Preciso do contrato confidencial assinado até sexta."),
+ "Preciso do contrato confidencial assinado até sexta.",
+)
+check(
+ "pt/`Obrigado` opening a sentence is not a signature",
+ clean_email_body("Oi,\nRecebi a resposta.\nObrigado pelo retorno, mas continua\nsem funcionar."),
+ "Oi,\nRecebi a resposta.\nObrigado pelo retorno, mas continua\nsem funcionar.",
+)
+check(
+ "pt/`caso tenha recebido` footer is dropped",
+ clean_email_body(
+ "Favor reenviar a nota fiscal.\n\nCaso tenha recebido esta mensagem por engano, "
+ "notifique o remetente."
+ ),
+ "Favor reenviar a nota fiscal.",
+)
+check(
+ "pt/gmail attribution wrapped inside the name is cut whole",
+ clean_email_body(
+ "Resolvido, pode fechar.\n\nEm qua., 24 de set. de 2026 às 09:02, Suporte\n"
+ "Técnico <[email protected]> escreveu:\n> texto antigo"
+ ),
+ "Resolvido, pode fechar.",
+)
+check(
+ "en/wrapped attribution is cut whole too",
+ clean_email_body(
+ "Fixed, thanks.\n\nOn Wed, Sep 24, 2026 at 9:02 AM Support Team <\n"
+ "[email protected]> wrote:\n> old text"
+ ),
+ "Fixed, thanks.",
+)
+check(
+ "pt/`Em ... escreveu:` without a date is body text",
+ clean_email_body("Oi,\nEm resposta ao que você escreveu:\no pedido 4411 ainda não chegou."),
+ "Oi,\nEm resposta ao que você escreveu:\no pedido 4411 ainda não chegou.",
+)
+check(
+ "pt/`destinado exclusivamente` in a request is kept",
+ clean_email_body("O valor é destinado exclusivamente ao pagamento do boleto. Podem confirmar?"),
+ "O valor é destinado exclusivamente ao pagamento do boleto. Podem confirmar?",
+)
+check(
+ "pt/`De:` without an address is body text",
+ clean_email_body("Preciso das férias.\nDe: 10/09 a 15/09\nPode aprovar?"),
+ "Preciso das férias.\nDe: 10/09 a 15/09\nPode aprovar?",
+)
+
+# --------------------------------------------------------------- Brazilian clients and footers
+BOLETO = "Preciso da segunda via do boleto."
+for label, footer in [
+ ("galaxy", "Enviado do meu Galaxy"),
+ ("samsung default, 41 characters", "Enviado do meu smartphone Samsung Galaxy."),
+ ("outlook ios", "Enviado do Outlook para iOS"),
+ ("outlook android download line", "Obter o Outlook para Android"),
+ ("windows mail", "Enviado do Email para Windows"),
+ ("yahoo", "Enviado do Yahoo Mail no Android"),
+ ("eco footer", "Antes de imprimir, pense em sua responsabilidade e compromisso com o MEIO AMBIENTE."),
+ ("eco footer, reversed", "Pense no meio ambiente antes de imprimir este e-mail."),
+]:
+ check("pt/footer removed: " + label, clean_email_body(BOLETO + "\n\n" + footer), BOLETO)
+check(
+ "en/outlook download line removed",
+ clean_email_body("Please resend the invoice.\n\nGet Outlook for iOS"),
+ "Please resend the invoice.",
+)
+# Exchange leaves the address out of the header; the `Enviado:`/dated `Data:` line under it still marks it
+for label, second in [("enviado", "Enviado: sexta-feira, 19 de setembro de 2026 10:02"),
+ ("data", "Data: sexta-feira, 19 de setembro de 2026 10:02")]:
+ check(
+ "pt/outlook header without address is cut: " + label,
+ clean_email_body("Segue o comprovante.\n\nDe: Maria Souza\n%s\nPara: Suporte\n"
+ "Assunto: cancelar contrato\n\nQueremos cancelar o contrato." % second),
+ "Segue o comprovante.",
+ )
+# ...and none of them may take the request with it
+for label, body in [
+ ("device words inside a request", "Oi,\nSegue o pedido.\nEnviado do meu celular o comprovante ontem."),
+ ("`De:`/`Para:` date range", "Preciso das férias.\nDe: 10/09\nPara: 15/09\nPode aprovar?"),
+ ("`De:` + undated `Data:`", "Relatório do evento.\nDe: João\nData: amanhã cedo\nPode confirmar?"),
+ ("`antes de imprimir` in a request", "Antes de imprimir o boleto, confira o valor. Está errado."),
+ ("`get` + device word", "Hi,\nThe box is at the front desk.\nGet mail"),
+]:
+ check("pt/kept: " + label, clean_email_body(body), body)
+
print("\n%d passed, %d failed" % (len(PASS), len(FAIL)))
for f in FAIL: