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

Upload app_simple_ui.py

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