saulsolis09 commited on
Commit
fd61a5c
·
verified ·
1 Parent(s): 8adf896

Delete app_simple_ui.py

Browse files
Files changed (1) hide show
  1. app_simple_ui.py +0 -819
app_simple_ui.py DELETED
@@ -1,819 +0,0 @@
1
- """
2
- Subdivision Cluster / FIPS-Validation pipeline — Hugging Face Space (Gradio).
3
-
4
- Faithful port of the Colab notebook
5
- `LatestUndeterminedZipCityCensusTract70_Threshold_95_Clusters.ipynb`.
6
-
7
- Colab-specific I/O replaced:
8
- * Drive input folder -> file upload (multiple .xlsx/.xls)
9
- * google.colab.files -> Gradio file outputs (written to a temp dir)
10
- * Drive safety-list path -> get_safety_list_path() (repo file OR private dataset)
11
-
12
- All processing logic (FIPS validation, RawFile snapshot, RapidFuzz clustering,
13
- wide tables, majority-vote replacement, column reorder, OnlyBlanks warnings,
14
- chunked CSV export, self-test) matches the notebook.
15
- """
16
-
17
- import os
18
- import re
19
- import gc
20
- import math
21
- import time
22
- import tempfile
23
- import zipfile
24
- from pathlib import Path
25
- from collections import defaultdict
26
-
27
- import numpy as np
28
- import pandas as pd
29
- import gradio as gr
30
- from rapidfuzz import fuzz
31
-
32
-
33
- # =====================================================================
34
- # REFERENCE FILE LOADER (the Subdivision Program Safety List)
35
- # ---------------------------------------------------------------------
36
- # 1. A file committed in the Space repo (override name via SAFETY_LIST_FILE).
37
- # Use ONLY if the Space is PRIVATE.
38
- # 2. A private HF *dataset* repo, downloaded with the HF_TOKEN secret. Set:
39
- # SAFETY_LIST_REPO e.g. "your-username/subdivision-safety-list"
40
- # SAFETY_LIST_REPO_FILE filename inside that dataset (optional)
41
- # HF_TOKEN read token, stored as a Space Secret
42
- # =====================================================================
43
- DEFAULT_SAFETY_LIST_NAME = "Subdivision_Program_Safety_List.xlsx"
44
- EXCEL_ROW_LIMIT = 1_048_575 # matches the notebook
45
-
46
- # Fixed pipeline settings (notebook values). Not exposed in the UI on purpose:
47
- # users should not be able to deviate from the notebook's behavior.
48
- STRICT_BLANK_CITIES = True # blank cities that are not in the safety list
49
- CLUSTER_THRESHOLD = 95 # RapidFuzz similarity for LegalSubDivision clusters
50
- REPLACE_THRESHOLD = 70 # majority-vote % required to fill a blank
51
- FILTER_DOMINANT_COUNTY = False # process ALL counties (multi-county / full-state files)
52
-
53
-
54
- def get_safety_list_path() -> str:
55
- local_name = os.environ.get("SAFETY_LIST_FILE", DEFAULT_SAFETY_LIST_NAME)
56
- if Path(local_name).exists():
57
- return local_name
58
-
59
- repo_id = os.environ.get("SAFETY_LIST_REPO")
60
- token = os.environ.get("HF_TOKEN")
61
- if repo_id and token:
62
- from huggingface_hub import hf_hub_download
63
- filename = os.environ.get("SAFETY_LIST_REPO_FILE", local_name)
64
- return hf_hub_download(
65
- repo_id=repo_id, filename=filename, repo_type="dataset", token=token
66
- )
67
-
68
- raise FileNotFoundError(
69
- "Safety list not found.\n"
70
- f" - Commit '{local_name}' into this Space (keep the Space private), OR\n"
71
- " - Set SAFETY_LIST_REPO + HF_TOKEN to pull it from a private dataset."
72
- )
73
-
74
-
75
- _SAFETY_CACHE: dict | None = None
76
-
77
-
78
- def build_whitelist_from_path(path):
79
- """Parse a safety-list file (xlsx or csv) into {pairs, cities, rows}."""
80
- if str(path).lower().endswith(".csv"):
81
- safety_df = pd.read_csv(path)
82
- else:
83
- safety_df = pd.read_excel(path)
84
- acceptable_cols = [c for c in safety_df.columns if str(c).startswith("Acceptable FIPS")]
85
-
86
- valid_pairs, valid_cities = set(), set()
87
- for _, r in safety_df.iterrows():
88
- c = _norm_city(r["City Name"])
89
- if c is None:
90
- continue
91
- valid_cities.add(c)
92
- for col in acceptable_cols:
93
- f = _norm_fips(r[col])
94
- if f:
95
- valid_pairs.add(c + "||" + f)
96
-
97
- return {"pairs": valid_pairs, "cities": valid_cities, "rows": len(safety_df)}
98
-
99
-
100
- def load_whitelist():
101
- """Server-side safety list (repo file or private dataset). Cached per process."""
102
- global _SAFETY_CACHE
103
- if _SAFETY_CACHE is None:
104
- _SAFETY_CACHE = build_whitelist_from_path(get_safety_list_path())
105
- return _SAFETY_CACHE
106
-
107
-
108
- # =====================================================================
109
- # NORMALIZATION HELPERS (identical to the notebook)
110
- # =====================================================================
111
- PLACEHOLDERS = {"UNDETERMINED CITY", "UNDETERMINED ZIP", "NULL", "NAN", "NONE", ""}
112
-
113
-
114
- def _norm_city(x):
115
- if pd.isna(x):
116
- return None
117
- return str(x).strip().upper()
118
-
119
-
120
- def _norm_fips(x):
121
- """5-digit FIPS string, or None. Handles 28071, 28071.0, '01067', '28071 - LAFAYETTE'."""
122
- if pd.isna(x):
123
- return None
124
- m = re.search(r"\d+", str(x))
125
- return str(int(m.group(0))).zfill(5) if m else None
126
-
127
-
128
- # ---------------------------------------------------------------------
129
- # FIPS-COUNTY COLUMN DETECTION (by CONTENT, not header name)
130
- # ---------------------------------------------------------------------
131
- # The source header has changed before ("** REC FIPS-COUNTY" ->
132
- # "** REC FIPS-COUNTY NAME"), so we identify the column by what's IN it:
133
- # values shaped like "05045-FAULKNER" (FIPS digits, a dash, a county name).
134
- # Header names are only used as a last-resort fallback.
135
- FIPS_COUNTY_PATTERN = r"^\s*\d{1,5}\s*-\s*[A-Za-z]"
136
- FALLBACK_FIPS_HEADERS = ["** REC FIPS-COUNTY NAME", "** REC FIPS-COUNTY", "County"]
137
-
138
-
139
- def detect_fips_county_column(df, sample_size=1000, min_score=0.5):
140
- """Return (column_name, reason). Picks the column whose values best match
141
- the 'FIPS-COUNTYNAME' shape; falls back to known headers, then to any
142
- header mentioning FIPS."""
143
- best_col, best_score = None, 0.0
144
- for col in df.columns:
145
- s = df[col].dropna()
146
- if s.empty:
147
- continue
148
- sample = s.head(sample_size).astype(str)
149
- try:
150
- score = float(sample.str.match(FIPS_COUNTY_PATTERN).mean())
151
- except Exception:
152
- continue
153
- if score > best_score:
154
- best_col, best_score = col, score
155
-
156
- if best_col is not None and best_score >= min_score:
157
- return best_col, f"content match {best_score:.0%} of sampled rows"
158
-
159
- for name in FALLBACK_FIPS_HEADERS:
160
- if name in df.columns:
161
- return name, "fallback: known header name"
162
-
163
- for col in df.columns:
164
- if "FIPS" in str(col).upper():
165
- return col, "fallback: header mentions FIPS"
166
-
167
- return None, "not found"
168
-
169
-
170
- # =====================================================================
171
- # SELF-TEST (startup health check — same logic as the notebook's cell)
172
- # =====================================================================
173
- def run_self_test() -> str:
174
- path = get_safety_list_path()
175
- st = pd.read_excel(path)
176
- fc = [c for c in st.columns if str(c).startswith("Acceptable FIPS")]
177
- pairs = set()
178
- for _, r in st.iterrows():
179
- c = _norm_city(r["City Name"])
180
- if c is None:
181
- continue
182
- for col in fc:
183
- f = _norm_fips(r[col])
184
- if f:
185
- pairs.add(c + "||" + f)
186
-
187
- good_city = st.iloc[0]["City Name"]
188
- good_fips = st.iloc[0]["Acceptable FIPS 1"]
189
- test = pd.DataFrame({
190
- "DDPPropertyCityFinal": [good_city, good_city],
191
- "** REC FIPS-COUNTY": [good_fips, 99999], # row 2 = wrong FIPS on purpose
192
- })
193
- cn = test["DDPPropertyCityFinal"].map(_norm_city)
194
- fn = test["** REC FIPS-COUNTY"].map(_norm_fips)
195
- key = cn.fillna("") + "||" + fn.fillna("")
196
- ok = key.isin(pairs)
197
- assert bool(ok.iloc[0]) and not bool(ok.iloc[1]), \
198
- "SELF-TEST FAILED -- matching logic is not working as expected."
199
- return f"SELF-TEST PASSED: known-good ({good_city}) kept, wrong FIPS flagged."
200
-
201
-
202
- # =====================================================================
203
- # STEP 1 — FIPS SAFETY-LIST VALIDATION
204
- # =====================================================================
205
- def fips_validate(df: pd.DataFrame, blank_cities_not_in_list: bool, log, wl=None,
206
- fips_col=None):
207
- if wl is None:
208
- wl = load_whitelist()
209
- valid_pairs, valid_cities = wl["pairs"], wl["cities"]
210
-
211
- if fips_col is None:
212
- fips_col, _reason = detect_fips_county_column(df)
213
- if fips_col is None:
214
- raise ValueError(
215
- "Could not find a FIPS-county column. Expected values like "
216
- "'05045-FAULKNER' in one of the columns."
217
- )
218
- FIPS_COL = fips_col
219
- CITY_COL, ZIP_COL, TRACT_COL = (
220
- "DDPPropertyCityFinal", "DDPPropertyZIPFinal", "DDPRevisedCensusTract",
221
- )
222
-
223
- city_norm = df[CITY_COL].map(_norm_city)
224
- fips_norm = df[FIPS_COL].map(_norm_fips)
225
- row_key = city_norm.fillna("") + "||" + fips_norm.fillna("")
226
-
227
- is_real_city = df[CITY_COL].notna() & (~city_norm.fillna("").isin(PLACEHOLDERS))
228
- city_in_list = city_norm.isin(valid_cities)
229
- pair_ok = row_key.isin(valid_pairs)
230
-
231
- if blank_cities_not_in_list:
232
- fails_mask = is_real_city & (~pair_ok)
233
- else:
234
- fails_mask = is_real_city & city_in_list & (~pair_ok)
235
-
236
- n_real = int(is_real_city.sum())
237
- n_inlist = int((is_real_city & city_in_list).sum())
238
- n_valid = int((is_real_city & pair_ok).sum())
239
- n_fail = int(fails_mask.sum())
240
- log.append(
241
- f"FIPS validation — list: {wl['rows']:,} rows | {len(valid_cities):,} cities | "
242
- f"{len(valid_pairs):,} pairs"
243
- )
244
- log.append(
245
- f" real:{n_real:,} in-list:{n_inlist:,} valid-kept:{n_valid:,} blanked:{n_fail:,}"
246
- )
247
- if n_real > 0 and n_inlist == 0:
248
- log.append(" !! 0 cities matched the list — likely a format/spelling mismatch.")
249
-
250
- # Audit built BEFORE overwrite (insert position matches the notebook).
251
- key_col = "RecordKey" if "RecordKey" in df.columns else None
252
- base_cols = [c for c in [key_col, CITY_COL, FIPS_COL, ZIP_COL, TRACT_COL] if c]
253
- audit = df.loc[fails_mask, base_cols].copy()
254
- audit.insert(
255
- len(base_cols) if key_col is None else 2,
256
- "NormalizedFIPS", fips_norm[fails_mask].values,
257
- )
258
- audit["Reason"] = np.where(
259
- city_in_list[fails_mask].values, "FIPS does not match city", "City not in safety list"
260
- )
261
- audit = audit.rename(
262
- columns={CITY_COL: "OLD_City", ZIP_COL: "OLD_ZIP", TRACT_COL: "OLD_CensusTract"}
263
- )
264
-
265
- # Recent pandas reads all-numeric Excel columns as float64 and refuses to
266
- # accept a string into them; Colab's older pandas silently upcast to object.
267
- # Cast first so the placeholder write reproduces the notebook's result.
268
- df[CITY_COL] = df[CITY_COL].astype(object)
269
- df[ZIP_COL] = df[ZIP_COL].astype(object)
270
- df.loc[fails_mask, CITY_COL] = "UNDETERMINED CITY"
271
- df.loc[fails_mask, ZIP_COL] = "UNDETERMINED ZIP"
272
- df.loc[fails_mask, TRACT_COL] = np.nan
273
- return df, audit
274
-
275
-
276
- # =====================================================================
277
- # STEP 2 — RAPIDFUZZ CLUSTERING (identical to the notebook)
278
- # =====================================================================
279
- def group_similar_strings_optimized(strings, threshold=95, prefix_len=3, max_len_diff=3):
280
- cleaned, seen = [], set()
281
- for s in strings:
282
- if pd.isna(s):
283
- continue
284
- s = str(s).strip()
285
- if s and s not in seen:
286
- cleaned.append(s)
287
- seen.add(s)
288
-
289
- visited, groups = set(), []
290
- buckets = defaultdict(list)
291
- for s in cleaned:
292
- buckets[s.upper()[:prefix_len]].append(s)
293
-
294
- for bucket in buckets.values():
295
- for i, base in enumerate(bucket):
296
- if base in visited:
297
- continue
298
- group = [base]
299
- visited.add(base)
300
- base_upper = base.upper()
301
- base_len = len(base_upper)
302
- for j in range(i + 1, len(bucket)):
303
- compare = bucket[j]
304
- if compare in visited:
305
- continue
306
- comp_upper = compare.upper()
307
- if abs(base_len - len(comp_upper)) > max_len_diff:
308
- continue
309
- if fuzz.ratio(base_upper, comp_upper) >= threshold:
310
- group.append(compare)
311
- visited.add(compare)
312
- groups.append(group)
313
- return groups
314
-
315
-
316
- def build_clusters(city_df, zip_df, census_tracts_df, cluster_threshold):
317
- all_legal = pd.concat(
318
- [
319
- city_df[["County", "LegalSubDivision"]],
320
- zip_df[["County", "LegalSubDivision"]],
321
- census_tracts_df[["County", "LegalSubDivision"]],
322
- ],
323
- ignore_index=True,
324
- ).dropna(subset=["County", "LegalSubDivision"])
325
- all_legal["County"] = all_legal["County"].astype(str).str.strip()
326
- all_legal["LegalSubDivision"] = all_legal["LegalSubDivision"].astype(str).str.strip()
327
- all_legal = all_legal[(all_legal["County"] != "") & (all_legal["LegalSubDivision"] != "")]
328
- all_legal = all_legal[["County", "LegalSubDivision"]].drop_duplicates()
329
-
330
- groups = [] # (county, [members]) so each cluster stays tied to its county
331
- for county in all_legal["County"].unique():
332
- strings = all_legal[all_legal["County"] == county]["LegalSubDivision"].tolist()
333
- for grp in group_similar_strings_optimized(
334
- strings, threshold=cluster_threshold, prefix_len=3, max_len_diff=3):
335
- groups.append((county, grp))
336
-
337
- rows = []
338
- for cid, (county, group) in enumerate(groups, start=1):
339
- for sub in group:
340
- rows.append({"Cluster_ID": cid, "County": county, "LegalSubDivision": sub})
341
- return pd.DataFrame(rows, columns=["Cluster_ID", "County", "LegalSubDivision"])
342
-
343
-
344
- # =====================================================================
345
- # STEP 3 — WIDE TABLES + MAJORITY-VOTE "REPLACE WITH"
346
- # =====================================================================
347
- def build_cluster_wide_table(source_df, cluster_df, value_col, prefix):
348
- # Map by (County, LegalSubDivision) -- NOT LegalSubDivision alone. The same
349
- # subdivision name occurs in many counties, each with its own cluster; keying
350
- # on the name only would collapse them and pool values across counties.
351
- lk = cluster_df[["County", "LegalSubDivision", "Cluster_ID"]].drop_duplicates(
352
- ["County", "LegalSubDivision"])
353
- cluster_map = {(c, s): cid for c, s, cid in
354
- zip(lk["County"].astype(str).str.strip(),
355
- lk["LegalSubDivision"].astype(str).str.strip(), lk["Cluster_ID"])}
356
-
357
- w = source_df[["County", "LegalSubDivision", value_col]].copy()
358
- w["County"] = w["County"].astype(str).str.strip()
359
- w["LegalSubDivision"] = w["LegalSubDivision"].astype(str).str.strip()
360
- w[value_col] = w[value_col].replace("", np.nan)
361
- w["Cluster_ID"] = [cluster_map.get((c, s))
362
- for c, s in zip(w["County"], w["LegalSubDivision"])]
363
- w = w.dropna(subset=["Cluster_ID", value_col])
364
- if w.empty:
365
- return pd.DataFrame(columns=["Cluster_ID"])
366
- w["Cluster_ID"] = w["Cluster_ID"].astype(int)
367
- w[value_col] = w[value_col].astype(str).str.strip()
368
- w = w[w[value_col] != ""]
369
-
370
- counts = w.groupby(["Cluster_ID", value_col], observed=True).size().unstack(fill_value=0)
371
- totals = counts.sum(axis=1)
372
- pct = counts.div(totals.replace(0, np.nan), axis=0).mul(100).fillna(0)
373
- counts.columns = [f"{prefix}{c}_Count" for c in counts.columns]
374
- pct.columns = [f"{prefix}{c}_Percentage" for c in pct.columns]
375
- wide = pd.concat([counts, pct], axis=1).reset_index()
376
-
377
- # Match the notebook: Cluster_ID first, all other columns sorted.
378
- other = sorted([c for c in wide.columns if c != "Cluster_ID"])
379
- return wide[["Cluster_ID"] + other]
380
-
381
-
382
- def build_replace_with(wide_df, prefix_to_remove, threshold):
383
- pct_cols = [c for c in wide_df.columns if c.endswith("_Percentage")]
384
- if not pct_cols:
385
- res = wide_df[["Cluster_ID"]].copy()
386
- res["Replace with"] = None
387
- return res.drop_duplicates(subset=["Cluster_ID"])
388
- labels = np.array(
389
- [c.replace(prefix_to_remove, "").replace("_Percentage", "") for c in pct_cols],
390
- dtype=object,
391
- )
392
- values = wide_df[pct_cols].to_numpy(copy=False)
393
- out = []
394
- for row in values:
395
- matched = labels[row >= threshold]
396
- out.append(", ".join(matched) if len(matched) else None)
397
- res = wide_df[["Cluster_ID"]].copy()
398
- res["Replace with"] = out
399
- return res.drop_duplicates(subset=["Cluster_ID"])
400
-
401
-
402
- def clean_census_tract_suffix(value):
403
- if pd.isna(value):
404
- return np.nan
405
- try:
406
- f = float(value)
407
- return str(int(f)) if f == int(f) else str(f)
408
- except ValueError:
409
- return str(value)
410
-
411
-
412
- def clean_zip(value):
413
- """Normalize ZIPs read from Excel as numbers: drop the float '.0' artifact and
414
- zero-pad to 5 digits (recovering leading zeros lost on numeric import, e.g.
415
- 7221.0 -> 07221). Handles comma-joined majority-vote results. ZIP+4 left as-is."""
416
- if pd.isna(value):
417
- return np.nan
418
- out = []
419
- for part in str(value).split(","):
420
- p = part.strip()
421
- if p.endswith(".0"):
422
- p = p[:-2]
423
- digits = re.sub(r"\D", "", p)
424
- if not digits:
425
- continue
426
- out.append(digits.zfill(5) if len(digits) <= 5 else digits)
427
- return ", ".join(out) if out else np.nan
428
-
429
-
430
- _BOOL_MAP = {
431
- True: "TRUE", False: "FALSE", 1: "TRUE", 0: "FALSE",
432
- "1": "TRUE", "0": "FALSE", "true": "TRUE", "false": "FALSE",
433
- "t": "TRUE", "f": "FALSE", "yes": "TRUE", "no": "FALSE",
434
- }
435
-
436
-
437
- def boolify(series):
438
- """Render a 0/1 (or True/False) column as literal 'TRUE'/'FALSE' text.
439
- Recognized values are mapped; anything unrecognized is left as-is; NaN kept."""
440
- def conv(v):
441
- if pd.isna(v):
442
- return v
443
- if v in _BOOL_MAP:
444
- return _BOOL_MAP[v]
445
- return _BOOL_MAP.get(str(v).strip().lower(), v)
446
- return series.map(conv)
447
-
448
-
449
- # =====================================================================
450
- # CHUNKED CSV WRITER (faithful port of save_csv_in_parts)
451
- # =====================================================================
452
- def save_csv_in_parts(df, base_filename, out_dir, row_limit=1_000_000):
453
- base_name = base_filename.replace(".csv", "")
454
- created = []
455
- total = len(df)
456
- num_parts = math.ceil(total / row_limit)
457
- for i in range(num_parts):
458
- start = i * row_limit
459
- end = min((i + 1) * row_limit, total)
460
- part = f"{base_name}_part_{i + 1}.csv" if num_parts > 1 else base_filename
461
- p = out_dir / part
462
- df.iloc[start:end].to_csv(p, index=False)
463
- created.append(str(p))
464
- gc.collect()
465
- return created
466
-
467
-
468
- # =====================================================================
469
- # MAIN PIPELINE
470
- # =====================================================================
471
- def run_pipeline(uploaded_files, reference_file, blank_cities_not_in_list,
472
- filter_dominant_county, cluster_threshold, replace_threshold):
473
- t_start = time.time()
474
- log = []
475
- if not uploaded_files:
476
- return "Please upload at least one Excel file.", []
477
-
478
- out_dir = Path(tempfile.mkdtemp(prefix="subdiv_"))
479
- outputs = []
480
-
481
- # ---- Resolve the reference (safety) list -------------------------
482
- # Default: server-side list (repo file or private dataset). If the user
483
- # uploads an override on the sidebar, use it for THIS run only.
484
- try:
485
- if reference_file is not None:
486
- wl = build_whitelist_from_path(reference_file.name)
487
- log.append(f"Using UPLOADED reference list: {Path(reference_file.name).name}")
488
- else:
489
- wl = load_whitelist()
490
- log.append("Using server-side safety list.")
491
- except FileNotFoundError as e:
492
- return "\n".join(log) + f"\n\nREFERENCE FILE ERROR:\n{e}", []
493
- except Exception as e:
494
- return "\n".join(log) + f"\n\nCould not parse reference list: {e}", []
495
-
496
- # ---- Load & merge uploads ----------------------------------------
497
- dfs = []
498
- for f in uploaded_files:
499
- try:
500
- dfs.append(pd.read_excel(f.name))
501
- log.append(f"Loaded {Path(f.name).name}")
502
- except Exception as e:
503
- log.append(f"ERROR loading {Path(f.name).name}: {e}")
504
- if not dfs:
505
- return "\n".join(log) + "\nNo files could be read.", []
506
- df = pd.concat(dfs, ignore_index=True)
507
- log.append(f"Merged shape: {df.shape}")
508
-
509
- # ---- Locate the FIPS-county column by CONTENT --------------------
510
- fips_col, fips_reason = detect_fips_county_column(df)
511
- if fips_col is None:
512
- return ("\n".join(log) +
513
- "\n\nCOLUMN ERROR: could not find a FIPS-county column. Expected "
514
- "values like '05045-FAULKNER' in one of the columns."), []
515
- log.append(f"FIPS-county column: '{fips_col}' ({fips_reason})")
516
-
517
- # ---- FIPS validation (uses the reference list) -------------------
518
- try:
519
- df, audit = fips_validate(df, blank_cities_not_in_list, log, wl=wl, fips_col=fips_col)
520
- except FileNotFoundError as e:
521
- return "\n".join(log) + f"\n\nREFERENCE FILE ERROR:\n{e}", []
522
-
523
- # ---- Verification files (audit + RawFile_FIPSValidated), CSV -----
524
- if len(audit) > 0:
525
- ap = out_dir / "FIPS_Validation_Audit_ChangedRecords.csv"
526
- audit.to_csv(ap, index=False)
527
- outputs.append(str(ap))
528
-
529
- rp = out_dir / "RawFile_FIPSValidated.csv"
530
- df.to_csv(rp, index=False)
531
- outputs.append(str(rp))
532
-
533
- # ---- UNDETERMINED/NULL -> NaN ------------------------------------
534
- for col in ["DDPPropertyCityFinal", "DDPPropertyZIPFinal",
535
- "DDPRevisedCensusTract", "LegalSubDivision"]:
536
- if col in df.columns:
537
- df[col] = df[col].replace(["UNDETERMINED CITY", "UNDETERMINED ZIP", "NULL"], np.nan)
538
-
539
- # ---- Rename detected FIPS col -> County --------------------------
540
- if fips_col != "County":
541
- if "County" in df.columns:
542
- df = df.drop(columns=["County"])
543
- df = df.rename(columns={fips_col: "County"})
544
-
545
- # ---- Filter to single most-dominant county -----------------------
546
- # DISABLED: we now process big multi-county files (up to a full state) in
547
- # one run, so we keep every county. Clustering already runs per-county.
548
- # To re-enable single-county mode, uncomment the block below.
549
- # if filter_dominant_county:
550
- # dominant = df["County"].value_counts().idxmax()
551
- # df = df[df["County"] == dominant].copy()
552
- # log.append(f"Filtered to dominant county: {dominant} -> {df.shape}")
553
-
554
- # ---- Source frames -----------------------------------------------
555
- city_df = df.loc[df["DDPPropertyCityFinal"].notna()].copy()
556
- zip_df = df.loc[df["DDPPropertyZIPFinal"].notna()].copy()
557
- census_tracts_df = df.loc[df["DDPRevisedCensusTract"].notna()].copy()
558
- original = df.loc[df["LegalSubDivision"].notna()].copy()
559
-
560
- # ---- Cluster ------------------------------------------------------
561
- cluster_df = build_clusters(city_df, zip_df, census_tracts_df, cluster_threshold)
562
- log.append(f"Clusters: {cluster_df['Cluster_ID'].nunique():,}")
563
-
564
- # ---- Replace-with (majority vote) --------------------------------
565
- zip_w = build_replace_with(
566
- build_cluster_wide_table(zip_df, cluster_df, "DDPPropertyZIPFinal", "ZIP_"),
567
- "ZIP_", replace_threshold).rename(columns={"Replace with": "Replace with Zip Codes"})
568
- city_w = build_replace_with(
569
- build_cluster_wide_table(city_df, cluster_df, "DDPPropertyCityFinal", "City_"),
570
- "City_", replace_threshold).rename(columns={"Replace with": "Replace with Cities"})
571
- cen_w = build_replace_with(
572
- build_cluster_wide_table(census_tracts_df, cluster_df, "DDPRevisedCensusTract", "CensusTract_"),
573
- "CensusTract_", replace_threshold).rename(columns={"Replace with": "Replace with Census Tracts"})
574
-
575
- # ---- Map back onto original --------------------------------------
576
- # Same fix: assign each row its county's cluster, keyed on (County, name).
577
- lk = cluster_df[["County", "LegalSubDivision", "Cluster_ID"]].drop_duplicates(
578
- ["County", "LegalSubDivision"])
579
- cmap = {(c, s): cid for c, s, cid in
580
- zip(lk["County"].astype(str).str.strip(),
581
- lk["LegalSubDivision"].astype(str).str.strip(), lk["Cluster_ID"])}
582
- original_final = original.copy()
583
- _oc = original_final["County"].astype(str).str.strip()
584
- _os = original_final["LegalSubDivision"].astype(str).str.strip()
585
- original_final["Cluster_ID"] = [cmap.get((c, s)) for c, s in zip(_oc, _os)]
586
- original_final["Replace with Zip Codes"] = original_final["Cluster_ID"].map(
587
- dict(zip(zip_w["Cluster_ID"], zip_w["Replace with Zip Codes"])))
588
- original_final["Replace with Cities"] = original_final["Cluster_ID"].map(
589
- dict(zip(city_w["Cluster_ID"], city_w["Replace with Cities"])))
590
- original_final["Replace with Census Tracts"] = original_final["Cluster_ID"].map(
591
- dict(zip(cen_w["Cluster_ID"], cen_w["Replace with Census Tracts"])))
592
-
593
- # Normalize ZIPs (drop float '.0', restore 5-digit zero-padding).
594
- original_final["Replace with Zip Codes"] = (
595
- original_final["Replace with Zip Codes"].apply(clean_zip))
596
-
597
- # ---- Reorder columns (desired_leading_columns) -------------------
598
- desired_leading = [
599
- "RecordKey", "ComesFromMtg2", "IsFlagged", "Cluster_ID", "LegalSubDivision",
600
- "County", "Replace with Zip Codes", "Replace with Cities", "Replace with Census Tracts",
601
- "DDPPropertyZIPFinal", "DDPPropertyCityFinal", "DDPRevisedCensusTract",
602
- "LotBlockSubdivisionTract", "DDPRevisedLatitude", "DDPRevisedLongitude",
603
- ]
604
- existing = original_final.columns.tolist()
605
- lead = [c for c in desired_leading if c in existing]
606
- other = [c for c in existing if c not in lead]
607
- original_final = original_final[lead + other]
608
-
609
- original_final_output = original_final.copy() # full output snapshot
610
-
611
- # ---- Split into final cities / zips / census tracts --------------
612
- keep = ["RecordKey", "ComesFromMtg2", "IsFlagged",
613
- "Replace with Zip Codes", "Replace with Cities", "Replace with Census Tracts",
614
- "DDPPropertyZIPFinal", "DDPPropertyCityFinal", "DDPRevisedCensusTract"]
615
- keep = [c for c in keep if c in original_final.columns]
616
- of = original_final[keep].rename(columns={
617
- "DDPPropertyZIPFinal": "DDPPropertyZIPFinalToRemove",
618
- "DDPPropertyCityFinal": "DDPPropertyCityFinalToRemove",
619
- "DDPRevisedCensusTract": "DDPRevisedCensusTractToRemove",
620
- "Replace with Zip Codes": "DDPPropertyZIPFinal",
621
- "Replace with Cities": "DDPPropertyCityFinal",
622
- "Replace with Census Tracts": "DDPRevisedCensusTract",
623
- })
624
- of["DDPRevisedCensusTract"] = of["DDPRevisedCensusTract"].apply(clean_census_tract_suffix)
625
-
626
- idcols = [c for c in ["RecordKey", "ComesFromMtg2", "IsFlagged"] if c in of.columns]
627
- final_cities = of[idcols + ["DDPPropertyCityFinalToRemove", "DDPPropertyCityFinal"]].copy()
628
- final_zips = of[idcols + ["DDPPropertyZIPFinalToRemove", "DDPPropertyZIPFinal"]].copy()
629
- final_ct = of[idcols + ["DDPRevisedCensusTractToRemove", "DDPRevisedCensusTract"]].copy()
630
-
631
- # keep only rows whose ORIGINAL value was blank (the ones we filled)
632
- final_cities = final_cities[final_cities["DDPPropertyCityFinalToRemove"].isna()].copy()
633
- final_zips = final_zips[final_zips["DDPPropertyZIPFinalToRemove"].isna()].copy()
634
- final_ct = final_ct[final_ct["DDPRevisedCensusTractToRemove"].isna()].copy()
635
-
636
- final_cities = final_cities.drop(columns=["DDPPropertyCityFinalToRemove"])
637
- final_zips = final_zips.drop(columns=["DDPPropertyZIPFinalToRemove"])
638
- final_ct = final_ct.drop(columns=["DDPRevisedCensusTractToRemove"])
639
-
640
- # ---- OnlyBlanks warnings (column entirely null) ------------------
641
- def only_blanks_warning(d, col, prefix):
642
- if col in d.columns and d[col].isnull().all():
643
- p = out_dir / f"OnlyBlanks_{prefix}.csv"
644
- d.to_csv(p, index=False)
645
- outputs.append(str(p))
646
- log.append(f"WARNING: {prefix} has only blanks in '{col}' -> {p.name}")
647
-
648
- only_blanks_warning(final_cities, "DDPPropertyCityFinal", "final_cities")
649
- only_blanks_warning(final_zips, "DDPPropertyZIPFinal", "final_zips")
650
- only_blanks_warning(final_ct, "DDPRevisedCensusTract", "final_census_tracts")
651
-
652
- # ---- Drop NaNs so only program assignments remain ----------------
653
- final_cities = final_cities[final_cities["DDPPropertyCityFinal"].notna()].copy()
654
- final_zips = final_zips[final_zips["DDPPropertyZIPFinal"].notna()].copy()
655
- final_ct = final_ct[final_ct["DDPRevisedCensusTract"].notna()].copy()
656
-
657
- # ---- Boolean columns as TRUE/FALSE (platform can't read 0/1) -----
658
- for d in (final_cities, final_zips, final_ct):
659
- for bc in ("ComesFromMtg2", "IsFlagged"):
660
- if bc in d.columns:
661
- d[bc] = boolify(d[bc])
662
-
663
- # ---- Write the per-category + cluster outputs (CSV) --------------
664
- for d, name in [(final_cities, "final_cities.csv"),
665
- (final_zips, "final_zips.csv"),
666
- (final_ct, "final_census_tracts.csv"),
667
- (cluster_df, "cluster_df.csv")]:
668
- p = out_dir / name
669
- d.to_csv(p, index=False)
670
- outputs.append(str(p))
671
-
672
- # ---- Full output CSV (chunked at 1,000,000 rows) -----------------
673
- # NB: no '%' in the filename -- '%' is the URL-encoding character and makes
674
- # the browser download fail with "unknown server error".
675
- csv_name = f"OutputFile_{replace_threshold}Threshold_{cluster_threshold}ClustersRapidFuzz.csv"
676
- outputs.extend(save_csv_in_parts(original_final_output, csv_name, out_dir, row_limit=1_000_000))
677
-
678
- # ---- Summary sheet: ONE ROW PER COUNTY ---------------------------
679
- # Totals (records / subdivisions) come from the FULL post-validation frame
680
- # (df -- every row, incl. those with no LegalSubDivision). The blank/fill/
681
- # cluster metrics come from the clustered subset (output_df), which is the
682
- # only set the pipeline can actually fill. Other output files are unchanged.
683
- output_df = original_final_output # rows WITH a LegalSubDivision + fills
684
- full_df = df # ALL post-validation rows, has County
685
- city_df, zips_df, census_df = final_cities, final_zips, final_ct
686
-
687
- def _fips_name(label):
688
- raw = str(label)
689
- parts = raw.split("-")
690
- fips = parts[0].strip()
691
- name = parts[1].strip().title() if len(parts) > 1 else raw.strip().title()
692
- return fips, name
693
-
694
- RW_CITY, RW_ZIP, RW_TRACT = ("Replace with Cities", "Replace with Zip Codes",
695
- "Replace with Census Tracts")
696
- ORIG_CITY, ORIG_ZIP, ORIG_TRACT = ("DDPPropertyCityFinal", "DDPPropertyZIPFinal",
697
- "DDPRevisedCensusTract")
698
-
699
- def _blank(g, col):
700
- return g[col].isna() if col in g.columns else pd.Series(False, index=g.index)
701
-
702
- def _fill(g, col):
703
- return g[col].notna() if col in g.columns else pd.Series(False, index=g.index)
704
-
705
- def _out_subset(label):
706
- if "County" not in output_df.columns:
707
- return output_df.iloc[0:0]
708
- m = output_df["County"].isna() if pd.isna(label) else (output_df["County"] == label)
709
- return output_df[m]
710
-
711
- summary_rows = []
712
- if "County" in full_df.columns and len(full_df):
713
- for county_label, gfull in full_df.groupby("County", dropna=False):
714
- fips, name = _fips_name(county_label)
715
- g = _out_subset(county_label) # clustered rows for this county
716
- city_blank, zip_blank, tract_blank = (_blank(g, ORIG_CITY),
717
- _blank(g, ORIG_ZIP), _blank(g, ORIG_TRACT))
718
- city_fill, zip_fill, tract_fill = (_fill(g, RW_CITY),
719
- _fill(g, RW_ZIP), _fill(g, RW_TRACT))
720
- summary_rows.append({
721
- "County": name,
722
- "FIPS": fips,
723
- # true totals from the full frame
724
- "Total Records in County": len(gfull),
725
- # how many of those records carry a LegalSubDivision (non-unique)
726
- "Total Subdivisions": int(gfull["LegalSubDivision"].count())
727
- if "LegalSubDivision" in gfull.columns else 0,
728
- "Total Clusters Made": int(g["Cluster_ID"].nunique())
729
- if "Cluster_ID" in g.columns else 0,
730
- "Total Blank Cities": int(city_blank.sum()),
731
- "Total Cities Assignment": int((city_blank & city_fill).sum()),
732
- "Total Blank Zips": int(zip_blank.sum()),
733
- "Total Zips Assignment": int((zip_blank & zip_fill).sum()),
734
- "Total Blank Census": int(tract_blank.sum()),
735
- "Total Census Assignment": int((tract_blank & tract_fill).sum()),
736
- })
737
-
738
- summary_cols = ["County", "FIPS", "Total Records in County", "Total Subdivisions",
739
- "Total Clusters Made", "Total Blank Cities", "Total Cities Assignment",
740
- "Total Blank Zips", "Total Zips Assignment", "Total Blank Census",
741
- "Total Census Assignment"]
742
- summary_df = pd.DataFrame(summary_rows, columns=summary_cols)
743
- log.append(f"Summary: {len(summary_df)} county row(s).")
744
-
745
- summary_path = out_dir / "Summary.csv"
746
- summary_df.to_csv(summary_path, index=False)
747
- outputs.append(str(summary_path))
748
-
749
- # ---- Master bundle: one ZIP of CSVs (no Excel row limit) ---------
750
- # A single CSV can hold only one table, so the "master workbook" becomes a
751
- # ZIP that bundles every result as its own CSV -- including the full output
752
- # (chunked into parts), which no longer hits Excel's 1,048,576-row ceiling.
753
- # CSV writing also avoids openpyxl's heavy memory use on huge files.
754
- master_path = out_dir / "Master_Dataset.zip"
755
- member_names = ["FIPS_Validation_Audit_ChangedRecords.csv", "cluster_df.csv",
756
- "final_cities.csv", "final_zips.csv", "final_census_tracts.csv",
757
- "Summary.csv"]
758
- members = [out_dir / n for n in member_names if (out_dir / n).exists()]
759
- members += sorted(out_dir.glob("OutputFile_*.csv")) # full output (chunked)
760
- with zipfile.ZipFile(master_path, "w", zipfile.ZIP_DEFLATED) as zf:
761
- for p in members:
762
- zf.write(p, arcname=p.name)
763
- outputs.append(str(master_path))
764
-
765
- elapsed_min = (time.time() - t_start) / 60
766
- log.append(f"Done. {len(outputs)} files ready.")
767
- log.append(f"Total processing time: {elapsed_min:.1f} minutes.")
768
- gc.collect()
769
- return "\n".join(log), outputs
770
-
771
-
772
- # =====================================================================
773
- # STARTUP HEALTH CHECK
774
- # =====================================================================
775
- def _startup_health_check():
776
- if os.environ.get("SELF_TEST_ON_STARTUP", "1") != "1":
777
- return
778
- try:
779
- print("[startup] " + run_self_test())
780
- except FileNotFoundError as e:
781
- # Reference file not configured yet — let the UI load so the user can fix it.
782
- print(f"[startup] Self-test skipped — safety list unavailable:\n{e}")
783
- # AssertionError intentionally propagates: a failed self-test fails the boot.
784
-
785
-
786
- _startup_health_check()
787
-
788
-
789
- # =====================================================================
790
- # GRADIO UI (simple vertical layout — previous design)
791
- # =====================================================================
792
- with gr.Blocks() as demo:
793
- gr.Markdown(
794
- "## Subdivision Cluster + FIPS Validation\n"
795
- "Upload the Excel files to process. Records are validated against the "
796
- "Subdivision Program Safety List, then `LegalSubDivision` values are "
797
- "fuzzy-clustered and city/ZIP/census-tract are filled by majority vote.\n\n"
798
- "*Runs with the notebook's fixed settings.*"
799
- )
800
- files_in = gr.File(file_count="multiple", file_types=[".xlsx", ".xls"],
801
- label="Excel files to process")
802
- run_btn = gr.Button("Run pipeline", variant="primary")
803
- status = gr.Textbox(label="Log", lines=14)
804
- files_out = gr.File(label="Output files", file_count="multiple")
805
-
806
- def _run_simple(files):
807
- # No reference upload in this layout -> always the server-side list.
808
- # All settings are fixed (see constants at top). No user-facing options.
809
- return run_pipeline(files, None, STRICT_BLANK_CITIES, FILTER_DOMINANT_COUNTY,
810
- CLUSTER_THRESHOLD, REPLACE_THRESHOLD)
811
-
812
- run_btn.click(
813
- _run_simple,
814
- inputs=[files_in],
815
- outputs=[status, files_out],
816
- )
817
-
818
- if __name__ == "__main__":
819
- demo.launch()