SmartCane/python_app/experiments/test_sar_download.py
2025-09-05 15:23:41 +02:00

146 lines
4.4 KiB
Python

#!/usr/bin/env python3
"""
Quick Test Script for SAR Download
==================================
This is a simplified test version to verify the setup works before running the full download.
Usage:
python test_sar_download.py
This will:
1. Test SentinelHub connection
2. Load field boundaries
3. Download 1 week of SAR data for testing
4. Save to test directory
"""
import os
import sys
from pathlib import Path
import logging
# Import our main downloader
from download_s1_aura import SARDownloader
# Configure logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
def test_connection():
"""Test SentinelHub connection and credentials"""
try:
from sentinelhub import SHConfig
config = SHConfig()
config.sh_client_id = '1a72d811-4f0e-4447-8282-df09608cff44'
config.sh_client_secret = 'FcBlRL29i9ZmTzhmKTv1etSMFs5PxSos'
logger.info("OK - SentinelHub credentials configured")
logger.info(f"OK - Client ID: {config.sh_client_id[:8]}...")
return True
except Exception as e:
logger.error(f"✗ Connection test failed: {e}")
return False
def test_field_boundaries():
"""Test loading field boundaries"""
try:
import geopandas as gpd
# Try to load the pivot.geojson file
geojson_path = "pivot.geojson"
if not os.path.exists(geojson_path):
geojson_path = "../pivot.geojson"
if os.path.exists(geojson_path):
gdf = gpd.read_file(geojson_path)
bounds = gdf.total_bounds
logger.info(f"OK - Field boundaries loaded: {geojson_path}")
logger.info(f"OK - {len(gdf)} fields found")
logger.info(f"OK - Bounds: {bounds}")
return True, gdf
else:
logger.error("✗ Could not find pivot.geojson file")
return False, None
except Exception as e:
logger.error(f"✗ Field boundary test failed: {e}")
return False, None
def test_quick_download():
"""Download 1 week of SAR data for testing"""
try:
# Create test output directory
test_dir = Path("test_sar_output")
test_dir.mkdir(exist_ok=True)
# Initialize downloader with test directory
downloader = SARDownloader(output_dir=test_dir)
# Load field boundaries
fields = downloader.load_field_boundaries()
# Download just 1 week of data (current week)
from datetime import datetime, timedelta
end_date = datetime.now()
start_date = end_date - timedelta(days=7)
logger.info(f"Testing download for: {start_date.strftime('%Y-%m-%d')} to {end_date.strftime('%Y-%m-%d')}")
# Download 1 week
downloader.download_weekly_sar(start_date, end_date)
# Check if files were created
tif_files = list(test_dir.glob("*.tif"))
if tif_files:
logger.info(f"OK - Test download successful! {len(tif_files)} files created")
for f in tif_files:
logger.info(f" - {f.name}")
return True
else:
logger.warning("ERROR - No files downloaded - check SentinelHub quota/permissions")
return False
except Exception as e:
logger.error(f"✗ Test download failed: {e}")
return False
def main():
"""Run all tests"""
logger.info("=== SAR Download Test Suite ===\n")
# Test 1: Connection
logger.info("1. Testing SentinelHub connection...")
if not test_connection():
logger.error("Connection test failed - check credentials")
return False
# Test 2: Field boundaries
logger.info("\n2. Testing field boundaries...")
success, fields = test_field_boundaries()
if not success:
logger.error("Field boundary test failed")
return False
# Test 3: Quick download
logger.info("\n3. Testing SAR download (1 week)...")
if not test_quick_download():
logger.error("Download test failed")
return False
logger.info("\n=== All Tests Passed! ===")
logger.info("You can now run the full download script:")
logger.info("python download_s1_aura.py")
return True
if __name__ == "__main__":
success = main()
sys.exit(0 if success else 1)