nascetti-a commited on
Commit
bad0359
·
verified ·
1 Parent(s): a201c57

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +1 -210
src/streamlit_app.py CHANGED
@@ -1,211 +1,2 @@
1
  import streamlit as st
2
- import ee
3
- import geemap.foliumap as geemap
4
- import base64
5
- import json
6
- import tempfile
7
- import os
8
- import datetime
9
- import pandas as pd # Added for data manipulation and plotting
10
- import altair as alt # Added for custom chart coloring
11
-
12
- # --- Configuration ---
13
- st.set_page_config(layout="wide")
14
- st.title("🇪🇺 European Capitals Satellite Viewer")
15
-
16
- # Define a list of major European capitals and their coordinates (Lon, Lat)
17
- EUROPEAN_CAPITALS = {
18
- "Rome, Italy": (12.4964, 41.9028),
19
- "Stockholm, Sweden": (18.0656, 59.3327),
20
- "Paris, France": (2.3522, 48.8566),
21
- "Berlin, Germany": (13.4050, 52.5200),
22
- "London, UK": (-0.1278, 51.5074),
23
- "Madrid, Spain": (-3.7038, 40.4168),
24
- "Vienna, Austria": (16.3738, 48.2082),
25
- "Athens, Greece": (23.7275, 37.9838),
26
- "Warsaw, Poland": (21.0118, 52.2297),
27
- "Amsterdam, Netherlands": (4.8952, 52.3702),
28
- "Oslo, Norway": (10.7522, 59.9139),
29
- "Lisbon, Portugal": (-9.1393, 38.7223),
30
- }
31
-
32
- # --- Initialize EE (using the temporary file method) ---
33
-
34
-
35
- @st.cache_resource
36
- def initialize_ee_session():
37
- """Initializes the Earth Engine session and caches the result."""
38
- try:
39
- # Ensure secrets are available
40
- SERVICE_ACCOUNT = st.secrets["service_account"]
41
- PRIVATE_KEY_B64 = st.secrets["private_key"]
42
-
43
- # Decode the private key and write it to a temporary file for ee.Initialize
44
- decoded = base64.b64decode(PRIVATE_KEY_B64).decode("utf-8")
45
- with tempfile.NamedTemporaryFile(mode="w+", suffix=".json", delete=False) as f:
46
- f.write(decoded)
47
- temp_path = f.name
48
-
49
- credentials = ee.ServiceAccountCredentials(SERVICE_ACCOUNT, temp_path)
50
- ee.Initialize(credentials)
51
- os.remove(temp_path)
52
-
53
- return True
54
- except Exception as e:
55
- st.error(f"❌ Error initializing Earth Engine. Check your Streamlit secrets configuration. Error: {e}")
56
- return False
57
-
58
-
59
- # Run the initialization only once
60
- if initialize_ee_session():
61
- st.success(f"✅ Earth Engine initialized successfully (Cached).")
62
- else:
63
- st.stop()
64
-
65
-
66
- # --- User Inputs ---
67
- st.sidebar.image("image/logo.png")
68
-
69
- st.sidebar.header("Controls")
70
-
71
- selected_city = st.sidebar.selectbox(
72
- "1. Select a European Capital:",
73
- options=list(EUROPEAN_CAPITALS.keys())
74
- )
75
-
76
- col1, col2 = st.sidebar.columns(2)
77
- with col1:
78
- # Fixed: Use datetime.date for Streamlit compatibility
79
- start_date = st.date_input("2. Start Date:", value=datetime.date(2023, 9, 1))
80
- with col2:
81
- # Fixed: Use datetime.date for Streamlit compatibility
82
- end_date = st.date_input("3. End Date:", value=datetime.date(2024, 3, 1))
83
-
84
- cloud_filter = st.sidebar.slider(
85
- "4. Max Cloud Filter (%):",
86
- min_value=1,
87
- max_value=100,
88
- value=15
89
- )
90
-
91
-
92
- # --- Processing Logic ---
93
-
94
- # Get selected city coordinates
95
- lon, lat = EUROPEAN_CAPITALS[selected_city]
96
- # Define a buffer around the city point (e.g., 25km radius)
97
- city_point = ee.Geometry.Point([lon, lat])
98
- aoi = city_point.buffer(25000)
99
-
100
- # 1. Collection filtered ONLY by date and bounds (used for comprehensive plotting)
101
- s2_unfiltered_collection = ee.ImageCollection("COPERNICUS/S2_HARMONIZED") \
102
- .filterDate(start_date.isoformat(), end_date.isoformat()) \
103
- .filterBounds(aoi)
104
-
105
- # 2. Collection filtered by date, bounds, AND cloud percentage (used for composite)
106
- # This ensures only images under the cloud_filter threshold are used for the median composite.
107
- s2_composite_collection = s2_unfiltered_collection \
108
- .filterMetadata('CLOUDY_PIXEL_PERCENTAGE', 'less_than', cloud_filter)
109
-
110
- # Calculate the size of the *composite* collection (blocking call)
111
- collection_size = s2_composite_collection.size().getInfo()
112
- unfiltered_collection_size = s2_unfiltered_collection.size().getInfo()
113
-
114
- try:
115
- if collection_size == 0:
116
- st.warning(
117
- f"⚠️ No Sentinel-2 images found for **{selected_city}** that meet the **{cloud_filter}%** max cloudiness filter. Try expanding the date range or increasing the cloud filter.")
118
- # Create a map centered on the city even if no image is found
119
- Map = geemap.Map(center=[lat, lon], zoom=11, plugin_Draw=False)
120
- Map.to_streamlit(width=800, height=500)
121
- st.stop()
122
- else:
123
- # Calculate the median composite image
124
- s2_composite = s2_composite_collection.median()
125
-
126
- # --- Data Extraction for Plotting (Using UNFILTERED Collection) ---
127
- # Get list of properties for each image in the UNFILTERED collection
128
- feature_list = s2_unfiltered_collection.toList(unfiltered_collection_size).getInfo()
129
- data_for_df = []
130
- for feature in feature_list:
131
- props = feature['properties']
132
- data_for_df.append({
133
- 'Acquisition Date': props['system:time_start'],
134
- 'Cloudiness (%)': props['CLOUDY_PIXEL_PERCENTAGE']
135
- })
136
-
137
- # Convert to Pandas DataFrame and format the date
138
- df = pd.DataFrame(data_for_df)
139
- # Convert Earth Engine Unix timestamp (milliseconds) to datetime objects
140
- df['Acquisition Date'] = pd.to_datetime(df['Acquisition Date'], unit='ms')
141
- df = df.set_index('Acquisition Date').sort_index()
142
-
143
- # Add color column based on the user's filter threshold (Blue <= threshold, Red > threshold)
144
- df['Color'] = df['Cloudiness (%)'].apply(
145
- lambda x: 'blue' if x <= cloud_filter else 'red'
146
- )
147
-
148
- # Calculate the average cloudiness of the source images (from the UNFILTERED set for proper reporting)
149
- mean_cloud_percentage = s2_unfiltered_collection.aggregate_mean('CLOUDY_PIXEL_PERCENTAGE').getInfo()
150
-
151
- # Display analysis results
152
- st.subheader(f"Data Analysis for {selected_city}")
153
- st.info(f"📸 Total available images (date/bounds filtered): **{unfiltered_collection_size}**")
154
- st.info(f"✅ Images used for composite (under {cloud_filter}% cloudiness): **{collection_size}**")
155
- st.info(f"☁️ Average Cloudiness of all available images: **{mean_cloud_percentage:.2f}%**")
156
-
157
- # --- PLOT CLOUDINESS OVER TIME with Conditional Colors using Altair ---
158
- st.subheader("Cloudiness Over Time vs. Filter Threshold")
159
- st.markdown(
160
- f"Bars are colored **blue** if cloudiness is below the **{cloud_filter}%** threshold (used for composite) and **red** if above.")
161
-
162
- # Define custom color scale to ensure blue and red are used
163
- color_scale = alt.Scale(domain=['blue', 'red'], range=['blue', 'red'])
164
-
165
- # Create the Altair chart
166
- chart = alt.Chart(df.reset_index()).mark_bar().encode(
167
- x=alt.X('Acquisition Date', title='Acquisition Date'),
168
- y=alt.Y('Cloudiness (%)', title='Cloudiness (%)'),
169
- color=alt.Color('Color', scale=color_scale), # Use the pre-calculated color column
170
- tooltip=['Acquisition Date', 'Cloudiness (%)']
171
- ).properties(
172
- height=300
173
- ).interactive() # Make the chart zoomable/pannable
174
-
175
- # Add a horizontal line to represent the user's cloud filter threshold
176
- rule = alt.Chart(pd.DataFrame({'y': [cloud_filter]})).mark_rule(color='green', strokeDash=[5, 5]).encode(
177
- y='y'
178
- )
179
-
180
- st.altair_chart(chart + rule, use_container_width=True)
181
- # --- END PLOT ---
182
-
183
- # Visualization parameters (Natural Color RGB)
184
- vis_params = {
185
- "bands": ["B4", "B3", "B2"],
186
- "min": 0,
187
- "max": 3000,
188
- "gamma": 1.4
189
- }
190
-
191
- # Create a map centered on the selected city
192
- Map = geemap.Map(center=[lat, lon], zoom=10)
193
-
194
- # Add the composite layer to the map
195
- Map.addLayer(s2_composite, vis_params, f"Sentinel-2 Composite: {selected_city}")
196
-
197
- # Add a marker for the capital city center
198
- Map.add_marker([lat, lon], tooltip=selected_city)
199
- #Map.add_ee_layer(aoi.bounds(), {'color': 'red'}, 'Area of Interest')
200
-
201
- # Display the map in Streamlit
202
- st.subheader("Satellite Composite Visualization")
203
- Map.to_streamlit(width=900, height=600)
204
-
205
- except Exception as e:
206
- st.error(f"An Earth Engine error occurred during processing: {e}")
207
-
208
- st.markdown("""
209
- ---
210
- *Data Source: ESA Copernicus Sentinel-2 Level 2A data via Google Earth Engine.*
211
- """)
 
1
  import streamlit as st
2
+ st.write(st.secrets)