Untitled
unknown
plain_text
4 months ago
3.8 kB
11
No Index
import ee
import json
from datetime import datetime, timedelta
import time
def get_metadata_for_s1_product(product_id, download_to_drive=False):
try:
ee.Initialize()
print("Earth Engine initialized successfully using stored credentials.")
except Exception:
try:
service_account = 'xxx@xxx.iam.gserviceaccount.com'
credentials = ee.ServiceAccountCredentials(service_account, 'xxx.json')
ee.Initialize(credentials)
print("Earth Engine initialized successfully using service account.")
except Exception as e:
print(f"Error initializing Earth Engine: {e}")
print(
"Please ensure you have authenticated via 'earthengine authenticate' or provided a valid service account key.")
return
# Example ID: S1A_EW_GRDM_1SSH_20160128T011137_20160128T011242_009687_00E225_B7E5
# The start time is the 5th element (index 4)
start_time_str = product_id.split('_')[4]
start_date = datetime.strptime(start_time_str, '%Y%m%dT%H%M%S')
end_date = start_date + timedelta(seconds=1)
print(f"Searching for product ID around start time: {start_date.isoformat()}Z")
# --- 3. Query Earth Engine ---
# Define the collection
collection = ee.ImageCollection('COPERNICUS/S1_GRD')
# Filter by the exact product ID (most efficient method)
image = collection.filter(ee.Filter.eq('system:index', product_id)).first()
# Retrieve the image information as a dictionary
image_info = image.getInfo()
if image_info:
print(f"\nSuccessfully found metadata for: {product_id}")
# Pretty-print the properties dictionary
metadata = image_info.get('properties', {})
print(json.dumps(metadata, indent=2))
else:
print(f"\n--- BUG REPRODUCED? ---")
print(f"No metadata found for product ID: {product_id}")
print("This could indicate the asset is not indexed as expected in the GEE collection.")
if download_to_drive:
band_to_export = image.bandNames().get(0).getInfo()
print(f"Exporting the first available band: '{band_to_export}'")
region = image.geometry()
task_config = {
'image': image.select([band_to_export]),
'description': f'Export_{product_id}', # The name of the task
'folder': "download_test", # The folder in your Google Drive
'fileNamePrefix': product_id, # The name of the output file
'scale': 1000,
'region': region,
'fileFormat': 'GeoTIFF',
'maxPixels': 1e10
}
# Start the export task
task = ee.batch.Export.image.toDrive(**task_config)
task.start()
print("\n--- Export Task Started ---")
print(f"Task ID: {task.id}")
print(f"Description: {task_config['description']}")
print("You can monitor the progress in the 'Tasks' tab of the Earth Engine Code Editor:")
print("https://code.earthengine.google.com/tasks")
# Wait for the task to complete and provide status updates
while task.active():
print("Task is running...")
time.sleep(30) # Check status every 30 seconds
final_status = task.status()['state']
print(f"--- Task Finished ---")
print(f"Final Status: {final_status}")
if final_status == 'COMPLETED':
print("✅ Export completed successfully! Check your Google Drive.")
else:
print(f"❌ Task failed or was canceled. Last message: {task.status().get('error_message', 'N/A')}")
if __name__ == "__main__":
get_metadata_for_s1_product("S1A_IW_GRDH_1SSH_20141217T050718_20141217T050747_003754_00479E_ED6D")Editor is loading...
Leave a Comment