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
 
 
 
 
 
 
 
1
+ import os
2
+ import gradio as gr
3
+ import numpy as np
4
+ import io
5
+ import random
6
+ from PIL import Image
7
+ from dotenv import load_dotenv
8
+ import pystac_client
9
+ from datetime import datetime
10
+ from src.auth.auth import S3Connector
11
+ from src.utils.utils import extract_s3_path_from_url
12
+ from src.utils.stac_client import get_product_content
13
+ from src.utils.geo_guesser import get_random_land_point
14
+ # Assuming these utility modules are in the specified paths relative to the script
15
+ # If not, adjust the import paths accordingly.
16
+
17
+ # import geopandas as gpd # Not used in the provided snippet, can be removed if not needed elsewhere
18
+ # from shapely.geometry import Point # Not used, can be removed
19
+ # import geodatasets # Not used, can be removed
20
+ import folium
21
+ from gradio_folium import Folium
22
+ import tempfile
23
+
24
+
25
+ # Function to create a Folium map for a location
26
+ def create_location_map(latitude, longitude):
27
+ try:
28
+ # Create a folium map centered at the point
29
+ m = folium.Map(location=[latitude, longitude], width='100%', height='100%', zoom_start=7, tiles="Cartodb dark_matter")
30
+
31
+ # Add a marker for the point
32
+ folium.Marker(
33
+ location=[latitude, longitude],
34
+ popup=f"Image Location<br>Lon: {longitude:.2f}<br>Lat: {latitude:.2f}",
35
+ icon=folium.Icon(color='red', icon='camera')
36
+ ).add_to(m)
37
+
38
+ return m
39
+ except Exception as e:
40
+ print(f"Error creating map: {e}")
41
+ return folium.Map(location=[0, 0], zoom_start=2)
42
+
43
+ # --- START MODIFICATION: Add Image Quality Check Function ---
44
+ def check_image_quality(img: Image.Image, max_black_pct=15.0, max_white_pct=50.0):
45
+ """
46
+ Checks if a PIL Image has excessive black or white pixels.
47
+
48
+ Args:
49
+ img: The PIL Image object.
50
+ max_black_pct: Maximum allowed percentage of pure black pixels.
51
+ max_white_pct: Maximum allowed percentage of pure white pixels.
52
+
53
+ Returns:
54
+ True if the image quality is problematic (too much black/white), False otherwise.
55
+ """
56
+ try:
57
+ img_array = np.array(img)
58
+ # Ensure it's an RGB image for consistent checks
59
+ if img_array.ndim != 3 or img_array.shape[2] != 3:
60
+ print("Warning: Image is not in standard RGB format. Skipping quality check.")
61
+ return False # Assume okay if not standard RGB
62
+
63
+ total_pixels = img_array.shape[0] * img_array.shape[1]
64
+ if total_pixels == 0:
65
+ print("Warning: Image has zero pixels.")
66
+ return True # Problematic if no pixels
67
+
68
+ # Count black pixels (0, 0, 0)
69
+ black_pixels = np.sum(np.all(img_array == [0, 0, 0], axis=2))
70
+ black_pct = (black_pixels / total_pixels) * 100
71
+
72
+ # Count white pixels (255, 255, 255)
73
+ white_pixels = np.sum(np.all(img_array == [255, 255, 255], axis=2))
74
+ white_pct = (white_pixels / total_pixels) * 100
75
+
76
+ print(f"Image Quality Check - Black: {black_pct:.2f}%, White: {white_pct:.2f}%")
77
+
78
+ if black_pct > max_black_pct:
79
+ print(f"Image rejected: Exceeds black pixel threshold ({black_pct:.2f}% > {max_black_pct}%)")
80
+ return True # Problematic
81
+ if white_pct > max_white_pct:
82
+ print(f"Image rejected: Exceeds white pixel threshold ({white_pct:.2f}% > {max_white_pct}%)")
83
+ return True # Problematic
84
+
85
+ return False # Image quality is acceptable
86
+ except Exception as e:
87
+ print(f"Error during image quality check: {e}")
88
+ # Decide how to handle check errors, e.g., assume okay or problematic
89
+ return False # Let's be lenient and assume okay if check fails
90
+ # --- END MODIFICATION ---
91
+
92
+
93
+ # Load environment variables
94
+ load_dotenv()
95
+
96
+ # Get credentials from environment variables
97
+ ACCESS_KEY_ID = os.environ.get("ACCESS_KEY_ID")
98
+ SECRET_ACCESS_KEY = os.environ.get("SECRET_ACCESS_KEY")
99
+ ENDPOINT_URL = 'https://eodata.dataspace.copernicus.eu'
100
+ ENDPOINT_STAC = "https://stac.dataspace.copernicus.eu/v1/"
101
+ BUCKET_NAME = "eodata"
102
+
103
+ # Initialize the connector
104
+ # Ensure S3Connector is correctly defined in src.auth.auth
105
+ try:
106
+ connector = S3Connector(
107
+ endpoint_url=ENDPOINT_URL,
108
+ access_key_id=ACCESS_KEY_ID,
109
+ secret_access_key=SECRET_ACCESS_KEY,
110
+ region_name='default' # Adjust if a specific region is needed
111
+ )
112
+
113
+ # Connect to S3
114
+ s3 = connector.get_s3_resource()
115
+ s3_client = connector.get_s3_client()
116
+ # buckets = connector.list_buckets() # Optional: Listing buckets might require different permissions
117
+ # print("Available buckets:", buckets) # Comment out if not needed or causes issues
118
+ except ImportError:
119
+ print("Error: S3Connector class not found. Ensure src/auth/auth.py exists and is correct.")
120
+ # Provide dummy clients if needed for Gradio interface to load without full functionality
121
+ s3 = None
122
+ s3_client = None
123
+ except Exception as e:
124
+ print(f"Error initializing S3 Connector: {e}")
125
+ s3 = None
126
+ s3_client = None
127
+
128
+ # Initialize STAC Client
129
+ try:
130
+ catalog = pystac_client.Client.open(ENDPOINT_STAC)
131
+ except Exception as e:
132
+ print(f"Error initializing STAC Client: {e}")
133
+ catalog = None
134
+
135
+ # --- START MODIFICATION: Update fetch_sentinel_image ---
136
+ def fetch_sentinel_image(longitude, latitude, date_from, date_to, cloud_cover):
137
+ """Fetch a Sentinel image based on criteria, retrying if quality is poor."""
138
+ if not catalog or not s3_client:
139
+ error_message = "STAC Catalog or S3 Client not initialized. Check credentials and endpoints."
140
+ print(error_message)
141
+ default_map = folium.Map(location=[0, 0], zoom_start=2)
142
+ return None, error_message, default_map
143
+
144
+ try:
145
+ # Use the coordinates from inputs
146
+ LON, LAT = float(longitude), float(latitude)
147
+
148
+ # Use the date range from inputs
149
+ date_range = f"{date_from}/{date_to}"
150
+
151
+ cloud_query = f"eo:cloud_cover<{cloud_cover}"
152
+
153
+ # Search for items
154
+ search = catalog.search(
155
+ collections=['sentinel-2-l2a'],
156
+ intersects=dict(type="Point", coordinates=[LON, LAT]),
157
+ datetime=date_range,
158
+ query=[cloud_query],
159
+ max_items=20 # Fetch a few items to have alternatives for quality check
160
+ )
161
+ # It's often better to get items as a list directly if possible
162
+ # Depending on pystac_client version, .items() or .item_collection() might be preferred
163
+ # Using item_collection and converting to list for broader compatibility
164
+ items_collection = search.item_collection()
165
+ items_list = list(items_collection)
166
+
167
+
168
+ if len(items_list) == 0:
169
+ # Return a default map with no data
170
+ default_map = create_location_map(LAT, LON) # Use helper function
171
+ folium.Marker(
172
+ location=[LAT, LON],
173
+ popup=f"No images found at this location\nLon: {LON:.2f}, Lat: {LAT:.2f}\nwithin {date_from} to {date_to}\nand cloud cover < {cloud_cover}%",
174
+ icon=folium.Icon(color='gray', icon='question-sign')
175
+ ).add_to(default_map)
176
+
177
+ return None, f"No images found for the specified criteria at coordinates ({LON}, {LAT}) with cloud cover < {cloud_cover}%.", default_map
178
+
179
+ # Shuffle the list to try different items if multiple calls are made
180
+ random.shuffle(items_list)
181
+
182
+ MAX_QUALITY_ATTEMPTS = 5 # Max images to check for quality from the found list
183
+ selected_item = None
184
+ img = None
185
+ product_url = None
186
+ metadata = "Failed to retrieve a suitable quality image." # Default failure msg
187
+
188
+ for attempt, item in enumerate(items_list):
189
+ if attempt >= MAX_QUALITY_ATTEMPTS:
190
+ print(f"Checked {MAX_QUALITY_ATTEMPTS} images, none passed quality criteria.")
191
+ metadata = f"Found {len(items_list)} images, but the first {MAX_QUALITY_ATTEMPTS} checked failed quality check (Black > 15% or White > 50%)."
192
+ break # Stop trying after max attempts
193
+
194
+ print(f"Attempt {attempt + 1}/{min(MAX_QUALITY_ATTEMPTS, len(items_list))}: Trying item {item.id}")
195
+
196
+ try:
197
+ # Ensure 'TCI_60m' asset exists
198
+ if 'TCI_60m' not in item.assets:
199
+ print(f"Item {item.id} does not have a 'TCI_60m' asset. Skipping.")
200
+ continue
201
+
202
+ # Get the TCI_60m asset from the randomly selected item
203
+ current_product_url = extract_s3_path_from_url(item.assets['TCI_60m'].href)
204
+ # Ensure get_product_content is correctly defined in src.utils.stac_client
205
+ product_content = get_product_content(s3_client=s3_client, bucket_name=BUCKET_NAME,
206
+ object_url=current_product_url)
207
+ print(f"Selected product URL: {current_product_url}")
208
+
209
+ # Convert to PIL Image
210
+ current_img = Image.open(io.BytesIO(product_content))
211
+
212
+ # Perform image quality check
213
+ if not check_image_quality(current_img, max_black_pct=15.0, max_white_pct=50.0):
214
+ # Quality is good, select this image
215
+ selected_item = item
216
+ img = current_img
217
+ product_url = current_product_url
218
+ print(f"Image {item.id} passed quality check.")
219
+ break # Found a good image, exit the loop
220
+ else:
221
+ # Quality is bad, close image and loop continues
222
+ print(f"Image {item.id} failed quality check. Trying next.")
223
+ current_img.close() # Close the problematic image
224
+
225
+ except (FileNotFoundError, KeyError) as asset_err: # Handle S3 errors or missing keys
226
+ print(f"Error accessing asset for item {item.id}: {asset_err}. Skipping.")
227
+ continue # Try the next item
228
+ except Exception as proc_err:
229
+ print(f"Error processing item {item.id}: {proc_err}. Skipping.")
230
+ # Close image if it was opened before error
231
+ if 'current_img' in locals() and hasattr(current_img, 'close'):
232
+ current_img.close()
233
+ continue # Try the next item
234
+
235
+ # After the loop, check if a good image was found
236
+ if selected_item and img:
237
+ # Format datetime for readability
238
+ datetime_str = selected_item.properties.get('datetime', 'N/A')
239
+ try:
240
+ # Handle potential timezone 'Z'
241
+ if isinstance(datetime_str, str) and datetime_str.endswith('Z'):
242
+ datetime_str = datetime_str[:-1] + '+00:00'
243
+ dt = datetime.fromisoformat(datetime_str)
244
+ formatted_date = dt.strftime('%Y-%m-%d %H:%M:%S UTC')
245
+ except ValueError:
246
+ formatted_date = datetime_str # Keep original if parsing fails
247
+ except Exception as date_e:
248
+ print(f"Date formatting error: {date_e}")
249
+ formatted_date = datetime_str # Fallback
250
+
251
+ # Extract metadata for display
252
+ metadata = f"""
253
+ ## Product Information
254
+ - **Location**: {LAT:.4f}°N, {LON:.4f}°E
255
+ - **Date**: {formatted_date}
256
+ - **Cloud Cover**: {selected_item.properties.get('eo:cloud_cover', 'N/A')}%
257
+ - **Cloud Cover Threshold**: < {cloud_cover}%
258
+ - **Satellite**: {selected_item.properties.get('platform', 'N/A')}
259
+ - **Product ID**: {selected_item.id}
260
+ """
261
+
262
+ # Create a location map
263
+ location_map = create_location_map(LAT, LON)
264
+
265
+ return img, metadata, location_map
266
+ else:
267
+ # If loop finished without finding a good image
268
+ default_map = create_location_map(LAT, LON) # Show location map
269
+ folium.Marker(
270
+ location=[LAT, LON],
271
+ popup=f"Found {len(items_list)} images, but none passed quality check (checked up to {MAX_QUALITY_ATTEMPTS}).\nLon: {LON:.2f}, Lat: {LAT:.2f}",
272
+ icon=folium.Icon(color='orange', icon='exclamation-sign')
273
+ ).add_to(default_map)
274
+ # Use the metadata message set earlier if loop failed
275
+ return None, metadata, default_map
276
+
277
+
278
+ except ValueError as ve:
279
+ error_message = f"Invalid input: {str(ve)}. Please ensure longitude and latitude are valid numbers."
280
+ print(error_message)
281
+ default_map = folium.Map(location=[0, 0], zoom_start=2)
282
+ return None, error_message, default_map
283
+ except pystac_client.exceptions.APIError as api_err:
284
+ error_message = f"STAC API Error: {api_err}. Check STAC endpoint and query parameters."
285
+ print(error_message)
286
+ default_map = folium.Map(location=[0,0], zoom_start=2)
287
+ return None, error_message, default_map
288
+ except Exception as e:
289
+ error_message = f"An unexpected error occurred: {str(e)}"
290
+ import traceback
291
+ print(error_message)
292
+ traceback.print_exc() # Print full traceback for debugging
293
+ default_map = folium.Map(location=[0, 0], zoom_start=2)
294
+ return None, error_message, default_map
295
+ # --- END MODIFICATION ---
296
+
297
+
298
+ # Function to handle random location and auto-fetch
299
+ def random_location_and_fetch(date_from, date_to, cloud_cover):
300
+ """Get a random land location and fetch an image from there."""
301
+ # Ensure get_random_land_point is correctly defined in src.utils.geo_guesser
302
+ try:
303
+ lon, lat = get_random_land_point()
304
+ except ImportError:
305
+ print("Error: get_random_land_point function not found. Ensure src/utils/geo_guesser.py exists.")
306
+ return 0, 0, None, "Error: Cannot generate random point.", folium.Map(location=[0,0], zoom_start=2)
307
+ except Exception as e:
308
+ print(f"Error getting random land point: {e}")
309
+ return 0, 0, None, f"Error generating random point: {e}", folium.Map(location=[0,0], zoom_start=2)
310
+
311
+ print(f"Random land point selected: Longitude={lon}, Latitude={lat}")
312
+
313
+ img, metadata, location_map = fetch_sentinel_image(lon, lat, date_from, date_to, cloud_cover)
314
+
315
+ # --- START MODIFICATION: Adjust retry logic message ---
316
+ # The retry for *location* is now less likely needed if fetch_sentinel_image
317
+ # itself tries multiple images. We keep it as a fallback if an entire area
318
+ # yields no images or only bad quality ones repeatedly.
319
+ attempts = 1
320
+ max_attempts = 3 # Max attempts for *different random locations*
321
+ while img is None and attempts < max_attempts:
322
+ attempts += 1
323
+ print(f"Attempt {attempts}/{max_attempts}: No suitable image at ({lon:.2f}, {lat:.2f}). Trying another random location...")
324
+ try:
325
+ lon, lat = get_random_land_point()
326
+ print(f"New random land point: Longitude={lon}, Latitude={lat}")
327
+ img, metadata, location_map = fetch_sentinel_image(lon, lat, date_from, date_to, cloud_cover)
328
+ except Exception as e:
329
+ print(f"Error getting random land point on attempt {attempts}: {e}")
330
+ # Decide if you want to stop or just report error and let loop continue
331
+ metadata = f"Error getting random location on attempt {attempts}: {e}"
332
+ # Keep trying if attempts remain
333
+
334
+ if img is None:
335
+ # Refine the message if no image was found after multiple location attempts
336
+ metadata = f"Failed to find a suitable image after trying {max_attempts} random locations. The last attempt was at ({lon:.2f}, {lat:.2f}).\nDetails: {metadata}" # Append last failure reason
337
+ # Ensure map shows the last attempted location
338
+ if 'location_map' not in locals() or location_map is None:
339
+ location_map = create_location_map(lat, lon)
340
+ folium.Marker(
341
+ location=[lat, lon],
342
+ popup=f"Failed to find image after {max_attempts} attempts.\nLast try: Lon: {lon:.2f}, Lat: {lat:.2f}",
343
+ icon=folium.Icon(color='red', icon='times')
344
+ ).add_to(location_map)
345
+
346
+ # Update the Gradio fields with the final lon/lat, even if fetching failed
347
+ return lon, lat, img, metadata, location_map
348
+ # --- END MODIFICATION ---
349
+
350
+
351
+ # Create Gradio interface
352
+ with gr.Blocks(title="Sentinel Product Viewer") as demo:
353
+ gr.Markdown("# Sentinel-2 Product Viewer")
354
+ gr.Markdown("Browse and view Sentinel-2 satellite product")
355
+
356
+ with gr.Row():
357
+ with gr.Column(scale=1):
358
+ # Location inputs
359
+ with gr.Row():
360
+ longitude = gr.Number(label="Longitude", value=15.0, minimum=-180, maximum=180)
361
+ latitude = gr.Number(label="Latitude", value=50.0, minimum=-90, maximum=90)
362
+
363
+ # Date range inputs
364
+ with gr.Row():
365
+ # Use gr.Date for better UX if Gradio version supports it well
366
+ # Otherwise, stick to Textbox and rely on user format
367
+ # date_from = gr.Date(label="Date From", value="2024-05-01")
368
+ # date_to = gr.Date(label="Date To", value="2025-02-01")
369
+ date_from = gr.Textbox(label="Date From (YYYY-MM-DD)", value="2024-05-01")
370
+ date_to = gr.Textbox(label="Date To (YYYY-MM-DD)", value="2025-02-01")
371
+
372
+
373
+ # Cloud cover slider
374
+ cloud_cover = gr.Slider(
375
+ label="Max Cloud Cover (%)",
376
+ minimum=0,
377
+ maximum=100,
378
+ value=20, # Lowered default for potentially better initial results
379
+ step=5
380
+ )
381
+ # Diverse landscape location buttons
382
+ gr.Markdown("### Preset Locations")
383
+ with gr.Row():
384
+ italy_btn = gr.Button("Italy")
385
+ amazon_btn = gr.Button("Amazon Rainforest")
386
+ with gr.Row():
387
+ tokyo_btn = gr.Button("Tokyo")
388
+ great_barrier_btn = gr.Button("Great Barrier Reef")
389
+ with gr.Row():
390
+ iceland_btn = gr.Button("Iceland Glacier")
391
+ canada_btn = gr.Button("Baffin Island")
392
+
393
+ fetch_btn = gr.Button("Fetch Image for Current Location", variant="secondary")
394
+
395
+ # Add Random Earth Location button (with distinctive styling)
396
+ gr.Markdown("### Random Discovery")
397
+ random_earth_btn = gr.Button("🌍 Get Random Earth Location & Image", variant="primary") # Changed size attr
398
+
399
+ metadata_output = gr.Markdown(label="Image Metadata")
400
+
401
+ with gr.Column(scale=2):
402
+ image_output = gr.Image(
403
+ type="pil",
404
+ label="Sentinel-2 Image (TCI 60m)",
405
+ # Removed fixed height/width to allow natural aspect ratio
406
+ # height=512, # Example: Set a moderate height if needed
407
+ # width=512,
408
+ show_download_button=True
409
+ )
410
+
411
+ map_output = Folium(
412
+ # Initialize with a default map view
413
+ value=create_location_map(50.0, 15.0), # Use initial lat/lon
414
+ label="Location Map",
415
+ height=400, # Maintain a fixed height for the map
416
+ )
417
+
418
+ # Button click handlers for diverse landscapes
419
+ # These lambda functions only update the lat/lon input fields
420
+ italy_btn.click(lambda: (12.39, 42.05), outputs=[longitude, latitude])
421
+ amazon_btn.click(lambda: (-64.7, -3.42), outputs=[longitude, latitude])
422
+ tokyo_btn.click(lambda: (139.70, 35.65), outputs=[longitude, latitude])
423
+ great_barrier_btn.click(lambda: (150.97, -20.92), outputs=[longitude, latitude])
424
+ iceland_btn.click(lambda: (-18.17, 64.61), outputs=[longitude, latitude])
425
+ canada_btn.click(lambda: (-71.56, 67.03), outputs=[longitude, latitude])
426
+
427
+ # Random Earth button - gets random location AND fetches image
428
+ random_earth_btn.click(
429
+ fn=random_location_and_fetch,
430
+ # Inputs: date range and cloud cover from the UI
431
+ inputs=[date_from, date_to, cloud_cover],
432
+ # Outputs: Update lon/lat fields AND image, metadata, map
433
+ outputs=[longitude, latitude, image_output, metadata_output, map_output]
434
+ )
435
+
436
+ # Main search button - uses current lat/lon, date, cloud cover
437
+ fetch_btn.click(
438
+ fn=fetch_sentinel_image,
439
+ inputs=[longitude, latitude, date_from, date_to, cloud_cover],
440
+ outputs=[image_output, metadata_output, map_output]
441
+ )
442
+
443
+ # Optional: Add back the About section if desired
444
+ # gr.Markdown("## About")
445
+ # ... (About text) ...
446
+
447
+ if __name__ == "__main__":
448
+ # Ensure necessary helper modules/functions are available
449
+ # (S3Connector, extract_s3_path_from_url, get_product_content, get_random_land_point)
450
+ if s3_client and catalog:
451
+ print("S3 and STAC clients initialized. Launching Gradio app.")
452
+ demo.launch(share=True) # Set share=False for local-only access
453
+ else:
454
+ print("Could not initialize S3 or STAC client. Ensure credentials and network access are correct.")
455
+ print("Gradio app will launch with limited functionality.")
456
+ # Optionally launch anyway, or exit
457
+ demo.launch(share=True) # Or exit(1) if clients are essential