Tru2025 commited on
Commit
3a3b874
·
verified ·
1 Parent(s): 2b83496

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +873 -0
app.py ADDED
@@ -0,0 +1,873 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import gradio as gr
3
+ import requests
4
+ import time
5
+ import re
6
+ import pandas as pd
7
+ import numpy as np
8
+ import json
9
+ import os
10
+ from datetime import datetime
11
+
12
+ # --- Areas and MicroMarkets Data ---
13
+ areasData = [
14
+ {"Area": "Central", "MicroMarkets": ["B Venkata Reddy Nagar", "Basavanagudi", "BTM Layout", "Chamrajapet", "Chickpet", "Fraser Town", "Jayamahal", "Jogupalya", "Kempapura Agrahara", "Lakkasandra", "Malleswaram", "Rajajinagar", "Sadashivanagar", "Shanthi Nagar", "Vasanth Nagar", "Vishveshwara Puram"]},
15
+ {"Area": "East", "MicroMarkets": ["A. Narayanapura", "Aavalahalli", "AECS Layout", "Agaram", "Avalahalli", "Balagere", "Bellandur", "Bhoganahalli", "Bidaraguppe", "Brookefield", "Byalahalli", "C V Raman Nagar", "Carmelaram", "Chikkabellandur", "Chikkakannalli", "Choodasandra", "Dodda Nekkundi", "Doddakannelli", "Domlur", "Dommasandra", "Garudachar Palya", "Gattahalli", "Gopasandra", "Gulimangala", "Gunjur", "HAL Airport", "Harlur", "Harohalli", "Hoskote", "HSR Layout", "Hudi", "Huskuru", "Indiranagar", "Indlabele", "K R Puram", "Kachamaranahalli", "Kadubeesanahalli", "Kadugodi", "Kaikondrahalli", "Kannamangala", "Kasvanahalli", "Kodathi", "Koramangala", "Kyalasanahalli", "Mahadevapura", "Marathahalli", "Mullur", "Muthanallur", "Naganathapura", "Neriga", "Panathur", "Rayasandra", "Sadaramangala", "Sarjapura", "Somsundarapalya", "Varthur", "Whitefield"]},
16
+ {"Area": "North", "MicroMarkets": ["Airport City", "Alur", "Bagaluru", "Baiyappanahalli", "Banasavadi", "Bande Bommasandra", "Bidarahalli", "Bileshivale", "Budigere", "Budigere Cross", "Byappanahalli", "Bylakere", "Byrathi", "Cheemasandra", "Chikkabanavara", "Chikkagubbi", "Dasanayakanahalli", "Devanahalli", "Dodda Gubbi", "Doddaballapur", "Gundur", "HBR Layout", "Hebbal", "Hennur", "Hesaraghatta", "Horamavu", "IISC", "Jakkur", "Jalahalli", "Kada agrahara", "Kadugondanahalli", "Kalkere", "Kannuru", "KIADB Park", "Kommasandra", "Kothanur", "Mandur", "Maralakunte", "Margondanahalli", "Mitganahalli", "Nagavara", "Narayanapura", "Nimbekaipura", "Radhakrishna Temple Ward", "Rajanukunte", "Ramamurthy Nagar", "RT Nagar", "Sahakara Nagar", "Thanisandra", "Vaderahalli", "Vidyaranyapura", "Vignana Kendra", "Vijinapura", "Visthar", "Yelahanka", "Yelahanka Satellite Town", "Yerappanahalli"]},
17
+ {"Area": "South", "MicroMarkets": ["Adigondanahalli", "Akshayanagar", "Anekal", "Anjanapura", "Attibele", "Banashankari", "Banashankari 6th Stage", "Bangalore South", "Bannerghatta", "Begur", "Bettadasanpura", "Bilekhalli", "Bommanahalli", "Bommasandra", "Electronic City", "Hemmigepura", "Hulimangala", "J P Nagar", "Jayanagar", "Jigani", "Kaggalipura", "Kengeri", "Kudlu", "Ragihalli", "Rajarajeshwari Nagar", "Uttarahalli"]},
18
+ {"Area": "West", "MicroMarkets": ["Challaghatta", "Gongadipura", "Lakshmipura", "Nagarabhavi", "Nagasandra", "Nelamangala", "Peenya", "Peenya Industrial Area", "Sulivara", "Yeshwantpur"]}
19
+ ]
20
+
21
+ # Configuration - USING GEMINI 1.5 FLASH FOR MICROMARKET EXTRACTION
22
+ EXISTING_COLUMNS = ['Price / sqft', 'Carpet Area', 'Super Built-up Area', 'Floor', 'Unit Configuration', 'Undivided Share (UDS)', 'Address', 'Asset_Type', 'Plot_Area', 'Zone', 'Micromarket']
23
+ GEMINI_API_KEY = "AIzaSyC1FoWG1pH3xQQm7PvofFx_SqrgIhErp8c"
24
+
25
+ # Main extraction API - Gemini 2.5 Flash
26
+ GEMINI_MAIN_URL = f"https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent?key={GEMINI_API_KEY}"
27
+
28
+ # Micromarket extraction API - Gemini 1.5 Flash
29
+ GEMINI_MICROMARKET_URL = f"https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:generateContent?key={GEMINI_API_KEY}"
30
+
31
+ # --- CORE PROCESSING FUNCTIONS ---
32
+
33
+ def process_field_value(text, field_name):
34
+ """
35
+ Universal field processing function - handles all field types
36
+ """
37
+ if not text or str(text).strip() == "" or str(text).upper() in ['NA', 'NULL', 'NAN']:
38
+ return "NA"
39
+
40
+ text = str(text).strip()
41
+
42
+ # Remove field name prefixes
43
+ text = re.sub(rf'^{re.escape(field_name)}[:\s]*', '', text, flags=re.IGNORECASE).strip()
44
+ text = re.sub(r'^[^:]*:\s*', '', text).strip()
45
+
46
+ # Field-specific processing
47
+ if field_name == 'Address':
48
+ return clean_address_field(text)
49
+ elif field_name in ['Carpet Area', 'Super Built-up Area', 'Plot_Area']:
50
+ return process_area_field(text)
51
+ elif field_name == 'Floor':
52
+ match = re.search(r'([0-9]+)', text)
53
+ return match.group(1) if match else "NA"
54
+ elif field_name == 'Unit Configuration':
55
+ return process_configuration_field(text)
56
+ elif field_name == 'Asset_Type':
57
+ return process_asset_type_field(text)
58
+ elif field_name == 'Price / sqft':
59
+ match = re.search(r'₹?\s*([0-9,]+)', text)
60
+ return f"₹{match.group(1)}" if match else "NA"
61
+
62
+ return text if len(text) <= 100 and text.upper() != 'NA' else 'NA'
63
+
64
+ def clean_address_field(raw_address):
65
+ """
66
+ Clean and trim address at Bangalore/Bengaluru + pincode
67
+ """
68
+ if not raw_address or str(raw_address).upper() == "NA":
69
+ return "NA"
70
+
71
+ text = str(raw_address).strip()
72
+ if len(text) < 10:
73
+ return text
74
+
75
+ # Remove junk
76
+ text = re.sub(r'Asset_Type[^|]*|Plot_Area[^|]*|\|.*', '', text, flags=re.IGNORECASE)
77
+
78
+ # Termination patterns
79
+ patterns = [
80
+ r'(.*?(?:bangalore|bengaluru).*?karnataka.*?\d{6})',
81
+ r'(.*?(?:bangalore|bengaluru).*?\d{6})',
82
+ r'(.*?(?:bangalore|bengaluru).*?karnataka)',
83
+ r'(.*?(?:bangalore|bengaluru))(?:\s+bounded|\s+measuring|\s+together|\s+admeasuring|\s+bearing)',
84
+ r'(.*?(?:bangalore|bengaluru))'
85
+ ]
86
+
87
+ for pattern in patterns:
88
+ match = re.search(pattern, text, re.IGNORECASE)
89
+ if match:
90
+ text = match.group(1).strip()
91
+ break
92
+
93
+ # Remove boundary descriptions
94
+ boundary_patterns = [
95
+ r'\s*bounded\s*by.*$', r'\s*measuring.*?(?:sq\.?ft|sq\.?\s*mtrs?).*$',
96
+ r'\s*together\s*with.*$', r'\s*inclusive\s*of.*$', r'\s*admeasuring.*$',
97
+ r'\s*bearing\s*no\..*$', r'\s*with\s*undivided.*$', r'\s*flat\s*measuring.*$'
98
+ ]
99
+
100
+ for pattern in boundary_patterns:
101
+ text = re.sub(pattern, '', text, flags=re.IGNORECASE)
102
+
103
+ # Clean up
104
+ text = re.sub(r'[,\s]+$|^[,\s]+|\s+', ' ', text).strip()
105
+ return text if len(text) >= 5 else "NA"
106
+
107
+ def process_area_field(text):
108
+ """
109
+ Process area fields with unit conversion
110
+ """
111
+ area_match = re.search(r'([0-9.]+)\s*(?:sq\.?\s*)?(ft|mtrs?|meters?|guntas?)', text, re.IGNORECASE)
112
+ if area_match:
113
+ value, unit = float(area_match.group(1)), area_match.group(2).lower()
114
+ if 'mtr' in unit or 'meter' in unit:
115
+ value *= 10.764
116
+ elif 'gunta' in unit:
117
+ value *= 1089
118
+ return f"{value:.0f}"
119
+
120
+ number_match = re.search(r'([0-9.]+)', text)
121
+ return f"{number_match.group(1)}" if number_match else "NA"
122
+
123
+ def process_configuration_field(text):
124
+ """
125
+ Process unit configuration field
126
+ """
127
+ config_patterns = [
128
+ (r'([0-9]+)\s*BHK', lambda m: f"{m.group(1)}BHK"),
129
+ (r'([0-9]+)\s*RK', lambda m: f"{m.group(1)}RK"),
130
+ (r'(Studio)', lambda m: 'Studio'),
131
+ (r'([0-9]+)\s*bed', lambda m: f"{m.group(1)}BHK"),
132
+ ]
133
+
134
+ for pattern, formatter in config_patterns:
135
+ match = re.search(pattern, text, re.IGNORECASE)
136
+ if match:
137
+ return formatter(match)
138
+ return "NA"
139
+
140
+ def process_asset_type_field(text):
141
+ """
142
+ Process asset type field
143
+ """
144
+ asset_types = ['Flat', 'Apartment', 'Villa', 'House', 'Plot', 'Commercial', 'Residential']
145
+ for asset_type in asset_types:
146
+ if asset_type.lower() in text.lower():
147
+ return asset_type
148
+ return "NA"
149
+
150
+ # --- GEMINI API FUNCTIONS ---
151
+
152
+ def test_api_key():
153
+ """Test API key validity"""
154
+ try:
155
+ print("🔑 Testing Gemini API keys...")
156
+ # Test main API
157
+ res = requests.post(GEMINI_MAIN_URL, json={'contents': [{'parts': [{'text': 'test'}]}], 'generationConfig': {'maxOutputTokens': 10}}, timeout=10)
158
+ if res.status_code == 200:
159
+ print("✅ Gemini 2.5 Flash API key working!")
160
+ else:
161
+ print(f"❌ Main API issue: {res.status_code}")
162
+ return False
163
+
164
+ # Test micromarket API
165
+ res = requests.post(GEMINI_MICROMARKET_URL, json={'contents': [{'parts': [{'text': 'test'}]}], 'generationConfig': {'maxOutputTokens': 10}}, timeout=10)
166
+ if res.status_code == 200:
167
+ print("✅ Gemini 1.5 Flash API key working!")
168
+ return True
169
+ else:
170
+ print(f"❌ Micromarket API issue: {res.status_code}")
171
+ return False
172
+ except Exception as e:
173
+ print(f"❌ API test failed: {e}")
174
+ return False
175
+
176
+ def extract_micromarket_and_zone_with_gemini(address):
177
+ """
178
+ Use Gemini 1.5 Flash to extract micromarket and zone from address with ENHANCED PRECISION
179
+ """
180
+ if not address or str(address).upper() == "NA":
181
+ return "NA", "NA"
182
+
183
+ # Create detailed micromarket mapping
184
+ micromarket_zone_mapping = {}
185
+ zone_info = []
186
+
187
+ for area_data in areasData:
188
+ zone = area_data["Area"]
189
+ micromarkets = area_data["MicroMarkets"]
190
+ zone_info.append(f"{zone}: {', '.join(micromarkets)}")
191
+
192
+ for micromarket in micromarkets:
193
+ micromarket_zone_mapping[micromarket] = zone
194
+
195
+ zone_list = '\n'.join(zone_info)
196
+
197
+ prompt = f"""You are an expert in Bangalore real estate geography. Your task is to identify the EXACT micromarket and corresponding zone from the given address.
198
+
199
+ ADDRESS TO ANALYZE: "{address}"
200
+
201
+ COMPLETE MICROMARKET-ZONE MAPPING (YOU MUST CHOOSE FROM THIS LIST ONLY):
202
+
203
+ Central: B Venkata Reddy Nagar, Basavanagudi, BTM Layout, Chamrajapet, Chickpet, Fraser Town, Jayamahal, Jogupalya, Kempapura Agrahara, Lakkasandra, Malleswaram, Rajajinagar, Sadashivanagar, Shanthi Nagar, Vasanth Nagar, Vishveshwara Puram
204
+
205
+ East: A. Narayanapura, Aavalahalli, AECS Layout, Agaram, Avalahalli, Balagere, Bellandur, Bhoganahalli, Bidaraguppe, Brookefield, Byalahalli, C V Raman Nagar, Carmelaram, Chikkabellandur, Chikkakannalli, Choodasandra, Dodda Nekkundi, Doddakannelli, Domlur, Dommasandra, Garudachar Palya, Gattahalli, Gopasandra, Gulimangala, Gunjur, HAL Airport, Harlur, Harohalli, Hoskote, HSR Layout, Hudi, Huskuru, Indiranagar, Indlabele, K R Puram, Kachamaranahalli, Kadubeesanahalli, Kadugodi, Kaikondrahalli, Kannamangala, Kasvanahalli, Kodathi, Koramangala, Kyalasanahalli, Mahadevapura, Marathahalli, Mullur, Muthanallur, Naganathapura, Neriga, Panathur, Rayasandra, Sadaramangala, Sarjapura, Somsundarapalya, Varthur, Whitefield
206
+
207
+ North: Airport City, Alur, Bagaluru, Baiyappanahalli, Banasavadi, Bande Bommasandra, Bidarahalli, Bileshivale, Budigere, Budigere Cross, Byappanahalli, Bylakere, Byrathi, Cheemasandra, Chikkabanavara, Chikkagubbi, Dasanayakanahalli, Devanahalli, Dodda Gubbi, Doddaballapur, Gundur, HBR Layout, Hebbal, Hennur, Hesaraghatta, Horamavu, IISC, Jakkur, Jalahalli, Kada agrahara, Kadugondanahalli, Kalkere, Kannuru, KIADB Park, Kommasandra, Kothanur, Mandur, Maralakunte, Margondanahalli, Mitganahalli, Nagavara, Narayanapura, Nimbekaipura, Radhakrishna Temple Ward, Rajanukunte, Ramamurthy Nagar, RT Nagar, Sahakara Nagar, Thanisandra, Vaderahalli, Vidyaranyapura, Vignana Kendra, Vijinapura, Visthar, Yelahanka, Yelahanka Satellite Town, Yerappanahalli
208
+
209
+ South: Adigondanahalli, Akshayanagar, Anekal, Anjanapura, Attibele, Banashankari, Banashankari 6th Stage, Bangalore South, Bannerghatta, Begur, Bettadasanpura, Bilekhalli, Bommanahalli, Bommasandra, Electronic City, Hemmigepura, Hulimangala, J P Nagar, Jayanagar, Jigani, Kaggalipura, Kengeri, Kudlu, Ragihalli, Rajarajeshwari Nagar, Uttarahalli
210
+
211
+ West: Challaghatta, Gongadipura, Lakshmipura, Nagarabhavi, Nagasandra, Nelamangala, Peenya, Peenya Industrial Area, Sulivara, Yeshwantpur
212
+
213
+ 🎯 CRITICAL ZONE AND MICROMARKET RULES (MUST FOLLOW):
214
+ 1. **BEGUR** is in **SOUTH** zone (NOT North or East)
215
+ 2. **HSR Layout** is in **EAST** zone
216
+ 3. **Electronic City** is in **SOUTH** zone
217
+ 4. **Whitefield** is in **EAST** zone
218
+ 5. **Hebbal** is in **NORTH** zone
219
+ 6. **Koramangala** is in **EAST** zone
220
+ 7. **Malleswaram** is in **CENTRAL** zone
221
+ 8. **Banashankari** is in **SOUTH** zone
222
+ 9. **Indiranagar** is in **EAST** zone
223
+ 10. **Jayanagar** is in **SOUTH** zone
224
+
225
+ ANALYSIS INSTRUCTIONS:
226
+ 1. Look for EXACT micromarket names from the list above
227
+ 2. Handle common variations (e.g., "HSR" = "HSR Layout", "Koramangla" = "Koramangala")
228
+ 3. Check for Village/Hobli names that might match micromarket names
229
+ 4. Consider project names, nearby landmarks, or area descriptions
230
+ 5. If no exact match found, extract the most specific location name from the address
231
+
232
+ EXAMPLES OF CORRECT MAPPINGS:
233
+ - "Begur Hobli" or "Begur Village" → Micromarket: Begur, Zone: South
234
+ - "HSR Layout" or "HSR" → Micromarket: HSR Layout, Zone: East
235
+ - "Electronic City Phase 1" → Micromarket: Electronic City, Zone: South
236
+ - "Koramangala 5th Block" → Micromarket: Koramangala, Zone: East
237
+ - "Whitefield Main Road" → Micromarket: Whitefield, Zone: East
238
+ - "Hebbal Lake" → Micromarket: Hebbal, Zone: North
239
+
240
+ If you cannot find a confident match from the predefined list, extract the most specific local area name from the address (like Village name, Hobli name, or locality) and set Zone to "NA".
241
+
242
+ RESPONSE FORMAT (EXACTLY):
243
+ Micromarket: [exact name from list above OR local area name if no match]
244
+ Zone: [Central/East/North/South/West OR NA if no match]
245
+ """
246
+
247
+ try:
248
+ response = requests.post(GEMINI_MICROMARKET_URL, json={
249
+ 'contents': [{'parts': [{'text': prompt}]}],
250
+ 'generationConfig': {'temperature': 0.1, 'maxOutputTokens': 150}
251
+ }, timeout=25)
252
+
253
+ if response.status_code == 200:
254
+ response_json = response.json()
255
+
256
+ # Extract response text
257
+ response_text = ""
258
+ candidate = response_json['candidates'][0]
259
+
260
+ # Handle different response structures
261
+ content = candidate.get('content', {})
262
+ if isinstance(content, dict) and 'parts' in content:
263
+ if len(content['parts']) > 0 and 'text' in content['parts'][0]:
264
+ response_text = content['parts'][0]['text']
265
+
266
+ if response_text:
267
+ # Parse micromarket and zone from response
268
+ micromarket_match = re.search(r'Micromarket:\s*(.+)', response_text, re.IGNORECASE)
269
+ zone_match = re.search(r'Zone:\s*(.+)', response_text, re.IGNORECASE)
270
+
271
+ micromarket = micromarket_match.group(1).strip() if micromarket_match else "NA"
272
+ zone = zone_match.group(1).strip() if zone_match else "NA"
273
+
274
+ # Clean up extracted values
275
+ micromarket = re.sub(r'[,\n\r\s]+$', '', micromarket).strip()
276
+ zone = re.sub(r'[,\n\r\s]+$', '', zone).strip()
277
+
278
+ # Validate micromarket is in our list
279
+ all_micromarkets = []
280
+ for area_data in areasData:
281
+ all_micromarkets.extend(area_data["MicroMarkets"])
282
+
283
+ # If micromarket is not in our predefined list, keep it as local area name
284
+ if micromarket not in all_micromarkets:
285
+ # Keep the extracted local area name
286
+ zone = "NA" # Set zone to NA if micromarket not in predefined list
287
+
288
+ # Validate zone
289
+ if zone not in ['Central', 'East', 'North', 'South', 'West']:
290
+ zone = "NA"
291
+
292
+ # Double check zone matches micromarket (only if micromarket is in our list)
293
+ if micromarket in all_micromarkets and zone != "NA":
294
+ expected_zone = micromarket_zone_mapping.get(micromarket)
295
+ if expected_zone and expected_zone != zone:
296
+ zone = expected_zone # Correct the zone based on micromarket
297
+
298
+ return micromarket, zone
299
+ else:
300
+ return "NA", "NA"
301
+ else:
302
+ print(f" ❌ Micromarket API Error: {response.status_code}")
303
+ return "NA", "NA"
304
+
305
+ except Exception as e:
306
+ print(f" ❌ Gemini micromarket extraction error: {e}")
307
+ return "NA", "NA"
308
+
309
+ def clean_extracted_value(value):
310
+ """Clean extracted values from Gemini response"""
311
+ if not value:
312
+ return 'NA'
313
+
314
+ value = str(value).strip()
315
+
316
+ # Remove bullet points and dashes
317
+ value = re.sub(r'^[\-•*]\s*', '', value)
318
+
319
+ # Remove trailing commas, newlines, and extra spaces
320
+ value = re.sub(r'[,\n\r\s]+$', '', value)
321
+
322
+ # Remove leading/trailing quotes
323
+ value = value.strip('"\'')
324
+
325
+ # If empty after cleaning, return NA
326
+ if not value or value.upper() == 'NA':
327
+ return 'NA'
328
+
329
+ return value
330
+
331
+ def process_with_gemini(descriptions, contexts, max_rows):
332
+ """
333
+ Process data with Gemini 2.5 Flash API including retry logic
334
+ """
335
+ if not test_api_key():
336
+ print("❌ Skipping Gemini processing due to API issues")
337
+ return [{col: 'NA' for col in EXISTING_COLUMNS} for _ in descriptions]
338
+
339
+ results = []
340
+
341
+ for i, (desc, ctx) in enumerate(zip(descriptions[:max_rows], contexts[:max_rows])):
342
+ print(f"🔄 Processing {i+1}/{max_rows} ({(i+1)/max_rows*100:.1f}%)...")
343
+
344
+ existing_info = '\n'.join(f"{f}: {v}" for f, v in ctx.items()) or 'No existing data'
345
+
346
+ # FIXED PROMPT with corrected rules and examples
347
+ full_prompt = f"""Extract real estate data from this auction description:
348
+
349
+ EXISTING: {existing_info}
350
+ DESCRIPTION: "{desc}"
351
+
352
+ Extract and format the following fields EXACTLY as shown below. If a field already has accurate information above, you may keep it, but verify and correct if needed:
353
+
354
+ Price / sqft: [value with ₹ symbol if mentioned]
355
+ Carpet Area: [area value only, no units]
356
+ Super Built-up Area: [area value only, no units]
357
+ Floor: [number only]
358
+ Unit Configuration: [like 2BHK, 3BHK, 1RK, Studio]
359
+ Undivided Share (UDS): [UDS details]
360
+ Address: [CLEAN ADDRESS - STOP at Bangalore/Bengaluru + pincode]
361
+ Asset_Type: [Flat/Apartment/Villa/House/Plot/Commercial/Residential]
362
+ Plot_Area: [area with sq.ft units - for plots only, NA for flats]
363
+
364
+ CRITICAL RULES FOR CARPET AREA VS SUPER BUILT-UP AREA:
365
+ 1. **Carpet Area**: The ACTUAL USABLE area of the property (excluding walls, balconies, common areas)
366
+ 2. **Super Built-up Area**: The TOTAL area including proportionate share of common areas, balconies, corridors, lifts
367
+ 3. **IMPORTANT**: Carpet Area is ALWAYS SMALLER than Super Built-up Area
368
+ 4. **When both are mentioned**: Extract each value to its correct field - DO NOT swap them
369
+ 5. **Area calculation priority**: If text says "Carpet Area X sq mtrs" and "Super Built Up Area Y sq mtrs", then:
370
+ - Carpet Area = X (converted to sq.ft)
371
+ - Super Built-up Area = Y (converted to sq.ft)
372
+
373
+ ADDITIONAL RULES:
374
+ 1. Use EXACTLY the field names shown above (with spaces & capitalization)
375
+ 2. For Address: STOP at "Bangalore"/"Bengaluru" + optional pincode. DO NOT include "Bounded by", "Measuring", "Together with", "Admeasuring", or boundary descriptions
376
+ 3. For FLATS/APARTMENTS: Plot_Area = NA
377
+ 4. For PLOTS: Extract plot/land area, Carpet Area and Super Built-up Area = NA
378
+ 5. Convert units: sq mtrs to sq.ft (×10.764), guntas to sq.ft (×1089)
379
+ 6. If information is not clearly mentioned, write "NA"
380
+
381
+ Example 1 - CORRECT Carpet vs Super Built-up Processing:
382
+ Input: "Flat No. T8-1304, Carpet Area Admeasuring About 75.74 Sq Mtrs, Super Built Up Area 111.81 Sq.Mtrs, Purva Zenium, Hosahalli Village, Bangalore 562157"
383
+ Correct Response:
384
+ Price / sqft: NA
385
+ Carpet Area: 815
386
+ Super Built-up Area: 1204
387
+ Floor: 13
388
+ Unit Configuration: NA
389
+ Undivided Share (UDS): NA
390
+ Address: Purva Zenium, Hosahalli Village, Bangalore 562157
391
+ Asset_Type: Flat
392
+ Plot_Area: NA
393
+
394
+ Example 2 - Address Termination:
395
+ Input: "Site no 11, Assessment no 2, Situated at Soladevanhalli Village, Hesaraghatta Hobli, New Yelahanka Taluk, Bangalore North Taluk, Bangalore, Karnataka, 560088 Bounded by East-Property belongs to Jajuraiah, West-Road..."
396
+ Correct Address: "Site no 11, Assessment no 2, Soladevanhalli Village, Hesaraghatta Hobli, New Yelahanka Taluk, Bangalore, Karnataka, 560088"
397
+
398
+ Example 3 - Plot Processing:
399
+ Input: "Plot measuring 20 guntas or 21,780 sq. ft at Sy.no. 11/7 situated at Kammanahalli, Begur Hobli, Bangalore South Taluk"
400
+ Correct Response:
401
+ Price / sqft: NA
402
+ Carpet Area: NA
403
+ Super Built-up Area: NA
404
+ Floor: NA
405
+ Unit Configuration: NA
406
+ Undivided Share (UDS): NA
407
+ Address: Sy.no. 11/7 Kammanahalli, Begur Hobli, Bangalore
408
+ Asset_Type: Plot
409
+ Plot_Area: 21780 sq.ft
410
+
411
+ Example 4 - CORRECTED Complete Processing:
412
+ Input: "Residential Apartment Bearing No. 17192, Situated On 19 Floor/Level, Flat Measuring 977 Sq. Ft. Of Carpet Area And 1376 Sq.Ft. Of Super Built Up Area, Undivided Share, Prestige Song Of The South, Chandrashekharapura Village, Begur Hobli, Bangalore South Taluk, Bengaluru Karnataka- 560068"
413
+ Correct Response:
414
+ Price / sqft: NA
415
+ Carpet Area: 977
416
+ Super Built-up Area: 1376
417
+ Floor: 19
418
+ Unit Configuration: NA
419
+ Undivided Share (UDS): 1376 sq.ft
420
+ Address: Prestige Song Of The South, Chandrashekharapura Village, Begur Hobli, Bangalore South Taluk, Bengaluru Karnataka- 560068
421
+ Asset_Type: Apartment
422
+ Plot_Area: NA
423
+
424
+ RESPONSE FORMAT (use exactly this format):
425
+ Price / sqft: [value]
426
+ Carpet Area: [value]
427
+ Super Built-up Area: [value]
428
+ Floor: [value]
429
+ Unit Configuration: [value]
430
+ Undivided Share (UDS): [value]
431
+ Address: [value]
432
+ Asset_Type: [value]
433
+ Plot_Area: [value]
434
+ """
435
+
436
+ # Shorter prompt for retry attempts
437
+ short_prompt = f"""Extract real estate data from: "{desc}"
438
+
439
+ Extract these fields EXACTLY:
440
+ Price / sqft: [₹ value if mentioned]
441
+ Carpet Area: [SMALLER usable area value only, no units]
442
+ Super Built-up Area: [LARGER total area value only, no units]
443
+ Floor: [number only]
444
+ Unit Configuration: [2BHK, 3BHK, 1RK, Studio]
445
+ Undivided Share (UDS): [UDS details]
446
+ Address: [STOP at Bangalore/Bengaluru + pincode - NO boundary descriptions]
447
+ Asset_Type: [Flat/Apartment/Villa/House/Plot/Commercial/Residential]
448
+ Plot_Area: [for plots only, NA for flats]
449
+
450
+ CRITICAL: Carpet Area < Super Built-up Area. Don't swap them. Convert sq mtrs×10.764, guntas×1089."""
451
+
452
+ # Retry logic
453
+ for attempt in range(3):
454
+ try:
455
+ # Use shorter prompt on retry attempts
456
+ current_prompt = short_prompt if attempt > 0 else full_prompt
457
+
458
+ response = requests.post(GEMINI_MAIN_URL, json={
459
+ 'contents': [{'parts': [{'text': current_prompt}]}],
460
+ 'generationConfig': {'temperature': 0.1, 'maxOutputTokens': 4096}
461
+ }, timeout=30)
462
+
463
+ if response.status_code == 200:
464
+ response_json = response.json()
465
+
466
+ # Handle different response structures for Gemini 2.5 Flash
467
+ response_text = ""
468
+
469
+ # Check for finish reason first
470
+ candidate = response_json['candidates'][0]
471
+ finish_reason = candidate.get('finishReason', '')
472
+
473
+ if finish_reason == 'MAX_TOKENS':
474
+ print(f" ⚠️ Hit token limit - trying shorter prompt (attempt {attempt+1}/3)...")
475
+ continue
476
+ elif finish_reason == 'SAFETY':
477
+ print(f" ⚠️ Response blocked for safety - skipping...")
478
+ results.append({col: 'NA' for col in EXISTING_COLUMNS})
479
+ break
480
+
481
+ try:
482
+ content = candidate.get('content', {})
483
+
484
+ # Try different parsing approaches for Gemini 2.5 Flash
485
+ if isinstance(content, dict) and 'parts' in content and isinstance(content['parts'], list):
486
+ if len(content['parts']) > 0 and 'text' in content['parts'][0]:
487
+ response_text = content['parts'][0]['text']
488
+
489
+ except Exception as e:
490
+ print(f" ❌ Parsing failed: {e}")
491
+ if attempt < 2:
492
+ continue
493
+ else:
494
+ results.append({col: 'NA' for col in EXISTING_COLUMNS})
495
+ break
496
+
497
+ if not response_text:
498
+ print(f" ❌ Could not extract text from response")
499
+ if attempt < 2:
500
+ continue
501
+ else:
502
+ results.append({col: 'NA' for col in EXISTING_COLUMNS})
503
+ break
504
+
505
+ # Process extracted fields (excluding Zone and Micromarket)
506
+ extracted = {}
507
+ for field in EXISTING_COLUMNS:
508
+ if field not in ['Zone', 'Micromarket']: # Skip these, handled separately
509
+ pattern = rf"{re.escape(field)}\s*:\s*(.+?)(?=\n[A-Z]|$)"
510
+ match = re.search(pattern, response_text, re.IGNORECASE | re.DOTALL)
511
+ if match:
512
+ value = match.group(1).strip()
513
+ value = clean_extracted_value(value)
514
+ extracted[field] = process_field_value(value, field)
515
+ else:
516
+ extracted[field] = 'NA'
517
+ else:
518
+ extracted[field] = 'NA' # Will be filled by dedicated micromarket extraction
519
+
520
+ results.append(extracted)
521
+ asset_type = extracted.get('Asset_Type', 'NA')
522
+ config = extracted.get('Unit Configuration', 'NA')
523
+ carpet_area = extracted.get('Carpet Area', 'NA')
524
+ super_area = extracted.get('Super Built-up Area', 'NA')
525
+ print(f" ✓ {asset_type} | {config} | Carpet: {carpet_area} | Super: {super_area}")
526
+ break
527
+
528
+ elif response.status_code == 503:
529
+ wait_time = 15 * (attempt + 1)
530
+ print(f" ⚠️ Service Unavailable - Retry {attempt+1}/3 in {wait_time}s...")
531
+ time.sleep(wait_time)
532
+
533
+ else:
534
+ print(f" ❌ API Error: {response.status_code}")
535
+ results.append({col: 'NA' for col in EXISTING_COLUMNS})
536
+ break
537
+
538
+ except Exception as e:
539
+ print(f" ❌ Error: {e}")
540
+ results.append({col: 'NA' for col in EXISTING_COLUMNS})
541
+ break
542
+ else:
543
+ # If all retries failed
544
+ results.append({col: 'NA' for col in EXISTING_COLUMNS})
545
+
546
+ # Rate limiting
547
+ if i < max_rows - 1:
548
+ time.sleep(2)
549
+
550
+ return results
551
+
552
+ # --- DATA CLEANING ---
553
+
554
+ def clean_overlapping_data(df):
555
+ """
556
+ Clean overlapping data and add missing columns
557
+ """
558
+ print("🧹 CLEANING: Separating overlapping fields...")
559
+
560
+ # Add missing columns
561
+ for col in EXISTING_COLUMNS:
562
+ if col not in df.columns:
563
+ df[col] = ""
564
+ print(f"✅ Added {col} column")
565
+
566
+ # Ensure all columns are object type
567
+ for col in EXISTING_COLUMNS:
568
+ if col in df.columns:
569
+ df[col] = df[col].astype(object)
570
+
571
+ # Process each row
572
+ for idx, row in df.iterrows():
573
+ if idx % 50 == 0:
574
+ print(f" Processing row {idx}...")
575
+
576
+ # Clean overlapping fields
577
+ cleaned_data = {}
578
+ for field_name in EXISTING_COLUMNS:
579
+ if field_name in row.index:
580
+ original_value = str(row[field_name]) if pd.notna(row[field_name]) else ""
581
+ cleaned_data[field_name] = process_field_value(original_value, field_name)
582
+
583
+ # Handle special overlaps
584
+ # 1. Carpet Area containing Super Built-up Area
585
+ carpet_text = str(row.get('Carpet Area', ''))
586
+ if 'Super Built-up Area:' in carpet_text:
587
+ super_match = re.search(r'Super\s*(?:Built-up\s*)?Area[:\s]*([^\\n\\r]+)', carpet_text, re.IGNORECASE)
588
+ if super_match:
589
+ cleaned_data['Super Built-up Area'] = process_field_value(super_match.group(1), 'Super Built-up Area')
590
+ cleaned_data['Carpet Area'] = process_field_value(re.sub(r'\\n.*|Super.*', '', carpet_text), 'Carpet Area')
591
+
592
+ # 2. Asset_Type containing Plot_Area
593
+ asset_text = str(row.get('Asset_Type', ''))
594
+ if 'Plot_Area:' in asset_text:
595
+ plot_match = re.search(r'Plot[_\s]*Area[:\s]*([^\\n\\r]+)', asset_text, re.IGNORECASE)
596
+ if plot_match:
597
+ cleaned_data['Plot_Area'] = process_field_value(plot_match.group(1), 'Plot_Area')
598
+ cleaned_data['Asset_Type'] = process_field_value(re.sub(r'\\n.*|Plot.*', '', asset_text), 'Asset_Type')
599
+
600
+ # Update dataframe
601
+ for field_name, clean_value in cleaned_data.items():
602
+ if field_name in df.columns:
603
+ df.at[idx, field_name] = clean_value
604
+
605
+ print("✅ Data cleaning completed")
606
+ return df
607
+
608
+ # --- MAIN PROCESSING FUNCTION FOR GRADIO ---
609
+
610
+ def process_real_estate_data(file, max_rows, progress=gr.Progress()):
611
+ """Main processing function for Gradio with ALL original logic preserved"""
612
+
613
+ if file is None:
614
+ return None, "❌ Please upload an Excel file"
615
+
616
+ try:
617
+ # Step 1: Read into DataFrame
618
+ progress(0.05, desc="Reading Excel file...")
619
+ df = pd.read_excel(file.name)
620
+
621
+ if 'auction_description' not in df.columns:
622
+ return None, "❌ Error: 'auction_description' column not found in the file"
623
+
624
+ total_rows = len(df)
625
+ max_rows = min(max_rows, total_rows)
626
+
627
+ # Display Excel structure
628
+ log_output = f"""Excel structure:
629
+ Columns: {df.columns.tolist()}
630
+ Total rows: {len(df)}
631
+ Total columns: {len(df.columns)}
632
+ Processing {max_rows} rows...
633
+
634
+ """
635
+
636
+ progress(0.1, desc="Cleaning overlapping data...")
637
+
638
+ # Step 1: Clean overlapping data
639
+ df_cleaned = clean_overlapping_data(df)
640
+
641
+ # Step 2: Process with Gemini 2.5 Flash (main extraction)
642
+ progress(0.2, desc="Starting Gemini 2.5 Flash processing...")
643
+ log_output += f"\n🤖 STARTING GEMINI 2.5 FLASH PROCESSING FOR {max_rows} ROWS...\n"
644
+ log_output += f"📝 Note: Zone and Micromarket will be extracted separately using Gemini 1.5 Flash\n"
645
+ log_output += f"🔧 FIXED: Carpet Area and Super Built-up Area swapping issue resolved\n"
646
+
647
+ descriptions = [str(row['auction_description']) for _, row in df_cleaned.head(max_rows).iterrows()]
648
+ contexts = []
649
+
650
+ for idx, row in df_cleaned.head(max_rows).iterrows():
651
+ ctx = {}
652
+ for col in EXISTING_COLUMNS:
653
+ if col in df_cleaned.columns:
654
+ value = row[col]
655
+ if pd.notna(value) and str(value).strip() != "" and str(value).upper() not in ['NA', 'NULL']:
656
+ ctx[col] = value
657
+ contexts.append(ctx)
658
+
659
+ gemini_results = process_with_gemini(descriptions, contexts, max_rows)
660
+
661
+ # Step 3: Update dataframe with main extraction results
662
+ progress(0.5, desc="Updating main extraction results...")
663
+ log_output += f"\n📝 Updating main extraction results...\n"
664
+
665
+ for i, result in enumerate(gemini_results):
666
+ for col, new_value in result.items():
667
+ if col in df_cleaned.columns and new_value != 'NA':
668
+ current_value = df_cleaned.at[i, col]
669
+
670
+ # Special handling for critical fields - always update if Gemini extracted a valid value
671
+ critical_fields = ['Carpet Area', 'Super Built-up Area', 'Address', 'Asset_Type', 'Floor', 'Unit Configuration']
672
+
673
+ if col in critical_fields:
674
+ # Always update critical fields with Gemini results
675
+ df_cleaned.at[i, col] = new_value
676
+ if i < 5: # Debug first 5 rows
677
+ log_output += f" Row {i+1}: Updated {col} = {new_value}\n"
678
+ else:
679
+ # For other fields, only update if current value is empty/NA
680
+ if (pd.isna(current_value) or str(current_value).strip() == '' or str(current_value).upper() in ['NA', 'NULL']):
681
+ df_cleaned.at[i, col] = new_value
682
+
683
+ # Step 4: Extract Zone and Micromarket using Gemini 1.5 Flash (ENHANCED PRECISION)
684
+ progress(0.6, desc="Extracting zones and micromarkets...")
685
+ log_output += f"\n🗺️ EXTRACTING ZONES AND MICROMARKETS WITH GEMINI 1.5 FLASH FOR {max_rows} ROWS...\n"
686
+ log_output += "📍 Using enhanced rules for precise mapping...\n"
687
+ log_output += "🎯 Key Rules: Begur→South, HSR Layout→East, Electronic City→South, Whitefield→East, Hebbal→North\n"
688
+
689
+ for idx in range(min(max_rows, len(df_cleaned))):
690
+ if idx % 5 == 0: # Update progress every 5 rows
691
+ progress(0.6 + 0.25 * (idx / max_rows), desc=f"Processing address {idx+1}/{max_rows}...")
692
+
693
+ log_output += f"🔍 Processing address {idx+1}/{max_rows}...\n"
694
+
695
+ # Get the cleaned address
696
+ address = df_cleaned.at[idx, 'Address']
697
+
698
+ # Use Gemini 1.5 Flash to extract micromarket and zone with enhanced precision
699
+ micromarket, zone = extract_micromarket_and_zone_with_gemini(address)
700
+
701
+ # Update dataframe
702
+ df_cleaned.at[idx, 'Micromarket'] = micromarket
703
+ df_cleaned.at[idx, 'Zone'] = zone
704
+
705
+ # Display result
706
+ if micromarket != "NA" and zone != "NA":
707
+ log_output += f" ✅ {micromarket} → {zone}\n"
708
+ elif micromarket != "NA" and zone == "NA":
709
+ log_output += f" ⚠️ Local Area: {micromarket} (not in predefined list)\n"
710
+ else:
711
+ log_output += f" ⚠️ Could not determine micromarket/zone from address\n"
712
+
713
+ # Rate limiting for API calls
714
+ if idx < max_rows - 1:
715
+ time.sleep(1.5)
716
+
717
+ # Step 5: Final address cleaning
718
+ progress(0.85, desc="Final address cleaning...")
719
+ log_output += f"\n🧹 Final address cleaning for {max_rows} rows...\n"
720
+
721
+ for idx in range(min(max_rows, len(df_cleaned))):
722
+ address = df_cleaned.at[idx, 'Address']
723
+ clean_address = process_field_value(address, 'Address')
724
+ df_cleaned.at[idx, 'Address'] = clean_address
725
+
726
+ # Step 6: Results validation and display
727
+ progress(0.9, desc="Validating results...")
728
+ log_output += f"\n=== VALIDATION & FINAL RESULTS FOR {max_rows} ROWS ===\n"
729
+ log_output += "🔍 Checking zone-micromarket accuracy...\n"
730
+
731
+ # Validate zone-micromarket mapping
732
+ for i in range(min(max_rows, len(df_cleaned))):
733
+ micromarket = df_cleaned.at[i, 'Micromarket']
734
+ zone = df_cleaned.at[i, 'Zone']
735
+
736
+ if micromarket != "NA" and zone != "NA":
737
+ # Find correct zone for the micromarket
738
+ correct_zone = None
739
+ for area_data in areasData:
740
+ if micromarket in area_data["MicroMarkets"]:
741
+ correct_zone = area_data["Area"]
742
+ break
743
+
744
+ if correct_zone and correct_zone != zone:
745
+ log_output += f" ⚠️ Row {i+1}: Correcting {micromarket} from {zone} to {correct_zone}\n"
746
+ df_cleaned.at[i, 'Zone'] = correct_zone
747
+
748
+ # Display final results
749
+ log_output += f"\n📊 Final Results (showing first 5 of {max_rows} processed rows):\n"
750
+ for i in range(min(5, max_rows)):
751
+ log_output += f"\n📋 Row {i+1}:\n"
752
+ for col in ['Asset_Type', 'Address', 'Zone', 'Micromarket', 'Carpet Area', 'Super Built-up Area', 'Plot_Area']:
753
+ if col in df_cleaned.columns:
754
+ value = df_cleaned.iloc[i][col]
755
+ display_value = str(value)[:60] + "..." if len(str(value)) > 60 else str(value)
756
+ log_output += f" {col}: {display_value}\n"
757
+
758
+ # Save results
759
+ progress(0.95, desc="Saving results...")
760
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
761
+ output_path = f"Enhanced_Real_Estate_Data_{max_rows}_rows_FIXED_{timestamp}.xlsx"
762
+ df_cleaned.to_excel(output_path, index=False)
763
+
764
+ log_output += f"\n🎉 PROCESSING COMPLETE!\n"
765
+ log_output += f"✅ File saved: {output_path}\n"
766
+ log_output += f"📊 Processed {max_rows} rows\n"
767
+ log_output += f"🚀 Using Gemini 2.5 Flash for main extraction\n"
768
+ log_output += f"🎯 Using Gemini 1.5 Flash for ENHANCED micromarket/zone extraction\n"
769
+ log_output += f"🔧 FIXED: Carpet Area and Super Built-up Area swapping issue\n"
770
+ log_output += f"📍 Enhanced rules for better accuracy: Begur→South, HSR Layout→East, etc.\n"
771
+ log_output += f"🔄 All existing rules and processing logic maintained\n"
772
+
773
+ progress(1.0, desc="Complete!")
774
+
775
+ return output_path, log_output
776
+
777
+ except Exception as e:
778
+ return None, f"❌ Error: {str(e)}"
779
+
780
+ # --- GRADIO INTERFACE ---
781
+
782
+ def create_interface():
783
+ with gr.Blocks(title="Real Estate Data Extractor", theme=gr.themes.Soft()) as iface:
784
+ gr.Markdown("""
785
+ # 🏠 Real Estate Data Extractor
786
+
787
+ Upload an Excel file with real estate auction descriptions and extract structured data using AI.
788
+
789
+ ## Features:
790
+ - 🤖 AI-powered extraction using Gemini 2.5 Flash
791
+ - 📍 Automatic micromarket and zone identification for Bangalore
792
+ - 🔧 Fixed carpet area vs super built-up area swapping
793
+ - 📊 Clean, structured output in Excel format
794
+ - 🔄 ALL original processing rules maintained
795
+ """)
796
+
797
+ with gr.Row():
798
+ with gr.Column():
799
+ file_input = gr.File(
800
+ label="Upload Excel File",
801
+ file_types=[".xlsx", ".xls"],
802
+ type="filepath"
803
+ )
804
+
805
+ max_rows_input = gr.Slider(
806
+ minimum=1,
807
+ maximum=1000,
808
+ value=5,
809
+ step=1,
810
+ label="Number of rows to process",
811
+ info="Start with a small number to test"
812
+ )
813
+
814
+ process_btn = gr.Button("🚀 Start Processing", variant="primary", size="lg")
815
+
816
+ with gr.Column():
817
+ output_file = gr.File(label="Download Processed File")
818
+
819
+ # Processing log output
820
+ log_output = gr.Textbox(
821
+ label="Processing Log",
822
+ lines=30,
823
+ max_lines=50,
824
+ show_copy_button=True,
825
+ interactive=False
826
+ )
827
+
828
+ # Examples section
829
+ gr.Markdown("""
830
+ ## 📋 Input Requirements:
831
+ - Excel file with 'auction_description' column
832
+ - Each row should contain real estate auction description text
833
+ - File should be in .xlsx or .xls format
834
+
835
+ ## 🎯 What it extracts:
836
+ - Price per sqft
837
+ - Carpet Area & Super Built-up Area (with proper conversion)
838
+ - Floor number
839
+ - Unit Configuration (2BHK, 3BHK, etc.)
840
+ - Clean Address (stops at Bangalore + pincode)
841
+ - Asset Type
842
+ - Zone & Micromarket for Bangalore (with enhanced precision)
843
+ - Undivided Share (UDS)
844
+ - Plot Area (for plots only)
845
+
846
+ ## 🔧 Key Features:
847
+ - ✅ All original processing rules preserved
848
+ - ✅ Enhanced zone-micromarket mapping
849
+ - ✅ Fixed carpet/super built-up area swapping
850
+ - ✅ Comprehensive address cleaning
851
+ - ✅ Unit conversion (sq mtrs → sq.ft, guntas → sq.ft)
852
+ - ✅ Retry logic for API failures
853
+ - ✅ Rate limiting for stable processing
854
+ """)
855
+
856
+ process_btn.click(
857
+ fn=process_real_estate_data,
858
+ inputs=[file_input, max_rows_input],
859
+ outputs=[output_file, log_output],
860
+ show_progress=True
861
+ )
862
+
863
+ return iface
864
+
865
+ if __name__ == "__main__":
866
+ # Create and launch the interface
867
+ iface = create_interface()
868
+ iface.launch(
869
+ server_name="0.0.0.0",
870
+ server_port=7860,
871
+ share=True,
872
+ show_error=True
873
+ )