UjjwalKGupta commited on
Commit
3bf4279
1 Parent(s): 95324aa

Accept KML files

Browse files
Files changed (1) hide show
  1. app.py +195 -150
app.py CHANGED
@@ -1,151 +1,196 @@
1
- import os
2
- import ee
3
- import geemap
4
- import json
5
- import geopandas as gpd
6
- import streamlit as st
7
- import pandas as pd
8
- from fastkml import kml
9
- import geojson
10
-
11
- ee_credentials = os.environ.get("EE")
12
- os.makedirs(os.path.expanduser("~/.config/earthengine/"), exist_ok=True)
13
- with open(os.path.expanduser("~/.config/earthengine/credentials"), "w") as f:
14
- f.write(ee_credentials)
15
-
16
- ee.Initialize()
17
-
18
- def convert_3d_to_2d(geometry):
19
- """
20
- Recursively convert any 3D coordinates in a geometry to 2D.
21
- """
22
- if geometry.is_empty:
23
- return geometry
24
-
25
- if geometry.geom_type == 'Polygon':
26
- return geojson.Polygon([[(x, y) for x, y, *_ in ring] for ring in geometry.coordinates])
27
-
28
- elif geometry.geom_type == 'MultiPolygon':
29
- return geojson.MultiPolygon([
30
- [[(x, y) for x, y, *_ in ring] for ring in poly]
31
- for poly in geometry.coordinates
32
- ])
33
-
34
- elif geometry.geom_type == 'LineString':
35
- return geojson.LineString([(x, y) for x, y, *_ in geometry.coordinates])
36
-
37
- elif geometry.geom_type == 'MultiLineString':
38
- return geojson.MultiLineString([
39
- [(x, y) for x, y, *_ in line]
40
- for line in geometry.coordinates
41
- ])
42
-
43
- elif geometry.geom_type == 'Point':
44
- x, y, *_ = geometry.coordinates
45
- return geojson.Point((x, y))
46
-
47
- elif geometry.geom_type == 'MultiPoint':
48
- return geojson.MultiPoint([(x, y) for x, y, *_ in geometry.coordinates])
49
-
50
- return geometry # Return unchanged if not a supported geometry type
51
-
52
- def kml_to_geojson(kml_string):
53
- k = kml.KML()
54
- k.from_string(kml_string.encode('utf-8')) # Convert the string to bytes
55
- features = list(k.features())
56
-
57
- geojson_features = []
58
- for feature in features:
59
- geometry_2d = convert_3d_to_2d(feature.geometry)
60
- geojson_features.append(geojson.Feature(geometry=geometry_2d))
61
-
62
- geojson_data = geojson.FeatureCollection(geojson_features)
63
- return geojson_data
64
-
65
- def geojson_to_ee(geojson_data):
66
- ee_object = geemap.geojson_to_ee(geojson_data)
67
- return ee_object
68
-
69
- # put title in center
70
- st.markdown("""
71
- <style>
72
- h1 {
73
- text-align: center;
74
- }
75
- </style>
76
- """, unsafe_allow_html=True)
77
-
78
- st.title("Mean NDVI Calculator")
79
-
80
- # get the start and end date from the user
81
- col = st.columns(2)
82
- start_date = col[0].date_input("Start Date", value=pd.to_datetime('2021-01-01'))
83
- end_date = col[1].date_input("End Date", value=pd.to_datetime('2021-01-30'))
84
- start_date = start_date.strftime("%Y-%m-%d")
85
- end_date = end_date.strftime("%Y-%m-%d")
86
-
87
- max_cloud_cover = st.number_input("Max Cloud Cover", value=20)
88
-
89
- # Get the geojson file from the user
90
- uploaded_file = st.file_uploader("Upload KML/GeoJSON file", type=["geojson", "kml"])
91
-
92
- # Read the KML file
93
- if uploaded_file is None:
94
- file_name = "Bhankhara_Df_11_he_5_2020-21.geojson"
95
- st.write(f"Using default file: {file_name}")
96
- data = gpd.read_file(file_name)
97
- with open(file_name) as f:
98
- str_data = f.read()
99
- else:
100
- st.write(f"Using uploaded file: {uploaded_file.name}")
101
- file_name = uploaded_file.name
102
- bytes_data = uploaded_file.getvalue()
103
- str_data = bytes_data.decode("utf-8")
104
-
105
-
106
- if file_name.endswith(".geojson"):
107
- geojson_data = json.loads(str_data)
108
- elif file_name.endswith(".kml"):
109
- geojson_data = kml_to_geojson(str_data)
110
- print(geojson_data)
111
-
112
- # Read Geojson File
113
- ee_object = geojson_to_ee(geojson_data)
114
-
115
- # Filter data based on the date, bounds, cloud coverage and select NIR and Red Band
116
- collection = ee.ImageCollection("COPERNICUS/S2_SR_HARMONIZED").filterBounds(ee_object).filter(ee.Filter.lt('CLOUDY_PIXEL_PERCENTAGE', max_cloud_cover)).filter(ee.Filter.date(start_date, end_date)).select(['B4', 'B8'])
117
-
118
- # Print Number of Images in collection
119
- # print("Number of images", collection.size().getInfo())
120
- st.write(f"Number of images: {collection.size().getInfo()}")
121
-
122
- # Calculate NDVI as Normalized Index
123
- def calculate_ndvi(image):
124
- ndvi = image.normalizedDifference(['B8', 'B4']).rename('NDVI')
125
- return image.addBands(ndvi)
126
-
127
- collection = collection.map(calculate_ndvi)
128
-
129
- # Write Zonalstats into csv file
130
- # out_dir = os.path.join("Output")
131
- # out_NDVI_stats = os.path.join(out_dir, "tmp.csv")
132
-
133
- # if not os.path.exists(out_dir):
134
- # os.makedirs(out_dir)
135
-
136
- geemap.zonal_stats(collection.select(["NDVI"]), ee_object, "tmp.csv", stat_type="mean", scale=10)
137
-
138
- # Show the table
139
- df = pd.read_csv("tmp.csv")
140
- df = df.T
141
- df = df.reset_index()
142
- df = df.iloc[:-2]
143
- df['index'] = pd.to_datetime(df['index'].apply(lambda x: x.split('_')[1].split('T')[0])).dt.strftime('%Y-%m-%d')
144
- df.rename(columns={'index': 'Date', 0: 'Mean NDVI'}, inplace=True)
145
- st.write(df)
146
-
147
- # plot the time series
148
- st.write("Time Series Plot")
149
- st.line_chart(df.set_index('Date'))
150
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
151
  st.write(f"Overall Mean NDVI: {df['Mean NDVI'].mean():.2f}")
 
1
+ import os
2
+ import ee
3
+ import geemap
4
+ import json
5
+ import geopandas as gpd
6
+ import streamlit as st
7
+ import pandas as pd
8
+ from fastkml import kml
9
+ import geojson
10
+
11
+ ee_credentials = os.environ.get("EE")
12
+ os.makedirs(os.path.expanduser("~/.config/earthengine/"), exist_ok=True)
13
+ with open(os.path.expanduser("~/.config/earthengine/credentials"), "w") as f:
14
+ f.write(ee_credentials)
15
+
16
+ ee.Initialize()
17
+
18
+ def convert_3d_to_2d(geometry):
19
+ """
20
+ Recursively convert any 3D coordinates in a geometry to 2D.
21
+ """
22
+ if geometry.is_empty:
23
+ return geometry
24
+
25
+ if geometry.geom_type == 'Polygon':
26
+ return geojson.Polygon([[(x, y) for x, y, *_ in ring] for ring in geometry.coordinates])
27
+
28
+ elif geometry.geom_type == 'MultiPolygon':
29
+ return geojson.MultiPolygon([
30
+ [[(x, y) for x, y, *_ in ring] for ring in poly]
31
+ for poly in geometry.coordinates
32
+ ])
33
+
34
+ elif geometry.geom_type == 'LineString':
35
+ return geojson.LineString([(x, y) for x, y, *_ in geometry.coordinates])
36
+
37
+ elif geometry.geom_type == 'MultiLineString':
38
+ return geojson.MultiLineString([
39
+ [(x, y) for x, y, *_ in line]
40
+ for line in geometry.coordinates
41
+ ])
42
+
43
+ elif geometry.geom_type == 'Point':
44
+ x, y, *_ = geometry.coordinates
45
+ return geojson.Point((x, y))
46
+
47
+ elif geometry.geom_type == 'MultiPoint':
48
+ return geojson.MultiPoint([(x, y) for x, y, *_ in geometry.coordinates])
49
+
50
+ return geometry # Return unchanged if not a supported geometry type
51
+
52
+ def convert_to_2d_geometry(geom): #Handles Polygon Only
53
+ if geom is None:
54
+ return None
55
+ elif geom.has_z:
56
+ # Extract exterior coordinates and convert to 2D
57
+ exterior_coords = geom.exterior.coords[:] # Get all coordinates of the exterior ring
58
+ exterior_coords_2d = [(x, y) for x, y, *_ in exterior_coords] # Keep only the x and y coordinates, ignoring z
59
+
60
+ # Handle interior rings (holes) if any
61
+ interior_coords_2d = []
62
+ for interior in geom.interiors:
63
+ interior_coords = interior.coords[:]
64
+ interior_coords_2d.append([(x, y) for x, y, *_ in interior_coords])
65
+
66
+ # Create a new Polygon with 2D coordinates
67
+ return type(geom)(exterior_coords_2d, interior_coords_2d)
68
+ else:
69
+ return geom
70
+
71
+ def kml_to_gdf(kml_file):
72
+ try:
73
+ gdf = gpd.read_file(kml_file)
74
+ for i in range(len(gdf)):
75
+ geom = gdf.iloc[i].geometry
76
+ new_geom = convert_to_2d_geometry(geom)
77
+ gdf.loc[i, 'geometry'] = new_geom
78
+ print(gdf.iloc[i].geometry)
79
+ print(f"KML file '{kml_file}' successfully read")
80
+ except Exception as e:
81
+ print(f"Error: {e}")
82
+ return gdf
83
+
84
+ def kml_to_geojson(kml_string):
85
+ k = kml.KML()
86
+ k.from_string(kml_string.encode('utf-8')) # Convert the string to bytes
87
+ features = list(k.features())
88
+
89
+ geojson_features = []
90
+ for feature in features:
91
+ geometry_2d = convert_3d_to_2d(feature.geometry)
92
+ geojson_features.append(geojson.Feature(geometry=geometry_2d))
93
+
94
+ geojson_data = geojson.FeatureCollection(geojson_features)
95
+ return geojson_data
96
+
97
+ def geojson_to_ee(geojson_data):
98
+ ee_object = ee.FeatureCollection(geojson_data)
99
+ return ee_object
100
+
101
+ def kml_to_gdf(kml_file):
102
+ try:
103
+ gdf = gpd.read_file(kml_file)
104
+ for i in range(len(gdf)):
105
+ geom = gdf.iloc[i].geometry
106
+ new_geom = convert_to_2d_geometry(geom)
107
+ gdf.loc[i, 'geometry'] = new_geom
108
+ print(gdf.iloc[i].geometry)
109
+ print(f"KML file '{kml_file}' successfully read")
110
+ except Exception as e:
111
+ print(f"Error: {e}")
112
+ return gdf
113
+
114
+ # put title in center
115
+ st.markdown("""
116
+ <style>
117
+ h1 {
118
+ text-align: center;
119
+ }
120
+ </style>
121
+ """, unsafe_allow_html=True)
122
+
123
+ st.title("Mean NDVI Calculator")
124
+
125
+ # get the start and end date from the user
126
+ col = st.columns(2)
127
+ start_date = col[0].date_input("Start Date", value=pd.to_datetime('2021-01-01'))
128
+ end_date = col[1].date_input("End Date", value=pd.to_datetime('2021-01-30'))
129
+ start_date = start_date.strftime("%Y-%m-%d")
130
+ end_date = end_date.strftime("%Y-%m-%d")
131
+
132
+ max_cloud_cover = st.number_input("Max Cloud Cover", value=20)
133
+
134
+ # Get the geojson file from the user
135
+ uploaded_file = st.file_uploader("Upload KML/GeoJSON file", type=["geojson", "kml"])
136
+
137
+ # Read the KML file
138
+ if uploaded_file is None:
139
+ file_name = "Bhankhara_Df_11_he_5_2020-21.geojson"
140
+ st.write(f"Using default file: {file_name}")
141
+ data = gpd.read_file(file_name)
142
+ with open(file_name) as f:
143
+ str_data = f.read()
144
+ else:
145
+ st.write(f"Using uploaded file: {uploaded_file.name}")
146
+ file_name = uploaded_file.name
147
+ bytes_data = uploaded_file.getvalue()
148
+ str_data = bytes_data.decode("utf-8")
149
+
150
+
151
+ if file_name.endswith(".geojson"):
152
+ geojson_data = json.loads(str_data)
153
+ elif file_name.endswith(".kml"):
154
+ geojson_data = json.loads(kml_to_gdf(str_data).to_json())
155
+ print(geojson_data)
156
+
157
+ # Read Geojson File
158
+ ee_object = geojson_to_ee(geojson_data)
159
+
160
+ # Filter data based on the date, bounds, cloud coverage and select NIR and Red Band
161
+ collection = ee.ImageCollection("COPERNICUS/S2_SR_HARMONIZED").filterBounds(ee_object).filter(ee.Filter.lt('CLOUDY_PIXEL_PERCENTAGE', max_cloud_cover)).filter(ee.Filter.date(start_date, end_date)).select(['B4', 'B8'])
162
+
163
+ # Print Number of Images in collection
164
+ # print("Number of images", collection.size().getInfo())
165
+ st.write(f"Number of images: {collection.size().getInfo()}")
166
+
167
+ # Calculate NDVI as Normalized Index
168
+ def calculate_ndvi(image):
169
+ ndvi = image.normalizedDifference(['B8', 'B4']).rename('NDVI')
170
+ return image.addBands(ndvi)
171
+
172
+ collection = collection.map(calculate_ndvi)
173
+
174
+ # Write Zonalstats into csv file
175
+ # out_dir = os.path.join("Output")
176
+ # out_NDVI_stats = os.path.join(out_dir, "tmp.csv")
177
+
178
+ # if not os.path.exists(out_dir):
179
+ # os.makedirs(out_dir)
180
+
181
+ geemap.zonal_stats(collection.select(["NDVI"]), ee_object, "tmp.csv", stat_type="mean", scale=10)
182
+
183
+ # Show the table
184
+ df = pd.read_csv("tmp.csv")
185
+ df = df.T
186
+ df = df.reset_index()
187
+ df = df.iloc[:-2]
188
+ df['index'] = pd.to_datetime(df['index'].apply(lambda x: x.split('_')[1].split('T')[0])).dt.strftime('%Y-%m-%d')
189
+ df.rename(columns={'index': 'Date', 0: 'Mean NDVI'}, inplace=True)
190
+ st.write(df)
191
+
192
+ # plot the time series
193
+ st.write("Time Series Plot")
194
+ st.line_chart(df.set_index('Date'))
195
+
196
  st.write(f"Overall Mean NDVI: {df['Mean NDVI'].mean():.2f}")