BuckalewFinancial's picture
Add two-tab Gradio demo, synthetic samples, and session caps
2793505 verified
Raw History Blame Contribute Delete
11.6 kB
"""Generate synthetic small-business spreadsheets. No PII — no people, phones, or addresses."""
from __future__ import annotations
import csv
import random
from datetime import date, timedelta
from pathlib import Path
import pandas as pd
BUSINESS_DIR = Path(__file__).resolve().parents[1] / "data" / "business"
def _weekdays(start: date, days: int, allowed: set[int]) -> list[date]:
out: list[date] = []
cur = start
while len(out) < days:
if cur.weekday() in allowed:
out.append(cur)
cur += timedelta(days=1)
return out
def generate_hvac_rows(seed: int = 2026) -> list[dict[str, str]]:
"""Hourly call-center style log for a fictional HVAC shop."""
rng = random.Random(seed)
# 6 weeks of Mon–Sat starting 2026-09-07
days = _weekdays(date(2026, 9, 7), 36, allowed={0, 1, 2, 3, 4, 5})
techs_by_hour_base = {
7: 2, 8: 3, 9: 4, 10: 4, 11: 4, 12: 3,
13: 4, 14: 4, 15: 4, 16: 3, 17: 2, 18: 1,
}
job_types = [
("AC repair", 185, 95),
("maintenance", 129, 55),
("install consult", 0, 40),
("heating repair", 210, 100),
("filter / diagnostic", 89, 35),
]
rows: list[dict[str, str]] = []
call_n = 1000
for d in days:
weekendish = d.weekday() == 5
for hour, techs in techs_by_hour_base.items():
# Missed calls spike at lunch and late afternoon
miss_p = 0.08
if hour == 12:
miss_p = 0.28
elif hour >= 17:
miss_p = 0.32
elif hour == 7:
miss_p = 0.18
demand = 2 + (1 if 9 <= hour <= 11 or 15 <= hour <= 16 else 0)
if weekendish and hour >= 14:
demand = max(1, demand - 1)
n_calls = max(0, int(rng.gauss(demand + (0.4 if not weekendish else 0), 1.1)))
n_calls = min(n_calls, 8)
for _ in range(n_calls):
call_n += 1
missed = rng.random() < miss_p
job_type, base_rev, minutes = rng.choice(job_types)
emergency = hour >= 17 and rng.random() < 0.25
if missed:
status = "missed"
revenue = 0
duration = 0
tech = ""
completed = "no"
else:
completed = "yes" if rng.random() > 0.12 else "no"
if completed == "no":
status = "answered_no_job"
revenue = 0
duration = int(rng.uniform(8, 20))
else:
status = "job_completed"
jitter = rng.uniform(0.85, 1.2)
revenue = 0 if base_rev == 0 else round(base_rev * jitter + (75 if emergency else 0), 2)
duration = int(minutes * rng.uniform(0.8, 1.35))
tech = rng.choice(["Tech A", "Tech B", "Tech C", "Tech D"][: max(2, techs)])
rows.append(
{
"call_id": f"CL-{call_n}",
"date": d.isoformat(),
"weekday": d.strftime("%A"),
"hour": str(hour),
"channel": rng.choice(["phone", "phone", "phone", "web form"]),
"job_type": job_type,
"emergency": "yes" if emergency and not missed else "no",
"status": status,
"answered": "no" if missed else "yes",
"job_completed": completed if not missed else "no",
"technician": tech,
"duration_minutes": str(duration),
"revenue_usd": f"{float(revenue):.2f}",
"service_area": rng.choice(
["Tampa", "Brandon", "Valrico", "Riverview", "Plant City"]
),
}
)
return rows
def generate_salon_rows(seed: int = 2026) -> list[dict[str, str]]:
"""Appointment book for a fictional salon. Stylists are labels only, not real people."""
rng = random.Random(seed)
days = _weekdays(date(2026, 8, 4), 48, allowed={1, 2, 3, 4, 5}) # Tue–Sat, 8 weeks
stylists = {
"Stylist A": ["cut", "blowout", "treatment"],
"Stylist B": ["cut", "color", "highlights"],
"Stylist C": ["color", "highlights", "treatment"],
"Stylist D": ["cut", "blowout"],
}
prices = {"cut": 55, "color": 130, "highlights": 165, "blowout": 40, "treatment": 75}
minutes = {"cut": 45, "color": 110, "highlights": 140, "blowout": 30, "treatment": 50}
rows: list[dict[str, str]] = []
appt_n = 2000
for d in days:
saturday = d.weekday() == 5
hours = range(9, 18)
for stylist, services in stylists.items():
n = rng.randint(5, 8) if saturday else rng.randint(4, 7)
used_hours: list[int] = []
for i in range(n):
appt_n += 1
service = rng.choice(services)
hour = rng.choice(list(hours))
used_hours.append(hour)
# No-shows a bit higher first appointment slots and Saturdays
no_show_p = 0.07
if hour == 9:
no_show_p += 0.05
if saturday:
no_show_p += 0.03
cancel_p = 0.06
roll = rng.random()
if roll < no_show_p:
status = "no-show"
elif roll < no_show_p + cancel_p:
status = "cancelled"
else:
status = "completed"
price = prices[service]
addon = 0
if status == "completed" and rng.random() < 0.2:
addon = rng.choice([15, 20, 25])
revenue = (price + addon) if status == "completed" else 0
rows.append(
{
"appointment_id": f"SA-{appt_n}",
"date": d.isoformat(),
"weekday": d.strftime("%A"),
"hour": str(hour),
"stylist": stylist,
"service": service,
"status": status,
"duration_minutes": str(minutes[service]),
"service_price_usd": f"{price:.2f}",
"addon_usd": f"{addon:.2f}" if status == "completed" else "0.00",
"revenue_usd": f"{float(revenue):.2f}",
}
)
rows.sort(key=lambda r: (r["date"], r["hour"], r["stylist"]))
return rows
def generate_dental_rows(seed: int = 2026) -> list[dict[str, str]]:
"""Appointment log for a fictional two-provider dental office. No patient names."""
rng = random.Random(seed)
days = _weekdays(date(2026, 8, 3), 40, allowed={0, 1, 2, 3, 4}) # Mon–Fri, 8 weeks
providers = {
"Provider A": ["exam", "filling", "crown", "consult"],
"Provider B": ["exam", "filling", "consult"],
"Hygienist 1": ["cleaning", "cleaning", "exam"],
"Hygienist 2": ["cleaning"],
}
prices = {"cleaning": 145, "exam": 95, "filling": 280, "crown": 1100, "consult": 0}
minutes = {"cleaning": 50, "exam": 30, "filling": 60, "crown": 90, "consult": 25}
rows: list[dict[str, str]] = []
appt_n = 3000
for d in days:
monday = d.weekday() == 0
friday = d.weekday() == 4
for provider, types in providers.items():
n = rng.randint(6, 9) if provider.startswith("Hygienist") else rng.randint(5, 8)
for _ in range(n):
appt_n += 1
kind = rng.choice(types)
hour = rng.choice([8, 9, 10, 11, 13, 14, 15, 16])
no_show_p = 0.06
if monday and hour <= 9:
no_show_p = 0.16
if friday and hour >= 15:
no_show_p = 0.14
late_cancel_p = 0.05
roll = rng.random()
if roll < no_show_p:
status = "no-show"
elif roll < no_show_p + late_cancel_p:
status = "late cancel"
elif roll < no_show_p + late_cancel_p + 0.05:
status = "cancelled"
else:
status = "completed"
billed = prices[kind] if status == "completed" else 0
# Same-day fill-ins sometimes recover a cancelled slot
filled_in = "no"
if status in {"cancelled", "late cancel"} and rng.random() < 0.25:
filled_in = "yes"
billed = prices[kind]
status = "completed_fill_in"
rows.append(
{
"appointment_id": f"DA-{appt_n}",
"date": d.isoformat(),
"weekday": d.strftime("%A"),
"hour": str(hour),
"provider": provider,
"appointment_type": kind,
"status": status,
"same_day_fill_in": filled_in,
"duration_minutes": str(minutes[kind]),
"billed_usd": f"{float(billed):.2f}",
"chair": rng.choice(["Chair 1", "Chair 2", "Chair 3"]),
}
)
rows.sort(key=lambda r: (r["date"], r["hour"], r["provider"]))
return rows
SAMPLES = {
"hvac": {
"stem": "hvac_service_calls",
"format": "csv",
"title": "Bay Breeze HVAC (synthetic) — service calls and missed calls",
"generator": generate_hvac_rows,
},
"salon": {
"stem": "salon_bookings_revenue",
"format": "xlsx",
"title": "Palm & Pine Salon (synthetic) — bookings and revenue",
"generator": generate_salon_rows,
},
"dental": {
"stem": "dental_appointments",
"format": "csv",
"title": "Oak Street Family Dental (synthetic) — appointments and no-shows",
"generator": generate_dental_rows,
},
}
def write_samples(directory: Path = BUSINESS_DIR) -> dict[str, Path]:
directory.mkdir(parents=True, exist_ok=True)
written: dict[str, Path] = {}
for key, meta in SAMPLES.items():
rows = meta["generator"]()
if not rows:
raise RuntimeError(f"No rows generated for {key}")
fieldnames = list(rows[0].keys())
if meta["format"] == "xlsx":
path = directory / f"{meta['stem']}.xlsx"
pd.DataFrame(rows).to_excel(path, index=False, sheet_name="bookings")
else:
path = directory / f"{meta['stem']}.csv"
with path.open("w", newline="", encoding="utf-8") as fh:
writer = csv.DictWriter(fh, fieldnames=fieldnames)
writer.writeheader()
writer.writerows(rows)
written[key] = path
return written
def main() -> None:
written = write_samples()
for key, path in written.items():
if path.suffix.lower() == ".xlsx":
n = len(pd.read_excel(path))
else:
n = sum(1 for _ in path.open(encoding="utf-8")) - 1
print(f"{key}: {n} rows -> {path}")
if __name__ == "__main__":
main()