Add Avg Index
Browse files
app.py
CHANGED
|
@@ -509,27 +509,27 @@ def calculate_indices(
|
|
| 509 |
traceback.print_exc()
|
| 510 |
return f"An error occurred during calculation: {e}", None, None, None
|
| 511 |
|
| 512 |
-
def get_histogram(index_name, image, geometry, bins):
|
| 513 |
-
|
| 514 |
-
|
| 515 |
-
|
| 516 |
-
|
| 517 |
-
|
| 518 |
-
|
| 519 |
-
|
| 520 |
-
|
| 521 |
-
|
| 522 |
-
|
| 523 |
-
|
| 524 |
-
|
| 525 |
-
|
| 526 |
-
|
| 527 |
-
|
| 528 |
-
|
| 529 |
-
|
| 530 |
-
|
| 531 |
-
|
| 532 |
-
|
| 533 |
|
| 534 |
def generate_comparison_maps(geometry_json, selected_index, selected_years, evi_vars, date_start_str, date_end_str, progress=gr.Progress()):
|
| 535 |
"""Generates side-by-side maps for a selected index and two selected years with a custom HTML legend."""
|
|
@@ -595,7 +595,21 @@ def generate_comparison_maps(geometry_json, selected_index, selected_years, evi_
|
|
| 595 |
|
| 596 |
if selected_index in ["NDVI", "RandomForest", "GujVDI", "CI", "EVI", "EVI2"]:
|
| 597 |
bins = [0, 0.2, 0.4, 0.6, 0.8, 1]
|
| 598 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 599 |
|
| 600 |
total_pix = np.sum(histogram)
|
| 601 |
formatted_histogram = ["0.00"] * len(histogram)
|
|
@@ -655,6 +669,7 @@ def generate_comparison_maps(geometry_json, selected_index, selected_years, evi_
|
|
| 655 |
|
| 656 |
return f"Comparison generated for {selected_years[0]} and {selected_years[1]}.", maps_html[0], maps_html[1]
|
| 657 |
|
|
|
|
| 658 |
# --- Gradio Interface ---
|
| 659 |
theme = gr.themes.Soft(primary_hue="teal", secondary_hue="orange").set(
|
| 660 |
background_fill_primary="white"
|
|
@@ -821,44 +836,86 @@ with gr.Blocks(theme=theme, title="Kamlan: KML Analyzer") as demo:
|
|
| 821 |
""")
|
| 822 |
|
| 823 |
def compute_index_histogram(file_url: str, index_name: str, start_date: str, end_date: str):
|
| 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 |
-
mosaic = collection.median()
|
| 850 |
|
| 851 |
-
|
| 852 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 853 |
|
| 854 |
-
|
| 855 |
-
|
| 856 |
-
|
| 857 |
-
|
| 858 |
-
|
| 859 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 860 |
|
| 861 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 862 |
|
| 863 |
|
| 864 |
# Register endpoints for multiple indices with date range
|
|
|
|
| 509 |
traceback.print_exc()
|
| 510 |
return f"An error occurred during calculation: {e}", None, None, None
|
| 511 |
|
| 512 |
+
# def get_histogram(index_name, image, geometry, bins):
|
| 513 |
+
# """Calculates the histogram for an image within a given geometry using GEE."""
|
| 514 |
+
# try:
|
| 515 |
+
# # Request histogram data from Earth Engine
|
| 516 |
+
# hist_info = image.reduceRegion(
|
| 517 |
+
# reducer=ee.Reducer.fixedHistogram(min=bins[0], max=bins[-1], steps=len(bins)-1),
|
| 518 |
+
# geometry=geometry,
|
| 519 |
+
# scale=10, # Scale in meters appropriate for Sentinel-2
|
| 520 |
+
# maxPixels=1e9
|
| 521 |
+
# ).get(index_name).getInfo()
|
| 522 |
+
|
| 523 |
+
# # Extract histogram counts
|
| 524 |
+
# if hist_info:
|
| 525 |
+
# histogram = [item[1] for item in hist_info]
|
| 526 |
+
# return np.array(histogram), bins
|
| 527 |
+
# else:
|
| 528 |
+
# # Return empty histogram if no data
|
| 529 |
+
# return np.array([0] * (len(bins) - 1)), bins
|
| 530 |
+
# except Exception as e:
|
| 531 |
+
# print(f"Could not compute histogram for {index_name}: {e}")
|
| 532 |
+
# return np.array([0] * (len(bins) - 1)), bins
|
| 533 |
|
| 534 |
def generate_comparison_maps(geometry_json, selected_index, selected_years, evi_vars, date_start_str, date_end_str, progress=gr.Progress()):
|
| 535 |
"""Generates side-by-side maps for a selected index and two selected years with a custom HTML legend."""
|
|
|
|
| 595 |
|
| 596 |
if selected_index in ["NDVI", "RandomForest", "GujVDI", "CI", "EVI", "EVI2"]:
|
| 597 |
bins = [0, 0.2, 0.4, 0.6, 0.8, 1]
|
| 598 |
+
# Calculate histogram directly
|
| 599 |
+
try:
|
| 600 |
+
hist_info = mosaic.select(selected_index).reduceRegion(
|
| 601 |
+
reducer=ee.Reducer.fixedHistogram(min=bins[0], max=bins[-1], steps=len(bins)-1),
|
| 602 |
+
geometry=ee_geometry,
|
| 603 |
+
scale=10,
|
| 604 |
+
maxPixels=1e9
|
| 605 |
+
).get(selected_index).getInfo()
|
| 606 |
+
|
| 607 |
+
if hist_info:
|
| 608 |
+
histogram = np.array([item[1] for item in hist_info])
|
| 609 |
+
else:
|
| 610 |
+
histogram = np.array([0] * (len(bins) - 1))
|
| 611 |
+
except Exception:
|
| 612 |
+
histogram = np.array([0] * (len(bins) - 1))
|
| 613 |
|
| 614 |
total_pix = np.sum(histogram)
|
| 615 |
formatted_histogram = ["0.00"] * len(histogram)
|
|
|
|
| 669 |
|
| 670 |
return f"Comparison generated for {selected_years[0]} and {selected_years[1]}.", maps_html[0], maps_html[1]
|
| 671 |
|
| 672 |
+
|
| 673 |
# --- Gradio Interface ---
|
| 674 |
theme = gr.themes.Soft(primary_hue="teal", secondary_hue="orange").set(
|
| 675 |
background_fill_primary="white"
|
|
|
|
| 836 |
""")
|
| 837 |
|
| 838 |
def compute_index_histogram(file_url: str, index_name: str, start_date: str, end_date: str):
|
| 839 |
+
"""
|
| 840 |
+
Computes average value and histogram percentage for a vegetation index
|
| 841 |
+
within a polygon and date range.
|
| 842 |
+
"""
|
| 843 |
+
try:
|
| 844 |
+
one_time_setup()
|
| 845 |
+
decoded_url = unquote(file_url)
|
| 846 |
+
gdf = get_gdf_from_url(decoded_url)
|
| 847 |
+
gdf = preprocess_gdf(gdf)
|
| 848 |
|
| 849 |
+
geometry_gdf = next((gdf.iloc[[i]] for i in range(len(gdf)) if is_valid_polygon(gdf.iloc[[i]])), None)
|
| 850 |
+
if geometry_gdf is None:
|
| 851 |
+
raise HTTPException(status_code=400, detail="No valid polygon found.")
|
| 852 |
|
| 853 |
+
ee_geometry = ee.Geometry(json.loads(geometry_gdf.to_crs(4326).to_json())['features'][0]['geometry'])
|
| 854 |
|
| 855 |
+
evi_vars = {'G': 2.5, 'C1': 6.0, 'C2': 7.5, 'L': 1.0, 'C': 2.4}
|
| 856 |
+
collection = (
|
| 857 |
+
ee.ImageCollection("COPERNICUS/S2_SR_HARMONIZED")
|
| 858 |
+
.filterDate(start_date, end_date)
|
| 859 |
+
.select(["B2", "B3", "B4", "B8"], ["Blue", "Green", "Red", "NIR"])
|
| 860 |
+
.map(lambda img: add_indices(img, 'NIR', 'Red', 'Blue', 'Green', evi_vars))
|
| 861 |
+
.filterBounds(ee_geometry)
|
| 862 |
+
)
|
| 863 |
|
| 864 |
+
if collection.size().getInfo() == 0:
|
| 865 |
+
raise HTTPException(status_code=404, detail="No imagery found for the polygon in given date range.")
|
| 866 |
|
| 867 |
+
mosaic = collection.median()
|
|
|
|
| 868 |
|
| 869 |
+
bins = [0.0, 0.2, 0.4, 0.6, 0.8, 1.0]
|
| 870 |
+
# Create a combined reducer for mean and histogram
|
| 871 |
+
combined_reducer = ee.Reducer.mean().combine(
|
| 872 |
+
reducer2=ee.Reducer.fixedHistogram(min=bins[0], max=bins[-1], steps=len(bins)-1),
|
| 873 |
+
sharedInputs=True
|
| 874 |
+
)
|
| 875 |
|
| 876 |
+
# Reduce the image in the region with the combined reducer
|
| 877 |
+
reduction_info = mosaic.select(index_name).reduceRegion(
|
| 878 |
+
reducer=combined_reducer,
|
| 879 |
+
geometry=ee_geometry,
|
| 880 |
+
scale=10,
|
| 881 |
+
maxPixels=1e9
|
| 882 |
+
).getInfo()
|
| 883 |
+
|
| 884 |
+
# Process the results
|
| 885 |
+
average_value = None
|
| 886 |
+
hist_result = {}
|
| 887 |
+
|
| 888 |
+
if reduction_info:
|
| 889 |
+
# Extract mean value
|
| 890 |
+
mean_val = reduction_info.get('mean')
|
| 891 |
+
average_value = round(mean_val, 4) if mean_val is not None else None
|
| 892 |
+
|
| 893 |
+
# Extract and process histogram
|
| 894 |
+
hist_info = reduction_info.get('histogram')
|
| 895 |
+
if hist_info:
|
| 896 |
+
histogram = np.array([item[1] for item in hist_info])
|
| 897 |
+
total = histogram.sum()
|
| 898 |
+
for i in range(len(bins) - 1):
|
| 899 |
+
label = f"{bins[i]}-{bins[i+1]}"
|
| 900 |
+
pct = (histogram[i] / total * 100) if total > 0 else 0
|
| 901 |
+
hist_result[label] = round(pct, 2)
|
| 902 |
+
else: # If histogram is empty, create a zeroed one
|
| 903 |
+
for i in range(len(bins) - 1):
|
| 904 |
+
label = f"{bins[i]}-{bins[i+1]}"
|
| 905 |
+
hist_result[label] = 0.0
|
| 906 |
+
|
| 907 |
+
# Combine into the final result object
|
| 908 |
+
final_result = {
|
| 909 |
+
"average_index_value": average_value,
|
| 910 |
+
"histogram_percentage": hist_result
|
| 911 |
+
}
|
| 912 |
|
| 913 |
+
return final_result
|
| 914 |
+
except HTTPException:
|
| 915 |
+
raise
|
| 916 |
+
except Exception as e:
|
| 917 |
+
# Handle other unexpected errors
|
| 918 |
+
raise HTTPException(status_code=500, detail=f"An unexpected error occurred: {e}")
|
| 919 |
|
| 920 |
|
| 921 |
# Register endpoints for multiple indices with date range
|