Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -1,4 +1,3 @@
|
|
1 |
-
|
2 |
import streamlit as st
|
3 |
import json
|
4 |
import ee
|
@@ -118,7 +117,6 @@ def calculate_custom_formula(image, geometry, selected_bands, custom_formula, re
|
|
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,7 +130,6 @@ def calculate_custom_formula(image, geometry, selected_bands, custom_formula, re
|
|
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,13 +140,11 @@ def calculate_custom_formula(image, geometry, selected_bands, custom_formula, re
|
|
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,68 +162,6 @@ def calculate_custom_formula(image, geometry, selected_bands, custom_formula, re
|
|
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,7 +193,6 @@ def preprocess_collection(collection, pixel_cloud_threshold):
|
|
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,20 +222,15 @@ def process_single_geometry(row, start_date_str, end_date_str, dataset_id, selec
|
|
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
|
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,7 +241,6 @@ def process_single_geometry(row, start_date_str, end_date_str, dataset_id, selec
|
|
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,7 +271,6 @@ def process_single_geometry(row, start_date_str, end_date_str, dataset_id, selec
|
|
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(
|
@@ -377,40 +302,22 @@ def process_aggregation(locations_df, start_date_str, end_date_str, dataset_id,
|
|
377 |
progress_bar = st.progress(0)
|
378 |
progress_text = st.empty()
|
379 |
start_time = time.time()
|
|
|
|
|
380 |
|
|
|
|
|
|
|
381 |
# Apply spatial filtering
|
382 |
if roi is not None:
|
383 |
-
raw_collection =
|
384 |
-
|
385 |
-
|
386 |
-
|
387 |
-
raw_collection = ee.ImageCollection(dataset_id) \
|
388 |
-
.filterDate(ee.Date(start_date_str), ee.Date(end_date_str))
|
389 |
-
|
390 |
-
st.write(f"Original Collection Size: {raw_collection.size().getInfo()}")
|
391 |
-
st.write(f"Original Collection Size: {ee.ImageCollection(dataset_id).filterDate(ee.Date(start_date_str), ee.Date(end_date_str)).size().getInfo()}")
|
392 |
-
st.write(f"Filtered Collection Size (After Spatial Filtering): {raw_collection.size().getInfo()}")
|
393 |
-
|
394 |
if pixel_cloud_threshold > 0:
|
395 |
raw_collection = preprocess_collection(raw_collection, pixel_cloud_threshold)
|
396 |
st.write(f"Filtered Collection Size (After Cloud Masking): {raw_collection.size().getInfo()}")
|
397 |
-
|
398 |
-
# if tile_cloud_threshold > 0 or pixel_cloud_threshold > 0:
|
399 |
-
# raw_collection = preprocess_collection(raw_collection, pixel_cloud_threshold)
|
400 |
-
# st.write(f"Preprocessed Collection Size: {raw_collection.size().getInfo()}")
|
401 |
-
# Apply cloud filtering
|
402 |
-
if imagery_base == "Sentinel" and "Sentinel-2" in sub_options[sub_selection]:
|
403 |
-
pixel_cloud_threshold = st.slider(
|
404 |
-
"Select Maximum Pixel-Based Cloud Coverage Threshold (%)",
|
405 |
-
min_value=0,
|
406 |
-
max_value=100,
|
407 |
-
value=5,
|
408 |
-
step=5,
|
409 |
-
help="Individual pixels with cloud coverage exceeding this threshold will be masked."
|
410 |
-
)
|
411 |
-
raw_collection = preprocess_collection(raw_collection, pixel_cloud_threshold)
|
412 |
-
st.write(f"Filtered Collection Size (After Cloud Masking): {raw_collection.size().getInfo()}")
|
413 |
-
|
414 |
with ThreadPoolExecutor(max_workers=10) as executor:
|
415 |
futures = []
|
416 |
for idx, row in locations_df.iterrows():
|
@@ -441,10 +348,8 @@ def process_aggregation(locations_df, start_date_str, end_date_str, dataset_id,
|
|
441 |
progress_percentage = completed / total_steps
|
442 |
progress_bar.progress(progress_percentage)
|
443 |
progress_text.markdown(f"Processing: {int(progress_percentage * 100)}%")
|
444 |
-
|
445 |
end_time = time.time()
|
446 |
processing_time = end_time - start_time
|
447 |
-
|
448 |
if aggregated_results:
|
449 |
result_df = pd.DataFrame(aggregated_results)
|
450 |
if aggregation_period.lower() == 'custom (start date to end date)':
|
@@ -526,7 +431,6 @@ elif imagery_base == "Custom Input":
|
|
526 |
if not data:
|
527 |
st.error("No valid dataset available. Please check your inputs.")
|
528 |
st.stop()
|
529 |
-
|
530 |
st.markdown("<hr><h5><b>{}</b></h5>".format(imagery_base), unsafe_allow_html=True)
|
531 |
main_selection = st.selectbox(f"Select {imagery_base} Dataset Category", list(data.keys()))
|
532 |
sub_selection = None
|
@@ -546,13 +450,10 @@ if main_selection:
|
|
546 |
st.write(f"Default Scale for Selected Dataset: {default_scale} meters")
|
547 |
except Exception as e:
|
548 |
st.error(f"Error fetching default scale: {str(e)}")
|
549 |
-
|
550 |
st.markdown("<hr><h5><b>Earth Engine Index Calculator</b></h5>", unsafe_allow_html=True)
|
551 |
if main_selection and sub_selection:
|
552 |
dataset_bands = data[main_selection]["bands"].get(sub_selection, [])
|
553 |
st.write(f"Available Bands for {sub_options[sub_selection]}: {', '.join(dataset_bands)}")
|
554 |
-
|
555 |
-
|
556 |
# Fetch nominal scales for all bands in the selected dataset
|
557 |
if dataset_id:
|
558 |
try:
|
@@ -560,20 +461,16 @@ if main_selection and sub_selection:
|
|
560 |
collection = ee.ImageCollection(dataset_id)
|
561 |
first_image = collection.first()
|
562 |
band_names = first_image.bandNames().getInfo()
|
563 |
-
|
564 |
# Extract scales for all bands
|
565 |
band_scales = []
|
566 |
for band in band_names:
|
567 |
band_scale = first_image.select(band).projection().nominalScale().getInfo()
|
568 |
band_scales.append(band_scale)
|
569 |
-
|
570 |
# Identify unique scales using np.unique
|
571 |
unique_scales = np.unique(band_scales)
|
572 |
-
|
573 |
# Display the unique scales to the user
|
574 |
st.write(f"Nominal Scales for Bands: {band_scales}")
|
575 |
st.write(f"Unique Scales in Dataset: {unique_scales}")
|
576 |
-
|
577 |
# If there are multiple unique scales, allow the user to choose one
|
578 |
if len(unique_scales) > 1:
|
579 |
selected_scale = st.selectbox(
|
@@ -586,11 +483,9 @@ if main_selection and sub_selection:
|
|
586 |
else:
|
587 |
default_scale = unique_scales[0]
|
588 |
st.write(f"Default Scale for Dataset: {default_scale} meters")
|
589 |
-
|
590 |
except Exception as e:
|
591 |
st.error(f"Error fetching band scales: {str(e)}")
|
592 |
default_scale = 30 # Fallback to 30 meters if an error occurs
|
593 |
-
|
594 |
selected_bands = st.multiselect(
|
595 |
"Select 1 or 2 Bands for Calculation",
|
596 |
options=dataset_bands,
|
@@ -629,18 +524,15 @@ if main_selection and sub_selection:
|
|
629 |
st.warning("Please enter a custom formula to proceed.")
|
630 |
st.stop()
|
631 |
st.write(f"Custom Formula: {custom_formula}")
|
632 |
-
|
633 |
reducer_choice = st.selectbox(
|
634 |
"Select Reducer (e.g, mean , sum , median , min , max , count)",
|
635 |
['mean', 'sum', 'median', 'min', 'max', 'count'],
|
636 |
index=0
|
637 |
)
|
638 |
-
|
639 |
start_date = st.date_input("Start Date", value=pd.to_datetime('2024-11-01'))
|
640 |
end_date = st.date_input("End Date", value=pd.to_datetime('2024-12-01'))
|
641 |
start_date_str = start_date.strftime('%Y-%m-%d')
|
642 |
end_date_str = end_date.strftime('%Y-%m-%d')
|
643 |
-
|
644 |
if imagery_base == "Sentinel" and "Sentinel-2" in sub_options[sub_selection]:
|
645 |
st.markdown("<h5>Cloud Filtering</h5>", unsafe_allow_html=True)
|
646 |
pixel_cloud_threshold = st.slider(
|
@@ -651,17 +543,14 @@ if imagery_base == "Sentinel" and "Sentinel-2" in sub_options[sub_selection]:
|
|
651 |
step=5,
|
652 |
help="Individual pixels with cloud coverage exceeding this threshold will be masked."
|
653 |
)
|
654 |
-
|
655 |
aggregation_period = st.selectbox(
|
656 |
"Select Aggregation Period (e.g, Custom(Start Date to End Date) , Daily , Weekly , Monthly , Yearly)",
|
657 |
["Custom (Start Date to End Date)", "Daily", "Weekly", "Monthly", "Yearly"],
|
658 |
index=0
|
659 |
)
|
660 |
-
|
661 |
shape_type = st.selectbox("Do you want to process 'Point' or 'Polygon' data?", ["Point", "Polygon"])
|
662 |
kernel_size = None
|
663 |
include_boundary = None
|
664 |
-
|
665 |
if shape_type.lower() == "point":
|
666 |
kernel_size = st.selectbox(
|
667 |
"Select Calculation Area(e.g, Point , 3x3 Kernel , 5x5 Kernel)",
|
@@ -675,7 +564,6 @@ elif shape_type.lower() == "polygon":
|
|
675 |
value=True,
|
676 |
help="Check to include pixels on the polygon boundary; uncheck to exclude them."
|
677 |
)
|
678 |
-
|
679 |
# st.markdown("<h5>Calculation Scale</h5>", unsafe_allow_html=True)
|
680 |
# default_scale = ee.ImageCollection(dataset_id).first().select(0).projection().nominalScale().getInfo()
|
681 |
# user_scale = st.number_input(
|
@@ -684,7 +572,6 @@ elif shape_type.lower() == "polygon":
|
|
684 |
# value=float(default_scale),
|
685 |
# help=f"Default scale for this dataset is {default_scale} meters. Adjust if needed."
|
686 |
# )
|
687 |
-
|
688 |
st.markdown("<h5>Calculation Scale</h5>", unsafe_allow_html=True)
|
689 |
user_scale = st.number_input(
|
690 |
"Enter Calculation Scale (meters) [Leave blank to use dataset's default scale]",
|
@@ -692,12 +579,10 @@ user_scale = st.number_input(
|
|
692 |
value=float(default_scale),
|
693 |
help=f"Default scale for this dataset is {default_scale} meters. Adjust if needed."
|
694 |
)
|
695 |
-
|
696 |
file_upload = st.file_uploader(f"Upload your {shape_type} data (CSV, GeoJSON, KML)", type=["csv", "geojson", "kml"])
|
697 |
locations_df = pd.DataFrame()
|
698 |
original_lat_col = None
|
699 |
original_lon_col = None
|
700 |
-
|
701 |
if file_upload is not None:
|
702 |
if shape_type.lower() == "point":
|
703 |
if file_upload.name.endswith('.csv'):
|
@@ -812,7 +697,6 @@ if file_upload is not None:
|
|
812 |
m.add_gdf(gdf=gdf, layer_name=row.get('name', 'Unnamed Polygon'))
|
813 |
st.write("Map of Uploaded Polygons:")
|
814 |
m.to_streamlit()
|
815 |
-
|
816 |
if st.button(f"Calculate {custom_formula}"):
|
817 |
if not locations_df.empty:
|
818 |
with st.spinner("Processing Data..."):
|
|
|
|
|
1 |
import streamlit as st
|
2 |
import json
|
3 |
import ee
|
|
|
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 |
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 |
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 |
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 |
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 |
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 |
+
st.write(f"After initial filtering: {collection.size().getInfo()} images")
|
230 |
+
# Apply pixel cloud masking if threshold > 0
|
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 |
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 |
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(
|
|
|
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 |
# Apply spatial filtering
|
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():
|
|
|
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)':
|
|
|
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 |
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 |
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 |
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 |
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 |
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 |
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 |
# 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 |
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 |
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..."):
|