-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapp.py
More file actions
1529 lines (1356 loc) Β· 75.1 KB
/
app.py
File metadata and controls
1529 lines (1356 loc) Β· 75.1 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
import warnings
import os
# Comprehensive warning suppression
warnings.filterwarnings("ignore")
os.environ['PYTHONWARNINGS'] = 'ignore'
# Now import everything else
import streamlit as st
import ee
import geemap.foliumap as geemap
import pandas as pd
import numpy as np
import plotly.express as px
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import json
import google.generativeai as genai
from google.oauth2 import service_account
from datetime import datetime, timedelta
import folium
from streamlit_folium import st_folium
import tempfile
import zipfile
import geopandas as gpd
from scipy import stats
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
from sklearn.cluster import KMeans
import seaborn as sns
import matplotlib.pyplot as plt
from dotenv import load_dotenv
# Load environment variables
load_dotenv()
# Configure Google AI
genai.configure(api_key=os.getenv('GOOGLE_API_KEY'))
# Page configuration
st.set_page_config(
page_title="π°οΈ Advanced Sentinel-2 Intelligence Dashboard",
page_icon="π°οΈ",
layout="wide",
initial_sidebar_state="expanded"
)
# Enhanced Custom CSS with more visual appeal
st.markdown("""
<style>
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap');
.main {
font-family: 'Inter', sans-serif;
}
.main-header {
text-align: center;
padding: 3rem;
background: linear-gradient(135deg, #667eea 0%, #764ba2 50%, #f093fb 100%);
color: white;
border-radius: 20px;
margin-bottom: 2rem;
box-shadow: 0 20px 60px rgba(31, 38, 135, 0.37);
backdrop-filter: blur(10px);
}
.category-header {
background: linear-gradient(90deg, #4facfe 0%, #00f2fe 100%);
color: white;
padding: 1.5rem;
border-radius: 15px;
margin: 1.5rem 0;
text-align: center;
font-weight: 600;
box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
font-size: 1.2rem;
}
.metric-card {
background: linear-gradient(135deg, #ffffff 0%, #f8f9ff 100%);
padding: 2rem;
border-radius: 15px;
box-shadow: 0 10px 30px rgba(0,0,0,0.1);
border-left: 6px solid #4facfe;
margin: 1rem 0;
transition: all 0.3s ease;
border: 1px solid rgba(255,255,255,0.2);
}
.metric-card:hover {
transform: translateY(-8px);
box-shadow: 0 20px 40px rgba(0,0,0,0.2);
}
.smart-card {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
padding: 2rem;
border-radius: 15px;
margin: 1rem 0;
box-shadow: 0 15px 35px rgba(0,0,0,0.15);
}
.recommendation-box {
background: linear-gradient(135deg, #e8f5e8 0%, #d4f1d4 100%);
padding: 2.5rem;
border-radius: 15px;
border-left: 6px solid #2e8b57;
margin: 1.5rem 0;
box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
}
.index-description {
background: rgba(255,255,255,0.9);
padding: 1.5rem;
border-radius: 12px;
border-left: 4px solid #007bff;
margin: 1rem 0;
font-size: 0.95rem;
box-shadow: 0 4px 15px rgba(0,0,0,0.05);
}
.trend-indicator {
font-size: 1.4rem;
font-weight: 700;
}
.trend-up { color: #28a745; }
.trend-down { color: #dc3545; }
.trend-stable { color: #ffc107; }
.stats-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
gap: 1rem;
margin: 1rem 0;
}
.stat-item {
background: white;
padding: 1.5rem;
border-radius: 10px;
box-shadow: 0 4px 15px rgba(0,0,0,0.1);
text-align: center;
border-top: 3px solid #4facfe;
}
.correlation-heatmap {
border-radius: 15px;
overflow: hidden;
box-shadow: 0 10px 25px rgba(0,0,0,0.1);
}
</style>
""", unsafe_allow_html=True)
# Google Earth Engine Authentication
@st.cache_resource
def ee_authenticate():
try:
json_creds = None
if "json_key" in st.secrets:
st.info("Authenticating with Google Earth Engine using service account...")
json_creds = st.secrets["json_key"]
if json_creds is not None:
if isinstance(json_creds, (dict, st.runtime.secrets.AttrDict)):
service_account_info = dict(json_creds)
elif isinstance(json_creds, str):
service_account_info = json.loads(json_creds)
else:
raise ValueError("Invalid json_key format in secrets. Expected dict, AttrDict, or JSON string.")
if "client_email" not in service_account_info:
raise ValueError("Service account email address missing in json_key")
creds = service_account.Credentials.from_service_account_info(
service_account_info, scopes=['https://www.googleapis.com/auth/earthengine']
)
ee.Initialize(creds)
st.success("Successfully authenticated with Google Earth Engine using service account.")
else:
st.info("Attempting authentication using Earth Engine CLI credentials...")
ee.Initialize()
st.success("Authenticated with Google Earth Engine using local CLI credentials.")
except Exception as e:
st.error(f"Failed to authenticate with Google Earth Engine: {str(e)}")
st.markdown(
"**Steps to resolve:**\n"
"- **Local setup**: Create `.streamlit/secrets.toml` with a valid service account key, or run `earthengine authenticate`.\n"
"- **Cloud deployment**: Configure `[json_key]` in Streamlit secrets.\n"
"- Ensure the service account has Earth Engine permissions (`roles/earthengine.user`).\n"
"- Register at https://developers.google.com/earth-engine/guides/access."
)
st.stop()
# Initialize Earth Engine
ee_authenticate()
# Enhanced Comprehensive Sentinel-2 Indices Dictionary with Mining & Industrial Indices
INDICES_CATEGORIES = {
'πΏ Vegetation Health': {
'NDVI': {
'formula': '(NIR - Red) / (NIR + Red)',
'description': 'Primary vegetation health indicator - most widely used',
'range': [-1, 1],
'interpretation': 'Higher values (0.3-0.8) indicate healthier vegetation',
'threshold': {'poor': 0.2, 'moderate': 0.4, 'good': 0.6, 'excellent': 0.8},
'color': '#228B22'
},
'EVI': {
'formula': '2.5 * ((NIR - Red) / (NIR + 6*Red - 7.5*Blue + 1))',
'description': 'Enhanced vegetation index - reduces atmospheric interference',
'range': [-1, 1],
'interpretation': 'Better for dense vegetation areas',
'threshold': {'poor': 0.15, 'moderate': 0.3, 'good': 0.45, 'excellent': 0.6},
'color': '#32CD32'
},
'SAVI': {
'formula': '((NIR - Red) / (NIR + Red + 0.5)) * 1.5',
'description': 'Soil-adjusted vegetation index - minimizes soil background',
'range': [-1.5, 1.5],
'interpretation': 'Ideal for sparse vegetation monitoring',
'threshold': {'poor': 0.1, 'moderate': 0.25, 'good': 0.4, 'excellent': 0.6},
'color': '#90EE90'
},
'GNDVI': {
'formula': '(NIR - Green) / (NIR + Green)',
'description': 'Green-based vegetation index - sensitive to chlorophyll',
'range': [-1, 1],
'interpretation': 'Excellent for crop monitoring and stress detection',
'threshold': {'poor': 0.2, 'moderate': 0.35, 'good': 0.5, 'excellent': 0.65},
'color': '#00FF00'
},
'NDRE': {
'formula': '(NIR - RedEdge) / (NIR + RedEdge)',
'description': 'Red-edge vegetation index - early stress detection',
'range': [-1, 1],
'interpretation': 'Highly sensitive to chlorophyll variations',
'threshold': {'poor': 0.1, 'moderate': 0.2, 'good': 0.3, 'excellent': 0.4},
'color': '#ADFF2F'
},
'ARVI': {
'formula': '(NIR - (2*Red - Blue)) / (NIR + (2*Red - Blue))',
'description': 'Atmospherically Resistant Vegetation Index - atmospheric correction',
'range': [-1, 1],
'interpretation': 'Reduces atmospheric effects on vegetation monitoring',
'threshold': {'poor': 0.15, 'moderate': 0.3, 'good': 0.5, 'excellent': 0.7},
'color': '#9ACD32'
}
},
'π§ Water Resources': {
'NDWI': {
'formula': '(Green - NIR) / (Green + NIR)',
'description': 'Primary water detection index for open water bodies',
'range': [-1, 1],
'interpretation': 'Values > 0.3 typically indicate water presence',
'threshold': {'dry': -0.3, 'moist': 0.0, 'wet': 0.3, 'water': 0.5},
'color': '#0000FF'
},
'MNDWI': {
'formula': '(Green - SWIR1) / (Green + SWIR1)',
'description': 'Modified water index - better for built-up areas',
'range': [-1, 1],
'interpretation': 'Enhanced water detection in urban environments',
'threshold': {'dry': -0.2, 'moist': 0.1, 'wet': 0.4, 'water': 0.6},
'color': '#1E90FF'
},
'AWEIsh': {
'formula': 'Blue + 2.5*Green - 1.5*(NIR + SWIR1) - 0.25*SWIR2',
'description': 'Automated Water Extraction Index (shadow) - handles shadows',
'range': [-2, 2],
'interpretation': 'Positive values indicate water with shadow tolerance',
'threshold': {'no_water': -0.5, 'possible': 0.0, 'water': 0.5, 'certain': 1.0},
'color': '#4169E1'
},
'AWEInsh': {
'formula': '4*(Green - SWIR1) - (0.25*NIR + 2.75*SWIR2)',
'description': 'Automated Water Extraction Index (no shadow) - pure water',
'range': [-2, 2],
'interpretation': 'Optimized for clear water detection',
'threshold': {'no_water': -0.3, 'possible': 0.0, 'water': 0.3, 'certain': 0.8},
'color': '#00BFFF'
}
},
'ποΈ Urban Development': {
'NDBI': {
'formula': '(SWIR1 - NIR) / (SWIR1 + NIR)',
'description': 'Built-up area identification index',
'range': [-1, 1],
'interpretation': 'Higher values indicate more built-up areas',
'threshold': {'natural': -0.1, 'mixed': 0.0, 'urban': 0.1, 'dense_urban': 0.2},
'color': '#FF4500'
},
'UI': {
'formula': '(SWIR2 - NIR) / (SWIR2 + NIR)',
'description': 'Urban Index - alternative built-up area detection',
'range': [-1, 1],
'interpretation': 'Complementary to NDBI for urban mapping',
'threshold': {'natural': -0.05, 'mixed': 0.05, 'urban': 0.15, 'dense': 0.25},
'color': '#FF6347'
},
'BUI': {
'formula': '(NDVI - NDWI) / (NDVI + NDWI)',
'description': 'Built-up Index - uses vegetation and water contrast',
'range': [-1, 1],
'interpretation': 'Effective for urban expansion monitoring',
'threshold': {'natural': -0.2, 'mixed': 0.0, 'urban': 0.2, 'dense': 0.4},
'color': '#CD5C5C'
}
},
'π₯ Fire & Burn Analysis': {
'NBR': {
'formula': '(NIR - SWIR2) / (NIR + SWIR2)',
'description': 'Normalized burn ratio for fire damage assessment',
'range': [-1, 1],
'interpretation': 'Lower values indicate burn damage',
'threshold': {'severe_burn': -0.25, 'moderate_burn': 0.0, 'low_burn': 0.1, 'unburned': 0.3},
'color': '#DC143C'
},
'NBRT': {
'formula': '(NIR - SWIR2*T) / (NIR + SWIR2*T)',
'description': 'NBR with thermal component - enhanced burn detection',
'range': [-1, 1],
'interpretation': 'Improved burn severity assessment',
'threshold': {'severe': -0.3, 'moderate': -0.1, 'low': 0.1, 'unburned': 0.3},
'color': '#B22222'
},
'BAI': {
'formula': '1 / ((0.1 - Red)^2 + (0.06 - NIR)^2)',
'description': 'Burn Area Index - highlights burned areas',
'range': [0, 500],
'interpretation': 'Higher values indicate burned areas',
'threshold': {'unburned': 50, 'low_burn': 100, 'moderate': 200, 'severe': 300},
'color': '#8B0000'
}
},
'βοΈ Mining & Geology': {
'FerricOxide': {
'formula': 'SWIR1 / NIR',
'description': 'Ferric Oxide detection - iron-rich minerals and mining areas',
'range': [0, 5],
'interpretation': 'Higher values indicate iron oxide presence (mining activity)',
'threshold': {'low': 1.0, 'moderate': 1.5, 'high': 2.0, 'very_high': 3.0},
'color': '#8B4513'
},
'ClayMinerals': {
'formula': 'SWIR1 / SWIR2',
'description': 'Clay mineral detection - alteration zones and tailings',
'range': [0, 3],
'interpretation': 'Detects clay alteration common in mining areas',
'threshold': {'background': 0.8, 'weak': 1.0, 'moderate': 1.2, 'strong': 1.5},
'color': '#D2691E'
},
'NDII': {
'formula': '(NIR - SWIR1) / (NIR + SWIR1)',
'description': 'Normalized Difference Infrared Index - moisture and mining impact',
'range': [-1, 1],
'interpretation': 'Detects moisture stress and bare soil from mining',
'threshold': {'dry': -0.2, 'moderate': 0.0, 'moist': 0.2, 'wet': 0.4},
'color': '#A0522D'
},
'SINDRI': {
'formula': '(SWIR2 - Blue) / (SWIR2 + Blue)',
'description': 'SWIR-NIR Difference Ratio Index - exposed soil and rocks',
'range': [-1, 1],
'interpretation': 'Highlights exposed surfaces typical of mining operations',
'threshold': {'vegetated': -0.1, 'mixed': 0.1, 'exposed': 0.3, 'mining': 0.5},
'color': '#CD853F'
},
'AlOH': {
'formula': '(SWIR2 / SWIR1) * (SWIR1 / NIR)',
'description': 'Aluminum Hydroxide - alteration mineral detection',
'range': [0, 5],
'interpretation': 'Detects hydrothermal alteration zones around mines',
'threshold': {'background': 0.8, 'weak': 1.2, 'moderate': 1.8, 'strong': 2.5},
'color': '#DEB887'
}
},
'π Industrial & Pollution': {
'NDSI': {
'formula': '(Green - SWIR1) / (Green + SWIR1)',
'description': 'Normalized Difference Salinity Index - soil salination',
'range': [-1, 1],
'interpretation': 'Detects salt accumulation from industrial activities',
'threshold': {'normal': -0.1, 'slight': 0.1, 'moderate': 0.3, 'severe': 0.5},
'color': '#F5DEB3'
},
'NDTI': {
'formula': '(Red - Green) / (Red + Green)',
'description': 'Normalized Difference Turbidity Index - water pollution',
'range': [-1, 1],
'interpretation': 'Monitors water turbidity from industrial discharge',
'threshold': {'clear': -0.1, 'slight': 0.1, 'turbid': 0.3, 'polluted': 0.5},
'color': '#778899'
},
'APRI': {
'formula': '(Blue - 2*Green + Red) / (Blue + 2*Green + Red)',
'description': 'Atmospheric Pollution Ratio Index - air quality assessment',
'range': [-1, 1],
'interpretation': 'Detects atmospheric pollution from industrial sources',
'threshold': {'clean': -0.1, 'moderate': 0.0, 'polluted': 0.2, 'severe': 0.4},
'color': '#696969'
}
},
'πΎ Agriculture Enhanced': {
'MSAVI': {
'formula': '(2*NIR + 1 - sqrt((2*NIR + 1)^2 - 8*(NIR - Red))) / 2',
'description': 'Modified Soil Adjusted Vegetation Index - precision agriculture',
'range': [-1, 1],
'interpretation': 'Advanced vegetation monitoring with soil correction',
'threshold': {'poor': 0.1, 'fair': 0.3, 'good': 0.5, 'excellent': 0.7},
'color': '#32CD32'
},
'VARI': {
'formula': '(Green - Red) / (Green + Red - Blue)',
'description': 'Visible Atmospherically Resistant Index - crop stress',
'range': [-1, 1],
'interpretation': 'Resistant to atmospheric effects for crop monitoring',
'threshold': {'stressed': 0.0, 'moderate': 0.2, 'healthy': 0.4, 'vigorous': 0.6},
'color': '#228B22'
},
'CIG': {
'formula': '(NIR / Green) - 1',
'description': 'Chlorophyll Index Green - chlorophyll content estimation',
'range': [0, 10],
'interpretation': 'Direct chlorophyll content assessment',
'threshold': {'low': 1.0, 'moderate': 2.0, 'good': 4.0, 'high': 6.0},
'color': '#00FF00'
}
},
'π Soil & Geology': {
'BSI': {
'formula': '((SWIR1 + Red) - (NIR + Blue)) / ((SWIR1 + Red) + (NIR + Blue))',
'description': 'Bare Soil Index - exposed soil detection',
'range': [-1, 1],
'interpretation': 'Identifies bare soil and erosion patterns',
'threshold': {'vegetated': -0.2, 'mixed': 0.0, 'bare': 0.3, 'eroded': 0.6},
'color': '#D2691E'
},
'GI': {
'formula': 'Green / Red',
'description': 'Greenness Index - vegetation greenness assessment',
'range': [0, 5],
'interpretation': 'Simple but effective vegetation greenness measure',
'threshold': {'brown': 0.8, 'yellow': 1.0, 'light_green': 1.2, 'green': 1.5},
'color': '#90EE90'
},
'RNDVI': {
'formula': '(NIR - Red) / sqrt(NIR + Red)',
'description': 'Renormalized Difference Vegetation Index - improved sensitivity',
'range': [-1, 1],
'interpretation': 'Enhanced vegetation detection in low biomass areas',
'threshold': {'sparse': 0.1, 'moderate': 0.3, 'dense': 0.5, 'very_dense': 0.7},
'color': '#228B22'
}
}
}
def calculate_comprehensive_indices(image):
"""Enhanced indices calculation with mining and industrial indices"""
try:
# Basic bands with null handling
B2 = image.select('B2').unmask(0) # Blue
B3 = image.select('B3').unmask(0) # Green
B4 = image.select('B4').unmask(0) # Red
B5 = image.select('B5').unmask(0) # Red Edge 1
B8 = image.select('B8').unmask(0) # NIR
B11 = image.select('B11').unmask(0) # SWIR1
B12 = image.select('B12').unmask(0) # SWIR2
# Vegetation Indices
ndvi = B8.subtract(B4).divide(B8.add(B4)).rename('NDVI')
evi = image.expression(
'2.5 * ((NIR - RED) / (NIR + 6 * RED - 7.5 * BLUE + 1))',
{'NIR': B8, 'RED': B4, 'BLUE': B2}
).rename('EVI')
savi = image.expression(
'((NIR - RED) / (NIR + RED + 0.5)) * 1.5',
{'NIR': B8, 'RED': B4}
).rename('SAVI')
gndvi = B8.subtract(B3).divide(B8.add(B3)).rename('GNDVI')
ndre = B8.subtract(B5).divide(B8.add(B5)).rename('NDRE')
arvi = image.expression(
'(NIR - (2*RED - BLUE)) / (NIR + (2*RED - BLUE))',
{'NIR': B8, 'RED': B4, 'BLUE': B2}
).rename('ARVI')
# Water Indices
ndwi = B3.subtract(B8).divide(B3.add(B8)).rename('NDWI')
mndwi = B3.subtract(B11).divide(B3.add(B11)).rename('MNDWI')
aweish = image.expression(
'BLUE + 2.5*GREEN - 1.5*(NIR + SWIR1) - 0.25*SWIR2',
{'BLUE': B2, 'GREEN': B3, 'NIR': B8, 'SWIR1': B11, 'SWIR2': B12}
).rename('AWEIsh')
aweinsh = image.expression(
'4*(GREEN - SWIR1) - (0.25*NIR + 2.75*SWIR2)',
{'GREEN': B3, 'NIR': B8, 'SWIR1': B11, 'SWIR2': B12}
).rename('AWEInsh')
# Urban/Built-up Indices
ndbi = B11.subtract(B8).divide(B11.add(B8)).rename('NDBI')
ui = B12.subtract(B8).divide(B12.add(B8)).rename('UI')
bui = ndvi.subtract(ndwi).divide(ndvi.add(ndwi)).rename('BUI')
# Fire/Burn Indices
nbr = B8.subtract(B12).divide(B8.add(B12)).rename('NBR')
nbrt = B8.subtract(B12).divide(B8.add(B12)).rename('NBRT') # Simplified version
bai = image.expression(
'1 / ((0.1 - RED)*(0.1 - RED) + (0.06 - NIR)*(0.06 - NIR))',
{'RED': B4, 'NIR': B8}
).rename('BAI')
# Mining & Geology Indices
ferric_oxide = B11.divide(B8).rename('FerricOxide')
clay_minerals = B11.divide(B12).rename('ClayMinerals')
ndii = B8.subtract(B11).divide(B8.add(B11)).rename('NDII')
sindri = B12.subtract(B2).divide(B12.add(B2)).rename('SINDRI')
aloh = B12.divide(B11).multiply(B11.divide(B8)).rename('AlOH')
# Industrial & Pollution Indices
ndsi = B3.subtract(B11).divide(B3.add(B11)).rename('NDSI')
ndti = B4.subtract(B3).divide(B4.add(B3)).rename('NDTI')
apri = image.expression(
'(BLUE - 2*GREEN + RED) / (BLUE + 2*GREEN + RED)',
{'BLUE': B2, 'GREEN': B3, 'RED': B4}
).rename('APRI')
# Agriculture Enhanced Indices
msavi = image.expression(
'(2*NIR + 1 - sqrt((2*NIR + 1)*(2*NIR + 1) - 8*(NIR - RED))) / 2',
{'NIR': B8, 'RED': B4}
).rename('MSAVI')
vari = image.expression(
'(GREEN - RED) / (GREEN + RED - BLUE)',
{'GREEN': B3, 'RED': B4, 'BLUE': B2}
).rename('VARI')
cig = B8.divide(B3).subtract(1).rename('CIG')
# Soil & Geology Indices
bsi = image.expression(
'((SWIR1 + RED) - (NIR + BLUE)) / ((SWIR1 + RED) + (NIR + BLUE))',
{'SWIR1': B11, 'RED': B4, 'NIR': B8, 'BLUE': B2}
).rename('BSI')
gi = B3.divide(B4).rename('GI')
rndvi = B8.subtract(B4).divide(B8.add(B4).sqrt()).rename('RNDVI')
# Combine all indices
all_indices = [
# Vegetation
ndvi, evi, savi, gndvi, ndre, arvi,
# Water
ndwi, mndwi, aweish, aweinsh,
# Urban
ndbi, ui, bui,
# Fire
nbr, nbrt, bai,
# Mining
ferric_oxide, clay_minerals, ndii, sindri, aloh,
# Industrial
ndsi, ndti, apri,
# Agriculture
msavi, vari, cig,
# Soil
bsi, gi, rndvi
]
indices_image = image
for index in all_indices:
indices_image = indices_image.addBands(index)
return indices_image
except Exception as e:
st.error(f"Error calculating indices: {str(e)}")
return image
def get_comprehensive_time_series(geometry, start_date, end_date, cloud_cover=20):
"""Enhanced time series with better filtering"""
try:
collection = ee.ImageCollection('COPERNICUS/S2_SR_HARMONIZED') \
.filterBounds(geometry) \
.filterDate(start_date, end_date) \
.filter(ee.Filter.lt('CLOUDY_PIXEL_PERCENTAGE', cloud_cover)) \
.sort('system:time_start')
# Check if collection is empty
size = collection.size()
if size.getInfo() == 0:
st.warning("No images found for the specified criteria. Try expanding the date range or increasing cloud cover threshold.")
return None
indices_collection = collection.map(calculate_comprehensive_indices)
def get_image_stats(image):
stats = image.reduceRegion(
reducer=ee.Reducer.mean(),
geometry=geometry,
scale=20,
maxPixels=1e9,
bestEffort=True
)
return ee.Feature(None, stats.set('date', image.date().format('YYYY-MM-dd')))
time_series = indices_collection.map(get_image_stats)
return ee.FeatureCollection(time_series)
except Exception as e:
st.error(f"Error in time series calculation: {str(e)}")
return None
def get_smart_trend_analysis(data):
"""Advanced trend analysis with statistical insights"""
if len(data) < 3:
return {"trend": "Insufficient data", "confidence": 0, "slope": 0}
x = np.arange(len(data))
slope, intercept, r_value, p_value, std_err = stats.linregress(x, data.values)
# Determine trend strength
if abs(r_value) > 0.7:
strength = "Strong"
elif abs(r_value) > 0.4:
strength = "Moderate"
else:
strength = "Weak"
if slope > 0.01:
direction = "Increasing"
emoji = "π"
color = "green"
elif slope < -0.01:
direction = "Decreasing"
emoji = "π"
color = "red"
else:
direction = "Stable"
emoji = "β‘οΈ"
color = "orange"
return {
"trend": f"{strength} {direction}",
"emoji": emoji,
"color": color,
"slope": slope,
"r_value": r_value,
"p_value": p_value,
"confidence": abs(r_value) * 100
}
def create_advanced_visualizations(df, categories):
"""Create comprehensive visualizations"""
# 1. Category-wise Time Series with Subplots
st.subheader("π Category-wise Index Analysis")
for category, indices in categories.items():
available_indices = [idx for idx in indices.keys() if idx in df.columns]
if available_indices:
st.markdown(f"""
<div class="category-header">
{category} Analysis
</div>
""", unsafe_allow_html=True)
# Create subplot for each category
fig = make_subplots(
rows=len(available_indices), cols=1,
subplot_titles=[f"{idx} - {indices[idx]['description']}" for idx in available_indices],
vertical_spacing=0.05
)
colors = px.colors.qualitative.Set3
# colors = px.colors.qualitative.Set3
for i, idx in enumerate(available_indices):
data = df[idx].dropna()
if len(data) > 0:
fig.add_trace(
go.Scatter(
x=df['date'],
y=df[idx],
name=idx,
line=dict(color=indices[idx]['color'], width=3),
mode='lines+markers',
hovertemplate=f'<b>{idx}</b><br>Date: %{{x}}<br>Value: %{{y:.3f}}<extra></extra>'
),
row=i+1, col=1
)
# Add threshold lines
thresholds = indices[idx].get('threshold', {})
for threshold_name, threshold_value in thresholds.items():
fig.add_hline(
y=threshold_value,
line_dash="dash",
line_color="gray",
opacity=0.5,
annotation_text=threshold_name,
row=i+1, col=1
)
fig.update_layout(
height=300 * len(available_indices),
title_text=f"{category} Time Series Analysis",
showlegend=False
)
st.plotly_chart(fig, use_container_width=True)
# 2. Correlation Heatmap
st.subheader("π Inter-Index Correlation Analysis")
numeric_columns = df.select_dtypes(include=[np.number]).columns
if len(numeric_columns) > 1:
correlation_matrix = df[numeric_columns].corr()
fig = go.Figure(data=go.Heatmap(
z=correlation_matrix.values,
x=correlation_matrix.columns,
y=correlation_matrix.columns,
colorscale='RdBu',
zmid=0,
text=correlation_matrix.round(2).values,
texttemplate="%{text}",
textfont={"size": 10},
hovertemplate='<b>%{x} vs %{y}</b><br>Correlation: %{z:.3f}<extra></extra>'
))
fig.update_layout(
title="Index Correlation Matrix",
height=600,
font=dict(size=12)
)
st.plotly_chart(fig, use_container_width=True)
# 3. Smart Statistical Summary
st.subheader("π Smart Statistical Insights")
stats_data = []
for category, indices in categories.items():
for idx in indices.keys():
if idx in df.columns:
data = df[idx].dropna()
if len(data) > 0:
trend_analysis = get_smart_trend_analysis(data)
stats_data.append({
'Category': category,
'Index': idx,
'Current': data.iloc[-1],
'Mean': data.mean(),
'Std': data.std(),
'Trend': trend_analysis['trend'],
'Confidence': f"{trend_analysis['confidence']:.1f}",
'Emoji': trend_analysis['emoji']
})
if stats_data:
stats_df = pd.DataFrame(stats_data)
# Display as interactive table
st.dataframe(
stats_df.style.format({
'Current': '{:.3f}',
'Mean': '{:.3f}',
'Std': '{:.3f}'
}),
use_container_width=True
)
def create_smart_dashboard_metrics(df, categories):
"""Create smart dashboard with key metrics"""
st.subheader("π― Smart Dashboard Metrics")
# Calculate overall health score
health_scores = {}
for category, indices in categories.items():
category_scores = []
for idx in indices.keys():
if idx in df.columns:
data = df[idx].dropna()
if len(data) > 0:
current_value = data.iloc[-1]
thresholds = indices[idx].get('threshold', {})
# Calculate normalized score based on thresholds
if thresholds:
max_threshold = max(thresholds.values())
min_threshold = min(thresholds.values())
if max_threshold != min_threshold:
normalized_score = (current_value - min_threshold) / (max_threshold - min_threshold)
category_scores.append(max(0, min(1, normalized_score)) * 100)
if category_scores:
health_scores[category] = np.mean(category_scores)
# Display health scores
if health_scores:
cols = st.columns(len(health_scores))
for i, (category, score) in enumerate(health_scores.items()):
with cols[i]:
# Determine color based on score
if score >= 70:
color = "green"
status = "Excellent"
elif score >= 50:
color = "orange"
status = "Good"
else:
color = "red"
status = "Needs Attention"
st.metric(
label=f"{category} Health",
value=f"{score:.1f}%",
delta=status
)
@st.cache_data(ttl=3600)
def get_enhanced_ai_recommendations(indices_data, location_name, categories):
"""Enhanced AI recommendations with deeper analysis"""
try:
model = genai.GenerativeModel('gemini-1.5-flash')
# Prepare comprehensive data summary
analysis_summary = f"""
COMPREHENSIVE SATELLITE ANALYSIS REPORT
========================================
Location: {location_name}
Analysis Period: {indices_data['date'].min()} to {indices_data['date'].max()}
Total Observations: {len(indices_data)}
DETAILED INDEX ANALYSIS BY CATEGORY:
"""
for category, indices in categories.items():
analysis_summary += f"\n\n{category.upper()}:\n"
analysis_summary += "=" * 50 + "\n"
for idx in indices.keys():
if idx in indices_data.columns:
data = indices_data[idx].dropna()
if len(data) > 0:
trend_analysis = get_smart_trend_analysis(data)
analysis_summary += f"""
{idx} ({indices[idx]['description']}):
- Current Value: {data.iloc[-1]:.3f}
- Mean Value: {data.mean():.3f}
- Standard Deviation: {data.std():.3f}
- Trend: {trend_analysis['trend']} (Confidence: {trend_analysis['confidence']:.1f}%)
- Range: {indices[idx]['range']}
- Interpretation: {indices[idx]['interpretation']}
"""
prompt = f"""
As a senior remote sensing and agricultural expert with 20+ years of experience,
provide a comprehensive analysis based on this Sentinel-2 satellite data:
{analysis_summary}
Please provide a detailed report with the following sections:
1. EXECUTIVE SUMMARY
- Overall assessment of the monitored area
- Key findings and critical insights
2. VEGETATION HEALTH ANALYSIS
- Detailed vegetation condition assessment
- Seasonal trends and patterns
- Areas of concern or improvement
3. WATER RESOURCES ASSESSMENT
- Water availability and distribution
- Moisture stress indicators
- Irrigation recommendations
4. ENVIRONMENTAL MONITORING
- Urban development impacts
- Fire risk assessment
- Ecosystem health indicators
5. ACTIONABLE RECOMMENDATIONS
- Immediate actions required
- Medium-term strategies
- Long-term planning suggestions
6. PREDICTIVE INSIGHTS
- Expected trends based on current data
- Risk factors to monitor
- Opportunity areas
Format your response with clear headings, bullet points, and specific numerical references to the data.
"""
response = model.generate_content(prompt)
return response.text
except Exception as e:
return f"Unable to generate enhanced AI recommendations: {str(e)}"
# Enhanced Main Dashboard Function
def main():
# Enhanced Header with better styling
st.markdown("""
<div class="main-header">
<h1>π°οΈ Advanced Sentinel-2 Intelligence Dashboard</h1>
<p style="font-size: 1.2rem; margin-top: 1rem;">
Next-Generation Satellite Imagery Analysis with AI-Powered Intelligence
</p>
<p style="font-size: 0.9rem; opacity: 0.9; margin-top: 0.5rem;">
Comprehensive Multi-Spectral Index Analysis | Smart Trend Detection | Predictive Insights
</p>
</div>
""", unsafe_allow_html=True)
# Enhanced Sidebar with better organization
st.sidebar.title("π§ Analysis Configuration")
st.sidebar.markdown("---")
# Location selection with simplified options
st.sidebar.markdown("### π Location Selection")
location_option = st.sidebar.selectbox(
"Choose Location Method:",
["π Custom Coordinates", "ποΈ Predefined Locations", "π Upload Shapefile"],
help="Select how you want to define your area of interest"
)
# Enhanced Data Configuration
st.sidebar.markdown("---")
st.sidebar.markdown("### π
Analysis Parameters")
# Date range with better defaults
col1, col2 = st.sidebar.columns(2)
with col1:
start_date = st.date_input(
"Start Date",
value=datetime(2023, 1, 1),
help="Start date for analysis"
)
with col2:
end_date = st.date_input(
"End Date",
value=datetime(2023, 12, 31),
help="End date for analysis"
)
cloud_cover = st.sidebar.slider(
"Max Cloud Cover (%)",
0, 100, 20, 5,
help="Maximum allowed cloud cover percentage"
)
# Index Selection - Available from the beginning
st.sidebar.markdown("---")
st.sidebar.markdown("### π Select Indices for Analysis")
selected_indices = {}
for category, indices in INDICES_CATEGORIES.items():
st.sidebar.markdown(f"**{category}**")
category_indices = {}
for idx in indices.keys():
category_indices[idx] = st.sidebar.checkbox(
f"{idx}",
value=(idx in ['NDVI', 'NDWI', 'NDBI']), # Default selections
help=f"{indices[idx]['description']}"
)
selected_indices.update(category_indices)
# Filter to get only selected indices
indices_to_analyze = [idx for idx, selected in selected_indices.items() if selected]
if not indices_to_analyze:
st.sidebar.warning("β οΈ Please select at least one index for analysis")
geometry = None
location_name = ""
lat, lon = 28.6139, 77.2090 # Default coordinates
if location_option == "π Custom Coordinates":
st.sidebar.markdown("---")
st.sidebar.markdown("**Enter Coordinates:**")
col1, col2 = st.sidebar.columns(2)
with col1:
lat = st.number_input("Latitude", value=28.6139, format="%.6f", help="Enter latitude in decimal degrees")
with col2:
lon = st.number_input("Longitude", value=77.2090, format="%.6f", help="Enter longitude in decimal degrees")
buffer_size = st.sidebar.slider(
"Buffer Size (km)",
0.5, 100.0, 5.0, 0.5,
help="Size of the analysis area around the point"
)
geometry = ee.Geometry.Point([lon, lat]).buffer(buffer_size * 1000)
location_name = f"Custom Location ({lat:.4f}, {lon:.4f})"
# Show selected indices info for custom coordinates
if indices_to_analyze:
st.sidebar.success(f"β
{len(indices_to_analyze)} indices selected for analysis")