adema5051 commited on
Commit
65b5bf6
·
verified ·
1 Parent(s): 0102d6a

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +27 -10
main.py CHANGED
@@ -143,15 +143,23 @@ async def predict_height(data: SingleAssessment) -> Dict:
143
  raise HTTPException(status_code=500, detail=str(e))
144
 
145
 
146
- def process_single_row(row, use_predicted_height=False):
147
  """Process a single row from CSV - used for parallel processing."""
148
  try:
149
  lat = row['latitude']
150
  lon = row['longitude']
151
  height = row.get('height', 0.0)
152
  basement = row.get('basement', 0.0)
153
-
154
- if use_predicted_height:
 
 
 
 
 
 
 
 
155
  try:
156
  predictor = get_predictor()
157
  pred = predictor.predict_from_coordinates(lat, lon)
@@ -213,7 +221,7 @@ def process_single_row(row, use_predicted_height=False):
213
 
214
 
215
  @app.post("/assess_batch")
216
- async def assess_batch(file: UploadFile = File(...), use_predicted_height: bool = False) -> StreamingResponse:
217
  """Assess flood vulnerability for multiple locations from a CSV file."""
218
  try:
219
  contents = await file.read()
@@ -239,7 +247,7 @@ async def assess_batch(file: UploadFile = File(...), use_predicted_height: bool
239
  loop = asyncio.get_event_loop()
240
  results = await loop.run_in_executor(
241
  executor,
242
- lambda: [process_single_row(row, use_predicted_height) for _, row in df.iterrows()]
243
  )
244
 
245
  results_df = pd.DataFrame(results)
@@ -260,7 +268,7 @@ async def assess_batch(file: UploadFile = File(...), use_predicted_height: bool
260
  except Exception as e:
261
  raise HTTPException(status_code=500, detail=f"Batch processing failed: {str(e)}")
262
  @app.post("/assess_batch_multihazard")
263
- async def assess_batch_multihazard(file: UploadFile = File(...), use_predicted_height: bool = False) -> StreamingResponse:
264
  try:
265
  contents = await file.read()
266
  df = pd.read_csv(io.StringIO(contents.decode('utf-8')))
@@ -275,7 +283,7 @@ async def assess_batch_multihazard(file: UploadFile = File(...), use_predicted_h
275
  from vulnerability import calculate_multi_hazard_vulnerability
276
  results = await loop.run_in_executor(
277
  executor,
278
- lambda: [process_single_row_multihazard(row, use_predicted_height) for _, row in df.iterrows()]
279
  )
280
 
281
  results_df = pd.DataFrame(results)
@@ -337,7 +345,7 @@ async def explain_assessment(data: SingleAssessment) -> Dict:
337
  raise HTTPException(status_code=500, detail=f"Assessment failed: {e}")
338
 
339
 
340
- def process_single_row_multihazard(row, use_predicted_height=False):
341
  """Process a single row with multi-hazard assessment."""
342
  try:
343
  from vulnerability import calculate_multi_hazard_vulnerability
@@ -347,7 +355,16 @@ def process_single_row_multihazard(row, use_predicted_height=False):
347
  height = row.get('height', 0.0)
348
  basement = row.get('basement', 0.0)
349
 
350
- if use_predicted_height:
 
 
 
 
 
 
 
 
 
351
  try:
352
  predictor = get_predictor()
353
  pred = predictor.predict_from_coordinates(lat, lon)
@@ -444,7 +461,7 @@ async def get_height_gba(data: SingleAssessment):
444
  result = gba_getter.get_height_m(data.latitude, data.longitude, buffer_m=5.0)
445
 
446
  if result.get("status") != "success":
447
- raise HTTPException(status_code=404, detail="GBA height not found for this location")
448
 
449
  return result
450
  except HTTPException:
 
143
  raise HTTPException(status_code=500, detail=str(e))
144
 
145
 
146
+ def process_single_row(row, use_predicted_height=False, use_gba_height=False):
147
  """Process a single row from CSV - used for parallel processing."""
148
  try:
149
  lat = row['latitude']
150
  lon = row['longitude']
151
  height = row.get('height', 0.0)
152
  basement = row.get('basement', 0.0)
153
+ if use_gba_height:
154
+ try:
155
+ result = gba_getter.get_height_m(lat, lon, buffer_m=5.0)
156
+ if result.get('status') == 'success' and result.get('predicted_height') is not None:
157
+ h = result['predicted_height']
158
+ if h >= 0: # Only use valid positive heights
159
+ height = h
160
+ except Exception as e:
161
+ print(f"GBA height failed for {lat},{lon}: {e}")
162
+ elif use_predicted_height:
163
  try:
164
  predictor = get_predictor()
165
  pred = predictor.predict_from_coordinates(lat, lon)
 
221
 
222
 
223
  @app.post("/assess_batch")
224
+ async def assess_batch(file: UploadFile = File(...), use_predicted_height:bool=False, use_gba_height:bool=False) -> StreamingResponse:
225
  """Assess flood vulnerability for multiple locations from a CSV file."""
226
  try:
227
  contents = await file.read()
 
247
  loop = asyncio.get_event_loop()
248
  results = await loop.run_in_executor(
249
  executor,
250
+ lambda: [process_single_row(row, use_predicted_height, use_gba_height) for _, row in df.iterrows()]
251
  )
252
 
253
  results_df = pd.DataFrame(results)
 
268
  except Exception as e:
269
  raise HTTPException(status_code=500, detail=f"Batch processing failed: {str(e)}")
270
  @app.post("/assess_batch_multihazard")
271
+ async def assess_batch_multihazard(file: UploadFile = File(...), use_predicted_height: bool = False, use_gba_height: bool = False) -> StreamingResponse:
272
  try:
273
  contents = await file.read()
274
  df = pd.read_csv(io.StringIO(contents.decode('utf-8')))
 
283
  from vulnerability import calculate_multi_hazard_vulnerability
284
  results = await loop.run_in_executor(
285
  executor,
286
+ lambda: [process_single_row_multihazard(row, use_predicted_height, use_gba_height) for _, row in df.iterrows()]
287
  )
288
 
289
  results_df = pd.DataFrame(results)
 
345
  raise HTTPException(status_code=500, detail=f"Assessment failed: {e}")
346
 
347
 
348
+ def process_single_row_multihazard(row, use_predicted_height=False, use_gba_height=False):
349
  """Process a single row with multi-hazard assessment."""
350
  try:
351
  from vulnerability import calculate_multi_hazard_vulnerability
 
355
  height = row.get('height', 0.0)
356
  basement = row.get('basement', 0.0)
357
 
358
+ if use_gba_height:
359
+ try:
360
+ result = gba_getter.get_height_m(lat, lon, buffer_m=5.0)
361
+ if result.get('status') == 'success' and result.get('predicted_height') is not None:
362
+ h = result['predicted_height']
363
+ if h >= 0: # Only use valid positive heights
364
+ height = h
365
+ except Exception as e:
366
+ print(f"GBA height failed for {lat},{lon}: {e}")
367
+ elif use_predicted_height:
368
  try:
369
  predictor = get_predictor()
370
  pred = predictor.predict_from_coordinates(lat, lon)
 
461
  result = gba_getter.get_height_m(data.latitude, data.longitude, buffer_m=5.0)
462
 
463
  if result.get("status") != "success":
464
+ raise HTTPException(status_code=404, detail="GBA height not found for this location. Please try predicting the height.")
465
 
466
  return result
467
  except HTTPException: