saulsolis09 commited on
Commit
384a877
·
verified ·
1 Parent(s): 7c11a85

Upload app_simple_ui.py

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