data-estate / generate.py
EMTIAZZ's picture
Refreshed synthetic data (new seed, company, id scheme, counts)
d385479 verified
Raw
History Blame Contribute Delete
15.5 kB
#!/usr/bin/env python3
"""
Generate a synthetic, LINKED "insurance data estate".
Everything ties back to the same customers / policies / claims, so you must
join + dedup + normalize across heterogeneous sources.
ALL personal data is FAKE (Faker). No real individuals. Safe to host publicly.
"""
import os, json, random, csv, io, textwrap
from datetime import date, timedelta
from faker import Faker
from fpdf import FPDF
from PIL import Image, ImageDraw, ImageFont, ImageFilter
SEED = 2026
random.seed(SEED)
fake = Faker()
Faker.seed(SEED)
# ---- branding / id scheme (different from the earlier version) ----
COMPANY = "Vantage Mutual"
DOMAIN = "vantage-mutual.example"
CUST_PREFIX = "CU"
POLICY_PREFIX = "PLC-"
CLAIM_PREFIX = "CLA-"
OUT = os.path.dirname(os.path.abspath(__file__))
def p(*a): return os.path.join(OUT, *a)
for d in ["structured", "documents/pdf", "documents/scans", "emails", "transcripts"]:
os.makedirs(p(*d.split("/")), exist_ok=True)
# ---- scale (representative SAMPLE; README says "design for millions") ----
N_CUST = 2400
N_POLICY = 3100
N_CLAIM = 3900
N_DOCS = 450 # subset of claims that also get a scanned form + PDF
N_EMAIL = 700 # email threads
N_CALL = 350 # call transcripts
LINES = ["auto", "home", "health", "life", "commercial"]
CLAIM_STATUS = ["open", "under_review", "approved", "denied", "paid", "closed"]
def msgid(): return f"<{fake.uuid4()}@{DOMAIN}>"
def phone(): return fake.numerify(random.choice(["(###) ###-####","###-###-####","+1##########","###.###.####"]))
def fake_ssn(): return fake.numerify("###-##-####") # synthetic, not a real SSN
def fake_policy_no(): return POLICY_PREFIX + fake.numerify("########")
def fake_claim_no(): return CLAIM_PREFIX + fake.numerify("#######")
# ============================================================
# 1) CUSTOMERS (CRM source) -- with injected PII + dup/noise
# ============================================================
customers = []
for i in range(N_CUST):
cid = f"{CUST_PREFIX}{500000+i}"
name = fake.name()
customers.append({
"customer_id": cid,
"full_name": name,
"email": fake.email(),
"phone": phone(),
"dob": fake.date_of_birth(minimum_age=18, maximum_age=88).isoformat(),
"ssn": fake_ssn(), # <-- PII (fake)
"street": fake.street_address(),
"city": fake.city(),
"state": fake.state_abbr(),
"zip": fake.postcode(),
"created_at": fake.date_between("-10y", "today").isoformat(),
})
real_cust_ids = [c["customer_id"] for c in customers] # the originals, before duplicates
# inject ~8% near-duplicate / dirty rows (re-entry, casing, whitespace, format drift)
dupes = []
for c in random.sample(customers, int(N_CUST*0.08)):
d = dict(c)
d["customer_id"] = f"{CUST_PREFIX}{990000+len(dupes)}" # different surrogate key, same person
mut = random.choice(["case","space","typo","phonefmt","emaildot"])
if mut == "case": d["full_name"] = d["full_name"].upper()
if mut == "space": d["full_name"] = " " + d["full_name"] + " "
if mut == "typo": d["full_name"] = d["full_name"].replace("a","@",1)
if mut == "phonefmt": d["phone"] = phone()
if mut == "emaildot": d["email"] = d["email"].replace("@",".dup@",1)
if random.random() < 0.3: d["ssn"] = "" # missing field
dupes.append(d)
customers += dupes
random.shuffle(customers)
# ============================================================
# 2) POLICIES + CLAIMS (ERP source) -- different schema/naming
# ============================================================
policies = []
for i in range(N_POLICY):
cust = random.choice(real_cust_ids)
start = fake.date_between("-10y", "-30d")
policies.append({
"PolicyNo": fake_policy_no(),
"CustomerID": cust, # links to CRM.customer_id
"LineOfBusiness": random.choice(LINES),
"Premium": round(random.uniform(180, 9500), 2),
"EffectiveDate": start.strftime("%m/%d/%Y"), # NOTE: different date format than CRM
"ExpiryDate": (start + timedelta(days=365)).strftime("%m/%d/%Y"),
"Status": random.choice(["active","lapsed","cancelled"]),
})
claims = []
for i in range(N_CLAIM):
pol = random.choice(policies)
fdate = fake.date_between("-5y", "today")
claims.append({
"claim_no": fake_claim_no(),
"policy_no": pol["PolicyNo"], # links to ERP.PolicyNo
"customer_id": pol["CustomerID"], # denormalized link to CRM
"line": pol["LineOfBusiness"],
"filed_date": fdate.isoformat(),
"amount_claimed": round(random.uniform(250, 75000), 2),
"status": random.choice(CLAIM_STATUS),
"description": fake.sentence(nb_words=12),
})
def write_csv(path, rows):
if not rows: return
with open(path, "w", newline="") as f:
w = csv.DictWriter(f, fieldnames=list(rows[0].keys())); w.writeheader(); w.writerows(rows)
write_csv(p("structured","crm_customers.csv"), customers)
write_csv(p("structured","erp_policies.csv"), policies)
write_csv(p("structured","claims.csv"), claims)
# ---- Postgres dump (two "source systems", inconsistent schemas) ----
def sql_val(v):
if v == "" or v is None: return "NULL"
return "'" + str(v).replace("'", "''") + "'"
with open(p("structured","postgres_dump.sql"), "w") as f:
f.write("-- Synthetic insurance estate (Postgres) -- all PII is FAKE\n")
f.write("-- All PII is FAKE (Faker). Two source systems with inconsistent schemas on purpose.\n\n")
f.write("DROP TABLE IF EXISTS crm_customers, erp_policies, claims CASCADE;\n\n")
f.write("""CREATE TABLE crm_customers (customer_id TEXT, full_name TEXT, email TEXT, phone TEXT,
dob TEXT, ssn TEXT, street TEXT, city TEXT, state TEXT, zip TEXT, created_at TEXT);\n""")
f.write("""CREATE TABLE erp_policies ("PolicyNo" TEXT, "CustomerID" TEXT, "LineOfBusiness" TEXT,
"Premium" NUMERIC, "EffectiveDate" TEXT, "ExpiryDate" TEXT, "Status" TEXT);\n""")
f.write("""CREATE TABLE claims (claim_no TEXT, policy_no TEXT, customer_id TEXT, line TEXT,
filed_date TEXT, amount_claimed NUMERIC, status TEXT, description TEXT);\n\n""")
for c in customers:
f.write("INSERT INTO crm_customers VALUES (" + ",".join(sql_val(c[k]) for k in c) + ");\n")
for pol in policies:
f.write("INSERT INTO erp_policies VALUES (" + ",".join(sql_val(pol[k]) for k in pol) + ");\n")
for cl in claims:
f.write("INSERT INTO claims VALUES (" + ",".join(sql_val(cl[k]) for k in cl) + ");\n")
# ============================================================
# 3) SCANNED CLAIM FORMS (images) + PDFs -- linked to claims
# ============================================================
def load_font(size):
for fp in ["/System/Library/Fonts/Supplemental/Arial.ttf",
"/Library/Fonts/Arial.ttf",
"/System/Library/Fonts/Helvetica.ttc"]:
if os.path.exists(fp):
try: return ImageFont.truetype(fp, size)
except Exception: pass
return ImageFont.load_default()
def cust_by_id(cid):
for c in customers:
if c["customer_id"] == cid: return c
return None
doc_claims = random.sample(claims, N_DOCS)
doc_index = []
for cl in doc_claims:
cust = cust_by_id(cl["customer_id"]) or random.choice(customers)
fields = [
("Claim Number", cl["claim_no"]),
("Policy Number", cl["policy_no"]),
("Claimant Name", cust["full_name"].strip()),
("SSN", cust["ssn"] or "___-__-____"),
("Date of Loss", cl["filed_date"]),
("Line of Business", cl["line"].title()),
("Amount Claimed", f"${cl['amount_claimed']:,.2f}"),
("Phone", cust["phone"]),
("Address", f"{cust['street']}, {cust['city']}, {cust['state']} {cust['zip']}"),
("Description", cl["description"]),
]
# ---- PDF ----
pdf = FPDF(); pdf.add_page(); pdf.set_font("Helvetica", "B", 15)
pdf.multi_cell(0, 12, f"{COMPANY.upper()} - CLAIM FORM")
pdf.ln(2); pdf.set_font("Helvetica", "", 11)
for k, v in fields:
pdf.set_x(pdf.l_margin)
pdf.multi_cell(0, 8, f"{k}: {v}")
pdf.output(p("documents","pdf", f"{cl['claim_no']}.pdf"))
# ---- "scanned" image (rendered then degraded) ----
W, H = 1000, 1300
img = Image.new("RGB", (W, H), "white"); dr = ImageDraw.Draw(img)
title_f, label_f, val_f = load_font(34), load_font(22), load_font(22)
dr.rectangle([30,30,W-30,H-30], outline="black", width=2)
dr.text((60,55), f"{COMPANY.upper()} - CLAIM FORM", font=title_f, fill="black")
dr.line([(60,110),(W-60,110)], fill="black", width=2)
y = 150
for k, v in fields:
dr.text((70, y), f"{k}:", font=label_f, fill="black")
for j, line in enumerate(textwrap.wrap(str(v), 52)):
dr.text((330, y + j*26), line, font=val_f, fill=(20,20,40))
y += max(40, 26*len(textwrap.wrap(str(v),52)) + 14)
dr.text((70, H-110), "Signature: ", font=label_f, fill="black")
dr.line([(220,H-90),(560,H-90)], fill="black", width=2)
# scan degradation: grayscale, rotate, noise, blur, brightness
img = img.convert("L").rotate(random.uniform(-1.6,1.6), expand=False, fillcolor=255)
px = img.load()
for _ in range(int(W*H*0.012)):
x_, y_ = random.randint(0,W-1), random.randint(0,H-1)
px[x_,y_] = random.randint(0,90) if random.random()<0.5 else random.randint(200,255)
img = img.filter(ImageFilter.GaussianBlur(0.5))
img.save(p("documents","scans", f"{cl['claim_no']}.png"), optimize=True)
doc_index.append({"claim_no": cl["claim_no"], "policy_no": cl["policy_no"],
"customer_id": cl["customer_id"],
"pdf": f"documents/pdf/{cl['claim_no']}.pdf",
"scan": f"documents/scans/{cl['claim_no']}.png"})
# ============================================================
# 4) SUPPORT EMAIL THREADS -- reference real policy/claim ids
# ============================================================
TOPICS = ["claim status update", "premium payment question", "policy renewal",
"document request", "address change", "complaint about delay", "coverage inquiry"]
email_rows = []
for i in range(N_EMAIL):
cl = random.choice(claims); cust = cust_by_id(cl["customer_id"]) or random.choice(customers)
topic = random.choice(TOPICS); subj = f"{topic.title()} - {cl['claim_no']}"
turns = random.randint(1,4); thread = []
body_intro = f"Hi, I'm writing about my {cl['line']} claim {cl['claim_no']} on policy {cl['policy_no']}. "
cust_sig = f"\n\nThanks,\n{cust['full_name'].strip()}\n{cust['email']} | {cust['phone']}" # PII in signature
for t in range(turns):
frm = (cust["email"] if t % 2 == 0 else f"support@{DOMAIN}")
body = (body_intro + fake.paragraph(nb_sentences=3) + cust_sig) if t == 0 else \
(("Thank you for reaching out regarding " + topic + ". " + fake.paragraph(nb_sentences=3) +
f"\n\n{COMPANY} Support") if frm.startswith("support") else
(fake.paragraph(nb_sentences=2) + cust_sig))
thread.append({"from": frm, "to": (f"support@{DOMAIN}" if frm==cust["email"] else cust["email"]),
"date": fake.date_time_between("-2y","now").isoformat(),
"subject": ("Re: "+subj if t>0 else subj), "message_id": msgid(), "body": body})
# write .eml-ish text with quoted history (messy)
lines = []
for t in reversed(thread):
lines += [f"From: {t['from']}", f"To: {t['to']}", f"Date: {t['date']}",
f"Subject: {t['subject']}", f"Message-ID: {t['message_id']}", "", t["body"], "",
"-"*60, "> quoted earlier message" if t is not thread[0] else "", ""]
with open(p("emails", f"thread_{i:04d}.txt"), "w") as f:
f.write("\n".join(lines))
email_rows.append({"thread_id": f"thread_{i:04d}", "claim_no": cl["claim_no"],
"customer_id": cl["customer_id"], "subject": subj, "turns": turns,
"file": f"emails/thread_{i:04d}.txt"})
# ============================================================
# 5) CALL-CENTER TRANSCRIPTS -- reference same claims
# ============================================================
DISFL = ["um,", "uh,", "you know,", "like,", "I mean,"]
call_rows = []
for i in range(N_CALL):
cl = random.choice(claims); cust = cust_by_id(cl["customer_id"]) or random.choice(customers)
convo = []
convo.append(("AGENT", f"Thank you for calling {COMPANY}, this is {fake.first_name()}. May I have your name?"))
convo.append(("CUSTOMER", f"{random.choice(DISFL)} yeah this is {cust['full_name'].strip()}."))
convo.append(("AGENT", "Thank you. Can you verify your phone number and date of birth?"))
convo.append(("CUSTOMER", f"Sure, it's {cust['phone']}, born {cust['dob']}.")) # PII in transcript
convo.append(("CUSTOMER", f"I'm calling about claim {cl['claim_no']} on my {cl['line']} policy {cl['policy_no']}."))
for _ in range(random.randint(3,7)):
spk = random.choice(["AGENT","CUSTOMER"])
line = (random.choice(DISFL)+" " if spk=="CUSTOMER" and random.random()<0.5 else "") + fake.sentence(nb_words=12)
convo.append((spk, line))
convo.append(("AGENT", f"Your claim is currently '{cl['status']}'. Is there anything else?"))
convo.append(("CUSTOMER", "No that's all, thanks."))
with open(p("transcripts", f"call_{i:04d}.txt"), "w") as f:
f.write(f"# Call {i:04d} | claim {cl['claim_no']} | customer {cl['customer_id']}\n\n")
f.write("\n".join(f"{s}: {t}" for s,t in convo))
call_rows.append({"call_id": f"call_{i:04d}", "claim_no": cl["claim_no"],
"customer_id": cl["customer_id"], "turns": len(convo),
"file": f"transcripts/call_{i:04d}.txt"})
# ============================================================
# MANIFEST
# ============================================================
manifest = {
"dataset": "data-estate",
"purpose": "Synthetic, LINKED insurance data estate for data-pipeline / RAG / fine-tuning exercises.",
"all_pii_is_fake": True,
"linkage_keys": ["customer_id <-> CustomerID", "policy_no <-> PolicyNo", "claim_no"],
"deliberate_quality_issues": ["near-duplicate customer rows", "inconsistent date formats across sources",
"inconsistent column naming (CRM vs ERP)", "missing fields",
"PII embedded in free text (emails, transcripts, forms)"],
"counts": {"customers_rows": len(customers), "policies": len(policies), "claims": len(claims),
"scanned_forms": len(doc_index), "email_threads": len(email_rows), "call_transcripts": len(call_rows)},
"structured": ["structured/crm_customers.csv","structured/erp_policies.csv","structured/claims.csv","structured/postgres_dump.sql"],
"documents_index": doc_index[:5] + ["...(see documents/)"],
"emails_index_file": "emails_index.json",
"calls_index_file": "calls_index.json",
}
json.dump(manifest, open(p("MANIFEST.json"),"w"), indent=2)
json.dump(email_rows, open(p("emails_index.json"),"w"), indent=2)
json.dump(call_rows, open(p("calls_index.json"),"w"), indent=2)
json.dump(doc_index, open(p("documents_index.json"),"w"), indent=2)
print("DONE:", json.dumps(manifest["counts"], indent=2))