rishab1090 commited on
Commit
eb0f67e
·
verified ·
1 Parent(s): f0e5b0e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +31 -9
app.py CHANGED
@@ -23,20 +23,41 @@ def _normalize_to_png(arr: np.ndarray, clip_high_if_needed=True) -> Image.Image:
23
  a = (a * 255).astype(np.uint8)
24
  return Image.fromarray(a)
25
 
26
-
27
  def _mask_from_geojson(ds: rasterio.io.DatasetReader, gj_text: str | None) -> np.ndarray:
28
- if not gj_text:
 
 
29
  return np.ones((ds.height, ds.width), dtype=bool)
 
 
 
 
 
30
  try:
31
  gj = json.loads(gj_text)
32
  except Exception:
33
- raise ValueError("Invalid GeoJSON text provided.")
34
- if gj.get("type") == "FeatureCollection":
35
- geoms = [shape(f["geometry"]) for f in gj["features"]]
36
- elif gj.get("type") == "Feature":
37
- geoms = [shape(gj["geometry"])]
38
- else:
39
- geoms = [shape(gj)]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40
  mask = rasterize(
41
  [(g, 1) for g in geoms],
42
  out_shape=(ds.height, ds.width),
@@ -48,6 +69,7 @@ def _mask_from_geojson(ds: rasterio.io.DatasetReader, gj_text: str | None) -> np
48
  return mask
49
 
50
 
 
51
  def _open_geotiff_strict(path: str) -> rasterio.io.DatasetReader:
52
  """
53
  Open the raster and ensure it's a GeoTIFF/COG.
 
23
  a = (a * 255).astype(np.uint8)
24
  return Image.fromarray(a)
25
 
 
26
  def _mask_from_geojson(ds: rasterio.io.DatasetReader, gj_text: str | None) -> np.ndarray:
27
+ """Return a boolean mask for the AOI. If text is empty/invalid, return full-extent mask."""
28
+ # Full-extent mask helper
29
+ def full_mask():
30
  return np.ones((ds.height, ds.width), dtype=bool)
31
+
32
+ if not gj_text or not str(gj_text).strip():
33
+ return full_mask()
34
+
35
+ # Try parse JSON; on failure -> full mask (do not crash job)
36
  try:
37
  gj = json.loads(gj_text)
38
  except Exception:
39
+ return full_mask()
40
+
41
+ # Accept FeatureCollection / Feature / raw geometry
42
+ try:
43
+ if isinstance(gj, dict) and gj.get("type") == "FeatureCollection":
44
+ geoms = [shape(f["geometry"]) for f in gj.get("features", []) if "geometry" in f]
45
+ elif isinstance(gj, dict) and gj.get("type") == "Feature":
46
+ geoms = [shape(gj["geometry"])]
47
+ elif isinstance(gj, dict) and "type" in gj:
48
+ geoms = [shape(gj)]
49
+ # Also accept a bare coordinate ring (list) like [[x,y], ...]
50
+ elif isinstance(gj, (list, tuple)) and gj and isinstance(gj[0], (list, tuple)):
51
+ from shapely.geometry import Polygon
52
+ geoms = [Polygon(gj)]
53
+ else:
54
+ return full_mask()
55
+ except Exception:
56
+ return full_mask()
57
+
58
+ if not geoms:
59
+ return full_mask()
60
+
61
  mask = rasterize(
62
  [(g, 1) for g in geoms],
63
  out_shape=(ds.height, ds.width),
 
69
  return mask
70
 
71
 
72
+
73
  def _open_geotiff_strict(path: str) -> rasterio.io.DatasetReader:
74
  """
75
  Open the raster and ensure it's a GeoTIFF/COG.