Spaces:
Sleeping

vb86's picture
Update app.py
b3aa74f verified
Raw History Blame Contribute Delete
14.7 kB
# app.py
import re, json
from collections import defaultdict
import pandas as pd
import gradio as gr
# ---------- Resources ----------
STATES = [
"Andhra Pradesh","Arunachal Pradesh","Assam","Bihar","Chhattisgarh","Goa","Gujarat",
"Haryana","Himachal Pradesh","Jharkhand","Karnataka","Kerala","Madhya Pradesh",
"Maharashtra","Manipur","Meghalaya","Mizoram","Nagaland","Odisha","Punjab",
"Rajasthan","Sikkim","Tamil Nadu","Telangana","Tripura","Uttar Pradesh",
"Uttarakhand","West Bengal","Delhi","Jammu and Kashmir","Ladakh"
]
STATES_LC = [s.lower() for s in STATES]
COMMON_LANDMARK_PREFIXES = ["near", "opp", "opp.", "opposite", "behind", "next to", "beside", "adjacent to", "in front of"]
COMMON_FLAT_WORDS = ["flat","apartment","apt","house","h.no","h no","shop","office","floor","unit","villa","bungalow","plot"]
ROAD_TOKENS = ["road","rd","street","st","lane","marg","sector","sector.","colony","nagar","layout","village","phase","block","plot","lane.","market","chowk","gali","mohalla"]
PINCODE_RE = re.compile(r"\b([1-9][0-9]{5})\b")
PAREN_RE = re.compile(r"[\(\)]")
# ---------- Helpers ----------
def clean_text(s):
if not s:
return ""
s = s.replace("\r", " ").replace("\n", " , ")
s = PAREN_RE.sub("", s)
s = re.sub(r"\s{2,}", " ", s)
return s.strip()
def extract_pincode(text):
m = PINCODE_RE.search(text)
return m.group(1) if m else None
def normalize_parts(text):
parts = [p.strip() for p in re.split(r",|;| - |—|-", text) if p.strip()]
if len(parts) == 1:
s = parts[0]
keywords = COMMON_LANDMARK_PREFIXES + ROAD_TOKENS + ["near","behind","opp","opposite","next to","beside","sector","sector."]
for kw in keywords:
s = re.sub(rf"\b({re.escape(kw)})\b", r"||\1", s, flags=re.IGNORECASE)
parts = [p.strip(" |") for p in s.split("||") if p.strip()]
return parts
def _strip_pin_state_from_fragment(fragment):
"""Remove pincode and (any) state names from a fragment and return cleaned text."""
# remove pin using compiled .sub
f = PINCODE_RE.sub("", fragment).strip()
# remove state names case-insensitively
for s_lc in STATES_LC:
f = re.sub(re.escape(s_lc), "", f, flags=re.IGNORECASE).strip()
f = re.sub(r"[-,:]\s*$", "", f).strip()
return f
# ---------- FIXED: robust city/state extraction ----------
def find_state_city_from_parts(parts, text_lower):
"""
1) prefer extracting city token from the SAME fragment that contains pincode or state.
2) pick the last alphabetic token as city (e.g., Faridabad), not the whole fragment.
3) fallback heuristics unchanged.
Returns (city, state)
"""
state = None
city = None
# explicit state
for s_lc, s in zip(STATES_LC, STATES):
if s_lc in text_lower:
state = s
break
pin = extract_pincode(text_lower)
# 1) If we have a pin fragment, derive city from that fragment
if pin:
for i, p in enumerate(parts):
if pin in p:
cleaned = _strip_pin_state_from_fragment(p)
if cleaned:
# extract alphabetic tokens (split on non-letters), ignore numeric tokens/keywords
tokens = [t for t in re.split(r"[^A-Za-z]+", cleaned) if t.strip()]
# filter out keywords (sector, near, etc.)
tokens = [t for t in tokens if t.lower() not in set(COMMON_LANDMARK_PREFIXES + COMMON_FLAT_WORDS + ROAD_TOKENS)]
if tokens:
# pick last token as the most likely city (e.g., 'Faridabad')
last_tok = tokens[-1]
# sanity check: token length and not a keyword
if len(last_tok) > 1:
city = last_tok.title()
return city, state
# fallback: previous part if it looks city-like
if i - 1 >= 0:
prev = parts[i - 1].strip()
prev_clean = _strip_pin_state_from_fragment(prev)
if prev_clean and not any(pref in prev_clean.lower() for pref in COMMON_LANDMARK_PREFIXES + COMMON_FLAT_WORDS + ROAD_TOKENS):
# pick last token from prev_clean too
toks = [t for t in re.split(r"[^A-Za-z]+", prev_clean) if t.strip()]
if toks:
city = toks[-1].title()
return city, state
break
# 2) If state present, try to pick token immediately before state
if state:
m = re.search(re.escape(state.lower()), text_lower)
if m:
before = text_lower[: m.start()].strip()
cand_parts = [c.strip() for c in re.split(r",|;| - |—|-", before) if c.strip()]
if cand_parts:
candidate = cand_parts[-1]
candidate_clean = _strip_pin_state_from_fragment(candidate)
toks = [t for t in re.split(r"[^A-Za-z]+", candidate_clean) if t.strip()]
if toks:
city = toks[-1].title()
return city, state
# 3) fallback: last part if it looks like a city
if parts:
last = parts[-1]
last_clean = _strip_pin_state_from_fragment(last)
toks = [t for t in re.split(r"[^A-Za-z]+", last_clean) if t.strip()]
if toks and not any(pref in last_clean.lower() for pref in COMMON_LANDMARK_PREFIXES + COMMON_FLAT_WORDS + ROAD_TOKENS):
city = toks[-1].title()
return city, state
return None, state
# ---------- Extractors (unchanged except fine-tuning) ----------
def extract_house(parts, text_lower):
house = None
m = re.search(r"\b(house\s*no\.?\s*\d+\w*|h\.?\s*no\.?\s*\d+\w*|flat\s*\d+\w*|house\s*\d+\w*|plot\s*\d+\w*|plot no\.?\s*\d+\w*)\b", text_lower)
if m:
house = m.group(0)
else:
for p in parts:
if re.search(r"\b(flat|house|h\.?no|plot|shop|unit)\b", p, flags=re.IGNORECASE) and re.search(r"\d+", p):
house = p
break
return house.title() if house else None
def extract_sector(parts, text_lower):
m = re.search(r"\b(sector|sec)\.?\s*([0-9A-Za-z\-]+)\b", text_lower)
if m:
return f"Sector {m.group(2)}"
return None
def extract_block_phase_plot(parts, text_lower):
block = phase = plot = None
m_block = re.search(r"\b(block|blk)\.?\s*([0-9A-Za-z\-]+)\b", text_lower)
m_phase = re.search(r"\b(phase)\.?\s*([0-9A-Za-z\-]+)\b", text_lower)
m_plot = re.search(r"\b(plot)\.?\s*no?\.?\s*([0-9A-Za-z\-]+)\b", text_lower)
if m_block:
block = f"Block {m_block.group(2)}"
if m_phase:
phase = f"Phase {m_phase.group(2)}"
if m_plot:
plot = f"Plot {m_plot.group(2)}"
return block, phase, plot
def extract_landmark(parts, text_lower):
"""
Capture prefix + phrase up to before city/state/pincode.
E.g., 'behind shani dev mandir faridabad' -> 'Behind Shani Dev Mandir'
"""
for p in parts:
for pref in COMMON_LANDMARK_PREFIXES:
if re.search(rf"\b{re.escape(pref)}\b", p, flags=re.IGNORECASE):
# capture from prefix to end, then strip trailing city/state/pin
lm_match = re.search(rf"(\b{re.escape(pref)}\b.*)", p, flags=re.IGNORECASE)
if lm_match:
candidate = lm_match.group(1).strip()
# remove trailing pin/state tokens only (not other words)
candidate = _strip_pin_state_from_fragment(candidate)
return candidate.title() if candidate else None
# fallback: pick parts mentioning temple/hospital/station etc.
for p in parts:
if re.search(r"\b(mandir|temple|hospital|station|metro|mall|bus stand|bus stop|church)\b", p, flags=re.IGNORECASE):
candidate = _strip_pin_state_from_fragment(p)
return candidate.title() if candidate else None
return None
def extract_locality_road(parts, text_lower, city, state):
locality = None
for p in parts:
pl = p.lower()
if any(tok in pl for tok in ROAD_TOKENS):
candidate = PINCODE_RE.sub("", p).strip()
if city and city.lower() in candidate.lower():
candidate = re.sub(re.escape(city), "", candidate, flags=re.IGNORECASE).strip()
if state and state.lower() in candidate.lower():
candidate = re.sub(re.escape(state), "", candidate, flags=re.IGNORECASE).strip()
if candidate:
locality = candidate.title()
break
if not locality and len(parts) >= 2:
candidate = parts[-2]
if not any(pref in candidate.lower() for pref in COMMON_LANDMARK_PREFIXES):
locality = PINCODE_RE.sub("", candidate).strip().title()
return locality
# ---------- Main parser ----------
def parse_address(text):
out = defaultdict(lambda: None)
original = clean_text(text)
out['input'] = original
if not original:
out['notes'] = "Empty input"
out['confidence'] = 0.0
return dict(out)
text_lower = original.lower()
out['pincode'] = extract_pincode(text_lower)
parts = normalize_parts(original)
# city/state early
city, state = find_state_city_from_parts(parts, text_lower)
if state: out['state'] = state
if city: out['city'] = city
out['house'] = extract_house(parts, text_lower)
out['sector'] = extract_sector(parts, text_lower)
block, phase, plot = extract_block_phase_plot(parts, text_lower)
if block: out['block'] = block
if phase: out['phase'] = phase
if plot: out['plot'] = plot
# landmark should be extracted AFTER city candidate is known (so we can strip trailing city if present)
landmark = extract_landmark(parts, text_lower)
out['landmark'] = landmark
out['locality'] = extract_locality_road(parts, text_lower, out.get('city'), out.get('state'))
# building heuristics
building = None
for p in parts:
pl = p.lower()
if p.strip() == "": continue
if out.get('house') and out['house'].lower() in pl: continue
if out.get('landmark') and out['landmark'].lower() in pl: continue
if out.get('city') and out['city'].lower() in pl: continue
if out.get('state') and out['state'].lower() in pl: continue
if PINCODE_RE.search(pl): continue
if any(b in pl for b in ["apartment","apartments","residency","residence","tower","enclave","plaza","complex","colony","society","building","block","bldg"]):
building = p.strip().title(); break
if not building:
for p in parts:
pl = p.lower()
if pl == "" or any(pref in pl for pref in COMMON_LANDMARK_PREFIXES): continue
if out.get('house') and out['house'].lower() in pl: continue
building = p.strip().title(); break
out['building_street'] = building
# ---- CLEAN UP: ensure we only remove the exact city token, and preserve landmark phrase ----
if out.get('city'):
city_tok = out['city']
# pattern to remove whole-word city token (case-insensitive)
city_pat = re.compile(rf"\b{re.escape(city_tok)}\b", flags=re.IGNORECASE)
def _remove_city_but_keep_phrase(val):
if not val: return None
# remove the city token only (not larger spans)
cleaned = city_pat.sub("", val).strip()
# remove trailing separators and normalize spaces
cleaned = re.sub(r"^[,:\-;\s]+|[,:\-;\s]+$", "", cleaned)
cleaned = re.sub(r"\s{2,}", " ", cleaned).strip()
return cleaned.title() if cleaned else None
# Only remove the city token from these fields, preserving everything else
if out.get('landmark'):
out['landmark'] = _remove_city_but_keep_phrase(out['landmark'])
if out.get('locality'):
out['locality'] = _remove_city_but_keep_phrase(out['locality'])
if out.get('building_street'):
out['building_street'] = _remove_city_but_keep_phrase(out['building_street'])
# Confidence
score = 0.0
score += 0.2 if out.get('pincode') else 0.0
score += 0.15 if out.get('city') else 0.0
score += 0.12 if out.get('house') else 0.0
score += 0.12 if out.get('sector') else 0.0
score += 0.12 if out.get('landmark') else 0.0
score += 0.12 if out.get('locality') else 0.0
score += 0.07 if out.get('building_street') else 0.0
out['confidence'] = round(min(score, 1.0), 2)
notes = []
if out.get('pincode'): notes.append(f"pincode:{out['pincode']}")
if out.get('state'): notes.append(f"state:{out['state']}")
if out.get('city'): notes.append(f"city:{out['city']}")
if out.get('house'): notes.append("house_detected")
if out.get('sector'): notes.append("sector_detected")
if out.get('landmark'): notes.append("landmark_detected")
if out.get('locality'): notes.append("locality_detected")
if out.get('building_street'): notes.append("building_detected")
if block: notes.append("block_detected")
if phase: notes.append("phase_detected")
if plot: notes.append("plot_detected")
out['notes'] = "; ".join(notes) if notes else None
return dict(out)
# ---------- UI wrapper ----------
def parse_and_pretty(addr: str):
try:
parsed = parse_address(addr)
if not isinstance(parsed, dict):
parsed = {"result": parsed}
df = pd.DataFrame([{"field": k, "value": v} for k, v in parsed.items()])
return parsed, df
except Exception as e:
err = str(e)
return {"error": err}, pd.DataFrame([{"field":"error","value":err}])
with gr.Blocks(title="Indian Address Parser (Improved)") as demo:
gr.Markdown("# 🧭 Indian Address Parser — Multiline & Comma Support")
gr.Markdown("Paste messy Indian address (multiline or single line) and get structured fields: house, sector, building/street, locality/road, landmark, city, state, pincode.")
with gr.Row():
inp = gr.Textbox(label="Paste address here", placeholder="Shop 2A Greenview Residency Near Gandhi Statue MG Road Mumbai 400001", lines=4)
with gr.Column():
parse_btn = gr.Button("Parse Address")
parsed_json = gr.JSON(label="Parsed JSON")
parsed_table = gr.Dataframe(headers=["field","value"], label="Parsed Fields (table)")
parse_btn.click(fn=parse_and_pretty, inputs=inp, outputs=[parsed_json, parsed_table])
if __name__ == "__main__":
demo.launch(server_name="0.0.0.0", server_port=7860, ssr_mode=False)