Skip to content

Commit

Permalink
Simplify ee_initialize function (gee-community#2162)
Browse files Browse the repository at this point in the history
* Simplify ee_initialize function

* Skip ee_initialize when not needed

* Remove ee.data import
  • Loading branch information
giswqs authored Nov 2, 2024
1 parent b67d678 commit 41d7d02
Showing 1 changed file with 24 additions and 63 deletions.
87 changes: 24 additions & 63 deletions geemap/coreutils.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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)
Expand All @@ -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")
Expand All @@ -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(
Expand Down

0 comments on commit 41d7d02

Please sign in to comment.