#!/usr/bin/env python3 """Generate and validate synthetic abandoned-cart email examples.""" from __future__ import annotations import json import random import re import unicodedata from collections import Counter, defaultdict from pathlib import Path OUTPUT_DIR = Path(__file__).resolve().parent / "data" SEED = 73 LANGUAGES = ("en", "fr") STAGES = ("first", "second", "final") VARIANTS = ("balanced", "focused_edit", "high_risk") CHECK_IDS = ("clarity", "cta", "personalization", "timing", "discount") PRODUCTS = ( {"slug": "trail-shoes", "en": "trail running shoes", "fr": "chaussures de trail"}, {"slug": "coffee-maker", "en": "ceramic coffee maker", "fr": "cafetière en céramique"}, {"slug": "linen-shirt", "en": "linen shirt", "fr": "chemise en lin"}, {"slug": "wireless-headphones", "en": "wireless headphones", "fr": "casque sans fil"}, {"slug": "desk-lamp", "en": "adjustable desk lamp", "fr": "lampe de bureau réglable"}, {"slug": "travel-backpack", "en": "travel backpack", "fr": "sac à dos de voyage"}, {"slug": "skincare-set", "en": "skincare set", "fr": "coffret de soins"}, {"slug": "cookbook", "en": "vegetarian cookbook", "fr": "livre de cuisine végétarienne"}, {"slug": "yoga-mat", "en": "recycled yoga mat", "fr": "tapis de yoga recyclé"}, {"slug": "watch-band", "en": "smartwatch band", "fr": "bracelet de montre connectée"}, ) IDEAL_DELAYS = {"first": 2, "second": 24, "final": 72} OUTSIDE_DELAYS = {"first": 24, "second": 72, "final": 24} NEARBY_DELAYS = {"first": 8, "second": 40, "final": 90} CONTEXT_PATTERN = re.compile( r"cart|basket|panier|commande|order|checkout|saved|selection|sélection|laiss[ée]|oubli[ée]", re.IGNORECASE, ) CTA_ACTION_PATTERN = re.compile( r"return|complete|finish|resume|view|recover|checkout|buy|shop|continue|retrieve|restore|" r"finaliser|terminer|reprendre|retrouver|voir|commander|continuer|payer|retourner", re.IGNORECASE, ) GENERIC_CTA_PATTERN = re.compile(r"click here|cliquez ici|learn more|en savoir plus", re.IGNORECASE) NAME_TOKEN_PATTERN = re.compile( r"\{\{\s*(first_?name|customer_?name|name)\s*\}\}|" r"\[\[\s*(first_?name|name)\s*\]\]|\*\|FNAME\|\*|%FIRSTNAME%", re.IGNORECASE, ) COMMERCE_TOKEN_PATTERN = re.compile( r"\{\{\s*(product_?name|cart_?url|cart_?items?|product_?url)\s*\}\}|" r"\[\[\s*(product|cart)[^\]]*\]\]", re.IGNORECASE, ) SECOND_PERSON_PATTERN = re.compile( r"\byour\b|\byou\b|\bvotre\b|\bvos\b|\bvous\b|\bton\b|\btes\b", re.IGNORECASE, ) GREETING_PATTERN = re.compile(r"\bhi\b|\bhello\b|\bbonjour\b|\bsalut\b", re.IGNORECASE) DISCOUNT_PATTERN = re.compile(r"(\d{1,2}(?:[.,]\d+)?)\s*%") def count_words(text: str) -> int: return len(text.strip().split()) if text.strip() else 0 def uppercase_ratio(text: str) -> float: letters = [character for character in text if character.isalpha()] if not letters: return 0.0 return sum(character.isupper() for character in letters) / len(letters) def evaluate_clarity(draft: dict[str, object]) -> int: subject = str(draft["subject"]) body = str(draft["body"]) score = 0 if 25 <= len(subject) <= 60: score += 5 elif 15 <= len(subject) <= 70: score += 3 if CONTEXT_PATTERN.search(subject): score += 4 body_words = count_words(body) if 35 <= body_words <= 180: score += 6 elif 20 <= body_words <= 260: score += 3 if CONTEXT_PATTERN.search(body): score += 3 if subject.count("!") <= 2 and uppercase_ratio(subject) < 0.35: score += 2 return min(20, score) def evaluate_cta(draft: dict[str, object]) -> int: cta = str(draft["cta"]).strip() words = count_words(cta) score = 0 if cta: score += 2 if 2 <= words <= 6: score += 5 elif 1 <= words <= 8: score += 2 if CTA_ACTION_PATTERN.search(cta): score += 7 if cta and not GENERIC_CTA_PATTERN.search(cta): score += 4 if cta and cta.count("!") == 0 and uppercase_ratio(cta) < 0.6: score += 2 return min(20, score) def evaluate_personalization(draft: dict[str, object]) -> int: combined = f'{draft["subject"]} {draft["preview_text"]} {draft["body"]}' score = 0 if NAME_TOKEN_PATTERN.search(combined): score += 7 if COMMERCE_TOKEN_PATTERN.search(combined): score += 7 if SECOND_PERSON_PATTERN.search(combined): score += 4 if GREETING_PATTERN.search(str(draft["body"])): score += 2 return min(20, score) def evaluate_timing(draft: dict[str, object]) -> int: stage = str(draft["stage"]) delay = float(draft["delay_hours"]) if stage == "first": if 1 <= delay <= 4: return 20 if 0.5 <= delay <= 12: return 12 elif stage == "second": if 20 <= delay <= 30: return 20 if 12 <= delay <= 48: return 12 else: if 48 <= delay <= 72: return 20 if 36 <= delay <= 96: return 12 return 4 def detected_discount(draft: dict[str, object]) -> float: combined = " ".join(str(draft[field]) for field in ("subject", "preview_text", "body", "cta")) values = [float(match.group(1).replace(",", ".")) for match in DISCOUNT_PATTERN.finditer(combined)] return max(values, default=0.0) def evaluate_discount(draft: dict[str, object]) -> tuple[int, float]: configured = float(draft["configured_discount_percent"]) found = detected_discount(draft) effective = max(configured, found) mismatch = abs(configured - found) > 1 and found > 0 stage = str(draft["stage"]) score = 20 if effective > 0 and stage == "first": score = 13 if effective <= 5 else 6 if effective <= 10 else 0 elif effective > 0 and stage == "second": score = 18 if effective <= 10 else 12 if effective <= 15 else 5 if effective <= 20 else 0 elif effective > 0 and stage == "final": score = 18 if effective <= 15 else 10 if effective <= 20 else 0 if mismatch: score = min(score, 12) return score, found def readiness_label(score: int) -> str: if score >= 85: return "ready_for_final_review" if score >= 65: return "needs_focused_edit" return "revise_before_scheduling" def split_for_product(product_index: int) -> str: if product_index < 6: return "train" if product_index < 8: return "validation" return "test" def balanced_draft( language: str, stage: str, product: dict[str, str], product_index: int, ) -> dict[str, object]: product_name = product[language] discount = 0 if stage == "first" else (5 if stage == "second" else 10 + 5 * (product_index % 2)) if language == "en": subjects = { "first": f"Your saved {product_name} are waiting", "second": f"A reminder about your saved {product_name}", "final": f"Final reminder for your saved {product_name}", } previews = { "first": "Return to your selection whenever you are ready.", "second": "Review your saved item, delivery choices, and final total.", "final": "A final opportunity to review the item saved in your cart.", } offer = ( f" A {discount}% recovery offer is available at checkout under the stated terms." if discount else "" ) body = ( f"Hi {{{{ first_name }}}},\n\nYour {{{{ product_name }}}} from the {product_name} selection is still saved in your cart. " "We kept the item ready so you can review its details, shipping choices, return information, and final total before deciding. " f"Use {{{{ cart_url }}}} to return securely whenever you are ready.{offer} " "Our support team can help if you have a question before completing the order." ) cta = "Return to your cart" if stage != "final" else "Complete your order" else: subjects = { "first": f"Votre {product_name} reste dans le panier", "second": f"Rappel pour votre {product_name} enregistré", "final": f"Dernier rappel pour votre {product_name}", } previews = { "first": "Retrouvez votre sélection lorsque vous serez prêt.", "second": "Vérifiez le produit, la livraison et le montant final.", "final": "Une dernière occasion de revoir l'article conservé dans votre panier.", } offer = ( f" Une offre de relance de {discount}% est disponible au paiement selon les conditions indiquées." if discount else "" ) body = ( f"Bonjour {{{{ first_name }}}},\n\nVotre {{{{ product_name }}}} de la sélection {product_name} est toujours enregistré dans votre panier. " "Nous avons conservé l'article afin que vous puissiez vérifier ses détails, la livraison, les retours et le montant final avant de décider. " f"Utilisez {{{{ cart_url }}}} pour retrouver votre panier en toute sécurité lorsque vous le souhaitez.{offer} " "Notre équipe peut vous aider si vous avez une question avant de finaliser la commande." ) cta = "Retrouver mon panier" if stage != "final" else "Finaliser ma commande" return { "language": language, "stage": stage, "product_category": product["slug"], "subject": subjects[stage], "preview_text": previews[stage], "body": body, "cta": cta, "delay_hours": IDEAL_DELAYS[stage], "configured_discount_percent": discount, } def focused_edit_draft( language: str, stage: str, product: dict[str, str], product_index: int, ) -> dict[str, object]: draft = balanced_draft(language, stage, product, product_index) profile = product_index % 5 product_name = product[language] if profile == 0: draft["cta"] = "" elif profile == 1: draft["delay_hours"] = OUTSIDE_DELAYS[stage] draft["preview_text"] = ( f"The {product_name} reminder is scheduled outside its preferred window." if language == "en" else f"Le rappel pour {product_name} est programmé hors de sa fenêtre conseillée." ) elif profile == 2: draft["delay_hours"] = NEARBY_DELAYS[stage] if language == "en": draft["body"] = ( f"Hello, the {product_name} is still saved in your cart. You can review the item details, delivery choices, returns, and final total before deciding. " "Your selection will remain available while stock lasts, and support can answer questions before you continue with the order." ) else: draft["body"] = ( f"Bonjour, le produit {product_name} est toujours enregistré dans votre panier. Vous pouvez vérifier ses détails, la livraison, les retours et le montant final avant de décider. " "Votre sélection reste disponible dans la limite des stocks et le support peut répondre à vos questions avant de continuer la commande." ) elif profile == 3: draft["subject"] = "REMINDER" if language == "en" else "RAPPEL" localized_stage = stage if language == "en" else { "first": "initial", "second": "intermédiaire", "final": "final", }[stage] draft["preview_text"] = ( f"A very short {localized_stage} reminder for the {product_name}." if language == "en" else f"Un rappel {localized_stage} très court pour {product_name}." ) draft["body"] = ( "Hi {{ first_name }}, your {{ product_name }} is waiting. Use {{ cart_url }} whenever you are ready." if language == "en" else "Bonjour {{ first_name }}, votre {{ product_name }} vous attend. Utilisez {{ cart_url }} quand vous le souhaitez." ) else: discount = 25 if stage != "final" else 30 draft["configured_discount_percent"] = discount draft["delay_hours"] = NEARBY_DELAYS[stage] if language == "en": draft["preview_text"] = f"A {discount}% offer is included in this reminder." draft["body"] += f" The stated recovery discount is {discount}% for this message." else: draft["preview_text"] = f"Une offre de {discount}% est incluse dans ce rappel." draft["body"] += f" La remise de relance indiquée est de {discount}% pour ce message." return draft def high_risk_draft(language: str, stage: str, product: dict[str, str]) -> dict[str, object]: product_name = product[language] if language == "en": stage_name = {"first": "FIRST", "second": "SECOND", "final": "FINAL"}[stage] subject = f"{stage_name} {product_name.upper()} - BUY NOW!!!" preview = "Your only chance disappears immediately!" body = ( f"Your {product_name} might disappear. Act immediately and do not miss this only chance. " "Get 50% off now!!!" ) cta = "CLICK HERE!!!" else: stage_name = {"first": "PREMIER", "second": "DEUXIEME", "final": "DERNIER"}[stage] subject = f"{stage_name} {product_name.upper()} - ACHETEZ MAINTENANT !!!" preview = "Votre seule chance disparaît immédiatement !" body = ( f"Votre {product_name} peut disparaître. Agissez immédiatement et ne manquez pas cette seule chance. " "Obtenez 50% maintenant !!!" ) cta = "CLIQUEZ ICI !!!" return { "language": language, "stage": stage, "product_category": product["slug"], "subject": subject, "preview_text": preview, "body": body, "cta": cta, "delay_hours": OUTSIDE_DELAYS[stage], "configured_discount_percent": 50, } def annotate(draft: dict[str, object]) -> dict[str, object]: discount_score, found_discount = evaluate_discount(draft) scores = { "clarity": evaluate_clarity(draft), "cta": evaluate_cta(draft), "personalization": evaluate_personalization(draft), "timing": evaluate_timing(draft), "discount": discount_score, } total = sum(scores.values()) issue_tags = [check_id for check_id in CHECK_IDS if scores[check_id] < 16] primary_issue = min(CHECK_IDS, key=lambda check_id: scores[check_id]) if issue_tags else "none" return { **draft, "detected_discount_percent": found_discount, "clarity_score": scores["clarity"], "cta_score": scores["cta"], "personalization_score": scores["personalization"], "timing_score": scores["timing"], "discount_score": scores["discount"], "readiness_score": total, "readiness_label": readiness_label(total), "issue_tags": issue_tags, "primary_issue": primary_issue, "synthetic": True, } def normalize_text(value: str) -> str: return " ".join(unicodedata.normalize("NFKC", value).casefold().split()) def build_rows() -> dict[str, list[dict[str, object]]]: rows_by_split: dict[str, list[dict[str, object]]] = defaultdict(list) builders = { "balanced": lambda language, stage, product, index: balanced_draft(language, stage, product, index), "focused_edit": lambda language, stage, product, index: focused_edit_draft(language, stage, product, index), "high_risk": lambda language, stage, product, index: high_risk_draft(language, stage, product), } for product_index, product in enumerate(PRODUCTS): split = split_for_product(product_index) for language in LANGUAGES: for stage in STAGES: for variant in VARIANTS: draft = builders[variant](language, stage, product, product_index) row = { "id": f"sace-{product['slug']}-{language}-{stage}-{variant}", "draft_variant": variant, **annotate(draft), } rows_by_split[split].append(row) for split_index, split in enumerate(("train", "validation", "test")): random.Random(SEED + split_index).shuffle(rows_by_split[split]) return dict(rows_by_split) def validate(rows_by_split: dict[str, list[dict[str, object]]]) -> None: assert {split: len(rows) for split, rows in rows_by_split.items()} == { "train": 108, "validation": 36, "test": 36, } all_rows = [row for split in ("train", "validation", "test") for row in rows_by_split[split]] assert len(all_rows) == 180 assert Counter(row["language"] for row in all_rows) == Counter({"en": 90, "fr": 90}) assert Counter(row["stage"] for row in all_rows) == Counter({stage: 60 for stage in STAGES}) assert Counter(row["draft_variant"] for row in all_rows) == Counter({variant: 60 for variant in VARIANTS}) assert Counter(row["readiness_label"] for row in all_rows) == Counter( { "ready_for_final_review": 60, "needs_focused_edit": 60, "revise_before_scheduling": 60, } ) assert len({row["id"] for row in all_rows}) == len(all_rows) content_keys = ("subject", "preview_text", "body", "cta") fingerprints = {normalize_text(" ".join(str(row[key]) for key in content_keys)) for row in all_rows} assert len(fingerprints) == len(all_rows) product_splits: dict[str, set[str]] = defaultdict(set) email_pattern = re.compile(r"[\w.+-]+@[\w-]+(?:\.[\w-]+)+") phone_pattern = re.compile(r"(?:\+?\d[\s().-]*){7,}") long_number_pattern = re.compile(r"\d{4,}") allowed_tokens = {"first_name", "product_name", "cart_url"} for split, rows in rows_by_split.items(): for row in rows: product_splits[str(row["product_category"])].add(split) combined = " ".join(str(row[key]) for key in content_keys) assert not email_pattern.search(combined) assert not phone_pattern.search(combined) assert not long_number_pattern.search(combined) tokens = {match.strip() for match in re.findall(r"\{\{\s*([^}]+?)\s*\}\}", combined)} assert tokens <= allowed_tokens, tokens assert row["synthetic"] is True assert row["language"] in LANGUAGES assert row["stage"] in STAGES assert row["draft_variant"] in VARIANTS assert 0 <= row["readiness_score"] <= 100 assert row["readiness_score"] == sum(row[f"{check_id}_score"] for check_id in CHECK_IDS) assert row["readiness_label"] == readiness_label(int(row["readiness_score"])) assert row["detected_discount_percent"] == detected_discount(row) expected_issues = [check_id for check_id in CHECK_IDS if row[f"{check_id}_score"] < 16] assert row["issue_tags"] == expected_issues assert (row["primary_issue"] == "none") == (not expected_issues) assert all(len(splits) == 1 for splits in product_splits.values()) def write_rows(rows_by_split: dict[str, list[dict[str, object]]]) -> None: OUTPUT_DIR.mkdir(parents=True, exist_ok=True) for split in ("train", "validation", "test"): path = OUTPUT_DIR / f"{split}.jsonl" with path.open("w", encoding="utf-8", newline="\n") as handle: for row in rows_by_split[split]: handle.write(json.dumps(row, ensure_ascii=False, separators=(",", ":")) + "\n") def main() -> None: rows_by_split = build_rows() validate(rows_by_split) write_rows(rows_by_split) all_rows = [row for rows in rows_by_split.values() for row in rows] print("Generated and validated 180 synthetic abandoned-cart email drafts.") print("Splits:", {split: len(rows) for split, rows in rows_by_split.items()}) print("Languages:", dict(sorted(Counter(row["language"] for row in all_rows).items()))) print("Stages:", dict(sorted(Counter(row["stage"] for row in all_rows).items()))) print("Readiness labels:", dict(sorted(Counter(row["readiness_label"] for row in all_rows).items()))) if __name__ == "__main__": main()