Spaces:
Running
Running
Gleb Tsyganov commited on
Commit ·
f27702b
1
Parent(s): 3e39245
simulate email campaign
Browse files- .env.example +19 -0
- .gitignore +5 -0
- __pycache__/client.cpython-313.pyc +0 -0
- __pycache__/models.cpython-313.pyc +0 -0
- client.py +33 -7
- config/brand_instructions.txt +7 -0
- config/brand_persona.json +102 -0
- demo_email_intro.py +36 -0
- models.py +42 -8
- pyproject.toml +2 -0
- server/__pycache__/clothing_brand_ctr_env_environment.cpython-313.pyc +0 -0
- server/clothing_brand_ctr_env_environment.py +304 -24
- simulate_5_email_campaign.py +569 -0
- simulate_brand_campaign.py +1057 -0
- simulate_email_variants.py +222 -0
.env.example
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Hugging Face access token with Inference API permission.
|
| 2 |
+
HF_TOKEN=hf_your_token_here
|
| 3 |
+
|
| 4 |
+
# DeepSeek model on Hugging Face Inference API.
|
| 5 |
+
HF_MODEL_ID=deepseek-ai/DeepSeek-V3
|
| 6 |
+
|
| 7 |
+
# Set to false to force deterministic template fallback.
|
| 8 |
+
USE_HF_LLM=true
|
| 9 |
+
|
| 10 |
+
# Optional: where persona/instructions are loaded from.
|
| 11 |
+
BRAND_PERSONA_FILE=config/brand_persona.json
|
| 12 |
+
BRAND_INSTRUCTIONS_FILE=config/brand_instructions.txt
|
| 13 |
+
|
| 14 |
+
# Optional direct override for instructions (takes precedence over file).
|
| 15 |
+
# BRAND_COPY_INSTRUCTIONS=Keep copy brand-consistent, short, and quirky.
|
| 16 |
+
|
| 17 |
+
# Optional: default HF persona dataset for campaign simulation.
|
| 18 |
+
HF_PERSONA_DATASET=nvidia/Nemotron-Personas-USA
|
| 19 |
+
HF_PERSONA_SPLIT=train
|
.gitignore
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
.env
|
| 2 |
+
__pycache__/
|
| 3 |
+
*.py[cod]
|
| 4 |
+
*.egg-info/
|
| 5 |
+
outputs/
|
__pycache__/client.cpython-313.pyc
CHANGED
|
Binary files a/__pycache__/client.cpython-313.pyc and b/__pycache__/client.cpython-313.pyc differ
|
|
|
__pycache__/models.cpython-313.pyc
CHANGED
|
Binary files a/__pycache__/models.cpython-313.pyc and b/__pycache__/models.cpython-313.pyc differ
|
|
|
client.py
CHANGED
|
@@ -29,17 +29,33 @@ class ClothingBrandCtrEnv(
|
|
| 29 |
>>> # Connect to a running server
|
| 30 |
>>> with ClothingBrandCtrEnv(base_url="http://localhost:8000") as client:
|
| 31 |
... result = client.reset()
|
| 32 |
-
... print(result.observation.
|
| 33 |
...
|
| 34 |
-
... result = client.step(
|
| 35 |
-
...
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 36 |
|
| 37 |
Example with Docker:
|
| 38 |
>>> # Automatically start container and connect
|
| 39 |
>>> client = ClothingBrandCtrEnv.from_docker_image("clothing_brand_ctr_env-env:latest")
|
| 40 |
>>> try:
|
| 41 |
... result = client.reset()
|
| 42 |
-
... result = client.step(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 43 |
... finally:
|
| 44 |
... client.close()
|
| 45 |
"""
|
|
@@ -55,7 +71,12 @@ class ClothingBrandCtrEnv(
|
|
| 55 |
Dictionary representation suitable for JSON encoding
|
| 56 |
"""
|
| 57 |
return {
|
| 58 |
-
"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 59 |
}
|
| 60 |
|
| 61 |
def _parse_result(self, payload: Dict) -> StepResult[ClothingBrandCtrObservation]:
|
|
@@ -70,8 +91,13 @@ class ClothingBrandCtrEnv(
|
|
| 70 |
"""
|
| 71 |
obs_data = payload.get("observation", {})
|
| 72 |
observation = ClothingBrandCtrObservation(
|
| 73 |
-
|
| 74 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 75 |
done=payload.get("done", False),
|
| 76 |
reward=payload.get("reward"),
|
| 77 |
metadata=obs_data.get("metadata", {}),
|
|
|
|
| 29 |
>>> # Connect to a running server
|
| 30 |
>>> with ClothingBrandCtrEnv(base_url="http://localhost:8000") as client:
|
| 31 |
... result = client.reset()
|
| 32 |
+
... print(result.observation.preview_text)
|
| 33 |
...
|
| 34 |
+
... result = client.step(
|
| 35 |
+
... ClothingBrandCtrAction(
|
| 36 |
+
... brand_name="AIRPORT CLUB",
|
| 37 |
+
... target_audience="style-focused people that travel",
|
| 38 |
+
... brand_voice="bold, easy-going, fun, wholesome",
|
| 39 |
+
... key_value_prop="premium t-shirts when traveling by plane",
|
| 40 |
+
... call_to_action="Shop the launch collection now",
|
| 41 |
+
... )
|
| 42 |
+
... )
|
| 43 |
+
... print(result.observation.validation_passed)
|
| 44 |
|
| 45 |
Example with Docker:
|
| 46 |
>>> # Automatically start container and connect
|
| 47 |
>>> client = ClothingBrandCtrEnv.from_docker_image("clothing_brand_ctr_env-env:latest")
|
| 48 |
>>> try:
|
| 49 |
... result = client.reset()
|
| 50 |
+
... result = client.step(
|
| 51 |
+
... ClothingBrandCtrAction(
|
| 52 |
+
... brand_name="ARPRT CLUB",
|
| 53 |
+
... target_audience="traveler",
|
| 54 |
+
... brand_voice="bold",
|
| 55 |
+
... key_value_prop="premium essentials with runway-level polish",
|
| 56 |
+
... call_to_action="Shop the launch collection now",
|
| 57 |
+
... )
|
| 58 |
+
... )
|
| 59 |
... finally:
|
| 60 |
... client.close()
|
| 61 |
"""
|
|
|
|
| 71 |
Dictionary representation suitable for JSON encoding
|
| 72 |
"""
|
| 73 |
return {
|
| 74 |
+
"brand_name": action.brand_name,
|
| 75 |
+
"target_audience": action.target_audience,
|
| 76 |
+
"brand_voice": action.brand_voice,
|
| 77 |
+
"key_value_prop": action.key_value_prop,
|
| 78 |
+
"call_to_action": action.call_to_action,
|
| 79 |
+
"metadata": action.metadata,
|
| 80 |
}
|
| 81 |
|
| 82 |
def _parse_result(self, payload: Dict) -> StepResult[ClothingBrandCtrObservation]:
|
|
|
|
| 91 |
"""
|
| 92 |
obs_data = payload.get("observation", {})
|
| 93 |
observation = ClothingBrandCtrObservation(
|
| 94 |
+
subject_line=obs_data.get("subject_line", ""),
|
| 95 |
+
preview_text=obs_data.get("preview_text", ""),
|
| 96 |
+
email_copy=obs_data.get("email_copy", ""),
|
| 97 |
+
word_count=obs_data.get("word_count", 0),
|
| 98 |
+
validation=obs_data.get("validation", {}),
|
| 99 |
+
validation_passed=obs_data.get("validation_passed", False),
|
| 100 |
+
ctr_proxy_score=obs_data.get("ctr_proxy_score", 0.0),
|
| 101 |
done=payload.get("done", False),
|
| 102 |
reward=payload.get("reward"),
|
| 103 |
metadata=obs_data.get("metadata", {}),
|
config/brand_instructions.txt
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Keep copy consistent with the brand persona and travel-forward positioning.
|
| 2 |
+
Use concise, punchy phrasing and make positioning lines short and quirky.
|
| 3 |
+
Sound culturally aware, stylish, and witty without being overly formal.
|
| 4 |
+
Avoid generic language and avoid buzzword-heavy copy.
|
| 5 |
+
Be inspired by brands like The Row, Jacquemus, Rhode.
|
| 6 |
+
Sell the dream of being able to travel and life your best life.
|
| 7 |
+
|
config/brand_persona.json
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"travel": {
|
| 3 |
+
"future_plans": ["Israel", "South Africa", "Portugal"],
|
| 4 |
+
"visited_places": ["France", "Italy", "Japan", "Mexico", "Greece"]
|
| 5 |
+
},
|
| 6 |
+
"hobbies": [
|
| 7 |
+
"yoga",
|
| 8 |
+
"pilates",
|
| 9 |
+
"hiking",
|
| 10 |
+
"tennis",
|
| 11 |
+
"volleyball",
|
| 12 |
+
"reading contemporary fiction",
|
| 13 |
+
"exploring art galleries"
|
| 14 |
+
],
|
| 15 |
+
"parents": {
|
| 16 |
+
"names": ["Rae Klein", "Joshua Klein"],
|
| 17 |
+
"description": "Parents are happily together, living in New York, and very supportive of Izzy's career.",
|
| 18 |
+
"relationship_status": "together"
|
| 19 |
+
},
|
| 20 |
+
"siblings": {
|
| 21 |
+
"names": ["Rachel Klein", "Daniel Klein"],
|
| 22 |
+
"total_count": 2
|
| 23 |
+
},
|
| 24 |
+
"favorites": {
|
| 25 |
+
"restaurants": ["Jack's Wife Freda", "Via Carota", "Lilia"],
|
| 26 |
+
"coffee_shops": ["Bluestone Lane", "Stumptown Coffee", "Devocion"],
|
| 27 |
+
"clothing_brands": ["Reformation", "Aritzia", "Vintage Levi's", "The Row"]
|
| 28 |
+
},
|
| 29 |
+
"full_name": "Izzy Klein",
|
| 30 |
+
"past_jobs": ["Reporter for The Badger Herald (University Newspaper)"],
|
| 31 |
+
"birth_city": "New York City",
|
| 32 |
+
"university": "University of Wisconsin - Madison",
|
| 33 |
+
"current_city": "New York City",
|
| 34 |
+
"current_jobs": ["Fashion Writer at Vogue"],
|
| 35 |
+
"birth_country": "USA",
|
| 36 |
+
"daily_routine": {
|
| 37 |
+
"sleep_time": "23:30",
|
| 38 |
+
"wake_up_time": "07:00"
|
| 39 |
+
},
|
| 40 |
+
"date_of_birth": "2001-06-14",
|
| 41 |
+
"relationships": {
|
| 42 |
+
"status": "single",
|
| 43 |
+
"past_partners": [
|
| 44 |
+
"Ethan (college boyfriend)",
|
| 45 |
+
"Sam (high school relationship)"
|
| 46 |
+
]
|
| 47 |
+
},
|
| 48 |
+
"social_circle": {
|
| 49 |
+
"other_friends": [
|
| 50 |
+
"A tight-knit friend group in NYC that she goes to dinners and yoga classes with"
|
| 51 |
+
],
|
| 52 |
+
"best_friends_names": ["Maya Cohen", "Leila Torres", "Hannah Kim"]
|
| 53 |
+
},
|
| 54 |
+
"writing_style": "personal, approachable, witty but thoughtful, with cultural and emotional depth",
|
| 55 |
+
"social_profiles": {
|
| 56 |
+
"other": "",
|
| 57 |
+
"twitter": "",
|
| 58 |
+
"linkedin": "",
|
| 59 |
+
"instagram": ""
|
| 60 |
+
},
|
| 61 |
+
"childhood_sports": ["soccer"],
|
| 62 |
+
"dreams_and_goals": [
|
| 63 |
+
"Make Airport Club a mainstream clothing brand",
|
| 64 |
+
"Travel more and write about culture and fashion globally",
|
| 65 |
+
"Build a strong voice as a cultural critic"
|
| 66 |
+
],
|
| 67 |
+
"media_preferences": {
|
| 68 |
+
"books": [
|
| 69 |
+
"The Bell Jar by Sylvia Plath",
|
| 70 |
+
"Normal People by Sally Rooney",
|
| 71 |
+
"On Beauty by Zadie Smith"
|
| 72 |
+
],
|
| 73 |
+
"movies": ["Call Me by Your Name", "Before Sunrise", "Lady Bird"],
|
| 74 |
+
"sources": {
|
| 75 |
+
"goodreads": "",
|
| 76 |
+
"letterboxd": ""
|
| 77 |
+
},
|
| 78 |
+
"tv_shows": ["Girls", "Normal People", "Succession"]
|
| 79 |
+
},
|
| 80 |
+
"music_preferences": {
|
| 81 |
+
"favorite_genres": ["indie rock", "classic rock", "house music", "edm"],
|
| 82 |
+
"recently_played": [
|
| 83 |
+
"Kyoto - Phoebe Bridgers",
|
| 84 |
+
"Last Nite - The Strokes",
|
| 85 |
+
"Lights Burn Dimmer - Fred Again"
|
| 86 |
+
],
|
| 87 |
+
"favorite_artists": [
|
| 88 |
+
"Phoebe Bridgers",
|
| 89 |
+
"The Strokes",
|
| 90 |
+
"Joni Mitchell",
|
| 91 |
+
"Fred Again"
|
| 92 |
+
]
|
| 93 |
+
},
|
| 94 |
+
"personality_traits": [
|
| 95 |
+
"curious",
|
| 96 |
+
"empathetic",
|
| 97 |
+
"good sense of humor",
|
| 98 |
+
"personal",
|
| 99 |
+
"creative",
|
| 100 |
+
"socially observant"
|
| 101 |
+
]
|
| 102 |
+
}
|
demo_email_intro.py
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Small local smoke demo for intro-email copy generation + validation."""
|
| 2 |
+
|
| 3 |
+
from clothing_brand_ctr_env import ClothingBrandCtrAction
|
| 4 |
+
from clothing_brand_ctr_env.server.clothing_brand_ctr_env_environment import (
|
| 5 |
+
ClothingBrandCtrEnvironment,
|
| 6 |
+
)
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def main() -> None:
|
| 10 |
+
env = ClothingBrandCtrEnvironment()
|
| 11 |
+
env.reset()
|
| 12 |
+
|
| 13 |
+
action = ClothingBrandCtrAction(
|
| 14 |
+
brand_name="AIRPORT CLUB",
|
| 15 |
+
target_audience="for working millenials and Gen Z that travel",
|
| 16 |
+
brand_voice="bold, easy-going, wholesome",
|
| 17 |
+
key_value_prop="quiet luxury items to where to the airport",
|
| 18 |
+
call_to_action="Shop the launch collection now",
|
| 19 |
+
)
|
| 20 |
+
|
| 21 |
+
observation = env.step(action)
|
| 22 |
+
|
| 23 |
+
print("Subject:", observation.subject_line)
|
| 24 |
+
print("Preview:", observation.preview_text)
|
| 25 |
+
print("CTR Proxy Score:", observation.ctr_proxy_score)
|
| 26 |
+
print("Validation Passed:", observation.validation_passed)
|
| 27 |
+
print("Validation:", observation.validation)
|
| 28 |
+
print("\nEmail Copy:\n")
|
| 29 |
+
print(observation.email_copy)
|
| 30 |
+
|
| 31 |
+
# Minimal pass/fail check for this demo run.
|
| 32 |
+
assert observation.validation_passed, "Validation failed for generated email copy."
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
if __name__ == "__main__":
|
| 36 |
+
main()
|
models.py
CHANGED
|
@@ -7,22 +7,56 @@
|
|
| 7 |
"""
|
| 8 |
Data models for the Clothing Brand Ctr Env Environment.
|
| 9 |
|
| 10 |
-
The clothing_brand_ctr_env environment
|
| 11 |
"""
|
| 12 |
|
|
|
|
|
|
|
| 13 |
from pydantic import Field
|
| 14 |
|
| 15 |
from openenv.core.env_server.types import Action, Observation
|
| 16 |
|
| 17 |
|
| 18 |
class ClothingBrandCtrAction(Action):
|
| 19 |
-
"""Action
|
| 20 |
-
|
| 21 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
|
| 23 |
|
| 24 |
class ClothingBrandCtrObservation(Observation):
|
| 25 |
-
"""Observation
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
"""
|
| 8 |
Data models for the Clothing Brand Ctr Env Environment.
|
| 9 |
|
| 10 |
+
The clothing_brand_ctr_env environment generates and validates marketing copy.
|
| 11 |
"""
|
| 12 |
|
| 13 |
+
from typing import Dict, Literal
|
| 14 |
+
|
| 15 |
from pydantic import Field
|
| 16 |
|
| 17 |
from openenv.core.env_server.types import Action, Observation
|
| 18 |
|
| 19 |
|
| 20 |
class ClothingBrandCtrAction(Action):
|
| 21 |
+
"""Action that asks the environment to generate launch email copy."""
|
| 22 |
+
|
| 23 |
+
brand_name: str = Field(..., description="Brand name to feature in the email")
|
| 24 |
+
target_audience: str = Field(
|
| 25 |
+
...,
|
| 26 |
+
description="Who this campaign is aimed at",
|
| 27 |
+
)
|
| 28 |
+
brand_voice: Literal["minimal", "bold", "playful", "luxury"] = Field(
|
| 29 |
+
default="bold",
|
| 30 |
+
description="Tone style for generated copy",
|
| 31 |
+
)
|
| 32 |
+
key_value_prop: str = Field(
|
| 33 |
+
...,
|
| 34 |
+
description="Main value proposition to communicate",
|
| 35 |
+
)
|
| 36 |
+
call_to_action: str = Field(
|
| 37 |
+
...,
|
| 38 |
+
description="Primary CTA text to include in the email body",
|
| 39 |
+
)
|
| 40 |
|
| 41 |
|
| 42 |
class ClothingBrandCtrObservation(Observation):
|
| 43 |
+
"""Observation with generated email copy and validation results."""
|
| 44 |
+
|
| 45 |
+
subject_line: str = Field(default="", description="Generated subject line")
|
| 46 |
+
preview_text: str = Field(default="", description="Generated preview/snippet text")
|
| 47 |
+
email_copy: str = Field(default="", description="Generated full email body copy")
|
| 48 |
+
word_count: int = Field(default=0, description="Word count for generated body")
|
| 49 |
+
validation: Dict[str, bool] = Field(
|
| 50 |
+
default_factory=dict,
|
| 51 |
+
description="Rule-by-rule validation outcomes",
|
| 52 |
+
)
|
| 53 |
+
validation_passed: bool = Field(
|
| 54 |
+
default=False,
|
| 55 |
+
description="True when all validation checks pass",
|
| 56 |
+
)
|
| 57 |
+
ctr_proxy_score: float = Field(
|
| 58 |
+
default=0.0,
|
| 59 |
+
ge=0.0,
|
| 60 |
+
le=1.0,
|
| 61 |
+
description="Simple proxy score (0-1) for likely CTR quality",
|
| 62 |
+
)
|
pyproject.toml
CHANGED
|
@@ -26,6 +26,8 @@ dependencies = [
|
|
| 26 |
"matplotlib>=3.8.0",
|
| 27 |
"seaborn>=0.13.0",
|
| 28 |
"python-dotenv>=1.0.0",
|
|
|
|
|
|
|
| 29 |
]
|
| 30 |
|
| 31 |
[project.optional-dependencies]
|
|
|
|
| 26 |
"matplotlib>=3.8.0",
|
| 27 |
"seaborn>=0.13.0",
|
| 28 |
"python-dotenv>=1.0.0",
|
| 29 |
+
"huggingface-hub>=1.0.0",
|
| 30 |
+
"datasets>=4.6.0",
|
| 31 |
]
|
| 32 |
|
| 33 |
[project.optional-dependencies]
|
server/__pycache__/clothing_brand_ctr_env_environment.cpython-313.pyc
CHANGED
|
Binary files a/server/__pycache__/clothing_brand_ctr_env_environment.cpython-313.pyc and b/server/__pycache__/clothing_brand_ctr_env_environment.cpython-313.pyc differ
|
|
|
server/clothing_brand_ctr_env_environment.py
CHANGED
|
@@ -7,10 +7,13 @@
|
|
| 7 |
"""
|
| 8 |
Clothing Brand Ctr Env Environment Implementation.
|
| 9 |
|
| 10 |
-
|
| 11 |
-
Perfect for testing HTTP server infrastructure.
|
| 12 |
"""
|
| 13 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
from uuid import uuid4
|
| 15 |
|
| 16 |
from openenv.core.env_server.interfaces import Environment
|
|
@@ -21,22 +24,40 @@ try:
|
|
| 21 |
except ImportError: # pragma: no cover - supports direct server.app imports
|
| 22 |
from models import ClothingBrandCtrAction, ClothingBrandCtrObservation
|
| 23 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
|
| 25 |
class ClothingBrandCtrEnvironment(Environment):
|
| 26 |
"""
|
| 27 |
-
|
| 28 |
|
| 29 |
-
|
| 30 |
-
|
| 31 |
|
| 32 |
Example:
|
| 33 |
>>> env = ClothingBrandCtrEnvironment()
|
| 34 |
>>> obs = env.reset()
|
| 35 |
-
>>> print(obs.
|
| 36 |
>>>
|
| 37 |
-
>>> obs = env.step(
|
| 38 |
-
|
| 39 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 40 |
"""
|
| 41 |
|
| 42 |
# Enable concurrent WebSocket sessions.
|
|
@@ -47,52 +68,311 @@ class ClothingBrandCtrEnvironment(Environment):
|
|
| 47 |
|
| 48 |
def __init__(self):
|
| 49 |
"""Initialize the clothing_brand_ctr_env environment."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 50 |
self._state = State(episode_id=str(uuid4()), step_count=0)
|
| 51 |
self._reset_count = 0
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 52 |
|
| 53 |
def reset(self) -> ClothingBrandCtrObservation:
|
| 54 |
"""
|
| 55 |
Reset the environment.
|
| 56 |
|
| 57 |
Returns:
|
| 58 |
-
ClothingBrandCtrObservation with
|
| 59 |
"""
|
| 60 |
self._state = State(episode_id=str(uuid4()), step_count=0)
|
| 61 |
self._reset_count += 1
|
| 62 |
|
| 63 |
return ClothingBrandCtrObservation(
|
| 64 |
-
|
| 65 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 66 |
done=False,
|
| 67 |
reward=0.0,
|
| 68 |
)
|
| 69 |
|
| 70 |
def step(self, action: ClothingBrandCtrAction) -> ClothingBrandCtrObservation: # type: ignore[override]
|
| 71 |
"""
|
| 72 |
-
|
| 73 |
|
| 74 |
Args:
|
| 75 |
-
action:
|
| 76 |
|
| 77 |
Returns:
|
| 78 |
-
ClothingBrandCtrObservation with
|
| 79 |
"""
|
| 80 |
self._state.step_count += 1
|
| 81 |
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 87 |
|
| 88 |
return ClothingBrandCtrObservation(
|
| 89 |
-
|
| 90 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 91 |
done=False,
|
| 92 |
-
reward=
|
| 93 |
-
metadata={
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 94 |
)
|
| 95 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 96 |
@property
|
| 97 |
def state(self) -> State:
|
| 98 |
"""
|
|
|
|
| 7 |
"""
|
| 8 |
Clothing Brand Ctr Env Environment Implementation.
|
| 9 |
|
| 10 |
+
Simple environment that generates launch email copy and validates quality checks.
|
|
|
|
| 11 |
"""
|
| 12 |
|
| 13 |
+
import json
|
| 14 |
+
import os
|
| 15 |
+
from pathlib import Path
|
| 16 |
+
from typing import Dict, Optional
|
| 17 |
from uuid import uuid4
|
| 18 |
|
| 19 |
from openenv.core.env_server.interfaces import Environment
|
|
|
|
| 24 |
except ImportError: # pragma: no cover - supports direct server.app imports
|
| 25 |
from models import ClothingBrandCtrAction, ClothingBrandCtrObservation
|
| 26 |
|
| 27 |
+
try:
|
| 28 |
+
from huggingface_hub import InferenceClient
|
| 29 |
+
except ImportError: # pragma: no cover
|
| 30 |
+
InferenceClient = None
|
| 31 |
+
|
| 32 |
+
try:
|
| 33 |
+
from dotenv import load_dotenv
|
| 34 |
+
except ImportError: # pragma: no cover
|
| 35 |
+
load_dotenv = None
|
| 36 |
+
|
| 37 |
|
| 38 |
class ClothingBrandCtrEnvironment(Environment):
|
| 39 |
"""
|
| 40 |
+
Generate introductory email campaign copy for a clothing brand.
|
| 41 |
|
| 42 |
+
The environment returns copy + validation checks so an agent can optimize
|
| 43 |
+
prompts/actions for better CTR proxy quality over multiple steps.
|
| 44 |
|
| 45 |
Example:
|
| 46 |
>>> env = ClothingBrandCtrEnvironment()
|
| 47 |
>>> obs = env.reset()
|
| 48 |
+
>>> print(obs.preview_text) # "Environment ready for email-copy simulation."
|
| 49 |
>>>
|
| 50 |
+
>>> obs = env.step(
|
| 51 |
+
... ClothingBrandCtrAction(
|
| 52 |
+
... brand_name="ARPRT CLUB",
|
| 53 |
+
... target_audience="urban professionals",
|
| 54 |
+
... brand_voice="bold",
|
| 55 |
+
... key_value_prop="clothing brand for people that travel",
|
| 56 |
+
... call_to_action="Shop the first drop",
|
| 57 |
+
... )
|
| 58 |
+
... )
|
| 59 |
+
>>> print(obs.subject_line)
|
| 60 |
+
>>> print(obs.validation_passed)
|
| 61 |
"""
|
| 62 |
|
| 63 |
# Enable concurrent WebSocket sessions.
|
|
|
|
| 68 |
|
| 69 |
def __init__(self):
|
| 70 |
"""Initialize the clothing_brand_ctr_env environment."""
|
| 71 |
+
if load_dotenv is not None:
|
| 72 |
+
load_dotenv()
|
| 73 |
+
|
| 74 |
+
self._project_root = Path(__file__).resolve().parents[1]
|
| 75 |
+
self._brand_persona_json = self._load_brand_persona_json(
|
| 76 |
+
os.getenv("BRAND_PERSONA_FILE", "config/brand_persona.json")
|
| 77 |
+
)
|
| 78 |
+
self._brand_copy_instructions = (
|
| 79 |
+
os.getenv("BRAND_COPY_INSTRUCTIONS", "").strip()
|
| 80 |
+
or self._load_brand_copy_instructions(
|
| 81 |
+
os.getenv("BRAND_INSTRUCTIONS_FILE", "config/brand_instructions.txt")
|
| 82 |
+
)
|
| 83 |
+
or (
|
| 84 |
+
"Keep copy consistent with the brand persona. "
|
| 85 |
+
"Keep positioning short, playful, and quirky."
|
| 86 |
+
)
|
| 87 |
+
)
|
| 88 |
+
|
| 89 |
self._state = State(episode_id=str(uuid4()), step_count=0)
|
| 90 |
self._reset_count = 0
|
| 91 |
+
self._hf_model_id = os.getenv("HF_MODEL_ID", "deepseek-ai/DeepSeek-V3")
|
| 92 |
+
self._use_hf_llm = os.getenv("USE_HF_LLM", "true").lower() in {
|
| 93 |
+
"1",
|
| 94 |
+
"true",
|
| 95 |
+
"yes",
|
| 96 |
+
"on",
|
| 97 |
+
}
|
| 98 |
+
self._hf_token = os.getenv("HF_TOKEN") or os.getenv("HUGGINGFACEHUB_API_TOKEN")
|
| 99 |
+
self._hf_client = None
|
| 100 |
+
if self._use_hf_llm and self._hf_token and InferenceClient is not None:
|
| 101 |
+
self._hf_client = InferenceClient(api_key=self._hf_token)
|
| 102 |
|
| 103 |
def reset(self) -> ClothingBrandCtrObservation:
|
| 104 |
"""
|
| 105 |
Reset the environment.
|
| 106 |
|
| 107 |
Returns:
|
| 108 |
+
ClothingBrandCtrObservation with initial empty copy state
|
| 109 |
"""
|
| 110 |
self._state = State(episode_id=str(uuid4()), step_count=0)
|
| 111 |
self._reset_count += 1
|
| 112 |
|
| 113 |
return ClothingBrandCtrObservation(
|
| 114 |
+
subject_line="",
|
| 115 |
+
preview_text="Environment ready for email-copy simulation.",
|
| 116 |
+
email_copy="",
|
| 117 |
+
word_count=0,
|
| 118 |
+
validation={},
|
| 119 |
+
validation_passed=False,
|
| 120 |
+
ctr_proxy_score=0.0,
|
| 121 |
done=False,
|
| 122 |
reward=0.0,
|
| 123 |
)
|
| 124 |
|
| 125 |
def step(self, action: ClothingBrandCtrAction) -> ClothingBrandCtrObservation: # type: ignore[override]
|
| 126 |
"""
|
| 127 |
+
Generate intro email copy and run quality validation.
|
| 128 |
|
| 129 |
Args:
|
| 130 |
+
action: Email generation request
|
| 131 |
|
| 132 |
Returns:
|
| 133 |
+
ClothingBrandCtrObservation with generated copy and validation
|
| 134 |
"""
|
| 135 |
self._state.step_count += 1
|
| 136 |
|
| 137 |
+
subject_line, preview_text, email_copy, generation_source = self._generate_email_copy(
|
| 138 |
+
action
|
| 139 |
+
)
|
| 140 |
+
word_count = len(email_copy.split())
|
| 141 |
+
validation = self._validate_email_copy(
|
| 142 |
+
action=action,
|
| 143 |
+
subject_line=subject_line,
|
| 144 |
+
preview_text=preview_text,
|
| 145 |
+
email_copy=email_copy,
|
| 146 |
+
word_count=word_count,
|
| 147 |
+
)
|
| 148 |
+
ctr_proxy_score = self._compute_ctr_proxy_score(validation)
|
| 149 |
+
validation_passed = all(validation.values())
|
| 150 |
|
| 151 |
return ClothingBrandCtrObservation(
|
| 152 |
+
subject_line=subject_line,
|
| 153 |
+
preview_text=preview_text,
|
| 154 |
+
email_copy=email_copy,
|
| 155 |
+
word_count=word_count,
|
| 156 |
+
validation=validation,
|
| 157 |
+
validation_passed=validation_passed,
|
| 158 |
+
ctr_proxy_score=ctr_proxy_score,
|
| 159 |
done=False,
|
| 160 |
+
reward=ctr_proxy_score,
|
| 161 |
+
metadata={
|
| 162 |
+
"step": self._state.step_count,
|
| 163 |
+
"brand_name": action.brand_name,
|
| 164 |
+
"brand_voice": action.brand_voice,
|
| 165 |
+
"generation_source": generation_source,
|
| 166 |
+
"hf_model_id": self._hf_model_id if generation_source == "hf_llm" else "",
|
| 167 |
+
},
|
| 168 |
+
)
|
| 169 |
+
|
| 170 |
+
def _generate_email_copy(
|
| 171 |
+
self,
|
| 172 |
+
action: ClothingBrandCtrAction,
|
| 173 |
+
) -> tuple[str, str, str, str]:
|
| 174 |
+
"""Generate copy via HF LLM when available, else fallback to template."""
|
| 175 |
+
llm_output = self._generate_email_copy_with_hf(action)
|
| 176 |
+
if llm_output is not None:
|
| 177 |
+
return llm_output[0], llm_output[1], llm_output[2], "hf_llm"
|
| 178 |
+
|
| 179 |
+
subject_line, preview_text, email_copy = self._generate_email_copy_template(action)
|
| 180 |
+
return subject_line, preview_text, email_copy, "template_fallback"
|
| 181 |
+
|
| 182 |
+
def _generate_email_copy_template(
|
| 183 |
+
self,
|
| 184 |
+
action: ClothingBrandCtrAction,
|
| 185 |
+
) -> tuple[str, str, str]:
|
| 186 |
+
"""Create deterministic fallback copy from the action fields."""
|
| 187 |
+
voice_openers = {
|
| 188 |
+
"minimal": "clean wardrobe staples designed for bringing to the airport",
|
| 189 |
+
"bold": "premium t-shirts for standing out when you travel",
|
| 190 |
+
"playful": "the only t-shirt you need for a 14 hour flight",
|
| 191 |
+
"luxury": "soft luxury items for traveling",
|
| 192 |
+
}
|
| 193 |
+
opener = voice_openers[action.brand_voice]
|
| 194 |
+
|
| 195 |
+
subject_line = f"Meet {action.brand_name}: Your New T-Shirt For Travel"
|
| 196 |
+
preview_text = (
|
| 197 |
+
f"{action.key_value_prop}. Built for {action.target_audience}. "
|
| 198 |
+
f"{action.call_to_action}."
|
| 199 |
+
)
|
| 200 |
+
|
| 201 |
+
email_copy = (
|
| 202 |
+
f"Hi {action.target_audience},\n\n"
|
| 203 |
+
f"We're excited to introduce {action.brand_name}.\n"
|
| 204 |
+
f"{opener}\n\n"
|
| 205 |
+
f"At {action.brand_name}, our focus is simple: {action.key_value_prop}.\n"
|
| 206 |
+
f"Every piece is designed so you can look put together without overthinking it.\n\n"
|
| 207 |
+
f"Ready to see the collection? {action.call_to_action}.\n\n"
|
| 208 |
+
f"See you at the lounge,\n"
|
| 209 |
+
f"Team {action.brand_name}"
|
| 210 |
)
|
| 211 |
|
| 212 |
+
return subject_line, preview_text, email_copy
|
| 213 |
+
|
| 214 |
+
def _generate_email_copy_with_hf(
|
| 215 |
+
self,
|
| 216 |
+
action: ClothingBrandCtrAction,
|
| 217 |
+
) -> Optional[tuple[str, str, str]]:
|
| 218 |
+
"""Generate copy via Hugging Face Inference API using a DeepSeek model."""
|
| 219 |
+
if not self._use_hf_llm or self._hf_client is None:
|
| 220 |
+
return None
|
| 221 |
+
|
| 222 |
+
system_prompt = (
|
| 223 |
+
"You are an expert lifecycle email marketer for fashion brands. "
|
| 224 |
+
"Return only strict JSON with keys: subject_line, preview_text, email_copy."
|
| 225 |
+
)
|
| 226 |
+
user_prompt = (
|
| 227 |
+
"Create intro campaign email copy using these inputs.\n"
|
| 228 |
+
f"brand_name: {action.brand_name}\n"
|
| 229 |
+
f"target_audience: {action.target_audience}\n"
|
| 230 |
+
f"brand_voice: {action.brand_voice}\n"
|
| 231 |
+
f"key_value_prop: {action.key_value_prop}\n"
|
| 232 |
+
f"call_to_action: {action.call_to_action}\n\n"
|
| 233 |
+
f"brand_persona_json: {self._brand_persona_json}\n"
|
| 234 |
+
f"additional_brand_instructions: {self._brand_copy_instructions}\n\n"
|
| 235 |
+
"Rules:\n"
|
| 236 |
+
"1) Subject line 24-70 chars and include brand_name.\n"
|
| 237 |
+
"2) Preview text 45-140 chars.\n"
|
| 238 |
+
"3) Email body 60-170 words.\n"
|
| 239 |
+
"4) Body must include brand_name, key_value_prop, and call_to_action.\n"
|
| 240 |
+
"5) Keep travel context and no markdown.\n"
|
| 241 |
+
"6) Ensure voice and references are consistent with brand_persona_json.\n"
|
| 242 |
+
"7) Positioning language must be short and quirky."
|
| 243 |
+
)
|
| 244 |
+
|
| 245 |
+
try:
|
| 246 |
+
response = self._hf_client.chat.completions.create(
|
| 247 |
+
model=self._hf_model_id,
|
| 248 |
+
messages=[
|
| 249 |
+
{"role": "system", "content": system_prompt},
|
| 250 |
+
{"role": "user", "content": user_prompt},
|
| 251 |
+
],
|
| 252 |
+
temperature=0.8,
|
| 253 |
+
max_tokens=500,
|
| 254 |
+
)
|
| 255 |
+
content = self._extract_hf_content(response)
|
| 256 |
+
if not content:
|
| 257 |
+
return None
|
| 258 |
+
parsed = self._parse_llm_json(content)
|
| 259 |
+
if parsed is None:
|
| 260 |
+
return None
|
| 261 |
+
subject_line = str(parsed.get("subject_line", "")).strip()
|
| 262 |
+
preview_text = str(parsed.get("preview_text", "")).strip()
|
| 263 |
+
email_copy = str(parsed.get("email_copy", "")).strip()
|
| 264 |
+
|
| 265 |
+
if not subject_line or not preview_text or not email_copy:
|
| 266 |
+
return None
|
| 267 |
+
return subject_line, preview_text, email_copy
|
| 268 |
+
except Exception:
|
| 269 |
+
return None
|
| 270 |
+
|
| 271 |
+
def _extract_hf_content(self, response: object) -> str:
|
| 272 |
+
"""Extract text content from HF chat completion response."""
|
| 273 |
+
choices = getattr(response, "choices", None)
|
| 274 |
+
if not choices:
|
| 275 |
+
return ""
|
| 276 |
+
first_choice = choices[0]
|
| 277 |
+
message = getattr(first_choice, "message", None)
|
| 278 |
+
if message is None and isinstance(first_choice, dict):
|
| 279 |
+
message = first_choice.get("message")
|
| 280 |
+
|
| 281 |
+
content = ""
|
| 282 |
+
if message is not None:
|
| 283 |
+
content = getattr(message, "content", "")
|
| 284 |
+
if not content and isinstance(message, dict):
|
| 285 |
+
content = message.get("content", "")
|
| 286 |
+
|
| 287 |
+
if isinstance(content, list):
|
| 288 |
+
text_parts = []
|
| 289 |
+
for item in content:
|
| 290 |
+
if isinstance(item, dict):
|
| 291 |
+
text_parts.append(str(item.get("text", "")))
|
| 292 |
+
else:
|
| 293 |
+
text_parts.append(str(item))
|
| 294 |
+
return "".join(text_parts).strip()
|
| 295 |
+
|
| 296 |
+
return str(content).strip()
|
| 297 |
+
|
| 298 |
+
def _parse_llm_json(self, content: str) -> Optional[Dict[str, object]]:
|
| 299 |
+
"""Parse JSON response, tolerating fenced blocks."""
|
| 300 |
+
cleaned = content.strip()
|
| 301 |
+
if cleaned.startswith("```"):
|
| 302 |
+
cleaned = cleaned.strip("`")
|
| 303 |
+
cleaned = cleaned.replace("json\n", "", 1).strip()
|
| 304 |
+
|
| 305 |
+
start = cleaned.find("{")
|
| 306 |
+
end = cleaned.rfind("}")
|
| 307 |
+
if start == -1 or end == -1 or end <= start:
|
| 308 |
+
return None
|
| 309 |
+
candidate = cleaned[start : end + 1]
|
| 310 |
+
try:
|
| 311 |
+
parsed = json.loads(candidate)
|
| 312 |
+
except json.JSONDecodeError:
|
| 313 |
+
return None
|
| 314 |
+
if not isinstance(parsed, dict):
|
| 315 |
+
return None
|
| 316 |
+
return parsed
|
| 317 |
+
|
| 318 |
+
def _load_brand_persona_json(self, persona_path: str) -> str:
|
| 319 |
+
"""Load persona JSON from file and normalize to a compact JSON string."""
|
| 320 |
+
path = Path(persona_path)
|
| 321 |
+
if not path.is_absolute():
|
| 322 |
+
path = self._project_root / path
|
| 323 |
+
try:
|
| 324 |
+
parsed = json.loads(path.read_text(encoding="utf-8"))
|
| 325 |
+
except (FileNotFoundError, json.JSONDecodeError, OSError):
|
| 326 |
+
return "{}"
|
| 327 |
+
return json.dumps(parsed, separators=(",", ":"))
|
| 328 |
+
|
| 329 |
+
def _load_brand_copy_instructions(self, instructions_path: str) -> str:
|
| 330 |
+
"""Load additional brand instruction text from file."""
|
| 331 |
+
path = Path(instructions_path)
|
| 332 |
+
if not path.is_absolute():
|
| 333 |
+
path = self._project_root / path
|
| 334 |
+
try:
|
| 335 |
+
return path.read_text(encoding="utf-8").strip()
|
| 336 |
+
except OSError:
|
| 337 |
+
return ""
|
| 338 |
+
|
| 339 |
+
def _validate_email_copy(
|
| 340 |
+
self,
|
| 341 |
+
action: ClothingBrandCtrAction,
|
| 342 |
+
subject_line: str,
|
| 343 |
+
preview_text: str,
|
| 344 |
+
email_copy: str,
|
| 345 |
+
word_count: int,
|
| 346 |
+
) -> Dict[str, bool]:
|
| 347 |
+
"""Validate copy quality checks for basic launch-email best practices."""
|
| 348 |
+
brand_lc = action.brand_name.lower()
|
| 349 |
+
cta_lc = action.call_to_action.lower()
|
| 350 |
+
value_prop_lc = action.key_value_prop.lower()
|
| 351 |
+
|
| 352 |
+
return {
|
| 353 |
+
"subject_has_brand": brand_lc in subject_line.lower(),
|
| 354 |
+
"subject_length_ok": 24 <= len(subject_line) <= 70,
|
| 355 |
+
"preview_length_ok": 45 <= len(preview_text) <= 140,
|
| 356 |
+
"body_has_brand": brand_lc in email_copy.lower(),
|
| 357 |
+
"body_mentions_value_prop": value_prop_lc in email_copy.lower(),
|
| 358 |
+
"body_has_cta": cta_lc in email_copy.lower(),
|
| 359 |
+
"body_word_count_ok": 60 <= word_count <= 180,
|
| 360 |
+
}
|
| 361 |
+
|
| 362 |
+
def _compute_ctr_proxy_score(self, validation: Dict[str, bool]) -> float:
|
| 363 |
+
"""Aggregate validation outcomes into a 0-1 proxy CTR score."""
|
| 364 |
+
weights = {
|
| 365 |
+
"subject_has_brand": 0.16,
|
| 366 |
+
"subject_length_ok": 0.17,
|
| 367 |
+
"preview_length_ok": 0.14,
|
| 368 |
+
"body_has_brand": 0.12,
|
| 369 |
+
"body_mentions_value_prop": 0.14,
|
| 370 |
+
"body_has_cta": 0.17,
|
| 371 |
+
"body_word_count_ok": 0.10,
|
| 372 |
+
}
|
| 373 |
+
score = sum(weights[key] for key, passed in validation.items() if passed)
|
| 374 |
+
return round(score, 4)
|
| 375 |
+
|
| 376 |
@property
|
| 377 |
def state(self) -> State:
|
| 378 |
"""
|
simulate_5_email_campaign.py
ADDED
|
@@ -0,0 +1,569 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Simulate a 5-email campaign and optimize send times for opens/CTR/purchases."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import argparse
|
| 6 |
+
import hashlib
|
| 7 |
+
import itertools
|
| 8 |
+
from dataclasses import dataclass
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
from typing import Dict, List, Sequence, Tuple
|
| 11 |
+
|
| 12 |
+
from clothing_brand_ctr_env import ClothingBrandCtrAction
|
| 13 |
+
from clothing_brand_ctr_env.server.clothing_brand_ctr_env_environment import (
|
| 14 |
+
ClothingBrandCtrEnvironment,
|
| 15 |
+
)
|
| 16 |
+
from simulate_brand_campaign import (
|
| 17 |
+
MLEngineerJudge,
|
| 18 |
+
TenXMarketerJudge,
|
| 19 |
+
AudiencePersona,
|
| 20 |
+
clamp,
|
| 21 |
+
load_or_create_persona_dataset,
|
| 22 |
+
parse_send_hours,
|
| 23 |
+
save_arm_metrics,
|
| 24 |
+
send_time_alignment,
|
| 25 |
+
)
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
@dataclass(frozen=True)
|
| 29 |
+
class EmailStepConfig:
|
| 30 |
+
"""Definition of each campaign email."""
|
| 31 |
+
|
| 32 |
+
step_idx: int
|
| 33 |
+
step_name: str
|
| 34 |
+
brand_voice: str
|
| 35 |
+
key_value_prop: str
|
| 36 |
+
call_to_action: str
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
@dataclass
|
| 40 |
+
class EmailStepGenerated:
|
| 41 |
+
"""Generated copy + quality info for a campaign step."""
|
| 42 |
+
|
| 43 |
+
step_idx: int
|
| 44 |
+
step_name: str
|
| 45 |
+
brand_voice: str
|
| 46 |
+
key_value_prop: str
|
| 47 |
+
call_to_action: str
|
| 48 |
+
subject_line: str
|
| 49 |
+
preview_text: str
|
| 50 |
+
email_copy: str
|
| 51 |
+
ctr_proxy_score: float
|
| 52 |
+
marketer_score: float
|
| 53 |
+
marketer_rationale: str
|
| 54 |
+
generation_source: str
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def default_email_steps() -> List[EmailStepConfig]:
|
| 58 |
+
"""Default 5-email sequence for brand launch lifecycle."""
|
| 59 |
+
return [
|
| 60 |
+
EmailStepConfig(
|
| 61 |
+
step_idx=1,
|
| 62 |
+
step_name="teaser",
|
| 63 |
+
brand_voice="playful",
|
| 64 |
+
key_value_prop="travel tees that stay crisp from gate to dinner",
|
| 65 |
+
call_to_action="Get on the early-access list",
|
| 66 |
+
),
|
| 67 |
+
EmailStepConfig(
|
| 68 |
+
step_idx=2,
|
| 69 |
+
step_name="launch",
|
| 70 |
+
brand_voice="bold",
|
| 71 |
+
key_value_prop="premium airport-ready staples built for repeat wear",
|
| 72 |
+
call_to_action="Shop the launch drop",
|
| 73 |
+
),
|
| 74 |
+
EmailStepConfig(
|
| 75 |
+
step_idx=3,
|
| 76 |
+
step_name="proof",
|
| 77 |
+
brand_voice="minimal",
|
| 78 |
+
key_value_prop="easy travel fits that real flyers keep reaching for",
|
| 79 |
+
call_to_action="See bestsellers",
|
| 80 |
+
),
|
| 81 |
+
EmailStepConfig(
|
| 82 |
+
step_idx=4,
|
| 83 |
+
step_name="offer",
|
| 84 |
+
brand_voice="luxury",
|
| 85 |
+
key_value_prop="elevated basics with lounge-level comfort",
|
| 86 |
+
call_to_action="Unlock your limited offer",
|
| 87 |
+
),
|
| 88 |
+
EmailStepConfig(
|
| 89 |
+
step_idx=5,
|
| 90 |
+
step_name="last_call",
|
| 91 |
+
brand_voice="bold",
|
| 92 |
+
key_value_prop="the last restock for your carry-on uniform",
|
| 93 |
+
call_to_action="Claim your size now",
|
| 94 |
+
),
|
| 95 |
+
]
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def generate_email_steps(
|
| 99 |
+
brand_name: str,
|
| 100 |
+
target_audience: str,
|
| 101 |
+
steps: List[EmailStepConfig],
|
| 102 |
+
) -> List[EmailStepGenerated]:
|
| 103 |
+
"""Generate campaign email copy for each step."""
|
| 104 |
+
env = ClothingBrandCtrEnvironment()
|
| 105 |
+
env.reset()
|
| 106 |
+
marketer = TenXMarketerJudge()
|
| 107 |
+
generated: List[EmailStepGenerated] = []
|
| 108 |
+
|
| 109 |
+
for step in steps:
|
| 110 |
+
action = ClothingBrandCtrAction(
|
| 111 |
+
brand_name=brand_name,
|
| 112 |
+
target_audience=target_audience,
|
| 113 |
+
brand_voice=step.brand_voice,
|
| 114 |
+
key_value_prop=step.key_value_prop,
|
| 115 |
+
call_to_action=step.call_to_action,
|
| 116 |
+
metadata={"campaign_step": step.step_name},
|
| 117 |
+
)
|
| 118 |
+
observation = env.step(action)
|
| 119 |
+
|
| 120 |
+
step_generated = EmailStepGenerated(
|
| 121 |
+
step_idx=step.step_idx,
|
| 122 |
+
step_name=step.step_name,
|
| 123 |
+
brand_voice=step.brand_voice,
|
| 124 |
+
key_value_prop=step.key_value_prop,
|
| 125 |
+
call_to_action=step.call_to_action,
|
| 126 |
+
subject_line=observation.subject_line,
|
| 127 |
+
preview_text=observation.preview_text,
|
| 128 |
+
email_copy=observation.email_copy,
|
| 129 |
+
ctr_proxy_score=observation.ctr_proxy_score,
|
| 130 |
+
marketer_score=0.0,
|
| 131 |
+
marketer_rationale="",
|
| 132 |
+
generation_source=observation.metadata.get("generation_source", "unknown"),
|
| 133 |
+
)
|
| 134 |
+
score, rationale = marketer.score(
|
| 135 |
+
arm=type(
|
| 136 |
+
"TempArm",
|
| 137 |
+
(),
|
| 138 |
+
{
|
| 139 |
+
"validation": observation.validation,
|
| 140 |
+
"ctr_proxy_score": observation.ctr_proxy_score,
|
| 141 |
+
"email_copy": observation.email_copy,
|
| 142 |
+
"preview_text": observation.preview_text,
|
| 143 |
+
"subject_line": observation.subject_line,
|
| 144 |
+
"key_value_prop": step.key_value_prop,
|
| 145 |
+
},
|
| 146 |
+
)(),
|
| 147 |
+
brand_name=brand_name,
|
| 148 |
+
)
|
| 149 |
+
step_generated.marketer_score = score
|
| 150 |
+
step_generated.marketer_rationale = rationale
|
| 151 |
+
generated.append(step_generated)
|
| 152 |
+
return generated
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
def _schedule_seed(schedule: Sequence[int], seed: int) -> int:
|
| 156 |
+
"""Create deterministic seed from schedule."""
|
| 157 |
+
digest = hashlib.sha256((",".join(map(str, schedule)) + f"|{seed}").encode("utf-8")).hexdigest()
|
| 158 |
+
return int(digest[:12], 16)
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def open_prob_for_step(
|
| 162 |
+
step: EmailStepGenerated,
|
| 163 |
+
send_hour: int,
|
| 164 |
+
persona: AudiencePersona,
|
| 165 |
+
engagement: float,
|
| 166 |
+
streak_unopened: int,
|
| 167 |
+
) -> float:
|
| 168 |
+
"""Probability of open for one persona on one campaign step."""
|
| 169 |
+
alignment = send_time_alignment(send_hour, persona.preferred_send_hour)
|
| 170 |
+
style_match = 1.0 if step.brand_voice == persona.style_preference else 0.0
|
| 171 |
+
travel_signal = 1.0 if "travel" in (step.preview_text + step.email_copy).lower() else 0.0
|
| 172 |
+
fatigue = max(0.0, streak_unopened * 0.015)
|
| 173 |
+
|
| 174 |
+
prob = persona.open_base
|
| 175 |
+
prob += 0.13 * ((step.marketer_score / 100.0) - 0.5)
|
| 176 |
+
prob += 0.10 * (step.ctr_proxy_score - 0.5)
|
| 177 |
+
prob += 0.09 * alignment
|
| 178 |
+
prob += 0.05 * style_match
|
| 179 |
+
prob += 0.07 * engagement
|
| 180 |
+
prob += 0.03 * travel_signal * min(persona.travel_intensity / 10.0, 1.0)
|
| 181 |
+
prob -= fatigue
|
| 182 |
+
return clamp(prob, 0.01, 0.95)
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
def click_prob_for_step(
|
| 186 |
+
step: EmailStepGenerated,
|
| 187 |
+
persona: AudiencePersona,
|
| 188 |
+
opened: bool,
|
| 189 |
+
engagement: float,
|
| 190 |
+
) -> float:
|
| 191 |
+
"""Probability of click after open."""
|
| 192 |
+
if not opened:
|
| 193 |
+
return 0.0
|
| 194 |
+
style_match = 1.0 if step.brand_voice == persona.style_preference else 0.0
|
| 195 |
+
|
| 196 |
+
prob = persona.click_base
|
| 197 |
+
prob += 0.13 * ((step.marketer_score / 100.0) - 0.5)
|
| 198 |
+
prob += 0.12 * (step.ctr_proxy_score - 0.5)
|
| 199 |
+
prob += 0.05 * style_match
|
| 200 |
+
prob += 0.04 * engagement
|
| 201 |
+
return clamp(prob, 0.005, 0.85)
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
def purchase_prob_for_step(
|
| 205 |
+
step_idx: int,
|
| 206 |
+
step: EmailStepGenerated,
|
| 207 |
+
persona: AudiencePersona,
|
| 208 |
+
clicked: bool,
|
| 209 |
+
engagement: float,
|
| 210 |
+
) -> float:
|
| 211 |
+
"""Probability of purchase after click."""
|
| 212 |
+
if not clicked:
|
| 213 |
+
return 0.0
|
| 214 |
+
style_match = 1.0 if step.brand_voice == persona.style_preference else 0.0
|
| 215 |
+
stage_lift = [0.75, 0.9, 1.0, 1.15, 1.3][min(max(step_idx - 1, 0), 4)]
|
| 216 |
+
income_lift = {"premium": 0.05, "mid": 0.02}.get(persona.income_band, 0.0)
|
| 217 |
+
|
| 218 |
+
prob = persona.purchase_base * stage_lift
|
| 219 |
+
prob += 0.08 * ((step.marketer_score / 100.0) - 0.5)
|
| 220 |
+
prob += 0.05 * style_match
|
| 221 |
+
prob += 0.03 * engagement
|
| 222 |
+
prob += income_lift
|
| 223 |
+
return clamp(prob, 0.002, 0.60)
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
def simulate_schedule(
|
| 227 |
+
schedule: Sequence[int],
|
| 228 |
+
generated_steps: List[EmailStepGenerated],
|
| 229 |
+
personas: List[AudiencePersona],
|
| 230 |
+
seed: int,
|
| 231 |
+
) -> Tuple[Dict[str, object], List[Dict[str, object]]]:
|
| 232 |
+
"""Simulate entire 5-email sequence for one send-time schedule."""
|
| 233 |
+
if len(schedule) != len(generated_steps):
|
| 234 |
+
raise ValueError("Schedule length must match number of campaign emails.")
|
| 235 |
+
|
| 236 |
+
rng = __import__("random").Random(_schedule_seed(schedule, seed))
|
| 237 |
+
states: Dict[str, Dict[str, float | int | bool]] = {
|
| 238 |
+
p.persona_id: {"engagement": 0.0, "streak_unopened": 0, "purchased": False}
|
| 239 |
+
for p in personas
|
| 240 |
+
}
|
| 241 |
+
|
| 242 |
+
total_sent = total_opens = total_clicks = total_purchases = 0
|
| 243 |
+
step_metrics: List[Dict[str, object]] = []
|
| 244 |
+
|
| 245 |
+
for idx, step in enumerate(generated_steps):
|
| 246 |
+
hour = schedule[idx]
|
| 247 |
+
sent = opens = clicks = purchases = 0
|
| 248 |
+
|
| 249 |
+
for persona in personas:
|
| 250 |
+
state = states[persona.persona_id]
|
| 251 |
+
if bool(state["purchased"]):
|
| 252 |
+
continue
|
| 253 |
+
|
| 254 |
+
sent += 1
|
| 255 |
+
open_prob = open_prob_for_step(
|
| 256 |
+
step=step,
|
| 257 |
+
send_hour=hour,
|
| 258 |
+
persona=persona,
|
| 259 |
+
engagement=float(state["engagement"]),
|
| 260 |
+
streak_unopened=int(state["streak_unopened"]),
|
| 261 |
+
)
|
| 262 |
+
opened = rng.random() < open_prob
|
| 263 |
+
|
| 264 |
+
click_prob = click_prob_for_step(
|
| 265 |
+
step=step,
|
| 266 |
+
persona=persona,
|
| 267 |
+
opened=opened,
|
| 268 |
+
engagement=float(state["engagement"]),
|
| 269 |
+
)
|
| 270 |
+
clicked = opened and (rng.random() < click_prob)
|
| 271 |
+
|
| 272 |
+
purchase_prob = purchase_prob_for_step(
|
| 273 |
+
step_idx=idx + 1,
|
| 274 |
+
step=step,
|
| 275 |
+
persona=persona,
|
| 276 |
+
clicked=clicked,
|
| 277 |
+
engagement=float(state["engagement"]),
|
| 278 |
+
)
|
| 279 |
+
purchased = clicked and (rng.random() < purchase_prob)
|
| 280 |
+
|
| 281 |
+
if opened:
|
| 282 |
+
opens += 1
|
| 283 |
+
state["streak_unopened"] = 0
|
| 284 |
+
state["engagement"] = clamp(float(state["engagement"]) + 0.08, -0.2, 0.6)
|
| 285 |
+
else:
|
| 286 |
+
state["streak_unopened"] = int(state["streak_unopened"]) + 1
|
| 287 |
+
state["engagement"] = clamp(float(state["engagement"]) - 0.03, -0.2, 0.6)
|
| 288 |
+
|
| 289 |
+
if clicked:
|
| 290 |
+
clicks += 1
|
| 291 |
+
state["engagement"] = clamp(float(state["engagement"]) + 0.07, -0.2, 0.7)
|
| 292 |
+
|
| 293 |
+
if purchased:
|
| 294 |
+
purchases += 1
|
| 295 |
+
state["purchased"] = True
|
| 296 |
+
|
| 297 |
+
total_sent += sent
|
| 298 |
+
total_opens += opens
|
| 299 |
+
total_clicks += clicks
|
| 300 |
+
total_purchases += purchases
|
| 301 |
+
|
| 302 |
+
step_metrics.append(
|
| 303 |
+
{
|
| 304 |
+
"step_idx": step.step_idx,
|
| 305 |
+
"step_name": step.step_name,
|
| 306 |
+
"send_hour": hour,
|
| 307 |
+
"sent": sent,
|
| 308 |
+
"opens": opens,
|
| 309 |
+
"clicks": clicks,
|
| 310 |
+
"purchases": purchases,
|
| 311 |
+
"open_rate": round(opens / sent, 4) if sent else 0.0,
|
| 312 |
+
"ctr": round(clicks / sent, 4) if sent else 0.0,
|
| 313 |
+
"purchase_rate": round(purchases / sent, 4) if sent else 0.0,
|
| 314 |
+
"subject_line": step.subject_line,
|
| 315 |
+
"generation_source": step.generation_source,
|
| 316 |
+
}
|
| 317 |
+
)
|
| 318 |
+
|
| 319 |
+
audience_size = len(personas)
|
| 320 |
+
open_rate = (total_opens / total_sent) if total_sent else 0.0
|
| 321 |
+
ctr = (total_clicks / total_sent) if total_sent else 0.0
|
| 322 |
+
purchase_rate = (total_purchases / audience_size) if audience_size else 0.0
|
| 323 |
+
click_to_open = (total_clicks / total_opens) if total_opens else 0.0
|
| 324 |
+
|
| 325 |
+
campaign_score = (0.15 * open_rate) + (0.25 * ctr) + (0.60 * purchase_rate)
|
| 326 |
+
summary = {
|
| 327 |
+
"arm_id": "schedule_" + "_".join(f"{h:02d}" for h in schedule),
|
| 328 |
+
"schedule": "-".join(f"{h:02d}:00" for h in schedule),
|
| 329 |
+
"sent": total_sent,
|
| 330 |
+
"opens": total_opens,
|
| 331 |
+
"clicks": total_clicks,
|
| 332 |
+
"purchases": total_purchases,
|
| 333 |
+
"open_rate": round(open_rate, 4),
|
| 334 |
+
"ctr": round(ctr, 4),
|
| 335 |
+
"click_to_open_rate": round(click_to_open, 4),
|
| 336 |
+
"purchase_rate": round(purchase_rate, 4),
|
| 337 |
+
"composite_score": round(campaign_score, 4),
|
| 338 |
+
"generation_source": generated_steps[0].generation_source if generated_steps else "unknown",
|
| 339 |
+
"marketer_score": round(
|
| 340 |
+
sum(step.marketer_score for step in generated_steps) / max(1, len(generated_steps)),
|
| 341 |
+
2,
|
| 342 |
+
),
|
| 343 |
+
}
|
| 344 |
+
for i, hour in enumerate(schedule, start=1):
|
| 345 |
+
summary[f"email_{i}_hour"] = hour
|
| 346 |
+
return summary, step_metrics
|
| 347 |
+
|
| 348 |
+
|
| 349 |
+
def candidate_schedules(
|
| 350 |
+
send_hours: List[int],
|
| 351 |
+
num_emails: int,
|
| 352 |
+
max_exhaustive: int,
|
| 353 |
+
sampled_count: int,
|
| 354 |
+
seed: int,
|
| 355 |
+
) -> Tuple[List[Tuple[int, ...]], str, int]:
|
| 356 |
+
"""Build schedule candidates via exhaustive or sampled search."""
|
| 357 |
+
total = len(send_hours) ** num_emails
|
| 358 |
+
if total <= max_exhaustive:
|
| 359 |
+
return list(itertools.product(send_hours, repeat=num_emails)), "exhaustive", total
|
| 360 |
+
|
| 361 |
+
rng = __import__("random").Random(seed)
|
| 362 |
+
needed = min(total, sampled_count)
|
| 363 |
+
schedules = set()
|
| 364 |
+
while len(schedules) < needed:
|
| 365 |
+
schedules.add(tuple(rng.choice(send_hours) for _ in range(num_emails)))
|
| 366 |
+
return list(schedules), "sampled", total
|
| 367 |
+
|
| 368 |
+
|
| 369 |
+
def save_step_metrics(step_metrics: List[Dict[str, object]], output_path: Path) -> None:
|
| 370 |
+
"""Persist per-email metrics for best schedule."""
|
| 371 |
+
output_path.parent.mkdir(parents=True, exist_ok=True)
|
| 372 |
+
with output_path.open("w", newline="", encoding="utf-8") as handle:
|
| 373 |
+
fields = [
|
| 374 |
+
"step_idx",
|
| 375 |
+
"step_name",
|
| 376 |
+
"send_hour",
|
| 377 |
+
"sent",
|
| 378 |
+
"opens",
|
| 379 |
+
"clicks",
|
| 380 |
+
"purchases",
|
| 381 |
+
"open_rate",
|
| 382 |
+
"ctr",
|
| 383 |
+
"purchase_rate",
|
| 384 |
+
"generation_source",
|
| 385 |
+
"subject_line",
|
| 386 |
+
]
|
| 387 |
+
writer = __import__("csv").DictWriter(handle, fieldnames=fields)
|
| 388 |
+
writer.writeheader()
|
| 389 |
+
for row in step_metrics:
|
| 390 |
+
writer.writerow(row)
|
| 391 |
+
|
| 392 |
+
|
| 393 |
+
def print_schedule_results(
|
| 394 |
+
ranked: List[Dict[str, object]],
|
| 395 |
+
top_steps: List[Dict[str, object]],
|
| 396 |
+
search_mode: str,
|
| 397 |
+
searched_count: int,
|
| 398 |
+
total_count: int,
|
| 399 |
+
ml_score: float,
|
| 400 |
+
ml_rationale: str,
|
| 401 |
+
) -> None:
|
| 402 |
+
"""Print summary leaderboard and winning schedule details."""
|
| 403 |
+
print("\n5-Email Schedule Leaderboard")
|
| 404 |
+
print("-" * 140)
|
| 405 |
+
print(
|
| 406 |
+
f"{'Rank':<5} {'Schedule':<38} {'Score':<7} {'Open':<7} {'CTR':<7} "
|
| 407 |
+
f"{'Purchase':<9} {'Opens':<7} {'Clicks':<7} {'Buys':<7}"
|
| 408 |
+
)
|
| 409 |
+
print("-" * 140)
|
| 410 |
+
for rank, row in enumerate(ranked[:10], start=1):
|
| 411 |
+
print(
|
| 412 |
+
f"{rank:<5} {str(row['schedule']):<38} {float(row['composite_score']):<7.3f} "
|
| 413 |
+
f"{float(row['open_rate']):<7.3f} {float(row['ctr']):<7.3f} "
|
| 414 |
+
f"{float(row['purchase_rate']):<9.3f} {int(row['opens']):<7} {int(row['clicks']):<7} {int(row['purchases']):<7}"
|
| 415 |
+
)
|
| 416 |
+
|
| 417 |
+
best = ranked[0]
|
| 418 |
+
print("\nBest 5-Email Schedule")
|
| 419 |
+
print("-" * 140)
|
| 420 |
+
print(f"Schedule: {best['schedule']}")
|
| 421 |
+
print(f"Composite score: {best['composite_score']}")
|
| 422 |
+
print(f"Open rate: {best['open_rate']}")
|
| 423 |
+
print(f"CTR: {best['ctr']}")
|
| 424 |
+
print(f"Purchase rate (per audience): {best['purchase_rate']}")
|
| 425 |
+
|
| 426 |
+
print("\nBest Schedule Step Breakdown")
|
| 427 |
+
print("-" * 140)
|
| 428 |
+
for row in top_steps:
|
| 429 |
+
print(
|
| 430 |
+
f"Email {row['step_idx']} ({row['step_name']}), {int(row['send_hour']):02d}:00 -> "
|
| 431 |
+
f"open {float(row['open_rate']):.3f}, ctr {float(row['ctr']):.3f}, purchase {float(row['purchase_rate']):.3f}"
|
| 432 |
+
)
|
| 433 |
+
|
| 434 |
+
print("\nJudge: ML Engineer (A/B Testing)")
|
| 435 |
+
print("-" * 140)
|
| 436 |
+
print(f"Experiment score: {ml_score}/100")
|
| 437 |
+
print(ml_rationale)
|
| 438 |
+
|
| 439 |
+
print("\nSearch Details")
|
| 440 |
+
print("-" * 140)
|
| 441 |
+
print(f"Mode: {search_mode}")
|
| 442 |
+
print(f"Schedules evaluated: {searched_count}")
|
| 443 |
+
print(f"Total possible schedules: {total_count}")
|
| 444 |
+
|
| 445 |
+
|
| 446 |
+
def main() -> None:
|
| 447 |
+
parser = argparse.ArgumentParser(
|
| 448 |
+
description="Simulate 5-email campaign and optimize send times.",
|
| 449 |
+
)
|
| 450 |
+
parser.add_argument("--brand-name", default="AIRPORT CLUB")
|
| 451 |
+
parser.add_argument("--target-audience", default="fellow traveler")
|
| 452 |
+
parser.add_argument(
|
| 453 |
+
"--send-hours",
|
| 454 |
+
default="8,10,12,15,18,21",
|
| 455 |
+
help="Candidate send hours to optimize across.",
|
| 456 |
+
)
|
| 457 |
+
parser.add_argument("--num-emails", type=int, default=5)
|
| 458 |
+
parser.add_argument(
|
| 459 |
+
"--persona-dataset",
|
| 460 |
+
default="outputs/evals/persona_dataset.csv",
|
| 461 |
+
)
|
| 462 |
+
parser.add_argument("--persona-count", type=int, default=1200)
|
| 463 |
+
parser.add_argument("--seed", type=int, default=42)
|
| 464 |
+
parser.add_argument("--persona-source", choices=["hf", "synthetic"], default="hf")
|
| 465 |
+
parser.add_argument(
|
| 466 |
+
"--hf-dataset-name",
|
| 467 |
+
default="nvidia/Nemotron-Personas-USA",
|
| 468 |
+
)
|
| 469 |
+
parser.add_argument("--hf-split", default="train")
|
| 470 |
+
parser.add_argument("--refresh-personas", action="store_true")
|
| 471 |
+
parser.add_argument("--allow-synthetic-fallback", action="store_true")
|
| 472 |
+
parser.add_argument("--max-exhaustive", type=int, default=5000)
|
| 473 |
+
parser.add_argument("--schedule-samples", type=int, default=2500)
|
| 474 |
+
parser.add_argument(
|
| 475 |
+
"--schedule-results-csv",
|
| 476 |
+
default="outputs/evals/five_email_schedule_results.csv",
|
| 477 |
+
)
|
| 478 |
+
parser.add_argument(
|
| 479 |
+
"--best-step-results-csv",
|
| 480 |
+
default="outputs/evals/five_email_best_schedule_steps.csv",
|
| 481 |
+
)
|
| 482 |
+
args = parser.parse_args()
|
| 483 |
+
|
| 484 |
+
if args.num_emails != 5:
|
| 485 |
+
raise ValueError("This simulator is configured specifically for 5-email campaigns.")
|
| 486 |
+
|
| 487 |
+
send_hours = parse_send_hours(args.send_hours)
|
| 488 |
+
personas = load_or_create_persona_dataset(
|
| 489 |
+
dataset_path=Path(args.persona_dataset),
|
| 490 |
+
size=args.persona_count,
|
| 491 |
+
seed=args.seed,
|
| 492 |
+
source=args.persona_source,
|
| 493 |
+
hf_dataset_name=args.hf_dataset_name,
|
| 494 |
+
hf_split=args.hf_split,
|
| 495 |
+
refresh=args.refresh_personas,
|
| 496 |
+
allow_synthetic_fallback=args.allow_synthetic_fallback,
|
| 497 |
+
)
|
| 498 |
+
|
| 499 |
+
steps = generate_email_steps(
|
| 500 |
+
brand_name=args.brand_name,
|
| 501 |
+
target_audience=args.target_audience,
|
| 502 |
+
steps=default_email_steps(),
|
| 503 |
+
)
|
| 504 |
+
schedules, search_mode, total_count = candidate_schedules(
|
| 505 |
+
send_hours=send_hours,
|
| 506 |
+
num_emails=args.num_emails,
|
| 507 |
+
max_exhaustive=args.max_exhaustive,
|
| 508 |
+
sampled_count=args.schedule_samples,
|
| 509 |
+
seed=args.seed,
|
| 510 |
+
)
|
| 511 |
+
|
| 512 |
+
summaries: List[Dict[str, object]] = []
|
| 513 |
+
best_step_metrics: List[Dict[str, object]] = []
|
| 514 |
+
for sched_idx, schedule in enumerate(schedules):
|
| 515 |
+
summary, step_metrics = simulate_schedule(
|
| 516 |
+
schedule=schedule,
|
| 517 |
+
generated_steps=steps,
|
| 518 |
+
personas=personas,
|
| 519 |
+
seed=args.seed + (sched_idx * 3571),
|
| 520 |
+
)
|
| 521 |
+
summaries.append(summary)
|
| 522 |
+
if not best_step_metrics:
|
| 523 |
+
best_step_metrics = step_metrics
|
| 524 |
+
|
| 525 |
+
ranked = sorted(
|
| 526 |
+
summaries,
|
| 527 |
+
key=lambda row: (
|
| 528 |
+
float(row["composite_score"]),
|
| 529 |
+
float(row["purchase_rate"]),
|
| 530 |
+
float(row["ctr"]),
|
| 531 |
+
float(row["open_rate"]),
|
| 532 |
+
),
|
| 533 |
+
reverse=True,
|
| 534 |
+
)
|
| 535 |
+
|
| 536 |
+
best_schedule = tuple(int(ranked[0][f"email_{i}_hour"]) for i in range(1, args.num_emails + 1))
|
| 537 |
+
_, best_step_metrics = simulate_schedule(
|
| 538 |
+
schedule=best_schedule,
|
| 539 |
+
generated_steps=steps,
|
| 540 |
+
personas=personas,
|
| 541 |
+
seed=args.seed + 999983,
|
| 542 |
+
)
|
| 543 |
+
|
| 544 |
+
ml_judge = MLEngineerJudge()
|
| 545 |
+
ml_score, ml_rationale = ml_judge.score_experiment(
|
| 546 |
+
ranked_results=ranked,
|
| 547 |
+
audience_size=len(personas),
|
| 548 |
+
)
|
| 549 |
+
|
| 550 |
+
save_arm_metrics(ranked, Path(args.schedule_results_csv))
|
| 551 |
+
save_step_metrics(best_step_metrics, Path(args.best_step_results_csv))
|
| 552 |
+
|
| 553 |
+
print_schedule_results(
|
| 554 |
+
ranked=ranked,
|
| 555 |
+
top_steps=best_step_metrics,
|
| 556 |
+
search_mode=search_mode,
|
| 557 |
+
searched_count=len(schedules),
|
| 558 |
+
total_count=total_count,
|
| 559 |
+
ml_score=ml_score,
|
| 560 |
+
ml_rationale=ml_rationale,
|
| 561 |
+
)
|
| 562 |
+
print(f"\nPersona source: {personas[0].persona_source if personas else 'unknown'}")
|
| 563 |
+
print(f"Persona dataset: {args.persona_dataset}")
|
| 564 |
+
print(f"Schedule results: {args.schedule_results_csv}")
|
| 565 |
+
print(f"Best schedule step results: {args.best_step_results_csv}")
|
| 566 |
+
|
| 567 |
+
|
| 568 |
+
if __name__ == "__main__":
|
| 569 |
+
main()
|
simulate_brand_campaign.py
ADDED
|
@@ -0,0 +1,1057 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Simulate brand email campaign performance with judge personas + A/B testing."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import argparse
|
| 6 |
+
import csv
|
| 7 |
+
import hashlib
|
| 8 |
+
import math
|
| 9 |
+
import os
|
| 10 |
+
import random
|
| 11 |
+
from dataclasses import dataclass
|
| 12 |
+
from pathlib import Path
|
| 13 |
+
from typing import Dict, List, Tuple
|
| 14 |
+
|
| 15 |
+
from clothing_brand_ctr_env import ClothingBrandCtrAction
|
| 16 |
+
from clothing_brand_ctr_env.server.clothing_brand_ctr_env_environment import (
|
| 17 |
+
ClothingBrandCtrEnvironment,
|
| 18 |
+
)
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
@dataclass(frozen=True)
|
| 22 |
+
class EmailVariant:
|
| 23 |
+
"""Single copy variant configuration."""
|
| 24 |
+
|
| 25 |
+
name: str
|
| 26 |
+
brand_voice: str
|
| 27 |
+
key_value_prop: str
|
| 28 |
+
call_to_action: str
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
@dataclass(frozen=True)
|
| 32 |
+
class AudiencePersona:
|
| 33 |
+
"""Audience member with behavior priors used in simulation."""
|
| 34 |
+
|
| 35 |
+
persona_id: str
|
| 36 |
+
segment: str
|
| 37 |
+
style_preference: str
|
| 38 |
+
travel_intensity: int
|
| 39 |
+
income_band: str
|
| 40 |
+
preferred_send_hour: int
|
| 41 |
+
open_base: float
|
| 42 |
+
click_base: float
|
| 43 |
+
purchase_base: float
|
| 44 |
+
persona_source: str = "synthetic"
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
@dataclass
|
| 48 |
+
class CampaignArm:
|
| 49 |
+
"""Variant + send-time arm with generated copy and judge scores."""
|
| 50 |
+
|
| 51 |
+
arm_id: str
|
| 52 |
+
variant_name: str
|
| 53 |
+
brand_voice: str
|
| 54 |
+
send_hour: int
|
| 55 |
+
key_value_prop: str
|
| 56 |
+
call_to_action: str
|
| 57 |
+
subject_line: str
|
| 58 |
+
preview_text: str
|
| 59 |
+
email_copy: str
|
| 60 |
+
word_count: int
|
| 61 |
+
validation: Dict[str, bool]
|
| 62 |
+
ctr_proxy_score: float
|
| 63 |
+
generation_source: str
|
| 64 |
+
marketer_score: float
|
| 65 |
+
marketer_rationale: str
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def default_variants() -> List[EmailVariant]:
|
| 69 |
+
"""Default set of copy variants for campaign testing."""
|
| 70 |
+
return [
|
| 71 |
+
EmailVariant(
|
| 72 |
+
name="Bold Launch",
|
| 73 |
+
brand_voice="bold",
|
| 74 |
+
key_value_prop="premium t-shirts for standing out when you travel",
|
| 75 |
+
call_to_action="Shop the launch collection now",
|
| 76 |
+
),
|
| 77 |
+
EmailVariant(
|
| 78 |
+
name="Minimal Core",
|
| 79 |
+
brand_voice="minimal",
|
| 80 |
+
key_value_prop="clean wardrobe staples designed for bringing to the airport",
|
| 81 |
+
call_to_action="Explore the core collection",
|
| 82 |
+
),
|
| 83 |
+
EmailVariant(
|
| 84 |
+
name="Quiet Luxury",
|
| 85 |
+
brand_voice="luxury",
|
| 86 |
+
key_value_prop="soft luxury items for traveling",
|
| 87 |
+
call_to_action="View the curated edit",
|
| 88 |
+
),
|
| 89 |
+
EmailVariant(
|
| 90 |
+
name="Playful Drop",
|
| 91 |
+
brand_voice="playful",
|
| 92 |
+
key_value_prop="the only t-shirt you need for a 14 hour flight",
|
| 93 |
+
call_to_action="See what's new today",
|
| 94 |
+
),
|
| 95 |
+
]
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
class TenXMarketerJudge:
|
| 99 |
+
"""Judge persona: growth marketer with successful fashion-brand launches."""
|
| 100 |
+
|
| 101 |
+
name = "10x_marketer"
|
| 102 |
+
|
| 103 |
+
def score(self, arm: CampaignArm, brand_name: str) -> Tuple[float, str]:
|
| 104 |
+
"""Score copy quality and brand positioning consistency from 0-100."""
|
| 105 |
+
score = 40.0
|
| 106 |
+
notes: List[str] = []
|
| 107 |
+
|
| 108 |
+
if arm.validation.get("subject_has_brand"):
|
| 109 |
+
score += 10
|
| 110 |
+
notes.append("Subject includes brand")
|
| 111 |
+
if arm.validation.get("subject_length_ok"):
|
| 112 |
+
score += 8
|
| 113 |
+
notes.append("Subject length is healthy")
|
| 114 |
+
if arm.validation.get("preview_length_ok"):
|
| 115 |
+
score += 8
|
| 116 |
+
notes.append("Preview length supports opens")
|
| 117 |
+
if arm.validation.get("body_has_cta"):
|
| 118 |
+
score += 10
|
| 119 |
+
notes.append("CTA is present")
|
| 120 |
+
if arm.validation.get("body_word_count_ok"):
|
| 121 |
+
score += 8
|
| 122 |
+
notes.append("Body length is concise")
|
| 123 |
+
|
| 124 |
+
score += arm.ctr_proxy_score * 10
|
| 125 |
+
|
| 126 |
+
lower_copy = arm.email_copy.lower()
|
| 127 |
+
lower_preview = arm.preview_text.lower()
|
| 128 |
+
lower_subject = arm.subject_line.lower()
|
| 129 |
+
quirky_terms = {
|
| 130 |
+
"lounge",
|
| 131 |
+
"flight",
|
| 132 |
+
"airport",
|
| 133 |
+
"carry-on",
|
| 134 |
+
"gate",
|
| 135 |
+
"jet",
|
| 136 |
+
"runway",
|
| 137 |
+
"passport",
|
| 138 |
+
}
|
| 139 |
+
if any(term in lower_copy or term in lower_preview for term in quirky_terms):
|
| 140 |
+
score += 8
|
| 141 |
+
notes.append("Quirky travel lexicon present")
|
| 142 |
+
|
| 143 |
+
positioning_text = f"{arm.key_value_prop} {arm.preview_text}"
|
| 144 |
+
if len(positioning_text.split()) <= 24:
|
| 145 |
+
score += 6
|
| 146 |
+
notes.append("Positioning is short")
|
| 147 |
+
|
| 148 |
+
if brand_name.lower() in lower_subject and brand_name.lower() in lower_copy:
|
| 149 |
+
score += 5
|
| 150 |
+
notes.append("Brand consistency is strong")
|
| 151 |
+
|
| 152 |
+
return max(0.0, min(100.0, round(score, 2))), "; ".join(notes[:4])
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
class MLEngineerJudge:
|
| 156 |
+
"""Judge persona: ML engineer focused on experiment quality and reliability."""
|
| 157 |
+
|
| 158 |
+
name = "ml_engineer_ab_tester"
|
| 159 |
+
|
| 160 |
+
def score_experiment(
|
| 161 |
+
self,
|
| 162 |
+
ranked_results: List[Dict[str, object]],
|
| 163 |
+
audience_size: int,
|
| 164 |
+
) -> Tuple[float, str]:
|
| 165 |
+
"""Score A/B experiment rigor from 0-100."""
|
| 166 |
+
if len(ranked_results) < 2:
|
| 167 |
+
return 0.0, "Need at least two arms to evaluate A/B quality."
|
| 168 |
+
|
| 169 |
+
best = ranked_results[0]
|
| 170 |
+
runner_up = ranked_results[1]
|
| 171 |
+
|
| 172 |
+
p_purchase = two_proportion_p_value(
|
| 173 |
+
int(best["purchases"]),
|
| 174 |
+
int(best["sent"]),
|
| 175 |
+
int(runner_up["purchases"]),
|
| 176 |
+
int(runner_up["sent"]),
|
| 177 |
+
)
|
| 178 |
+
p_ctr = two_proportion_p_value(
|
| 179 |
+
int(best["clicks"]),
|
| 180 |
+
int(best["sent"]),
|
| 181 |
+
int(runner_up["clicks"]),
|
| 182 |
+
int(runner_up["sent"]),
|
| 183 |
+
)
|
| 184 |
+
|
| 185 |
+
score = 55.0
|
| 186 |
+
notes: List[str] = []
|
| 187 |
+
|
| 188 |
+
if audience_size >= 1000:
|
| 189 |
+
score += 15
|
| 190 |
+
notes.append("Strong sample size")
|
| 191 |
+
elif audience_size >= 500:
|
| 192 |
+
score += 10
|
| 193 |
+
notes.append("Good sample size")
|
| 194 |
+
else:
|
| 195 |
+
score -= 5
|
| 196 |
+
notes.append("Limited sample size")
|
| 197 |
+
|
| 198 |
+
if p_purchase < 0.05:
|
| 199 |
+
score += 18
|
| 200 |
+
notes.append("Purchase lift appears significant")
|
| 201 |
+
elif p_purchase < 0.1:
|
| 202 |
+
score += 10
|
| 203 |
+
notes.append("Purchase lift is directional")
|
| 204 |
+
else:
|
| 205 |
+
score -= 6
|
| 206 |
+
notes.append("Purchase lift not significant")
|
| 207 |
+
|
| 208 |
+
if p_ctr < 0.05:
|
| 209 |
+
score += 10
|
| 210 |
+
notes.append("CTR lift appears significant")
|
| 211 |
+
elif p_ctr >= 0.2:
|
| 212 |
+
score -= 4
|
| 213 |
+
notes.append("CTR separation is weak")
|
| 214 |
+
|
| 215 |
+
rationale = (
|
| 216 |
+
f"{'; '.join(notes[:4])}. "
|
| 217 |
+
f"p_purchase={p_purchase:.4f}, p_ctr={p_ctr:.4f}. "
|
| 218 |
+
f"Recommended arm={best['arm_id']}."
|
| 219 |
+
)
|
| 220 |
+
return max(0.0, min(100.0, round(score, 2))), rationale
|
| 221 |
+
|
| 222 |
+
|
| 223 |
+
def generate_persona_dataset(size: int, seed: int) -> List[AudiencePersona]:
|
| 224 |
+
"""Generate synthetic audience personas used to simulate campaign outcomes."""
|
| 225 |
+
rng = random.Random(seed)
|
| 226 |
+
archetypes = [
|
| 227 |
+
{
|
| 228 |
+
"segment": "frequent_flyer_creative",
|
| 229 |
+
"styles": ["bold", "playful"],
|
| 230 |
+
"travel": (6, 14),
|
| 231 |
+
"income": "premium",
|
| 232 |
+
"open": (0.27, 0.42),
|
| 233 |
+
"click": (0.09, 0.18),
|
| 234 |
+
"purchase": (0.03, 0.09),
|
| 235 |
+
"hours": [7, 8, 20, 21],
|
| 236 |
+
},
|
| 237 |
+
{
|
| 238 |
+
"segment": "minimal_urban_professional",
|
| 239 |
+
"styles": ["minimal", "luxury"],
|
| 240 |
+
"travel": (3, 8),
|
| 241 |
+
"income": "premium",
|
| 242 |
+
"open": (0.22, 0.36),
|
| 243 |
+
"click": (0.07, 0.14),
|
| 244 |
+
"purchase": (0.025, 0.07),
|
| 245 |
+
"hours": [8, 12, 18],
|
| 246 |
+
},
|
| 247 |
+
{
|
| 248 |
+
"segment": "budget_style_hunter",
|
| 249 |
+
"styles": ["playful", "bold", "minimal"],
|
| 250 |
+
"travel": (1, 5),
|
| 251 |
+
"income": "mid",
|
| 252 |
+
"open": (0.18, 0.3),
|
| 253 |
+
"click": (0.05, 0.11),
|
| 254 |
+
"purchase": (0.01, 0.04),
|
| 255 |
+
"hours": [12, 18, 19],
|
| 256 |
+
},
|
| 257 |
+
{
|
| 258 |
+
"segment": "luxury_fashion_reader",
|
| 259 |
+
"styles": ["luxury", "minimal"],
|
| 260 |
+
"travel": (4, 10),
|
| 261 |
+
"income": "premium",
|
| 262 |
+
"open": (0.24, 0.38),
|
| 263 |
+
"click": (0.08, 0.15),
|
| 264 |
+
"purchase": (0.03, 0.08),
|
| 265 |
+
"hours": [9, 13, 20],
|
| 266 |
+
},
|
| 267 |
+
]
|
| 268 |
+
weights = [0.28, 0.32, 0.22, 0.18]
|
| 269 |
+
|
| 270 |
+
personas: List[AudiencePersona] = []
|
| 271 |
+
for idx in range(size):
|
| 272 |
+
archetype = rng.choices(archetypes, weights=weights, k=1)[0]
|
| 273 |
+
personas.append(
|
| 274 |
+
AudiencePersona(
|
| 275 |
+
persona_id=f"p_{idx:05d}",
|
| 276 |
+
segment=archetype["segment"],
|
| 277 |
+
style_preference=rng.choice(archetype["styles"]),
|
| 278 |
+
travel_intensity=rng.randint(*archetype["travel"]),
|
| 279 |
+
income_band=archetype["income"],
|
| 280 |
+
preferred_send_hour=rng.choice(archetype["hours"]),
|
| 281 |
+
open_base=round(rng.uniform(*archetype["open"]), 4),
|
| 282 |
+
click_base=round(rng.uniform(*archetype["click"]), 4),
|
| 283 |
+
purchase_base=round(rng.uniform(*archetype["purchase"]), 4),
|
| 284 |
+
persona_source="synthetic",
|
| 285 |
+
)
|
| 286 |
+
)
|
| 287 |
+
return personas
|
| 288 |
+
|
| 289 |
+
|
| 290 |
+
def _clamp_int(value: int, low: int, high: int) -> int:
|
| 291 |
+
"""Clamp integer value to [low, high]."""
|
| 292 |
+
return max(low, min(high, value))
|
| 293 |
+
|
| 294 |
+
|
| 295 |
+
def _infer_style_preference(text: str, rng: random.Random) -> str:
|
| 296 |
+
"""Infer style preference label from Nemotron persona text."""
|
| 297 |
+
groups = {
|
| 298 |
+
"luxury": ["luxury", "couture", "designer", "high-end", "refined", "elegant"],
|
| 299 |
+
"minimal": ["minimal", "clean", "understated", "simple", "neutral"],
|
| 300 |
+
"playful": ["playful", "fun", "quirky", "vibrant", "whimsical", "colorful"],
|
| 301 |
+
"bold": ["bold", "edgy", "statement", "daring", "confident"],
|
| 302 |
+
}
|
| 303 |
+
scores = {
|
| 304 |
+
label: sum(text.count(keyword) for keyword in keywords)
|
| 305 |
+
for label, keywords in groups.items()
|
| 306 |
+
}
|
| 307 |
+
best_score = max(scores.values())
|
| 308 |
+
if best_score <= 0:
|
| 309 |
+
return rng.choice(["minimal", "bold", "playful", "luxury"])
|
| 310 |
+
winners = [label for label, score in scores.items() if score == best_score]
|
| 311 |
+
return rng.choice(winners)
|
| 312 |
+
|
| 313 |
+
|
| 314 |
+
def _infer_income_band(occupation: str, education_level: str) -> str:
|
| 315 |
+
"""Map occupation/education to simplified income band."""
|
| 316 |
+
text = f"{occupation} {education_level}".lower()
|
| 317 |
+
premium_terms = [
|
| 318 |
+
"physician",
|
| 319 |
+
"surgeon",
|
| 320 |
+
"lawyer",
|
| 321 |
+
"attorney",
|
| 322 |
+
"executive",
|
| 323 |
+
"director",
|
| 324 |
+
"manager",
|
| 325 |
+
"engineer",
|
| 326 |
+
"founder",
|
| 327 |
+
"consultant",
|
| 328 |
+
"architect",
|
| 329 |
+
"master",
|
| 330 |
+
"doctorate",
|
| 331 |
+
"phd",
|
| 332 |
+
]
|
| 333 |
+
if any(term in text for term in premium_terms):
|
| 334 |
+
return "premium"
|
| 335 |
+
return "mid"
|
| 336 |
+
|
| 337 |
+
|
| 338 |
+
def _infer_preferred_send_hour(age: int, occupation_text: str, rng: random.Random) -> int:
|
| 339 |
+
"""Infer likely preferred send hour from age/occupation."""
|
| 340 |
+
if age < 28:
|
| 341 |
+
choices = [9, 12, 20, 21]
|
| 342 |
+
elif age < 45:
|
| 343 |
+
choices = [8, 12, 18, 20]
|
| 344 |
+
else:
|
| 345 |
+
choices = [7, 11, 17, 19]
|
| 346 |
+
|
| 347 |
+
occupation_lower = occupation_text.lower()
|
| 348 |
+
if any(term in occupation_lower for term in ["nurse", "doctor", "hospital", "shift"]):
|
| 349 |
+
choices = [7, 15, 21]
|
| 350 |
+
elif any(term in occupation_lower for term in ["student", "intern"]):
|
| 351 |
+
choices = [12, 19, 21]
|
| 352 |
+
|
| 353 |
+
return rng.choice(choices)
|
| 354 |
+
|
| 355 |
+
|
| 356 |
+
def _nemotron_row_to_persona(row: Dict[str, object], seed: int, idx: int) -> AudiencePersona:
|
| 357 |
+
"""Convert Nemotron dataset row into campaign simulation persona."""
|
| 358 |
+
persona_id = str(row.get("uuid") or f"hf_{idx:06d}")
|
| 359 |
+
row_seed = int(
|
| 360 |
+
hashlib.sha256(f"{persona_id}|{seed}".encode("utf-8")).hexdigest()[:16],
|
| 361 |
+
16,
|
| 362 |
+
)
|
| 363 |
+
rng = random.Random(row_seed)
|
| 364 |
+
|
| 365 |
+
professional = str(row.get("professional_persona", ""))
|
| 366 |
+
sports = str(row.get("sports_persona", ""))
|
| 367 |
+
arts = str(row.get("arts_persona", ""))
|
| 368 |
+
travel = str(row.get("travel_persona", ""))
|
| 369 |
+
culinary = str(row.get("culinary_persona", ""))
|
| 370 |
+
persona = str(row.get("persona", ""))
|
| 371 |
+
occupation = str(row.get("occupation", ""))
|
| 372 |
+
education_level = str(row.get("education_level", ""))
|
| 373 |
+
|
| 374 |
+
text_blob = " ".join(
|
| 375 |
+
[
|
| 376 |
+
professional,
|
| 377 |
+
sports,
|
| 378 |
+
arts,
|
| 379 |
+
travel,
|
| 380 |
+
culinary,
|
| 381 |
+
persona,
|
| 382 |
+
str(row.get("hobbies_and_interests", "")),
|
| 383 |
+
str(row.get("hobbies_and_interests_list", "")),
|
| 384 |
+
occupation,
|
| 385 |
+
education_level,
|
| 386 |
+
str(row.get("career_goals_and_ambitions", "")),
|
| 387 |
+
]
|
| 388 |
+
).lower()
|
| 389 |
+
|
| 390 |
+
style_preference = _infer_style_preference(text_blob, rng=rng)
|
| 391 |
+
income_band = _infer_income_band(occupation=occupation, education_level=education_level)
|
| 392 |
+
|
| 393 |
+
travel_terms = [
|
| 394 |
+
"travel",
|
| 395 |
+
"trip",
|
| 396 |
+
"flight",
|
| 397 |
+
"airport",
|
| 398 |
+
"journey",
|
| 399 |
+
"vacation",
|
| 400 |
+
"passport",
|
| 401 |
+
"nomad",
|
| 402 |
+
"explore",
|
| 403 |
+
]
|
| 404 |
+
travel_hits = sum(text_blob.count(term) for term in travel_terms)
|
| 405 |
+
travel_intensity = _clamp_int(1 + travel_hits + rng.randint(0, 2), 1, 14)
|
| 406 |
+
|
| 407 |
+
age = int(row.get("age", 34) or 34)
|
| 408 |
+
preferred_send_hour = _infer_preferred_send_hour(
|
| 409 |
+
age=age,
|
| 410 |
+
occupation_text=occupation,
|
| 411 |
+
rng=rng,
|
| 412 |
+
)
|
| 413 |
+
|
| 414 |
+
open_base = 0.19 + 0.06 * (travel_intensity / 14)
|
| 415 |
+
open_base += 0.05 if income_band == "premium" else 0.0
|
| 416 |
+
open_base += rng.uniform(-0.04, 0.04)
|
| 417 |
+
|
| 418 |
+
click_base = 0.055 + 0.04 * (style_preference in {"bold", "playful"})
|
| 419 |
+
click_base += 0.02 if income_band == "premium" else 0.0
|
| 420 |
+
click_base += rng.uniform(-0.02, 0.02)
|
| 421 |
+
|
| 422 |
+
purchase_base = 0.01 + 0.015 * (travel_intensity / 14)
|
| 423 |
+
purchase_base += 0.022 if income_band == "premium" else 0.0
|
| 424 |
+
purchase_base += rng.uniform(-0.01, 0.01)
|
| 425 |
+
|
| 426 |
+
return AudiencePersona(
|
| 427 |
+
persona_id=persona_id,
|
| 428 |
+
segment=(occupation or professional or "general_consumer").strip().lower().replace(" ", "_"),
|
| 429 |
+
style_preference=style_preference,
|
| 430 |
+
travel_intensity=travel_intensity,
|
| 431 |
+
income_band=income_band,
|
| 432 |
+
preferred_send_hour=preferred_send_hour,
|
| 433 |
+
open_base=round(clamp(open_base, 0.08, 0.65), 4),
|
| 434 |
+
click_base=round(clamp(click_base, 0.02, 0.35), 4),
|
| 435 |
+
purchase_base=round(clamp(purchase_base, 0.003, 0.12), 4),
|
| 436 |
+
persona_source="hf_nemotron",
|
| 437 |
+
)
|
| 438 |
+
|
| 439 |
+
|
| 440 |
+
def load_hf_persona_dataset(
|
| 441 |
+
dataset_name: str,
|
| 442 |
+
split: str,
|
| 443 |
+
size: int,
|
| 444 |
+
seed: int,
|
| 445 |
+
token: str | None,
|
| 446 |
+
) -> List[AudiencePersona]:
|
| 447 |
+
"""Load and map personas from Hugging Face Nemotron dataset."""
|
| 448 |
+
try:
|
| 449 |
+
from datasets import load_dataset
|
| 450 |
+
except ImportError as exc:
|
| 451 |
+
raise RuntimeError("`datasets` package is required for HF persona loading.") from exc
|
| 452 |
+
|
| 453 |
+
kwargs = {
|
| 454 |
+
"path": dataset_name,
|
| 455 |
+
"split": split,
|
| 456 |
+
"streaming": True,
|
| 457 |
+
}
|
| 458 |
+
if token:
|
| 459 |
+
kwargs["token"] = token
|
| 460 |
+
|
| 461 |
+
try:
|
| 462 |
+
dataset_stream = load_dataset(**kwargs)
|
| 463 |
+
except TypeError:
|
| 464 |
+
# Compatibility with older `datasets` argument naming.
|
| 465 |
+
kwargs.pop("token", None)
|
| 466 |
+
kwargs["use_auth_token"] = token
|
| 467 |
+
dataset_stream = load_dataset(**kwargs)
|
| 468 |
+
|
| 469 |
+
try:
|
| 470 |
+
dataset_stream = dataset_stream.shuffle(seed=seed, buffer_size=min(5000, max(1000, size * 3)))
|
| 471 |
+
except Exception:
|
| 472 |
+
# Some iterable backends may not support shuffle; keep original order.
|
| 473 |
+
pass
|
| 474 |
+
|
| 475 |
+
personas: List[AudiencePersona] = []
|
| 476 |
+
for idx, row in enumerate(dataset_stream):
|
| 477 |
+
personas.append(_nemotron_row_to_persona(row=row, seed=seed, idx=idx))
|
| 478 |
+
if len(personas) >= size:
|
| 479 |
+
break
|
| 480 |
+
if not personas:
|
| 481 |
+
raise RuntimeError("No personas loaded from HF dataset.")
|
| 482 |
+
return personas
|
| 483 |
+
|
| 484 |
+
|
| 485 |
+
def save_persona_dataset(personas: List[AudiencePersona], dataset_path: Path) -> None:
|
| 486 |
+
"""Persist mapped persona dataset as CSV."""
|
| 487 |
+
dataset_path.parent.mkdir(parents=True, exist_ok=True)
|
| 488 |
+
with dataset_path.open("w", newline="", encoding="utf-8") as handle:
|
| 489 |
+
writer = csv.DictWriter(
|
| 490 |
+
handle,
|
| 491 |
+
fieldnames=[
|
| 492 |
+
"persona_id",
|
| 493 |
+
"segment",
|
| 494 |
+
"style_preference",
|
| 495 |
+
"travel_intensity",
|
| 496 |
+
"income_band",
|
| 497 |
+
"preferred_send_hour",
|
| 498 |
+
"open_base",
|
| 499 |
+
"click_base",
|
| 500 |
+
"purchase_base",
|
| 501 |
+
"persona_source",
|
| 502 |
+
],
|
| 503 |
+
)
|
| 504 |
+
writer.writeheader()
|
| 505 |
+
for persona in personas:
|
| 506 |
+
writer.writerow(
|
| 507 |
+
{
|
| 508 |
+
"persona_id": persona.persona_id,
|
| 509 |
+
"segment": persona.segment,
|
| 510 |
+
"style_preference": persona.style_preference,
|
| 511 |
+
"travel_intensity": persona.travel_intensity,
|
| 512 |
+
"income_band": persona.income_band,
|
| 513 |
+
"preferred_send_hour": persona.preferred_send_hour,
|
| 514 |
+
"open_base": persona.open_base,
|
| 515 |
+
"click_base": persona.click_base,
|
| 516 |
+
"purchase_base": persona.purchase_base,
|
| 517 |
+
"persona_source": persona.persona_source,
|
| 518 |
+
}
|
| 519 |
+
)
|
| 520 |
+
|
| 521 |
+
|
| 522 |
+
def load_or_create_persona_dataset(
|
| 523 |
+
dataset_path: Path,
|
| 524 |
+
size: int,
|
| 525 |
+
seed: int,
|
| 526 |
+
source: str,
|
| 527 |
+
hf_dataset_name: str,
|
| 528 |
+
hf_split: str,
|
| 529 |
+
refresh: bool,
|
| 530 |
+
allow_synthetic_fallback: bool,
|
| 531 |
+
) -> List[AudiencePersona]:
|
| 532 |
+
"""Load existing persona dataset or create from requested source."""
|
| 533 |
+
if dataset_path.exists() and not refresh:
|
| 534 |
+
return load_persona_dataset(dataset_path)
|
| 535 |
+
|
| 536 |
+
if source == "hf":
|
| 537 |
+
try:
|
| 538 |
+
personas = load_hf_persona_dataset(
|
| 539 |
+
dataset_name=hf_dataset_name,
|
| 540 |
+
split=hf_split,
|
| 541 |
+
size=size,
|
| 542 |
+
seed=seed,
|
| 543 |
+
token=os.getenv("HF_TOKEN") or os.getenv("HUGGINGFACEHUB_API_TOKEN"),
|
| 544 |
+
)
|
| 545 |
+
except Exception as exc:
|
| 546 |
+
if not allow_synthetic_fallback:
|
| 547 |
+
raise RuntimeError(
|
| 548 |
+
"Failed to load personas from Hugging Face dataset. "
|
| 549 |
+
"Use --allow-synthetic-fallback to continue with synthetic personas."
|
| 550 |
+
) from exc
|
| 551 |
+
print(f"Warning: HF dataset load failed ({exc}); using synthetic personas.")
|
| 552 |
+
personas = generate_persona_dataset(size=size, seed=seed)
|
| 553 |
+
else:
|
| 554 |
+
personas = generate_persona_dataset(size=size, seed=seed)
|
| 555 |
+
|
| 556 |
+
save_persona_dataset(personas, dataset_path=dataset_path)
|
| 557 |
+
return personas
|
| 558 |
+
|
| 559 |
+
|
| 560 |
+
def load_persona_dataset(dataset_path: Path) -> List[AudiencePersona]:
|
| 561 |
+
"""Load persona dataset CSV."""
|
| 562 |
+
personas: List[AudiencePersona] = []
|
| 563 |
+
with dataset_path.open("r", newline="", encoding="utf-8") as handle:
|
| 564 |
+
reader = csv.DictReader(handle)
|
| 565 |
+
for row in reader:
|
| 566 |
+
personas.append(
|
| 567 |
+
AudiencePersona(
|
| 568 |
+
persona_id=row["persona_id"],
|
| 569 |
+
segment=row["segment"],
|
| 570 |
+
style_preference=row["style_preference"],
|
| 571 |
+
travel_intensity=int(row["travel_intensity"]),
|
| 572 |
+
income_band=row["income_band"],
|
| 573 |
+
preferred_send_hour=int(row["preferred_send_hour"]),
|
| 574 |
+
open_base=float(row["open_base"]),
|
| 575 |
+
click_base=float(row["click_base"]),
|
| 576 |
+
purchase_base=float(row["purchase_base"]),
|
| 577 |
+
persona_source=row.get("persona_source", "unknown"),
|
| 578 |
+
)
|
| 579 |
+
)
|
| 580 |
+
return personas
|
| 581 |
+
|
| 582 |
+
|
| 583 |
+
def build_campaign_arms(
|
| 584 |
+
brand_name: str,
|
| 585 |
+
target_audience: str,
|
| 586 |
+
send_hours: List[int],
|
| 587 |
+
) -> List[CampaignArm]:
|
| 588 |
+
"""Generate copy with OpenEnv and expand into variant x send-time arms."""
|
| 589 |
+
env = ClothingBrandCtrEnvironment()
|
| 590 |
+
env.reset()
|
| 591 |
+
marketer = TenXMarketerJudge()
|
| 592 |
+
|
| 593 |
+
arms: List[CampaignArm] = []
|
| 594 |
+
for variant in default_variants():
|
| 595 |
+
action = ClothingBrandCtrAction(
|
| 596 |
+
brand_name=brand_name,
|
| 597 |
+
target_audience=target_audience,
|
| 598 |
+
brand_voice=variant.brand_voice,
|
| 599 |
+
key_value_prop=variant.key_value_prop,
|
| 600 |
+
call_to_action=variant.call_to_action,
|
| 601 |
+
metadata={"variant_name": variant.name},
|
| 602 |
+
)
|
| 603 |
+
observation = env.step(action)
|
| 604 |
+
|
| 605 |
+
for hour in send_hours:
|
| 606 |
+
arm = CampaignArm(
|
| 607 |
+
arm_id=f"{variant.name.replace(' ', '_').lower()}__{hour:02d}00",
|
| 608 |
+
variant_name=variant.name,
|
| 609 |
+
brand_voice=variant.brand_voice,
|
| 610 |
+
send_hour=hour,
|
| 611 |
+
key_value_prop=variant.key_value_prop,
|
| 612 |
+
call_to_action=variant.call_to_action,
|
| 613 |
+
subject_line=observation.subject_line,
|
| 614 |
+
preview_text=observation.preview_text,
|
| 615 |
+
email_copy=observation.email_copy,
|
| 616 |
+
word_count=observation.word_count,
|
| 617 |
+
validation=observation.validation,
|
| 618 |
+
ctr_proxy_score=observation.ctr_proxy_score,
|
| 619 |
+
generation_source=observation.metadata.get(
|
| 620 |
+
"generation_source",
|
| 621 |
+
"unknown",
|
| 622 |
+
),
|
| 623 |
+
marketer_score=0.0,
|
| 624 |
+
marketer_rationale="",
|
| 625 |
+
)
|
| 626 |
+
score, rationale = marketer.score(arm=arm, brand_name=brand_name)
|
| 627 |
+
arm.marketer_score = score
|
| 628 |
+
arm.marketer_rationale = rationale
|
| 629 |
+
arms.append(arm)
|
| 630 |
+
return arms
|
| 631 |
+
|
| 632 |
+
|
| 633 |
+
def simulate_arm(
|
| 634 |
+
arm: CampaignArm,
|
| 635 |
+
personas: List[AudiencePersona],
|
| 636 |
+
seed: int,
|
| 637 |
+
capture_outcomes: bool = False,
|
| 638 |
+
) -> Tuple[Dict[str, object], List[Dict[str, object]]]:
|
| 639 |
+
"""Simulate one campaign arm across all personas."""
|
| 640 |
+
rng = random.Random(seed)
|
| 641 |
+
|
| 642 |
+
sent = len(personas)
|
| 643 |
+
opens = clicks = purchases = 0
|
| 644 |
+
outcomes: List[Dict[str, object]] = []
|
| 645 |
+
|
| 646 |
+
for persona in personas:
|
| 647 |
+
open_prob = calc_open_probability(arm=arm, persona=persona)
|
| 648 |
+
opened = rng.random() < open_prob
|
| 649 |
+
|
| 650 |
+
click_prob = calc_click_probability(arm=arm, persona=persona, opened=opened)
|
| 651 |
+
clicked = opened and rng.random() < click_prob
|
| 652 |
+
|
| 653 |
+
purchase_prob = calc_purchase_probability(
|
| 654 |
+
arm=arm,
|
| 655 |
+
persona=persona,
|
| 656 |
+
clicked=clicked,
|
| 657 |
+
)
|
| 658 |
+
purchased = clicked and rng.random() < purchase_prob
|
| 659 |
+
|
| 660 |
+
opens += int(opened)
|
| 661 |
+
clicks += int(clicked)
|
| 662 |
+
purchases += int(purchased)
|
| 663 |
+
|
| 664 |
+
if capture_outcomes:
|
| 665 |
+
outcomes.append(
|
| 666 |
+
{
|
| 667 |
+
"persona_id": persona.persona_id,
|
| 668 |
+
"segment": persona.segment,
|
| 669 |
+
"persona_source": persona.persona_source,
|
| 670 |
+
"style_preference": persona.style_preference,
|
| 671 |
+
"preferred_send_hour": persona.preferred_send_hour,
|
| 672 |
+
"opened": int(opened),
|
| 673 |
+
"clicked": int(clicked),
|
| 674 |
+
"purchased": int(purchased),
|
| 675 |
+
}
|
| 676 |
+
)
|
| 677 |
+
|
| 678 |
+
open_rate = opens / sent if sent else 0.0
|
| 679 |
+
ctr = clicks / sent if sent else 0.0
|
| 680 |
+
click_to_open_rate = clicks / opens if opens else 0.0
|
| 681 |
+
purchase_rate = purchases / sent if sent else 0.0
|
| 682 |
+
composite_score = (0.2 * open_rate) + (0.3 * ctr) + (0.5 * purchase_rate)
|
| 683 |
+
|
| 684 |
+
metrics = {
|
| 685 |
+
"arm_id": arm.arm_id,
|
| 686 |
+
"variant_name": arm.variant_name,
|
| 687 |
+
"brand_voice": arm.brand_voice,
|
| 688 |
+
"send_hour": arm.send_hour,
|
| 689 |
+
"generation_source": arm.generation_source,
|
| 690 |
+
"marketer_score": arm.marketer_score,
|
| 691 |
+
"marketer_rationale": arm.marketer_rationale,
|
| 692 |
+
"subject_line": arm.subject_line,
|
| 693 |
+
"sent": sent,
|
| 694 |
+
"opens": opens,
|
| 695 |
+
"clicks": clicks,
|
| 696 |
+
"purchases": purchases,
|
| 697 |
+
"open_rate": round(open_rate, 4),
|
| 698 |
+
"ctr": round(ctr, 4),
|
| 699 |
+
"click_to_open_rate": round(click_to_open_rate, 4),
|
| 700 |
+
"purchase_rate": round(purchase_rate, 4),
|
| 701 |
+
"composite_score": round(composite_score, 4),
|
| 702 |
+
}
|
| 703 |
+
return metrics, outcomes
|
| 704 |
+
|
| 705 |
+
|
| 706 |
+
def calc_open_probability(arm: CampaignArm, persona: AudiencePersona) -> float:
|
| 707 |
+
"""Estimate probability that persona opens this email."""
|
| 708 |
+
alignment = send_time_alignment(arm.send_hour, persona.preferred_send_hour)
|
| 709 |
+
style_match = 1.0 if arm.brand_voice == persona.style_preference else 0.0
|
| 710 |
+
travel_signal = 1.0 if "travel" in (arm.preview_text + arm.email_copy).lower() else 0.0
|
| 711 |
+
|
| 712 |
+
prob = persona.open_base
|
| 713 |
+
prob += 0.16 * ((arm.marketer_score / 100.0) - 0.5)
|
| 714 |
+
prob += 0.10 * (arm.ctr_proxy_score - 0.5)
|
| 715 |
+
prob += 0.09 * alignment
|
| 716 |
+
prob += 0.05 * style_match
|
| 717 |
+
prob += 0.03 * travel_signal * min(persona.travel_intensity / 10.0, 1.0)
|
| 718 |
+
return clamp(prob, 0.01, 0.95)
|
| 719 |
+
|
| 720 |
+
|
| 721 |
+
def calc_click_probability(
|
| 722 |
+
arm: CampaignArm,
|
| 723 |
+
persona: AudiencePersona,
|
| 724 |
+
opened: bool,
|
| 725 |
+
) -> float:
|
| 726 |
+
"""Estimate probability that persona clicks after open."""
|
| 727 |
+
if not opened:
|
| 728 |
+
return 0.0
|
| 729 |
+
style_match = 1.0 if arm.brand_voice == persona.style_preference else 0.0
|
| 730 |
+
|
| 731 |
+
prob = persona.click_base
|
| 732 |
+
prob += 0.15 * ((arm.marketer_score / 100.0) - 0.5)
|
| 733 |
+
prob += 0.14 * (arm.ctr_proxy_score - 0.5)
|
| 734 |
+
prob += 0.05 if arm.validation.get("body_has_cta") else -0.02
|
| 735 |
+
prob += 0.02 if arm.validation.get("preview_length_ok") else -0.01
|
| 736 |
+
prob += 0.03 * style_match
|
| 737 |
+
return clamp(prob, 0.005, 0.85)
|
| 738 |
+
|
| 739 |
+
|
| 740 |
+
def calc_purchase_probability(
|
| 741 |
+
arm: CampaignArm,
|
| 742 |
+
persona: AudiencePersona,
|
| 743 |
+
clicked: bool,
|
| 744 |
+
) -> float:
|
| 745 |
+
"""Estimate probability that persona purchases after click."""
|
| 746 |
+
if not clicked:
|
| 747 |
+
return 0.0
|
| 748 |
+
income_boost = {"premium": 0.05, "mid": 0.02}.get(persona.income_band, 0.0)
|
| 749 |
+
style_match = 1.0 if arm.brand_voice == persona.style_preference else 0.0
|
| 750 |
+
travel_signal = 1.0 if "travel" in arm.email_copy.lower() else 0.0
|
| 751 |
+
|
| 752 |
+
prob = persona.purchase_base
|
| 753 |
+
prob += 0.10 * ((arm.marketer_score / 100.0) - 0.5)
|
| 754 |
+
prob += 0.05 * style_match
|
| 755 |
+
prob += 0.02 * travel_signal * min(persona.travel_intensity / 10.0, 1.0)
|
| 756 |
+
prob += income_boost
|
| 757 |
+
return clamp(prob, 0.002, 0.55)
|
| 758 |
+
|
| 759 |
+
|
| 760 |
+
def send_time_alignment(send_hour: int, preferred_hour: int) -> float:
|
| 761 |
+
"""Return alignment score in [-1, 1] based on send-hour distance."""
|
| 762 |
+
diff = abs(send_hour - preferred_hour) % 24
|
| 763 |
+
wrapped = min(diff, 24 - diff)
|
| 764 |
+
return (1.0 - (wrapped / 12.0)) * 2.0 - 1.0
|
| 765 |
+
|
| 766 |
+
|
| 767 |
+
def clamp(value: float, low: float, high: float) -> float:
|
| 768 |
+
"""Clamp a numeric value to [low, high]."""
|
| 769 |
+
return max(low, min(high, value))
|
| 770 |
+
|
| 771 |
+
|
| 772 |
+
def two_proportion_p_value(
|
| 773 |
+
success_a: int,
|
| 774 |
+
total_a: int,
|
| 775 |
+
success_b: int,
|
| 776 |
+
total_b: int,
|
| 777 |
+
) -> float:
|
| 778 |
+
"""Two-sided p-value for difference between two Bernoulli proportions."""
|
| 779 |
+
if total_a <= 0 or total_b <= 0:
|
| 780 |
+
return 1.0
|
| 781 |
+
p_a = success_a / total_a
|
| 782 |
+
p_b = success_b / total_b
|
| 783 |
+
pooled = (success_a + success_b) / (total_a + total_b)
|
| 784 |
+
variance = pooled * (1 - pooled) * ((1 / total_a) + (1 / total_b))
|
| 785 |
+
if variance <= 0:
|
| 786 |
+
return 1.0
|
| 787 |
+
z = (p_a - p_b) / math.sqrt(variance)
|
| 788 |
+
cdf = 0.5 * (1 + math.erf(abs(z) / math.sqrt(2)))
|
| 789 |
+
return max(0.0, min(1.0, 2 * (1 - cdf)))
|
| 790 |
+
|
| 791 |
+
|
| 792 |
+
def save_arm_metrics(results: List[Dict[str, object]], output_path: Path) -> None:
|
| 793 |
+
"""Write arm-level simulation metrics to CSV."""
|
| 794 |
+
output_path.parent.mkdir(parents=True, exist_ok=True)
|
| 795 |
+
with output_path.open("w", newline="", encoding="utf-8") as handle:
|
| 796 |
+
writer = csv.DictWriter(
|
| 797 |
+
handle,
|
| 798 |
+
fieldnames=[
|
| 799 |
+
"rank",
|
| 800 |
+
"arm_id",
|
| 801 |
+
"variant_name",
|
| 802 |
+
"brand_voice",
|
| 803 |
+
"send_hour",
|
| 804 |
+
"generation_source",
|
| 805 |
+
"marketer_score",
|
| 806 |
+
"open_rate",
|
| 807 |
+
"ctr",
|
| 808 |
+
"click_to_open_rate",
|
| 809 |
+
"purchase_rate",
|
| 810 |
+
"composite_score",
|
| 811 |
+
"opens",
|
| 812 |
+
"clicks",
|
| 813 |
+
"purchases",
|
| 814 |
+
"sent",
|
| 815 |
+
"subject_line",
|
| 816 |
+
],
|
| 817 |
+
)
|
| 818 |
+
writer.writeheader()
|
| 819 |
+
for rank, row in enumerate(results, start=1):
|
| 820 |
+
writer.writerow(
|
| 821 |
+
{
|
| 822 |
+
"rank": rank,
|
| 823 |
+
"arm_id": row["arm_id"],
|
| 824 |
+
"variant_name": row["variant_name"],
|
| 825 |
+
"brand_voice": row["brand_voice"],
|
| 826 |
+
"send_hour": row["send_hour"],
|
| 827 |
+
"generation_source": row["generation_source"],
|
| 828 |
+
"marketer_score": row["marketer_score"],
|
| 829 |
+
"open_rate": row["open_rate"],
|
| 830 |
+
"ctr": row["ctr"],
|
| 831 |
+
"click_to_open_rate": row["click_to_open_rate"],
|
| 832 |
+
"purchase_rate": row["purchase_rate"],
|
| 833 |
+
"composite_score": row["composite_score"],
|
| 834 |
+
"opens": row["opens"],
|
| 835 |
+
"clicks": row["clicks"],
|
| 836 |
+
"purchases": row["purchases"],
|
| 837 |
+
"sent": row["sent"],
|
| 838 |
+
"subject_line": row["subject_line"],
|
| 839 |
+
}
|
| 840 |
+
)
|
| 841 |
+
|
| 842 |
+
|
| 843 |
+
def save_top_arm_outcomes(outcomes: List[Dict[str, object]], output_path: Path) -> None:
|
| 844 |
+
"""Write per-persona outcomes for the winning arm."""
|
| 845 |
+
output_path.parent.mkdir(parents=True, exist_ok=True)
|
| 846 |
+
with output_path.open("w", newline="", encoding="utf-8") as handle:
|
| 847 |
+
writer = csv.DictWriter(
|
| 848 |
+
handle,
|
| 849 |
+
fieldnames=[
|
| 850 |
+
"persona_id",
|
| 851 |
+
"segment",
|
| 852 |
+
"persona_source",
|
| 853 |
+
"style_preference",
|
| 854 |
+
"preferred_send_hour",
|
| 855 |
+
"opened",
|
| 856 |
+
"clicked",
|
| 857 |
+
"purchased",
|
| 858 |
+
],
|
| 859 |
+
)
|
| 860 |
+
writer.writeheader()
|
| 861 |
+
for row in outcomes:
|
| 862 |
+
writer.writerow(row)
|
| 863 |
+
|
| 864 |
+
|
| 865 |
+
def print_results(
|
| 866 |
+
ranked_results: List[Dict[str, object]],
|
| 867 |
+
marketer_name: str,
|
| 868 |
+
ml_score: float,
|
| 869 |
+
ml_rationale: str,
|
| 870 |
+
) -> None:
|
| 871 |
+
"""Print top-line simulation leaderboard + judge outputs."""
|
| 872 |
+
print("\nCampaign Arms Leaderboard")
|
| 873 |
+
print("-" * 130)
|
| 874 |
+
print(
|
| 875 |
+
f"{'Rank':<5} {'Arm':<26} {'Score':<7} {'Open':<7} {'CTR':<7} {'Purchase':<9} "
|
| 876 |
+
f"{'MktScore':<9} {'Source':<17} {'Send'}"
|
| 877 |
+
)
|
| 878 |
+
print("-" * 130)
|
| 879 |
+
for rank, row in enumerate(ranked_results[:10], start=1):
|
| 880 |
+
print(
|
| 881 |
+
f"{rank:<5} {str(row['arm_id']):<26} {float(row['composite_score']):<7.3f} "
|
| 882 |
+
f"{float(row['open_rate']):<7.3f} {float(row['ctr']):<7.3f} "
|
| 883 |
+
f"{float(row['purchase_rate']):<9.3f} {float(row['marketer_score']):<9.1f} "
|
| 884 |
+
f"{str(row['generation_source']):<17} {int(row['send_hour']):02d}:00"
|
| 885 |
+
)
|
| 886 |
+
|
| 887 |
+
top = ranked_results[0]
|
| 888 |
+
print("\nWinning Campaign Arm")
|
| 889 |
+
print("-" * 130)
|
| 890 |
+
print(f"Arm: {top['arm_id']}")
|
| 891 |
+
print(f"Subject: {top['subject_line']}")
|
| 892 |
+
print(f"Open Rate: {top['open_rate']}")
|
| 893 |
+
print(f"CTR: {top['ctr']}")
|
| 894 |
+
print(f"Purchase Rate: {top['purchase_rate']}")
|
| 895 |
+
print(f"{marketer_name} score: {top['marketer_score']} ({top['marketer_rationale']})")
|
| 896 |
+
|
| 897 |
+
print("\nJudge: ML Engineer (A/B Testing)")
|
| 898 |
+
print("-" * 130)
|
| 899 |
+
print(f"Experiment score: {ml_score}/100")
|
| 900 |
+
print(ml_rationale)
|
| 901 |
+
|
| 902 |
+
|
| 903 |
+
def parse_send_hours(raw: str) -> List[int]:
|
| 904 |
+
"""Parse comma-separated hour list into integers [0,23]."""
|
| 905 |
+
hours: List[int] = []
|
| 906 |
+
for token in raw.split(","):
|
| 907 |
+
token = token.strip()
|
| 908 |
+
if not token:
|
| 909 |
+
continue
|
| 910 |
+
hour = int(token)
|
| 911 |
+
if hour < 0 or hour > 23:
|
| 912 |
+
raise ValueError(f"Invalid send hour: {hour}")
|
| 913 |
+
hours.append(hour)
|
| 914 |
+
if not hours:
|
| 915 |
+
raise ValueError("At least one send hour is required.")
|
| 916 |
+
return sorted(set(hours))
|
| 917 |
+
|
| 918 |
+
|
| 919 |
+
def main() -> None:
|
| 920 |
+
parser = argparse.ArgumentParser(
|
| 921 |
+
description="Simulate brand email campaign performance with judge personas.",
|
| 922 |
+
)
|
| 923 |
+
parser.add_argument("--brand-name", default="AIRPORT CLUB")
|
| 924 |
+
parser.add_argument("--target-audience", default="fellow traveler")
|
| 925 |
+
parser.add_argument(
|
| 926 |
+
"--send-hours",
|
| 927 |
+
default="8,12,18,21",
|
| 928 |
+
help="Comma-separated send hours (0-23).",
|
| 929 |
+
)
|
| 930 |
+
parser.add_argument(
|
| 931 |
+
"--persona-dataset",
|
| 932 |
+
default="outputs/evals/persona_dataset.csv",
|
| 933 |
+
help="CSV path for audience persona dataset.",
|
| 934 |
+
)
|
| 935 |
+
parser.add_argument(
|
| 936 |
+
"--persona-source",
|
| 937 |
+
choices=["hf", "synthetic"],
|
| 938 |
+
default="hf",
|
| 939 |
+
help="Persona source. Default uses Hugging Face Nemotron dataset.",
|
| 940 |
+
)
|
| 941 |
+
parser.add_argument(
|
| 942 |
+
"--hf-dataset-name",
|
| 943 |
+
default=os.getenv("HF_PERSONA_DATASET", "nvidia/Nemotron-Personas-USA"),
|
| 944 |
+
help="Hugging Face dataset id used when --persona-source=hf.",
|
| 945 |
+
)
|
| 946 |
+
parser.add_argument(
|
| 947 |
+
"--hf-split",
|
| 948 |
+
default=os.getenv("HF_PERSONA_SPLIT", "train"),
|
| 949 |
+
help="Hugging Face split used when --persona-source=hf.",
|
| 950 |
+
)
|
| 951 |
+
parser.add_argument(
|
| 952 |
+
"--refresh-personas",
|
| 953 |
+
action="store_true",
|
| 954 |
+
help="Rebuild persona CSV from source even if cached CSV exists.",
|
| 955 |
+
)
|
| 956 |
+
parser.add_argument(
|
| 957 |
+
"--allow-synthetic-fallback",
|
| 958 |
+
action="store_true",
|
| 959 |
+
help="Allow fallback to synthetic personas if HF dataset load fails.",
|
| 960 |
+
)
|
| 961 |
+
parser.add_argument(
|
| 962 |
+
"--persona-count",
|
| 963 |
+
type=int,
|
| 964 |
+
default=1200,
|
| 965 |
+
help="How many personas to generate when dataset does not exist.",
|
| 966 |
+
)
|
| 967 |
+
parser.add_argument(
|
| 968 |
+
"--seed",
|
| 969 |
+
type=int,
|
| 970 |
+
default=42,
|
| 971 |
+
help="Random seed for reproducibility.",
|
| 972 |
+
)
|
| 973 |
+
parser.add_argument(
|
| 974 |
+
"--results-csv",
|
| 975 |
+
default="outputs/evals/brand_campaign_arm_results.csv",
|
| 976 |
+
help="Output CSV path for arm-level metrics.",
|
| 977 |
+
)
|
| 978 |
+
parser.add_argument(
|
| 979 |
+
"--top-arm-outcomes-csv",
|
| 980 |
+
default="outputs/evals/top_arm_persona_outcomes.csv",
|
| 981 |
+
help="Output CSV path for winner-arm per-persona outcomes.",
|
| 982 |
+
)
|
| 983 |
+
args = parser.parse_args()
|
| 984 |
+
|
| 985 |
+
send_hours = parse_send_hours(args.send_hours)
|
| 986 |
+
persona_path = Path(args.persona_dataset)
|
| 987 |
+
personas = load_or_create_persona_dataset(
|
| 988 |
+
dataset_path=persona_path,
|
| 989 |
+
size=args.persona_count,
|
| 990 |
+
seed=args.seed,
|
| 991 |
+
source=args.persona_source,
|
| 992 |
+
hf_dataset_name=args.hf_dataset_name,
|
| 993 |
+
hf_split=args.hf_split,
|
| 994 |
+
refresh=args.refresh_personas,
|
| 995 |
+
allow_synthetic_fallback=args.allow_synthetic_fallback,
|
| 996 |
+
)
|
| 997 |
+
|
| 998 |
+
arms = build_campaign_arms(
|
| 999 |
+
brand_name=args.brand_name,
|
| 1000 |
+
target_audience=args.target_audience,
|
| 1001 |
+
send_hours=send_hours,
|
| 1002 |
+
)
|
| 1003 |
+
|
| 1004 |
+
metrics: List[Dict[str, object]] = []
|
| 1005 |
+
for idx, arm in enumerate(arms):
|
| 1006 |
+
arm_seed = args.seed + (idx * 7919)
|
| 1007 |
+
arm_metrics, _ = simulate_arm(
|
| 1008 |
+
arm=arm,
|
| 1009 |
+
personas=personas,
|
| 1010 |
+
seed=arm_seed,
|
| 1011 |
+
capture_outcomes=False,
|
| 1012 |
+
)
|
| 1013 |
+
metrics.append(arm_metrics)
|
| 1014 |
+
|
| 1015 |
+
ranked_results = sorted(
|
| 1016 |
+
metrics,
|
| 1017 |
+
key=lambda row: (
|
| 1018 |
+
float(row["composite_score"]),
|
| 1019 |
+
float(row["purchase_rate"]),
|
| 1020 |
+
float(row["ctr"]),
|
| 1021 |
+
float(row["open_rate"]),
|
| 1022 |
+
),
|
| 1023 |
+
reverse=True,
|
| 1024 |
+
)
|
| 1025 |
+
|
| 1026 |
+
# Re-run winning arm with deterministic seed to export per-persona outcomes.
|
| 1027 |
+
best_arm_id = ranked_results[0]["arm_id"]
|
| 1028 |
+
best_arm = next(arm for arm in arms if arm.arm_id == best_arm_id)
|
| 1029 |
+
_, outcomes = simulate_arm(
|
| 1030 |
+
arm=best_arm,
|
| 1031 |
+
personas=personas,
|
| 1032 |
+
seed=args.seed + 999999,
|
| 1033 |
+
capture_outcomes=True,
|
| 1034 |
+
)
|
| 1035 |
+
|
| 1036 |
+
ml_judge = MLEngineerJudge()
|
| 1037 |
+
ml_score, ml_rationale = ml_judge.score_experiment(
|
| 1038 |
+
ranked_results=ranked_results,
|
| 1039 |
+
audience_size=len(personas),
|
| 1040 |
+
)
|
| 1041 |
+
|
| 1042 |
+
save_arm_metrics(ranked_results, Path(args.results_csv))
|
| 1043 |
+
save_top_arm_outcomes(outcomes, Path(args.top_arm_outcomes_csv))
|
| 1044 |
+
print_results(
|
| 1045 |
+
ranked_results=ranked_results,
|
| 1046 |
+
marketer_name=TenXMarketerJudge.name,
|
| 1047 |
+
ml_score=ml_score,
|
| 1048 |
+
ml_rationale=ml_rationale,
|
| 1049 |
+
)
|
| 1050 |
+
print(f"\nPersona source: {personas[0].persona_source if personas else 'unknown'}")
|
| 1051 |
+
print(f"\nPersona dataset: {persona_path}")
|
| 1052 |
+
print(f"Arm results: {args.results_csv}")
|
| 1053 |
+
print(f"Top-arm outcomes: {args.top_arm_outcomes_csv}")
|
| 1054 |
+
|
| 1055 |
+
|
| 1056 |
+
if __name__ == "__main__":
|
| 1057 |
+
main()
|
simulate_email_variants.py
ADDED
|
@@ -0,0 +1,222 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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| 1 |
+
"""Run a simple multi-step simulation to compare and rank email variants."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import argparse
|
| 6 |
+
import csv
|
| 7 |
+
import os
|
| 8 |
+
from dataclasses import dataclass
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
from typing import Dict, List
|
| 11 |
+
|
| 12 |
+
from clothing_brand_ctr_env import ClothingBrandCtrAction
|
| 13 |
+
from clothing_brand_ctr_env.server.clothing_brand_ctr_env_environment import (
|
| 14 |
+
ClothingBrandCtrEnvironment,
|
| 15 |
+
)
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
@dataclass(frozen=True)
|
| 19 |
+
class EmailVariant:
|
| 20 |
+
"""Single email variant configuration."""
|
| 21 |
+
|
| 22 |
+
name: str
|
| 23 |
+
brand_voice: str
|
| 24 |
+
key_value_prop: str
|
| 25 |
+
call_to_action: str
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def default_variants() -> List[EmailVariant]:
|
| 29 |
+
"""Default set of variants for quick comparisons."""
|
| 30 |
+
return [
|
| 31 |
+
EmailVariant(
|
| 32 |
+
name="Bold Launch",
|
| 33 |
+
brand_voice="bold",
|
| 34 |
+
key_value_prop="premium t-shirts for standing out when you travel",
|
| 35 |
+
call_to_action="Shop the launch collection now",
|
| 36 |
+
),
|
| 37 |
+
EmailVariant(
|
| 38 |
+
name="Minimal Core",
|
| 39 |
+
brand_voice="minimal",
|
| 40 |
+
key_value_prop="clean wardrobe staples designed for bringing to the airport",
|
| 41 |
+
call_to_action="Explore the core collection",
|
| 42 |
+
),
|
| 43 |
+
EmailVariant(
|
| 44 |
+
name="Quiet Luxury",
|
| 45 |
+
brand_voice="luxury",
|
| 46 |
+
key_value_prop="soft luxury items for traveling",
|
| 47 |
+
call_to_action="View the curated edit",
|
| 48 |
+
),
|
| 49 |
+
EmailVariant(
|
| 50 |
+
name="Playful Drop",
|
| 51 |
+
brand_voice="playful",
|
| 52 |
+
key_value_prop="the only t-shirt you need for a 14 hour flight",
|
| 53 |
+
call_to_action="See what's new today",
|
| 54 |
+
),
|
| 55 |
+
]
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def run_simulation(
|
| 59 |
+
brand_name: str,
|
| 60 |
+
target_audience: str,
|
| 61 |
+
variants: List[EmailVariant],
|
| 62 |
+
) -> List[Dict[str, object]]:
|
| 63 |
+
"""Evaluate variants over multiple steps and return ranked results."""
|
| 64 |
+
env = ClothingBrandCtrEnvironment()
|
| 65 |
+
env.reset()
|
| 66 |
+
|
| 67 |
+
results: List[Dict[str, object]] = []
|
| 68 |
+
for variant in variants:
|
| 69 |
+
action = ClothingBrandCtrAction(
|
| 70 |
+
brand_name=brand_name,
|
| 71 |
+
target_audience=target_audience,
|
| 72 |
+
brand_voice=variant.brand_voice,
|
| 73 |
+
key_value_prop=variant.key_value_prop,
|
| 74 |
+
call_to_action=variant.call_to_action,
|
| 75 |
+
metadata={"variant_name": variant.name},
|
| 76 |
+
)
|
| 77 |
+
observation = env.step(action)
|
| 78 |
+
|
| 79 |
+
passed_rules = sum(1 for passed in observation.validation.values() if passed)
|
| 80 |
+
results.append(
|
| 81 |
+
{
|
| 82 |
+
"variant_name": variant.name,
|
| 83 |
+
"brand_voice": variant.brand_voice,
|
| 84 |
+
"ctr_proxy_score": observation.ctr_proxy_score,
|
| 85 |
+
"validation_passed": observation.validation_passed,
|
| 86 |
+
"passed_rules": passed_rules,
|
| 87 |
+
"generation_source": observation.metadata.get(
|
| 88 |
+
"generation_source",
|
| 89 |
+
"unknown",
|
| 90 |
+
),
|
| 91 |
+
"subject_line": observation.subject_line,
|
| 92 |
+
"preview_text": observation.preview_text,
|
| 93 |
+
"email_copy": observation.email_copy,
|
| 94 |
+
"word_count": observation.word_count,
|
| 95 |
+
"validation": observation.validation,
|
| 96 |
+
}
|
| 97 |
+
)
|
| 98 |
+
|
| 99 |
+
return sorted(
|
| 100 |
+
results,
|
| 101 |
+
key=lambda item: (
|
| 102 |
+
float(item["ctr_proxy_score"]),
|
| 103 |
+
int(item["passed_rules"]),
|
| 104 |
+
int(item["word_count"]),
|
| 105 |
+
),
|
| 106 |
+
reverse=True,
|
| 107 |
+
)
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def print_rankings(rankings: List[Dict[str, object]]) -> None:
|
| 111 |
+
"""Print a compact leaderboard for quick comparison."""
|
| 112 |
+
print("\nEmail Variant Leaderboard")
|
| 113 |
+
print("-" * 116)
|
| 114 |
+
print(
|
| 115 |
+
f"{'Rank':<5} {'Variant':<16} {'Voice':<9} {'Score':<7} {'Checks':<7} {'Source':<18} {'Subject Line'}"
|
| 116 |
+
)
|
| 117 |
+
print("-" * 116)
|
| 118 |
+
|
| 119 |
+
for rank, row in enumerate(rankings, start=1):
|
| 120 |
+
subject = str(row["subject_line"])
|
| 121 |
+
if len(subject) > 46:
|
| 122 |
+
subject = subject[:43] + "..."
|
| 123 |
+
checks = f"{row['passed_rules']}/{len(row['validation'])}"
|
| 124 |
+
print(
|
| 125 |
+
f"{rank:<5} {str(row['variant_name']):<16} {str(row['brand_voice']):<9} "
|
| 126 |
+
f"{float(row['ctr_proxy_score']):<7.2f} {checks:<7} "
|
| 127 |
+
f"{str(row['generation_source']):<18} {subject}"
|
| 128 |
+
)
|
| 129 |
+
|
| 130 |
+
best = rankings[0]
|
| 131 |
+
print("\nTop Variant")
|
| 132 |
+
print("-" * 96)
|
| 133 |
+
print(f"Name: {best['variant_name']}")
|
| 134 |
+
print(f"Voice: {best['brand_voice']}")
|
| 135 |
+
print(f"Score: {best['ctr_proxy_score']}")
|
| 136 |
+
print(f"Validation Passed: {best['validation_passed']}")
|
| 137 |
+
print(f"Generation Source: {best['generation_source']}")
|
| 138 |
+
print(f"Preview: {best['preview_text']}")
|
| 139 |
+
print("\nEmail Copy:\n")
|
| 140 |
+
print(best["email_copy"])
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def save_rankings_csv(rankings: List[Dict[str, object]], output_path: Path) -> None:
|
| 144 |
+
"""Persist ranking output for later analysis."""
|
| 145 |
+
output_path.parent.mkdir(parents=True, exist_ok=True)
|
| 146 |
+
with output_path.open("w", newline="", encoding="utf-8") as handle:
|
| 147 |
+
writer = csv.DictWriter(
|
| 148 |
+
handle,
|
| 149 |
+
fieldnames=[
|
| 150 |
+
"rank",
|
| 151 |
+
"variant_name",
|
| 152 |
+
"brand_voice",
|
| 153 |
+
"ctr_proxy_score",
|
| 154 |
+
"validation_passed",
|
| 155 |
+
"passed_rules",
|
| 156 |
+
"generation_source",
|
| 157 |
+
"word_count",
|
| 158 |
+
"subject_line",
|
| 159 |
+
"preview_text",
|
| 160 |
+
],
|
| 161 |
+
)
|
| 162 |
+
writer.writeheader()
|
| 163 |
+
for rank, row in enumerate(rankings, start=1):
|
| 164 |
+
writer.writerow(
|
| 165 |
+
{
|
| 166 |
+
"rank": rank,
|
| 167 |
+
"variant_name": row["variant_name"],
|
| 168 |
+
"brand_voice": row["brand_voice"],
|
| 169 |
+
"ctr_proxy_score": row["ctr_proxy_score"],
|
| 170 |
+
"validation_passed": row["validation_passed"],
|
| 171 |
+
"passed_rules": row["passed_rules"],
|
| 172 |
+
"generation_source": row["generation_source"],
|
| 173 |
+
"word_count": row["word_count"],
|
| 174 |
+
"subject_line": row["subject_line"],
|
| 175 |
+
"preview_text": row["preview_text"],
|
| 176 |
+
}
|
| 177 |
+
)
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
def main() -> None:
|
| 181 |
+
parser = argparse.ArgumentParser(
|
| 182 |
+
description="Run a multi-step simulation and rank email campaign variants."
|
| 183 |
+
)
|
| 184 |
+
parser.add_argument("--brand-name", default="AIRPORT CLUB")
|
| 185 |
+
parser.add_argument(
|
| 186 |
+
"--target-audience",
|
| 187 |
+
default="fellow traveler",
|
| 188 |
+
)
|
| 189 |
+
parser.add_argument(
|
| 190 |
+
"--output-csv",
|
| 191 |
+
default="outputs/evals/email_variant_rankings.csv",
|
| 192 |
+
help="Path to save CSV ranking output",
|
| 193 |
+
)
|
| 194 |
+
parser.add_argument(
|
| 195 |
+
"--hf-model-id",
|
| 196 |
+
default=None,
|
| 197 |
+
help="Optional override for HF model id (e.g., deepseek-ai/DeepSeek-V3).",
|
| 198 |
+
)
|
| 199 |
+
parser.add_argument(
|
| 200 |
+
"--disable-llm",
|
| 201 |
+
action="store_true",
|
| 202 |
+
help="Disable HF generation and use deterministic template fallback.",
|
| 203 |
+
)
|
| 204 |
+
args = parser.parse_args()
|
| 205 |
+
|
| 206 |
+
if args.hf_model_id:
|
| 207 |
+
os.environ["HF_MODEL_ID"] = args.hf_model_id
|
| 208 |
+
if args.disable_llm:
|
| 209 |
+
os.environ["USE_HF_LLM"] = "false"
|
| 210 |
+
|
| 211 |
+
rankings = run_simulation(
|
| 212 |
+
brand_name=args.brand_name,
|
| 213 |
+
target_audience=args.target_audience,
|
| 214 |
+
variants=default_variants(),
|
| 215 |
+
)
|
| 216 |
+
print_rankings(rankings)
|
| 217 |
+
save_rankings_csv(rankings, Path(args.output_csv))
|
| 218 |
+
print(f"\nSaved rankings to: {args.output_csv}")
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
if __name__ == "__main__":
|
| 222 |
+
main()
|