"""Builds the demo dashboard data set and runs it through the real classifier and portfolio code.""" import argparse import csv import json import os import random import sys import tempfile from collections import Counter from pathlib import Path ROOT = Path(__file__).resolve().parent.parent sys.path.insert(0, str(ROOT)) from leads.classify import LEAD_TIERS, classify, group_key, norm_display # noqa: E402 from leads.feed_guard import assert_produced # noqa: E402 from leads.portfolio import build_portfolios # noqa: E402 TOWNS = [("ASH", "Ashgrove", 9200), ("KES", "Kestrel Bay", 7400), ("HAL", "Port Halvard", 6800), ("LIN", "Linden Ridge", 4900), ("SEL", "Selby Crossing", 3300)] TOWN_NAME = dict((c, n) for c, n, _ in TOWNS) STREETS = ["Quarry", "Wren", "Harbor", "Mill", "Larkspur", "Copper", "Juniper", "Tallow", "Ferris", "Beacon", "Orchard", "Granite", "Saltmarsh", "Heron", "Alder", "Cobalt", "Thornbury", "Pellham", "Marlowe", "Ivy", "Station", "Bramble", "Linden", "Ridge"] SUFFIX = ["St", "Ave", "Rd", "Ln", "Way", "Ct", "Blvd", "Dr"] FIRST = ["Dana", "Rafael", "Imogen", "Teodor", "Priya", "Callum", "Marisol", "Bennett", "Yusra", "Odette", "Lorne", "Saoirse", "Emeka", "Henrietta", "Anders", "Celeste", "Desmond", "Noor", "Ingrid", "Tobias", "Mirela", "Hollis", "Annika", "Rowan", "Leocadia", "Ezra"] LAST = ["Whitcombe", "Okafor-Lind", "Varga", "Pellworth", "Ostrander", "Quillon", "Harrowgate", "Brannagh", "Dellacroix", "Fennimore", "Kaplow", "Ivanko", "Selwyn", "Marchetti", "Tolliver", "Abernathy-Cole", "Strand", "Voss", "Lindqvist", "Corrigan", "Nakashima", "Ellery", "Bartok", "Ravenhill", "Mendelsohn", "Ashdown", "Galloway", "Pruett"] # Conglomerates: name, properties, kind of holding, spelling variants seen in the rolls. CONGLOMERATES = [ ("Halvard Harbor Holdings LLC", 184, "apartment", ["HALVARD HARBOR HOLDINGS, L.L.C.", "HALVARD HARBOR HOLDINGS LLC."]), ("Northgate Residential Partners LP", 151, "house", ["NORTHGATE RESIDENTIAL PARTNERS, LP"]), ("Copperline Realty Group Inc", 127, "commercial", ["COPPERLINE REALTY GROUP, INC."]), ("Bramblewood Apartments LLC", 98, "apartment", []), ("Meadowlark Rental Group LLC", 91, "house", ["MEADOWLARK RENTAL GROUP L.L.C."]), ("Ironvale Capital Partners LP", 77, "commercial", []), ("Kestrel Bay Properties LLC", 64, "house", ["KESTREL BAY PROPERTIES, LLC"]), ("Larkspur Commercial Ventures LLC", 58, "commercial", []), ("Silverbirch Homes Inc", 52, "house", ["SILVERBIRCH HOMES, INC"]), ("Quarry Street Investments LLC", 47, "house", []), ("Cobalt Ridge Holdings LLC", 43, "apartment", []), ("Granite Pier Logistics LLC", 39, "industrial", []), ("Wrenfield Management Co", 36, "apartment", []), ("Fennimore Estates LLC", 33, "house", []), ("Blue Heron Self Storage LLC", 29, "commercial", []), ("Riverstone Hospitality Group LLC", 26, "commercial", []), ("Tallow Creek Builders Inc", 24, "land", []), ("Corvid Industrial Park LLC", 22, "industrial", []), ("Juniper Court Apartments LLC", 19, "apartment", []), ("Westlake Plaza Associates LP", 17, "commercial", []), ("Bramble Roofing LLC", 14, "commercial", []), ("Marlowe Auto Group Inc", 13, "commercial", []), ("Ostrander & Sons", 12, "house", []), ("Brightwater Senior Living LLC", 11, "apartment", []), ("Harrow Lane Properties LLC", 10, "house", []), ("Vantorre Plumbing & Heating Inc", 9, "commercial", []), ] INSTITUTIONS = [("City of Ashgrove", 410), ("Kestrel Bay School Board", 96), ("Port Halvard Housing Authority", 230), ("County of Linden", 120), ("First Church of Ashgrove", 14), ("Linden Ridge Homeowners Association", 38), ("Halvard Electric and Power Company", 61), ("Northgate Railway", 44), ("Selby Crossing Water Authority", 27)] VALUE = {"house": (140_000, 420_000), "apartment": (900_000, 7_800_000), "commercial": (450_000, 4_200_000), "industrial": (700_000, 5_500_000), "land": (40_000, 260_000)} BIZ_A = ["Acorn", "Basalt", "Cedar", "Driftwood", "Ember", "Fairlane", "Gull", "Hearth", "Indigo", "Jasper", "Keel", "Lantern", "Marigold", "Nettle", "Oriel", "Pinnacle", "Quail", "Rook", "Sable", "Teal", "Umber", "Vesper", "Willow", "Yarrow", "Zephyr"] BIZ_B = ["Point", "Hollow", "Crest", "Landing", "Square", "Commons", "Gate", "Yard", "Row", "Wharf"] BIZ_C = ["LLC", "LLC", "LLC", "Properties LLC", "Holdings LLC", "Inc", "Realty LLC", "Investments LLC", "Group LLC", "Rentals LLC"] TITLES = {"Limited Liability Company": ["Managing Member", "Manager", "Member"], "Corporation": ["President", "Secretary", "Treasurer"], "Limited Partnership": ["General Partner", "Manager of General Partner", "Limited Partner"]} PROFILE_COUNT = 12 def address(rng): return f"{rng.randint(10, 9899)} {rng.choice(STREETS)} {rng.choice(SUFFIX)}" def person(rng): return f"{rng.choice(FIRST)} {rng.choice(LAST)}" def make_parcels(rng): parcels, next_id = [], Counter() def add(town, owner, kind, mail_town): next_id[town] += 1 lo, hi = VALUE[kind] parcels.append({ "city": town, "parcel_id": f"{town[0]}{next_id[town] + 10000:05d}", "owner_name": owner, "situs": address(rng), "use": kind, "total_value": str(round(rng.uniform(lo, hi), -3)), "mailing_address": address(rng), "mailing_city": TOWN_NAME[mail_town], "mailing_state": "", "mailing_zip": ""}) codes = [c for c, _, _ in TOWNS] for name, count, kind, variants in CONGLOMERATES: home = rng.choice(codes) towns = rng.sample(codes, rng.randint(2, 5) if count > 15 else rng.randint(1, 2)) for i in range(count): spelling = name.upper() if variants and i % 7 == 3: spelling = variants[i % len(variants)] add(rng.choice(towns), spelling, kind, home) for name, count in INSTITUTIONS: for _ in range(count): add(rng.choice(codes), name.upper(), "land", "ASH") small = set() while len(small) < 1880: small.add(f"{rng.choice(BIZ_A)} {rng.choice(BIZ_B)} {rng.choice(BIZ_C)}".upper()) for name in sorted(small): for _ in range(rng.choice([1, 1, 1, 2, 2, 3])): add(rng.choice(codes), name, rng.choice(["house", "commercial", "land"]), "KES") total = sum(n for _, _, n in TOWNS) while len(parcels) < total: first, last = rng.choice(FIRST).upper(), rng.choice(LAST).upper() roll = rng.random() if roll < 0.06: owner = f"{last} {first} {rng.choice('ABCDEJMR')} REVOCABLE TRUST" elif roll < 0.30: owner = f"{last} {first} {rng.choice('ABCDEJMR')} & {last} {rng.choice(FIRST).upper()}" else: owner = f"{last} {first} {rng.choice('ABCDEJMR')}" add(rng.choice(codes), owner, "house", rng.choice(codes)) rng.shuffle(parcels) return parcels def make_filings(rng, rows): """Entity record and decision-makers for the top business portfolios.""" profiles, people = {}, {} leads = [r for r in rows if r["tier"] in ("BUSINESS", "TRADE")][:PROFILE_COUNT] pool = [person(rng) for _ in range(40)] for i, r in enumerate(leads): eid = f"{rng.randint(1000000, 9899999)}" base = f"https://example.org/registry/entity/{eid}" form = "Limited Partnership" if r["name"].endswith(" LP") else ( "Corporation" if r["name"].endswith((" INC", " CO")) else "Limited Liability Company") officers = [] for j in range(rng.choice([2, 2, 3])): name = pool[(i * 2 + j) % len(pool)] if j else pool[i % 9] officers.append({ "name": name, "title": TITLES[form][j], "source": "Annual report" if j == 0 else "Officer filing", "filed": f"2025-{rng.randint(1, 12):02d}-{rng.randint(1, 28):02d}", "url": f"{base}/{'annual-report-2025' if j == 0 else 'officers'}"}) people.setdefault(name, []).append(r["name"]) profiles[r["_key"]] = { "entity_id": eid, "entity_type": form, "status": "Active", "formed": f"{rng.randint(1996, 2021)}-{rng.randint(1, 12):02d}-{rng.randint(1, 28):02d}", "registered_agent": rng.choice(["Ledgerline Registered Agents Inc", "Harborview Corporate Services LLC"]), "principal_office": f"{address(rng)}, {rng.choice(list(TOWN_NAME.values()))}", "record_url": base, "officers": officers} # the same person filed on a sibling company: the link that ties LLCs into one conglomerate for r in leads: for o in profiles[r["_key"]]["officers"]: o["also_on"] = [n for n in people[o["name"]] if n != r["name"]][:2] return profiles def main(argv=None): ap = argparse.ArgumentParser(description=__doc__) ap.add_argument("--workdir", type=Path, default=Path(os.environ.get("TMPDIR", tempfile.gettempdir())) / "leads-demo") ap.add_argument("--out", type=Path, default=ROOT / "docs" / "demo-site" / "data.json") ap.add_argument("--seed", type=int, default=20261001) args = ap.parse_args(argv) rng = random.Random(args.seed) parcels = make_parcels(rng) args.workdir.mkdir(parents=True, exist_ok=True) roll = args.workdir / "parcels.csv" with roll.open("w", newline="") as fh: w = csv.DictWriter(fh, fieldnames=list(parcels[0])) w.writeheader() w.writerows(parcels) assert_produced("parcels", [roll], min_rows=1000) order = [c for c, _, _ in TOWNS] rows, trusts = build_portfolios(parcels, city_order=order) tiers = Counter(r["tier"] for r in rows + trusts) leads = [r for r in rows if r["tier"] in LEAD_TIERS] filings = make_filings(rng, rows) by_owner = {} for p in parcels: key = group_key(norm_display(p["owner_name"]).upper()) if key in filings: by_owner.setdefault(key, []).append(p) def portfolio_json(r): out = {k: r[k] for k in ("name", "tier", "total_parcels", "n_cities", "name_variants")} out["value"] = int(r["total_assessed_value"] or 0) out["cities"] = [[TOWN_NAME[c.split(":")[0]], int(c.split(":")[1])] for c in r["cities"].split()] out["id"] = r["_key"].lower().replace(" ", "-").replace("&", "and") if r["_key"] in filings: props = sorted(by_owner[r["_key"]], key=lambda p: -float(p["total_value"])) out["filing"] = filings[r["_key"]] out["properties"] = [{"parcel": p["parcel_id"], "address": p["situs"], "town": TOWN_NAME[p["city"]], "use": p["use"], "value": int(float(p["total_value"])), "owner_as_recorded": p["owner_name"], "url": f"https://example.org/assessor/" f"{TOWN_NAME[p['city']].lower().replace(' ', '-')}" f"/parcel/{p['parcel_id']}"} for p in props] return out sample = [] for p in parcels[:60]: t = classify(group_key(norm_display(p["owner_name"]).upper())) sample.append({"parcel": p["parcel_id"], "town": TOWN_NAME[p["city"]], "address": p["situs"], "owner": p["owner_name"], "tier": t, "value": int(float(p["total_value"]))}) data = { "towns": [{"code": c, "name": n, "parcels": sum(1 for p in parcels if p["city"] == c)} for c, n, _ in TOWNS], "funnel": {"parcels": len(parcels), "owners": len(rows) + len(trusts), "leads": len(leads), "profiles": len(filings)}, "tiers": dict(tiers), "records": sample, "portfolios": [portfolio_json(r) for r in leads[:120]], } args.out.write_text(json.dumps(data, separators=(",", ":")) + "\n") print(f"parcels {len(parcels):,} owners {len(rows) + len(trusts):,} " f"businesses {len(leads):,} profiles {len(filings)}") print(f"tiers {dict(tiers)}") print(f"wrote {args.out} ({args.out.stat().st_size:,} bytes); roll in {roll}") if __name__ == "__main__": main()