saulsolis09 commited on
Commit
4bfad2e
·
verified ·
1 Parent(s): 5a94d22

Upload 3 files

Browse files
Files changed (3) hide show
  1. app.py +649 -0
  2. app_simple_ui.py +629 -0
  3. requirements.txt +10 -0
app.py ADDED
@@ -0,0 +1,649 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
45
+ def get_safety_list_path() -> str:
46
+ local_name = os.environ.get("SAFETY_LIST_FILE", DEFAULT_SAFETY_LIST_NAME)
47
+ if Path(local_name).exists():
48
+ return local_name
49
+
50
+ repo_id = os.environ.get("SAFETY_LIST_REPO")
51
+ token = os.environ.get("HF_TOKEN")
52
+ if repo_id and token:
53
+ from huggingface_hub import hf_hub_download
54
+ filename = os.environ.get("SAFETY_LIST_REPO_FILE", local_name)
55
+ return hf_hub_download(
56
+ repo_id=repo_id, filename=filename, repo_type="dataset", token=token
57
+ )
58
+
59
+ raise FileNotFoundError(
60
+ "Safety list not found.\n"
61
+ f" - Commit '{local_name}' into this Space (keep the Space private), OR\n"
62
+ " - Set SAFETY_LIST_REPO + HF_TOKEN to pull it from a private dataset."
63
+ )
64
+
65
+
66
+ _SAFETY_CACHE: dict | None = None
67
+
68
+
69
+ def build_whitelist_from_path(path):
70
+ """Parse a safety-list file (xlsx or csv) into {pairs, cities, rows}."""
71
+ if str(path).lower().endswith(".csv"):
72
+ safety_df = pd.read_csv(path)
73
+ else:
74
+ safety_df = pd.read_excel(path)
75
+ acceptable_cols = [c for c in safety_df.columns if str(c).startswith("Acceptable FIPS")]
76
+
77
+ valid_pairs, valid_cities = set(), set()
78
+ for _, r in safety_df.iterrows():
79
+ c = _norm_city(r["City Name"])
80
+ if c is None:
81
+ continue
82
+ valid_cities.add(c)
83
+ for col in acceptable_cols:
84
+ f = _norm_fips(r[col])
85
+ if f:
86
+ valid_pairs.add(c + "||" + f)
87
+
88
+ return {"pairs": valid_pairs, "cities": valid_cities, "rows": len(safety_df)}
89
+
90
+
91
+ def load_whitelist():
92
+ """Server-side safety list (repo file or private dataset). Cached per process."""
93
+ global _SAFETY_CACHE
94
+ if _SAFETY_CACHE is None:
95
+ _SAFETY_CACHE = build_whitelist_from_path(get_safety_list_path())
96
+ return _SAFETY_CACHE
97
+
98
+
99
+ # =====================================================================
100
+ # NORMALIZATION HELPERS (identical to the notebook)
101
+ # =====================================================================
102
+ PLACEHOLDERS = {"UNDETERMINED CITY", "UNDETERMINED ZIP", "NULL", "NAN", "NONE", ""}
103
+
104
+
105
+ def _norm_city(x):
106
+ if pd.isna(x):
107
+ return None
108
+ return str(x).strip().upper()
109
+
110
+
111
+ def _norm_fips(x):
112
+ """5-digit FIPS string, or None. Handles 28071, 28071.0, '01067', '28071 - LAFAYETTE'."""
113
+ if pd.isna(x):
114
+ return None
115
+ m = re.search(r"\d+", str(x))
116
+ return str(int(m.group(0))).zfill(5) if m else None
117
+
118
+
119
+ # =====================================================================
120
+ # SELF-TEST (startup health check — same logic as the notebook's cell)
121
+ # =====================================================================
122
+ def run_self_test() -> str:
123
+ path = get_safety_list_path()
124
+ st = pd.read_excel(path)
125
+ fc = [c for c in st.columns if str(c).startswith("Acceptable FIPS")]
126
+ pairs = set()
127
+ for _, r in st.iterrows():
128
+ c = _norm_city(r["City Name"])
129
+ if c is None:
130
+ continue
131
+ for col in fc:
132
+ f = _norm_fips(r[col])
133
+ if f:
134
+ pairs.add(c + "||" + f)
135
+
136
+ good_city = st.iloc[0]["City Name"]
137
+ good_fips = st.iloc[0]["Acceptable FIPS 1"]
138
+ test = pd.DataFrame({
139
+ "DDPPropertyCityFinal": [good_city, good_city],
140
+ "** REC FIPS-COUNTY": [good_fips, 99999], # row 2 = wrong FIPS on purpose
141
+ })
142
+ cn = test["DDPPropertyCityFinal"].map(_norm_city)
143
+ fn = test["** REC FIPS-COUNTY"].map(_norm_fips)
144
+ key = cn.fillna("") + "||" + fn.fillna("")
145
+ ok = key.isin(pairs)
146
+ assert bool(ok.iloc[0]) and not bool(ok.iloc[1]), \
147
+ "SELF-TEST FAILED -- matching logic is not working as expected."
148
+ return f"SELF-TEST PASSED: known-good ({good_city}) kept, wrong FIPS flagged."
149
+
150
+
151
+ # =====================================================================
152
+ # STEP 1 — FIPS SAFETY-LIST VALIDATION
153
+ # =====================================================================
154
+ def fips_validate(df: pd.DataFrame, blank_cities_not_in_list: bool, log, wl=None):
155
+ if wl is None:
156
+ wl = load_whitelist()
157
+ valid_pairs, valid_cities = wl["pairs"], wl["cities"]
158
+
159
+ FIPS_COL = "** REC FIPS-COUNTY" if "** REC FIPS-COUNTY" in df.columns else "County"
160
+ CITY_COL, ZIP_COL, TRACT_COL = (
161
+ "DDPPropertyCityFinal", "DDPPropertyZIPFinal", "DDPRevisedCensusTract",
162
+ )
163
+
164
+ city_norm = df[CITY_COL].map(_norm_city)
165
+ fips_norm = df[FIPS_COL].map(_norm_fips)
166
+ row_key = city_norm.fillna("") + "||" + fips_norm.fillna("")
167
+
168
+ is_real_city = df[CITY_COL].notna() & (~city_norm.fillna("").isin(PLACEHOLDERS))
169
+ city_in_list = city_norm.isin(valid_cities)
170
+ pair_ok = row_key.isin(valid_pairs)
171
+
172
+ if blank_cities_not_in_list:
173
+ fails_mask = is_real_city & (~pair_ok)
174
+ else:
175
+ fails_mask = is_real_city & city_in_list & (~pair_ok)
176
+
177
+ n_real = int(is_real_city.sum())
178
+ n_inlist = int((is_real_city & city_in_list).sum())
179
+ n_valid = int((is_real_city & pair_ok).sum())
180
+ n_fail = int(fails_mask.sum())
181
+ log.append(
182
+ f"FIPS validation — list: {wl['rows']:,} rows | {len(valid_cities):,} cities | "
183
+ f"{len(valid_pairs):,} pairs"
184
+ )
185
+ log.append(
186
+ f" real:{n_real:,} in-list:{n_inlist:,} valid-kept:{n_valid:,} blanked:{n_fail:,}"
187
+ )
188
+ if n_real > 0 and n_inlist == 0:
189
+ log.append(" !! 0 cities matched the list — likely a format/spelling mismatch.")
190
+
191
+ # Audit built BEFORE overwrite (insert position matches the notebook).
192
+ key_col = "RecordKey" if "RecordKey" in df.columns else None
193
+ base_cols = [c for c in [key_col, CITY_COL, FIPS_COL, ZIP_COL, TRACT_COL] if c]
194
+ audit = df.loc[fails_mask, base_cols].copy()
195
+ audit.insert(
196
+ len(base_cols) if key_col is None else 2,
197
+ "NormalizedFIPS", fips_norm[fails_mask].values,
198
+ )
199
+ audit["Reason"] = np.where(
200
+ city_in_list[fails_mask].values, "FIPS does not match city", "City not in safety list"
201
+ )
202
+ audit = audit.rename(
203
+ columns={CITY_COL: "OLD_City", ZIP_COL: "OLD_ZIP", TRACT_COL: "OLD_CensusTract"}
204
+ )
205
+
206
+ # Recent pandas reads all-numeric Excel columns as float64 and refuses to
207
+ # accept a string into them; Colab's older pandas silently upcast to object.
208
+ # Cast first so the placeholder write reproduces the notebook's result.
209
+ df[CITY_COL] = df[CITY_COL].astype(object)
210
+ df[ZIP_COL] = df[ZIP_COL].astype(object)
211
+ df.loc[fails_mask, CITY_COL] = "UNDETERMINED CITY"
212
+ df.loc[fails_mask, ZIP_COL] = "UNDETERMINED ZIP"
213
+ df.loc[fails_mask, TRACT_COL] = np.nan
214
+ return df, audit
215
+
216
+
217
+ # =====================================================================
218
+ # STEP 2 — RAPIDFUZZ CLUSTERING (identical to the notebook)
219
+ # =====================================================================
220
+ def group_similar_strings_optimized(strings, threshold=95, prefix_len=3, max_len_diff=3):
221
+ cleaned, seen = [], set()
222
+ for s in strings:
223
+ if pd.isna(s):
224
+ continue
225
+ s = str(s).strip()
226
+ if s and s not in seen:
227
+ cleaned.append(s)
228
+ seen.add(s)
229
+
230
+ visited, groups = set(), []
231
+ buckets = defaultdict(list)
232
+ for s in cleaned:
233
+ buckets[s.upper()[:prefix_len]].append(s)
234
+
235
+ for bucket in buckets.values():
236
+ for i, base in enumerate(bucket):
237
+ if base in visited:
238
+ continue
239
+ group = [base]
240
+ visited.add(base)
241
+ base_upper = base.upper()
242
+ base_len = len(base_upper)
243
+ for j in range(i + 1, len(bucket)):
244
+ compare = bucket[j]
245
+ if compare in visited:
246
+ continue
247
+ comp_upper = compare.upper()
248
+ if abs(base_len - len(comp_upper)) > max_len_diff:
249
+ continue
250
+ if fuzz.ratio(base_upper, comp_upper) >= threshold:
251
+ group.append(compare)
252
+ visited.add(compare)
253
+ groups.append(group)
254
+ return groups
255
+
256
+
257
+ def build_clusters(city_df, zip_df, census_tracts_df, cluster_threshold):
258
+ all_legal = pd.concat(
259
+ [
260
+ city_df[["County", "LegalSubDivision"]],
261
+ zip_df[["County", "LegalSubDivision"]],
262
+ census_tracts_df[["County", "LegalSubDivision"]],
263
+ ],
264
+ ignore_index=True,
265
+ ).dropna(subset=["County", "LegalSubDivision"])
266
+ all_legal["County"] = all_legal["County"].astype(str).str.strip()
267
+ all_legal["LegalSubDivision"] = all_legal["LegalSubDivision"].astype(str).str.strip()
268
+ all_legal = all_legal[(all_legal["County"] != "") & (all_legal["LegalSubDivision"] != "")]
269
+ all_legal = all_legal[["County", "LegalSubDivision"]].drop_duplicates()
270
+
271
+ groups = []
272
+ for county in all_legal["County"].unique():
273
+ strings = all_legal[all_legal["County"] == county]["LegalSubDivision"].tolist()
274
+ groups.extend(
275
+ group_similar_strings_optimized(
276
+ strings, threshold=cluster_threshold, prefix_len=3, max_len_diff=3
277
+ )
278
+ )
279
+
280
+ rows = []
281
+ for cid, group in enumerate(groups, start=1):
282
+ for sub in group:
283
+ rows.append({"Cluster_ID": cid, "LegalSubDivision": sub})
284
+ return pd.DataFrame(rows, columns=["Cluster_ID", "LegalSubDivision"])
285
+
286
+
287
+ # =====================================================================
288
+ # STEP 3 — WIDE TABLES + MAJORITY-VOTE "REPLACE WITH"
289
+ # =====================================================================
290
+ def build_cluster_wide_table(source_df, cluster_df, value_col, prefix):
291
+ lk = cluster_df[["LegalSubDivision", "Cluster_ID"]].drop_duplicates("LegalSubDivision")
292
+ cluster_map = dict(zip(lk["LegalSubDivision"], lk["Cluster_ID"]))
293
+
294
+ w = source_df[["LegalSubDivision", value_col]].copy()
295
+ w["LegalSubDivision"] = w["LegalSubDivision"].astype(str).str.strip()
296
+ w[value_col] = w[value_col].replace("", np.nan)
297
+ w["Cluster_ID"] = w["LegalSubDivision"].map(cluster_map)
298
+ w = w.dropna(subset=["Cluster_ID", value_col])
299
+ if w.empty:
300
+ return pd.DataFrame(columns=["Cluster_ID"])
301
+ w["Cluster_ID"] = w["Cluster_ID"].astype(int)
302
+ w[value_col] = w[value_col].astype(str).str.strip()
303
+ w = w[w[value_col] != ""]
304
+
305
+ counts = w.groupby(["Cluster_ID", value_col], observed=True).size().unstack(fill_value=0)
306
+ totals = counts.sum(axis=1)
307
+ pct = counts.div(totals.replace(0, np.nan), axis=0).mul(100).fillna(0)
308
+ counts.columns = [f"{prefix}{c}_Count" for c in counts.columns]
309
+ pct.columns = [f"{prefix}{c}_Percentage" for c in pct.columns]
310
+ wide = pd.concat([counts, pct], axis=1).reset_index()
311
+
312
+ # Match the notebook: Cluster_ID first, all other columns sorted.
313
+ other = sorted([c for c in wide.columns if c != "Cluster_ID"])
314
+ return wide[["Cluster_ID"] + other]
315
+
316
+
317
+ def build_replace_with(wide_df, prefix_to_remove, threshold):
318
+ pct_cols = [c for c in wide_df.columns if c.endswith("_Percentage")]
319
+ if not pct_cols:
320
+ res = wide_df[["Cluster_ID"]].copy()
321
+ res["Replace with"] = None
322
+ return res.drop_duplicates(subset=["Cluster_ID"])
323
+ labels = np.array(
324
+ [c.replace(prefix_to_remove, "").replace("_Percentage", "") for c in pct_cols],
325
+ dtype=object,
326
+ )
327
+ values = wide_df[pct_cols].to_numpy(copy=False)
328
+ out = []
329
+ for row in values:
330
+ matched = labels[row >= threshold]
331
+ out.append(", ".join(matched) if len(matched) else None)
332
+ res = wide_df[["Cluster_ID"]].copy()
333
+ res["Replace with"] = out
334
+ return res.drop_duplicates(subset=["Cluster_ID"])
335
+
336
+
337
+ def clean_census_tract_suffix(value):
338
+ if pd.isna(value):
339
+ return np.nan
340
+ try:
341
+ f = float(value)
342
+ return str(int(f)) if f == int(f) else str(f)
343
+ except ValueError:
344
+ return str(value)
345
+
346
+
347
+ def clean_zip(value):
348
+ """Normalize ZIPs read from Excel as numbers: drop the float '.0' artifact and
349
+ zero-pad to 5 digits (recovering leading zeros lost on numeric import, e.g.
350
+ 7221.0 -> 07221). Handles comma-joined majority-vote results. ZIP+4 left as-is."""
351
+ if pd.isna(value):
352
+ return np.nan
353
+ out = []
354
+ for part in str(value).split(","):
355
+ p = part.strip()
356
+ if p.endswith(".0"):
357
+ p = p[:-2]
358
+ digits = re.sub(r"\D", "", p)
359
+ if not digits:
360
+ continue
361
+ out.append(digits.zfill(5) if len(digits) <= 5 else digits)
362
+ return ", ".join(out) if out else np.nan
363
+
364
+
365
+ # =====================================================================
366
+ # CHUNKED CSV WRITER (faithful port of save_csv_in_parts)
367
+ # =====================================================================
368
+ def save_csv_in_parts(df, base_filename, out_dir, row_limit=1_000_000):
369
+ base_name = base_filename.replace(".csv", "")
370
+ created = []
371
+ total = len(df)
372
+ num_parts = math.ceil(total / row_limit)
373
+ for i in range(num_parts):
374
+ start = i * row_limit
375
+ end = min((i + 1) * row_limit, total)
376
+ part = f"{base_name}_part_{i + 1}.csv" if num_parts > 1 else base_filename
377
+ p = out_dir / part
378
+ df.iloc[start:end].to_csv(p, index=False)
379
+ created.append(str(p))
380
+ gc.collect()
381
+ return created
382
+
383
+
384
+ # =====================================================================
385
+ # MAIN PIPELINE
386
+ # =====================================================================
387
+ def run_pipeline(uploaded_files, reference_file, blank_cities_not_in_list,
388
+ filter_dominant_county, cluster_threshold, replace_threshold):
389
+ log = []
390
+ if not uploaded_files:
391
+ return "Please upload at least one Excel file.", []
392
+
393
+ out_dir = Path(tempfile.mkdtemp(prefix="subdiv_"))
394
+ outputs = []
395
+
396
+ # ---- Resolve the reference (safety) list -------------------------
397
+ # Default: server-side list (repo file or private dataset). If the user
398
+ # uploads an override on the sidebar, use it for THIS run only.
399
+ try:
400
+ if reference_file is not None:
401
+ wl = build_whitelist_from_path(reference_file.name)
402
+ log.append(f"Using UPLOADED reference list: {Path(reference_file.name).name}")
403
+ else:
404
+ wl = load_whitelist()
405
+ log.append("Using server-side safety list.")
406
+ except FileNotFoundError as e:
407
+ return "\n".join(log) + f"\n\nREFERENCE FILE ERROR:\n{e}", []
408
+ except Exception as e:
409
+ return "\n".join(log) + f"\n\nCould not parse reference list: {e}", []
410
+
411
+ # ---- Load & merge uploads ----------------------------------------
412
+ dfs = []
413
+ for f in uploaded_files:
414
+ try:
415
+ dfs.append(pd.read_excel(f.name))
416
+ log.append(f"Loaded {Path(f.name).name}")
417
+ except Exception as e:
418
+ log.append(f"ERROR loading {Path(f.name).name}: {e}")
419
+ if not dfs:
420
+ return "\n".join(log) + "\nNo files could be read.", []
421
+ df = pd.concat(dfs, ignore_index=True)
422
+ log.append(f"Merged shape: {df.shape}")
423
+
424
+ # ---- FIPS validation (uses the reference list) -------------------
425
+ try:
426
+ df, audit = fips_validate(df, blank_cities_not_in_list, log, wl=wl)
427
+ except FileNotFoundError as e:
428
+ return "\n".join(log) + f"\n\nREFERENCE FILE ERROR:\n{e}", []
429
+
430
+ # ---- Download verification files (audit + RawFile_FIPSValidated) -
431
+ if len(audit) > 0:
432
+ ap = out_dir / "FIPS_Validation_Audit_ChangedRecords.xlsx"
433
+ audit.to_excel(ap, index=False)
434
+ outputs.append(str(ap))
435
+
436
+ if len(df) <= EXCEL_ROW_LIMIT:
437
+ rp = out_dir / "RawFile_FIPSValidated.xlsx"
438
+ df.to_excel(rp, index=False)
439
+ else:
440
+ rp = out_dir / "RawFile_FIPSValidated.csv"
441
+ df.to_csv(rp, index=False)
442
+ outputs.append(str(rp))
443
+
444
+ # ---- UNDETERMINED/NULL -> NaN ------------------------------------
445
+ for col in ["DDPPropertyCityFinal", "DDPPropertyZIPFinal",
446
+ "DDPRevisedCensusTract", "LegalSubDivision"]:
447
+ if col in df.columns:
448
+ df[col] = df[col].replace(["UNDETERMINED CITY", "UNDETERMINED ZIP", "NULL"], np.nan)
449
+
450
+ # ---- Rename FIPS col -> County -----------------------------------
451
+ if "** REC FIPS-COUNTY" in df.columns:
452
+ df = df.rename(columns={"** REC FIPS-COUNTY": "County"})
453
+
454
+ # ---- Optional: filter to single most-dominant county -------------
455
+ if filter_dominant_county:
456
+ dominant = df["County"].value_counts().idxmax()
457
+ df = df[df["County"] == dominant].copy()
458
+ log.append(f"Filtered to dominant county: {dominant} -> {df.shape}")
459
+
460
+ # ---- Source frames -----------------------------------------------
461
+ city_df = df.loc[df["DDPPropertyCityFinal"].notna()].copy()
462
+ zip_df = df.loc[df["DDPPropertyZIPFinal"].notna()].copy()
463
+ census_tracts_df = df.loc[df["DDPRevisedCensusTract"].notna()].copy()
464
+ original = df.loc[df["LegalSubDivision"].notna()].copy()
465
+
466
+ # ---- Cluster ------------------------------------------------------
467
+ cluster_df = build_clusters(city_df, zip_df, census_tracts_df, cluster_threshold)
468
+ log.append(f"Clusters: {cluster_df['Cluster_ID'].nunique():,}")
469
+
470
+ # ---- Replace-with (majority vote) --------------------------------
471
+ zip_w = build_replace_with(
472
+ build_cluster_wide_table(zip_df, cluster_df, "DDPPropertyZIPFinal", "ZIP_"),
473
+ "ZIP_", replace_threshold).rename(columns={"Replace with": "Replace with Zip Codes"})
474
+ city_w = build_replace_with(
475
+ build_cluster_wide_table(city_df, cluster_df, "DDPPropertyCityFinal", "City_"),
476
+ "City_", replace_threshold).rename(columns={"Replace with": "Replace with Cities"})
477
+ cen_w = build_replace_with(
478
+ build_cluster_wide_table(census_tracts_df, cluster_df, "DDPRevisedCensusTract", "CensusTract_"),
479
+ "CensusTract_", replace_threshold).rename(columns={"Replace with": "Replace with Census Tracts"})
480
+
481
+ # ---- Map back onto original --------------------------------------
482
+ lk = cluster_df[["LegalSubDivision", "Cluster_ID"]].drop_duplicates("LegalSubDivision")
483
+ cmap = dict(zip(lk["LegalSubDivision"], lk["Cluster_ID"]))
484
+ original_final = original.copy()
485
+ original_final["Cluster_ID"] = original_final["LegalSubDivision"].map(cmap)
486
+ original_final["Replace with Zip Codes"] = original_final["Cluster_ID"].map(
487
+ dict(zip(zip_w["Cluster_ID"], zip_w["Replace with Zip Codes"])))
488
+ original_final["Replace with Cities"] = original_final["Cluster_ID"].map(
489
+ dict(zip(city_w["Cluster_ID"], city_w["Replace with Cities"])))
490
+ original_final["Replace with Census Tracts"] = original_final["Cluster_ID"].map(
491
+ dict(zip(cen_w["Cluster_ID"], cen_w["Replace with Census Tracts"])))
492
+
493
+ # Normalize ZIPs (drop float '.0', restore 5-digit zero-padding).
494
+ original_final["Replace with Zip Codes"] = (
495
+ original_final["Replace with Zip Codes"].apply(clean_zip))
496
+
497
+ # ---- Reorder columns (desired_leading_columns) -------------------
498
+ desired_leading = [
499
+ "RecordKey", "ComesFromMtg2", "IsFlagged", "Cluster_ID", "LegalSubDivision",
500
+ "County", "Replace with Zip Codes", "Replace with Cities", "Replace with Census Tracts",
501
+ "DDPPropertyZIPFinal", "DDPPropertyCityFinal", "DDPRevisedCensusTract",
502
+ "LotBlockSubdivisionTract", "DDPRevisedLatitude", "DDPRevisedLongitude",
503
+ ]
504
+ existing = original_final.columns.tolist()
505
+ lead = [c for c in desired_leading if c in existing]
506
+ other = [c for c in existing if c not in lead]
507
+ original_final = original_final[lead + other]
508
+
509
+ original_final_output = original_final.copy() # full output snapshot
510
+
511
+ # ---- Split into final cities / zips / census tracts --------------
512
+ keep = ["RecordKey", "ComesFromMtg2", "IsFlagged",
513
+ "Replace with Zip Codes", "Replace with Cities", "Replace with Census Tracts",
514
+ "DDPPropertyZIPFinal", "DDPPropertyCityFinal", "DDPRevisedCensusTract"]
515
+ keep = [c for c in keep if c in original_final.columns]
516
+ of = original_final[keep].rename(columns={
517
+ "DDPPropertyZIPFinal": "DDPPropertyZIPFinalToRemove",
518
+ "DDPPropertyCityFinal": "DDPPropertyCityFinalToRemove",
519
+ "DDPRevisedCensusTract": "DDPRevisedCensusTractToRemove",
520
+ "Replace with Zip Codes": "DDPPropertyZIPFinal",
521
+ "Replace with Cities": "DDPPropertyCityFinal",
522
+ "Replace with Census Tracts": "DDPRevisedCensusTract",
523
+ })
524
+ of["DDPRevisedCensusTract"] = of["DDPRevisedCensusTract"].apply(clean_census_tract_suffix)
525
+
526
+ idcols = [c for c in ["RecordKey", "ComesFromMtg2", "IsFlagged"] if c in of.columns]
527
+ final_cities = of[idcols + ["DDPPropertyCityFinalToRemove", "DDPPropertyCityFinal"]].copy()
528
+ final_zips = of[idcols + ["DDPPropertyZIPFinalToRemove", "DDPPropertyZIPFinal"]].copy()
529
+ final_ct = of[idcols + ["DDPRevisedCensusTractToRemove", "DDPRevisedCensusTract"]].copy()
530
+
531
+ # keep only rows whose ORIGINAL value was blank (the ones we filled)
532
+ final_cities = final_cities[final_cities["DDPPropertyCityFinalToRemove"].isna()].copy()
533
+ final_zips = final_zips[final_zips["DDPPropertyZIPFinalToRemove"].isna()].copy()
534
+ final_ct = final_ct[final_ct["DDPRevisedCensusTractToRemove"].isna()].copy()
535
+
536
+ final_cities = final_cities.drop(columns=["DDPPropertyCityFinalToRemove"])
537
+ final_zips = final_zips.drop(columns=["DDPPropertyZIPFinalToRemove"])
538
+ final_ct = final_ct.drop(columns=["DDPRevisedCensusTractToRemove"])
539
+
540
+ # ---- OnlyBlanks warnings (column entirely null) ------------------
541
+ def only_blanks_warning(d, col, prefix):
542
+ if col in d.columns and d[col].isnull().all():
543
+ p = out_dir / f"OnlyBlanks_{prefix}.xlsx"
544
+ d.to_excel(p, index=False)
545
+ outputs.append(str(p))
546
+ log.append(f"WARNING: {prefix} has only blanks in '{col}' -> {p.name}")
547
+
548
+ only_blanks_warning(final_cities, "DDPPropertyCityFinal", "final_cities")
549
+ only_blanks_warning(final_zips, "DDPPropertyZIPFinal", "final_zips")
550
+ only_blanks_warning(final_ct, "DDPRevisedCensusTract", "final_census_tracts")
551
+
552
+ # ---- Drop NaNs so only program assignments remain ----------------
553
+ final_cities = final_cities[final_cities["DDPPropertyCityFinal"].notna()].copy()
554
+ final_zips = final_zips[final_zips["DDPPropertyZIPFinal"].notna()].copy()
555
+ final_ct = final_ct[final_ct["DDPRevisedCensusTract"].notna()].copy()
556
+
557
+ # ---- Write the per-category + cluster outputs --------------------
558
+ for d, name in [(final_cities, "final_cities.xlsx"),
559
+ (final_zips, "final_zips.xlsx"),
560
+ (final_ct, "final_census_tracts.xlsx"),
561
+ (cluster_df, "cluster_df.xlsx")]:
562
+ p = out_dir / name
563
+ d.to_excel(p, index=False)
564
+ outputs.append(str(p))
565
+
566
+ # ---- Full output CSV (chunked at 1,000,000 rows) -----------------
567
+ csv_name = f"OutputFile_{replace_threshold}%Threshold_{cluster_threshold}%ClustersRapidFuzz.csv"
568
+ outputs.extend(save_csv_in_parts(original_final_output, csv_name, out_dir, row_limit=1_000_000))
569
+
570
+ log.append(f"Done. {len(outputs)} files ready.")
571
+ gc.collect()
572
+ return "\n".join(log), outputs
573
+
574
+
575
+ # =====================================================================
576
+ # STARTUP HEALTH CHECK
577
+ # =====================================================================
578
+ def _startup_health_check():
579
+ if os.environ.get("SELF_TEST_ON_STARTUP", "1") != "1":
580
+ return
581
+ try:
582
+ print("[startup] " + run_self_test())
583
+ except FileNotFoundError as e:
584
+ # Reference file not configured yet — let the UI load so the user can fix it.
585
+ print(f"[startup] Self-test skipped — safety list unavailable:\n{e}")
586
+ # AssertionError intentionally propagates: a failed self-test fails the boot.
587
+
588
+
589
+ _startup_health_check()
590
+
591
+
592
+ # =====================================================================
593
+ # GRADIO UI (sidebar "Upload Files" layout)
594
+ # =====================================================================
595
+ CSS = """
596
+ #sidebar {background: var(--block-background-fill); border-right: 1px solid var(--border-color-primary);
597
+ padding: 18px 16px; min-width: 270px;}
598
+ #sidebar h3 {margin: 0 0 14px 0; font-size: 1.15rem; font-weight: 700;}
599
+ .step-label {font-size: .82rem; color: var(--body-text-color-subdued); margin: 14px 0 6px 0;}
600
+ #main-title {font-size: 2.2rem; font-weight: 800; margin: 6px 0 18px 0;}
601
+ .info-banner {background: #e8f1fe; color: #1d4ed8; border-radius: 10px;
602
+ padding: 16px 18px; font-size: 1rem; margin-bottom: 18px;}
603
+ """
604
+
605
+ with gr.Blocks() as demo:
606
+ gr.HTML(f"<style>{CSS}</style>")
607
+ with gr.Row():
608
+ # -------- LEFT SIDEBAR: uploads ---------------------------------
609
+ with gr.Column(scale=1, elem_id="sidebar", min_width=270):
610
+ gr.Markdown("### Upload Files")
611
+
612
+ gr.HTML('<div class="step-label">1. Upload Excel Files</div>')
613
+ files_in = gr.File(file_count="multiple", file_types=[".xlsx", ".xls"],
614
+ label="200MB per file • XLSX", show_label=True)
615
+
616
+ gr.HTML('<div class="step-label">2. Upload Reference File (Optional)</div>')
617
+ reference_in = gr.File(file_count="single", file_types=[".xlsx", ".csv"],
618
+ label="200MB per file • XLSX, CSV", show_label=True)
619
+
620
+ with gr.Accordion("Options", open=False):
621
+ blank_flag = gr.Checkbox(
622
+ value=True, label="Strict: blank cities not in the safety list")
623
+ dominant_flag = gr.Checkbox(
624
+ value=True, label="Filter to single most-dominant county")
625
+ clu_thr = gr.Slider(70, 100, value=95, step=1, label="Cluster threshold (%)")
626
+ rep_thr = gr.Slider(50, 100, value=70, step=1, label="Replace-with threshold (%)")
627
+
628
+ run_btn = gr.Button("Run pipeline", variant="primary")
629
+
630
+ # -------- MAIN AREA: title, info, results -----------------------
631
+ with gr.Column(scale=4):
632
+ gr.HTML('<div id="main-title">Subdivision Cluster &amp; FIPS Validation</div>')
633
+ gr.HTML(
634
+ '<div class="info-banner">Please upload your Excel file(s) using the '
635
+ 'sidebar, then click <b>Run pipeline</b>. The reference safety list is '
636
+ 'applied automatically; upload one on the sidebar only to override it for '
637
+ 'a single run.</div>'
638
+ )
639
+ status = gr.Textbox(label="Log", lines=14)
640
+ files_out = gr.File(label="Output files", file_count="multiple")
641
+
642
+ run_btn.click(
643
+ run_pipeline,
644
+ inputs=[files_in, reference_in, blank_flag, dominant_flag, clu_thr, rep_thr],
645
+ outputs=[status, files_out],
646
+ )
647
+
648
+ if __name__ == "__main__":
649
+ demo.launch()
app_simple_ui.py ADDED
@@ -0,0 +1,629 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
45
+ def get_safety_list_path() -> str:
46
+ local_name = os.environ.get("SAFETY_LIST_FILE", DEFAULT_SAFETY_LIST_NAME)
47
+ if Path(local_name).exists():
48
+ return local_name
49
+
50
+ repo_id = os.environ.get("SAFETY_LIST_REPO")
51
+ token = os.environ.get("HF_TOKEN")
52
+ if repo_id and token:
53
+ from huggingface_hub import hf_hub_download
54
+ filename = os.environ.get("SAFETY_LIST_REPO_FILE", local_name)
55
+ return hf_hub_download(
56
+ repo_id=repo_id, filename=filename, repo_type="dataset", token=token
57
+ )
58
+
59
+ raise FileNotFoundError(
60
+ "Safety list not found.\n"
61
+ f" - Commit '{local_name}' into this Space (keep the Space private), OR\n"
62
+ " - Set SAFETY_LIST_REPO + HF_TOKEN to pull it from a private dataset."
63
+ )
64
+
65
+
66
+ _SAFETY_CACHE: dict | None = None
67
+
68
+
69
+ def build_whitelist_from_path(path):
70
+ """Parse a safety-list file (xlsx or csv) into {pairs, cities, rows}."""
71
+ if str(path).lower().endswith(".csv"):
72
+ safety_df = pd.read_csv(path)
73
+ else:
74
+ safety_df = pd.read_excel(path)
75
+ acceptable_cols = [c for c in safety_df.columns if str(c).startswith("Acceptable FIPS")]
76
+
77
+ valid_pairs, valid_cities = set(), set()
78
+ for _, r in safety_df.iterrows():
79
+ c = _norm_city(r["City Name"])
80
+ if c is None:
81
+ continue
82
+ valid_cities.add(c)
83
+ for col in acceptable_cols:
84
+ f = _norm_fips(r[col])
85
+ if f:
86
+ valid_pairs.add(c + "||" + f)
87
+
88
+ return {"pairs": valid_pairs, "cities": valid_cities, "rows": len(safety_df)}
89
+
90
+
91
+ def load_whitelist():
92
+ """Server-side safety list (repo file or private dataset). Cached per process."""
93
+ global _SAFETY_CACHE
94
+ if _SAFETY_CACHE is None:
95
+ _SAFETY_CACHE = build_whitelist_from_path(get_safety_list_path())
96
+ return _SAFETY_CACHE
97
+
98
+
99
+ # =====================================================================
100
+ # NORMALIZATION HELPERS (identical to the notebook)
101
+ # =====================================================================
102
+ PLACEHOLDERS = {"UNDETERMINED CITY", "UNDETERMINED ZIP", "NULL", "NAN", "NONE", ""}
103
+
104
+
105
+ def _norm_city(x):
106
+ if pd.isna(x):
107
+ return None
108
+ return str(x).strip().upper()
109
+
110
+
111
+ def _norm_fips(x):
112
+ """5-digit FIPS string, or None. Handles 28071, 28071.0, '01067', '28071 - LAFAYETTE'."""
113
+ if pd.isna(x):
114
+ return None
115
+ m = re.search(r"\d+", str(x))
116
+ return str(int(m.group(0))).zfill(5) if m else None
117
+
118
+
119
+ # =====================================================================
120
+ # SELF-TEST (startup health check — same logic as the notebook's cell)
121
+ # =====================================================================
122
+ def run_self_test() -> str:
123
+ path = get_safety_list_path()
124
+ st = pd.read_excel(path)
125
+ fc = [c for c in st.columns if str(c).startswith("Acceptable FIPS")]
126
+ pairs = set()
127
+ for _, r in st.iterrows():
128
+ c = _norm_city(r["City Name"])
129
+ if c is None:
130
+ continue
131
+ for col in fc:
132
+ f = _norm_fips(r[col])
133
+ if f:
134
+ pairs.add(c + "||" + f)
135
+
136
+ good_city = st.iloc[0]["City Name"]
137
+ good_fips = st.iloc[0]["Acceptable FIPS 1"]
138
+ test = pd.DataFrame({
139
+ "DDPPropertyCityFinal": [good_city, good_city],
140
+ "** REC FIPS-COUNTY": [good_fips, 99999], # row 2 = wrong FIPS on purpose
141
+ })
142
+ cn = test["DDPPropertyCityFinal"].map(_norm_city)
143
+ fn = test["** REC FIPS-COUNTY"].map(_norm_fips)
144
+ key = cn.fillna("") + "||" + fn.fillna("")
145
+ ok = key.isin(pairs)
146
+ assert bool(ok.iloc[0]) and not bool(ok.iloc[1]), \
147
+ "SELF-TEST FAILED -- matching logic is not working as expected."
148
+ return f"SELF-TEST PASSED: known-good ({good_city}) kept, wrong FIPS flagged."
149
+
150
+
151
+ # =====================================================================
152
+ # STEP 1 — FIPS SAFETY-LIST VALIDATION
153
+ # =====================================================================
154
+ def fips_validate(df: pd.DataFrame, blank_cities_not_in_list: bool, log, wl=None):
155
+ if wl is None:
156
+ wl = load_whitelist()
157
+ valid_pairs, valid_cities = wl["pairs"], wl["cities"]
158
+
159
+ FIPS_COL = "** REC FIPS-COUNTY" if "** REC FIPS-COUNTY" in df.columns else "County"
160
+ CITY_COL, ZIP_COL, TRACT_COL = (
161
+ "DDPPropertyCityFinal", "DDPPropertyZIPFinal", "DDPRevisedCensusTract",
162
+ )
163
+
164
+ city_norm = df[CITY_COL].map(_norm_city)
165
+ fips_norm = df[FIPS_COL].map(_norm_fips)
166
+ row_key = city_norm.fillna("") + "||" + fips_norm.fillna("")
167
+
168
+ is_real_city = df[CITY_COL].notna() & (~city_norm.fillna("").isin(PLACEHOLDERS))
169
+ city_in_list = city_norm.isin(valid_cities)
170
+ pair_ok = row_key.isin(valid_pairs)
171
+
172
+ if blank_cities_not_in_list:
173
+ fails_mask = is_real_city & (~pair_ok)
174
+ else:
175
+ fails_mask = is_real_city & city_in_list & (~pair_ok)
176
+
177
+ n_real = int(is_real_city.sum())
178
+ n_inlist = int((is_real_city & city_in_list).sum())
179
+ n_valid = int((is_real_city & pair_ok).sum())
180
+ n_fail = int(fails_mask.sum())
181
+ log.append(
182
+ f"FIPS validation — list: {wl['rows']:,} rows | {len(valid_cities):,} cities | "
183
+ f"{len(valid_pairs):,} pairs"
184
+ )
185
+ log.append(
186
+ f" real:{n_real:,} in-list:{n_inlist:,} valid-kept:{n_valid:,} blanked:{n_fail:,}"
187
+ )
188
+ if n_real > 0 and n_inlist == 0:
189
+ log.append(" !! 0 cities matched the list — likely a format/spelling mismatch.")
190
+
191
+ # Audit built BEFORE overwrite (insert position matches the notebook).
192
+ key_col = "RecordKey" if "RecordKey" in df.columns else None
193
+ base_cols = [c for c in [key_col, CITY_COL, FIPS_COL, ZIP_COL, TRACT_COL] if c]
194
+ audit = df.loc[fails_mask, base_cols].copy()
195
+ audit.insert(
196
+ len(base_cols) if key_col is None else 2,
197
+ "NormalizedFIPS", fips_norm[fails_mask].values,
198
+ )
199
+ audit["Reason"] = np.where(
200
+ city_in_list[fails_mask].values, "FIPS does not match city", "City not in safety list"
201
+ )
202
+ audit = audit.rename(
203
+ columns={CITY_COL: "OLD_City", ZIP_COL: "OLD_ZIP", TRACT_COL: "OLD_CensusTract"}
204
+ )
205
+
206
+ # Recent pandas reads all-numeric Excel columns as float64 and refuses to
207
+ # accept a string into them; Colab's older pandas silently upcast to object.
208
+ # Cast first so the placeholder write reproduces the notebook's result.
209
+ df[CITY_COL] = df[CITY_COL].astype(object)
210
+ df[ZIP_COL] = df[ZIP_COL].astype(object)
211
+ df.loc[fails_mask, CITY_COL] = "UNDETERMINED CITY"
212
+ df.loc[fails_mask, ZIP_COL] = "UNDETERMINED ZIP"
213
+ df.loc[fails_mask, TRACT_COL] = np.nan
214
+ return df, audit
215
+
216
+
217
+ # =====================================================================
218
+ # STEP 2 — RAPIDFUZZ CLUSTERING (identical to the notebook)
219
+ # =====================================================================
220
+ def group_similar_strings_optimized(strings, threshold=95, prefix_len=3, max_len_diff=3):
221
+ cleaned, seen = [], set()
222
+ for s in strings:
223
+ if pd.isna(s):
224
+ continue
225
+ s = str(s).strip()
226
+ if s and s not in seen:
227
+ cleaned.append(s)
228
+ seen.add(s)
229
+
230
+ visited, groups = set(), []
231
+ buckets = defaultdict(list)
232
+ for s in cleaned:
233
+ buckets[s.upper()[:prefix_len]].append(s)
234
+
235
+ for bucket in buckets.values():
236
+ for i, base in enumerate(bucket):
237
+ if base in visited:
238
+ continue
239
+ group = [base]
240
+ visited.add(base)
241
+ base_upper = base.upper()
242
+ base_len = len(base_upper)
243
+ for j in range(i + 1, len(bucket)):
244
+ compare = bucket[j]
245
+ if compare in visited:
246
+ continue
247
+ comp_upper = compare.upper()
248
+ if abs(base_len - len(comp_upper)) > max_len_diff:
249
+ continue
250
+ if fuzz.ratio(base_upper, comp_upper) >= threshold:
251
+ group.append(compare)
252
+ visited.add(compare)
253
+ groups.append(group)
254
+ return groups
255
+
256
+
257
+ def build_clusters(city_df, zip_df, census_tracts_df, cluster_threshold):
258
+ all_legal = pd.concat(
259
+ [
260
+ city_df[["County", "LegalSubDivision"]],
261
+ zip_df[["County", "LegalSubDivision"]],
262
+ census_tracts_df[["County", "LegalSubDivision"]],
263
+ ],
264
+ ignore_index=True,
265
+ ).dropna(subset=["County", "LegalSubDivision"])
266
+ all_legal["County"] = all_legal["County"].astype(str).str.strip()
267
+ all_legal["LegalSubDivision"] = all_legal["LegalSubDivision"].astype(str).str.strip()
268
+ all_legal = all_legal[(all_legal["County"] != "") & (all_legal["LegalSubDivision"] != "")]
269
+ all_legal = all_legal[["County", "LegalSubDivision"]].drop_duplicates()
270
+
271
+ groups = []
272
+ for county in all_legal["County"].unique():
273
+ strings = all_legal[all_legal["County"] == county]["LegalSubDivision"].tolist()
274
+ groups.extend(
275
+ group_similar_strings_optimized(
276
+ strings, threshold=cluster_threshold, prefix_len=3, max_len_diff=3
277
+ )
278
+ )
279
+
280
+ rows = []
281
+ for cid, group in enumerate(groups, start=1):
282
+ for sub in group:
283
+ rows.append({"Cluster_ID": cid, "LegalSubDivision": sub})
284
+ return pd.DataFrame(rows, columns=["Cluster_ID", "LegalSubDivision"])
285
+
286
+
287
+ # =====================================================================
288
+ # STEP 3 — WIDE TABLES + MAJORITY-VOTE "REPLACE WITH"
289
+ # =====================================================================
290
+ def build_cluster_wide_table(source_df, cluster_df, value_col, prefix):
291
+ lk = cluster_df[["LegalSubDivision", "Cluster_ID"]].drop_duplicates("LegalSubDivision")
292
+ cluster_map = dict(zip(lk["LegalSubDivision"], lk["Cluster_ID"]))
293
+
294
+ w = source_df[["LegalSubDivision", value_col]].copy()
295
+ w["LegalSubDivision"] = w["LegalSubDivision"].astype(str).str.strip()
296
+ w[value_col] = w[value_col].replace("", np.nan)
297
+ w["Cluster_ID"] = w["LegalSubDivision"].map(cluster_map)
298
+ w = w.dropna(subset=["Cluster_ID", value_col])
299
+ if w.empty:
300
+ return pd.DataFrame(columns=["Cluster_ID"])
301
+ w["Cluster_ID"] = w["Cluster_ID"].astype(int)
302
+ w[value_col] = w[value_col].astype(str).str.strip()
303
+ w = w[w[value_col] != ""]
304
+
305
+ counts = w.groupby(["Cluster_ID", value_col], observed=True).size().unstack(fill_value=0)
306
+ totals = counts.sum(axis=1)
307
+ pct = counts.div(totals.replace(0, np.nan), axis=0).mul(100).fillna(0)
308
+ counts.columns = [f"{prefix}{c}_Count" for c in counts.columns]
309
+ pct.columns = [f"{prefix}{c}_Percentage" for c in pct.columns]
310
+ wide = pd.concat([counts, pct], axis=1).reset_index()
311
+
312
+ # Match the notebook: Cluster_ID first, all other columns sorted.
313
+ other = sorted([c for c in wide.columns if c != "Cluster_ID"])
314
+ return wide[["Cluster_ID"] + other]
315
+
316
+
317
+ def build_replace_with(wide_df, prefix_to_remove, threshold):
318
+ pct_cols = [c for c in wide_df.columns if c.endswith("_Percentage")]
319
+ if not pct_cols:
320
+ res = wide_df[["Cluster_ID"]].copy()
321
+ res["Replace with"] = None
322
+ return res.drop_duplicates(subset=["Cluster_ID"])
323
+ labels = np.array(
324
+ [c.replace(prefix_to_remove, "").replace("_Percentage", "") for c in pct_cols],
325
+ dtype=object,
326
+ )
327
+ values = wide_df[pct_cols].to_numpy(copy=False)
328
+ out = []
329
+ for row in values:
330
+ matched = labels[row >= threshold]
331
+ out.append(", ".join(matched) if len(matched) else None)
332
+ res = wide_df[["Cluster_ID"]].copy()
333
+ res["Replace with"] = out
334
+ return res.drop_duplicates(subset=["Cluster_ID"])
335
+
336
+
337
+ def clean_census_tract_suffix(value):
338
+ if pd.isna(value):
339
+ return np.nan
340
+ try:
341
+ f = float(value)
342
+ return str(int(f)) if f == int(f) else str(f)
343
+ except ValueError:
344
+ return str(value)
345
+
346
+
347
+ def clean_zip(value):
348
+ """Normalize ZIPs read from Excel as numbers: drop the float '.0' artifact and
349
+ zero-pad to 5 digits (recovering leading zeros lost on numeric import, e.g.
350
+ 7221.0 -> 07221). Handles comma-joined majority-vote results. ZIP+4 left as-is."""
351
+ if pd.isna(value):
352
+ return np.nan
353
+ out = []
354
+ for part in str(value).split(","):
355
+ p = part.strip()
356
+ if p.endswith(".0"):
357
+ p = p[:-2]
358
+ digits = re.sub(r"\D", "", p)
359
+ if not digits:
360
+ continue
361
+ out.append(digits.zfill(5) if len(digits) <= 5 else digits)
362
+ return ", ".join(out) if out else np.nan
363
+
364
+
365
+ # =====================================================================
366
+ # CHUNKED CSV WRITER (faithful port of save_csv_in_parts)
367
+ # =====================================================================
368
+ def save_csv_in_parts(df, base_filename, out_dir, row_limit=1_000_000):
369
+ base_name = base_filename.replace(".csv", "")
370
+ created = []
371
+ total = len(df)
372
+ num_parts = math.ceil(total / row_limit)
373
+ for i in range(num_parts):
374
+ start = i * row_limit
375
+ end = min((i + 1) * row_limit, total)
376
+ part = f"{base_name}_part_{i + 1}.csv" if num_parts > 1 else base_filename
377
+ p = out_dir / part
378
+ df.iloc[start:end].to_csv(p, index=False)
379
+ created.append(str(p))
380
+ gc.collect()
381
+ return created
382
+
383
+
384
+ # =====================================================================
385
+ # MAIN PIPELINE
386
+ # =====================================================================
387
+ def run_pipeline(uploaded_files, reference_file, blank_cities_not_in_list,
388
+ filter_dominant_county, cluster_threshold, replace_threshold):
389
+ log = []
390
+ if not uploaded_files:
391
+ return "Please upload at least one Excel file.", []
392
+
393
+ out_dir = Path(tempfile.mkdtemp(prefix="subdiv_"))
394
+ outputs = []
395
+
396
+ # ---- Resolve the reference (safety) list -------------------------
397
+ # Default: server-side list (repo file or private dataset). If the user
398
+ # uploads an override on the sidebar, use it for THIS run only.
399
+ try:
400
+ if reference_file is not None:
401
+ wl = build_whitelist_from_path(reference_file.name)
402
+ log.append(f"Using UPLOADED reference list: {Path(reference_file.name).name}")
403
+ else:
404
+ wl = load_whitelist()
405
+ log.append("Using server-side safety list.")
406
+ except FileNotFoundError as e:
407
+ return "\n".join(log) + f"\n\nREFERENCE FILE ERROR:\n{e}", []
408
+ except Exception as e:
409
+ return "\n".join(log) + f"\n\nCould not parse reference list: {e}", []
410
+
411
+ # ---- Load & merge uploads ----------------------------------------
412
+ dfs = []
413
+ for f in uploaded_files:
414
+ try:
415
+ dfs.append(pd.read_excel(f.name))
416
+ log.append(f"Loaded {Path(f.name).name}")
417
+ except Exception as e:
418
+ log.append(f"ERROR loading {Path(f.name).name}: {e}")
419
+ if not dfs:
420
+ return "\n".join(log) + "\nNo files could be read.", []
421
+ df = pd.concat(dfs, ignore_index=True)
422
+ log.append(f"Merged shape: {df.shape}")
423
+
424
+ # ---- FIPS validation (uses the reference list) -------------------
425
+ try:
426
+ df, audit = fips_validate(df, blank_cities_not_in_list, log, wl=wl)
427
+ except FileNotFoundError as e:
428
+ return "\n".join(log) + f"\n\nREFERENCE FILE ERROR:\n{e}", []
429
+
430
+ # ---- Download verification files (audit + RawFile_FIPSValidated) -
431
+ if len(audit) > 0:
432
+ ap = out_dir / "FIPS_Validation_Audit_ChangedRecords.xlsx"
433
+ audit.to_excel(ap, index=False)
434
+ outputs.append(str(ap))
435
+
436
+ if len(df) <= EXCEL_ROW_LIMIT:
437
+ rp = out_dir / "RawFile_FIPSValidated.xlsx"
438
+ df.to_excel(rp, index=False)
439
+ else:
440
+ rp = out_dir / "RawFile_FIPSValidated.csv"
441
+ df.to_csv(rp, index=False)
442
+ outputs.append(str(rp))
443
+
444
+ # ---- UNDETERMINED/NULL -> NaN ------------------------------------
445
+ for col in ["DDPPropertyCityFinal", "DDPPropertyZIPFinal",
446
+ "DDPRevisedCensusTract", "LegalSubDivision"]:
447
+ if col in df.columns:
448
+ df[col] = df[col].replace(["UNDETERMINED CITY", "UNDETERMINED ZIP", "NULL"], np.nan)
449
+
450
+ # ---- Rename FIPS col -> County -----------------------------------
451
+ if "** REC FIPS-COUNTY" in df.columns:
452
+ df = df.rename(columns={"** REC FIPS-COUNTY": "County"})
453
+
454
+ # ---- Optional: filter to single most-dominant county -------------
455
+ if filter_dominant_county:
456
+ dominant = df["County"].value_counts().idxmax()
457
+ df = df[df["County"] == dominant].copy()
458
+ log.append(f"Filtered to dominant county: {dominant} -> {df.shape}")
459
+
460
+ # ---- Source frames -----------------------------------------------
461
+ city_df = df.loc[df["DDPPropertyCityFinal"].notna()].copy()
462
+ zip_df = df.loc[df["DDPPropertyZIPFinal"].notna()].copy()
463
+ census_tracts_df = df.loc[df["DDPRevisedCensusTract"].notna()].copy()
464
+ original = df.loc[df["LegalSubDivision"].notna()].copy()
465
+
466
+ # ---- Cluster ------------------------------------------------------
467
+ cluster_df = build_clusters(city_df, zip_df, census_tracts_df, cluster_threshold)
468
+ log.append(f"Clusters: {cluster_df['Cluster_ID'].nunique():,}")
469
+
470
+ # ---- Replace-with (majority vote) --------------------------------
471
+ zip_w = build_replace_with(
472
+ build_cluster_wide_table(zip_df, cluster_df, "DDPPropertyZIPFinal", "ZIP_"),
473
+ "ZIP_", replace_threshold).rename(columns={"Replace with": "Replace with Zip Codes"})
474
+ city_w = build_replace_with(
475
+ build_cluster_wide_table(city_df, cluster_df, "DDPPropertyCityFinal", "City_"),
476
+ "City_", replace_threshold).rename(columns={"Replace with": "Replace with Cities"})
477
+ cen_w = build_replace_with(
478
+ build_cluster_wide_table(census_tracts_df, cluster_df, "DDPRevisedCensusTract", "CensusTract_"),
479
+ "CensusTract_", replace_threshold).rename(columns={"Replace with": "Replace with Census Tracts"})
480
+
481
+ # ---- Map back onto original --------------------------------------
482
+ lk = cluster_df[["LegalSubDivision", "Cluster_ID"]].drop_duplicates("LegalSubDivision")
483
+ cmap = dict(zip(lk["LegalSubDivision"], lk["Cluster_ID"]))
484
+ original_final = original.copy()
485
+ original_final["Cluster_ID"] = original_final["LegalSubDivision"].map(cmap)
486
+ original_final["Replace with Zip Codes"] = original_final["Cluster_ID"].map(
487
+ dict(zip(zip_w["Cluster_ID"], zip_w["Replace with Zip Codes"])))
488
+ original_final["Replace with Cities"] = original_final["Cluster_ID"].map(
489
+ dict(zip(city_w["Cluster_ID"], city_w["Replace with Cities"])))
490
+ original_final["Replace with Census Tracts"] = original_final["Cluster_ID"].map(
491
+ dict(zip(cen_w["Cluster_ID"], cen_w["Replace with Census Tracts"])))
492
+
493
+ # Normalize ZIPs (drop float '.0', restore 5-digit zero-padding).
494
+ original_final["Replace with Zip Codes"] = (
495
+ original_final["Replace with Zip Codes"].apply(clean_zip))
496
+
497
+ # ---- Reorder columns (desired_leading_columns) -------------------
498
+ desired_leading = [
499
+ "RecordKey", "ComesFromMtg2", "IsFlagged", "Cluster_ID", "LegalSubDivision",
500
+ "County", "Replace with Zip Codes", "Replace with Cities", "Replace with Census Tracts",
501
+ "DDPPropertyZIPFinal", "DDPPropertyCityFinal", "DDPRevisedCensusTract",
502
+ "LotBlockSubdivisionTract", "DDPRevisedLatitude", "DDPRevisedLongitude",
503
+ ]
504
+ existing = original_final.columns.tolist()
505
+ lead = [c for c in desired_leading if c in existing]
506
+ other = [c for c in existing if c not in lead]
507
+ original_final = original_final[lead + other]
508
+
509
+ original_final_output = original_final.copy() # full output snapshot
510
+
511
+ # ---- Split into final cities / zips / census tracts --------------
512
+ keep = ["RecordKey", "ComesFromMtg2", "IsFlagged",
513
+ "Replace with Zip Codes", "Replace with Cities", "Replace with Census Tracts",
514
+ "DDPPropertyZIPFinal", "DDPPropertyCityFinal", "DDPRevisedCensusTract"]
515
+ keep = [c for c in keep if c in original_final.columns]
516
+ of = original_final[keep].rename(columns={
517
+ "DDPPropertyZIPFinal": "DDPPropertyZIPFinalToRemove",
518
+ "DDPPropertyCityFinal": "DDPPropertyCityFinalToRemove",
519
+ "DDPRevisedCensusTract": "DDPRevisedCensusTractToRemove",
520
+ "Replace with Zip Codes": "DDPPropertyZIPFinal",
521
+ "Replace with Cities": "DDPPropertyCityFinal",
522
+ "Replace with Census Tracts": "DDPRevisedCensusTract",
523
+ })
524
+ of["DDPRevisedCensusTract"] = of["DDPRevisedCensusTract"].apply(clean_census_tract_suffix)
525
+
526
+ idcols = [c for c in ["RecordKey", "ComesFromMtg2", "IsFlagged"] if c in of.columns]
527
+ final_cities = of[idcols + ["DDPPropertyCityFinalToRemove", "DDPPropertyCityFinal"]].copy()
528
+ final_zips = of[idcols + ["DDPPropertyZIPFinalToRemove", "DDPPropertyZIPFinal"]].copy()
529
+ final_ct = of[idcols + ["DDPRevisedCensusTractToRemove", "DDPRevisedCensusTract"]].copy()
530
+
531
+ # keep only rows whose ORIGINAL value was blank (the ones we filled)
532
+ final_cities = final_cities[final_cities["DDPPropertyCityFinalToRemove"].isna()].copy()
533
+ final_zips = final_zips[final_zips["DDPPropertyZIPFinalToRemove"].isna()].copy()
534
+ final_ct = final_ct[final_ct["DDPRevisedCensusTractToRemove"].isna()].copy()
535
+
536
+ final_cities = final_cities.drop(columns=["DDPPropertyCityFinalToRemove"])
537
+ final_zips = final_zips.drop(columns=["DDPPropertyZIPFinalToRemove"])
538
+ final_ct = final_ct.drop(columns=["DDPRevisedCensusTractToRemove"])
539
+
540
+ # ---- OnlyBlanks warnings (column entirely null) ------------------
541
+ def only_blanks_warning(d, col, prefix):
542
+ if col in d.columns and d[col].isnull().all():
543
+ p = out_dir / f"OnlyBlanks_{prefix}.xlsx"
544
+ d.to_excel(p, index=False)
545
+ outputs.append(str(p))
546
+ log.append(f"WARNING: {prefix} has only blanks in '{col}' -> {p.name}")
547
+
548
+ only_blanks_warning(final_cities, "DDPPropertyCityFinal", "final_cities")
549
+ only_blanks_warning(final_zips, "DDPPropertyZIPFinal", "final_zips")
550
+ only_blanks_warning(final_ct, "DDPRevisedCensusTract", "final_census_tracts")
551
+
552
+ # ---- Drop NaNs so only program assignments remain ----------------
553
+ final_cities = final_cities[final_cities["DDPPropertyCityFinal"].notna()].copy()
554
+ final_zips = final_zips[final_zips["DDPPropertyZIPFinal"].notna()].copy()
555
+ final_ct = final_ct[final_ct["DDPRevisedCensusTract"].notna()].copy()
556
+
557
+ # ---- Write the per-category + cluster outputs --------------------
558
+ for d, name in [(final_cities, "final_cities.xlsx"),
559
+ (final_zips, "final_zips.xlsx"),
560
+ (final_ct, "final_census_tracts.xlsx"),
561
+ (cluster_df, "cluster_df.xlsx")]:
562
+ p = out_dir / name
563
+ d.to_excel(p, index=False)
564
+ outputs.append(str(p))
565
+
566
+ # ---- Full output CSV (chunked at 1,000,000 rows) -----------------
567
+ csv_name = f"OutputFile_{replace_threshold}%Threshold_{cluster_threshold}%ClustersRapidFuzz.csv"
568
+ outputs.extend(save_csv_in_parts(original_final_output, csv_name, out_dir, row_limit=1_000_000))
569
+
570
+ log.append(f"Done. {len(outputs)} files ready.")
571
+ gc.collect()
572
+ return "\n".join(log), outputs
573
+
574
+
575
+ # =====================================================================
576
+ # STARTUP HEALTH CHECK
577
+ # =====================================================================
578
+ def _startup_health_check():
579
+ if os.environ.get("SELF_TEST_ON_STARTUP", "1") != "1":
580
+ return
581
+ try:
582
+ print("[startup] " + run_self_test())
583
+ except FileNotFoundError as e:
584
+ # Reference file not configured yet — let the UI load so the user can fix it.
585
+ print(f"[startup] Self-test skipped — safety list unavailable:\n{e}")
586
+ # AssertionError intentionally propagates: a failed self-test fails the boot.
587
+
588
+
589
+ _startup_health_check()
590
+
591
+
592
+ # =====================================================================
593
+ # GRADIO UI (simple vertical layout — previous design)
594
+ # =====================================================================
595
+ with gr.Blocks() as demo:
596
+ gr.Markdown(
597
+ "## Subdivision Cluster + FIPS Validation\n"
598
+ "Upload the Excel files to process. Records are validated against the "
599
+ "Subdivision Program Safety List, then `LegalSubDivision` values are "
600
+ "fuzzy-clustered and city/ZIP/census-tract are filled by majority vote.\n\n"
601
+ "*Defaults reproduce the notebook exactly. Change the controls only if you "
602
+ "intend to deviate from it.*"
603
+ )
604
+ files_in = gr.File(file_count="multiple", file_types=[".xlsx", ".xls"],
605
+ label="Excel files to process")
606
+ with gr.Row():
607
+ blank_flag = gr.Checkbox(
608
+ value=True, label="Strict: blank cities not in the safety list")
609
+ dominant_flag = gr.Checkbox(
610
+ value=True, label="Filter to single most-dominant county")
611
+ with gr.Row():
612
+ clu_thr = gr.Slider(70, 100, value=95, step=1, label="Cluster threshold (%)")
613
+ rep_thr = gr.Slider(50, 100, value=70, step=1, label="Replace-with threshold (%)")
614
+ run_btn = gr.Button("Run pipeline", variant="primary")
615
+ status = gr.Textbox(label="Log", lines=14)
616
+ files_out = gr.File(label="Output files", file_count="multiple")
617
+
618
+ def _run_simple(files, blank, dominant, clu, rep):
619
+ # This layout has no reference upload, so always use the server-side list.
620
+ return run_pipeline(files, None, blank, dominant, clu, rep)
621
+
622
+ run_btn.click(
623
+ _run_simple,
624
+ inputs=[files_in, blank_flag, dominant_flag, clu_thr, rep_thr],
625
+ outputs=[status, files_out],
626
+ )
627
+
628
+ if __name__ == "__main__":
629
+ demo.launch()
requirements.txt ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ gradio>=4.0
2
+ pandas>=2.0
3
+ numpy>=1.24
4
+ openpyxl>=3.1
5
+ rapidfuzz>=3.0
6
+ huggingface_hub>=0.23,<1.0
7
+ pydantic>=2.0,<2.11
8
+ fastapi<0.116
9
+ starlette<1.0
10
+ audioop-lts; python_version >= "3.13"