SATRANG / app.py
YashMK89's picture
update app.py
c16c7db verified
raw
history blame
4.2 kB
import streamlit as st
import json
import ee
import geemap
import os
st.set_page_config(layout="wide")
m = st.markdown(
"""
<style>
div.stButton > button:first-child {
background-color: #006400;
color:#ffffff;
}
</style>""",
unsafe_allow_html=True,
)
# Authenticate and initialize Earth Engine
earthengine_credentials = os.environ.get("EE_Authentication")
# Initialize Earth Engine with the secret credentials
os.makedirs(os.path.expanduser("~/.config/earthengine/"), exist_ok=True)
with open(os.path.expanduser("~/.config/earthengine/credentials"), "w") as f:
f.write(earthengine_credentials)
ee.Initialize(project='ee-yashsacisro24')
# Load JSON data for Sentinel dataset options
with open("sentinel_datasets.json") as f:
data = json.load(f)
# Define index calculation functions
def calculate_ndvi(image):
"""Calculate NDVI."""
return image.normalizedDifference(['B5', 'B4']).rename('NDVI')
def calculate_ndwi(image):
"""Calculate NDWI."""
return image.normalizedDifference(['B3', 'B5']).rename('NDWI')
def calculate_avg_no2(image):
"""Calculate average NO2."""
return image.select('NO2').reduceRegion(
reducer=ee.Reducer.mean(),
geometry=image.geometry(),
scale=1000
).get('NO2')
def calculate_custom_formula(image, formula):
"""Apply a custom formula to the image."""
return image.expression(formula).rename('Custom Index')
# Streamlit UI - Title
st.title("Sentinel Dataset Selector and Earth Engine Index Calculator")
# Sentinel Dataset Selector Section
st.header("Sentinel Dataset Selector")
# Step 1: Select main dataset category
main_selection = st.selectbox("Select Sentinel Dataset Category", list(data.keys()))
# Step 2: Display sub-options based on main selection
sub_selection = None
if main_selection:
sub_options = data[main_selection]["sub_options"]
sub_selection = st.selectbox("Select Specific Dataset ID", list(sub_options.keys()))
# # Step 3: Display band selection based on sub-selection with max 3 selections
# selected_bands = []
# if sub_selection:
# bands = sub_options[sub_selection]
# st.write("Select up to 3 bands:")
# # Display bands in a side-by-side layout with three columns
# cols = st.columns(3)
# for i, band in enumerate(bands):
# with cols[i % 3]:
# if st.checkbox(band, key=band):
# selected_bands.append(band)
# # Limit selection to a maximum of 3 bands
# if len(selected_bands) == 3:
# break
# # Show selected bands
# st.write("Selected Bands:", selected_bands)
# Earth Engine Index Calculator Section
st.header("Earth Engine Index Calculator")
# Step 4: Select Index Calculation Option
index_choice = st.selectbox("Select an Index or Enter Custom Formula", ['NDVI', 'NDWI', 'Average NO₂', 'Custom Formula'])
# Step 5: Custom Formula Input
custom_formula = ""
if index_choice == 'Custom Formula':
custom_formula = st.text_input("Enter Custom Formula (e.g., 'B5 - B4 / B5 + B4')")
# Step 6: Calculate and Display Results based on selected index or formula
if sub_selection and st.button("Calculate Index"):
# Use the selected dataset from the main and sub-selection as an ImageCollection
collection = ee.ImageCollection(sub_selection).filterDate('2020-01-01', '2020-1-31')
image = collection.first() # Using the first image in the collection as an example
result_image = None
if index_choice == 'NDVI':
result_image = calculate_ndvi(image)
elif index_choice == 'NDWI':
result_image = calculate_ndwi(image)
elif index_choice == 'Average NO₂':
result = calculate_avg_no2(image)
st.write("Average NO₂ Concentration:", result.getInfo())
elif index_choice == 'Custom Formula' and custom_formula:
result_image = calculate_custom_formula(image, custom_formula)
# If an index image is generated, add it to the map
if result_image:
Map = geemap.Map()
Map.centerObject(image, 10)
Map.addLayer(result_image, {}, index_choice)
Map.to_streamlit(height=600)