Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -1,3 +1,4 @@
|
|
|
|
1 |
import streamlit as st
|
2 |
import json
|
3 |
import ee
|
@@ -117,6 +118,7 @@ def calculate_custom_formula(image, geometry, selected_bands, custom_formula, re
|
|
117 |
band_scales.append(band_scale)
|
118 |
default_scale = min(band_scales) if band_scales else 30 # Default to 30m if no bands are found
|
119 |
scale = user_scale if user_scale is not None else default_scale
|
|
|
120 |
# Rescale all bands to the chosen scale
|
121 |
rescaled_bands = {}
|
122 |
for band in selected_bands:
|
@@ -130,6 +132,7 @@ def calculate_custom_formula(image, geometry, selected_bands, custom_formula, re
|
|
130 |
rescaled_bands[band] = rescaled_band
|
131 |
else:
|
132 |
rescaled_bands[band] = band_image
|
|
|
133 |
# Validate and extract band values
|
134 |
reduced_values = {}
|
135 |
reducer = get_reducer(reducer_choice)
|
@@ -140,11 +143,13 @@ def calculate_custom_formula(image, geometry, selected_bands, custom_formula, re
|
|
140 |
scale=scale
|
141 |
).get(band).getInfo()
|
142 |
reduced_values[band] = float(value if value is not None else 0)
|
|
|
143 |
# Evaluate the custom formula
|
144 |
formula = custom_formula
|
145 |
for band in selected_bands:
|
146 |
formula = formula.replace(band, str(reduced_values[band]))
|
147 |
result = eval(formula, {"__builtins__": {}}, reduced_values)
|
|
|
148 |
# Validate the result
|
149 |
if not isinstance(result, (int, float)):
|
150 |
raise ValueError("Formula did not result in a numeric value.")
|
@@ -162,6 +167,68 @@ def calculate_custom_formula(image, geometry, selected_bands, custom_formula, re
|
|
162 |
st.error(f"Unexpected error: {e}")
|
163 |
return ee.Image(0).rename('custom_result').set('error', str(e))
|
164 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
165 |
# Cloud percentage calculation
|
166 |
def calculate_cloud_percentage(image, cloud_band='QA60'):
|
167 |
qa60 = image.select(cloud_band)
|
@@ -193,6 +260,7 @@ def preprocess_collection(collection, pixel_cloud_threshold):
|
|
193 |
cloud_mask = opaque_clouds.Or(cirrus_clouds)
|
194 |
clear_pixels = cloud_mask.Not()
|
195 |
return image.updateMask(clear_pixels)
|
|
|
196 |
if pixel_cloud_threshold > 0:
|
197 |
return collection.map(mask_cloudy_pixels)
|
198 |
return collection
|
@@ -222,15 +290,20 @@ def process_single_geometry(row, start_date_str, end_date_str, dataset_id, selec
|
|
222 |
roi = roi.buffer(-30).bounds()
|
223 |
except ValueError:
|
224 |
return None
|
|
|
225 |
# Filter collection by date and area first
|
|
|
226 |
collection = ee.ImageCollection(dataset_id) \
|
227 |
.filterDate(ee.Date(start_date_str), ee.Date(end_date_str)) \
|
228 |
.filterBounds(roi)
|
229 |
-
|
230 |
-
# Apply
|
231 |
if pixel_cloud_threshold > 0:
|
232 |
collection = preprocess_collection(collection, pixel_cloud_threshold)
|
233 |
st.write(f"After cloud masking: {collection.size().getInfo()} images")
|
|
|
|
|
|
|
234 |
if aggregation_period.lower() == 'custom (start date to end date)':
|
235 |
collection = aggregate_data_custom(collection)
|
236 |
elif aggregation_period.lower() == 'daily':
|
@@ -241,6 +314,7 @@ def process_single_geometry(row, start_date_str, end_date_str, dataset_id, selec
|
|
241 |
collection = aggregate_data_monthly(collection, start_date_str, end_date_str)
|
242 |
elif aggregation_period.lower() == 'yearly':
|
243 |
collection = aggregate_data_yearly(collection)
|
|
|
244 |
image_list = collection.toList(collection.size())
|
245 |
processed_weeks = set()
|
246 |
aggregated_results = []
|
@@ -271,6 +345,7 @@ def process_single_geometry(row, start_date_str, end_date_str, dataset_id, selec
|
|
271 |
timestamp = image.get('year')
|
272 |
period_label = 'Year'
|
273 |
date = ee.Date(timestamp).format('YYYY').getInfo()
|
|
|
274 |
index_image = calculate_custom_formula(image, roi, selected_bands, custom_formula, reducer_choice, dataset_id, user_scale=user_scale)
|
275 |
try:
|
276 |
index_value = index_image.reduceRegion(
|
@@ -295,6 +370,7 @@ def process_single_geometry(row, start_date_str, end_date_str, dataset_id, selec
|
|
295 |
st.error(f"Error retrieving value for {location_name}: {e}")
|
296 |
return aggregated_results
|
297 |
|
|
|
298 |
# Process aggregation
|
299 |
def process_aggregation(locations_df, start_date_str, end_date_str, dataset_id, selected_bands, reducer_choice, shape_type, aggregation_period, original_lat_col, original_lon_col, custom_formula="", kernel_size=None, include_boundary=None, tile_cloud_threshold=0, pixel_cloud_threshold=0, user_scale=None):
|
300 |
aggregated_results = []
|
@@ -302,22 +378,18 @@ def process_aggregation(locations_df, start_date_str, end_date_str, dataset_id,
|
|
302 |
progress_bar = st.progress(0)
|
303 |
progress_text = st.empty()
|
304 |
start_time = time.time()
|
|
|
|
|
305 |
raw_collection = ee.ImageCollection(dataset_id) \
|
306 |
.filterDate(ee.Date(start_date_str), ee.Date(end_date_str))
|
307 |
-
|
308 |
-
# Log the original collection size
|
309 |
st.write(f"Original Collection Size: {raw_collection.size().getInfo()}")
|
310 |
|
311 |
-
#
|
312 |
-
# if roi is not None:
|
313 |
-
# raw_collection = raw_collection.filterBounds(roi)
|
314 |
-
# st.write(f"Filtered Collection Size (After Spatial Filtering): {raw_collection.size().getInfo()}")
|
315 |
-
|
316 |
-
# Apply cloud masking if threshold > 0
|
317 |
if pixel_cloud_threshold > 0:
|
318 |
raw_collection = preprocess_collection(raw_collection, pixel_cloud_threshold)
|
319 |
st.write(f"Filtered Collection Size (After Cloud Masking): {raw_collection.size().getInfo()}")
|
320 |
|
|
|
321 |
with ThreadPoolExecutor(max_workers=10) as executor:
|
322 |
futures = []
|
323 |
for idx, row in locations_df.iterrows():
|
@@ -339,6 +411,7 @@ def process_aggregation(locations_df, start_date_str, end_date_str, dataset_id,
|
|
339 |
user_scale=user_scale
|
340 |
)
|
341 |
futures.append(future)
|
|
|
342 |
completed = 0
|
343 |
for future in as_completed(futures):
|
344 |
result = future.result()
|
@@ -348,8 +421,10 @@ def process_aggregation(locations_df, start_date_str, end_date_str, dataset_id,
|
|
348 |
progress_percentage = completed / total_steps
|
349 |
progress_bar.progress(progress_percentage)
|
350 |
progress_text.markdown(f"Processing: {int(progress_percentage * 100)}%")
|
|
|
351 |
end_time = time.time()
|
352 |
processing_time = end_time - start_time
|
|
|
353 |
if aggregated_results:
|
354 |
result_df = pd.DataFrame(aggregated_results)
|
355 |
if aggregation_period.lower() == 'custom (start date to end date)':
|
@@ -367,8 +442,8 @@ def process_aggregation(locations_df, start_date_str, end_date_str, dataset_id,
|
|
367 |
else:
|
368 |
return result_df.to_dict(orient='records'), processing_time
|
369 |
return [], processing_time
|
370 |
-
|
371 |
-
#
|
372 |
st.markdown("<h5>Image Collection</h5>", unsafe_allow_html=True)
|
373 |
imagery_base = st.selectbox("Select Imagery Base", ["Sentinel", "Landsat", "MODIS", "VIIRS", "Custom Input"], index=0)
|
374 |
data = {}
|
@@ -431,6 +506,7 @@ elif imagery_base == "Custom Input":
|
|
431 |
if not data:
|
432 |
st.error("No valid dataset available. Please check your inputs.")
|
433 |
st.stop()
|
|
|
434 |
st.markdown("<hr><h5><b>{}</b></h5>".format(imagery_base), unsafe_allow_html=True)
|
435 |
main_selection = st.selectbox(f"Select {imagery_base} Dataset Category", list(data.keys()))
|
436 |
sub_selection = None
|
@@ -450,10 +526,13 @@ if main_selection:
|
|
450 |
st.write(f"Default Scale for Selected Dataset: {default_scale} meters")
|
451 |
except Exception as e:
|
452 |
st.error(f"Error fetching default scale: {str(e)}")
|
|
|
453 |
st.markdown("<hr><h5><b>Earth Engine Index Calculator</b></h5>", unsafe_allow_html=True)
|
454 |
if main_selection and sub_selection:
|
455 |
dataset_bands = data[main_selection]["bands"].get(sub_selection, [])
|
456 |
st.write(f"Available Bands for {sub_options[sub_selection]}: {', '.join(dataset_bands)}")
|
|
|
|
|
457 |
# Fetch nominal scales for all bands in the selected dataset
|
458 |
if dataset_id:
|
459 |
try:
|
@@ -461,16 +540,20 @@ if main_selection and sub_selection:
|
|
461 |
collection = ee.ImageCollection(dataset_id)
|
462 |
first_image = collection.first()
|
463 |
band_names = first_image.bandNames().getInfo()
|
|
|
464 |
# Extract scales for all bands
|
465 |
band_scales = []
|
466 |
for band in band_names:
|
467 |
band_scale = first_image.select(band).projection().nominalScale().getInfo()
|
468 |
band_scales.append(band_scale)
|
|
|
469 |
# Identify unique scales using np.unique
|
470 |
unique_scales = np.unique(band_scales)
|
|
|
471 |
# Display the unique scales to the user
|
472 |
st.write(f"Nominal Scales for Bands: {band_scales}")
|
473 |
st.write(f"Unique Scales in Dataset: {unique_scales}")
|
|
|
474 |
# If there are multiple unique scales, allow the user to choose one
|
475 |
if len(unique_scales) > 1:
|
476 |
selected_scale = st.selectbox(
|
@@ -483,9 +566,11 @@ if main_selection and sub_selection:
|
|
483 |
else:
|
484 |
default_scale = unique_scales[0]
|
485 |
st.write(f"Default Scale for Dataset: {default_scale} meters")
|
|
|
486 |
except Exception as e:
|
487 |
st.error(f"Error fetching band scales: {str(e)}")
|
488 |
default_scale = 30 # Fallback to 30 meters if an error occurs
|
|
|
489 |
selected_bands = st.multiselect(
|
490 |
"Select 1 or 2 Bands for Calculation",
|
491 |
options=dataset_bands,
|
@@ -524,15 +609,18 @@ if main_selection and sub_selection:
|
|
524 |
st.warning("Please enter a custom formula to proceed.")
|
525 |
st.stop()
|
526 |
st.write(f"Custom Formula: {custom_formula}")
|
|
|
527 |
reducer_choice = st.selectbox(
|
528 |
"Select Reducer (e.g, mean , sum , median , min , max , count)",
|
529 |
['mean', 'sum', 'median', 'min', 'max', 'count'],
|
530 |
index=0
|
531 |
)
|
|
|
532 |
start_date = st.date_input("Start Date", value=pd.to_datetime('2024-11-01'))
|
533 |
end_date = st.date_input("End Date", value=pd.to_datetime('2024-12-01'))
|
534 |
start_date_str = start_date.strftime('%Y-%m-%d')
|
535 |
end_date_str = end_date.strftime('%Y-%m-%d')
|
|
|
536 |
if imagery_base == "Sentinel" and "Sentinel-2" in sub_options[sub_selection]:
|
537 |
st.markdown("<h5>Cloud Filtering</h5>", unsafe_allow_html=True)
|
538 |
pixel_cloud_threshold = st.slider(
|
@@ -543,14 +631,17 @@ if imagery_base == "Sentinel" and "Sentinel-2" in sub_options[sub_selection]:
|
|
543 |
step=5,
|
544 |
help="Individual pixels with cloud coverage exceeding this threshold will be masked."
|
545 |
)
|
|
|
546 |
aggregation_period = st.selectbox(
|
547 |
"Select Aggregation Period (e.g, Custom(Start Date to End Date) , Daily , Weekly , Monthly , Yearly)",
|
548 |
["Custom (Start Date to End Date)", "Daily", "Weekly", "Monthly", "Yearly"],
|
549 |
index=0
|
550 |
)
|
|
|
551 |
shape_type = st.selectbox("Do you want to process 'Point' or 'Polygon' data?", ["Point", "Polygon"])
|
552 |
kernel_size = None
|
553 |
include_boundary = None
|
|
|
554 |
if shape_type.lower() == "point":
|
555 |
kernel_size = st.selectbox(
|
556 |
"Select Calculation Area(e.g, Point , 3x3 Kernel , 5x5 Kernel)",
|
@@ -564,6 +655,7 @@ elif shape_type.lower() == "polygon":
|
|
564 |
value=True,
|
565 |
help="Check to include pixels on the polygon boundary; uncheck to exclude them."
|
566 |
)
|
|
|
567 |
# st.markdown("<h5>Calculation Scale</h5>", unsafe_allow_html=True)
|
568 |
# default_scale = ee.ImageCollection(dataset_id).first().select(0).projection().nominalScale().getInfo()
|
569 |
# user_scale = st.number_input(
|
@@ -572,6 +664,7 @@ elif shape_type.lower() == "polygon":
|
|
572 |
# value=float(default_scale),
|
573 |
# help=f"Default scale for this dataset is {default_scale} meters. Adjust if needed."
|
574 |
# )
|
|
|
575 |
st.markdown("<h5>Calculation Scale</h5>", unsafe_allow_html=True)
|
576 |
user_scale = st.number_input(
|
577 |
"Enter Calculation Scale (meters) [Leave blank to use dataset's default scale]",
|
@@ -579,10 +672,12 @@ user_scale = st.number_input(
|
|
579 |
value=float(default_scale),
|
580 |
help=f"Default scale for this dataset is {default_scale} meters. Adjust if needed."
|
581 |
)
|
|
|
582 |
file_upload = st.file_uploader(f"Upload your {shape_type} data (CSV, GeoJSON, KML)", type=["csv", "geojson", "kml"])
|
583 |
locations_df = pd.DataFrame()
|
584 |
original_lat_col = None
|
585 |
original_lon_col = None
|
|
|
586 |
if file_upload is not None:
|
587 |
if shape_type.lower() == "point":
|
588 |
if file_upload.name.endswith('.csv'):
|
@@ -697,6 +792,7 @@ if file_upload is not None:
|
|
697 |
m.add_gdf(gdf=gdf, layer_name=row.get('name', 'Unnamed Polygon'))
|
698 |
st.write("Map of Uploaded Polygons:")
|
699 |
m.to_streamlit()
|
|
|
700 |
if st.button(f"Calculate {custom_formula}"):
|
701 |
if not locations_df.empty:
|
702 |
with st.spinner("Processing Data..."):
|
|
|
1 |
+
|
2 |
import streamlit as st
|
3 |
import json
|
4 |
import ee
|
|
|
118 |
band_scales.append(band_scale)
|
119 |
default_scale = min(band_scales) if band_scales else 30 # Default to 30m if no bands are found
|
120 |
scale = user_scale if user_scale is not None else default_scale
|
121 |
+
|
122 |
# Rescale all bands to the chosen scale
|
123 |
rescaled_bands = {}
|
124 |
for band in selected_bands:
|
|
|
132 |
rescaled_bands[band] = rescaled_band
|
133 |
else:
|
134 |
rescaled_bands[band] = band_image
|
135 |
+
|
136 |
# Validate and extract band values
|
137 |
reduced_values = {}
|
138 |
reducer = get_reducer(reducer_choice)
|
|
|
143 |
scale=scale
|
144 |
).get(band).getInfo()
|
145 |
reduced_values[band] = float(value if value is not None else 0)
|
146 |
+
|
147 |
# Evaluate the custom formula
|
148 |
formula = custom_formula
|
149 |
for band in selected_bands:
|
150 |
formula = formula.replace(band, str(reduced_values[band]))
|
151 |
result = eval(formula, {"__builtins__": {}}, reduced_values)
|
152 |
+
|
153 |
# Validate the result
|
154 |
if not isinstance(result, (int, float)):
|
155 |
raise ValueError("Formula did not result in a numeric value.")
|
|
|
167 |
st.error(f"Unexpected error: {e}")
|
168 |
return ee.Image(0).rename('custom_result').set('error', str(e))
|
169 |
|
170 |
+
# Aggregation functions
|
171 |
+
def aggregate_data_custom(collection):
|
172 |
+
collection = collection.map(lambda image: image.set('day', ee.Date(image.get('system:time_start')).format('YYYY-MM-dd')))
|
173 |
+
grouped_by_day = collection.aggregate_array('day').distinct()
|
174 |
+
def calculate_daily_mean(day):
|
175 |
+
daily_collection = collection.filter(ee.Filter.eq('day', day))
|
176 |
+
daily_mean = daily_collection.mean()
|
177 |
+
return daily_mean.set('day', day)
|
178 |
+
daily_images = ee.List(grouped_by_day.map(calculate_daily_mean))
|
179 |
+
return ee.ImageCollection(daily_images)
|
180 |
+
|
181 |
+
def aggregate_data_daily(collection):
|
182 |
+
def set_day_start(image):
|
183 |
+
date = ee.Date(image.get('system:time_start'))
|
184 |
+
day_start = date.format('YYYY-MM-dd')
|
185 |
+
return image.set('day_start', day_start)
|
186 |
+
collection = collection.map(set_day_start)
|
187 |
+
grouped_by_day = collection.aggregate_array('day_start').distinct()
|
188 |
+
def calculate_daily_mean(day_start):
|
189 |
+
daily_collection = collection.filter(ee.Filter.eq('day_start', day_start))
|
190 |
+
daily_mean = daily_collection.mean()
|
191 |
+
return daily_mean.set('day_start', day_start)
|
192 |
+
daily_images = ee.List(grouped_by_day.map(calculate_daily_mean))
|
193 |
+
return ee.ImageCollection(daily_images)
|
194 |
+
|
195 |
+
def aggregate_data_weekly(collection, start_date_str, end_date_str):
|
196 |
+
start_date = ee.Date(start_date_str)
|
197 |
+
end_date = ee.Date(end_date_str)
|
198 |
+
days_diff = end_date.difference(start_date, 'day')
|
199 |
+
num_weeks = days_diff.divide(7).ceil().getInfo()
|
200 |
+
weekly_images = []
|
201 |
+
for week in range(num_weeks):
|
202 |
+
week_start = start_date.advance(week * 7, 'day')
|
203 |
+
week_end = week_start.advance(7, 'day')
|
204 |
+
weekly_collection = collection.filterDate(week_start, week_end)
|
205 |
+
if weekly_collection.size().getInfo() > 0:
|
206 |
+
weekly_mean = weekly_collection.mean()
|
207 |
+
weekly_mean = weekly_mean.set('week_start', week_start.format('YYYY-MM-dd'))
|
208 |
+
weekly_images.append(weekly_mean)
|
209 |
+
return ee.ImageCollection.fromImages(weekly_images)
|
210 |
+
|
211 |
+
def aggregate_data_monthly(collection, start_date, end_date):
|
212 |
+
collection = collection.filterDate(start_date, end_date)
|
213 |
+
collection = collection.map(lambda image: image.set('month', ee.Date(image.get('system:time_start')).format('YYYY-MM')))
|
214 |
+
grouped_by_month = collection.aggregate_array('month').distinct()
|
215 |
+
def calculate_monthly_mean(month):
|
216 |
+
monthly_collection = collection.filter(ee.Filter.eq('month', month))
|
217 |
+
monthly_mean = monthly_collection.mean()
|
218 |
+
return monthly_mean.set('month', month)
|
219 |
+
monthly_images = ee.List(grouped_by_month.map(calculate_monthly_mean))
|
220 |
+
return ee.ImageCollection(monthly_images)
|
221 |
+
|
222 |
+
def aggregate_data_yearly(collection):
|
223 |
+
collection = collection.map(lambda image: image.set('year', ee.Date(image.get('system:time_start')).format('YYYY')))
|
224 |
+
grouped_by_year = collection.aggregate_array('year').distinct()
|
225 |
+
def calculate_yearly_mean(year):
|
226 |
+
yearly_collection = collection.filter(ee.Filter.eq('year', year))
|
227 |
+
yearly_mean = yearly_collection.mean()
|
228 |
+
return yearly_mean.set('year', year)
|
229 |
+
yearly_images = ee.List(grouped_by_year.map(calculate_yearly_mean))
|
230 |
+
return ee.ImageCollection(yearly_images)
|
231 |
+
|
232 |
# Cloud percentage calculation
|
233 |
def calculate_cloud_percentage(image, cloud_band='QA60'):
|
234 |
qa60 = image.select(cloud_band)
|
|
|
260 |
cloud_mask = opaque_clouds.Or(cirrus_clouds)
|
261 |
clear_pixels = cloud_mask.Not()
|
262 |
return image.updateMask(clear_pixels)
|
263 |
+
|
264 |
if pixel_cloud_threshold > 0:
|
265 |
return collection.map(mask_cloudy_pixels)
|
266 |
return collection
|
|
|
290 |
roi = roi.buffer(-30).bounds()
|
291 |
except ValueError:
|
292 |
return None
|
293 |
+
|
294 |
# Filter collection by date and area first
|
295 |
+
# Apply spatial filtering
|
296 |
collection = ee.ImageCollection(dataset_id) \
|
297 |
.filterDate(ee.Date(start_date_str), ee.Date(end_date_str)) \
|
298 |
.filterBounds(roi)
|
299 |
+
|
300 |
+
# Apply cloud filtering if applicable
|
301 |
if pixel_cloud_threshold > 0:
|
302 |
collection = preprocess_collection(collection, pixel_cloud_threshold)
|
303 |
st.write(f"After cloud masking: {collection.size().getInfo()} images")
|
304 |
+
|
305 |
+
st.write(f"After initial filtering: {collection.size().getInfo()} images")
|
306 |
+
|
307 |
if aggregation_period.lower() == 'custom (start date to end date)':
|
308 |
collection = aggregate_data_custom(collection)
|
309 |
elif aggregation_period.lower() == 'daily':
|
|
|
314 |
collection = aggregate_data_monthly(collection, start_date_str, end_date_str)
|
315 |
elif aggregation_period.lower() == 'yearly':
|
316 |
collection = aggregate_data_yearly(collection)
|
317 |
+
|
318 |
image_list = collection.toList(collection.size())
|
319 |
processed_weeks = set()
|
320 |
aggregated_results = []
|
|
|
345 |
timestamp = image.get('year')
|
346 |
period_label = 'Year'
|
347 |
date = ee.Date(timestamp).format('YYYY').getInfo()
|
348 |
+
|
349 |
index_image = calculate_custom_formula(image, roi, selected_bands, custom_formula, reducer_choice, dataset_id, user_scale=user_scale)
|
350 |
try:
|
351 |
index_value = index_image.reduceRegion(
|
|
|
370 |
st.error(f"Error retrieving value for {location_name}: {e}")
|
371 |
return aggregated_results
|
372 |
|
373 |
+
# Process aggregation
|
374 |
# Process aggregation
|
375 |
def process_aggregation(locations_df, start_date_str, end_date_str, dataset_id, selected_bands, reducer_choice, shape_type, aggregation_period, original_lat_col, original_lon_col, custom_formula="", kernel_size=None, include_boundary=None, tile_cloud_threshold=0, pixel_cloud_threshold=0, user_scale=None):
|
376 |
aggregated_results = []
|
|
|
378 |
progress_bar = st.progress(0)
|
379 |
progress_text = st.empty()
|
380 |
start_time = time.time()
|
381 |
+
|
382 |
+
# Fetch the original collection size
|
383 |
raw_collection = ee.ImageCollection(dataset_id) \
|
384 |
.filterDate(ee.Date(start_date_str), ee.Date(end_date_str))
|
|
|
|
|
385 |
st.write(f"Original Collection Size: {raw_collection.size().getInfo()}")
|
386 |
|
387 |
+
# Apply cloud filtering globally if applicable
|
|
|
|
|
|
|
|
|
|
|
388 |
if pixel_cloud_threshold > 0:
|
389 |
raw_collection = preprocess_collection(raw_collection, pixel_cloud_threshold)
|
390 |
st.write(f"Filtered Collection Size (After Cloud Masking): {raw_collection.size().getInfo()}")
|
391 |
|
392 |
+
# Use ThreadPoolExecutor to process each geometry
|
393 |
with ThreadPoolExecutor(max_workers=10) as executor:
|
394 |
futures = []
|
395 |
for idx, row in locations_df.iterrows():
|
|
|
411 |
user_scale=user_scale
|
412 |
)
|
413 |
futures.append(future)
|
414 |
+
|
415 |
completed = 0
|
416 |
for future in as_completed(futures):
|
417 |
result = future.result()
|
|
|
421 |
progress_percentage = completed / total_steps
|
422 |
progress_bar.progress(progress_percentage)
|
423 |
progress_text.markdown(f"Processing: {int(progress_percentage * 100)}%")
|
424 |
+
|
425 |
end_time = time.time()
|
426 |
processing_time = end_time - start_time
|
427 |
+
|
428 |
if aggregated_results:
|
429 |
result_df = pd.DataFrame(aggregated_results)
|
430 |
if aggregation_period.lower() == 'custom (start date to end date)':
|
|
|
442 |
else:
|
443 |
return result_df.to_dict(orient='records'), processing_time
|
444 |
return [], processing_time
|
445 |
+
|
446 |
+
#streamlit logic
|
447 |
st.markdown("<h5>Image Collection</h5>", unsafe_allow_html=True)
|
448 |
imagery_base = st.selectbox("Select Imagery Base", ["Sentinel", "Landsat", "MODIS", "VIIRS", "Custom Input"], index=0)
|
449 |
data = {}
|
|
|
506 |
if not data:
|
507 |
st.error("No valid dataset available. Please check your inputs.")
|
508 |
st.stop()
|
509 |
+
|
510 |
st.markdown("<hr><h5><b>{}</b></h5>".format(imagery_base), unsafe_allow_html=True)
|
511 |
main_selection = st.selectbox(f"Select {imagery_base} Dataset Category", list(data.keys()))
|
512 |
sub_selection = None
|
|
|
526 |
st.write(f"Default Scale for Selected Dataset: {default_scale} meters")
|
527 |
except Exception as e:
|
528 |
st.error(f"Error fetching default scale: {str(e)}")
|
529 |
+
|
530 |
st.markdown("<hr><h5><b>Earth Engine Index Calculator</b></h5>", unsafe_allow_html=True)
|
531 |
if main_selection and sub_selection:
|
532 |
dataset_bands = data[main_selection]["bands"].get(sub_selection, [])
|
533 |
st.write(f"Available Bands for {sub_options[sub_selection]}: {', '.join(dataset_bands)}")
|
534 |
+
|
535 |
+
|
536 |
# Fetch nominal scales for all bands in the selected dataset
|
537 |
if dataset_id:
|
538 |
try:
|
|
|
540 |
collection = ee.ImageCollection(dataset_id)
|
541 |
first_image = collection.first()
|
542 |
band_names = first_image.bandNames().getInfo()
|
543 |
+
|
544 |
# Extract scales for all bands
|
545 |
band_scales = []
|
546 |
for band in band_names:
|
547 |
band_scale = first_image.select(band).projection().nominalScale().getInfo()
|
548 |
band_scales.append(band_scale)
|
549 |
+
|
550 |
# Identify unique scales using np.unique
|
551 |
unique_scales = np.unique(band_scales)
|
552 |
+
|
553 |
# Display the unique scales to the user
|
554 |
st.write(f"Nominal Scales for Bands: {band_scales}")
|
555 |
st.write(f"Unique Scales in Dataset: {unique_scales}")
|
556 |
+
|
557 |
# If there are multiple unique scales, allow the user to choose one
|
558 |
if len(unique_scales) > 1:
|
559 |
selected_scale = st.selectbox(
|
|
|
566 |
else:
|
567 |
default_scale = unique_scales[0]
|
568 |
st.write(f"Default Scale for Dataset: {default_scale} meters")
|
569 |
+
|
570 |
except Exception as e:
|
571 |
st.error(f"Error fetching band scales: {str(e)}")
|
572 |
default_scale = 30 # Fallback to 30 meters if an error occurs
|
573 |
+
|
574 |
selected_bands = st.multiselect(
|
575 |
"Select 1 or 2 Bands for Calculation",
|
576 |
options=dataset_bands,
|
|
|
609 |
st.warning("Please enter a custom formula to proceed.")
|
610 |
st.stop()
|
611 |
st.write(f"Custom Formula: {custom_formula}")
|
612 |
+
|
613 |
reducer_choice = st.selectbox(
|
614 |
"Select Reducer (e.g, mean , sum , median , min , max , count)",
|
615 |
['mean', 'sum', 'median', 'min', 'max', 'count'],
|
616 |
index=0
|
617 |
)
|
618 |
+
|
619 |
start_date = st.date_input("Start Date", value=pd.to_datetime('2024-11-01'))
|
620 |
end_date = st.date_input("End Date", value=pd.to_datetime('2024-12-01'))
|
621 |
start_date_str = start_date.strftime('%Y-%m-%d')
|
622 |
end_date_str = end_date.strftime('%Y-%m-%d')
|
623 |
+
|
624 |
if imagery_base == "Sentinel" and "Sentinel-2" in sub_options[sub_selection]:
|
625 |
st.markdown("<h5>Cloud Filtering</h5>", unsafe_allow_html=True)
|
626 |
pixel_cloud_threshold = st.slider(
|
|
|
631 |
step=5,
|
632 |
help="Individual pixels with cloud coverage exceeding this threshold will be masked."
|
633 |
)
|
634 |
+
|
635 |
aggregation_period = st.selectbox(
|
636 |
"Select Aggregation Period (e.g, Custom(Start Date to End Date) , Daily , Weekly , Monthly , Yearly)",
|
637 |
["Custom (Start Date to End Date)", "Daily", "Weekly", "Monthly", "Yearly"],
|
638 |
index=0
|
639 |
)
|
640 |
+
|
641 |
shape_type = st.selectbox("Do you want to process 'Point' or 'Polygon' data?", ["Point", "Polygon"])
|
642 |
kernel_size = None
|
643 |
include_boundary = None
|
644 |
+
|
645 |
if shape_type.lower() == "point":
|
646 |
kernel_size = st.selectbox(
|
647 |
"Select Calculation Area(e.g, Point , 3x3 Kernel , 5x5 Kernel)",
|
|
|
655 |
value=True,
|
656 |
help="Check to include pixels on the polygon boundary; uncheck to exclude them."
|
657 |
)
|
658 |
+
|
659 |
# st.markdown("<h5>Calculation Scale</h5>", unsafe_allow_html=True)
|
660 |
# default_scale = ee.ImageCollection(dataset_id).first().select(0).projection().nominalScale().getInfo()
|
661 |
# user_scale = st.number_input(
|
|
|
664 |
# value=float(default_scale),
|
665 |
# help=f"Default scale for this dataset is {default_scale} meters. Adjust if needed."
|
666 |
# )
|
667 |
+
|
668 |
st.markdown("<h5>Calculation Scale</h5>", unsafe_allow_html=True)
|
669 |
user_scale = st.number_input(
|
670 |
"Enter Calculation Scale (meters) [Leave blank to use dataset's default scale]",
|
|
|
672 |
value=float(default_scale),
|
673 |
help=f"Default scale for this dataset is {default_scale} meters. Adjust if needed."
|
674 |
)
|
675 |
+
|
676 |
file_upload = st.file_uploader(f"Upload your {shape_type} data (CSV, GeoJSON, KML)", type=["csv", "geojson", "kml"])
|
677 |
locations_df = pd.DataFrame()
|
678 |
original_lat_col = None
|
679 |
original_lon_col = None
|
680 |
+
|
681 |
if file_upload is not None:
|
682 |
if shape_type.lower() == "point":
|
683 |
if file_upload.name.endswith('.csv'):
|
|
|
792 |
m.add_gdf(gdf=gdf, layer_name=row.get('name', 'Unnamed Polygon'))
|
793 |
st.write("Map of Uploaded Polygons:")
|
794 |
m.to_streamlit()
|
795 |
+
|
796 |
if st.button(f"Calculate {custom_formula}"):
|
797 |
if not locations_df.empty:
|
798 |
with st.spinner("Processing Data..."):
|