-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnew_architecture.py
More file actions
1576 lines (1260 loc) Β· 58.4 KB
/
new_architecture.py
File metadata and controls
1576 lines (1260 loc) Β· 58.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
New Clean Architecture for Geospatial Agent
================================================================================
"""
import os
import requests
import json
import statistics
import re
import traceback
from typing import Dict, Any, List, Optional, Tuple
from datetime import datetime
import tempfile
# LangGraph and LLM imports
from langchain_google_genai import ChatGoogleGenerativeAI
from langgraph.graph import StateGraph
from dotenv import load_dotenv
# Geospatial processing imports
import pandas as pd
import geopandas as gpd
import rasterio
from rasterio.mask import mask
from rasterio.merge import merge as rio_merge
from rasterio.mask import mask as rio_mask
from shapely.geometry import Point, box, shape, Polygon
from shapely.ops import transform as shp_transform
import pyproj
from pyproj import CRS, Transformer
from geopy.geocoders import Nominatim
from geopy.distance import geodesic as geopy_geodesic
import numpy as np
import ee
import geemap
load_dotenv()
# Initialize Earth Engine
GEE_PROJECT = os.getenv("GEE_PROJECT", "apt-achievment-453417-h6")
try:
ee.Initialize(project=GEE_PROJECT)
print(f"β
Earth Engine initialized with project: {GEE_PROJECT}")
except Exception as e:
print(f"β οΈ Earth Engine initialization failed: {e}")
# ============================================================================
GEMINI_API_KEY = os.getenv("GEMINI_API_KEY")
CORE_STACK_API_KEY = os.getenv("CORE_STACK_API_KEY")
if not GEMINI_API_KEY or not CORE_STACK_API_KEY:
raise ValueError("GEMINI_API_KEY and CORE_STACK_API_KEY must be set in environment")
# API Configuration
BASE_URL = "https://geoserver.core-stack.org/api/v1/"
API_HEADERS = {"X-API-Key": CORE_STACK_API_KEY}
# ============================================================================
# CORESTACK API WRAPPER FUNCTIONS
# ============================================================================
class CoreStackAPI:
"""
Wrapper for all CoreStack API endpoints with proper coupling.
Based on official Swagger documentation.
"""
def __init__(self, api_key: str, base_url: str = BASE_URL):
self.api_key = api_key
self.base_url = base_url
self.headers = {"X-API-Key": api_key}
# ========================================================================
# GROUP 1: SPATIAL LAYER ACCESS (Coupled APIs)
# ========================================================================
def get_admin_details_by_latlon(self, latitude: float, longitude: float) -> Dict[str, Any]:
"""
Get administrative details (state, district, tehsil) from coordinates.
Swagger: GET /get_admin_details_by_latlon/
Parameters: latitude (float), longitude (float)
Returns: {"State": str, "District": str, "Tehsil": str}
Use case: Required before calling get_generated_layer_urls
"""
print(f"\nπ‘ API CALL: get_admin_details_by_latlon")
print(f" Params: latitude={latitude}, longitude={longitude}")
params = {"latitude": latitude, "longitude": longitude}
response = requests.get(
f"{self.base_url}get_admin_details_by_latlon/",
params=params,
headers=self.headers
)
if response.status_code == 200:
result = response.json()
print(f"π¦ RESPONSE: State={result.get('State')}, District={result.get('District')}, Tehsil={result.get('Tehsil')}")
return result
else:
error_msg = f"Admin details lookup failed: {response.text}"
print(f"β ERROR: {error_msg}")
raise Exception(error_msg)
def get_generated_layer_urls(self, state: str, district: str, tehsil: str) -> List[Dict[str, Any]]:
"""
Get all available spatial layers for a location.
Swagger: GET /get_generated_layer_urls/
Parameters: state (str), district (str), tehsil (str)
Returns: List of {layer_name: str, layer_url: str, layer_type: str}
Dependencies: Requires state/district/tehsil from get_admin_details_by_latlon
"""
print(f"\nπ‘ API CALL: get_generated_layer_urls")
print(f" Params: state={state}, district={district}, tehsil={tehsil}")
params = {
'state': state,
'district': district,
'tehsil': tehsil
}
response = requests.get(
f"{self.base_url}get_generated_layer_urls/",
params=params,
headers=self.headers
)
if response.status_code == 200:
layers = response.json()
vector_count = sum(1 for l in layers if l.get('layer_type') == 'vector')
raster_count = sum(1 for l in layers if l.get('layer_type') == 'raster')
print(f"π¦ RESPONSE: {len(layers)} total layers ({vector_count} vector, {raster_count} raster)")
# Print layer names only (not full details)
layer_names = [l.get('layer_name', 'Unknown') for l in layers[:5]]
if len(layers) > 5:
print(f" First 5 layers: {', '.join(layer_names)} ... (+{len(layers)-5} more)")
else:
print(f" Layers: {', '.join(layer_names)}")
return layers
else:
error_msg = f"Layer fetch failed: {response.text}"
print(f"β ERROR: {error_msg}")
raise Exception(error_msg)
def get_spatial_layers_by_coordinates(self, latitude: float, longitude: float) -> Tuple[Dict, List[Dict]]:
"""
COUPLED API: Get spatial layers for coordinates (combines both APIs).
Workflow:
1. get_admin_details_by_latlon(lat, lon) β state/district/tehsil
2. get_generated_layer_urls(state, district, tehsil) β layers
Returns: (admin_info, layers)
"""
print("\n" + "="*70)
print("π COUPLED API WORKFLOW: Spatial Layers by Coordinates")
print("="*70)
# Step 1: Get admin boundaries
admin_info = self.get_admin_details_by_latlon(latitude, longitude)
# Step 2: Get layers using admin info
layers = self.get_generated_layer_urls(
state=admin_info.get('State', admin_info.get('state')),
district=admin_info.get('District', admin_info.get('district')),
tehsil=admin_info.get('Tehsil', admin_info.get('tehsil'))
)
return admin_info, layers
# ========================================================================
# GROUP 2: WATERSHED TIMESERIES DATA (Coupled APIs)
# ========================================================================
def get_mwsid_by_latlon(self, latitude: float, longitude: float) -> Dict[str, Any]:
"""
Get watershed UID from coordinates.
Swagger: GET /get_mwsid_by_latlon/
Parameters: latitude (float), longitude (float)
Returns: {"uid": str, "state": str, "district": str, "tehsil": str}
Use case: Required before calling get_mws_data for timeseries
Note: NOT for spatial layers! Use get_admin_details_by_latlon instead.
"""
print(f"\nπ‘ API CALL: get_mwsid_by_latlon")
print(f" Params: latitude={latitude}, longitude={longitude}")
params = {"latitude": latitude, "longitude": longitude}
response = requests.get(
f"{self.base_url}get_mwsid_by_latlon/",
params=params,
headers=self.headers
)
if response.status_code == 200:
result = response.json()
print(f"π¦ RESPONSE: UID={result.get('uid')}")
return result
else:
error_msg = f"Watershed lookup failed: {response.text}"
print(f"β ERROR: {error_msg}")
raise Exception(error_msg)
def get_mws_data(self, uid: str) -> Dict[str, Any]:
"""
Get timeseries data for a watershed.
Swagger: GET /get_mws_data/
Parameters: uid (str)
Returns: Timeseries data with year/value/source arrays
Dependencies: Requires UID from get_mwsid_by_latlon
"""
print(f"\nπ‘ API CALL: get_mws_data")
print(f" Params: uid={uid}")
params = {"uid": uid}
response = requests.get(
f"{self.base_url}get_mws_data/",
params=params,
headers=self.headers
)
if response.status_code == 200:
result = response.json()
print(f"π¦ RESPONSE: Timeseries data retrieved")
return result
else:
error_msg = f"Timeseries fetch failed: {response.text}"
print(f"β ERROR: {error_msg}")
raise Exception(error_msg)
def get_timeseries_by_coordinates(self, latitude: float, longitude: float) -> Tuple[Dict, Dict]:
"""
COUPLED API: Get timeseries data for coordinates (combines both APIs).
Workflow:
1. get_mwsid_by_latlon(lat, lon) β uid
2. get_mws_data(uid) β timeseries
Returns: (watershed_info, timeseries_data)
"""
print("\n" + "="*70)
print("π COUPLED API WORKFLOW: Timeseries by Coordinates")
print("="*70)
# Step 1: Get watershed UID
watershed_info = self.get_mwsid_by_latlon(latitude, longitude)
# Step 2: Get timeseries data
uid = watershed_info.get('uid')
timeseries_data = self.get_mws_data(uid)
return watershed_info, timeseries_data
# ============================================================================
# UTILITY FUNCTIONS
# ============================================================================
def geocode_location(location_name: str) -> Optional[Tuple[float, float]]:
"""Geocode a location name to coordinates (latitude, longitude)"""
try:
geolocator = Nominatim(user_agent="geospatial_agent")
location = geolocator.geocode(location_name)
if location:
return (location.latitude, location.longitude)
except Exception as e:
print(f"Geocoding error: {e}")
return None
def geodesic_buffer(lon: float, lat: float, radius_m: float, out_crs: str = "EPSG:4326") -> Polygon:
"""
Create a circular buffer around a point using geodesic distance.
Args:
lon: Longitude of center point
lat: Latitude of center point
radius_m: Buffer radius in meters
out_crs: Output coordinate reference system
Returns:
Shapely Polygon representing the buffer
"""
from pyproj import Geod
geod = Geod(ellps="WGS84")
angles = np.linspace(0, 360, 64)
circle_points = []
for angle in angles:
end_lon, end_lat, _ = geod.fwd(lon, lat, angle, radius_m)
circle_points.append((end_lon, end_lat))
circle = Polygon(circle_points)
if out_crs != "EPSG:4326":
project = pyproj.Transformer.from_crs("EPSG:4326", out_crs, always_xy=True).transform
circle = shp_transform(project, circle)
return circle
# Initialize API wrapper
api = CoreStackAPI(api_key=CORE_STACK_API_KEY)
# ============================================================================
# SPATIAL DATA PROCESSOR
# ============================================================================
class SpatialDataProcessor:
"""Handles vector and raster data processing"""
@staticmethod
def process_vector_url(url: str, point: Optional[tuple] = None, buffer_km: float = 1.0) -> Dict:
"""
Process vector data from URL
Args:
url: GeoJSON URL
point: (lat, lon) tuple for filtering
buffer_km: Buffer radius in km
Returns:
Dict with statistics and sample features
"""
print(f"\nπ‘ DOWNLOADING VECTOR: {url[:100]}...")
try:
gdf = gpd.read_file(url)
print(f"π¦ LOADED: {len(gdf)} features")
print(f"π COLUMNS: {list(gdf.columns)}")
# Filter by buffer if point provided
if point:
lat, lon = point
buffer_geom = geodesic_buffer(lon, lat, buffer_km * 1000, out_crs=gdf.crs)
gdf = gdf[gdf.intersects(buffer_geom)]
print(f"π FILTERED: {len(gdf)} features within {buffer_km}km")
# Calculate statistics (reproject to UTM for accurate area calculation)
stats = {
'feature_count': len(gdf),
'columns': list(gdf.columns),
'attributes': {},
'sample_features': []
}
# Calculate area in hectares (reproject to UTM zone for India: EPSG:32643)
if len(gdf) > 0:
try:
gdf_projected = gdf.to_crs('EPSG:32643') # UTM Zone 43N for India
stats['total_area_ha'] = gdf_projected.geometry.area.sum() / 10000 # mΒ² to ha
except:
stats['total_area_ha'] = 0
stats['area_calculation_error'] = 'Could not reproject for area calculation'
else:
stats['total_area_ha'] = 0
# Extract numeric attributes
for col in gdf.columns:
if col != 'geometry':
try:
# Check if column is numeric
if np.issubdtype(gdf[col].dtype, np.number):
stats['attributes'][col] = {
'mean': float(gdf[col].mean()),
'sum': float(gdf[col].sum()),
'min': float(gdf[col].min()),
'max': float(gdf[col].max())
}
except:
pass # Skip non-numeric columns
# Add sample features (first 3) for inspection
if len(gdf) > 0:
for idx in range(min(3, len(gdf))):
feature_dict = {}
for col in gdf.columns:
if col != 'geometry':
feature_dict[col] = gdf.iloc[idx][col]
stats['sample_features'].append(feature_dict)
return stats
except Exception as e:
return {'error': str(e)}
@staticmethod
def process_raster_url(url: str, bounds: Optional[tuple] = None,
circle_geom_4326: Optional[Any] = None) -> Dict:
"""
Process raster data from URL using HTTP range requests
Args:
url: GeoTIFF URL (will be automatically prefixed with /vsicurl/ if needed)
bounds: (minx, miny, maxx, maxy) bounding box
circle_geom_4326: Shapely geometry for masking
Returns:
Dict with statistics
"""
print(f"\nπ‘ PROCESSING RASTER: {url[:100]}...")
print(f"π DEBUG: Function called with circle_geom={circle_geom_4326 is not None}, bounds={bounds}")
# Prefix with /vsicurl/ if it's an HTTP URL without it
if url.startswith('http') and not url.startswith('/vsicurl/'):
url = f'/vsicurl/{url}'
print(f"π DEBUG: Added /vsicurl/ prefix")
try:
# Enable GDAL options for better WCS support
import os
os.environ['GDAL_HTTP_UNSAFESSL'] = 'YES'
os.environ['CPL_VSIL_CURL_ALLOWED_EXTENSIONS'] = '.tif,.tiff,.vrt'
print(f"π DEBUG: Set GDAL environment variables")
print(f"π DEBUG: Opening raster with rasterio...")
with rasterio.open(url) as src:
# Get raster info
print(f"π¦ RASTER INFO: {src.width}x{src.height}, CRS: {src.crs}")
# Read data (windowed if bounds provided)
if bounds:
window = src.window(*bounds)
data = src.read(1, window=window)
elif circle_geom_4326:
# Get window from circle bounds
minx, miny, maxx, maxy = circle_geom_4326.bounds
print(f"π¦ Circle bounds: ({minx:.4f}, {miny:.4f}, {maxx:.4f}, {maxy:.4f})")
try:
window = src.window(minx, miny, maxx, maxy)
data = src.read(1, window=window)
print(f"π¦ Window read: {data.shape}, non-zero pixels: {np.count_nonzero(data)}")
except Exception as e:
print(f"β οΈ Window read failed, trying full read with mask: {e}")
# Fallback: read full and mask
from rasterio.mask import mask as rio_mask
out_image, out_transform = rio_mask(src, [circle_geom_4326], crop=True, filled=False)
data = out_image[0]
else:
# Read full raster
data = src.read(1)
# Filter nodata
nodata = src.nodata
print(f"π¦ Nodata value: {nodata}")
print(f"π¦ Data shape: {data.shape}, dtype: {data.dtype}")
print(f"π¦ Data range: min={np.min(data)}, max={np.max(data)}")
print(f"π¦ Unique values: {np.unique(data)[:10]}") # First 10 unique values
# Filter nodata - handle multiple common nodata values
if nodata is not None:
valid_data = data[data != nodata]
else:
# Common nodata values if not specified
valid_data = data[(data != 0) & (data != -9999) & (data != 255) & (~np.isnan(data))]
print(f"π¦ Valid pixels: {len(valid_data)} out of {data.size}")
# Calculate statistics
if len(valid_data) > 0:
stats = {
'mean': float(np.mean(valid_data)),
'median': float(np.median(valid_data)),
'std': float(np.std(valid_data)),
'min': float(np.min(valid_data)),
'max': float(np.max(valid_data)),
'pixel_count': int(len(valid_data))
}
print(f"β
Stats: mean={stats['mean']:.2f}, pixels={stats['pixel_count']}")
else:
stats = {'error': 'No valid data in raster', 'total_pixels': int(data.size), 'nodata_value': nodata}
print(f"β No valid data found!")
return stats
except Exception as e:
return {'error': str(e)}
# ============================================================================
# CODEACT AGENT
# ============================================================================
class CodeActAgent:
"""Clean CodeAct implementation with planning and execution"""
def __init__(self, gemini_api_key: str):
self.llm = ChatGoogleGenerativeAI(
model="gemini-2.0-flash-lite",
temperature=0.1,
google_api_key=gemini_api_key
)
def generate_plan(self, query: str, available_layers: Dict[str, list]) -> Dict[str, Any]:
"""Generate human-readable execution plan"""
print("\n" + "="*70)
print("π§ GENERATING EXECUTION PLAN")
print("="*70)
# Simplify layer info for LLM
vector_layers = [f"{l['layer_name']} (vector)" for l in available_layers.get('vector', [])]
raster_layers = [f"{l['layer_name']} (raster)" for l in available_layers.get('raster', [])]
prompt = f"""You are a geospatial analyst. Create a clear execution plan.
USER QUERY: "{query}"
AVAILABLE DATA:
Vector Layers: {', '.join(vector_layers) if vector_layers else 'None'}
Raster Layers: {', '.join(raster_layers) if raster_layers else 'None'}
TASK: Create a step-by-step plan to answer the query.
RULES:
1. Each step should be clear and specific
2. Identify which data layers to use
3. Specify operations needed (filter, intersect, mask, calculate, etc.)
4. Keep it simple - aim for 3-6 steps
OUTPUT FORMAT (JSON):
{{
"steps": [
"Step 1: Download and load cropping intensity vector layer",
"Step 2: Filter features where intensity > threshold",
"Step 3: Calculate total area of filtered regions"
],
"data_needed": ["Cropping Intensity", "LULC_level_1"]
}}
Generate plan now:"""
try:
response = self.llm.invoke(prompt)
content = response.content.strip()
content = re.sub(r"^```json\s*|```$", "", content, flags=re.MULTILINE).strip()
plan = json.loads(content)
print("\nπ EXECUTION PLAN:")
for i, step in enumerate(plan.get('steps', []), 1):
print(f" {i}. {step}")
print(f"\nπ¦ DATA NEEDED: {', '.join(plan.get('data_needed', []))}")
return plan
except Exception as e:
print(f"β Plan generation error: {e}")
return {"steps": ["Error generating plan"], "data_needed": []}
def generate_code(self, query: str, plan: Dict[str, Any], selected_layers: Dict[str, list]) -> str:
"""Generate Python code based on the plan"""
print("\n" + "="*70)
print("π» GENERATING PYTHON CODE")
print("="*70)
# Build context about available data WITH SCHEMA INFORMATION
layer_context = []
# For vector layers, try to fetch schema information
for layer in selected_layers.get('vector', []):
layer_info = f"VECTOR: '{layer['layer_name']}' at URL: {layer['layer_url']}"
# Try to get column information (quick peek)
try:
import geopandas as gpd
gdf_sample = gpd.read_file(layer['layer_url'], rows=1) # Just read 1 row for schema
columns = [col for col in gdf_sample.columns if col != 'geometry']
layer_info += f"\n Columns: {columns[:20]}" # Show first 20 columns
except:
layer_info += "\n Columns: (could not fetch)"
layer_context.append(layer_info)
for layer in selected_layers.get('raster', []):
layer_context.append(f"RASTER: '{layer['layer_name']}' at URL: {layer['layer_url']}")
prompt = f"""You are a Python code generator for geospatial analysis.
USER QUERY: "{query}"
EXECUTION PLAN:
{chr(10).join(f"{i+1}. {step}" for i, step in enumerate(plan.get('steps', [])))}
AVAILABLE DATA:
{chr(10).join(layer_context)}
AVAILABLE FUNCTIONS:
- SpatialDataProcessor.process_vector_url(url, point=None, buffer_km=1.0) β Returns dict with:
- 'feature_count': number of features
- 'total_area_ha': total area in hectares
- 'columns': list of all column names
- 'attributes': dict mapping column names to stats (mean, sum, min, max)
- 'sample_features': list of first 3 feature dicts (without geometry)
- SpatialDataProcessor.process_raster_url(url, bounds=None, circle_geom_4326=None) β dict with stats
- geodesic_buffer(lon, lat, radius_m, out_crs="EPSG:4326") β circle geometry (standalone function!)
**IMPORTANT**: For raster analysis, use radius_m >= 1000 (1km+) to capture sufficient pixels
- find_layer(layer_list, search_term) β dict (helper to find layers with fuzzy matching - RECOMMENDED!)
VARIABLES IN SCOPE:
- query_lat: float (user's latitude if provided)
- query_lon: float (user's longitude if provided)
- vector_layers: list of dicts with 'layer_name' and 'layer_url'
- raster_layers: list of dicts with 'layer_name' and 'layer_url'
- SpatialDataProcessor: class with static methods for processing layers
- geodesic_buffer: standalone function for creating buffers
- find_layer: helper function for robust layer search
CODE GENERATION RULES:
1. Write clean Python code (no markdown, no explanations)
2. Use the provided helper functions to download/process data
3. Store final result in variable called 'result' (dict or string)
4. Handle errors gracefully (try-except where needed)
5. For vector data: use process_vector_url()
6. For raster data: use process_raster_url() with geodesic_buffer(lon, lat, radius_m)
- **CRITICAL**: Use radius_m >= 1000 (at least 1km) for rasters to capture enough pixels
- For point queries: use 1000-5000m radius
- For "around/near" queries: use 5000-10000m radius
7. DO NOT import additional libraries beyond what's available
8. Keep it simple and focused on answering the query
9. **CRITICAL**: When searching for layers, use EXACT MATCHING with the layer names provided above
10. Layer names are case-sensitive and may have spaces (e.g., "Cropping Intensity", not "crop_intensity")
LAYER MATCHING EXAMPLES:
- **RECOMMENDED**: Use find_layer() helper for robust matching:
target_layer = find_layer(vector_layers, 'Cropping Intensity')
target_layer = find_layer(raster_layers, 'NDVI')
- Manual exact match: if layer['layer_name'] == 'Cropping Intensity'
- Manual case-insensitive: if 'cropping intensity' in layer['layer_name'].lower()
EXAMPLE CODE FOR VECTOR DATA:
```python
# Use find_layer helper for robust layer matching
target_layer = find_layer(vector_layers, 'Cropping Intensity')
if target_layer:
stats = SpatialDataProcessor.process_vector_url(
target_layer['layer_url'],
point=(query_lat, query_lon),
buffer_km=5.0
)
result = {{
'total_area': stats['attributes']['doubly_cropped_area_2023']['sum']
}}
else:
result = {{'error': 'Layer not found'}}
```
EXAMPLE CODE FOR RASTER DATA:
```python
# Find LULC or NDVI raster layer
lulc_layer = find_layer(raster_layers, 'LULC_level_1')
if lulc_layer:
# Create buffer geometry (use 1-10km radius for rasters!)
buffer_geom = geodesic_buffer(query_lon, query_lat, 5000, out_crs="EPSG:4326")
# Process raster
stats = SpatialDataProcessor.process_raster_url(
lulc_layer['layer_url'],
circle_geom_4326=buffer_geom
)
result = {{
'mean_value': stats.get('mean'),
'pixel_count': stats.get('pixel_count')
}}
else:
result = {{'error': 'Layer not found'}}
```
NOW GENERATE CODE (Python only, no markdown):"""
try:
response = self.llm.invoke(prompt)
code = response.content.strip()
code = re.sub(r"^```python\s*|^```\s*|```$", "", code, flags=re.MULTILINE).strip()
print("\nπ GENERATED CODE:")
print("β" * 70)
print(code)
print("β" * 70)
return code
except Exception as e:
print(f"β Code generation error: {e}")
return "result = {'error': 'Code generation failed'}"
def execute_code(self, code: str, context: Dict[str, Any]) -> Dict[str, Any]:
"""Execute the generated code in a controlled environment"""
print("\n" + "="*70)
print("π EXECUTING CODE")
print("="*70)
# Helper function to find layers by name (case-insensitive, partial match)
def find_layer(layer_list: List[Dict], search_term: str) -> Optional[Dict]:
"""
Find a layer by name with fuzzy matching.
Returns the best match or None.
"""
search_lower = search_term.lower()
# First try exact match (case-insensitive)
for layer in layer_list:
if layer['layer_name'].lower() == search_lower:
return layer
# Then try partial match
for layer in layer_list:
if search_lower in layer['layer_name'].lower():
return layer
# Last resort: try matching individual words
search_words = search_lower.split()
for layer in layer_list:
layer_name_lower = layer['layer_name'].lower()
if all(word in layer_name_lower for word in search_words):
return layer
return None
# Prepare safe execution environment
safe_globals = {
'__builtins__': __builtins__,
'SpatialDataProcessor': SpatialDataProcessor,
'geodesic_buffer': geodesic_buffer,
'find_layer': find_layer, # Add helper function
'gpd': gpd,
'np': np,
'json': json
}
# Add context variables
safe_globals.update(context)
try:
exec(code, safe_globals)
result = safe_globals.get('result', {'error': 'No result variable found'})
print("β
CODE EXECUTED SUCCESSFULLY")
print(f"π RESULT: {result}")
return {'result': result, 'error': None}
except Exception as e:
error_msg = f"{type(e).__name__}: {str(e)}"
print(f"β EXECUTION ERROR: {error_msg}")
print("\nπ TRACEBACK:")
print(traceback.format_exc())
return {'result': None, 'error': error_msg}
# ============================================================================
# LANGGRAPH NODES
# ============================================================================
def llm_intent_parser(state: Dict[str, Any]) -> Dict[str, Any]:
"""
Simplified intent parser: Extract ONLY location and temporal info.
Layer selection is handled by Architecture 4's CodeAct.
"""
print("\n" + "="*70)
print("π§ PARSING INTENT (Location & Temporal)")
print("="*70)
user_query = state["user_query"]
llm = ChatGoogleGenerativeAI(
model="gemini-2.0-flash",
temperature=0,
google_api_key=GEMINI_API_KEY
)
prompt = f"""Extract location and temporal information from this geospatial query.
USER QUERY: "{user_query}"
TASK: Extract structured location and time information ONLY.
Return JSON:
{{
"latitude": <float or null>,
"longitude": <float or null>,
"location_name": <string or null>,
"location_type": "village" | "tehsil" | "state" | "coordinates",
"district": <string or null>,
"temporal": <bool - true if query asks about trends/changes over time>,
"start_year": <int or null>,
"end_year": <int or null>
}}
EXAMPLES:
Query: "Cropping intensity in Shirur village over years"
{{
"latitude": null,
"longitude": null,
"location_name": "Shirur",
"location_type": "village",
"district": null,
"temporal": true,
"start_year": null,
"end_year": null
}}
Query: "Tree cover loss in Bangalore since 2018"
{{
"latitude": null,
"longitude": null,
"location_name": "Bangalore",
"location_type": "tehsil",
"district": null,
"temporal": true,
"start_year": 2018,
"end_year": null
}}
Query: "Surface water at coordinates 15.123, 76.456"
{{
"latitude": 15.123,
"longitude": 76.456,
"location_name": null,
"location_type": "coordinates",
"district": null,
"temporal": false,
"start_year": null,
"end_year": null
}}
NOW PARSE THE QUERY:"""
try:
response = llm.invoke(prompt)
content = response.content.strip()
content = re.sub(r"^```json\s*|```$", "", content, flags=re.MULTILINE).strip()
parsed = json.loads(content)
# Geocode if needed
if parsed.get('location_name') and not parsed.get('latitude'):
coords = geocode_location(parsed['location_name'])
if coords:
parsed['latitude'], parsed['longitude'] = coords
print(f"π Geocoded '{parsed['location_name']}' β ({coords[0]:.5f}, {coords[1]:.5f})")
state["parsed"] = parsed
print(f"\nβ
PARSED INTENT:")
location_display = parsed.get('location_name') or f"({parsed.get('latitude')}, {parsed.get('longitude')})"
print(f" Location: {location_display} ({parsed.get('location_type')})")
print(f" Temporal: {parsed.get('temporal')}")
if parsed.get('start_year') or parsed.get('end_year'):
print(f" Time Range: {parsed.get('start_year')} - {parsed.get('end_year')}")
except Exception as e:
state["error"] = f"Intent parsing failed: {str(e)}"
print(f"β ERROR: {state['error']}")
return state
def fetch_spatial_layers_multiregion(state: Dict[str, Any]) -> Dict[str, Any]:
"""
Fetch ALL spatial layers from intersecting regions.
Returns complete layer list for Architecture 4 CodeAct to choose from.
"""
if "error" in state:
return state
print("\n" + "="*70)
print("π₯ FETCHING ALL SPATIAL LAYERS (MULTI-REGION)")
print("="*70)
parsed = state["parsed"]
resolved = state.get("resolved_geometry", {})
tehsil_list = resolved.get("tehsil_list", [])
if not tehsil_list:
state["error"] = "No tehsils resolved"
return state
print(f"\nπ Fetching from {len(tehsil_list)} regions...")
all_layers = {'vector': {}, 'raster': {}} # Use dict to deduplicate by layer_name
location_info = {}
for tehsil_info in tehsil_list:
state_name = tehsil_info['state']
district_name = tehsil_info['district']
tehsil_name = tehsil_info['tehsil']
print(f"\n π Fetching: {tehsil_name} ({district_name}, {state_name})")
try:
# Get representative point from tehsil geometry
centroid = tehsil_info['geometry'].centroid
lat, lon = centroid.y, centroid.x
# Call CoreStack API for this specific tehsil
admin_info = api.get_admin_details_by_latlon(
latitude=lat,
longitude=lon
)
layers = api.get_generated_layer_urls(
state=state_name,
district=district_name,
tehsil=tehsil_name
)
location_info = admin_info # Store last location info
# Collect ALL layers (group by layer_name)
for layer in layers:
layer_name = layer['layer_name']
layer_type = layer.get('layer_type', 'vector')
# Initialize layer entry if first time seeing this layer
if layer_type == 'vector':
if layer_name not in all_layers['vector']:
all_layers['vector'][layer_name] = {
'layer_name': layer_name,
'layer_type': 'vector',
'urls': []
}
all_layers['vector'][layer_name]['urls'].append({
'tehsil': tehsil_name,
'district': district_name,
'state': state_name,
'url': layer['layer_url']
})
elif layer_type == 'raster':
if layer_name not in all_layers['raster']:
all_layers['raster'][layer_name] = {
'layer_name': layer_name,
'layer_type': 'raster',
'urls': []
}
all_layers['raster'][layer_name]['urls'].append({
'tehsil': tehsil_name,
'district': district_name,
'state': state_name,
'url': layer['layer_url']
})
print(f" β
Collected {len(layers)} layers")
except Exception as e:
print(f" β οΈ Error fetching from {tehsil_name}: {str(e)}")
continue
# Convert dict to list format
vector_layers = list(all_layers['vector'].values())
raster_layers = list(all_layers['raster'].values())
print(f"\nβ
FETCHING COMPLETE:")
print(f" Unique vector layers: {len(vector_layers)}")
print(f" Unique raster layers: {len(raster_layers)}")
print(f"\nπ Available layers:")
for layer in vector_layers[:10]: # Show first 10
print(f" β’ {layer['layer_name']} (vector, {len(layer['urls'])} regions)")
for layer in raster_layers[:10]:
print(f" β’ {layer['layer_name']} (raster, {len(layer['urls'])} regions)")
if len(vector_layers) == 0 and len(raster_layers) == 0:
state["error"] = "No layers found in any region"
print(f"β ERROR: {state['error']}")
return state
state["available_layers"] = {'vector': vector_layers, 'raster': raster_layers}
state["location_info"] = location_info
return state
def fetch_timeseries_data(state: Dict[str, Any]) -> Dict[str, Any]:
"""
Fetch timeseries data for the location.
Uses COUPLED API workflow: get_mwsid_by_latlon β get_mws_data
"""
if "error" in state:
return state
print("\n" + "="*70)
print("οΏ½ FETCHING TIMESERIES DATA")
print("="*70)