HarshAg1702 commited on
Commit
268e1ae
·
1 Parent(s): 412df76
Files changed (2) hide show
  1. .DS_Store +0 -0
  2. app.py +0 -1064
.DS_Store CHANGED
Binary files a/.DS_Store and b/.DS_Store differ
 
app.py CHANGED
@@ -1,1067 +1,3 @@
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
- # # Firebase imports
13
- # import firebase_admin
14
- # from firebase_admin import credentials, firestore
15
-
16
- # # --- Areas and MicroMarkets Data ---
17
- # areasData = [
18
- # {"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"]},
19
- # {"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"]},
20
- # {"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"]},
21
- # {"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"]},
22
- # {"Area": "West", "MicroMarkets": ["Challaghatta", "Gongadipura", "Lakshmipura", "Nagarabhavi", "Nagasandra", "Nelamangala", "Peenya", "Peenya Industrial Area", "Sulivara", "Yeshwantpur"]}
23
- # ]
24
-
25
- # # Configuration - USING GEMINI 1.5 FLASH FOR MICROMARKET EXTRACTION
26
- # EXISTING_COLUMNS = ['Price / sqft', 'Carpet Area', 'Super Built-up Area', 'Floor', 'Unit Configuration', 'Undivided Share (UDS)', 'Address', 'Asset_Type', 'Plot_Area', 'Zone', 'Micromarket']
27
- # GEMINI_API_KEY = "AIzaSyC1FoWG1pH3xQQm7PvofFx_SqrgIhErp8c"
28
-
29
- # # Main extraction API - Gemini 2.5 Flash
30
- # GEMINI_MAIN_URL = f"https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent?key={GEMINI_API_KEY}"
31
-
32
- # # Micromarket extraction API - Gemini 1.5 Flash
33
- # GEMINI_MICROMARKET_URL = f"https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:generateContent?key={GEMINI_API_KEY}"
34
-
35
- # # --- FIREBASE INITIALIZATION ---
36
- # def initialize_firebase():
37
- # """Initialize Firebase with service account key"""
38
- # try:
39
- # # Create service account key file
40
- # service_account_info = {
41
- # "type": "service_account",
42
- # "project_id": "iqol-crm",
43
- # "private_key_id": "acdc77ac88c41e7202776aa0185f2626b87dad3b",
44
- # "private_key": "-----BEGIN PRIVATE KEY-----\nMIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDA3oCeHoo9kYfg\nxihmbBb4NkzYtxOL8lBUxIa8ViCO5xgLir5KvvldP4aEYgjeteRO1e5GT6FuHHtB\nziLTKEdqwGJ2HKiMFX1aP1wauNnMt47ecBrOPEyV3roWv3Pj8L1ROmD6G0wAyG1t\nYemCoylO+qgIlQykD9gcZ1v7778aaHaXLFFM7KdgJTKHdoeh0ZIpEl/tsdK9OwUR\nt3/39eg07lv0Ak71l7DFDhff17OaVum8DK+LxZoXONO4T94CkM93jRfFMUEq/Esj\nc1bKDfK/zpYgPbj0ry8g57GRLIx7/zBdJiCSrSMZppTig3ULOvx9IsyONXZfluDA\nMJim9ogDAgMBAAECggEAEFuuz/pqIi+yNRvJeGpphlLgsK7Sbxe1vYLPpLCvYT9z\neCMj4aYR81k8eQTxmKYXv6IAbCE74WF0CNBJftxXNlQr5bWni/4UnC9sie2st2LI\nMNCUTXKq0jlKUjyZwTb9b6LCb+QZzaUyNslLq2NYURUMZHHz2QRpAXu4vwUGEeCt\nkYv6AuFWRQoelLmLM01wDhnqct2Fy8Ik2M+CtE9u8HJcqAh+lUD7ScInmXxGGGi1\nNziVZSMmuxBTGu5Zmv6PAe96W9IuVFZ994kbZMchntE2t2s0Wg1C82BfbutCWGRJ\nXjbJo9eHz+raC9Rlhh332+mrBijbrAJWzdhvWX24wQKBgQDrGC0e5iHoasvDRpJt\nsL8cyEBcdUOPeFdipstvNLwO8pJTj5/yT+ZYvPR4KrbofGMTVfTL3ZV29WrWKHLi\nirhNoeyuWnbogaQrM1TSB2aEIgaIAYFusRul8+yatUutgLlXuRdcavd6AptyRjxt\njHjZPXSuUIAczVGa20iWj4F7wQKBgQDSBRXsMkXGyyT+p5y93FFUuRZVsJLkfyzh\nifhclA8HTBwCwVFFGfUFSB64M+EAsbsdQjPFS+0h5tPyZ5zZJBAkaTZg1jhHRk9W\nTilMgj5/xj+6o2EWaqY2Fcbk4AmeOG236xdcwRzo+LVV1sVMI+/lIA/OEPKideB3\nR8Drx/ZEwwKBgHnNrdr7ewfzBR1onAcu8uWTrxz4OIfF3uii6HX2iZTpAv0+Ra2C\nziKdy7/Sya+MeryS5WEWrhDTOIY6sMNFAhZe1cTD5CW0vX0QfFrRMME269FdjlTu\neBe0WJsTYWFEd0LHCB5+4Tea0DUVxMsxY4+Scri5xpalnikwgdxX/8tBAoGABWI7\n/aIMR9xNRnnlerh7HUDhYbD1EwZvkBiJVVY2TGmXDjsGak8QCOKgZvhtfCcSNN3N\nlfEsUwInzL77NlXGVCieTD0xlCIpRn0aceukzoG2gIJPqtNxD1Hfl15m4LdxmJVe\nM/J/WzmE7H5k8F67d5Qq0417qs56wpQETgcCOSECgYBArxYUJEdAdGyGQUNtezpz\noCsWQ47SFu49ZjDmcCrhPT+BM4loB/H08A8mKPS9ck2/2VFI0GqTHEwfPxT61faK\ny+TTR8lyR3ZYtrXTXC2h1mwrNxrhEih3iNDfaxYl/EpwM4bmlosLWBbdwJnPRk9c\nD2s40XxtD+yWH+ESDfIeCA==\n-----END PRIVATE KEY-----\n",
45
- # "client_email": "firebase-adminsdk-fbsvc@iqol-crm.iam.gserviceaccount.com",
46
- # "client_id": "105834381785699477522",
47
- # "auth_uri": "https://accounts.google.com/o/oauth2/auth",
48
- # "token_uri": "https://oauth2.googleapis.com/token",
49
- # "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
50
- # "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/firebase-adminsdk-fbsvc%40iqol-crm.iam.gserviceaccount.com",
51
- # "universe_domain": "googleapis.com"
52
- # }
53
-
54
- # # Save to temporary file
55
- # with open('temp_serviceAccountKey.json', 'w') as f:
56
- # json.dump(service_account_info, f)
57
-
58
- # # Initialize Firebase
59
- # if not firebase_admin._apps:
60
- # cred = credentials.Certificate('temp_serviceAccountKey.json')
61
- # firebase_admin.initialize_app(cred)
62
-
63
- # # Clean up temporary file
64
- # if os.path.exists('temp_serviceAccountKey.json'):
65
- # os.remove('temp_serviceAccountKey.json')
66
-
67
- # return firestore.client()
68
- # except Exception as e:
69
- # print(f"Firebase initialization error: {e}")
70
- # return None
71
-
72
- # def upload_to_firestore(data, collection_name="DUPLICATES"):
73
- # """Upload JSON data to Firestore"""
74
- # try:
75
- # db = initialize_firebase()
76
- # if not db:
77
- # return "❌ Failed to initialize Firebase"
78
-
79
- # collection_ref = db.collection(collection_name)
80
- # uploaded_count = 0
81
- # updated_count = 0
82
-
83
- # for item in data:
84
- # doc_id = item.get('id')
85
-
86
- # if doc_id:
87
- # doc_ref = collection_ref.document(doc_id)
88
- # doc = doc_ref.get()
89
- # if doc.exists:
90
- # doc_ref.update(item)
91
- # updated_count += 1
92
- # else:
93
- # doc_ref.set(item)
94
- # uploaded_count += 1
95
- # else:
96
- # doc_ref = collection_ref.add(item)
97
- # uploaded_count += 1
98
-
99
- # return f"✅ Successfully uploaded {uploaded_count} new documents and updated {updated_count} existing documents to Firestore collection '{collection_name}'"
100
-
101
- # except Exception as e:
102
- # return f"❌ Error uploading to Firestore: {str(e)}"
103
-
104
- # # --- JSON TO INTERNAL FIELD MAPPING ---
105
- # JSON_FIELD_MAPPING = {
106
- # 'description': 'auction_description', # Main description field
107
- # 'price_per_sqft': 'Price / sqft',
108
- # 'carpet_area': 'Carpet Area',
109
- # 'super_built_area': 'Super Built-up Area',
110
- # 'floor': 'Floor',
111
- # 'unit_configuration': 'Unit Configuration',
112
- # 'undivided_share': 'Undivided Share (UDS)',
113
- # 'address': 'Address',
114
- # 'asset_type': 'Asset_Type',
115
- # 'plot_area': 'Plot_Area'
116
- # }
117
-
118
- # # --- CORE PROCESSING FUNCTIONS ---
119
-
120
- # def process_field_value(text, field_name):
121
- # """
122
- # Universal field processing function - handles all field types
123
- # """
124
- # if not text or str(text).strip() == "" or str(text).upper() in ['NA', 'NULL', 'NAN']:
125
- # return "NA"
126
-
127
- # text = str(text).strip()
128
-
129
- # # Remove field name prefixes
130
- # text = re.sub(rf'^{re.escape(field_name)}[:\s]*', '', text, flags=re.IGNORECASE).strip()
131
- # text = re.sub(r'^[^:]*:\s*', '', text).strip()
132
-
133
- # # Field-specific processing
134
- # if field_name == 'Address':
135
- # return clean_address_field(text)
136
- # elif field_name in ['Carpet Area', 'Super Built-up Area', 'Plot_Area']:
137
- # return process_area_field(text)
138
- # elif field_name == 'Floor':
139
- # match = re.search(r'([0-9]+)', text)
140
- # return match.group(1) if match else "NA"
141
- # elif field_name == 'Unit Configuration':
142
- # return process_configuration_field(text)
143
- # elif field_name == 'Asset_Type':
144
- # return process_asset_type_field(text)
145
- # elif field_name == 'Price / sqft':
146
- # match = re.search(r'₹?\s*([0-9,]+)', text)
147
- # return f"₹{match.group(1)}" if match else "NA"
148
-
149
- # return text if len(text) <= 100 and text.upper() != 'NA' else 'NA'
150
-
151
- # def clean_address_field(raw_address):
152
- # """
153
- # Clean and trim address at Bangalore/Bengaluru + pincode
154
- # """
155
- # if not raw_address or str(raw_address).upper() == "NA":
156
- # return "NA"
157
-
158
- # text = str(raw_address).strip()
159
- # if len(text) < 10:
160
- # return text
161
-
162
- # # Remove junk
163
- # text = re.sub(r'Asset_Type[^|]*|Plot_Area[^|]*|\|.*', '', text, flags=re.IGNORECASE)
164
-
165
- # # Termination patterns
166
- # patterns = [
167
- # r'(.*?(?:bangalore|bengaluru).*?karnataka.*?\d{6})',
168
- # r'(.*?(?:bangalore|bengaluru).*?\d{6})',
169
- # r'(.*?(?:bangalore|bengaluru).*?karnataka)',
170
- # r'(.*?(?:bangalore|bengaluru))(?:\s+bounded|\s+measuring|\s+together|\s+admeasuring|\s+bearing)',
171
- # r'(.*?(?:bangalore|bengaluru))'
172
- # ]
173
-
174
- # for pattern in patterns:
175
- # match = re.search(pattern, text, re.IGNORECASE)
176
- # if match:
177
- # text = match.group(1).strip()
178
- # break
179
-
180
- # # Remove boundary descriptions
181
- # boundary_patterns = [
182
- # r'\s*bounded\s*by.*$', r'\s*measuring.*?(?:sq\.?ft|sq\.?\s*mtrs?).*$',
183
- # r'\s*together\s*with.*$', r'\s*inclusive\s*of.*$', r'\s*admeasuring.*$',
184
- # r'\s*bearing\s*no\..*$', r'\s*with\s*undivided.*$', r'\s*flat\s*measuring.*$'
185
- # ]
186
-
187
- # for pattern in boundary_patterns:
188
- # text = re.sub(pattern, '', text, flags=re.IGNORECASE)
189
-
190
- # # Clean up
191
- # text = re.sub(r'[,\s]+$|^[,\s]+|\s+', ' ', text).strip()
192
- # return text if len(text) >= 5 else "NA"
193
-
194
- # def process_area_field(text):
195
- # """
196
- # Process area fields with unit conversion
197
- # """
198
- # area_match = re.search(r'([0-9.]+)\s*(?:sq\.?\s*)?(ft|mtrs?|meters?|guntas?)', text, re.IGNORECASE)
199
- # if area_match:
200
- # value, unit = float(area_match.group(1)), area_match.group(2).lower()
201
- # if 'mtr' in unit or 'meter' in unit:
202
- # value *= 10.764
203
- # elif 'gunta' in unit:
204
- # value *= 1089
205
- # return f"{value:.0f}"
206
-
207
- # number_match = re.search(r'([0-9.]+)', text)
208
- # return f"{number_match.group(1)}" if number_match else "NA"
209
-
210
- # def process_configuration_field(text):
211
- # """
212
- # Process unit configuration field
213
- # """
214
- # config_patterns = [
215
- # (r'([0-9]+)\s*BHK', lambda m: f"{m.group(1)}BHK"),
216
- # (r'([0-9]+)\s*RK', lambda m: f"{m.group(1)}RK"),
217
- # (r'(Studio)', lambda m: 'Studio'),
218
- # (r'([0-9]+)\s*bed', lambda m: f"{m.group(1)}BHK"),
219
- # ]
220
-
221
- # for pattern, formatter in config_patterns:
222
- # match = re.search(pattern, text, re.IGNORECASE)
223
- # if match:
224
- # return formatter(match)
225
- # return "NA"
226
-
227
- # def process_asset_type_field(text):
228
- # """
229
- # Process asset type field
230
- # """
231
- # asset_types = ['Flat', 'Apartment', 'Villa', 'House', 'Plot', 'Commercial', 'Residential']
232
- # for asset_type in asset_types:
233
- # if asset_type.lower() in text.lower():
234
- # return asset_type
235
- # return "NA"
236
-
237
- # # --- GEMINI API FUNCTIONS ---
238
-
239
- # def test_api_key():
240
- # """Test API key validity"""
241
- # try:
242
- # # Test main API with longer timeout
243
- # res = requests.post(GEMINI_MAIN_URL, json={'contents': [{'parts': [{'text': 'test'}]}], 'generationConfig': {'maxOutputTokens': 10}}, timeout=30)
244
- # if res.status_code != 200:
245
- # return False
246
-
247
- # # Test micromarket API with longer timeout
248
- # res = requests.post(GEMINI_MICROMARKET_URL, json={'contents': [{'parts': [{'text': 'test'}]}], 'generationConfig': {'maxOutputTokens': 10}}, timeout=30)
249
- # return res.status_code == 200
250
- # except:
251
- # return False
252
-
253
- # def extract_micromarket_and_zone_with_gemini(address):
254
- # """
255
- # Use Gemini 1.5 Flash to extract micromarket and zone from address with ENHANCED PRECISION
256
- # """
257
- # if not address or str(address).upper() == "NA":
258
- # return "NA", "NA"
259
-
260
- # # Create detailed micromarket mapping
261
- # micromarket_zone_mapping = {}
262
- # zone_info = []
263
-
264
- # for area_data in areasData:
265
- # zone = area_data["Area"]
266
- # micromarkets = area_data["MicroMarkets"]
267
- # zone_info.append(f"{zone}: {', '.join(micromarkets)}")
268
-
269
- # for micromarket in micromarkets:
270
- # micromarket_zone_mapping[micromarket] = zone
271
-
272
- # zone_list = '\n'.join(zone_info)
273
-
274
- # 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.
275
- # ADDRESS TO ANALYZE: "{address}"
276
- # COMPLETE MICROMARKET-ZONE MAPPING (YOU MUST CHOOSE FROM THIS LIST ONLY):
277
- # 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
278
- # 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
279
- # 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
280
- # 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
281
- # West: Challaghatta, Gongadipura, Lakshmipura, Nagarabhavi, Nagasandra, Nelamangala, Peenya, Peenya Industrial Area, Sulivara, Yeshwantpur
282
- # 🎯 CRITICAL ZONE AND MICROMARKET RULES (MUST FOLLOW):
283
- # 1. **BEGUR** is in **SOUTH** zone (NOT North or East)
284
- # 2. **HSR Layout** is in **EAST** zone
285
- # 3. **Electronic City** is in **SOUTH** zone
286
- # 4. **Whitefield** is in **EAST** zone
287
- # 5. **Hebbal** is in **NORTH** zone
288
- # 6. **Koramangala** is in **EAST** zone
289
- # 7. **Malleswaram** is in **CENTRAL** zone
290
- # 8. **Banashankari** is in **SOUTH** zone
291
- # 9. **Indiranagar** is in **EAST** zone
292
- # 10. **Jayanagar** is in **SOUTH** zone
293
- # ANALYSIS INSTRUCTIONS:
294
- # 1. Look for EXACT micromarket names from the list above
295
- # 2. Handle common variations (e.g., "HSR" = "HSR Layout", "Koramangla" = "Koramangala")
296
- # 3. Check for Village/Hobli names that might match micromarket names
297
- # 4. Consider project names, nearby landmarks, or area descriptions
298
- # 5. If no exact match found, extract the most specific location name from the address
299
- # EXAMPLES OF CORRECT MAPPINGS:
300
- # - "Begur Hobli" or "Begur Village" → Micromarket: Begur, Zone: South
301
- # - "HSR Layout" or "HSR" → Micromarket: HSR Layout, Zone: East
302
- # - "Electronic City Phase 1" → Micromarket: Electronic City, Zone: South
303
- # - "Koramangala 5th Block" → Micromarket: Koramangala, Zone: East
304
- # - "Whitefield Main Road" → Micromarket: Whitefield, Zone: East
305
- # - "Hebbal Lake" → Micromarket: Hebbal, Zone: North
306
- # 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".
307
- # RESPONSE FORMAT (EXACTLY):
308
- # Micromarket: [exact name from list above OR local area name if no match]
309
- # Zone: [Central/East/North/South/West OR NA if no match]
310
- # """
311
-
312
- # try:
313
- # response = requests.post(GEMINI_MICROMARKET_URL, json={
314
- # 'contents': [{'parts': [{'text': prompt}]}],
315
- # 'generationConfig': {'temperature': 0.1, 'maxOutputTokens': 150}
316
- # }, timeout=60) # Increased timeout
317
-
318
- # if response.status_code == 200:
319
- # response_json = response.json()
320
-
321
- # # Extract response text
322
- # response_text = ""
323
- # candidate = response_json['candidates'][0]
324
-
325
- # # Handle different response structures
326
- # content = candidate.get('content', {})
327
- # if isinstance(content, dict) and 'parts' in content:
328
- # if len(content['parts']) > 0 and 'text' in content['parts'][0]:
329
- # response_text = content['parts'][0]['text']
330
-
331
- # if response_text:
332
- # # Parse micromarket and zone from response
333
- # micromarket_match = re.search(r'Micromarket:\s*(.+)', response_text, re.IGNORECASE)
334
- # zone_match = re.search(r'Zone:\s*(.+)', response_text, re.IGNORECASE)
335
-
336
- # micromarket = micromarket_match.group(1).strip() if micromarket_match else "NA"
337
- # zone = zone_match.group(1).strip() if zone_match else "NA"
338
-
339
- # # Clean up extracted values
340
- # micromarket = re.sub(r'[,\n\r\s]+$', '', micromarket).strip()
341
- # zone = re.sub(r'[,\n\r\s]+$', '', zone).strip()
342
-
343
- # # Validate micromarket is in our list
344
- # all_micromarkets = []
345
- # for area_data in areasData:
346
- # all_micromarkets.extend(area_data["MicroMarkets"])
347
-
348
- # # If micromarket is not in our predefined list, keep it as local area name
349
- # if micromarket not in all_micromarkets:
350
- # # Keep the extracted local area name
351
- # zone = "NA" # Set zone to NA if micromarket not in predefined list
352
-
353
- # # Validate zone
354
- # if zone not in ['Central', 'East', 'North', 'South', 'West']:
355
- # zone = "NA"
356
-
357
- # # Double check zone matches micromarket (only if micromarket is in our list)
358
- # if micromarket in all_micromarkets and zone != "NA":
359
- # expected_zone = micromarket_zone_mapping.get(micromarket)
360
- # if expected_zone and expected_zone != zone:
361
- # zone = expected_zone # Correct the zone based on micromarket
362
-
363
- # return micromarket, zone
364
- # else:
365
- # return "NA", "NA"
366
- # else:
367
- # return "NA", "NA"
368
- # except:
369
- # return "NA", "NA"
370
-
371
- # def clean_extracted_value(value):
372
- # """Clean extracted values from Gemini response"""
373
- # if not value:
374
- # return 'NA'
375
-
376
- # value = str(value).strip()
377
-
378
- # # Remove bullet points and dashes
379
- # value = re.sub(r'^[\-•*]\s*', '', value)
380
-
381
- # # Remove trailing commas, newlines, and extra spaces
382
- # # value = re.sub(r'[,\n\r\s]+, '', value)
383
- # value = re.sub(r'[,\n\r\s]+$', '', value)
384
-
385
- # # Remove leading/trailing quotes
386
- # value = value.strip('"\'')
387
-
388
- # # If empty after cleaning, return NA
389
- # if not value or value.upper() == 'NA':
390
- # return 'NA'
391
-
392
- # return value
393
-
394
- # def process_with_gemini(descriptions, contexts, max_rows):
395
- # """
396
- # Process data with Gemini 2.5 Flash API including retry logic
397
- # """
398
- # if not test_api_key():
399
- # return [{col: 'NA' for col in EXISTING_COLUMNS} for _ in descriptions]
400
-
401
- # results = []
402
-
403
- # for i, (desc, ctx) in enumerate(zip(descriptions[:max_rows], contexts[:max_rows])):
404
-
405
- # existing_info = '\n'.join(f"{f}: {v}" for f, v in ctx.items()) or 'No existing data'
406
-
407
- # # FIXED PROMPT with corrected rules and examples
408
- # full_prompt = f"""Extract real estate data from this auction description:
409
- # EXISTING: {existing_info}
410
- # DESCRIPTION: "{desc}"
411
- # 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:
412
- # Price / sqft: [value with ₹ symbol if mentioned]
413
- # Carpet Area: [area value only, no units]
414
- # Super Built-up Area: [area value only, no units]
415
- # Floor: [number only]
416
- # Unit Configuration: [like 2BHK, 3BHK, 1RK, Studio]
417
- # Undivided Share (UDS): [UDS details]
418
- # Address: [CLEAN ADDRESS - STOP at Bangalore/Bengaluru + pincode]
419
- # Asset_Type: [Flat/Apartment/Villa/House/Plot/Commercial/Residential]
420
- # Plot_Area: [area with sq.ft units - for plots only, NA for flats]
421
- # CRITICAL RULES FOR CARPET AREA VS SUPER BUILT-UP AREA:
422
- # 1. **Carpet Area**: The ACTUAL USABLE area of the property (excluding walls, balconies, common areas)
423
- # 2. **Super Built-up Area**: The TOTAL area including proportionate share of common areas, balconies, corridors, lifts
424
- # 3. **IMPORTANT**: Carpet Area is ALWAYS SMALLER than Super Built-up Area
425
- # 4. **When both are mentioned**: Extract each value to its correct field - DO NOT swap them
426
- # 5. **Area calculation priority**: If text says "Carpet Area X sq mtrs" and "Super Built Up Area Y sq mtrs", then:
427
- # - Carpet Area = X (converted to sq.ft)
428
- # - Super Built-up Area = Y (converted to sq.ft)
429
- # ADDITIONAL RULES:
430
- # 1. Use EXACTLY the field names shown above (with spaces & capitalization)
431
- # 2. For Address: STOP at "Bangalore"/"Bengaluru" + optional pincode. DO NOT include "Bounded by", "Measuring", "Together with", "Admeasuring", or boundary descriptions
432
- # 3. For FLATS/APARTMENTS: Plot_Area = NA
433
- # 4. For PLOTS: Extract plot/land area, Carpet Area and Super Built-up Area = NA
434
- # 5. Convert units: sq mtrs to sq.ft (×10.764), guntas to sq.ft (×1089)
435
- # 6. If information is not clearly mentioned, write "NA"
436
- # Example 1 - CORRECT Carpet vs Super Built-up Processing:
437
- # 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"
438
- # Correct Response:
439
- # Price / sqft: NA
440
- # Carpet Area: 815
441
- # Super Built-up Area: 1204
442
- # Floor: 13
443
- # Unit Configuration: NA
444
- # Undivided Share (UDS): NA
445
- # Address: Purva Zenium, Hosahalli Village, Bangalore 562157
446
- # Asset_Type: Flat
447
- # Plot_Area: NA
448
- # Example 2 - Address Termination:
449
- # 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..."
450
- # Correct Address: "Site no 11, Assessment no 2, Soladevanhalli Village, Hesaraghatta Hobli, New Yelahanka Taluk, Bangalore, Karnataka, 560088"
451
- # Example 3 - Plot Processing:
452
- # Input: "Plot measuring 20 guntas or 21,780 sq. ft at Sy.no. 11/7 situated at Kammanahalli, Begur Hobli, Bangalore South Taluk"
453
- # Correct Response:
454
- # Price / sqft: NA
455
- # Carpet Area: NA
456
- # Super Built-up Area: NA
457
- # Floor: NA
458
- # Unit Configuration: NA
459
- # Undivided Share (UDS): NA
460
- # Address: Sy.no. 11/7 Kammanahalli, Begur Hobli, Bangalore
461
- # Asset_Type: Plot
462
- # Plot_Area: 21780 sq.ft
463
- # Example 4 - CORRECTED Complete Processing:
464
- # 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"
465
- # Correct Response:
466
- # Price / sqft: NA
467
- # Carpet Area: 977
468
- # Super Built-up Area: 1376
469
- # Floor: 19
470
- # Unit Configuration: NA
471
- # Undivided Share (UDS): 1376 sq.ft
472
- # Address: Prestige Song Of The South, Chandrashekharapura Village, Begur Hobli, Bangalore South Taluk, Bengaluru Karnataka- 560068
473
- # Asset_Type: Apartment
474
- # Plot_Area: NA
475
- # RESPONSE FORMAT (use exactly this format):
476
- # Price / sqft: [value]
477
- # Carpet Area: [value]
478
- # Super Built-up Area: [value]
479
- # Floor: [value]
480
- # Unit Configuration: [value]
481
- # Undivided Share (UDS): [value]
482
- # Address: [value]
483
- # Asset_Type: [value]
484
- # Plot_Area: [value]
485
- # """
486
-
487
- # # Shorter prompt for retry attempts
488
- # short_prompt = f"""Extract real estate data from: "{desc}"
489
- # Extract these fields EXACTLY:
490
- # Price / sqft: [₹ value if mentioned]
491
- # Carpet Area: [SMALLER usable area value only, no units]
492
- # Super Built-up Area: [LARGER total area value only, no units]
493
- # Floor: [number only]
494
- # Unit Configuration: [2BHK, 3BHK, 1RK, Studio]
495
- # Undivided Share (UDS): [UDS details]
496
- # Address: [STOP at Bangalore/Bengaluru + pincode - NO boundary descriptions]
497
- # Asset_Type: [Flat/Apartment/Villa/House/Plot/Commercial/Residential]
498
- # Plot_Area: [for plots only, NA for flats]
499
- # CRITICAL: Carpet Area < Super Built-up Area. Don't swap them. Convert sq mtrs×10.764, guntas×1089."""
500
-
501
- # # Retry logic
502
- # for attempt in range(3):
503
- # try:
504
- # # Use shorter prompt on retry attempts
505
- # current_prompt = short_prompt if attempt > 0 else full_prompt
506
-
507
- # response = requests.post(GEMINI_MAIN_URL, json={
508
- # 'contents': [{'parts': [{'text': current_prompt}]}],
509
- # 'generationConfig': {'temperature': 0.1, 'maxOutputTokens': 4096}
510
- # }, timeout=60) # Increased timeout
511
-
512
- # if response.status_code == 200:
513
- # response_json = response.json()
514
-
515
- # # Handle different response structures for Gemini 2.5 Flash
516
- # response_text = ""
517
-
518
- # # Check for finish reason first
519
- # candidate = response_json['candidates'][0]
520
- # finish_reason = candidate.get('finishReason', '')
521
-
522
- # if finish_reason == 'MAX_TOKENS':
523
- # continue
524
- # elif finish_reason == 'SAFETY':
525
- # results.append({col: 'NA' for col in EXISTING_COLUMNS})
526
- # break
527
-
528
- # try:
529
- # content = candidate.get('content', {})
530
-
531
- # # Try different parsing approaches for Gemini 2.5 Flash
532
- # if isinstance(content, dict) and 'parts' in content and isinstance(content['parts'], list):
533
- # if len(content['parts']) > 0 and 'text' in content['parts'][0]:
534
- # response_text = content['parts'][0]['text']
535
-
536
- # except Exception as e:
537
- # if attempt < 2:
538
- # continue
539
- # else:
540
- # results.append({col: 'NA' for col in EXISTING_COLUMNS})
541
- # break
542
-
543
- # if not response_text:
544
- # if attempt < 2:
545
- # continue
546
- # else:
547
- # results.append({col: 'NA' for col in EXISTING_COLUMNS})
548
- # break
549
-
550
- # # Process extracted fields (excluding Zone and Micromarket)
551
- # extracted = {}
552
- # for field in EXISTING_COLUMNS:
553
- # if field not in ['Zone', 'Micromarket']: # Skip these, handled separately
554
- # pattern = rf"{re.escape(field)}\s*:\s*(.+?)(?=\n[A-Z]|$)"
555
- # match = re.search(pattern, response_text, re.IGNORECASE | re.DOTALL)
556
- # if match:
557
- # value = match.group(1).strip()
558
- # value = clean_extracted_value(value)
559
- # extracted[field] = process_field_value(value, field)
560
- # else:
561
- # extracted[field] = 'NA'
562
- # else:
563
- # extracted[field] = 'NA' # Will be filled by dedicated micromarket extraction
564
-
565
- # results.append(extracted)
566
- # break
567
-
568
- # elif response.status_code == 503:
569
- # wait_time = 15 * (attempt + 1)
570
- # time.sleep(wait_time)
571
-
572
- # else:
573
- # results.append({col: 'NA' for col in EXISTING_COLUMNS})
574
- # break
575
-
576
- # except Exception as e:
577
- # results.append({col: 'NA' for col in EXISTING_COLUMNS})
578
- # break
579
- # else:
580
- # # If all retries failed
581
- # results.append({col: 'NA' for col in EXISTING_COLUMNS})
582
-
583
- # # Rate limiting - increased wait time
584
- # if i < max_rows - 1:
585
- # time.sleep(3) # Increased from 2 to 3 seconds
586
-
587
- # return results
588
-
589
- # # --- JSON DATA LOADING AND MAPPING ---
590
-
591
- # def load_json_data(file_path):
592
- # """
593
- # Load JSON data and convert to DataFrame with field mapping
594
- # """
595
- # try:
596
- # with open(file_path, 'r', encoding='utf-8') as f:
597
- # data = json.load(f)
598
-
599
- # # Handle both single object and array of objects
600
- # if isinstance(data, dict):
601
- # data = [data]
602
- # elif not isinstance(data, list):
603
- # raise ValueError("JSON must contain an object or array of objects")
604
-
605
- # # Convert to DataFrame
606
- # df = pd.DataFrame(data)
607
-
608
- # # Map JSON fields to internal structure
609
- # mapped_df = pd.DataFrame()
610
-
611
- # # Add the main description field (required)
612
- # if 'description' in df.columns:
613
- # mapped_df['auction_description'] = df['description']
614
- # else:
615
- # raise ValueError("JSON must contain 'description' field")
616
-
617
- # # Map other fields using the mapping dictionary
618
- # for json_field, internal_field in JSON_FIELD_MAPPING.items():
619
- # if json_field in df.columns:
620
- # mapped_df[internal_field] = df[json_field]
621
- # else:
622
- # mapped_df[internal_field] = "NA"
623
-
624
- # # Add Zone and Micromarket columns (will be filled later)
625
- # mapped_df['Zone'] = "NA"
626
- # mapped_df['Micromarket'] = "NA"
627
-
628
- # # Ensure all required columns exist
629
- # for col in EXISTING_COLUMNS:
630
- # if col not in mapped_df.columns:
631
- # mapped_df[col] = "NA"
632
-
633
- # return mapped_df
634
-
635
- # except Exception as e:
636
- # raise Exception(f"Error loading JSON file: {str(e)}")
637
-
638
- # # --- DATA CLEANING ---
639
-
640
- # def clean_overlapping_data(df):
641
- # """
642
- # Clean overlapping data and add missing columns
643
- # """
644
- # # Add missing columns
645
- # for col in EXISTING_COLUMNS:
646
- # if col not in df.columns:
647
- # df[col] = ""
648
-
649
- # # Ensure all columns are object type
650
- # for col in EXISTING_COLUMNS:
651
- # if col in df.columns:
652
- # df[col] = df[col].astype(object)
653
-
654
- # # Process each row
655
- # for idx, row in df.iterrows():
656
-
657
- # # Clean overlapping fields
658
- # cleaned_data = {}
659
- # for field_name in EXISTING_COLUMNS:
660
- # if field_name in row.index:
661
- # original_value = str(row[field_name]) if pd.notna(row[field_name]) else ""
662
- # cleaned_data[field_name] = process_field_value(original_value, field_name)
663
-
664
- # # Handle special overlaps
665
- # # 1. Carpet Area containing Super Built-up Area
666
- # carpet_text = str(row.get('Carpet Area', ''))
667
- # if 'Super Built-up Area:' in carpet_text:
668
- # super_match = re.search(r'Super\s*(?:Built-up\s*)?Area[:\s]*([^\\n\\r]+)', carpet_text, re.IGNORECASE)
669
- # if super_match:
670
- # cleaned_data['Super Built-up Area'] = process_field_value(super_match.group(1), 'Super Built-up Area')
671
- # cleaned_data['Carpet Area'] = process_field_value(re.sub(r'\\n.*|Super.*', '', carpet_text), 'Carpet Area')
672
-
673
- # # 2. Asset_Type containing Plot_Area
674
- # asset_text = str(row.get('Asset_Type', ''))
675
- # if 'Plot_Area:' in asset_text:
676
- # plot_match = re.search(r'Plot[_\s]*Area[:\s]*([^\\n\\r]+)', asset_text, re.IGNORECASE)
677
- # if plot_match:
678
- # cleaned_data['Plot_Area'] = process_field_value(plot_match.group(1), 'Plot_Area')
679
- # cleaned_data['Asset_Type'] = process_field_value(re.sub(r'\\n.*|Plot.*', '', asset_text), 'Asset_Type')
680
-
681
- # # Update dataframe
682
- # for field_name, clean_value in cleaned_data.items():
683
- # if field_name in df.columns:
684
- # df.at[idx, field_name] = clean_value
685
-
686
- # return df
687
-
688
- # # --- SAVE RESULTS TO JSON WITH NEW SCHEMA ---
689
-
690
- # def create_json_output(df, original_data):
691
- # """
692
- # Create JSON output following the specified schema
693
- # """
694
- # results = []
695
-
696
- # for idx, row in df.iterrows():
697
- # # Get original data for this row
698
- # original_row = original_data[idx] if idx < len(original_data) else {}
699
-
700
- # # Extract pincode from address
701
- # pincode = "NA"
702
- # address = row.get('Address', 'NA')
703
- # if address != "NA":
704
- # pincode_match = re.search(r'\b(\d{6})\b', str(address))
705
- # if pincode_match:
706
- # pincode = pincode_match.group(1)
707
-
708
- # # Map micromarket to area field
709
- # micromarket = row.get('Micromarket', 'NA')
710
- # zone = row.get('Zone', 'NA')
711
- # area_field = f"{micromarket}, {zone}" if micromarket != "NA" and zone != "NA" else micromarket
712
-
713
- # # Create JSON object following the specified schema
714
- # json_obj = {
715
- # "id": original_row.get('id', f"property_{idx+1}"),
716
- # "source": original_row.get('source', "NA"),
717
- # "url": original_row.get('url', "NA"),
718
- # "bank": original_row.get('bank', "NA"),
719
- # "description": original_row.get('description', "NA"),
720
- # "property_type": original_row.get('property_type', row.get('Asset_Type', 'NA')),
721
- # "area": area_field,
722
- # "city": "Bangalore",
723
- # "state": "Karnataka",
724
- # "contact": original_row.get('contact', "NA"),
725
- # "reserved_price": original_row.get('reserved_price', "NA"),
726
- # "emd_amount": original_row.get('emd_amount', "NA"),
727
- # "submission_emd": original_row.get('submission_emd', "NA"),
728
- # "auction_start_date": original_row.get('auction_start_date', "NA"),
729
- # "auction_end_date": original_row.get('auction_end_date', "NA"),
730
- # "pincode": pincode,
731
- # "carpet_area": row.get('Carpet Area', 'NA'),
732
- # "super_built_area": row.get('Super Built-up Area', 'NA'),
733
- # "floor": row.get('Floor', 'NA'),
734
- # "unit_configuration": row.get('Unit Configuration', 'NA'),
735
- # "address": row.get('Address', 'NA'),
736
- # "asset_type": row.get('Asset_Type', 'NA'),
737
- # "undivided_share": row.get('Undivided Share (UDS)', 'NA'),
738
- # "price_per_sqft": row.get('Price / sqft', 'NA')
739
- # }
740
-
741
- # results.append(json_obj)
742
-
743
- # return results
744
-
745
- # def save_results_to_json(df, output_path, original_data):
746
- # """
747
- # Save processed DataFrame to JSON format with the new schema
748
- # """
749
- # # Create JSON output with new schema
750
- # results = create_json_output(df, original_data)
751
-
752
- # # Save to JSON file
753
- # with open(output_path, 'w', encoding='utf-8') as f:
754
- # json.dump(results, f, indent=2, ensure_ascii=False)
755
-
756
- # return output_path
757
-
758
- # # --- MAIN PROCESSING FUNCTION FOR GRADIO ---
759
-
760
- # def process_real_estate_data(file, max_rows, upload_to_db, progress=gr.Progress()):
761
- # """Main processing function for Gradio with JSON support, new schema output, and Firebase upload"""
762
-
763
- # if file is None:
764
- # return None, "❌ Please upload a JSON file"
765
-
766
- # try:
767
- # # Step 1: Load JSON data and store original
768
- # progress(0.05, desc="Reading JSON file...")
769
-
770
- # # Load original data for schema mapping
771
- # with open(file.name, 'r', encoding='utf-8') as f:
772
- # original_data = json.load(f)
773
-
774
- # # Handle both single object and array of objects
775
- # if isinstance(original_data, dict):
776
- # original_data = [original_data]
777
- # elif not isinstance(original_data, list):
778
- # raise ValueError("JSON must contain an object or array of objects")
779
-
780
- # df = load_json_data(file.name)
781
-
782
- # if 'auction_description' not in df.columns:
783
- # return None, "❌ Error: 'description' field not found in the JSON file"
784
-
785
- # total_rows = len(df)
786
- # max_rows = min(max_rows, total_rows)
787
-
788
- # # Initialize log output
789
- # log_output = f"🚀 Starting processing of {max_rows} records...\n\n"
790
- # if upload_to_db:
791
- # log_output += "📊 Firebase upload is ENABLED - processed data will be uploaded to Firestore\n\n"
792
-
793
- # progress(0.1, desc="Cleaning overlapping data...")
794
-
795
- # # Step 1: Clean overlapping data
796
- # df_cleaned = clean_overlapping_data(df)
797
-
798
- # # Step 2: Process with Gemini 2.5 Flash (main extraction)
799
- # progress(0.2, desc="Starting Gemini 2.5 Flash processing...")
800
-
801
- # descriptions = [str(row['auction_description']) for _, row in df_cleaned.head(max_rows).iterrows()]
802
- # contexts = []
803
-
804
- # for idx, row in df_cleaned.head(max_rows).iterrows():
805
- # ctx = {}
806
- # for col in EXISTING_COLUMNS:
807
- # if col in df_cleaned.columns:
808
- # value = row[col]
809
- # if pd.notna(value) and str(value).strip() != "" and str(value).upper() not in ['NA', 'NULL']:
810
- # ctx[col] = value
811
- # contexts.append(ctx)
812
-
813
- # gemini_results = process_with_gemini(descriptions, contexts, max_rows)
814
-
815
- # # Step 3: Update dataframe with main extraction results
816
- # progress(0.5, desc="Updating main extraction results...")
817
-
818
- # for i, result in enumerate(gemini_results):
819
- # for col, new_value in result.items():
820
- # if col in df_cleaned.columns and new_value != 'NA':
821
- # current_value = df_cleaned.at[i, col]
822
-
823
- # # Special handling for critical fields - always update if Gemini extracted a valid value
824
- # critical_fields = ['Carpet Area', 'Super Built-up Area', 'Address', 'Asset_Type', 'Floor', 'Unit Configuration']
825
-
826
- # if col in critical_fields:
827
- # # Always update critical fields with Gemini results
828
- # df_cleaned.at[i, col] = new_value
829
- # else:
830
- # # For other fields, only update if current value is empty/NA
831
- # if (pd.isna(current_value) or str(current_value).strip() == '' or str(current_value).upper() in ['NA', 'NULL']):
832
- # df_cleaned.at[i, col] = new_value
833
-
834
- # # Step 4: Extract Zone and Micromarket using Gemini 1.5 Flash
835
- # progress(0.6, desc="Extracting zones and micromarkets...")
836
-
837
- # for idx in range(min(max_rows, len(df_cleaned))):
838
- # if idx % 5 == 0: # Update progress every 5 rows
839
- # progress(0.6 + 0.25 * (idx / max_rows), desc=f"Processing address {idx+1}/{max_rows}...")
840
-
841
- # # Get the cleaned address
842
- # address = df_cleaned.at[idx, 'Address']
843
-
844
- # # Use Gemini 1.5 Flash to extract micromarket and zone
845
- # micromarket, zone = extract_micromarket_and_zone_with_gemini(address)
846
-
847
- # # Update dataframe
848
- # df_cleaned.at[idx, 'Micromarket'] = micromarket
849
- # df_cleaned.at[idx, 'Zone'] = zone
850
-
851
- # # Show COMPLETE JSON output for each row (all 22 fields)
852
- # row_data = df_cleaned.iloc[idx]
853
- # json_row = create_json_output(pd.DataFrame([row_data]), [original_data[idx] if idx < len(original_data) else {}])[0]
854
- # log_output += f"📝 Record {idx+1}:\n" + json.dumps(json_row, indent=2, ensure_ascii=False) + "\n\n"
855
-
856
- # # Rate limiting - increased wait time
857
- # if idx < max_rows - 1:
858
- # time.sleep(3) # Increased from 1.5 to 3 seconds
859
-
860
- # # Step 5: Final address cleaning
861
- # progress(0.85, desc="Final address cleaning...")
862
-
863
- # for idx in range(min(max_rows, len(df_cleaned))):
864
- # address = df_cleaned.at[idx, 'Address']
865
- # clean_address = process_field_value(address, 'Address')
866
- # df_cleaned.at[idx, 'Address'] = clean_address
867
-
868
- # # Step 6: Results validation
869
- # progress(0.9, desc="Validating results...")
870
-
871
- # # Validate zone-micromarket mapping
872
- # for i in range(min(max_rows, len(df_cleaned))):
873
- # micromarket = df_cleaned.at[i, 'Micromarket']
874
- # zone = df_cleaned.at[i, 'Zone']
875
-
876
- # if micromarket != "NA" and zone != "NA":
877
- # # Find correct zone for the micromarket
878
- # correct_zone = None
879
- # for area_data in areasData:
880
- # if micromarket in area_data["MicroMarkets"]:
881
- # correct_zone = area_data["Area"]
882
- # break
883
-
884
- # if correct_zone and correct_zone != zone:
885
- # df_cleaned.at[i, 'Zone'] = correct_zone
886
-
887
- # # Step 7: Save results and upload to Firebase
888
- # progress(0.95, desc="Saving results...")
889
- # timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
890
-
891
- # # Save JSON with new schema
892
- # json_output_path = f"Enhanced_Real_Estate_Data_{max_rows}_records_NEW_SCHEMA_{timestamp}.json"
893
-
894
- # # Save JSON with new schema
895
- # save_results_to_json(df_cleaned.head(max_rows), json_output_path, original_data[:max_rows])
896
-
897
- # # Step 8: Upload to Firebase if requested
898
- # firebase_result = ""
899
- # if upload_to_db:
900
- # progress(0.97, desc="Uploading to Firebase Firestore...")
901
-
902
- # # Load the saved JSON data
903
- # with open(json_output_path, 'r', encoding='utf-8') as f:
904
- # json_data = json.load(f)
905
-
906
- # # Upload to Firestore
907
- # firebase_result = upload_to_firestore(json_data, "DUPLICATES")
908
- # log_output += f"\n🔥 Firebase Upload Result:\n{firebase_result}\n\n"
909
-
910
- # progress(1.0, desc="Complete!")
911
-
912
- # # Final summary
913
- # log_output += f"✅ Processing complete!\n"
914
- # log_output += f"📊 Processed {max_rows} records\n"
915
- # log_output += f"💾 JSON file saved: {json_output_path}\n"
916
- # if upload_to_db:
917
- # log_output += f"🔥 Firebase upload: {'✅ Success' if '✅' in firebase_result else '❌ Failed'}\n"
918
-
919
- # return json_output_path, log_output
920
-
921
- # except Exception as e:
922
- # return None, f"❌ Error: {str(e)}"
923
-
924
- # # --- GRADIO INTERFACE ---
925
-
926
- # def create_interface():
927
- # with gr.Blocks(title="Real Estate JSON Data Extractor with Firebase", theme=gr.themes.Soft()) as iface:
928
- # gr.Markdown("""
929
- # # 🏠 Real Estate JSON Data Extractor with Firebase Integration
930
- # Upload a JSON file with real estate auction descriptions and extract structured data using AI.
931
- # ## Features:
932
- # - 🤖 AI-powered extraction using Gemini 2.5 Flash
933
- # - 📍 Automatic micromarket and zone identification for Bangalore
934
- # - 🔧 Fixed carpet area vs super built-up area swapping
935
- # - 📊 Clean, structured output in NEW JSON schema format
936
- # - 🔥 **NEW: Firebase Firestore integration for database upload**
937
- # - 🔄 ALL original processing rules maintained
938
- # - 📁 Complete schema compliance with all required fields
939
- # - 📄 JSON output logged after each row for debugging
940
- # """)
941
-
942
- # with gr.Row():
943
- # with gr.Column():
944
- # file_input = gr.File(
945
- # label="Upload JSON File",
946
- # file_types=[".json"],
947
- # type="filepath"
948
- # )
949
-
950
- # max_rows_input = gr.Slider(
951
- # minimum=1,
952
- # maximum=1000,
953
- # value=5,
954
- # step=1,
955
- # label="Number of records to process",
956
- # info="Start with a small number to test"
957
- # )
958
-
959
- # upload_to_db_checkbox = gr.Checkbox(
960
- # label="🔥 Upload to Firebase Firestore",
961
- # value=False,
962
- # info="Upload processed data to 'DUPLICATES' collection in Firebase"
963
- # )
964
-
965
- # process_btn = gr.Button("🚀 Start Processing", variant="primary", size="lg")
966
-
967
- # with gr.Column():
968
- # output_file = gr.File(label="Download Processed JSON File (NEW SCHEMA)")
969
-
970
- # # Processing log output
971
- # log_output = gr.Textbox(
972
- # label="Processing Log (includes JSON output for each row + Firebase status)",
973
- # lines=30,
974
- # max_lines=50,
975
- # show_copy_button=True,
976
- # interactive=False
977
- # )
978
-
979
- # # Examples section
980
- # gr.Markdown("""
981
- # ## 📋 Input Requirements:
982
- # - JSON file with objects containing 'description' field
983
- # - Each object should contain real estate auction description text
984
- # - File should be in .json format
985
- # - Can be a single object or array of objects
986
-
987
- # ## 🔥 Firebase Integration:
988
- # - **Collection**: Data will be uploaded to `DUPLICATES` collection
989
- # - **Document ID**: Uses the `id` field from your JSON data (auto-generated if missing)
990
- # - **Update/Insert**: Existing documents are updated, new documents are inserted
991
- # - **Error Handling**: Comprehensive error reporting for upload issues
992
-
993
- # ## 📝 NEW OUTPUT SCHEMA:
994
- # ```json
995
- # {
996
- # "id": "string",
997
- # "source": "string",
998
- # "url": "string",
999
- # "bank": "string",
1000
- # "description": "string",
1001
- # "property_type": "string",
1002
- # "area": "string",
1003
- # "city": "Bangalore",
1004
- # "state": "Karnataka",
1005
- # "contact": "string",
1006
- # "reserved_price": "string",
1007
- # "emd_amount": "string",
1008
- # "submission_emd": "string",
1009
- # "auction_start_date": "string",
1010
- # "auction_end_date": "string",
1011
- # "pincode": "string",
1012
- # "carpet_area": "string",
1013
- # "super_built_area": "string",
1014
- # "floor": "string",
1015
- # "unit_configuration": "string",
1016
- # "address": "string",
1017
- # "asset_type": "string",
1018
- # "undivided_share": "string",
1019
- # "price_per_sqft": "string"
1020
- # }
1021
- # ```
1022
-
1023
- # ## 🎯 What it extracts and enhances:
1024
- # - All fields from the new schema
1025
- # - Price per sqft
1026
- # - Carpet Area & Super Built-up Area (with proper conversion)
1027
- # - Floor number
1028
- # - Unit Configuration (2BHK, 3BHK, etc.)
1029
- # - Clean Address (stops at Bangalore + pincode)
1030
- # - Asset Type
1031
- # - Zone & Micromarket mapping to 'area' field
1032
- # - Automatic pincode extraction from address
1033
- # - City and State auto-populated for Bangalore
1034
- # - All missing fields marked as "NA"
1035
- # - **Firebase upload with comprehensive logging**
1036
-
1037
- # ## 🔧 Key Features:
1038
- # - ✅ All original processing rules preserved
1039
- # - ✅ Enhanced zone-micromarket mapping
1040
- # - ✅ Fixed carpet/super built-up area swapping
1041
- # - ✅ Complete schema compliance
1042
- # """)
1043
- # # Event handlers
1044
- # process_btn.click(
1045
- # fn=process_real_estate_data,
1046
- # inputs=[file_input, max_rows_input, upload_to_db_checkbox],
1047
- # outputs=[output_file, log_output],
1048
- # show_progress=True
1049
- # )
1050
-
1051
- # return iface
1052
-
1053
- # # --- MAIN ---
1054
- # if __name__ == "__main__":
1055
- # print("🚀 Starting Real Estate JSON Data Extractor...")
1056
- # app = create_interface()
1057
- # app.launch(
1058
- # server_name="0.0.0.0",
1059
- # server_port=7860,
1060
- # share=True,
1061
- # show_error=True
1062
- # )
1063
-
1064
- # #
1065
  import gradio as gr
1066
  import requests
1067
  import time
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
2
  import requests
3
  import time