-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathcopernicus_marimo.py
More file actions
2214 lines (1886 loc) · 82.3 KB
/
copernicus_marimo.py
File metadata and controls
2214 lines (1886 loc) · 82.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Copernicus Data Space Ecosystem Explorer - Interactive GUI
This Marimo app provides an interactive interface for:
1. Configuring Copernicus API credentials
2. Searching for Sentinel-1 (SAR) and Sentinel-2 (optical) satellite data
3. Downloading and visualizing satellite imagery
The app uses the Copernicus Data Space Ecosystem API, which provides free access
to Sentinel satellite data. No credit card required - just register at:
https://dataspace.copernicus.eu/
"""
import marimo
__generated_with = "0.18.4"
app = marimo.App(width="medium")
@app.cell
def _():
"""Import required libraries for the application."""
import os
import traceback
from datetime import datetime, timedelta
from pathlib import Path
import marimo as mo
return Path, datetime, mo, os, timedelta, traceback
@app.cell
def _(mo):
"""Display the application header with instructions."""
mo.md(
"""
# Copernicus Data Space Ecosystem Explorer
This interactive GUI allows you to:
1. **Configure credentials** - Save your Copernicus account credentials securely
2. **Search for data** - Find Sentinel-1 (SAR) or Sentinel-2 (optical) imagery
3. **Download & visualize** - Automatically download and display satellite images
## Getting Started
**Get free Copernicus account:**
1. Visit: https://dataspace.copernicus.eu/
2. Click "Register" (no credit card required)
3. Use your account username/email and password below
**About the satellites:**
- **Sentinel-2 (S2)**: Optical imagery (like a camera), best for seeing colors, vegetation, water
- **Sentinel-1 (S1)**: Radar imagery (SAR), works through clouds, day/night, good for water detection
"""
)
return
@app.cell
def _(Path):
"""Check if Copernicus credentials are already configured in .env file.
This cell reads the .env file (if it exists) and checks for valid
COPERNICUS_USERNAME and COPERNICUS_PASSWORD entries.
"""
env_path = Path(".env")
env_exists = env_path.exists()
# Initialize credential flags
has_username = False
has_password = False
# If .env exists, check if it has valid credentials
if env_exists:
with open(env_path, "r") as _f:
content = _f.read()
# Check for USERNAME (must have non-empty value)
has_username = (
"COPERNICUS_USERNAME=" in content
and len(content.split("COPERNICUS_USERNAME=")[1].split("\n")[0].strip()) > 0
)
# Check for PASSWORD (must have non-empty value)
has_password = (
"COPERNICUS_PASSWORD=" in content
and len(content.split("COPERNICUS_PASSWORD=")[1].split("\n")[0].strip()) > 0
)
# Credentials are configured only if both username and password are present
credentials_configured = has_username and has_password
return credentials_configured, env_path
@app.cell
def _(credentials_configured, mo):
"""Display credential input form with status message.
Shows a green checkmark if credentials are already configured,
or a warning if they need to be entered.
"""
# Show appropriate status message
if credentials_configured:
status_msg = mo.md(
"""
## ✅ Credentials Configured
Your Copernicus credentials are saved in `.env` file.
You can proceed to search for satellite data below.
*To update credentials, enter new values and click Save.*
"""
)
else:
status_msg = mo.md(
"""
## ⚠️ Credentials Required
Please enter your Copernicus account credentials below.
These will be saved securely in a `.env` file.
**Don't have an account yet?**
1. Register for free at: https://dataspace.copernicus.eu/
2. Use your account username/email and password below
"""
)
# Create input widgets (password type hides the values for security)
username_input = mo.ui.text(
label="Username/Email",
kind="text",
placeholder="Enter your Copernicus username or email",
)
password_input = mo.ui.text(
label="Password",
kind="password",
placeholder="Enter your Copernicus password",
)
save_button = mo.ui.run_button(label="💾 Save Credentials")
# Display the form vertically stacked
mo.vstack([status_msg, username_input, password_input, save_button])
return password_input, save_button, username_input
@app.cell
def _(
env_path,
mo,
os,
password_input,
save_button,
traceback,
username_input,
):
"""Save credentials to .env file when Save button is clicked.
This cell:
1. Validates that both fields are filled
2. Preserves any existing .env variables (doesn't overwrite other settings)
3. Writes COPERNICUS_USERNAME and COPERNICUS_PASSWORD
4. Sets credentials in current environment for immediate use
"""
save_result = ""
# Only process if save button was clicked
if save_button.value:
# Get values from input fields
username = username_input.value
password = password_input.value
# Validate that both fields have values
if not username or not password:
save_result = """
❌ **Error: Both fields are required**
Please enter both your username/email and password.
"""
else:
try:
# Read existing .env content to preserve other variables
existing_content = ""
if env_path.exists():
with open(env_path, "r") as _f:
lines = _f.readlines()
# Keep all lines except COPERNICUS credentials
# (we'll add updated ones below)
existing_content = "".join(
[
line
for line in lines
if not line.startswith("COPERNICUS_USERNAME=")
and not line.startswith("COPERNICUS_PASSWORD=")
]
)
# Write the updated .env file
with open(env_path, "w") as _f:
_f.write(existing_content)
# Ensure newline before adding credentials
if existing_content and not existing_content.endswith("\n"):
_f.write("\n")
_f.write(f"COPERNICUS_USERNAME={username}\n")
_f.write(f"COPERNICUS_PASSWORD={password}\n")
# Also set in current environment for immediate use
# (so you don't need to restart the app)
os.environ["COPERNICUS_USERNAME"] = username
os.environ["COPERNICUS_PASSWORD"] = password
save_result = """
✅ **Credentials saved successfully!**
Your credentials are now saved in `.env` file and ready to use.
You can proceed to search for satellite data below.
"""
except Exception as e:
save_result = f"""
❌ **Error saving credentials**
{str(e)}
Please check file permissions and try again.
"""
# Display result message if there is one
mo.md(save_result) if save_result else None
return
@app.cell
def _(mo):
"""Display section header for search parameters."""
mo.md(
"""
---
## 🛰️ Search Parameters
Configure your search below. The default values show a small area in Luxembourg
as an example. You can modify any parameter to search for data in your area of interest.
"""
)
return
@app.cell
def _(datetime, mo, timedelta):
"""Create search parameter input widgets.
Default values:
- Location: Bloemhof Dam area, South Africa (25.68-25.69°E, -27.67--27.66°S)
- Date range: Last 30 days
- Satellite: Sentinel-2 (optical)
- Max products: 2 (to keep download size manageable)
- Crop to bbox: False (show full context by default)
"""
# Calculate default date range (last 30 days)
default_end_date = datetime.now().strftime("%Y-%m-%d")
default_start_date = (datetime.now() - timedelta(days=30)).strftime("%Y-%m-%d")
# Coordinate inputs (bounding box)
# Format: [min_lon, min_lat, max_lon, max_lat]
min_lon = mo.ui.number(
start=-180,
stop=180,
step=0.01,
value=25.6796,
label="Min Longitude (°E)",
)
min_lat = mo.ui.number(
start=-90,
stop=90,
step=0.01,
value=-27.6721,
label="Min Latitude (°N)",
)
max_lon = mo.ui.number(
start=-180,
stop=180,
step=0.01,
value=25.6897,
label="Max Longitude (°E)",
)
max_lat = mo.ui.number(
start=-90,
stop=90,
step=0.01,
value=-27.663,
label="Max Latitude (°N)",
)
# Satellite type selection
# S2 = Sentinel-2 (optical/camera-like imagery)
# S1 = Sentinel-1 (radar/SAR imagery, works through clouds)
# S1+S2 = Both (required for Galileo time series export)
satellite_type = mo.ui.dropdown(
options=["S2", "S1", "S1+S2"],
value="S2",
label="Satellite Type (S2=Optical, S1=Radar, S1+S2=Both)",
)
# Date range inputs
start_date = mo.ui.date(value=default_start_date, label="Start Date")
end_date = mo.ui.date(value=default_end_date, label="End Date")
# Max products to download (limited to prevent excessive downloads)
max_products = mo.ui.number(
start=1,
stop=50,
step=1,
value=2,
label="Max Products",
)
# Crop to bbox option
# When enabled: Only shows target area (faster, less memory)
# When disabled: Shows full tile with context (slower, more memory)
crop_to_bbox = mo.ui.checkbox(
value=False,
label="Crop to target area only (faster, less memory)",
)
# Search button triggers the search and download
search_button = mo.ui.run_button(label="🔍 Search & Download")
return (
crop_to_bbox,
end_date,
max_lat,
max_lon,
max_products,
min_lat,
min_lon,
satellite_type,
search_button,
start_date,
)
@app.cell
def _(
crop_to_bbox,
end_date,
max_lat,
max_lon,
max_products,
min_lat,
min_lon,
mo,
satellite_type,
search_button,
start_date,
):
"""Display search parameter widgets in a nice layout."""
mo.vstack(
[
mo.md(
"""
**Bounding Box**: Define the geographic area to search.
Coordinates are in decimal degrees (WGS84).
"""
),
mo.hstack([min_lon, min_lat, max_lon, max_lat]),
mo.md(
"""
**Satellite & Time Range**: Choose satellite type and date range.
- **S2 (Sentinel-2)**: Optical imagery, 10m resolution, affected by clouds
- **S1 (Sentinel-1)**: Radar imagery, 10m resolution, works through clouds
**Max Products**: Number of images to download (1-50). Start with 2-5 for testing.
"""
),
mo.hstack([satellite_type, start_date, end_date, max_products]),
mo.md(
"""
**Visualization Options**:
"""
),
crop_to_bbox,
mo.callout(
mo.md(
"""
**Tip**: Unchecked (default) shows full satellite tile with context around your target area.
Check the box if you only want to see the target area (uses less memory, good for many images).
"""
),
kind="info",
),
mo.callout(
mo.md(
"""
**Note**: After changing any parameters above, click "Search & Download" again to apply the changes.
"""
),
kind="warn",
),
search_button,
]
)
return
@app.cell
def _(
credentials_configured,
end_date,
max_lat,
max_lon,
max_products,
min_lat,
min_lon,
mo,
satellite_type,
search_button,
start_date,
traceback,
):
"""Search for and download satellite data when Search button is clicked.
This cell:
1. Validates that credentials are configured
2. Initializes the Copernicus client
3. Searches for products matching the criteria
4. Downloads the products to data/cache/copernicus/
5. Returns list of downloaded file paths for visualization
The search uses different parameters for S1 vs S2:
- S2: Filters by cloud cover (<30%), uses L2A processing level
- S1: Filters by polarization (VV+VH), uses GRD product type
"""
download_result = ""
downloaded_files = []
# Only process if search button was clicked
if search_button.value:
# First check: Do we have credentials?
if not credentials_configured:
download_result = """
❌ **Credentials Required**
Please configure your Copernicus credentials above before searching.
"""
else:
# Show spinner while processing (can take 30s-2min for downloads)
with mo.status.spinner(title="Searching and downloading...") as _spinner:
try:
# Import the Copernicus client
_spinner.update(title="Initializing Copernicus client...")
from src.data.copernicus import CopernicusClient
# Get search parameters from widgets
_bbox = [min_lon.value, min_lat.value, max_lon.value, max_lat.value]
# Validate bounding box
if _bbox[0] >= _bbox[2] or _bbox[1] >= _bbox[3]:
download_result = """
❌ **Invalid Bounding Box**
Min longitude must be less than max longitude.
Min latitude must be less than max latitude.
"""
raise ValueError("Invalid bounding box")
# Initialize the client (handles OAuth2 authentication)
client = CopernicusClient()
# Build initial result message
download_result = f"""
### 🔍 Searching for {satellite_type.value} products
**Area**: {_bbox[0]:.3f}°E to {_bbox[2]:.3f}°E, {_bbox[1]:.3f}°N to {_bbox[3]:.3f}°N
**Dates**: {start_date.value} to {end_date.value}
**Max products**: {max_products.value}
"""
# Capture stdout to get the "Found X products" message
import io
import sys
_stdout_capture = io.StringIO()
_old_stdout = sys.stdout
sys.stdout = _stdout_capture
try:
# Call appropriate fetch method based on satellite type
if satellite_type.value == "S2":
_spinner.update(title="Searching for Sentinel-2 products...")
# Sentinel-2 parameters:
# - resolution: 10m (highest resolution for RGB bands)
# - max_cloud_cover: 30% (filter out very cloudy images)
# - product_type: S2MSI2A (Level-2A = atmospherically corrected)
downloaded_files = client.fetch_s2(
bbox=_bbox,
start_date=str(start_date.value),
end_date=str(end_date.value),
resolution=10,
max_cloud_cover=30,
product_type="S2MSI2A",
download_data=True,
interactive=False,
max_products=max_products.value,
)
elif satellite_type.value == "S1":
_spinner.update(title="Searching for Sentinel-1 products...")
# Sentinel-1 parameters:
# - product_type: GRD (Ground Range Detected = processed SAR)
# - polarization: VV,VH (dual-pol for better feature detection)
# - orbit_direction: ASCENDING (consistent viewing geometry)
downloaded_files = client.fetch_s1(
bbox=_bbox,
start_date=str(start_date.value),
end_date=str(end_date.value),
product_type="GRD",
polarization="VV,VH",
orbit_direction="ASCENDING",
download_data=True,
max_products=max_products.value,
)
else: # S1+S2
_spinner.update(title="Searching for Sentinel-2 products...")
# Download S2 first
_s2_files = client.fetch_s2(
bbox=_bbox,
start_date=str(start_date.value),
end_date=str(end_date.value),
resolution=10,
max_cloud_cover=30,
product_type="S2MSI2A",
download_data=True,
interactive=False,
max_products=max_products.value,
)
_spinner.update(title="Searching for Sentinel-1 products...")
# Download S1 second
_s1_files = client.fetch_s1(
bbox=_bbox,
start_date=str(start_date.value),
end_date=str(end_date.value),
product_type="GRD",
polarization="VV,VH",
orbit_direction="ASCENDING",
download_data=True,
max_products=max_products.value,
)
# Store both as a dict for later use
downloaded_files = {"s2": _s2_files, "s1": _s1_files}
finally:
# Restore stdout
sys.stdout = _old_stdout
_captured_output = _stdout_capture.getvalue()
# Try to get total available from cache file
# The cache stores all products found, not just the ones downloaded
_total_available = None
try:
import json
from src.data.copernicus.utils import build_cache_key
_cache_key = build_cache_key(
"s2" if satellite_type.value == "S2" else "s1",
bbox=_bbox,
start_date=str(start_date.value),
end_date=str(end_date.value),
resolution=10 if satellite_type.value == "S2" else None,
max_cloud_cover=30 if satellite_type.value == "S2" else None,
product_type="S2MSI2A" if satellite_type.value == "S2" else "GRD",
download_data=True,
max_products=max_products.value,
polarization="VV,VH" if satellite_type.value == "S1" else None,
orbit_direction="ASCENDING" if satellite_type.value == "S1" else None,
)
_cache_file = client.cache_dir / f"{_cache_key}.json"
if _cache_file.exists():
with open(_cache_file) as _f:
_cache_data = json.load(_f)
_all_products = _cache_data.get("products", [])
_total_available = len(_all_products)
except Exception as _e:
# If cache reading fails, try parsing stdout
for _line in _captured_output.split("\n"):
if "Found" in _line and "products" in _line:
import re as _re
_match = _re.search(r"Found (\d+)", _line)
if _match:
_total_available = int(_match.group(1))
break
# Check if we got any files
if satellite_type.value == "S1+S2":
# Handle S1+S2 case
_s2_count = (
len(downloaded_files.get("s2", []))
if isinstance(downloaded_files, dict)
else 0
)
_s1_count = (
len(downloaded_files.get("s1", []))
if isinstance(downloaded_files, dict)
else 0
)
if _s2_count > 0 or _s1_count > 0:
_spinner.update(title="Download complete!")
download_result += f"""
✅ **Downloaded S1+S2 products!**
- **S2 (Optical)**: {_s2_count} product(s)
- **S1 (Radar)**: {_s1_count} product(s)
Files are cached in `data/cache/copernicus/` for future use.
*Note: Visualization will show S2 images. Use "Export Time Series for Galileo" to export both.*
"""
else:
download_result += """
⚠️ **No products found**
Try adjusting your search parameters:
- Expand the date range
- Try a different location
- For S2, try a different time of year (less clouds)
"""
elif downloaded_files and len(downloaded_files) > 0:
_spinner.update(title="Download complete!")
# Show total available vs downloaded
if _total_available is not None and _total_available > len(
downloaded_files
):
download_result += f"""
✅ **Downloaded {len(downloaded_files)} of {_total_available} available product(s)!**
*Note: {_total_available - len(downloaded_files)} additional product(s) available. Increase "Max Products" to download more.*
Files are cached in `data/cache/copernicus/` for future use.
**Downloaded files:**
"""
elif _total_available is not None:
download_result += f"""
✅ **Downloaded all {len(downloaded_files)} available product(s)!**
Files are cached in `data/cache/copernicus/` for future use.
**Downloaded files:**
"""
else:
download_result += f"""
✅ **Downloaded {len(downloaded_files)} product(s)!**
Files are cached in `data/cache/copernicus/` for future use.
**Downloaded files:**
"""
for _f in downloaded_files:
# Show just the filename, not full path
download_result += f"\n- `{_f.name}`"
else:
download_result += """
⚠️ **No products found**
Try adjusting your search parameters:
- Expand the date range
- Try a different location
- For S2, try a different time of year (less clouds)
"""
except ValueError:
# Validation error (already set download_result above)
pass
except Exception as e:
# Handle any other errors
_error_msg = str(e)
download_result = f"""
❌ **Error during search/download**
{_error_msg}
**Common issues:**
- Check your internet connection
- Verify your credentials are correct
- Try a smaller area or fewer products
- Check console for detailed error trace
"""
# Print full traceback to console for debugging
print("Error details:")
print(traceback.format_exc())
# Display the result message
mo.md(download_result) if download_result else None
return (downloaded_files,)
@app.cell
def _(
crop_to_bbox,
datetime,
downloaded_files,
max_lat,
max_lon,
min_lat,
min_lon,
mo,
satellite_type,
):
"""Create time slider and pre-process all images for fast rendering.
This cell:
1. Extracts dates from filenames and creates metadata
2. Pre-processes ALL images into memory (cached)
3. Runs quality assessment (S1: invalid pixels / border noise, S2: cloud/shadow)
4. Creates slider widget for navigation
Pre-processing happens once, making slider interactions instant.
For S1+S2 mode: Both S1 and S2 tiles are processed, quality-checked, and
shown in the viewer sorted by date. Each tile carries its own badge.
"""
time_slider = None
file_metadata = []
cached_images = []
# Build a list of (file_path, sat_type) tuples to process
_work_items = []
if satellite_type.value == "S1+S2":
if isinstance(downloaded_files, dict):
for _f in downloaded_files.get("s2", []):
_work_items.append((_f, "S2"))
for _f in downloaded_files.get("s1", []):
_work_items.append((_f, "S1"))
elif (
satellite_type.value == "S2"
and downloaded_files
and not isinstance(downloaded_files, dict)
):
for _f in downloaded_files:
_work_items.append((_f, "S2"))
elif (
satellite_type.value == "S1"
and downloaded_files
and not isinstance(downloaded_files, dict)
):
for _f in downloaded_files:
_work_items.append((_f, "S1"))
if _work_items:
# Show progress while pre-processing
with mo.status.spinner(title="Pre-processing images for fast slider...") as _spinner:
import re
# Get bbox for optional cropping
_bbox = [min_lon.value, min_lat.value, max_lon.value, max_lat.value]
_use_bbox = crop_to_bbox.value # User's choice
# Import quality functions
from src.data.copernicus.quality import (
assess_s1_quality,
assess_s2_quality,
)
# Extract dates and pre-process images
for _idx, (_file_path, _sat) in enumerate(_work_items):
_spinner.update(title=f"Processing {_sat} image {_idx + 1}/{len(_work_items)}...")
_filename = _file_path.name
# Extract date from filename
_date_match = re.search(r"(\d{8}T\d{6})", _filename)
if _date_match:
_date_str = _date_match.group(1)
_date_obj = datetime.strptime(_date_str, "%Y%m%dT%H%M%S")
_date_display = _date_obj.strftime("%Y-%m-%d %H:%M")
else:
_date_obj = None
_date_display = "Unknown date"
# Pre-process the image based on satellite type
_processed_data = None
try:
if _sat == "S2":
from src.data.copernicus.image_processing import extract_rgb_composite
_processed_data = extract_rgb_composite(
_file_path, bbox=_bbox if _use_bbox else None
)
else:
from src.data.copernicus.image_processing import extract_sar_composite
_processed_data = extract_sar_composite(
_file_path,
polarizations=["VV"],
bbox=_bbox if _use_bbox else None,
)
if (
_processed_data is not None
and _processed_data.get("bounds_wgs84") is not None
):
# --- Quality assessment ---
_quality_report = None
_spinner.update(
title=f"Quality check {_sat} {_idx + 1}/{len(_work_items)}..."
)
if _sat == "S1":
_quality_report = assess_s1_quality(_file_path)
else:
_quality_report = assess_s2_quality(_file_path)
# Store metadata and cached image data
file_metadata.append(
{
"path": _file_path,
"date": _date_obj,
"date_str": _date_display,
"filename": _filename,
"sat_type": _sat,
"quality_report": _quality_report,
}
)
cached_images.append(_processed_data)
else:
print(f"Warning: Failed to process {_filename} (missing bounds or data)")
except Exception as _e:
print(f"Error processing {_filename}: {_e}")
import traceback as _tb
_tb.print_exc()
continue
_spinner.update(title="Processing complete!")
# Sort by date (oldest first) - sort both lists together
if file_metadata:
_sorted_pairs = sorted(
zip(file_metadata, cached_images),
key=lambda x: x[0]["date"] if x[0]["date"] else datetime.min,
)
file_metadata, cached_images = (
[x[0] for x in _sorted_pairs],
[x[1] for x in _sorted_pairs],
)
# Create slider if we have multiple files
if len(file_metadata) > 1:
time_slider = mo.ui.slider(
start=0,
stop=len(file_metadata) - 1,
step=1,
value=0,
label=f"Time Step (1 of {len(file_metadata)})",
show_value=False,
)
return cached_images, file_metadata, time_slider
@app.cell
def _(cached_images, mo, satellite_type):
"""Create band recipe selector (independent of time slider to maintain state)."""
band_recipe_selector = None
if cached_images and len(cached_images) > 0:
from src.data.copernicus.band_recipes import get_available_recipes
_recipes = get_available_recipes()
# Filter recipes based on satellite type
if satellite_type.value == "S2":
# S2: Show optical recipes only
_recipe_names = [r.name for rid, r in _recipes.items() if not rid.startswith("sar_")]
elif satellite_type.value == "S1":
# S1: Show SAR recipes only
_recipe_names = [r.name for rid, r in _recipes.items() if rid.startswith("sar_")]
else: # S1+S2
# S1+S2: Show all recipes (both optical and SAR tiles are in the viewer)
_recipe_names = [r.name for rid, r in _recipes.items()]
if _recipe_names:
band_recipe_selector = mo.ui.dropdown(
options=_recipe_names,
label="Band Recipe",
)
return (band_recipe_selector,)
@app.cell
def _(cached_images, file_metadata, mo):
"""Create quality threshold sliders (separate cell so they don't reset on interaction)."""
s2_quality_threshold = None
s1_quality_threshold = None
s2_nodata_threshold = None
if cached_images and len(cached_images) > 0:
# Check which satellite types are present
_has_s2 = any(m.get("sat_type") == "S2" for m in file_metadata)
_has_s1 = any(m.get("sat_type") == "S1" for m in file_metadata)
if _has_s2:
s2_quality_threshold = mo.ui.slider(
start=0,
stop=100,
step=5,
value=50,
label="S2 min usable % (cloud/shadow filter)",
show_value=True,
)
s2_nodata_threshold = mo.ui.slider(
start=0,
stop=100,
step=5,
value=20,
label="S2 max nodata % (data gap filter)",
show_value=True,
)
if _has_s1:
s1_quality_threshold = mo.ui.slider(
start=0,
stop=100,
step=5,
value=50,
label="S1 min usable % (invalid pixel filter)",
show_value=True,
)
return (s1_quality_threshold, s2_nodata_threshold, s2_quality_threshold)
@app.cell
def _(
band_recipe_selector,
cached_images,
file_metadata,
mo,
s1_quality_threshold,
s2_nodata_threshold,
s2_quality_threshold,
time_slider,
):
"""Display time slider, quality filter, and adjustment sliders."""
slider_display = None
contrast_slider = None
brightness_slider = None
gamma_slider = None
filtered_indices = []
if cached_images and len(cached_images) > 0:
# Compute filtered indices — each sat type uses its own thresholds
_s2_thresh = s2_quality_threshold.value if s2_quality_threshold is not None else 0
_s1_thresh = s1_quality_threshold.value if s1_quality_threshold is not None else 0
_s2_nodata_max = s2_nodata_threshold.value if s2_nodata_threshold is not None else 100
for _i, _meta in enumerate(file_metadata):
_qr = _meta.get("quality_report")
if _qr is None:
filtered_indices.append(_i)
continue
_sat = _meta.get("sat_type", "S2")
if _sat == "S2":
# S2: check usable % AND nodata %
_nodata_total = _qr.get("nodata_pct", 0) + _qr.get("defective_pct", 0)
if _qr["usable_pct"] >= _s2_thresh and _nodata_total <= _s2_nodata_max:
filtered_indices.append(_i)
else:
# S1: check usable % only
if _qr["usable_pct"] >= _s1_thresh:
filtered_indices.append(_i)
_total = len(file_metadata)
_kept = len(filtered_indices)
_removed = _total - _kept
# Create adjustment sliders
contrast_slider = mo.ui.slider(
start=0,
stop=100,
step=1,
value=50,
label="Contrast",
show_value=True,
)
brightness_slider = mo.ui.slider(
start=0,
stop=100,
step=1,
value=50,
label="Brightness",
show_value=True,
)
gamma_slider = mo.ui.slider(
start=0,