Spaces:
Sleeping
Sleeping
File size: 2,165 Bytes
a359779 |
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 |
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
|