From 41d7d026e6e557696189b333a183d80dc31afcc4 Mon Sep 17 00:00:00 2001 From: Qiusheng Wu Date: Sat, 2 Nov 2024 16:47:55 -0400 Subject: [PATCH] Simplify ee_initialize function (#2162) * Simplify ee_initialize function * Skip ee_initialize when not needed * Remove ee.data import --- geemap/coreutils.py | 87 +++++++++++++-------------------------------- 1 file changed, 24 insertions(+), 63 deletions(-) diff --git a/geemap/coreutils.py b/geemap/coreutils.py index c5b9117ba6..0b5e8f0163 100644 --- a/geemap/coreutils.py +++ b/geemap/coreutils.py @@ -42,7 +42,6 @@ def get_env_var(key: str) -> Optional[str]: def ee_initialize( token_name: str = "EARTHENGINE_TOKEN", auth_mode: Optional[str] = None, - service_account: bool = False, auth_args: Optional[Dict[str, Any]] = None, user_agent_prefix: str = "geemap", project: Optional[str] = None, @@ -58,8 +57,6 @@ def ee_initialize( notebook, localhost, or gcloud. See https://developers.google.com/earth-engine/guides/auth for more details. Defaults to None. - service_account (bool, optional): If True, use a service account. - Defaults to False. auth_args (dict, optional): Additional authentication parameters for aa.Authenticate(). Defaults to {}. user_agent_prefix (str, optional): If set, the prefix (version-less) @@ -70,17 +67,33 @@ def ee_initialize( For example, opt_url='https://earthengine-highvolume.googleapis.com' to use the Earth Engine High-Volume platform. Defaults to {}. """ - import httplib2 + import google.oauth2.credentials from .__init__ import __version__ - if auth_args is None: - auth_args = {} - user_agent = f"{user_agent_prefix}/{__version__}" ee.data.setUserAgent(user_agent) - if "http_transport" not in kwargs: - kwargs["http_transport"] = httplib2.Http() + if ee.data._credentials is not None: + return + + ee_token = get_env_var(token_name) + if ee_token is not None: + + stored = json.loads(ee_token) + credentials = google.oauth2.credentials.Credentials( + None, + token_uri="https://oauth2.googleapis.com/token", + client_id=stored["client_id"], + client_secret=stored["client_secret"], + refresh_token=stored["refresh_token"], + quota_project_id=stored["project"], + ) + + ee.Initialize(credentials=credentials, **kwargs) + return + + if auth_args is None: + auth_args = {} if project is None: kwargs["project"] = get_env_var("EE_PROJECT_ID") @@ -97,60 +110,8 @@ def ee_initialize( auth_args["auth_mode"] = auth_mode - if ee.data._credentials is None: - ee_token = get_env_var(token_name) - if service_account: - try: - credential_file_path = os.path.expanduser( - "~/.config/earthengine/private-key.json" - ) - - if os.path.exists(credential_file_path): - with open(credential_file_path) as f: - token_dict = json.load(f) - else: - token_name = "EARTHENGINE_TOKEN" - ee_token = os.environ.get(token_name) - token_dict = json.loads(ee_token, strict=False) - service_account = token_dict["client_email"] - private_key = token_dict["private_key"] - - credentials = ee.ServiceAccountCredentials( - service_account, key_data=private_key - ) - ee.Initialize(credentials, **kwargs) - - except Exception as e: - raise Exception(e) - - else: - try: - if ee_token is not None: - credential_file_path = os.path.expanduser( - "~/.config/earthengine/credentials" - ) - if not os.path.exists(credential_file_path): - os.makedirs( - os.path.dirname(credential_file_path), exist_ok=True - ) - if ee_token.startswith("{") and ee_token.endswith( - "}" - ): # deals with token generated by new auth method (earthengine-api>=0.1.304). - token_dict = json.loads(ee_token) - with open(credential_file_path, "w") as f: - f.write(json.dumps(token_dict)) - else: - credential = ( - '{"refresh_token":"%s"}' % ee_token - ) # deals with token generated by old auth method. - with open(credential_file_path, "w") as f: - f.write(credential) - - ee.Initialize(**kwargs) - - except Exception: - ee.Authenticate(**auth_args) - ee.Initialize(**kwargs) + ee.Authenticate(**auth_args) + ee.Initialize(**kwargs) def get_info(