YashMK89 commited on
Commit
13769e5
·
verified ·
1 Parent(s): a19473c

update app.py

Browse files
Files changed (1) hide show
  1. app.py +56 -71
app.py CHANGED
@@ -26,96 +26,81 @@ with open(os.path.expanduser("~/.config/earthengine/credentials"), "w") as f:
26
 
27
  ee.Initialize(project='ee-yashsacisro24')
28
 
29
- # Load JSON data for Sentinel dataset options
30
  with open("sentinel_datasets.json") as f:
31
  data = json.load(f)
32
 
33
- # Define index calculation functions
34
- def calculate_ndvi(image):
35
- """Calculate NDVI."""
36
- return image.normalizedDifference(['B5', 'B4']).rename('NDVI')
37
-
38
- def calculate_ndwi(image):
39
- """Calculate NDWI."""
40
- return image.normalizedDifference(['B3', 'B5']).rename('NDWI')
41
-
42
- def calculate_avg_no2(image):
43
- """Calculate average NO2."""
44
- return image.select('NO2').reduceRegion(
45
- reducer=ee.Reducer.mean(),
46
- geometry=image.geometry(),
47
- scale=1000
48
- ).get('NO2')
49
-
50
- def calculate_custom_formula(image, formula):
51
- """Apply a custom formula to the image."""
52
- return image.expression(formula).rename('Custom Index')
53
-
54
- # Streamlit UI - Title
55
- st.title("Sentinel Dataset Selector and Earth Engine Index Calculator")
56
-
57
- # Sentinel Dataset Selector Section
58
- st.header("Sentinel Dataset Selector")
59
 
60
  # Step 1: Select main dataset category
61
  main_selection = st.selectbox("Select Sentinel Dataset Category", list(data.keys()))
62
 
63
  # Step 2: Display sub-options based on main selection
64
- sub_selection = None
65
  if main_selection:
66
  sub_options = data[main_selection]["sub_options"]
67
  sub_selection = st.selectbox("Select Specific Dataset ID", list(sub_options.keys()))
68
 
69
- # # Step 3: Display band selection based on sub-selection with max 3 selections
70
- # selected_bands = []
71
- # if sub_selection:
72
- # bands = sub_options[sub_selection]
73
- # st.write("Select up to 3 bands:")
74
-
75
- # # Display bands in a side-by-side layout with three columns
76
- # cols = st.columns(3)
77
- # for i, band in enumerate(bands):
78
- # with cols[i % 3]:
79
- # if st.checkbox(band, key=band):
80
- # selected_bands.append(band)
81
- # # Limit selection to a maximum of 3 bands
82
- # if len(selected_bands) == 3:
83
- # break
84
-
85
- # # Show selected bands
86
- # st.write("Selected Bands:", selected_bands)
87
 
88
  # Earth Engine Index Calculator Section
89
  st.header("Earth Engine Index Calculator")
90
 
91
- # Step 4: Select Index Calculation Option
92
  index_choice = st.selectbox("Select an Index or Enter Custom Formula", ['NDVI', 'NDWI', 'Average NO₂', 'Custom Formula'])
93
 
94
- # Step 5: Custom Formula Input
95
  custom_formula = ""
96
  if index_choice == 'Custom Formula':
97
  custom_formula = st.text_input("Enter Custom Formula (e.g., 'B5 - B4 / B5 + B4')")
98
 
99
- # Step 6: Calculate and Display Results based on selected index or formula
100
- if sub_selection and st.button("Calculate Index"):
101
- # Use the selected dataset from the main and sub-selection as an ImageCollection
102
- collection = ee.ImageCollection(data[main_selection]["sub_options"][sub_selection]).filterDate('2020-01-01', '2020-1-31')
103
- image = collection.first() # Using the first image in the collection as an example
104
-
105
- result_image = None
106
- if index_choice == 'NDVI':
107
- result_image = calculate_ndvi(image)
108
- elif index_choice == 'NDWI':
109
- result_image = calculate_ndwi(image)
110
- elif index_choice == 'Average NO₂':
111
- result = calculate_avg_no2(image)
112
- st.write("Average NO₂ Concentration:", result.getInfo())
113
- elif index_choice == 'Custom Formula' and custom_formula:
114
- result_image = calculate_custom_formula(image, custom_formula)
115
-
116
- # If an index image is generated, add it to the map
117
- if result_image:
118
- Map = geemap.Map()
119
- Map.centerObject(image, 10)
120
- Map.addLayer(result_image, {}, index_choice)
121
- Map.to_streamlit(height=600)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26
 
27
  ee.Initialize(project='ee-yashsacisro24')
28
 
29
+ # Load Sentinel dataset options from JSON file
30
  with open("sentinel_datasets.json") as f:
31
  data = json.load(f)
32
 
33
+ # Display title and dataset selection
34
+ st.title("Sentinel Dataset and Index Calculator")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35
 
36
  # Step 1: Select main dataset category
37
  main_selection = st.selectbox("Select Sentinel Dataset Category", list(data.keys()))
38
 
39
  # Step 2: Display sub-options based on main selection
 
40
  if main_selection:
41
  sub_options = data[main_selection]["sub_options"]
42
  sub_selection = st.selectbox("Select Specific Dataset ID", list(sub_options.keys()))
43
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44
 
45
  # Earth Engine Index Calculator Section
46
  st.header("Earth Engine Index Calculator")
47
 
48
+ # Step 4: Choose Index or Custom Formula
49
  index_choice = st.selectbox("Select an Index or Enter Custom Formula", ['NDVI', 'NDWI', 'Average NO₂', 'Custom Formula'])
50
 
51
+ # Step 5: Enter Custom Formula if selected
52
  custom_formula = ""
53
  if index_choice == 'Custom Formula':
54
  custom_formula = st.text_input("Enter Custom Formula (e.g., 'B5 - B4 / B5 + B4')")
55
 
56
+ # Define functions for index calculations
57
+ def calculate_ndvi(image):
58
+ return image.normalizedDifference(['B5', 'B4']).rename('NDVI')
59
+
60
+ def calculate_ndwi(image):
61
+ return image.normalizedDifference(['B3', 'B5']).rename('NDWI')
62
+
63
+ def calculate_avg_no2(image):
64
+ return image.select('NO2').reduceRegion(
65
+ reducer=ee.Reducer.mean(),
66
+ geometry=image.geometry(),
67
+ scale=1000
68
+ ).get('NO2')
69
+
70
+ def calculate_custom_formula(image, formula):
71
+ return image.expression(formula).rename('Custom Index')
72
+
73
+ # Step 6: Perform the calculation based on user choice
74
+ result_image = None
75
+ if st.button("Calculate Index"):
76
+ try:
77
+ # Load dataset based on user selection
78
+ dataset_id = sub_selection # Dataset ID from the JSON structure
79
+ collection = ee.ImageCollection(dataset_id).filterDate('2020-01-01', '2020-12-31')
80
+ image = collection.first() # Using the first image in the collection as an example
81
+
82
+ # Choose calculation based on user selection
83
+ if index_choice == 'NDVI':
84
+ result_image = calculate_ndvi(image)
85
+ elif index_choice == 'NDWI':
86
+ result_image = calculate_ndwi(image)
87
+ elif index_choice == 'Average NO₂':
88
+ result = calculate_avg_no2(image)
89
+ st.write("Average NO₂ Concentration:", result.getInfo())
90
+ elif index_choice == 'Custom Formula' and custom_formula:
91
+ result_image = calculate_custom_formula(image, custom_formula)
92
+
93
+ # Visualization Parameters for Index Layers
94
+ vis_params = {"min": 0, "max": 1, "palette": ["blue", "white", "green"]}
95
+
96
+ # If an index image is generated, add it to the map
97
+ if result_image:
98
+ Map = geemap.Map()
99
+ Map.setCenter(-100.0, 40.0, 4) # Example coordinates; adjust as needed
100
+ Map.addLayer(result_image, vis_params, index_choice)
101
+ Map.to_streamlit(height=600)
102
+ else:
103
+ st.warning("Result image not generated; check parameters.")
104
+
105
+ except ee.EEException as e:
106
+ st.error(f"Earth Engine Error: {e}")