py242 lines12.2 KB
| 1 | """Builds the demo dashboard data set and runs it through the real classifier and portfolio code.""" |
| 2 | import argparse |
| 3 | import csv |
| 4 | import json |
| 5 | import os |
| 6 | import random |
| 7 | import sys |
| 8 | import tempfile |
| 9 | from collections import Counter |
| 10 | from pathlib import Path |
| 11 | |
| 12 | ROOT = Path(__file__).resolve().parent.parent |
| 13 | sys.path.insert(0, str(ROOT)) |
| 14 | |
| 15 | from leads.classify import LEAD_TIERS, classify, group_key, norm_display # noqa: E402 |
| 16 | from leads.feed_guard import assert_produced # noqa: E402 |
| 17 | from leads.portfolio import build_portfolios # noqa: E402 |
| 18 | |
| 19 | TOWNS = [("ASH", "Ashgrove", 9200), ("KES", "Kestrel Bay", 7400), ("HAL", "Port Halvard", 6800), |
| 20 | ("LIN", "Linden Ridge", 4900), ("SEL", "Selby Crossing", 3300)] |
| 21 | TOWN_NAME = dict((c, n) for c, n, _ in TOWNS) |
| 22 | STREETS = ["Quarry", "Wren", "Harbor", "Mill", "Larkspur", "Copper", "Juniper", "Tallow", "Ferris", |
| 23 | "Beacon", "Orchard", "Granite", "Saltmarsh", "Heron", "Alder", "Cobalt", "Thornbury", |
| 24 | "Pellham", "Marlowe", "Ivy", "Station", "Bramble", "Linden", "Ridge"] |
| 25 | SUFFIX = ["St", "Ave", "Rd", "Ln", "Way", "Ct", "Blvd", "Dr"] |
| 26 | FIRST = ["Dana", "Rafael", "Imogen", "Teodor", "Priya", "Callum", "Marisol", "Bennett", "Yusra", |
| 27 | "Odette", "Lorne", "Saoirse", "Emeka", "Henrietta", "Anders", "Celeste", "Desmond", |
| 28 | "Noor", "Ingrid", "Tobias", "Mirela", "Hollis", "Annika", "Rowan", "Leocadia", "Ezra"] |
| 29 | LAST = ["Whitcombe", "Okafor-Lind", "Varga", "Pellworth", "Ostrander", "Quillon", "Harrowgate", |
| 30 | "Brannagh", "Dellacroix", "Fennimore", "Kaplow", "Ivanko", "Selwyn", "Marchetti", |
| 31 | "Tolliver", "Abernathy-Cole", "Strand", "Voss", "Lindqvist", "Corrigan", "Nakashima", |
| 32 | "Ellery", "Bartok", "Ravenhill", "Mendelsohn", "Ashdown", "Galloway", "Pruett"] |
| 33 | |
| 34 | # Conglomerates: name, properties, kind of holding, spelling variants seen in the rolls. |
| 35 | CONGLOMERATES = [ |
| 36 | ("Halvard Harbor Holdings LLC", 184, "apartment", ["HALVARD HARBOR HOLDINGS, L.L.C.", "HALVARD HARBOR HOLDINGS LLC."]), |
| 37 | ("Northgate Residential Partners LP", 151, "house", ["NORTHGATE RESIDENTIAL PARTNERS, LP"]), |
| 38 | ("Copperline Realty Group Inc", 127, "commercial", ["COPPERLINE REALTY GROUP, INC."]), |
| 39 | ("Bramblewood Apartments LLC", 98, "apartment", []), |
| 40 | ("Meadowlark Rental Group LLC", 91, "house", ["MEADOWLARK RENTAL GROUP L.L.C."]), |
| 41 | ("Ironvale Capital Partners LP", 77, "commercial", []), |
| 42 | ("Kestrel Bay Properties LLC", 64, "house", ["KESTREL BAY PROPERTIES, LLC"]), |
| 43 | ("Larkspur Commercial Ventures LLC", 58, "commercial", []), |
| 44 | ("Silverbirch Homes Inc", 52, "house", ["SILVERBIRCH HOMES, INC"]), |
| 45 | ("Quarry Street Investments LLC", 47, "house", []), |
| 46 | ("Cobalt Ridge Holdings LLC", 43, "apartment", []), |
| 47 | ("Granite Pier Logistics LLC", 39, "industrial", []), |
| 48 | ("Wrenfield Management Co", 36, "apartment", []), |
| 49 | ("Fennimore Estates LLC", 33, "house", []), |
| 50 | ("Blue Heron Self Storage LLC", 29, "commercial", []), |
| 51 | ("Riverstone Hospitality Group LLC", 26, "commercial", []), |
| 52 | ("Tallow Creek Builders Inc", 24, "land", []), |
| 53 | ("Corvid Industrial Park LLC", 22, "industrial", []), |
| 54 | ("Juniper Court Apartments LLC", 19, "apartment", []), |
| 55 | ("Westlake Plaza Associates LP", 17, "commercial", []), |
| 56 | ("Bramble Roofing LLC", 14, "commercial", []), |
| 57 | ("Marlowe Auto Group Inc", 13, "commercial", []), |
| 58 | ("Ostrander & Sons", 12, "house", []), |
| 59 | ("Brightwater Senior Living LLC", 11, "apartment", []), |
| 60 | ("Harrow Lane Properties LLC", 10, "house", []), |
| 61 | ("Vantorre Plumbing & Heating Inc", 9, "commercial", []), |
| 62 | ] |
| 63 | INSTITUTIONS = [("City of Ashgrove", 410), ("Kestrel Bay School Board", 96), |
| 64 | ("Port Halvard Housing Authority", 230), ("County of Linden", 120), |
| 65 | ("First Church of Ashgrove", 14), ("Linden Ridge Homeowners Association", 38), |
| 66 | ("Halvard Electric and Power Company", 61), ("Northgate Railway", 44), |
| 67 | ("Selby Crossing Water Authority", 27)] |
| 68 | VALUE = {"house": (140_000, 420_000), "apartment": (900_000, 7_800_000), |
| 69 | "commercial": (450_000, 4_200_000), "industrial": (700_000, 5_500_000), |
| 70 | "land": (40_000, 260_000)} |
| 71 | BIZ_A = ["Acorn", "Basalt", "Cedar", "Driftwood", "Ember", "Fairlane", "Gull", "Hearth", "Indigo", |
| 72 | "Jasper", "Keel", "Lantern", "Marigold", "Nettle", "Oriel", "Pinnacle", "Quail", "Rook", |
| 73 | "Sable", "Teal", "Umber", "Vesper", "Willow", "Yarrow", "Zephyr"] |
| 74 | BIZ_B = ["Point", "Hollow", "Crest", "Landing", "Square", "Commons", "Gate", "Yard", "Row", "Wharf"] |
| 75 | BIZ_C = ["LLC", "LLC", "LLC", "Properties LLC", "Holdings LLC", "Inc", "Realty LLC", "Investments LLC", |
| 76 | "Group LLC", "Rentals LLC"] |
| 77 | TITLES = {"Limited Liability Company": ["Managing Member", "Manager", "Member"], |
| 78 | "Corporation": ["President", "Secretary", "Treasurer"], |
| 79 | "Limited Partnership": ["General Partner", "Manager of General Partner", "Limited Partner"]} |
| 80 | PROFILE_COUNT = 12 |
| 81 | |
| 82 | |
| 83 | def address(rng): |
| 84 | return f"{rng.randint(10, 9899)} {rng.choice(STREETS)} {rng.choice(SUFFIX)}" |
| 85 | |
| 86 | |
| 87 | def person(rng): |
| 88 | return f"{rng.choice(FIRST)} {rng.choice(LAST)}" |
| 89 | |
| 90 | |
| 91 | def make_parcels(rng): |
| 92 | parcels, next_id = [], Counter() |
| 93 | |
| 94 | def add(town, owner, kind, mail_town): |
| 95 | next_id[town] += 1 |
| 96 | lo, hi = VALUE[kind] |
| 97 | parcels.append({ |
| 98 | "city": town, "parcel_id": f"{town[0]}{next_id[town] + 10000:05d}", |
| 99 | "owner_name": owner, "situs": address(rng), "use": kind, |
| 100 | "total_value": str(round(rng.uniform(lo, hi), -3)), |
| 101 | "mailing_address": address(rng), "mailing_city": TOWN_NAME[mail_town], |
| 102 | "mailing_state": "", "mailing_zip": ""}) |
| 103 | |
| 104 | codes = [c for c, _, _ in TOWNS] |
| 105 | for name, count, kind, variants in CONGLOMERATES: |
| 106 | home = rng.choice(codes) |
| 107 | towns = rng.sample(codes, rng.randint(2, 5) if count > 15 else rng.randint(1, 2)) |
| 108 | for i in range(count): |
| 109 | spelling = name.upper() |
| 110 | if variants and i % 7 == 3: |
| 111 | spelling = variants[i % len(variants)] |
| 112 | add(rng.choice(towns), spelling, kind, home) |
| 113 | for name, count in INSTITUTIONS: |
| 114 | for _ in range(count): |
| 115 | add(rng.choice(codes), name.upper(), "land", "ASH") |
| 116 | small = set() |
| 117 | while len(small) < 1880: |
| 118 | small.add(f"{rng.choice(BIZ_A)} {rng.choice(BIZ_B)} {rng.choice(BIZ_C)}".upper()) |
| 119 | for name in sorted(small): |
| 120 | for _ in range(rng.choice([1, 1, 1, 2, 2, 3])): |
| 121 | add(rng.choice(codes), name, rng.choice(["house", "commercial", "land"]), "KES") |
| 122 | total = sum(n for _, _, n in TOWNS) |
| 123 | while len(parcels) < total: |
| 124 | first, last = rng.choice(FIRST).upper(), rng.choice(LAST).upper() |
| 125 | roll = rng.random() |
| 126 | if roll < 0.06: |
| 127 | owner = f"{last} {first} {rng.choice('ABCDEJMR')} REVOCABLE TRUST" |
| 128 | elif roll < 0.30: |
| 129 | owner = f"{last} {first} {rng.choice('ABCDEJMR')} & {last} {rng.choice(FIRST).upper()}" |
| 130 | else: |
| 131 | owner = f"{last} {first} {rng.choice('ABCDEJMR')}" |
| 132 | add(rng.choice(codes), owner, "house", rng.choice(codes)) |
| 133 | rng.shuffle(parcels) |
| 134 | return parcels |
| 135 | |
| 136 | |
| 137 | def make_filings(rng, rows): |
| 138 | """Entity record and decision-makers for the top business portfolios.""" |
| 139 | profiles, people = {}, {} |
| 140 | leads = [r for r in rows if r["tier"] in ("BUSINESS", "TRADE")][:PROFILE_COUNT] |
| 141 | pool = [person(rng) for _ in range(40)] |
| 142 | for i, r in enumerate(leads): |
| 143 | eid = f"{rng.randint(1000000, 9899999)}" |
| 144 | base = f"https://example.org/registry/entity/{eid}" |
| 145 | form = "Limited Partnership" if r["name"].endswith(" LP") else ( |
| 146 | "Corporation" if r["name"].endswith((" INC", " CO")) else "Limited Liability Company") |
| 147 | officers = [] |
| 148 | for j in range(rng.choice([2, 2, 3])): |
| 149 | name = pool[(i * 2 + j) % len(pool)] if j else pool[i % 9] |
| 150 | officers.append({ |
| 151 | "name": name, |
| 152 | "title": TITLES[form][j], |
| 153 | "source": "Annual report" if j == 0 else "Officer filing", |
| 154 | "filed": f"2025-{rng.randint(1, 12):02d}-{rng.randint(1, 28):02d}", |
| 155 | "url": f"{base}/{'annual-report-2025' if j == 0 else 'officers'}"}) |
| 156 | people.setdefault(name, []).append(r["name"]) |
| 157 | profiles[r["_key"]] = { |
| 158 | "entity_id": eid, "entity_type": form, "status": "Active", |
| 159 | "formed": f"{rng.randint(1996, 2021)}-{rng.randint(1, 12):02d}-{rng.randint(1, 28):02d}", |
| 160 | "registered_agent": rng.choice(["Ledgerline Registered Agents Inc", |
| 161 | "Harborview Corporate Services LLC"]), |
| 162 | "principal_office": f"{address(rng)}, {rng.choice(list(TOWN_NAME.values()))}", |
| 163 | "record_url": base, "officers": officers} |
| 164 | # the same person filed on a sibling company: the link that ties LLCs into one conglomerate |
| 165 | for r in leads: |
| 166 | for o in profiles[r["_key"]]["officers"]: |
| 167 | o["also_on"] = [n for n in people[o["name"]] if n != r["name"]][:2] |
| 168 | return profiles |
| 169 | |
| 170 | |
| 171 | def main(argv=None): |
| 172 | ap = argparse.ArgumentParser(description=__doc__) |
| 173 | ap.add_argument("--workdir", type=Path, |
| 174 | default=Path(os.environ.get("TMPDIR", tempfile.gettempdir())) / "leads-demo") |
| 175 | ap.add_argument("--out", type=Path, default=ROOT / "docs" / "demo-site" / "data.json") |
| 176 | ap.add_argument("--seed", type=int, default=20261001) |
| 177 | args = ap.parse_args(argv) |
| 178 | rng = random.Random(args.seed) |
| 179 | |
| 180 | parcels = make_parcels(rng) |
| 181 | args.workdir.mkdir(parents=True, exist_ok=True) |
| 182 | roll = args.workdir / "parcels.csv" |
| 183 | with roll.open("w", newline="") as fh: |
| 184 | w = csv.DictWriter(fh, fieldnames=list(parcels[0])) |
| 185 | w.writeheader() |
| 186 | w.writerows(parcels) |
| 187 | assert_produced("parcels", [roll], min_rows=1000) |
| 188 | |
| 189 | order = [c for c, _, _ in TOWNS] |
| 190 | rows, trusts = build_portfolios(parcels, city_order=order) |
| 191 | tiers = Counter(r["tier"] for r in rows + trusts) |
| 192 | leads = [r for r in rows if r["tier"] in LEAD_TIERS] |
| 193 | filings = make_filings(rng, rows) |
| 194 | |
| 195 | by_owner = {} |
| 196 | for p in parcels: |
| 197 | key = group_key(norm_display(p["owner_name"]).upper()) |
| 198 | if key in filings: |
| 199 | by_owner.setdefault(key, []).append(p) |
| 200 | |
| 201 | def portfolio_json(r): |
| 202 | out = {k: r[k] for k in ("name", "tier", "total_parcels", "n_cities", "name_variants")} |
| 203 | out["value"] = int(r["total_assessed_value"] or 0) |
| 204 | out["cities"] = [[TOWN_NAME[c.split(":")[0]], int(c.split(":")[1])] |
| 205 | for c in r["cities"].split()] |
| 206 | out["id"] = r["_key"].lower().replace(" ", "-").replace("&", "and") |
| 207 | if r["_key"] in filings: |
| 208 | props = sorted(by_owner[r["_key"]], key=lambda p: -float(p["total_value"])) |
| 209 | out["filing"] = filings[r["_key"]] |
| 210 | out["properties"] = [{"parcel": p["parcel_id"], "address": p["situs"], |
| 211 | "town": TOWN_NAME[p["city"]], "use": p["use"], |
| 212 | "value": int(float(p["total_value"])), |
| 213 | "owner_as_recorded": p["owner_name"], |
| 214 | "url": f"https://example.org/assessor/" |
| 215 | f"{TOWN_NAME[p['city']].lower().replace(' ', '-')}" |
| 216 | f"/parcel/{p['parcel_id']}"} for p in props] |
| 217 | return out |
| 218 | |
| 219 | sample = [] |
| 220 | for p in parcels[:60]: |
| 221 | t = classify(group_key(norm_display(p["owner_name"]).upper())) |
| 222 | sample.append({"parcel": p["parcel_id"], "town": TOWN_NAME[p["city"]], |
| 223 | "address": p["situs"], "owner": p["owner_name"], "tier": t, |
| 224 | "value": int(float(p["total_value"]))}) |
| 225 | data = { |
| 226 | "towns": [{"code": c, "name": n, "parcels": sum(1 for p in parcels if p["city"] == c)} |
| 227 | for c, n, _ in TOWNS], |
| 228 | "funnel": {"parcels": len(parcels), "owners": len(rows) + len(trusts), |
| 229 | "leads": len(leads), "profiles": len(filings)}, |
| 230 | "tiers": dict(tiers), |
| 231 | "records": sample, |
| 232 | "portfolios": [portfolio_json(r) for r in leads[:120]], |
| 233 | } |
| 234 | args.out.write_text(json.dumps(data, separators=(",", ":")) + "\n") |
| 235 | print(f"parcels {len(parcels):,} owners {len(rows) + len(trusts):,} " |
| 236 | f"businesses {len(leads):,} profiles {len(filings)}") |
| 237 | print(f"tiers {dict(tiers)}") |
| 238 | print(f"wrote {args.out} ({args.out.stat().st_size:,} bytes); roll in {roll}") |
| 239 | |
| 240 | |
| 241 | if __name__ == "__main__": |
| 242 | main() |