Spaces:
Sleeping
Sleeping
| import ee | |
| import os | |
| import json | |
| def initialize_gee(): | |
| """Initialize Google Earth Engine with service account from env""" | |
| try: | |
| # Local development - JSON file | |
| if os.path.exists('gee-service-account.json'): | |
| SERVICE_ACCOUNT = 'gee-access@gee-research-project.iam.gserviceaccount.com' | |
| credentials = ee.ServiceAccountCredentials( | |
| SERVICE_ACCOUNT, | |
| 'gee-service-account.json' | |
| ) | |
| ee.Initialize(credentials) | |
| print("β GEE authenticated (local file)") | |
| return True | |
| # Cloud Run - full JSON key as secret | |
| gee_key_json = os.getenv('GEE_SERVICE_ACCOUNT_KEY') | |
| if gee_key_json: | |
| # Parse JSON credentials | |
| key_dict = json.loads(gee_key_json) | |
| credentials = ee.ServiceAccountCredentials( | |
| email=key_dict['client_email'], | |
| key_data=gee_key_json | |
| ) | |
| ee.Initialize(credentials) | |
| print("β GEE authenticated (Cloud Run secret)") | |
| return True | |
| # Fallback to split-key format (Render compatibility) | |
| service_account = os.getenv('GEE_SERVICE_ACCOUNT') | |
| private_key_json = os.getenv('GEE_PRIVATE_KEY') | |
| if service_account and private_key_json: | |
| # Clean up private key formatting | |
| if private_key_json.startswith('"'): | |
| private_key = private_key_json.strip('"').replace('\\n', '\n') | |
| else: | |
| private_key = private_key_json.replace('\\n', '\n') | |
| credentials = ee.ServiceAccountCredentials( | |
| email=service_account, | |
| key_data=private_key | |
| ) | |
| ee.Initialize(credentials) | |
| print("β GEE authenticated (split credentials)") | |
| return True | |
| raise ValueError("No GEE credentials found - set GEE_SERVICE_ACCOUNT_KEY or use local JSON file") | |
| except Exception as e: | |
| print(f"β GEE authentication failed: {e}") | |
| return False | |