-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathapp.py
More file actions
1389 lines (1140 loc) · 57.6 KB
/
app.py
File metadata and controls
1389 lines (1140 loc) · 57.6 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
"""
Original Project Author: IndigoWizard, August 6, 2023.
Project Name: NDVI Viewer
"""
import streamlit as st
import ee
from ee import oauth
from google.oauth2 import service_account
import folium
from streamlit_folium import folium_static, st_folium
from branca.element import Template, MacroElement, Figure, Element
from folium.utilities import escape_backticks
from datetime import datetime, timedelta, date
import json
import pandas as pd
import geopandas as gpd
import calendar
import altair as alt
import tempfile
import zipfile
import os
import xml.etree.ElementTree as ET
import fiona
from shapely.geometry import shape, mapping
st.set_page_config(
page_title="NDVI Viewer",
page_icon="https://cdn-icons-png.flaticon.com/512/2516/2516640.png",
layout="wide",
initial_sidebar_state="expanded",
menu_items={
'Get help': "https://github.com/IndigoWizard/NDVI-Viewer",
'Report a bug': "https://github.com/IndigoWizard/NDVI-Viewer/issues",
'About': "This app was developped by [IndigoWizard](https://github.com/IndigoWizard/NDVI-Viewer) for the purpose of environmental monitoring and geospatial analysis. Give proper credit when using this app or forking the open source projet code/piece of code."
}
)
### CSS STYLING
st.markdown(
"""
<style>
/* Header*/
/* Dark theme version */
.st-emotion-cache-h4xjwg, .st-emotion-cache-12fmjuu {
height: 1rem;
background: none;
}
/*Header banner*/
.st-emotion-cache-ropwps.egexzqm2 h1#wildfire-burn-severity-analysis {
font-size: 1.75rem;
}
/*Main: Smooth scrolling*/
.stMain.st-emotion-cache-bm2z3a.eht7o1d1 {
scroll-behavior: smooth;
}
/* main app body with less padding*/
.st-emotion-cache-t1wise.eht7o1d4 {
padding: 0.2rem 2rem;
}
/* main app body with less padding in different screen size*/
@media (min-width: calc(736px + 8rem)) {
.st-emotion-cache-t1wise {
padding: 0.2rem 2rem;
}
}
/* ******* Sidebar ******* */
/* Main container */
/*Dark theme - Light theme class names*/
.stSidebar.st-emotion-cache-1wqrzgl.e1c29vlm0, .stSidebar.st-emotion-cache-vmpjyt.e1c29vlm0 {
min-width: 280px;
max-width: fit-content;
}
/*Light theme sidbar background color*/
.stSidebar.st-emotion-cache-vmpjyt, .stSidebar.st-emotion-cache-wgfafi.e1c29vlm0 {
background-color: rgb(38, 39, 48);
color: #fafafa;
}
/*sidebar light theme mobile view*/
@media (max-width: 576px) {
.stSidebar.st-emotion-cache-g8bi16.e1c29vlm0 {
background-color: rgb(38, 39, 48);
color: #fafafa;
}
.stVerticalBlock.st-emotion-cache-10e86g4.e6rk8up3, .stVerticalBlock.st-emotion-cache-1vn87qs.e6rk8up3 {
gap: 1.6rem;
}
}
/*Sidebar header*/
.st-emotion-cache-kgpedg {
padding: 0;
}
.st-emotion-cache-1mi2ry5.eczjsme6 {
height: 0;
}
/* Logo */
.st-emotion-cache-1kyxreq.e115fcil2 {
justify-content: center;
}
/* Sidebar : inside container */
.css-ge7e53 {
width: fit-content;
}
/*Sidebar : image*/
.st-emotion-cache-vew1uq.e6rk8up1 {
display: flex;
justify-content: center;
}
/*Sidebar : Navigation list*/
div.element-container:nth-child(4) > div:nth-child(1) > div:nth-child(1) > ul:nth-child(1) {
margin: 0;
padding: 0;
list-style: none;
}
div.element-container:nth-child(4) > div:nth-child(1) > div:nth-child(1) > ul:nth-child(1) > li {
padding: 0;
margin: 0;
padding: 0;
font-weight: 600;
}
div.element-container:nth-child(4) > div:nth-child(1) > div:nth-child(1) > ul:nth-child(1) > li > a {
text-decoration: none;
transition: 0.2s ease-in-out;
padding-inline: 10px;
}
div.element-container:nth-child(4) > div:nth-child(1) > div:nth-child(1) > ul:nth-child(1) > li > a:hover {
color: rgb(46, 206, 255);
transition: 0.2s ease-in-out;
background: #131720;
border-radius: 4px;
}
/* Sidebar: socials*/
div.css-rklnmr:nth-child(6) > div:nth-child(1) > div:nth-child(1) > p {
display: flex;
flex-direction: row;
gap: 1rem;
}
/*Socials flex properties: dark & light theme*/
.st-emotion-cache-1espb9k p, .st-emotion-cache-1mw54nq p {
display: flex;
flex-direction: row;
justify-content: start;
gap: 0.8rem;
padding-inline: 10px;
}
/* Linkedin logo*/
.st-emotion-cache-1espb9k.egexzqm0 p a img, .st-emotion-cache-1mw54nq.egexzqm0 p a img {
width: 32px;
}
/*GitHub logo: Dark Theme - Light Theme*/
.st-emotion-cache-14j6x93:nth-child(6) > div:nth-child(1) > div:nth-child(1) > p:nth-child(1) > a:nth-child(2) > img:nth-child(1) {
background-color: #26273040;
border-radius: 50%;
}
/*GitHub logo: Dark Theme - Light Theme - Mobile version*/
div.st-emotion-cache-vew1uq:nth-child(6) > div:nth-child(1) > div:nth-child(1) > p:nth-child(1) > a:nth-child(2) > img:nth-child(1) {
background-color: #26273040;
border-radius: 50%;
}
/*Main body Title*/
.st-emotion-cache-ropwps.egexzqm2 h1#wildfire-burn-severity-analysis, .st-emotion-cache-18netey.egexzqm2 h1#wildfire-burn-severity-analysis {
font-size: 2rem;
padding: 1.8rem 0 0.5rem;
}
/* ******* Upload Section ******* */
/* ***** Upload info box */
/* Light theme version */
.st-emotion-cache-1gulkj5.e1blfcsg0 {
background-color: rgb(215, 210, 225);
color: rgb(40, 40, 55);
display: flex;
flex-direction: column;
align-items: inherit;
font-size: 14px;
}
/* ***** Upload SVG: Mobile view */
@media (max-width: 576px) {
/* Dark theme version*/
.st-emotion-cache-wn8ljn.e1b2p2ww13 {
display: unset;
}
/* Light theme version*/
.st-emotion-cache-nwtri.e1b2p2ww13 {
display: unset;
}
}
/* ***** Upload button: dark theme*/
.st-emotion-cache-1erivf3.e1blfcsg0 {
display: flex;
flex-direction: column;
align-items: inherit;
font-size: 14px;
}
.st-emotion-cache-19rxjzo.ef3psqc12 {
display: flex;
flex-direction: row;
margin-inline: 0;
}
/* ***** Upload button: light theme*/
.st-emotion-cache-1gulkj5.e1b2p2ww15 {
display: flex;
flex-direction: column;
align-items: inherit;
font-size: 14px;
}
.st-emotion-cache-7ym5gk.ef3psqc12 {
display: flex;
flex-direction: row;
margin-inline: 0;
background: rgba(0, 3, 172, 0.15);
}
/* ******* Form Submit ******* */
/* ***** Generate Map */
/* Dark theme version */
.st-emotion-cache-19rxjzo.ef3psqc7 {
width: 100%;
}
/* Light Theme Version */
.st-emotion-cache-7ym5gk.ef3psqc7 {
width: 100%;
background: rgba(0, 3, 172, 0.25);
}
/* Buttons */
/* Light theme verison; hober effect */
.st-emotion-cache-7ym5gk:hover {
border-color: rgb(255, 0, 110);
color: rgb(255, 0, 110);
}
/* ******* Legend style ******* */
.ndwilegend {
transition: 0.2s ease-in-out;
border-radius: 5px;
box-shadow: 0 0 5px rgba(0, 0, 0, 0.2);
background: rgba(0, 0, 0, 0.05);
}
.ndwilegend:hover {
transition: 0.3s ease-in-out;
box-shadow: 0 0 5px rgba(0, 0, 0, 0.8);
background: rgba(0, 0, 0, 0.12);
cursor: pointer;
}
.reclassifieddNBR {
transition: 0.2s ease-in-out;
border-radius: 5px;
box-shadow: 0 0 5px rgba(0, 0, 0, 0.2);
background: rgba(0, 0, 0, 0.05);
}
.reclassifieddNBR:hover {
transition: 0.3s ease-in-out;
box-shadow: 0 0 5px rgba(0, 0, 0, 0.8);
background: rgba(0, 0, 0, 0.12);
cursor: pointer;
}
.stCustomComponentV1.st-emotion-cache-1tvzk6f.e1begtbc0 {
width: 100%;
height: 500px !important;
min-height: 500px !important;
max-height: 500px !important;
overflow: hidden !important;
}
</style>
""", unsafe_allow_html=True)
# Initializing the Earth Engine library
# Use ee.Initialize() only on local machine! Comment back before deployement (Unusable on deployment)
#ee.Initialize()
# GEE Servuce Account Auth+init for cloud deployment
@st.cache_data(persist=True)
def ee_authenticate():
# Check for json key in Streamlit Secrets
if "json_key" in st.secrets:
json_creds = st.secrets["json_key"]
service_account_info = json.loads(json_creds)
# Catching eventual email related error
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=oauth.SCOPES)
# Initializing gee for each run of the app
ee.Initialize(creds)
else:
# Fallback to normal init method if no json key/st secrets available. (local machine)
ee.Initialize()
# Error dialog box
@st.dialog("Error Report:")
def show_error_dialog(messages):
st.error(messages)
# Earth Engine drawing method setup
def add_ee_layer(self, ee_image_object, vis_params, name):
map_id_dict = ee.Image(ee_image_object).getMapId(vis_params)
layer = folium.raster_layers.TileLayer(
tiles=map_id_dict['tile_fetcher'].url_format,
attr='Map Data © <a href="https://earthengine.google.com/">Google Earth Engine</a>',
name=name,
overlay=True,
control=True
)
layer.add_to(self)
return layer
# Configuring Earth Engine display rendering method in Folium
folium.Map.add_ee_layer = add_ee_layer
# Defining a function to create and filter a GEE image collection for results
def satCollection(cloudRate, initialDate, updatedDate, aoi):
try:
collection = (
ee.ImageCollection('COPERNICUS/S2_SR')
.filter(ee.Filter.lt("CLOUDY_PIXEL_PERCENTAGE", cloudRate))
.filterDate(initialDate, updatedDate)
.filterBounds(aoi)
)
# Check collection size
collection_size = collection.size().getInfo()
if collection_size == 0:
return None, (
"No Sentinel-2 L2A images found for the selected parameters. \n\n"
"Try increasing the cloud threshold or expanding the date range."
)
# Defining a function to clip the colleciton to the area of interst
def clipCollection(image):
return image.clip(aoi).divide(10000)
# clipping the collection
collection = collection.map(clipCollection)
return collection, None
except Exception as e:
return collection, f"Earth Engine encountered an error while building Sentinel-2 Collection: \n {str(e)}"
# File Parser: GeoPackage (.gpkg)
def parse_geopackage(gpkg_path):
# prepare geometry
geometry_list = []
try:
with fiona.open(gpkg_path) as fu:
if len(fu) == 0:
return [], "GeoPackage contains no features."
for feat in fu:
if not feat or not feat.get("geometry"):
continue
try:
geom = shape(feat["geometry"])
except Exception:
continue
# Polygon
if geom.geom_type == "Polygon":
try:
geometry_list.append(ee.Geometry.Polygon(list(geom.exterior.coords)))
except Exception:
continue
# MultiPolygon
elif geom.geom_type == "MultiPolygon":
try:
coords = [list(poly.exterior.coords) for poly in geom.geoms]
geometry_list.append(ee.Geometry.MultiPolygon(coords))
except Exception:
continue
# Ignore other geometry types silently
if not geometry_list:
return [], "No valid Polygon or MultiPolygon geometries found in GeoPackage."
return geometry_list, None
except fiona.errors.DriverError:
return [], "Invalid or corrupted GeoPackage file."
except Exception as e:
return [], f"Error processing GeoPackage file: {str(e)}"
# File Parser: CSV
# column name variations found in CSV datasets
COLUMN_SYNONYMS = {
"x": ["x", "ln", "lon", "lons", "lng", "lngs", "longitude", "longitudes"],
"y": ["y", "lt", "lat", "lats", "latitude", "latitudes"]
}
# finding coordinates colomns
def find_column(df, possible_col_name):
for c in possible_col_name:
if c in df.columns:
return c
return None
# main csv parse function
def parse_csv(upload_file):
try:
try:
df = pd.read_csv(upload_file)
except Exception:
return [], "Invalid CSV file. Could not be read."
if df.empty:
return [], "CSV file is empty."
df.columns = df.columns.str.lower().str.strip()
geometry_list = []
# single-row polygon coordinates
if "coordinates" in df.columns:
for idx, row in df.iterrows():
try:
coords = json.loads(row["coordinates"])
geometry_list.append(ee.Geometry.Polygon(coords))
except Exception:
return [], "Invalid 'coordinates' column. Must contain valid JSON polygon coordinates."
if not geometry_list:
return [], "No valid geometries found in 'coordinates' column."
return geometry_list, None
# multi-row polygon coordinates
required_cols = ["id", "vertex_index"]
for col in required_cols:
if col not in df.columns:
return [], f"Missing required column '{col}'."
x_col = find_column(df, COLUMN_SYNONYMS["x"])
y_col = find_column(df, COLUMN_SYNONYMS["y"])
if not x_col or not y_col:
return [], "Could not detect longitude/latitude columns."
for gid, group in df.groupby("id"):
try:
group = group.sort_values("vertex_index")
coords = group[[x_col, y_col]].values.tolist()
# checks for minimum polygon vertices
if len(coords) < 3:
return [], f"Polygon with id '{gid}' has fewer than 3 vertices."
# always check if the polygon coords close the shape and fix it
if coords[0] != coords[-1]:
coords.append(coords[0])
geometry_list.append(ee.Geometry.Polygon(coords))
except Exception:
return [], f"Invalid polygon geometry for id '{gid}'."
if not geometry_list:
return [], "No valid polygon geometries could be constructed from CSV."
return geometry_list, None
except Exception as e:
return [], f"Error processing CSV file: {str(e)}"
# File Parser: Zipped Shapefile (.zip)
def parse_zip_shapefile(upload_file):
try:
# creating a temporary directoruy
with tempfile.TemporaryDirectory() as tmpdir:
zip_path = os.path.join(tmpdir, "uploaded.zip")
try:
# write uploaded file to disk
with open(zip_path, "wb") as f:
f.write(upload_file.read())
except Exception:
return [], "Couldn't read uploaded Zip file."
try:
# extract zipfile content
with zipfile.ZipFile(zip_path, "r") as zf:
zf.extractall(tmpdir)
except zipfile.BadZipFile:
return [], "Not a valid zip file."
# parse for .shp file within extracted content
shp_files = [os.path.join(tmpdir, f) for f in os.listdir(tmpdir) if f.endswith(".shp")]
if not shp_files:
return [], "Zip file does not contain .SHP file."
#laod shapefile with geopandas
try:
gdf = gpd.read_file(shp_files[0])
except Exception as e:
return [], f"Failed to read Shapefile with GeoPandas: Missing one or multiple companion files (.SHX, .DBF, .CPG, .PRJ) {str(e)}"
if gdf.empty:
return [], "Shapefile contains no features."
# convert geometry to match earth engine geometry object (as multipolygon)
geometry_list = []
for geom in gdf.geometry:
try:
if geom.geom_type == "Polygon":
coords = [list(geom.exterior.coords)]
ee_geom = ee.Geometry.Polygon(coords)
elif geom.geom_type == "MultiPolygon":
coords = [list(p.exterior.coords) for p in geom.geoms]
ee_geom = ee.Geometry.MultiPolygon(coords)
else:
continue # ignore non-area geometries
geometry_list.append(ee_geom)
except Exception:
continue # skip invalid EE geometries
if not geometry_list:
return [], "No valid Polygon or MultiPolygon geometries found in Shapefile."
return geometry_list, None
except Exception as e:
return [], f"Unexpected error while processing Shapefile: {str(e)}"
# File Parser: KML (.kml)
def parse_kml(upload_file):
try:
upload_file.seek(0)
try:
tree = ET.parse(upload_file)
except ET.ParseError:
return [], "Invalid KML file. XML could not be parsed."
# get kml tree structure
root = tree.getroot()
# namespace
ns = {"kml": "http://www.opengis.net/kml/2.2"}
placemarks = root.findall(".//kml:Placemark", ns)
if not placemarks:
return [], "No Placemark elements found in KML file."
geometry_list = []
# getting coordinates from placemark in the kml
for placemark in placemarks:
coords_elem = placemark.find(".//kml:coordinates", ns)
if coords_elem is None or not coords_elem.text:
continue
try:
coords_raw = coords_elem.text.strip().split()
coords = []
for c in coords_raw:
lon, lat, *_ = map(float, c.split(","))
coords.append([lon, lat])
# valid polygon needs at least 3 points
if len(coords) < 3:
continue
# ensure closed polygon
if coords[0] != coords[-1]:
coords.append(coords[0])
ee_geom = ee.Geometry.Polygon([coords])
geometry_list.append(ee_geom)
except Exception:
# skip malformed placemark
continue
if not geometry_list:
return [], "No valid polygon geometries could be constructed from KML."
return geometry_list, None
except Exception as e:
return [], f"Error processing KML file: {str(e)}"
# File Parser: TopoJSON (.topojson)
def parse_topojson(upload_file):
try:
bytes_data = upload_file.read()
try:
topojson_data = json.loads(bytes_data)
except json.JSONDecodeError:
return [], "Invalid TopoJSON file. JSON could not be decoded."
# Check TopoJSON signature
if topojson_data.get("type") != "Topology":
return [], "File is not a valid TopoJSON (missing or invalid 'Topology' type)."
# Manually decode TopoJSON arcs to avoid library performance issues
# Extract arcs and transform parameters
arcs = topojson_data.get("arcs")
objects = topojson_data.get("objects")
transform = topojson_data.get("transform", {})
scale = transform.get("scale", [1, 1])
translate = transform.get("translate", [0, 0])
if not arcs or not isinstance(arcs, list):
return [], "TopoJSON file contains no valid arcs."
if not objects or not isinstance(objects, dict):
return [], "TopoJSON file contains no objects."
# Decode arcs from delta-encoded to absolute coordinates
decoded_arcs = []
for arc in arcs:
x, y = 0, 0
points = []
for dx, dy in arc:
x += dx
y += dy
lon = x * scale[0] + translate[0]
lat = y * scale[1] + translate[1]
points.append([lon, lat])
decoded_arcs.append(points)
# Extract geometries from objects
geometries = []
for obj in objects.values():
if obj.get("type") == "GeometryCollection":
geometries.extend(obj.get("geometries", []))
else:
geometries.append(obj)
if not geometries:
return [], "TopoJSON file contains no geometries."
# Convert geometries to Earth Engine geometry objects
geometry_list = []
# Build Earth Engine geometries
for geom_data in geometries:
geom_type = geom_data.get("type")
arcs_refs = geom_data.get("arcs")
if not arcs_refs:
continue
try:
# Polygon
if geom_type == "Polygon":
# Polygon: arcs_refs is a list of arc index lists (one per ring)
rings = []
for ring_refs in arcs_refs:
ring = []
for arc_ref in ring_refs:
arc_idx = abs(arc_ref)
arc_points = (
decoded_arcs[arc_idx]
if arc_ref >= 0
else list(reversed(decoded_arcs[arc_idx]))
)
ring.extend(arc_points)
rings.append(ring)
geometry_list.append(ee.Geometry.Polygon(rings))
# MultiPolygon
elif geom_type == "MultiPolygon":
polygons = []
for polygon_refs in arcs_refs:
rings = []
for ring_refs in polygon_refs:
ring = []
for arc_ref in ring_refs:
arc_idx = abs(arc_ref)
arc_points = (
decoded_arcs[arc_idx]
if arc_ref >= 0
else list(reversed(decoded_arcs[arc_idx]))
)
ring.extend(arc_points)
rings.append(ring)
polygons.append(rings)
geometry_list.append(ee.Geometry.MultiPolygon(polygons))
# Ignore other geometry types
except Exception:
continue
if not geometry_list:
return [], "No valid Polygon or MultiPolygon geometries could be constructed from TopoJSON."
return geometry_list, None
except Exception as e:
return [], f"Error processing TopoJSON file: {str(e)}"
# File Parser: GeoJSON (.geojson, .json)
def parse_geojson(upload_file):
try:
bytes_data = upload_file.read()
try:
geojson_data = json.loads(bytes_data)
except json.JSONDecodeError:
return [], "Invalid GeoJSON file. JSON could not be decoded."
# detect the correct container of features
if 'features' in geojson_data and isinstance(geojson_data['features'], list):
features = geojson_data['features']
elif 'geometries' in geojson_data and isinstance(geojson_data['geometries'], list):
# Handle GeometryCollection-style structures
features = [{'geometry': geo} for geo in geojson_data['geometries']]
else:
# skip unsupported or invalid GeoJSON
return [], "Unsupported GeoJSON structure. Must containe a 'features' or 'geometries' field."
geometry_list = []
# build Earth Engine geometries
for feature in features:
if 'geometry' in feature and 'coordinates' in feature['geometry']:
coordinates = feature['geometry']['coordinates']
geometry_type = feature['geometry']['type']
# Create Polygon or MultiPolygon geometry
geometry = (
ee.Geometry.Polygon(coordinates)
if geometry_type == 'Polygon'
else ee.Geometry.MultiPolygon(coordinates)
)
geometry_list.append(geometry)
if not geometry_list:
return [], "No valide geometries in the GeoJSON file. Ensure it contains Polygon or MultiPolygon features."
return geometry_list, None
except Exception as e:
return [], f"Error processing GeoJSON file: {str(e)} Please verify the file is valid."
# Main Upload Function
last_uploaded_centroid = None
def upload_files_proc(upload_files):
# A global variable to track the latest geojson uploaded
global last_uploaded_centroid
# Setting up a variable that takes all polygons/geometries within the same/different geojson
geometry_aoi_list = []
# Variable to store all error messages from various parsers
error_messages = []
for upload_file in upload_files:
# Get the file name for extension detection
file_name = getattr(upload_file, 'name').lower()
# reset file pointer if it was read before
upload_file.seek(0)
# File Parser: GeoPackage
if file_name.endswith(".gpkg"):
# store gpkg into a temporary file for Fiona
with tempfile.NamedTemporaryFile(suffix=".gpkg", delete=False) as tmp:
# write uploaded file content to temp file
tmp.write(upload_file.getbuffer())
# write data to disk for readability
tmp.flush()
# parse temporary geopackage
gpkg_geoms, error = parse_geopackage(tmp.name)
if error:
error_messages.append(f"→ {file_name}:\n > {error}")
geometry_aoi_list.extend(gpkg_geoms)
if gpkg_geoms:
last_uploaded_centroid = gpkg_geoms[0].centroid(maxError=1).getInfo()["coordinates"]
continue
# File Parser: CSV
if file_name.endswith(".csv"):
csv_geoms, error = parse_csv(upload_file)
if error:
error_messages.append(f"→ {file_name}:\n > {error}")
geometry_aoi_list.extend(csv_geoms)
if csv_geoms:
last_uploaded_centroid = csv_geoms[0].centroid(maxError=1).getInfo()["coordinates"]
continue
# File Parser: KML
if file_name.endswith(".kml"):
kml_geoms, error = parse_kml(upload_file)
if error:
error_messages.append(f"→ {file_name}:\n > {error}")
geometry_aoi_list.extend(kml_geoms)
if kml_geoms:
last_uploaded_centroid = kml_geoms[0].centroid(maxError=1).getInfo()['coordinates']
continue
# File Parser: ZIP .Shapefile
if file_name.endswith(".zip"):
shp_geoms, error = parse_zip_shapefile(upload_file)
if error:
error_messages.append(f"→ {file_name}:\n > {error}")
geometry_aoi_list.extend(shp_geoms)
if shp_geoms:
last_uploaded_centroid = shp_geoms[0].centroid(maxError=1).getInfo()['coordinates']
continue
# File Parser: TopoJSON files
if file_name.endswith(".topojson"):
topojson_geoms, error = parse_topojson(upload_file)
if error:
error_messages.append(f"→ {file_name}:\n > {error}")
geometry_aoi_list.extend(topojson_geoms)
if topojson_geoms:
last_uploaded_centroid = topojson_geoms[0].centroid(maxError=1).getInfo()['coordinates']
continue
# File Parser: GeoJSON files
if file_name.endswith(".geojson") or file_name.endswith(".json"):
geojson_geoms, error = parse_geojson(upload_file)
if error:
error_messages.append(f"→ {file_name}: \n > {error}")
geometry_aoi_list.extend(geojson_geoms)
if geojson_geoms:
last_uploaded_centroid = geojson_geoms[0].centroid(maxError=1).getInfo()['coordinates']
continue
if error_messages:
show_error_dialog("\n\n---\n\n".join(error_messages))
# assembling aoi geometries
if geometry_aoi_list:
geometry_aoi = ee.Geometry.MultiPolygon(geometry_aoi_list)
else:
geometry_aoi = ee.Geometry.Point([16.25, 36.65])
return geometry_aoi
# Time input processing function
def date_input_proc(input_date, time_range):
end_date = input_date
start_date = input_date - timedelta(days=time_range)
str_start_date = start_date.strftime('%Y-%m-%d')
str_end_date = end_date.strftime('%Y-%m-%d')
return str_start_date, str_end_date
# Main function to run the Streamlit app
def main():
# initiate gee
ee_authenticate()
# Session states
st.session_state.setdefault("ee_ready", False)
# sidebar
with st.sidebar:
st.title("NDVI Viewer App")
st.image("https://cdn-icons-png.flaticon.com/512/2516/2516640.png", width=90)
st.subheader("Navigation:")
st.markdown(
"""
- [NDVI Map](#ndvi-viewer)
- [Map Legend](#map-legend)
- [Process workflow](#process-workflow-aoi-date-range-and-classification)
- [Interpreting the Results](#interpreting-the-results)
- [Environmental Index](#using-an-environmental-index-ndvi)
- [Data](#data-sentinel-2-imagery-and-l2a-product)
- [Contribution](#contribute-to-the-app)
- [About](#about)
- [Credit](#credit)
""")
st.subheader("Contact:")
st.markdown("[](https://linkedin.com/in/ahmed-islem-mokhtari) [](https://github.com/IndigoWizard) [](https://medium.com/@Indigo.Wizard/mt-chenoua-forest-fires-analysis-with-remote-sensing-614681f468e9)")
st.caption("ʕ •ᴥ•ʔ Star⭐the [project on GitHub](https://github.com/IndigoWizard/NDVI-Viewer/)!")
with st.container():
st.title("NDVI Viewer")
st.markdown("**Monitor Vegetation Health by Viewing & Comparing NDVI Values Through Time and Location with Sentinel-2 Satellite Images on The Fly!**")
# columns for input - map
with st.form("input_form"):
c1, c2 = st.columns([3, 1])
#### User input section - START
with st.container():
with c2:
## Cloud coverage input
st.info("Cloud Coverage 🌥️")
cloud_pixel_percentage = st.slider(label="cloud pixel rate", min_value=5, max_value=100, step=5, value=100 , label_visibility="collapsed")
## File upload
# User input GeoJSON file
st.info("Upload Area Of Interest file:")
upload_files = st.file_uploader("Crete a GeoJSON file at: [geojson.io](https://geojson.io/)", accept_multiple_files=True)
# calling upload files function
geometry_aoi = upload_files_proc(upload_files)
## Accessibility: Color palette input
st.info("Custom Color Palettes")
accessibility = st.selectbox("Accessibility: Colorblind-friendly Palettes", ["Normal", "Deuteranopia", "Protanopia", "Tritanopia", "Achromatopsia"])
# Define default color palettes: used in map layers & map legend
default_ndvi_palette = ["#ffffe5", "#f7fcb9", "#78c679", "#41ab5d", "#238443", "#005a32"]
default_reclassified_ndvi_palette = ["#a50026","#ed5e3d","#f9f7ae","#f4ff78","#9ed569","#229b51","#006837"]
# a copy of default colors that can be reaffected
ndvi_palette = default_ndvi_palette.copy()
reclassified_ndvi_palette = default_reclassified_ndvi_palette.copy()
if accessibility == "Deuteranopia":
ndvi_palette = ["#fffaa1","#f4ef8e","#9a5d67","#573f73","#372851","#191135"]
reclassified_ndvi_palette = ["#95a600","#92ed3e","#affac5","#78ffb0","#69d6c6","#22459c","#000e69"]
elif accessibility == "Protanopia":
ndvi_palette = ["#a6f697","#7def75","#2dcebb","#1597ab","#0c677e","#002c47"]
reclassified_ndvi_palette = ["#95a600","#92ed3e","#affac5","#78ffb0","#69d6c6","#22459c","#000e69"]
elif accessibility == "Tritanopia":
ndvi_palette = ["#cdffd7","#a1fbb6","#6cb5c6","#3a77a5","#205080","#001752"]
reclassified_ndvi_palette = ["#ed4700","#ed8a00","#e1fabe","#99ff94","#87bede","#2e40cf","#0600bc"]
elif accessibility == "Achromatopsia":
ndvi_palette = ["#407de0", "#2763da", "#394388", "#272c66", "#16194f", "#010034"]
reclassified_ndvi_palette = ["#004f3d", "#338796", "#66a4f5", "#3683ff", "#3d50ca", "#421c7f", "#290058"]
with st.container():
## Time range input
with c1:
col1, col2 = st.columns(2)
# Creating a 2 days delay for the date_input placeholder to be sure there are satellite images in the dataset on app start
today = datetime.today()
delay = today - timedelta(days=2)
# Date input widgets
col1.warning("Initial NDVI Date 📅")
initial_date = col1.date_input("initial", datetime(2026, 1, 12), label_visibility="collapsed")
col2.success("Updated NDVI Date 📅")
updated_date = col2.date_input("updated", datetime(2026, 1, 12), label_visibility="collapsed")
# Setting up the time range variable for an image collection
time_range = 7
# Process initial date
str_initial_start_date, str_initial_end_date = date_input_proc(initial_date, time_range)
# Process updated date
str_updated_start_date, str_updated_end_date = date_input_proc(updated_date, time_range)
#### User input section - END
#### Map section - START
global last_uploaded_centroid
# Create the initial map
if last_uploaded_centroid is not None:
latitude = last_uploaded_centroid[1]
longitude = last_uploaded_centroid[0]
m = folium.Map(location=[latitude, longitude], tiles=None, zoom_start=12, control_scale=True, attributionControl=0)
else:
# Default location if no file is uploaded
m = folium.Map(location=[36.45, 10.85], tiles=None, zoom_start=5, control_scale=True, attributionControl=0)
### BASEMAPS - START
## Primary basemaps
# OSM
b0 = folium.TileLayer('OpenStreetMap', name='Open Street Map', attr='OSM')
b0.add_to(m)
# Mapbox
mapbox_api = st.secrets["mapbox_token"]