YashMK89 commited on
Commit
5dec096
·
verified ·
1 Parent(s): 80787f5

update app.py

Browse files
Files changed (1) hide show
  1. app.py +24 -39
app.py CHANGED
@@ -8,9 +8,10 @@ import pandas as pd
8
  import geopandas as gpd
9
  from shapely.geometry import Point
10
 
 
11
  st.set_page_config(layout="wide")
12
 
13
- # Custom styling for the button
14
  m = st.markdown(
15
  """
16
  <style>
@@ -25,7 +26,7 @@ m = st.markdown(
25
  # Authenticate and initialize Earth Engine
26
  earthengine_credentials = os.environ.get("EE_Authentication")
27
 
28
- # Initialize Earth Engine with the secret credentials
29
  os.makedirs(os.path.expanduser("~/.config/earthengine/"), exist_ok=True)
30
  with open(os.path.expanduser("~/.config/earthengine/credentials"), "w") as f:
31
  f.write(earthengine_credentials)
@@ -36,13 +37,12 @@ ee.Initialize(project='ee-yashsacisro24')
36
  with open("sentinel_datasets.json") as f:
37
  data = json.load(f)
38
 
39
- # Display title and dataset selection
40
  st.title("Sentinel Dataset and Index Calculator")
41
 
42
- # Step 1: Select main dataset category
43
  main_selection = st.selectbox("Select Sentinel Dataset Category", list(data.keys()))
44
 
45
- # Step 2: Display sub-options based on main selection
46
  if main_selection:
47
  sub_options = data[main_selection]["sub_options"]
48
  sub_selection = st.selectbox("Select Specific Dataset ID", list(sub_options.keys()))
@@ -50,93 +50,88 @@ if main_selection:
50
  # Earth Engine Index Calculator Section
51
  st.header("Earth Engine Index Calculator")
52
 
53
- # Step 3: Choose Index or Custom Formula
54
  index_choice = st.selectbox("Select an Index or Enter Custom Formula", ['NDVI', 'NDWI', 'Average NO₂', 'Custom Formula'])
55
 
56
- # Step 4: Enter Custom Formula if selected
57
  custom_formula = ""
58
  if index_choice == 'Custom Formula':
59
  custom_formula = st.text_input("Enter Custom Formula (e.g., 'B5 - B4 / B5 + B4')")
60
 
61
- # Step 5: Select Geometry Type (Point or Polygon)
62
  geometry_type = st.selectbox("Select Geometry Type", ['Point', 'Polygon'])
63
 
64
- # Step 6: File Upload Based on Geometry Type
65
  if geometry_type == 'Point':
66
  uploaded_file = st.file_uploader("Upload a CSV, GeoJSON, or KML file with Point Data", type=["csv", "geojson", "kml"])
67
  else:
68
  uploaded_file = st.file_uploader("Upload a GeoJSON or KML file with Polygon Data", type=["geojson", "kml"])
69
 
70
- # Function to get geometry points from uploaded file
71
  def get_user_points(uploaded_file):
72
  points = []
73
  if uploaded_file.name.endswith('.csv'):
74
- # Read CSV file
75
  df = pd.read_csv(uploaded_file)
76
  for _, row in df.iterrows():
77
  lat = row['latitude']
78
  lon = row['longitude']
79
  # Check for NaN values
80
  if pd.isna(lat) or pd.isna(lon):
81
- continue # Skip this point if latitude or longitude is NaN
82
- name = row.get('name', f"Location {len(points) + 1}") # Default name if not provided
83
  points.append({"geometry": ee.Geometry.Point([lon, lat]), "name": name})
84
-
85
  elif uploaded_file.name.endswith('.geojson'):
86
- # Read GeoJSON file
87
  geojson_data = json.load(uploaded_file)
88
  for feature in geojson_data['features']:
89
  lat, lon = feature['geometry']['coordinates']
90
  # Check for NaN values
91
  if lat is None or lon is None:
92
- continue # Skip this point if latitude or longitude is NaN
93
  name = feature.get('properties', {}).get('Name', f"Location {len(points) + 1}")
94
  points.append({"geometry": ee.Geometry.Point([lon, lat]), "name": name})
95
-
96
  elif uploaded_file.name.endswith('.kml'):
97
- # Read KML file
98
  gdf = gpd.read_file(uploaded_file)
99
  for _, row in gdf.iterrows():
100
  lat = row.geometry.y
101
  lon = row.geometry.x
102
  # Check for NaN values
103
  if pd.isna(lat) or pd.isna(lon):
104
- continue # Skip this point if latitude or longitude is NaN
105
  name = row.get('name', f"Location {len(points) + 1}")
106
  points.append({"geometry": ee.Geometry.Point([lon, lat]), "name": name})
107
-
108
  return points
109
 
110
- # Function to get geometry polygons from uploaded file
111
  def get_user_polygons(uploaded_file):
112
  polygons = []
113
  if uploaded_file.name.endswith('.geojson'):
114
- # Read GeoJSON file
115
  geojson_data = json.load(uploaded_file)
116
  for feature in geojson_data['features']:
117
  if feature['geometry']['type'] in ['Polygon', 'MultiPolygon']:
118
  geom = ee.Geometry(feature['geometry'])
119
  name = feature.get('properties', {}).get('Name', f"Polygon {len(polygons) + 1}")
120
  polygons.append({"geometry": geom, "name": name})
121
-
122
  elif uploaded_file.name.endswith('.kml'):
123
- # Read KML file
124
  gdf = gpd.read_file(uploaded_file)
125
  for _, row in gdf.iterrows():
126
  geom = row.geometry
127
  if geom.geom_type in ['Polygon', 'MultiPolygon']:
128
  name = row.get('name', f"Polygon {len(polygons) + 1}")
129
  polygons.append({"geometry": ee.Geometry(geom), "name": name})
130
-
131
  return polygons
132
 
133
- # Step 7: Parse the file and get geometries (points or polygons)
134
  if uploaded_file is not None:
135
  if geometry_type == 'Point':
136
  points = get_user_points(uploaded_file)
137
  if points:
138
  st.write(f"Loaded {len(points)} points.")
139
- points_df = pd.DataFrame([{'Latitude': point['geometry'].coordinates().get(0),
140
  'Longitude': point['geometry'].coordinates().get(1),
141
  'Name': point['name']} for point in points])
142
  st.write("Points from file:", points_df)
@@ -154,17 +149,7 @@ if uploaded_file is not None:
154
  else:
155
  geometries = []
156
 
157
- # Visualization for Points
158
- if len(geometries) > 0 and geometry_type == 'Point':
159
- # Show points on map using geemap
160
- Map = geemap.Map()
161
- Map.setCenter(-100.0, 40.0, 4) # Adjusted for example
162
- for point in points:
163
- Map.add_marker(location=[point['geometry'].coordinates().get(1), point['geometry'].coordinates().get(0)],
164
- popup=point['name'])
165
- Map.to_streamlit(height=600)
166
-
167
- # Define functions for index calculations
168
  def calculate_ndvi(image, geometry):
169
  return image.normalizedDifference(['B5', 'B4']).rename('NDVI').reduceRegion(
170
  reducer=ee.Reducer.mean(),
@@ -193,7 +178,7 @@ def calculate_custom_formula(image, geometry, formula):
193
  scale=30
194
  )
195
 
196
- # Step 8: Perform the calculation based on user choice
197
  if st.button("Calculate Index"):
198
  if geometries:
199
  try:
 
8
  import geopandas as gpd
9
  from shapely.geometry import Point
10
 
11
+ # Set the page layout
12
  st.set_page_config(layout="wide")
13
 
14
+ # Custom button styling
15
  m = st.markdown(
16
  """
17
  <style>
 
26
  # Authenticate and initialize Earth Engine
27
  earthengine_credentials = os.environ.get("EE_Authentication")
28
 
29
+ # Initialize Earth Engine with secret credentials
30
  os.makedirs(os.path.expanduser("~/.config/earthengine/"), exist_ok=True)
31
  with open(os.path.expanduser("~/.config/earthengine/credentials"), "w") as f:
32
  f.write(earthengine_credentials)
 
37
  with open("sentinel_datasets.json") as f:
38
  data = json.load(f)
39
 
40
+ # Display the title and dataset selection
41
  st.title("Sentinel Dataset and Index Calculator")
42
 
43
+ # Select dataset category and subcategory
44
  main_selection = st.selectbox("Select Sentinel Dataset Category", list(data.keys()))
45
 
 
46
  if main_selection:
47
  sub_options = data[main_selection]["sub_options"]
48
  sub_selection = st.selectbox("Select Specific Dataset ID", list(sub_options.keys()))
 
50
  # Earth Engine Index Calculator Section
51
  st.header("Earth Engine Index Calculator")
52
 
53
+ # Choose Index or Custom Formula
54
  index_choice = st.selectbox("Select an Index or Enter Custom Formula", ['NDVI', 'NDWI', 'Average NO₂', 'Custom Formula'])
55
 
56
+ # Enter custom formula if selected
57
  custom_formula = ""
58
  if index_choice == 'Custom Formula':
59
  custom_formula = st.text_input("Enter Custom Formula (e.g., 'B5 - B4 / B5 + B4')")
60
 
61
+ # Select Geometry Type (Point or Polygon)
62
  geometry_type = st.selectbox("Select Geometry Type", ['Point', 'Polygon'])
63
 
64
+ # File uploader for Point or Polygon geometry
65
  if geometry_type == 'Point':
66
  uploaded_file = st.file_uploader("Upload a CSV, GeoJSON, or KML file with Point Data", type=["csv", "geojson", "kml"])
67
  else:
68
  uploaded_file = st.file_uploader("Upload a GeoJSON or KML file with Polygon Data", type=["geojson", "kml"])
69
 
70
+ # Function to get user points from CSV, GeoJSON, or KML file
71
  def get_user_points(uploaded_file):
72
  points = []
73
  if uploaded_file.name.endswith('.csv'):
 
74
  df = pd.read_csv(uploaded_file)
75
  for _, row in df.iterrows():
76
  lat = row['latitude']
77
  lon = row['longitude']
78
  # Check for NaN values
79
  if pd.isna(lat) or pd.isna(lon):
80
+ continue
81
+ name = row.get('name', f"Location {len(points) + 1}")
82
  points.append({"geometry": ee.Geometry.Point([lon, lat]), "name": name})
83
+
84
  elif uploaded_file.name.endswith('.geojson'):
 
85
  geojson_data = json.load(uploaded_file)
86
  for feature in geojson_data['features']:
87
  lat, lon = feature['geometry']['coordinates']
88
  # Check for NaN values
89
  if lat is None or lon is None:
90
+ continue
91
  name = feature.get('properties', {}).get('Name', f"Location {len(points) + 1}")
92
  points.append({"geometry": ee.Geometry.Point([lon, lat]), "name": name})
93
+
94
  elif uploaded_file.name.endswith('.kml'):
 
95
  gdf = gpd.read_file(uploaded_file)
96
  for _, row in gdf.iterrows():
97
  lat = row.geometry.y
98
  lon = row.geometry.x
99
  # Check for NaN values
100
  if pd.isna(lat) or pd.isna(lon):
101
+ continue
102
  name = row.get('name', f"Location {len(points) + 1}")
103
  points.append({"geometry": ee.Geometry.Point([lon, lat]), "name": name})
104
+
105
  return points
106
 
107
+ # Function to get user polygons from GeoJSON or KML file
108
  def get_user_polygons(uploaded_file):
109
  polygons = []
110
  if uploaded_file.name.endswith('.geojson'):
 
111
  geojson_data = json.load(uploaded_file)
112
  for feature in geojson_data['features']:
113
  if feature['geometry']['type'] in ['Polygon', 'MultiPolygon']:
114
  geom = ee.Geometry(feature['geometry'])
115
  name = feature.get('properties', {}).get('Name', f"Polygon {len(polygons) + 1}")
116
  polygons.append({"geometry": geom, "name": name})
117
+
118
  elif uploaded_file.name.endswith('.kml'):
 
119
  gdf = gpd.read_file(uploaded_file)
120
  for _, row in gdf.iterrows():
121
  geom = row.geometry
122
  if geom.geom_type in ['Polygon', 'MultiPolygon']:
123
  name = row.get('name', f"Polygon {len(polygons) + 1}")
124
  polygons.append({"geometry": ee.Geometry(geom), "name": name})
125
+
126
  return polygons
127
 
128
+ # Parse the file and get geometries (points or polygons)
129
  if uploaded_file is not None:
130
  if geometry_type == 'Point':
131
  points = get_user_points(uploaded_file)
132
  if points:
133
  st.write(f"Loaded {len(points)} points.")
134
+ points_df = pd.DataFrame([{'Latitude': point['geometry'].coordinates().get(0),
135
  'Longitude': point['geometry'].coordinates().get(1),
136
  'Name': point['name']} for point in points])
137
  st.write("Points from file:", points_df)
 
149
  else:
150
  geometries = []
151
 
152
+ # Function for index calculation
 
 
 
 
 
 
 
 
 
 
153
  def calculate_ndvi(image, geometry):
154
  return image.normalizedDifference(['B5', 'B4']).rename('NDVI').reduceRegion(
155
  reducer=ee.Reducer.mean(),
 
178
  scale=30
179
  )
180
 
181
+ # Step: Perform the calculation based on user choice
182
  if st.button("Calculate Index"):
183
  if geometries:
184
  try: