UjjwalKGupta commited on
Commit
ca95339
·
verified ·
1 Parent(s): 8384327

Correct DEM and Slope

Browse files
Files changed (1) hide show
  1. app.py +101 -146
app.py CHANGED
@@ -25,7 +25,7 @@ def one_time_setup():
25
  try:
26
  # Attempt to initialize with default credentials
27
  ee.Initialize()
28
- except Exception as e:
29
  try:
30
  # Fallback to service account credentials if default init fails
31
  credentials_path = os.path.expanduser("~/.config/earthengine/credentials.json")
@@ -36,9 +36,6 @@ def one_time_setup():
36
  f.write(ee_credentials)
37
  credentials = ee.ServiceAccountCredentials('ujjwal@ee-ujjwaliitd.iam.gserviceaccount.com', credentials_path)
38
  ee.Initialize(credentials, project='ee-ujjwaliitd')
39
- else:
40
- # If no credentials are found, re-raise the original exception
41
- raise e
42
  except Exception as inner_e:
43
  # If the fallback also fails, print the error
44
  print(f"Earth Engine initialization failed: {inner_e}")
@@ -180,25 +177,20 @@ def get_wayback_data():
180
 
181
  # Parse XML
182
  root = ET.fromstring(response.content)
183
-
184
  ns = {
185
- "wmts": "https://www.opengis.net/wmts/1.0",
186
- "ows": "https://www.opengis.net/ows/1.1",
187
- "xlink": "https://www.w3.org/1999/xlink",
188
  }
189
 
190
- # Use a robust XPath to find all 'Layer' elements anywhere in the document.
191
- # This is less brittle than specifying the full path.
192
  layers = root.findall(".//wmts:Contents/wmts:Layer", ns)
193
 
194
  layer_data = []
195
  for layer in layers:
196
  title = layer.find("ows:Title", ns)
197
- identifier = layer.find("ows:Identifier", ns)
198
  resource = layer.find("wmts:ResourceURL", ns) # Tile URL template
199
 
200
  title_text = title.text if title is not None else "N/A"
201
- identifier_text = identifier.text if identifier is not None else "N/A"
202
  url_template = resource.get("template") if resource is not None else "N/A"
203
 
204
  layer_data.append({"Title": title_text, "ResourceURL_Template": url_template})
@@ -206,57 +198,65 @@ def get_wayback_data():
206
  wayback_df = pd.DataFrame(layer_data)
207
  wayback_df["date"] = pd.to_datetime(wayback_df["Title"].str.extract(r"(\d{4}-\d{2}-\d{2})").squeeze(), errors="coerce")
208
  wayback_df.set_index("date", inplace=True)
 
209
  return wayback_df
210
 
211
- except requests.exceptions.RequestException as e:
212
- print(f"Could not fetch Wayback data from URL: {e}")
213
- return pd.DataFrame()
214
- except ET.ParseError as e:
215
- print(f"Could not parse Wayback XML data: {e}")
216
- return pd.DataFrame()
217
- except Exception as e:
218
- print(f"An unexpected error occurred in get_wayback_data: {e}")
219
  return pd.DataFrame() # Return empty dataframe on failure
220
 
221
- def get_dem_slope_maps(ee_geometry):
222
- """Creates DEM and Slope maps from SRTM data."""
223
- one_time_setup() # Ensure GEE is initialized
224
-
225
- # --- DEM Map ---
226
- dem_map = gee_folium.Map(add_google_map=True) # Add basemap for context
227
- dem_map.centerObject(ee_geometry)
228
-
229
- dem_image = ee.Image("USGS/SRTMGL1_003").clip(ee_geometry)
230
 
231
- stats = dem_image.reduceRegion(reducer=ee.Reducer.minMax(), geometry=ee_geometry, scale=30, maxPixels=1e9).getInfo()
232
-
233
- # Check if data is available
234
- if not stats or stats.get('elevation_max') is None:
235
- dem_map_html = "<div>No DEM data available for this area.</div>"
236
- slope_map_html = "<div>No Slope data available for this area.</div>"
237
- return dem_map_html, slope_map_html
238
 
239
- min_elev, max_elev = stats['elevation_min'], stats['elevation_max']
240
- vis_params = {"min": min_elev, "max": max_elev, "palette": ["blue", "green", "yellow", "red"]}
 
 
 
 
 
 
 
 
 
 
 
 
241
 
242
- dem_map.addLayer(dem_image, vis_params, "DEM")
243
- dem_map.add_colorbar(vis_params=vis_params, label="Elevation (m)")
244
  dem_map.addLayerControl()
 
245
 
246
  # --- Slope Map ---
247
- slope_map = gee_folium.Map(add_google_map=True) # Add basemap for context
248
- slope_map.centerObject(ee_geometry)
 
 
 
249
 
250
- slope_image = ee.Terrain.slope(dem_image)
251
- slope_vis_params = {"min": 0, "max": 60, "palette": ["blue", "green", "yellow", "red"]}
 
 
 
 
 
 
252
 
253
- slope_map.addLayer(slope_image, slope_vis_params, "Slope")
254
- slope_map.add_colorbar(vis_params=slope_vis_params, label="Slope (degrees)")
255
  slope_map.addLayerControl()
 
 
 
256
 
257
- return dem_map._repr_html_(), slope_map._repr_html_()
258
 
259
- def add_indices(image, nir_band, red_band, blue_band, green_band, swir1_band, swir2_band, evi_vars):
260
  """Calculates and adds multiple vegetation indices to an Earth Engine image."""
261
  # It's safer to work with the image bands directly
262
  nir = image.select(nir_band).divide(10000)
@@ -283,7 +283,6 @@ def add_indices(image, nir_band, red_band, blue_band, green_band, swir1_band, sw
283
 
284
  # RandomForest (This part requires a pre-trained model asset in GEE)
285
  try:
286
- # FIX: Select and rename bands from the training data to match what the classifier expects.
287
  table = ee.FeatureCollection('projects/in793-aq-nb-24330048/assets/cleanedVDI').select(
288
  ["B2", "B4", "B8", "cVDI"],
289
  ["Blue", "Red", "NIR", 'cVDI']
@@ -297,11 +296,10 @@ def add_indices(image, nir_band, red_band, blue_band, green_band, swir1_band, sw
297
  classProperty=label,
298
  inputProperties=bands,
299
  )
300
- # Classify the image. The image already has bands named 'Blue', 'Red', 'NIR' from the previous select.
301
  rf = image.classify(classifier).multiply(ee.Number(0.2)).add(ee.Number(0.1)).rename('RandomForest')
302
  except Exception as e:
303
- print(f"Random Forest calculation failed: {e}") # More specific error message
304
- rf = ee.Image.constant(0).rename('RandomForest')
305
 
306
 
307
  # Cubic Function Index (CI)
@@ -333,25 +331,14 @@ def process_and_display(file_obj, url_str, buffer_m, progress=gr.Progress()):
333
 
334
  progress(0, desc="Reading and processing geometry...")
335
  try:
336
- if file_obj is not None:
337
- # Prioritize file upload
338
- input_gdf = get_gdf_from_file(file_obj)
339
- else:
340
- # Use URL if file is not provided
341
- input_gdf = get_gdf_from_url(url_str)
342
-
343
  input_gdf = preprocess_gdf(input_gdf)
344
 
345
  # Find the first valid polygon
346
- geometry_gdf = None
347
- for i in range(len(input_gdf)):
348
- temp_gdf = input_gdf.iloc[[i]]
349
- if is_valid_polygon(temp_gdf):
350
- geometry_gdf = temp_gdf
351
- break
352
 
353
  if geometry_gdf is None:
354
- return None, "No valid polygon found in the provided file or URL.", None, None, None, None, None
355
 
356
  geometry_gdf = to_best_crs(geometry_gdf)
357
 
@@ -368,19 +355,11 @@ def process_and_display(file_obj, url_str, buffer_m, progress=gr.Progress()):
368
 
369
  progress(0.5, desc="Generating maps and stats...")
370
 
371
- # Convert to EE geometry
372
- ee_geometry = ee.Geometry(json.loads(geometry_gdf.to_crs(4326).to_json())['features'][0]['geometry'])
373
-
374
- # Generate DEM and Slope maps
375
- dem_html, slope_html = get_dem_slope_maps(ee_geometry)
376
-
377
-
378
- # Create main map
379
- m = folium.Map()
380
-
381
  if not WAYBACK_DF.empty:
382
- # The DataFrame is already sorted by date, so the last item is the latest.
383
  latest_item = WAYBACK_DF.iloc[0]
 
384
  wayback_url = (
385
  latest_item["ResourceURL_Template"]
386
  .replace("{TileMatrixSet}", "GoogleMapsCompatible")
@@ -388,28 +367,27 @@ def process_and_display(file_obj, url_str, buffer_m, progress=gr.Progress()):
388
  .replace("{TileRow}", "{y}")
389
  .replace("{TileCol}", "{x}")
390
  )
391
- folium.TileLayer(
392
- tiles=wayback_url,
393
- attr=f"Esri, i-cubed, USDA, USGS, AEX, GeoEye, Getmapping, Aerogrid, IGN, IGP, UPR-EGP, and the GIS User Community | Imagery Date: {latest_item.name.strftime('%Y-%m-%d')}",
394
- name="Latest Esri Satellite"
395
- ).add_to(m)
396
 
397
- # Add geometries to the map
398
- m = add_geometry_to_map(m, geometry_gdf, buffer_geometry_gdf, opacity=0.3)
 
 
 
 
 
 
399
 
400
- # Add a layer control panel
 
 
 
401
  m.add_child(folium.LayerControl())
402
-
403
- # Fit the map view to the bounds of the geometry
404
- bounds = geometry_gdf.to_crs(epsg=4326).total_bounds
405
- map_bounds = [[bounds[1], bounds[0]], [bounds[3], bounds[2]]] # Format: [[south, west], [north, east]]
406
- m.fit_bounds(map_bounds, padding=(10, 10))
407
-
408
 
409
  # Generate stats
410
  stats_df = pd.DataFrame({
411
- "Area (ha)": [geometry_gdf.area.item() / 10000],
412
- "Perimeter (m)": [geometry_gdf.length.item()],
413
  "Centroid (Lat, Lon)": [f"({geometry_gdf.to_crs(4326).centroid.y.iloc[0]:.6f}, {geometry_gdf.to_crs(4326).centroid.x.iloc[0]:.6f})"]
414
  })
415
 
@@ -426,7 +404,6 @@ def calculate_indices(
426
  min_year, max_year, progress=gr.Progress()
427
  ):
428
  """Calculates vegetation indices based on user inputs."""
429
- # **FIX**: Ensure GEE is initialized before making any calls.
430
  one_time_setup()
431
 
432
  if not all([geometry_json, buffer_geometry_json, veg_indices]):
@@ -435,7 +412,7 @@ def calculate_indices(
435
  try:
436
  # Recreate GDFs from JSON
437
  geometry_gdf = gpd.read_file(geometry_json)
438
- buffer_geometry_gdf = gpd.read_file(buffer_geometry_json)
439
 
440
  # Convert to EE geometry
441
  ee_geometry = ee.Geometry(json.loads(geometry_gdf.to_crs(4326).to_json())['features'][0]['geometry'])
@@ -453,51 +430,42 @@ def calculate_indices(
453
  collection = (
454
  ee.ImageCollection("COPERNICUS/S2_SR_HARMONIZED")
455
  .select(
456
- ["B2", "B3", "B4", "B8", "B11", "B12", "MSK_CLDPRB"],
457
- ["Blue", "Green", "Red", "NIR", "SWIR1", "SWIR2", "MSK_CLDPRB"]
458
  )
459
- .map(lambda img: add_indices(img, 'NIR', 'Red', 'Blue', 'Green', "SWIR1", "SWIR2", evi_vars))
460
  )
461
 
462
  result_rows = []
463
- total_dates = len(dates)
464
  for i, (start_date, end_date) in enumerate(dates):
465
- progress((i + 1) / total_dates, desc=f"Processing {start_date} to {end_date}")
466
  filtered_collection = collection.filterDate(start_date, end_date).filterBounds(ee_geometry)
467
  if filtered_collection.size().getInfo() == 0:
468
  continue
469
 
470
- row = {'daterange': f"{start_date}_to_{end_date}"}
471
  for veg_index in veg_indices:
472
  mosaic = filtered_collection.qualityMosaic(veg_index)
473
 
474
- mean_dict = mosaic.reduceRegion(reducer=ee.Reducer.mean(), geometry=ee_geometry, scale=10, maxPixels=1e9).getInfo()
475
- mean_val = mean_dict.get(veg_index) if mean_dict else None
476
 
477
- buffer_mean_dict = mosaic.reduceRegion(reducer=ee.Reducer.mean(), geometry=buffer_ee_geometry, scale=10, maxPixels=1e9).getInfo()
478
- buffer_mean_val = buffer_mean_dict.get(veg_index) if buffer_mean_dict else None
479
-
480
- row[veg_index] = mean_val if mean_val is not None else np.nan
481
- row[f"{veg_index}_buffer"] = buffer_mean_val if buffer_mean_val is not None else np.nan
482
-
483
- if mean_val is not None and buffer_mean_val is not None and buffer_mean_val != 0:
484
- row[f"{veg_index}_ratio"] = mean_val / buffer_mean_val
485
- else:
486
- row[f"{veg_index}_ratio"] = np.nan
487
-
488
  result_rows.append(row)
489
 
490
  if not result_rows:
491
  return "No satellite imagery found for the selected dates.", None, None, None
492
 
493
  result_df = pd.DataFrame(result_rows).set_index('daterange')
494
- result_df.index = result_df.index.str.split('-').str[0] # Use start year as index for plotting
495
  result_df = result_df.round(3)
496
 
497
  # Create plots
498
  plots = []
499
  for veg_index in veg_indices:
500
- plot_df = result_df[[veg_index, f"{veg_index}_buffer", f"{veg_index}_ratio"]].dropna()
 
501
  if not plot_df.empty:
502
  fig = px.line(plot_df, x=plot_df.index, y=plot_df.columns, markers=True, title=f"{veg_index} Time Series")
503
  fig.update_layout(xaxis_title="Year", yaxis_title="Index Value")
@@ -510,9 +478,7 @@ def calculate_indices(
510
  traceback.print_exc()
511
  return f"An error occurred during calculation: {e}", None, None, None
512
 
513
-
514
  # --- Gradio UI Definition ---
515
-
516
  with gr.Blocks(theme=gr.themes.Soft(), title="Kamlan: KML Analyzer") as demo:
517
  # Hidden state to store geometry data
518
  geometry_data = gr.State()
@@ -534,8 +500,7 @@ with gr.Blocks(theme=gr.themes.Soft(), title="Kamlan: KML Analyzer") as demo:
534
  url_input = gr.Textbox(label="Or Provide File URL", placeholder="e.g., https://.../my_file.kml")
535
  buffer_input = gr.Number(label="Buffer (meters)", value=50)
536
  process_button = gr.Button("Process Input", variant="primary")
537
- info_box = gr.Textbox(label="Status", interactive=False)
538
-
539
  with gr.Accordion("Advanced Settings", open=False):
540
  gr.Markdown("### Select Vegetation Indices")
541
  all_veg_indices = ["GujVDI", "NDVI", "EVI", "EVI2", "RandomForest", "CI"]
@@ -560,28 +525,28 @@ with gr.Blocks(theme=gr.themes.Soft(), title="Kamlan: KML Analyzer") as demo:
560
  max_year_input = gr.Number(label="End Year", value=today.year, precision=0)
561
 
562
  calculate_button = gr.Button("Calculate Vegetation Indices", variant="primary")
 
563
 
564
  with gr.Column(scale=2):
565
  gr.Markdown("## 2. Results")
566
- stats_output = gr.DataFrame(label="Geometry Metrics")
567
  map_output = gr.HTML(label="Map View")
 
568
 
569
  gr.Markdown("### Digital Elevation Model (DEM) and Slope")
570
  with gr.Row():
571
  dem_map_output = gr.HTML(label="DEM Map")
572
  slope_map_output = gr.HTML(label="Slope Map")
573
 
574
- results_info_box = gr.Textbox(label="Calculation Status", interactive=False)
575
- timeseries_table = gr.DataFrame(label="Time Series Data")
576
- plot_output = gr.Plot(label="Time Series Plot")
577
-
 
578
 
579
  # --- Event Handlers ---
580
-
581
  def process_on_load(request: gr.Request):
582
  """Checks for a 'file_url' query parameter when the app loads and populates the URL input field."""
583
- file_url = request.query_params.get("file_url")
584
- return file_url if file_url else ""
585
 
586
  demo.load(process_on_load, None, url_input)
587
 
@@ -591,39 +556,30 @@ with gr.Blocks(theme=gr.themes.Soft(), title="Kamlan: KML Analyzer") as demo:
591
  outputs=[map_output, info_box, stats_output, dem_map_output, slope_map_output, geometry_data, buffer_geometry_data]
592
  )
593
 
594
- def calculate_wrapper(geometry_json, buffer_geometry_json, veg_indices,
595
  g, c1, c2, l, c, start_date_str, end_date_str,
596
  min_year, max_year, progress=gr.Progress()):
597
  """Wrapper to parse inputs and handle outputs for the main calculation function."""
598
  try:
599
- # Prepare inputs for the main function
600
  evi_vars = {'G': g, 'C1': c1, 'C2': c2, 'L': l, 'C': c}
601
  start_month, start_day = map(int, start_date_str.split('-'))
602
  end_month, end_day = map(int, end_date_str.split('-'))
 
603
  date_range = (datetime(2000, start_month, start_day), datetime(2000, end_month, end_day))
604
 
605
- # Call the main calculation function
606
  error_msg, df, plots, success_msg = calculate_indices(
607
- geometry_json, buffer_geometry_json, veg_indices,
608
  evi_vars, date_range, int(min_year), int(max_year), progress
609
  )
610
-
611
- # Determine the final status message to display
612
- status_message = error_msg if error_msg else success_msg
613
 
614
- # Select the first plot to display, if any exist
615
  first_plot = plots[0] if plots else None
 
616
 
617
- # Round the dataframe to 3 decimal places for display
618
- if df is not None:
619
- df = df.round(3)
620
-
621
- # Return a clean set of outputs for the UI
622
- return status_message, df, first_plot
623
 
624
  except Exception as e:
625
- # Catch any other unexpected errors during the process
626
- return f"An error occurred in the calculation wrapper: {e}", None, None
627
 
628
  calculate_button.click(
629
  fn=calculate_wrapper,
@@ -633,7 +589,7 @@ with gr.Blocks(theme=gr.themes.Soft(), title="Kamlan: KML Analyzer") as demo:
633
  date_start_input, date_end_input,
634
  min_year_input, max_year_input
635
  ],
636
- outputs=[results_info_box, timeseries_table, plot_output]
637
  )
638
 
639
  gr.HTML("""
@@ -645,4 +601,3 @@ with gr.Blocks(theme=gr.themes.Soft(), title="Kamlan: KML Analyzer") as demo:
645
 
646
  if __name__ == "__main__":
647
  demo.launch(debug=True)
648
-
 
25
  try:
26
  # Attempt to initialize with default credentials
27
  ee.Initialize()
28
+ except Exception:
29
  try:
30
  # Fallback to service account credentials if default init fails
31
  credentials_path = os.path.expanduser("~/.config/earthengine/credentials.json")
 
36
  f.write(ee_credentials)
37
  credentials = ee.ServiceAccountCredentials('ujjwal@ee-ujjwaliitd.iam.gserviceaccount.com', credentials_path)
38
  ee.Initialize(credentials, project='ee-ujjwaliitd')
 
 
 
39
  except Exception as inner_e:
40
  # If the fallback also fails, print the error
41
  print(f"Earth Engine initialization failed: {inner_e}")
 
177
 
178
  # Parse XML
179
  root = ET.fromstring(response.content)
 
180
  ns = {
181
+ "wmts": "http://www.opengis.net/wmts/1.0",
182
+ "ows": "http://www.opengis.net/ows/1.1",
183
+ "xlink": "http://www.w3.org/1999/xlink",
184
  }
185
 
 
 
186
  layers = root.findall(".//wmts:Contents/wmts:Layer", ns)
187
 
188
  layer_data = []
189
  for layer in layers:
190
  title = layer.find("ows:Title", ns)
 
191
  resource = layer.find("wmts:ResourceURL", ns) # Tile URL template
192
 
193
  title_text = title.text if title is not None else "N/A"
 
194
  url_template = resource.get("template") if resource is not None else "N/A"
195
 
196
  layer_data.append({"Title": title_text, "ResourceURL_Template": url_template})
 
198
  wayback_df = pd.DataFrame(layer_data)
199
  wayback_df["date"] = pd.to_datetime(wayback_df["Title"].str.extract(r"(\d{4}-\d{2}-\d{2})").squeeze(), errors="coerce")
200
  wayback_df.set_index("date", inplace=True)
201
+ wayback_df.sort_index(ascending=False, inplace=True) # Sort with the latest first
202
  return wayback_df
203
 
204
+ except (requests.exceptions.RequestException, ET.ParseError, Exception) as e:
205
+ print(f"Could not fetch or parse Wayback data: {e}")
 
 
 
 
 
 
206
  return pd.DataFrame() # Return empty dataframe on failure
207
 
208
+ def get_dem_slope_maps(ee_geometry, wayback_url=None, wayback_title=None):
209
+ """Creates DEM and Slope maps from SRTM data, using wayback tiles as a basemap if available."""
210
+ one_time_setup()
 
 
 
 
 
 
211
 
212
+ # --- DEM Map ---
213
+ dem_map = gee_folium.Map(center_object=ee_geometry, zoom_start=12)
214
+ if wayback_url:
215
+ dem_map.add_tile_layer(wayback_url, name=wayback_title, attribution="Esri")
216
+ else:
217
+ dem_map.add_basemap("SATELLITE")
 
218
 
219
+ try:
220
+ dem_layer = ee.Image("USGS/SRTMGL1_003").resample("bilinear").reproject(crs="EPSG:4326", scale=30).clip(ee_geometry)
221
+ stats = dem_layer.reduceRegion(reducer=ee.Reducer.minMax(), geometry=ee_geometry, scale=30, maxPixels=1e9).getInfo()
222
+
223
+ if stats and stats.get('elevation_min') is not None:
224
+ min_val, max_val = stats['elevation_min'], stats['elevation_max']
225
+ vis_params = {"min": min_val, "max": max_val, "palette": ['#0000FF', '#00FF00', '#FFFF00', '#FF0000']} # Blue to Red
226
+ dem_map.addLayer(dem_layer, vis_params, "Elevation")
227
+ dem_map.add_colorbar(vis_params=vis_params, label="Elevation (m)")
228
+ else:
229
+ dem_map_html = "<div>No DEM data available for this area.</div>"
230
+ except Exception as e:
231
+ print(f"Error creating DEM map: {e}")
232
+ dem_map_html = f"<div>Error creating DEM map: {e}</div>"
233
 
 
 
234
  dem_map.addLayerControl()
235
+ dem_map_html = dem_map._repr_html_()
236
 
237
  # --- Slope Map ---
238
+ slope_map = gee_folium.Map(center_object=ee_geometry, zoom_start=12)
239
+ if wayback_url:
240
+ slope_map.add_tile_layer(wayback_url, name=wayback_title, attribution="Esri")
241
+ else:
242
+ slope_map.add_basemap("SATELLITE")
243
 
244
+ try:
245
+ slope_layer = ee.Terrain.slope(dem_layer)
246
+ slope_vis_params = {"min": 0, "max": 60, "palette": ['#00FF00', '#FFFF00', '#FFA500', '#FF0000']} # Green to Red
247
+ slope_map.addLayer(slope_layer, slope_vis_params, "Slope")
248
+ slope_map.add_colorbar(vis_params=slope_vis_params, label="Slope (degrees)")
249
+ except Exception as e:
250
+ print(f"Error creating Slope map: {e}")
251
+ slope_map_html = f"<div>Error creating Slope map: {e}</div>"
252
 
 
 
253
  slope_map.addLayerControl()
254
+ slope_map_html = slope_map._repr_html_()
255
+
256
+ return dem_map_html, slope_map_html
257
 
 
258
 
259
+ def add_indices(image, nir_band, red_band, blue_band, green_band, evi_vars):
260
  """Calculates and adds multiple vegetation indices to an Earth Engine image."""
261
  # It's safer to work with the image bands directly
262
  nir = image.select(nir_band).divide(10000)
 
283
 
284
  # RandomForest (This part requires a pre-trained model asset in GEE)
285
  try:
 
286
  table = ee.FeatureCollection('projects/in793-aq-nb-24330048/assets/cleanedVDI').select(
287
  ["B2", "B4", "B8", "cVDI"],
288
  ["Blue", "Red", "NIR", 'cVDI']
 
296
  classProperty=label,
297
  inputProperties=bands,
298
  )
 
299
  rf = image.classify(classifier).multiply(ee.Number(0.2)).add(ee.Number(0.1)).rename('RandomForest')
300
  except Exception as e:
301
+ print(f"Random Forest calculation failed: {e}")
302
+ rf = ee.Image.constant(0).rename('RandomForest') # Return a constant image on failure
303
 
304
 
305
  # Cubic Function Index (CI)
 
331
 
332
  progress(0, desc="Reading and processing geometry...")
333
  try:
334
+ input_gdf = get_gdf_from_file(file_obj) if file_obj is not None else get_gdf_from_url(url_str)
 
 
 
 
 
 
335
  input_gdf = preprocess_gdf(input_gdf)
336
 
337
  # Find the first valid polygon
338
+ geometry_gdf = next((input_gdf.iloc[[i]] for i in range(len(input_gdf)) if is_valid_polygon(input_gdf.iloc[[i]])), None)
 
 
 
 
 
339
 
340
  if geometry_gdf is None:
341
+ return None, "No valid polygon found in the provided file.", None, None, None, None, None
342
 
343
  geometry_gdf = to_best_crs(geometry_gdf)
344
 
 
355
 
356
  progress(0.5, desc="Generating maps and stats...")
357
 
358
+ # --- Generate Maps ---
359
+ wayback_url, wayback_title = None, None
 
 
 
 
 
 
 
 
360
  if not WAYBACK_DF.empty:
 
361
  latest_item = WAYBACK_DF.iloc[0]
362
+ wayback_title = f"Esri Wayback ({latest_item.name.strftime('%Y-%m-%d')})"
363
  wayback_url = (
364
  latest_item["ResourceURL_Template"]
365
  .replace("{TileMatrixSet}", "GoogleMapsCompatible")
 
367
  .replace("{TileRow}", "{y}")
368
  .replace("{TileCol}", "{x}")
369
  )
 
 
 
 
 
370
 
371
+ # Convert to EE geometry for DEM/Slope maps
372
+ ee_geometry = ee.Geometry(json.loads(geometry_gdf.to_crs(4326).to_json())['features'][0]['geometry'])
373
+ dem_html, slope_html = get_dem_slope_maps(ee_geometry, wayback_url, wayback_title)
374
+
375
+ # Create main map with folium
376
+ bounds = geometry_gdf.to_crs(epsg=4326).total_bounds
377
+ map_center = [(bounds[1] + bounds[3]) / 2, (bounds[0] + bounds[2]) / 2]
378
+ m = folium.Map(location=map_center)
379
 
380
+ if wayback_url:
381
+ folium.TileLayer(tiles=wayback_url, attr="Esri", name=wayback_title).add_to(m)
382
+
383
+ m = add_geometry_to_map(m, geometry_gdf, buffer_geometry_gdf)
384
  m.add_child(folium.LayerControl())
385
+ m.fit_bounds([[bounds[1], bounds[0]], [bounds[3], bounds[2]]])
 
 
 
 
 
386
 
387
  # Generate stats
388
  stats_df = pd.DataFrame({
389
+ "Area (ha)": [f"{geometry_gdf.area.item() / 10000:.2f}"],
390
+ "Perimeter (m)": [f"{geometry_gdf.length.item():.2f}"],
391
  "Centroid (Lat, Lon)": [f"({geometry_gdf.to_crs(4326).centroid.y.iloc[0]:.6f}, {geometry_gdf.to_crs(4326).centroid.x.iloc[0]:.6f})"]
392
  })
393
 
 
404
  min_year, max_year, progress=gr.Progress()
405
  ):
406
  """Calculates vegetation indices based on user inputs."""
 
407
  one_time_setup()
408
 
409
  if not all([geometry_json, buffer_geometry_json, veg_indices]):
 
412
  try:
413
  # Recreate GDFs from JSON
414
  geometry_gdf = gpd.read_file(geometry_json)
415
+ buffer_geometry_gdf = gpd.read_file(buffer_json)
416
 
417
  # Convert to EE geometry
418
  ee_geometry = ee.Geometry(json.loads(geometry_gdf.to_crs(4326).to_json())['features'][0]['geometry'])
 
430
  collection = (
431
  ee.ImageCollection("COPERNICUS/S2_SR_HARMONIZED")
432
  .select(
433
+ ["B2", "B3", "B4", "B8", "MSK_CLDPRB"],
434
+ ["Blue", "Green", "Red", "NIR", "MSK_CLDPRB"]
435
  )
436
+ .map(lambda img: add_indices(img, 'NIR', 'Red', 'Blue', 'Green', evi_vars))
437
  )
438
 
439
  result_rows = []
 
440
  for i, (start_date, end_date) in enumerate(dates):
441
+ progress((i + 1) / len(dates), desc=f"Processing {start_date} to {end_date}")
442
  filtered_collection = collection.filterDate(start_date, end_date).filterBounds(ee_geometry)
443
  if filtered_collection.size().getInfo() == 0:
444
  continue
445
 
446
+ row = {'daterange': f"{start_date.split('-')[0]}"}
447
  for veg_index in veg_indices:
448
  mosaic = filtered_collection.qualityMosaic(veg_index)
449
 
450
+ mean_val = mosaic.reduceRegion(reducer=ee.Reducer.mean(), geometry=ee_geometry, scale=10, maxPixels=1e9).get(veg_index).getInfo()
451
+ buffer_mean_val = mosaic.reduceRegion(reducer=ee.Reducer.mean(), geometry=buffer_ee_geometry, scale=10, maxPixels=1e9).get(veg_index).getInfo()
452
 
453
+ row[veg_index] = mean_val
454
+ row[f"{veg_index}_buffer"] = buffer_mean_val
455
+ row[f"{veg_index}_ratio"] = (mean_val / buffer_mean_val) if buffer_mean_val else np.nan
 
 
 
 
 
 
 
 
456
  result_rows.append(row)
457
 
458
  if not result_rows:
459
  return "No satellite imagery found for the selected dates.", None, None, None
460
 
461
  result_df = pd.DataFrame(result_rows).set_index('daterange')
 
462
  result_df = result_df.round(3)
463
 
464
  # Create plots
465
  plots = []
466
  for veg_index in veg_indices:
467
+ plot_cols = [col for col in [veg_index, f"{veg_index}_buffer", f"{veg_index}_ratio"] if col in result_df.columns]
468
+ plot_df = result_df[plot_cols].dropna()
469
  if not plot_df.empty:
470
  fig = px.line(plot_df, x=plot_df.index, y=plot_df.columns, markers=True, title=f"{veg_index} Time Series")
471
  fig.update_layout(xaxis_title="Year", yaxis_title="Index Value")
 
478
  traceback.print_exc()
479
  return f"An error occurred during calculation: {e}", None, None, None
480
 
 
481
  # --- Gradio UI Definition ---
 
482
  with gr.Blocks(theme=gr.themes.Soft(), title="Kamlan: KML Analyzer") as demo:
483
  # Hidden state to store geometry data
484
  geometry_data = gr.State()
 
500
  url_input = gr.Textbox(label="Or Provide File URL", placeholder="e.g., https://.../my_file.kml")
501
  buffer_input = gr.Number(label="Buffer (meters)", value=50)
502
  process_button = gr.Button("Process Input", variant="primary")
503
+
 
504
  with gr.Accordion("Advanced Settings", open=False):
505
  gr.Markdown("### Select Vegetation Indices")
506
  all_veg_indices = ["GujVDI", "NDVI", "EVI", "EVI2", "RandomForest", "CI"]
 
525
  max_year_input = gr.Number(label="End Year", value=today.year, precision=0)
526
 
527
  calculate_button = gr.Button("Calculate Vegetation Indices", variant="primary")
528
+ info_box = gr.Textbox(label="Status", interactive=False)
529
 
530
  with gr.Column(scale=2):
531
  gr.Markdown("## 2. Results")
 
532
  map_output = gr.HTML(label="Map View")
533
+ stats_output = gr.DataFrame(label="Geometry Metrics")
534
 
535
  gr.Markdown("### Digital Elevation Model (DEM) and Slope")
536
  with gr.Row():
537
  dem_map_output = gr.HTML(label="DEM Map")
538
  slope_map_output = gr.HTML(label="Slope Map")
539
 
540
+ with gr.Tabs():
541
+ with gr.TabItem("Time Series Plot"):
542
+ plot_output = gr.Plot(label="Time Series Plot")
543
+ with gr.TabItem("Time Series Data"):
544
+ timeseries_table = gr.DataFrame(label="Time Series Data")
545
 
546
  # --- Event Handlers ---
 
547
  def process_on_load(request: gr.Request):
548
  """Checks for a 'file_url' query parameter when the app loads and populates the URL input field."""
549
+ return request.query_params.get("file_url", "")
 
550
 
551
  demo.load(process_on_load, None, url_input)
552
 
 
556
  outputs=[map_output, info_box, stats_output, dem_map_output, slope_map_output, geometry_data, buffer_geometry_data]
557
  )
558
 
559
+ def calculate_wrapper(geometry_json, buffer_json, veg_indices,
560
  g, c1, c2, l, c, start_date_str, end_date_str,
561
  min_year, max_year, progress=gr.Progress()):
562
  """Wrapper to parse inputs and handle outputs for the main calculation function."""
563
  try:
 
564
  evi_vars = {'G': g, 'C1': c1, 'C2': c2, 'L': l, 'C': c}
565
  start_month, start_day = map(int, start_date_str.split('-'))
566
  end_month, end_day = map(int, end_date_str.split('-'))
567
+ # Use a placeholder year; the actual year is iterated inside the main function
568
  date_range = (datetime(2000, start_month, start_day), datetime(2000, end_month, end_day))
569
 
 
570
  error_msg, df, plots, success_msg = calculate_indices(
571
+ geometry_json, buffer_json, veg_indices,
572
  evi_vars, date_range, int(min_year), int(max_year), progress
573
  )
 
 
 
574
 
575
+ status_message = error_msg or success_msg
576
  first_plot = plots[0] if plots else None
577
+ df_display = df.round(3) if df is not None else None
578
 
579
+ return status_message, df_display, first_plot
 
 
 
 
 
580
 
581
  except Exception as e:
582
+ return f"An error occurred in the wrapper: {e}", None, None
 
583
 
584
  calculate_button.click(
585
  fn=calculate_wrapper,
 
589
  date_start_input, date_end_input,
590
  min_year_input, max_year_input
591
  ],
592
+ outputs=[info_box, timeseries_table, plot_output]
593
  )
594
 
595
  gr.HTML("""
 
601
 
602
  if __name__ == "__main__":
603
  demo.launch(debug=True)