Ritu-AI / scripts /generate_mask.py
SeriousSam07's picture
features- Enhanced Map and what if simlulation and heat pockets.
0c02b78
Raw History Blame Contribute Delete
2.21 kB
import requests
import json
from shapely.geometry import shape, mapping, Polygon, MultiPolygon
from shapely.ops import unary_union
import urllib.parse
def fetch_boundary(state):
url = f"https://nominatim.openstreetmap.org/search?state={urllib.parse.quote(state)}&country=India&polygon_geojson=1&format=json"
headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 Safari/537.36"}
res = requests.get(url, headers=headers)
res.raise_for_status()
data = res.json()
for item in data:
if item.get('geojson') and item['geojson']['type'] in ['Polygon', 'MultiPolygon']:
return shape(item['geojson'])
return None
states = ["Maharashtra", "Goa", "Karnataka"]
polys = []
for s in states:
print(f"Fetching {s} boundary...")
poly = fetch_boundary(s)
if poly:
polys.append(poly)
else:
print(f"Could not find boundary for {s}")
if polys:
print("Merging boundaries...")
merged = unary_union(polys)
# Create an outer bounding box that covers the world (or a large enough area)
outer = Polygon([(-180, -90), (180, -90), (180, 90), (-180, 90)])
# Create the inverse mask (hole)
mask = outer.difference(merged)
geojson_mask = {
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"geometry": mapping(mask),
"properties": {}
}
]
}
geojson_bounds = {
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"geometry": mapping(merged),
"properties": {}
}
]
}
out_mask_path = "frontend/public/data/multi_state_mask.json"
out_bounds_path = "frontend/public/data/state_boundaries.json"
with open(out_mask_path, 'w') as f:
json.dump(geojson_mask, f)
with open(out_bounds_path, 'w') as f:
json.dump(geojson_bounds, f)
print(f"Mask saved to {out_mask_path}")
print(f"Boundaries saved to {out_bounds_path}")
else:
print("Failed to fetch polygons.")