forever-sheikh commited on
Commit
eaeeca4
·
verified ·
1 Parent(s): 6135042

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -295
app.py DELETED
@@ -1,295 +0,0 @@
1
- import gradio as gr
2
- import googlemaps
3
- import osmnx as ox
4
- import geopandas as gpd
5
- import pandas as pd
6
- import requests
7
- import zipfile
8
- import os
9
- import glob
10
- import shutil
11
- import time
12
- import math
13
- from shapely.geometry import Point, Polygon
14
- from shapely.ops import transform
15
-
16
- # ==========================================
17
- # AUTHENTICATION
18
- # ==========================================
19
- try:
20
- API_KEY = os.environ.get("GOOGLE_API_KEY")
21
- except:
22
- API_KEY = None
23
-
24
- # ==========================================
25
- # HELPER FUNCTIONS
26
- # ==========================================
27
- def load_geodata_to_polygon(file_obj):
28
- extract_path = "temp_extract"
29
- if os.path.exists(extract_path):
30
- shutil.rmtree(extract_path)
31
- os.makedirs(extract_path)
32
-
33
- target_kml = None
34
- try:
35
- if file_obj.name.lower().endswith('.kmz'):
36
- with zipfile.ZipFile(file_obj.name, 'r') as zip_ref:
37
- zip_ref.extractall(extract_path)
38
- kml_files = glob.glob(extract_path + "/**/*.kml", recursive=True)
39
- if kml_files:
40
- target_kml = kml_files[0]
41
- elif file_obj.name.lower().endswith('.kml'):
42
- target_kml = file_obj.name
43
-
44
- if target_kml:
45
- gdf = gpd.read_file(target_kml)
46
-
47
- # Fix 3D Coordinates (Force 2D)
48
- def force_2d(geometry):
49
- if geometry.has_z:
50
- return transform(lambda x, y, z=None: (x, y), geometry)
51
- return geometry
52
-
53
- gdf.geometry = gdf.geometry.apply(force_2d)
54
- return gdf.union_all()
55
- except Exception as e:
56
- print(f"Error loading KML: {e}")
57
- return None
58
- return None
59
-
60
- def get_roof_area(lat, lng, api_key):
61
- base_url = "https://solar.googleapis.com/v1/buildingInsights:findClosest"
62
- params = {
63
- "location.latitude": lat,
64
- "location.longitude": lng,
65
- "requiredQuality": "HIGH",
66
- "key": api_key
67
- }
68
- try:
69
- resp = requests.get(base_url, params=params)
70
- data = resp.json()
71
- if 'error' in data: return None
72
- return data.get('solarPotential', {}).get('wholeRoofStats', {}).get('areaMeters2', None)
73
- except:
74
- return None
75
-
76
- def get_osm_physics(lat, lng):
77
- try:
78
- tags = {'building': True}
79
- gdf = ox.features.features_from_point((lat, lng), tags, dist=60)
80
- if not gdf.empty:
81
- gdf_proj = gdf.to_crs(epsg=3857)
82
- gdf_proj['area_m2'] = gdf_proj.geometry.area
83
- best = gdf_proj.sort_values(by='area_m2', ascending=False).iloc[0]
84
-
85
- floors = None
86
- if 'building:levels' in best and pd.notna(best['building:levels']):
87
- try: floors = int(float(str(best['building:levels']).split(';')[0]))
88
- except: pass
89
-
90
- height = None
91
- if 'height' in best and pd.notna(best['height']):
92
- try: height = float(str(best['height']).replace('m','').strip())
93
- except: pass
94
- return height, floors
95
- except:
96
- pass
97
- return None, None
98
-
99
- def calculate_dynamic_radius(polygon):
100
- """
101
- Calculates the optimal search radius (in meters) to cover the polygon.
102
- This prevents searching 50km away and missing local stores due to API limits.
103
- """
104
- try:
105
- # Project to meters (EPSG:3857 is Web Mercator, good for distance approx)
106
- gs = gpd.GeoSeries([polygon], crs="EPSG:4326").to_crs(epsg=3857)
107
- minx, miny, maxx, maxy = gs.total_bounds
108
-
109
- # Calculate diagonal distance of the bounding box
110
- width = maxx - minx
111
- height = maxy - miny
112
- diagonal = math.sqrt(width**2 + height**2)
113
-
114
- # Radius is half the diagonal, plus a safety margin (10%)
115
- radius_meters = (diagonal / 2) * 1.1
116
-
117
- # Ensure min radius of 1km and max of 50km
118
- return max(min(radius_meters, 50000), 1000)
119
- except:
120
- return 5000 # Fallback 5km
121
-
122
- # DATA CONSTANTS
123
- BRAND_FLOORS = {
124
- "Macy's": 2, "JCPenney": 2, "Nordstrom": 2, "Sears": 2, "IKEA": 2,
125
- "Target": 1, "Walmart": 1, "Costco": 1, "Home Depot": 1, "Lowe's": 1,
126
- "Barnes & Noble": 1, "Dick's Sporting Goods": 1, "Kohl's": 1
127
- }
128
-
129
- BRAND_AVG_AREA = {
130
- "IKEA": 28000, "Walmart": 15000, "Costco": 14000, "Sam's Club": 13000,
131
- "Meijer": 18000, "Target": 12000, "Home Depot": 10000, "Lowe's": 10000,
132
- "Kroger": 6000, "Safeway": 5000, "Whole Foods": 4000, "Macy's": 16000,
133
- "JCPenney": 10000, "Sears": 12000, "Kohl's": 8000, "Dick's Sporting Goods": 4500,
134
- "T.J. Maxx": 2800, "Marshalls": 2800, "Ross Dress for Less": 2800,
135
- "Old Navy": 1400, "Barnes & Noble": 2500, "Best Buy": 3500, "Staples": 2000,
136
- "Office Depot": 2000, "PetSmart": 1800, "Petco": 1400, "Trader Joe's": 1200,
137
- "Aldi": 1500, "Lidl": 1500, "Ace Hardware": 800, "DSW Designer Shoe Warehouse": 2000
138
- }
139
-
140
- SEARCH_LIST = [
141
- "Walmart", "Target", "Kmart", "Sears", "Kohl's", "Macy's", "JCPenney",
142
- "TJX", "TJX Companies", "T.J. Maxx", "Marshalls", "HomeGoods", "HomeSense",
143
- "Ross", "Ross Dress for Less", "Burlington", "Dick's Sporting Goods",
144
- "Albertsons", "Safeway", "Home Depot", "Lowe's", "Best Buy",
145
- "IKEA", "Bob's Furniture", "Bob's Discount Furniture", "Raymour & Flanigan",
146
- "Barnes & Noble", "Office Depot", "OfficeMax", "Staples",
147
- "PetSmart", "Petco", "Kroger", "Meijer", "Costco", "BJ's Wholesale Club",
148
- "Sam's Club", "Whole Foods", "ShopRite", "Stop & Shop", "Trader Joe's",
149
- "Michaels", "Lidl", "Aldi", "DSW Designer Shoe Warehouse", "Old Navy",
150
- "Ace", "Ace Hardware", "Hobby Lobby"
151
- ]
152
-
153
- # ==========================================
154
- # MAIN LOGIC WITH GENERATOR (YIELD)
155
- # ==========================================
156
- def process_data(file_obj):
157
- if not API_KEY:
158
- yield "❌ API Key not found! Set GOOGLE_API_KEY in Secrets.", None
159
- return
160
-
161
- if file_obj is None:
162
- yield "❌ Please upload a file.", None
163
- return
164
-
165
- yield "📂 Loading Polygon...", None
166
- polygon = load_geodata_to_polygon(file_obj)
167
-
168
- if not polygon:
169
- yield "❌ Failed to read KML/KMZ file.", None
170
- return
171
-
172
- # --- CHECK AREA SIZE ---
173
- try:
174
- gs = gpd.GeoSeries([polygon], crs="EPSG:4326")
175
- gs_proj = gs.to_crs(epsg=6933)
176
- area_sq_meters = gs_proj.area.iloc[0]
177
- limit_sq_meters = 250_000_000
178
-
179
- if area_sq_meters > limit_sq_meters:
180
- yield f"⚠️ AREA TOO LARGE: {area_sq_meters:,.0f} sq m (Limit: {limit_sq_meters:,.0f}). Upload a smaller file.", None
181
- return
182
-
183
- yield f"✅ Area: {area_sq_meters:,.0f} sq m. Calculating optimal search...", None
184
-
185
- except Exception as e:
186
- print(f"Area Check Error: {e}")
187
- yield "⚠️ Area check skipped (System Error). Proceeding...", None
188
-
189
- # --- NEW: DYNAMIC RADIUS CALCULATION ---
190
- # We calculate how big the polygon is, and set the API search radius to match it.
191
- # This ensures we don't search 50km away and miss local stores.
192
- search_radius_meters = calculate_dynamic_radius(polygon)
193
- yield f"📏 Search Radius Optimized: {int(search_radius_meters)} meters...", None
194
-
195
- # --- SMALL BUFFER ---
196
- # Just a small safety buffer (approx 20 meters) to handle edge cases
197
- search_polygon = polygon.buffer(0.0002)
198
-
199
- gmaps = googlemaps.Client(key=API_KEY)
200
- results = []
201
- seen_ids = set()
202
- total_brands = len(SEARCH_LIST)
203
-
204
- for i, brand in enumerate(SEARCH_LIST):
205
- yield f"🔍 Scanning Brand {i+1}/{total_brands}: {brand}...", None
206
-
207
- try:
208
- # SEARCH WITH DYNAMIC RADIUS
209
- places = gmaps.places_nearby(
210
- location=(polygon.centroid.y, polygon.centroid.x),
211
- radius=search_radius_meters, # <--- Uses the optimized radius
212
- keyword=brand
213
- )
214
-
215
- all_results = places.get('results', [])
216
-
217
- # Fetch Next Pages (up to 2 more pages) to be safe
218
- while 'next_page_token' in places:
219
- time.sleep(2)
220
- places = gmaps.places_nearby(
221
- location=(polygon.centroid.y, polygon.centroid.x),
222
- radius=search_radius_meters,
223
- keyword=brand,
224
- page_token=places['next_page_token']
225
- )
226
- all_results.extend(places.get('results', []))
227
-
228
- for p in all_results:
229
- pid = p.get('place_id')
230
- if pid in seen_ids: continue
231
-
232
- name = p.get('name')
233
- if any(x in name for x in ["ATM", "Redbox", "Kiosk", "Coinme", "Gas", "Fuel"]): continue
234
-
235
- lat = p['geometry']['location']['lat']
236
- lng = p['geometry']['location']['lng']
237
-
238
- # STRICT GEOMETRY CHECK
239
- if not search_polygon.contains(Point(lng, lat)): continue
240
- seen_ids.add(pid)
241
-
242
- # Get Data
243
- roof_area = get_roof_area(lat, lng, API_KEY)
244
- height, floors = get_osm_physics(lat, lng)
245
-
246
- # Logic
247
- source_note = "SolarAPI"
248
- if roof_area is None:
249
- roof_area = BRAND_AVG_AREA.get(brand, 2500.0)
250
- source_note = "Brand_Avg (Missing)"
251
- else:
252
- if roof_area > 30000 and brand not in ["IKEA", "Costco", "Meijer", "Sam's Club", "Walmart"]:
253
- roof_area = BRAND_AVG_AREA.get(brand, 2500.0)
254
- source_note = "Brand_Avg (Mall detected)"
255
- elif roof_area < 500 and brand not in ["Ace Hardware", "Trader Joe's", "GameStop"]:
256
- roof_area = BRAND_AVG_AREA.get(brand, 2500.0)
257
- source_note = "Brand_Avg (Too Small detected)"
258
-
259
- if floors is None: floors = BRAND_FLOORS.get(brand, 1)
260
- if height is None: height = floors * 6.0
261
-
262
- results.append({
263
- 'Name': name, 'Brand': brand, 'Latitude': lat, 'Longitude': lng,
264
- 'Height_m': round(height, 2), 'Num_Floors': int(floors),
265
- 'Area_sqm': round(roof_area, 2), 'Data_Source': source_note
266
- })
267
- except Exception as e:
268
- print(f"❌ Error scanning {brand}: {str(e)}")
269
- pass
270
-
271
- if not results:
272
- yield "❌ No stores found in this area.", None
273
- return
274
-
275
- df = pd.DataFrame(results)
276
- bad_keywords = ['Mobile', 'Salon', 'Floral', 'Bakery', 'Pharmacy', 'Optical', 'Geek Squad', 'Photo']
277
- df = df[~df['Name'].str.contains('|'.join(bad_keywords), case=False, na=False)]
278
-
279
- output_path = "Building_Inventory.csv"
280
- df.to_csv(output_path, index=False)
281
-
282
- yield f"✅ Success! Found {len(df)} stores.", output_path
283
-
284
- iface = gr.Interface(
285
- fn=process_data,
286
- inputs=gr.File(label="Upload Polygon (Limit: 250,000,000 sq m)"),
287
- outputs=[
288
- gr.Textbox(label="Status Log"),
289
- gr.File(label="Download CSV")
290
- ],
291
- title="🏙️ Commercial Building Inventory Generator",
292
- description="Upload a KMZ file. The tool will scan for major Big Box brands (Walmart, Target, Meijer, IKEA, etc.), check Solar API for area, and OpenStreetMap for height/floors."
293
- )
294
-
295
- iface.launch()