Spaces:
Sleeping
Sleeping
File size: 14,714 Bytes
c7d7a61 c6d95d4 c7d7a61 269e581 c7d7a61 269e581 c7d7a61 269e581 11ad40c c7d7a61 269e581 c7d7a61 269e581 c7d7a61 269e581 c7d7a61 11ad40c c7d7a61 269e581 11ad40c 269e581 c6d95d4 5f473ed c6d95d4 88bfacd c6d95d4 269e581 88bfacd c6d95d4 88bfacd 269e581 88bfacd c6d95d4 269e581 c7d7a61 88bfacd 269e581 ca69604 c6d95d4 269e581 c6d95d4 88bfacd c6d95d4 ca69604 c6d95d4 ca69604 c6d95d4 88bfacd c6d95d4 88bfacd c6d95d4 88bfacd c6d95d4 88bfacd c6d95d4 11ad40c c6d95d4 11ad40c c6d95d4 11ad40c 88bfacd c6d95d4 88bfacd c6d95d4 88bfacd 269e581 c6d95d4 88bfacd c6d95d4 269e581 c6d95d4 88bfacd 269e581 11ad40c c6d95d4 11ad40c c6d95d4 11ad40c c6d95d4 11ad40c 5f473ed 11ad40c c7d7a61 269e581 c7d7a61 269e581 c7d7a61 269e581 c6d95d4 269e581 c6d95d4 269e581 c6d95d4 269e581 c6d95d4 c7d7a61 c6d95d4 c7d7a61 c6d95d4 269e581 c6d95d4 269e581 c6d95d4 269e581 c6d95d4 c7d7a61 c6d95d4 adfbf96 c6d95d4 adfbf96 c6d95d4 adfbf96 c6d95d4 adfbf96 c6d95d4 adfbf96 c6d95d4 adfbf96 c6d95d4 269e581 c7d7a61 c6d95d4 c7d7a61 c6d95d4 c7d7a61 5f473ed c6d95d4 5f473ed c6d95d4 c7d7a61 269e581 c6d95d4 c7d7a61 08a8019 c7d7a61 b3aa74f | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 | # 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) |