Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -3,18 +3,29 @@ Hugging Face Space Entry Point for Project Vaayu
|
|
| 3 |
Serves both an interactive Gradio interface and REST API endpoints for Vercel.
|
| 4 |
"""
|
| 5 |
|
|
|
|
| 6 |
import io
|
| 7 |
import base64
|
|
|
|
| 8 |
import numpy as np
|
| 9 |
from pathlib import Path
|
| 10 |
from PIL import Image
|
| 11 |
import gradio as gr
|
| 12 |
from fastapi import FastAPI, File, UploadFile, Form
|
| 13 |
from fastapi.middleware.cors import CORSMiddleware
|
| 14 |
-
from fastapi.responses import JSONResponse
|
|
|
|
| 15 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
from inference import VaayuSegmentationModel
|
| 17 |
|
|
|
|
| 18 |
app = FastAPI(title="Vaayu Geospatial AI API")
|
| 19 |
|
| 20 |
# Enable CORS for Vercel & localhost
|
|
@@ -26,6 +37,7 @@ app.add_middleware(
|
|
| 26 |
allow_headers=["*"],
|
| 27 |
)
|
| 28 |
|
|
|
|
| 29 |
model_instance = None
|
| 30 |
|
| 31 |
def get_model():
|
|
@@ -63,6 +75,52 @@ def dataset_stats():
|
|
| 63 |
},
|
| 64 |
"avg_structure_area_m2": 87.3,
|
| 65 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 66 |
return JSONResponse(content=stats)
|
| 67 |
|
| 68 |
@app.post("/api/predict")
|
|
@@ -117,12 +175,13 @@ async def predict_api(
|
|
| 117 |
except Exception as e:
|
| 118 |
return JSONResponse(status_code=500, content={"error": str(e)})
|
| 119 |
|
| 120 |
-
# --- Gradio
|
| 121 |
|
| 122 |
def gradio_predict(input_image, feature_type, confidence_threshold):
|
| 123 |
if input_image is None:
|
| 124 |
return None, None, "Please upload an orthophoto image."
|
| 125 |
|
|
|
|
| 126 |
temp_p = "temp_gradio_input.png"
|
| 127 |
Image.fromarray(input_image).save(temp_p)
|
| 128 |
|
|
@@ -141,6 +200,7 @@ def gradio_predict(input_image, feature_type, confidence_threshold):
|
|
| 141 |
|
| 142 |
return res["overlay"], res["mask"], summary
|
| 143 |
|
|
|
|
| 144 |
demo = gr.Interface(
|
| 145 |
fn=gradio_predict,
|
| 146 |
inputs=[
|
|
|
|
| 3 |
Serves both an interactive Gradio interface and REST API endpoints for Vercel.
|
| 4 |
"""
|
| 5 |
|
| 6 |
+
import os
|
| 7 |
import io
|
| 8 |
import base64
|
| 9 |
+
import json
|
| 10 |
import numpy as np
|
| 11 |
from pathlib import Path
|
| 12 |
from PIL import Image
|
| 13 |
import gradio as gr
|
| 14 |
from fastapi import FastAPI, File, UploadFile, Form
|
| 15 |
from fastapi.middleware.cors import CORSMiddleware
|
| 16 |
+
from fastapi.responses import JSONResponse, StreamingResponse
|
| 17 |
+
from fastapi.staticfiles import StaticFiles
|
| 18 |
|
| 19 |
+
try:
|
| 20 |
+
import spaces
|
| 21 |
+
has_spaces = True
|
| 22 |
+
except ImportError:
|
| 23 |
+
has_spaces = False
|
| 24 |
+
|
| 25 |
+
# Import existing inference engine
|
| 26 |
from inference import VaayuSegmentationModel
|
| 27 |
|
| 28 |
+
# Initialize FastAPI App
|
| 29 |
app = FastAPI(title="Vaayu Geospatial AI API")
|
| 30 |
|
| 31 |
# Enable CORS for Vercel & localhost
|
|
|
|
| 37 |
allow_headers=["*"],
|
| 38 |
)
|
| 39 |
|
| 40 |
+
# Initialize Model Instance
|
| 41 |
model_instance = None
|
| 42 |
|
| 43 |
def get_model():
|
|
|
|
| 75 |
},
|
| 76 |
"avg_structure_area_m2": 87.3,
|
| 77 |
}
|
| 78 |
+
|
| 79 |
+
try:
|
| 80 |
+
import shapefile
|
| 81 |
+
bldg_path = Path("sample_data/ShapeFiles/LalPur/Gujarat_Build_Up_Area_Type.shp")
|
| 82 |
+
road_path = Path("sample_data/ShapeFiles/LalPur/Gujarat_Road.shp")
|
| 83 |
+
|
| 84 |
+
if bldg_path.exists():
|
| 85 |
+
sf_b = shapefile.Reader(str(bldg_path))
|
| 86 |
+
sf_r = shapefile.Reader(str(road_path))
|
| 87 |
+
recs = sf_b.records()
|
| 88 |
+
roof_counts = {"RCC / Concrete": 0, "Tiled / Terracotta": 0, "Tin / Metal Sheet": 0, "Others": 0}
|
| 89 |
+
areas = []
|
| 90 |
+
table_data = []
|
| 91 |
+
|
| 92 |
+
for idx, r in enumerate(recs):
|
| 93 |
+
d = r.as_dict()
|
| 94 |
+
rt = d.get("roof_type", 1)
|
| 95 |
+
area = float(d.get("area_sqm", 0.0) or d.get("area_geo", 0.0) or 0.0)
|
| 96 |
+
areas.append(area)
|
| 97 |
+
|
| 98 |
+
if rt == 1:
|
| 99 |
+
roof_counts["RCC / Concrete"] += 1
|
| 100 |
+
elif rt == 2:
|
| 101 |
+
roof_counts["Tiled / Terracotta"] += 1
|
| 102 |
+
elif rt == 3:
|
| 103 |
+
roof_counts["Tin / Metal Sheet"] += 1
|
| 104 |
+
else:
|
| 105 |
+
roof_counts["Others"] += 1
|
| 106 |
+
|
| 107 |
+
if idx < 20:
|
| 108 |
+
table_data.append({
|
| 109 |
+
"objectId": d.get("objectid", idx),
|
| 110 |
+
"roofType": "RCC / Concrete" if rt == 1 else "Tiled / Terracotta" if rt == 2 else "Tin / Metal Sheet" if rt == 3 else "Others",
|
| 111 |
+
"areaSqm": round(area, 2),
|
| 112 |
+
"propertyId": d.get("property_i") or d.get("uniq_id") or f"LAL-PROP-{d.get('objectid', idx)}",
|
| 113 |
+
"village": d.get("village_na") or "Lalpur"
|
| 114 |
+
})
|
| 115 |
+
|
| 116 |
+
stats["total_buildings"] = len(recs)
|
| 117 |
+
stats["total_roads"] = len(sf_r)
|
| 118 |
+
stats["roof_types"] = roof_counts
|
| 119 |
+
stats["avg_structure_area_m2"] = round(float(np.mean(areas)), 1) if areas else 0
|
| 120 |
+
stats["sample_records"] = table_data
|
| 121 |
+
except Exception as e:
|
| 122 |
+
stats["shapefile_note"] = f"Fallback stats: {e}"
|
| 123 |
+
|
| 124 |
return JSONResponse(content=stats)
|
| 125 |
|
| 126 |
@app.post("/api/predict")
|
|
|
|
| 175 |
except Exception as e:
|
| 176 |
return JSONResponse(status_code=500, content={"error": str(e)})
|
| 177 |
|
| 178 |
+
# --- Gradio UI Component ---
|
| 179 |
|
| 180 |
def gradio_predict(input_image, feature_type, confidence_threshold):
|
| 181 |
if input_image is None:
|
| 182 |
return None, None, "Please upload an orthophoto image."
|
| 183 |
|
| 184 |
+
# Save temp image for inference
|
| 185 |
temp_p = "temp_gradio_input.png"
|
| 186 |
Image.fromarray(input_image).save(temp_p)
|
| 187 |
|
|
|
|
| 200 |
|
| 201 |
return res["overlay"], res["mask"], summary
|
| 202 |
|
| 203 |
+
# Build Gradio Interface
|
| 204 |
demo = gr.Interface(
|
| 205 |
fn=gradio_predict,
|
| 206 |
inputs=[
|