id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
12,138
import argparse import json import math import os import subprocess import time import zipfile from collections import Counter import requests The provided code snippet includes necessary dependencies for implementing the `get_artifacts_links` function. Write a Python function `def get_artifacts_links(worflow_run_id)` to solve the following problem: Get all artifact links from a workflow run Here is the function: def get_artifacts_links(worflow_run_id): """Get all artifact links from a workflow run""" url = f"https://api.github.com/repos/huggingface/transformers/actions/runs/{worflow_run_id}/artifacts?per_page=100" result = requests.get(url).json() artifacts = {} try: artifacts.update({artifact["name"]: artifact["archive_download_url"] for artifact in result["artifacts"]}) pages_to_iterate_over = math.ceil((result["total_count"] - 100) / 100) for i in range(pages_to_iterate_over): result = requests.get(url + f"&page={i + 2}").json() artifacts.update({artifact["name"]: artifact["archive_download_url"] for artifact in result["artifacts"]}) return artifacts except Exception as e: print("Unknown error, could not fetch links.", e) return {}
Get all artifact links from a workflow run
12,139
import argparse import json import math import os import subprocess import time import zipfile from collections import Counter import requests The provided code snippet includes necessary dependencies for implementing the `download_artifact` function. Write a Python function `def download_artifact(artifact_name, artifact_url, output_dir, token)` to solve the following problem: Download a GitHub Action artifact from a URL. The URL is of the from `https://api.github.com/repos/huggingface/transformers/actions/artifacts/{ARTIFACT_ID}/zip`, but it can't be used to download directly. We need to get a redirect URL first. See https://docs.github.com/en/rest/actions/artifacts#download-an-artifact Here is the function: def download_artifact(artifact_name, artifact_url, output_dir, token): """Download a GitHub Action artifact from a URL. The URL is of the from `https://api.github.com/repos/huggingface/transformers/actions/artifacts/{ARTIFACT_ID}/zip`, but it can't be used to download directly. We need to get a redirect URL first. See https://docs.github.com/en/rest/actions/artifacts#download-an-artifact """ # Get the redirect URL first cmd = f'curl -v -H "Accept: application/vnd.github+json" -H "Authorization: token {token}" {artifact_url}' output = subprocess.run(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) o = output.stdout.decode("utf-8") lines = o.splitlines() for line in lines: if line.startswith("< Location: "): redirect_url = line[len("< Location: ") :] r = requests.get(redirect_url, allow_redirects=True) p = os.path.join(output_dir, f"{artifact_name}.zip") open(p, "wb").write(r.content) break
Download a GitHub Action artifact from a URL. The URL is of the from `https://api.github.com/repos/huggingface/transformers/actions/artifacts/{ARTIFACT_ID}/zip`, but it can't be used to download directly. We need to get a redirect URL first. See https://docs.github.com/en/rest/actions/artifacts#download-an-artifact
12,140
import argparse import json import math import os import subprocess import time import zipfile from collections import Counter import requests def get_errors_from_single_artifact(artifact_zip_path, job_links=None): """Extract errors from a downloaded artifact (in .zip format)""" errors = [] failed_tests = [] job_name = None with zipfile.ZipFile(artifact_zip_path) as z: for filename in z.namelist(): if not os.path.isdir(filename): # read the file if filename in ["failures_line.txt", "summary_short.txt", "job_name.txt"]: with z.open(filename) as f: for line in f: line = line.decode("UTF-8").strip() if filename == "failures_line.txt": try: # `error_line` is the place where `error` occurs error_line = line[: line.index(": ")] error = line[line.index(": ") + len(": ") :] errors.append([error_line, error]) except Exception: # skip un-related lines pass elif filename == "summary_short.txt" and line.startswith("FAILED "): # `test` is the test method that failed test = line[len("FAILED ") :] failed_tests.append(test) elif filename == "job_name.txt": job_name = line if len(errors) != len(failed_tests): raise ValueError( f"`errors` and `failed_tests` should have the same number of elements. Got {len(errors)} for `errors` " f"and {len(failed_tests)} for `failed_tests` instead. The test reports in {artifact_zip_path} have some" " problem." ) job_link = None if job_name and job_links: job_link = job_links.get(job_name, None) # A list with elements of the form (line of error, error, failed test) result = [x + [y] + [job_link] for x, y in zip(errors, failed_tests)] return result The provided code snippet includes necessary dependencies for implementing the `get_all_errors` function. Write a Python function `def get_all_errors(artifact_dir, job_links=None)` to solve the following problem: Extract errors from all artifact files Here is the function: def get_all_errors(artifact_dir, job_links=None): """Extract errors from all artifact files""" errors = [] paths = [os.path.join(artifact_dir, p) for p in os.listdir(artifact_dir) if p.endswith(".zip")] for p in paths: errors.extend(get_errors_from_single_artifact(p, job_links=job_links)) return errors
Extract errors from all artifact files
12,141
import argparse import json import math import os import subprocess import time import zipfile from collections import Counter import requests The provided code snippet includes necessary dependencies for implementing the `reduce_by_error` function. Write a Python function `def reduce_by_error(logs, error_filter=None)` to solve the following problem: count each error Here is the function: def reduce_by_error(logs, error_filter=None): """count each error""" counter = Counter() counter.update([x[1] for x in logs]) counts = counter.most_common() r = {} for error, count in counts: if error_filter is None or error not in error_filter: r[error] = {"count": count, "failed_tests": [(x[2], x[0]) for x in logs if x[1] == error]} r = dict(sorted(r.items(), key=lambda item: item[1]["count"], reverse=True)) return r
count each error
12,142
import argparse import json import math import os import subprocess import time import zipfile from collections import Counter import requests def get_model(test): """Get the model name from a test method""" test = test.split("::")[0] if test.startswith("tests/models/"): test = test.split("/")[2] else: test = None return test The provided code snippet includes necessary dependencies for implementing the `reduce_by_model` function. Write a Python function `def reduce_by_model(logs, error_filter=None)` to solve the following problem: count each error per model Here is the function: def reduce_by_model(logs, error_filter=None): """count each error per model""" logs = [(x[0], x[1], get_model(x[2])) for x in logs] logs = [x for x in logs if x[2] is not None] tests = set([x[2] for x in logs]) r = {} for test in tests: counter = Counter() # count by errors in `test` counter.update([x[1] for x in logs if x[2] == test]) counts = counter.most_common() error_counts = {error: count for error, count in counts if (error_filter is None or error not in error_filter)} n_errors = sum(error_counts.values()) if n_errors > 0: r[test] = {"count": n_errors, "errors": error_counts} r = dict(sorted(r.items(), key=lambda item: item[1]["count"], reverse=True)) return r
count each error per model
12,143
import argparse import json import math import os import subprocess import time import zipfile from collections import Counter import requests def make_github_table(reduced_by_error): header = "| no. | error | status |" sep = "|-:|:-|:-|" lines = [header, sep] for error in reduced_by_error: count = reduced_by_error[error]["count"] line = f"| {count} | {error[:100]} | |" lines.append(line) return "\n".join(lines)
null
12,144
import argparse import json import math import os import subprocess import time import zipfile from collections import Counter import requests def make_github_table_per_model(reduced_by_model): header = "| model | no. of errors | major error | count |" sep = "|-:|-:|-:|-:|" lines = [header, sep] for model in reduced_by_model: count = reduced_by_model[model]["count"] error, _count = list(reduced_by_model[model]["errors"].items())[0] line = f"| {model} | {count} | {error[:60]} | {_count} |" lines.append(line) return "\n".join(lines)
null
12,145
import argparse import collections import importlib.util import os import re import tempfile import pandas as pd from datasets import Dataset from huggingface_hub import Repository def get_frameworks_table(): """ Generates a dataframe containing the supported auto classes for each model type, using the content of the auto modules. """ # Dictionary model names to config. config_maping_names = transformers_module.models.auto.configuration_auto.CONFIG_MAPPING_NAMES model_prefix_to_model_type = { config.replace("Config", ""): model_type for model_type, config in config_maping_names.items() } # Dictionaries flagging if each model prefix has a backend in PT/TF/Flax. pt_models = collections.defaultdict(bool) tf_models = collections.defaultdict(bool) flax_models = collections.defaultdict(bool) # Let's lookup through all transformers object (once) and find if models are supported by a given backend. for attr_name in dir(transformers_module): lookup_dict = None if _re_tf_models.match(attr_name) is not None: lookup_dict = tf_models attr_name = _re_tf_models.match(attr_name).groups()[0] elif _re_flax_models.match(attr_name) is not None: lookup_dict = flax_models attr_name = _re_flax_models.match(attr_name).groups()[0] elif _re_pt_models.match(attr_name) is not None: lookup_dict = pt_models attr_name = _re_pt_models.match(attr_name).groups()[0] if lookup_dict is not None: while len(attr_name) > 0: if attr_name in model_prefix_to_model_type: lookup_dict[model_prefix_to_model_type[attr_name]] = True break # Try again after removing the last word in the name attr_name = "".join(camel_case_split(attr_name)[:-1]) all_models = set(list(pt_models.keys()) + list(tf_models.keys()) + list(flax_models.keys())) all_models = list(all_models) all_models.sort() data = {"model_type": all_models} data["pytorch"] = [pt_models[t] for t in all_models] data["tensorflow"] = [tf_models[t] for t in all_models] data["flax"] = [flax_models[t] for t in all_models] # Now let's use the auto-mapping names to make sure processors = {} for t in all_models: if t in transformers_module.models.auto.processing_auto.PROCESSOR_MAPPING_NAMES: processors[t] = "AutoProcessor" elif t in transformers_module.models.auto.tokenization_auto.TOKENIZER_MAPPING_NAMES: processors[t] = "AutoTokenizer" elif t in transformers_module.models.auto.feature_extraction_auto.FEATURE_EXTRACTOR_MAPPING_NAMES: processors[t] = "AutoFeatureExtractor" else: # Default to AutoTokenizer if a model has nothing, for backward compatibility. processors[t] = "AutoTokenizer" data["processor"] = [processors[t] for t in all_models] return pd.DataFrame(data) def update_pipeline_and_auto_class_table(table): """ Update the table of model class to (pipeline_tag, auto_class) without removing old keys if they don't exist anymore. """ auto_modules = [ transformers_module.models.auto.modeling_auto, transformers_module.models.auto.modeling_tf_auto, transformers_module.models.auto.modeling_flax_auto, ] for pipeline_tag, model_mapping, auto_class in PIPELINE_TAGS_AND_AUTO_MODELS: model_mappings = [model_mapping, f"TF_{model_mapping}", f"FLAX_{model_mapping}"] auto_classes = [auto_class, f"TF_{auto_class}", f"Flax_{auto_class}"] # Loop through all three frameworks for module, cls, mapping in zip(auto_modules, auto_classes, model_mappings): # The type of pipeline may not exist in this framework if not hasattr(module, mapping): continue # First extract all model_names model_names = [] for name in getattr(module, mapping).values(): if isinstance(name, str): model_names.append(name) else: model_names.extend(list(name)) # Add pipeline tag and auto model class for those models table.update({model_name: (pipeline_tag, cls) for model_name in model_names}) return table The provided code snippet includes necessary dependencies for implementing the `update_metadata` function. Write a Python function `def update_metadata(token, commit_sha)` to solve the following problem: Update the metada for the Transformers repo. Here is the function: def update_metadata(token, commit_sha): """ Update the metada for the Transformers repo. """ with tempfile.TemporaryDirectory() as tmp_dir: repo = Repository( tmp_dir, clone_from="huggingface/transformers-metadata", repo_type="dataset", use_auth_token=token ) frameworks_table = get_frameworks_table() frameworks_dataset = Dataset.from_pandas(frameworks_table) frameworks_dataset.to_json(os.path.join(tmp_dir, "frameworks.json")) tags_dataset = Dataset.from_json(os.path.join(tmp_dir, "pipeline_tags.json")) table = { tags_dataset[i]["model_class"]: (tags_dataset[i]["pipeline_tag"], tags_dataset[i]["auto_class"]) for i in range(len(tags_dataset)) } table = update_pipeline_and_auto_class_table(table) # Sort the model classes to avoid some nondeterministic updates to create false update commits. model_classes = sorted(list(table.keys())) tags_table = pd.DataFrame( { "model_class": model_classes, "pipeline_tag": [table[m][0] for m in model_classes], "auto_class": [table[m][1] for m in model_classes], } ) tags_dataset = Dataset.from_pandas(tags_table) tags_dataset.to_json(os.path.join(tmp_dir, "pipeline_tags.json")) if repo.is_repo_clean(): print("Nothing to commit!") else: if commit_sha is not None: commit_message = ( f"Update with commit {commit_sha}\n\nSee: " f"https://github.com/huggingface/transformers/commit/{commit_sha}" ) else: commit_message = "Update" repo.push_to_hub(commit_message)
Update the metada for the Transformers repo.
12,146
import argparse import collections import importlib.util import os import re import tempfile import pandas as pd from datasets import Dataset from huggingface_hub import Repository transformers_module = spec.loader.load_module() PIPELINE_TAGS_AND_AUTO_MODELS = [ ("pretraining", "MODEL_FOR_PRETRAINING_MAPPING_NAMES", "AutoModelForPreTraining"), ("feature-extraction", "MODEL_MAPPING_NAMES", "AutoModel"), ("audio-classification", "MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES", "AutoModelForAudioClassification"), ("text-generation", "MODEL_FOR_CAUSAL_LM_MAPPING_NAMES", "AutoModelForCausalLM"), ("automatic-speech-recognition", "MODEL_FOR_CTC_MAPPING_NAMES", "AutoModelForCTC"), ("image-classification", "MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES", "AutoModelForImageClassification"), ("image-segmentation", "MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES", "AutoModelForImageSegmentation"), ("fill-mask", "MODEL_FOR_MASKED_LM_MAPPING_NAMES", "AutoModelForMaskedLM"), ("object-detection", "MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES", "AutoModelForObjectDetection"), ( "zero-shot-object-detection", "MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES", "AutoModelForZeroShotObjectDetection", ), ("question-answering", "MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES", "AutoModelForQuestionAnswering"), ("text2text-generation", "MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES", "AutoModelForSeq2SeqLM"), ("text-classification", "MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES", "AutoModelForSequenceClassification"), ("automatic-speech-recognition", "MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES", "AutoModelForSpeechSeq2Seq"), ( "table-question-answering", "MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING_NAMES", "AutoModelForTableQuestionAnswering", ), ("token-classification", "MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES", "AutoModelForTokenClassification"), ("multiple-choice", "MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES", "AutoModelForMultipleChoice"), ( "next-sentence-prediction", "MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING_NAMES", "AutoModelForNextSentencePrediction", ), ( "audio-frame-classification", "MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES", "AutoModelForAudioFrameClassification", ), ("audio-xvector", "MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES", "AutoModelForAudioXVector"), ( "document-question-answering", "MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES", "AutoModelForDocumentQuestionAnswering", ), ( "visual-question-answering", "MODEL_FOR_VISUAL_QUESTION_ANSWERING_MAPPING_NAMES", "AutoModelForVisualQuestionAnswering", ), ("image-to-text", "MODEL_FOR_FOR_VISION_2_SEQ_MAPPING_NAMES", "AutoModelForVision2Seq"), ( "zero-shot-image-classification", "_MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING_NAMES", "AutoModel", ), ("depth-estimation", "MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES", "AutoModelForDepthEstimation"), ] def check_pipeline_tags(): in_table = {tag: cls for tag, _, cls in PIPELINE_TAGS_AND_AUTO_MODELS} pipeline_tasks = transformers_module.pipelines.SUPPORTED_TASKS missing = [] for key in pipeline_tasks: if key not in in_table: model = pipeline_tasks[key]["pt"] if isinstance(model, (list, tuple)): model = model[0] model = model.__name__ if model not in in_table.values(): missing.append(key) if len(missing) > 0: msg = ", ".join(missing) raise ValueError( "The following pipeline tags are not present in the `PIPELINE_TAGS_AND_AUTO_MODELS` constant inside " f"`utils/update_metadata.py`: {msg}. Please add them!" )
null
12,147
import argparse import os import re PATH_TO_TRANSFORMERS = "src/transformers" def sort_imports(file, check_only=True): """ Sort `_import_structure` imports in `file`, `check_only` determines if we only check or overwrite. """ with open(file, encoding="utf-8") as f: code = f.read() if "_import_structure" not in code: return # Blocks of indent level 0 main_blocks = split_code_in_indented_blocks( code, start_prompt="_import_structure = {", end_prompt="if TYPE_CHECKING:" ) # We ignore block 0 (everything untils start_prompt) and the last block (everything after end_prompt). for block_idx in range(1, len(main_blocks) - 1): # Check if the block contains some `_import_structure`s thingy to sort. block = main_blocks[block_idx] block_lines = block.split("\n") # Get to the start of the imports. line_idx = 0 while line_idx < len(block_lines) and "_import_structure" not in block_lines[line_idx]: # Skip dummy import blocks if "import dummy" in block_lines[line_idx]: line_idx = len(block_lines) else: line_idx += 1 if line_idx >= len(block_lines): continue # Ignore beginning and last line: they don't contain anything. internal_block_code = "\n".join(block_lines[line_idx:-1]) indent = get_indent(block_lines[1]) # Slit the internal block into blocks of indent level 1. internal_blocks = split_code_in_indented_blocks(internal_block_code, indent_level=indent) # We have two categories of import key: list or _import_structu[key].append/extend pattern = _re_direct_key if "_import_structure" in block_lines[0] else _re_indirect_key # Grab the keys, but there is a trap: some lines are empty or jsut comments. keys = [(pattern.search(b).groups()[0] if pattern.search(b) is not None else None) for b in internal_blocks] # We only sort the lines with a key. keys_to_sort = [(i, key) for i, key in enumerate(keys) if key is not None] sorted_indices = [x[0] for x in sorted(keys_to_sort, key=lambda x: x[1])] # We reorder the blocks by leaving empty lines/comments as they were and reorder the rest. count = 0 reorderded_blocks = [] for i in range(len(internal_blocks)): if keys[i] is None: reorderded_blocks.append(internal_blocks[i]) else: block = sort_objects_in_import(internal_blocks[sorted_indices[count]]) reorderded_blocks.append(block) count += 1 # And we put our main block back together with its first and last line. main_blocks[block_idx] = "\n".join(block_lines[:line_idx] + reorderded_blocks + [block_lines[-1]]) if code != "\n".join(main_blocks): if check_only: return True else: print(f"Overwriting {file}.") with open(file, "w", encoding="utf-8") as f: f.write("\n".join(main_blocks)) def sort_imports_in_all_inits(check_only=True): failures = [] for root, _, files in os.walk(PATH_TO_TRANSFORMERS): if "__init__.py" in files: result = sort_imports(os.path.join(root, "__init__.py"), check_only=check_only) if result: failures = [os.path.join(root, "__init__.py")] if len(failures) > 0: raise ValueError(f"Would overwrite {len(failures)} files, run `make style`.")
null
12,148
import argparse import os import re PATH_TO_AUTO_MODULE = "src/transformers/models/auto" def sort_auto_mapping(fname, overwrite: bool = False): with open(fname, "r", encoding="utf-8") as f: content = f.read() lines = content.split("\n") new_lines = [] line_idx = 0 while line_idx < len(lines): if _re_intro_mapping.search(lines[line_idx]) is not None: indent = len(re.search(r"^(\s*)\S", lines[line_idx]).groups()[0]) + 8 # Start of a new mapping! while not lines[line_idx].startswith(" " * indent + "("): new_lines.append(lines[line_idx]) line_idx += 1 blocks = [] while lines[line_idx].strip() != "]": # Blocks either fit in one line or not if lines[line_idx].strip() == "(": start_idx = line_idx while not lines[line_idx].startswith(" " * indent + ")"): line_idx += 1 blocks.append("\n".join(lines[start_idx : line_idx + 1])) else: blocks.append(lines[line_idx]) line_idx += 1 # Sort blocks by their identifiers blocks = sorted(blocks, key=lambda x: _re_identifier.search(x).groups()[0]) new_lines += blocks else: new_lines.append(lines[line_idx]) line_idx += 1 if overwrite: with open(fname, "w", encoding="utf-8") as f: f.write("\n".join(new_lines)) elif "\n".join(new_lines) != content: return True def sort_all_auto_mappings(overwrite: bool = False): fnames = [os.path.join(PATH_TO_AUTO_MODULE, f) for f in os.listdir(PATH_TO_AUTO_MODULE) if f.endswith(".py")] diffs = [sort_auto_mapping(fname, overwrite=overwrite) for fname in fnames] if not overwrite and any(diffs): failures = [f for f, d in zip(fnames, diffs) if d] raise ValueError( f"The following files have auto mappings that need sorting: {', '.join(failures)}. Run `make style` to fix" " this." )
null
12,149
import argparse import collections import importlib.util import os import re PATH_TO_DOCS = "docs/source/en" def _find_text_in_file(filename, start_prompt, end_prompt): """ Find the text in `filename` between a line beginning with `start_prompt` and before `end_prompt`, removing empty lines. """ with open(filename, "r", encoding="utf-8", newline="\n") as f: lines = f.readlines() # Find the start prompt. start_index = 0 while not lines[start_index].startswith(start_prompt): start_index += 1 start_index += 1 end_index = start_index while not lines[end_index].startswith(end_prompt): end_index += 1 end_index -= 1 while len(lines[start_index]) <= 1: start_index += 1 while len(lines[end_index]) <= 1: end_index -= 1 end_index += 1 return "".join(lines[start_index:end_index]), start_index, end_index, lines def get_model_table_from_auto_modules(): """Generates an up-to-date model table from the content of the auto modules.""" # Dictionary model names to config. config_maping_names = transformers_module.models.auto.configuration_auto.CONFIG_MAPPING_NAMES model_name_to_config = { name: config_maping_names[code] for code, name in transformers_module.MODEL_NAMES_MAPPING.items() if code in config_maping_names } model_name_to_prefix = {name: config.replace("Config", "") for name, config in model_name_to_config.items()} # Dictionaries flagging if each model prefix has a slow/fast tokenizer, backend in PT/TF/Flax. slow_tokenizers = collections.defaultdict(bool) fast_tokenizers = collections.defaultdict(bool) pt_models = collections.defaultdict(bool) tf_models = collections.defaultdict(bool) flax_models = collections.defaultdict(bool) # Let's lookup through all transformers object (once). for attr_name in dir(transformers_module): lookup_dict = None if attr_name.endswith("Tokenizer"): lookup_dict = slow_tokenizers attr_name = attr_name[:-9] elif attr_name.endswith("TokenizerFast"): lookup_dict = fast_tokenizers attr_name = attr_name[:-13] elif _re_tf_models.match(attr_name) is not None: lookup_dict = tf_models attr_name = _re_tf_models.match(attr_name).groups()[0] elif _re_flax_models.match(attr_name) is not None: lookup_dict = flax_models attr_name = _re_flax_models.match(attr_name).groups()[0] elif _re_pt_models.match(attr_name) is not None: lookup_dict = pt_models attr_name = _re_pt_models.match(attr_name).groups()[0] if lookup_dict is not None: while len(attr_name) > 0: if attr_name in model_name_to_prefix.values(): lookup_dict[attr_name] = True break # Try again after removing the last word in the name attr_name = "".join(camel_case_split(attr_name)[:-1]) # Let's build that table! model_names = list(model_name_to_config.keys()) model_names.sort(key=str.lower) columns = ["Model", "Tokenizer slow", "Tokenizer fast", "PyTorch support", "TensorFlow support", "Flax Support"] # We'll need widths to properly display everything in the center (+2 is to leave one extra space on each side). widths = [len(c) + 2 for c in columns] widths[0] = max([len(name) for name in model_names]) + 2 # Build the table per se table = "|" + "|".join([_center_text(c, w) for c, w in zip(columns, widths)]) + "|\n" # Use ":-----:" format to center-aligned table cell texts table += "|" + "|".join([":" + "-" * (w - 2) + ":" for w in widths]) + "|\n" check = {True: "✅", False: "❌"} for name in model_names: prefix = model_name_to_prefix[name] line = [ name, check[slow_tokenizers[prefix]], check[fast_tokenizers[prefix]], check[pt_models[prefix]], check[tf_models[prefix]], check[flax_models[prefix]], ] table += "|" + "|".join([_center_text(l, w) for l, w in zip(line, widths)]) + "|\n" return table The provided code snippet includes necessary dependencies for implementing the `check_model_table` function. Write a Python function `def check_model_table(overwrite=False)` to solve the following problem: Check the model table in the index.rst is consistent with the state of the lib and maybe `overwrite`. Here is the function: def check_model_table(overwrite=False): """Check the model table in the index.rst is consistent with the state of the lib and maybe `overwrite`.""" current_table, start_index, end_index, lines = _find_text_in_file( filename=os.path.join(PATH_TO_DOCS, "index.mdx"), start_prompt="<!--This table is updated automatically from the auto modules", end_prompt="<!-- End table-->", ) new_table = get_model_table_from_auto_modules() if current_table != new_table: if overwrite: with open(os.path.join(PATH_TO_DOCS, "index.mdx"), "w", encoding="utf-8", newline="\n") as f: f.writelines(lines[:start_index] + [new_table] + lines[end_index:]) else: raise ValueError( "The model table in the `index.mdx` has not been updated. Run `make fix-copies` to fix this." )
Check the model table in the index.rst is consistent with the state of the lib and maybe `overwrite`.
12,150
import argparse import collections import importlib.util import os import re PATH_TO_DOCS = "docs/source/en" def _find_text_in_file(filename, start_prompt, end_prompt): """ Find the text in `filename` between a line beginning with `start_prompt` and before `end_prompt`, removing empty lines. """ with open(filename, "r", encoding="utf-8", newline="\n") as f: lines = f.readlines() # Find the start prompt. start_index = 0 while not lines[start_index].startswith(start_prompt): start_index += 1 start_index += 1 end_index = start_index while not lines[end_index].startswith(end_prompt): end_index += 1 end_index -= 1 while len(lines[start_index]) <= 1: start_index += 1 while len(lines[end_index]) <= 1: end_index -= 1 end_index += 1 return "".join(lines[start_index:end_index]), start_index, end_index, lines def get_onnx_model_list(): """ Return the list of models supporting ONNX. """ config_mapping = transformers_module.models.auto.configuration_auto.CONFIG_MAPPING model_names = config_mapping = transformers_module.models.auto.configuration_auto.MODEL_NAMES_MAPPING onnx_model_types = [model_type for model_type in config_mapping.keys() if has_onnx(model_type)] onnx_model_names = [model_names[model_type] for model_type in onnx_model_types] onnx_model_names.sort(key=lambda x: x.upper()) return "\n".join([f"- {name}" for name in onnx_model_names]) + "\n" The provided code snippet includes necessary dependencies for implementing the `check_onnx_model_list` function. Write a Python function `def check_onnx_model_list(overwrite=False)` to solve the following problem: Check the model list in the serialization.mdx is consistent with the state of the lib and maybe `overwrite`. Here is the function: def check_onnx_model_list(overwrite=False): """Check the model list in the serialization.mdx is consistent with the state of the lib and maybe `overwrite`.""" current_list, start_index, end_index, lines = _find_text_in_file( filename=os.path.join(PATH_TO_DOCS, "serialization.mdx"), start_prompt="<!--This table is automatically generated by `make fix-copies`, do not fill manually!-->", end_prompt="In the next two sections, we'll show you how to:", ) new_list = get_onnx_model_list() if current_list != new_list: if overwrite: with open(os.path.join(PATH_TO_DOCS, "serialization.mdx"), "w", encoding="utf-8", newline="\n") as f: f.writelines(lines[:start_index] + [new_list] + lines[end_index:]) else: raise ValueError("The list of ONNX-supported models needs an update. Run `make fix-copies` to fix this.")
Check the model list in the serialization.mdx is consistent with the state of the lib and maybe `overwrite`.
12,151
import argparse import json import os from tensorflow.core.protobuf.saved_model_pb2 import SavedModel REPO_PATH = "." INTERNAL_OPS = [ "Assert", "AssignVariableOp", "EmptyTensorList", "MergeV2Checkpoints", "ReadVariableOp", "ResourceGather", "RestoreV2", "SaveV2", "ShardedFilename", "StatefulPartitionedCall", "StaticRegexFullMatch", "VarHandleOp", ] def onnx_compliancy(saved_model_path, strict, opset): saved_model = SavedModel() onnx_ops = [] with open(os.path.join(REPO_PATH, "utils", "tf_ops", "onnx.json")) as f: onnx_opsets = json.load(f)["opsets"] for i in range(1, opset + 1): onnx_ops.extend(onnx_opsets[str(i)]) with open(saved_model_path, "rb") as f: saved_model.ParseFromString(f.read()) model_op_names = set() # Iterate over every metagraph in case there is more than one (a saved model can contain multiple graphs) for meta_graph in saved_model.meta_graphs: # Add operations in the graph definition model_op_names.update(node.op for node in meta_graph.graph_def.node) # Go through the functions in the graph definition for func in meta_graph.graph_def.library.function: # Add operations in each function model_op_names.update(node.op for node in func.node_def) # Convert to list, sorted if you want model_op_names = sorted(model_op_names) incompatible_ops = [] for op in model_op_names: if op not in onnx_ops and op not in INTERNAL_OPS: incompatible_ops.append(op) if strict and len(incompatible_ops) > 0: raise Exception(f"Found the following incompatible ops for the opset {opset}:\n" + incompatible_ops) elif len(incompatible_ops) > 0: print(f"Found the following incompatible ops for the opset {opset}:") print(*incompatible_ops, sep="\n") else: print(f"The saved model {saved_model_path} can properly be converted with ONNX.")
null
12,152
import argparse import os import re PATH_TO_TRANSFORMERS = "src/transformers" def create_dummy_files(backend_specific_objects=None): """Create the content of the dummy files.""" if backend_specific_objects is None: backend_specific_objects = read_init() # For special correspondence backend to module name as used in the function requires_modulename dummy_files = {} for backend, objects in backend_specific_objects.items(): backend_name = "[" + ", ".join(f'"{b}"' for b in backend.split("_and_")) + "]" dummy_file = "# This file is autogenerated by the command `make fix-copies`, do not edit.\n" dummy_file += "# flake8: noqa\n" dummy_file += "from ..utils import DummyObject, requires_backends\n\n" dummy_file += "\n".join([create_dummy_object(o, backend_name) for o in objects]) dummy_files[backend] = dummy_file return dummy_files The provided code snippet includes necessary dependencies for implementing the `check_dummies` function. Write a Python function `def check_dummies(overwrite=False)` to solve the following problem: Check if the dummy files are up to date and maybe `overwrite` with the right content. Here is the function: def check_dummies(overwrite=False): """Check if the dummy files are up to date and maybe `overwrite` with the right content.""" dummy_files = create_dummy_files() # For special correspondence backend to shortcut as used in utils/dummy_xxx_objects.py short_names = {"torch": "pt"} # Locate actual dummy modules and read their content. path = os.path.join(PATH_TO_TRANSFORMERS, "utils") dummy_file_paths = { backend: os.path.join(path, f"dummy_{short_names.get(backend, backend)}_objects.py") for backend in dummy_files.keys() } actual_dummies = {} for backend, file_path in dummy_file_paths.items(): if os.path.isfile(file_path): with open(file_path, "r", encoding="utf-8", newline="\n") as f: actual_dummies[backend] = f.read() else: actual_dummies[backend] = "" for backend in dummy_files.keys(): if dummy_files[backend] != actual_dummies[backend]: if overwrite: print( f"Updating transformers.utils.dummy_{short_names.get(backend, backend)}_objects.py as the main " "__init__ has new objects." ) with open(dummy_file_paths[backend], "w", encoding="utf-8", newline="\n") as f: f.write(dummy_files[backend]) else: raise ValueError( "The main __init__ has objects that are not present in " f"transformers.utils.dummy_{short_names.get(backend, backend)}_objects.py. Run `make fix-copies` " "to fix this." )
Check if the dummy files are up to date and maybe `overwrite` with the right content.
12,153
import argparse import glob import importlib.util import os import re import black from doc_builder.style_doc import style_docstrings_in_code TRANSFORMERS_PATH = "src/transformers" def is_copy_consistent(filename, overwrite=False): def check_model_list_copy(overwrite=False, max_per_line=119): def check_copies(overwrite: bool = False): all_files = glob.glob(os.path.join(TRANSFORMERS_PATH, "**/*.py"), recursive=True) diffs = [] for filename in all_files: new_diffs = is_copy_consistent(filename, overwrite) diffs += [f"- {filename}: copy does not match {d[0]} at line {d[1]}" for d in new_diffs] if not overwrite and len(diffs) > 0: diff = "\n".join(diffs) raise Exception( "Found the following copy inconsistencies:\n" + diff + "\nRun `make fix-copies` or `python utils/check_copies.py --fix_and_overwrite` to fix them." ) check_model_list_copy(overwrite=overwrite)
null
12,154
import argparse import glob import importlib.util import os import re import black from doc_builder.style_doc import style_docstrings_in_code FULL_COPIES = { "examples/tensorflow/question-answering/utils_qa.py": "examples/pytorch/question-answering/utils_qa.py", "examples/flax/question-answering/utils_qa.py": "examples/pytorch/question-answering/utils_qa.py", } def check_full_copies(overwrite: bool = False): diffs = [] for target, source in FULL_COPIES.items(): with open(source, "r", encoding="utf-8") as f: source_code = f.read() with open(target, "r", encoding="utf-8") as f: target_code = f.read() if source_code != target_code: if overwrite: with open(target, "w", encoding="utf-8") as f: print(f"Replacing the content of {target} by the one of {source}.") f.write(source_code) else: diffs.append(f"- {target}: copy does not match {source}.") if not overwrite and len(diffs) > 0: diff = "\n".join(diffs) raise Exception( "Found the following copy inconsistencies:\n" + diff + "\nRun `make fix-copies` or `python utils/check_copies.py --fix_and_overwrite` to fix them." )
null
12,155
import argparse import glob import importlib.util import os import re import black from doc_builder.style_doc import style_docstrings_in_code REPO_PATH = "." LOCALIZED_READMES = { # If the introduction or the conclusion of the list change, the prompts may need to be updated. "README.md": { "start_prompt": "🤗 Transformers currently provides the following architectures", "end_prompt": "1. Want to contribute a new model?", "format_model_list": ( "**[{title}]({model_link})** (from {paper_affiliations}) released with the paper {paper_title_link} by" " {paper_authors}.{supplements}" ), }, "README_zh-hans.md": { "start_prompt": "🤗 Transformers 目前支持如下的架构", "end_prompt": "1. 想要贡献新的模型?", "format_model_list": ( "**[{title}]({model_link})** (来自 {paper_affiliations}) 伴随论文 {paper_title_link} 由 {paper_authors}" " 发布。{supplements}" ), }, "README_zh-hant.md": { "start_prompt": "🤗 Transformers 目前支援以下的架構", "end_prompt": "1. 想要貢獻新的模型?", "format_model_list": ( "**[{title}]({model_link})** (from {paper_affiliations}) released with the paper {paper_title_link} by" " {paper_authors}.{supplements}" ), }, "README_ko.md": { "start_prompt": "🤗 Transformers는 다음 모델들을 제공합니다", "end_prompt": "1. 새로운 모델을 올리고 싶나요?", "format_model_list": ( "**[{title}]({model_link})** (from {paper_affiliations}) released with the paper {paper_title_link} by" " {paper_authors}.{supplements}" ), }, "README_es.md": { "start_prompt": "🤗 Transformers actualmente proporciona las siguientes arquitecturas", "end_prompt": "1. ¿Quieres aportar un nuevo modelo?", "format_model_list": ( "**[{title}]({model_link})** (from {paper_affiliations}) released with the paper {paper_title_link} by" " {paper_authors}.{supplements}" ), }, } transformers_module = spec.loader.load_module() def _find_text_in_file(filename, start_prompt, end_prompt): SPECIAL_MODEL_NAMES = { "Bert Generation": "BERT For Sequence Generation", "BigBird": "BigBird-RoBERTa", "Data2VecAudio": "Data2Vec", "Data2VecText": "Data2Vec", "Data2VecVision": "Data2Vec", "DonutSwin": "Donut", "Marian": "MarianMT", "OpenAI GPT-2": "GPT-2", "OpenAI GPT": "GPT", "Perceiver": "Perceiver IO", "ViT": "Vision Transformer (ViT)", } MODELS_NOT_IN_README = [ "BertJapanese", "Encoder decoder", "FairSeq Machine-Translation", "HerBERT", "RetriBERT", "Speech Encoder decoder", "Speech2Text", "Speech2Text2", "Vision Encoder decoder", "VisionTextDualEncoder", ] README_TEMPLATE = ( "1. **[{model_name}](https://huggingface.co/docs/main/transformers/model_doc/{model_type})** (from " "<FILL INSTITUTION>) released with the paper [<FILL PAPER TITLE>](<FILL ARKIV LINK>) by <FILL AUTHORS>." ) def check_readme(overwrite=False): info = LOCALIZED_READMES["README.md"] models, start_index, end_index, lines = _find_text_in_file( os.path.join(REPO_PATH, "README.md"), info["start_prompt"], info["end_prompt"], ) models_in_readme = [re.search(r"\*\*\[([^\]]*)", line).groups()[0] for line in models.strip().split("\n")] model_names_mapping = transformers_module.models.auto.configuration_auto.MODEL_NAMES_MAPPING absents = [ (key, name) for key, name in model_names_mapping.items() if SPECIAL_MODEL_NAMES.get(name, name) not in models_in_readme ] # Remove exceptions absents = [(key, name) for key, name in absents if name not in MODELS_NOT_IN_README] if len(absents) > 0 and not overwrite: print(absents) raise ValueError( "The main README doesn't contain all models, run `make fix-copies` to fill it with the missing model(s)" " then complete the generated entries.\nIf the model is not supposed to be in the main README, add it to" " the list `MODELS_NOT_IN_README` in utils/check_copies.py.\nIf it has a different name in the repo than" " in the README, map the correspondence in `SPECIAL_MODEL_NAMES` in utils/check_copies.py." ) new_models = [README_TEMPLATE.format(model_name=name, model_type=key) for key, name in absents] all_models = models.strip().split("\n") + new_models all_models = sorted(all_models, key=lambda x: re.search(r"\*\*\[([^\]]*)", x).groups()[0].lower()) all_models = "\n".join(all_models) + "\n" if all_models != models: if overwrite: print("Fixing the main README.") with open(os.path.join(REPO_PATH, "README.md"), "w", encoding="utf-8", newline="\n") as f: f.writelines(lines[:start_index] + [all_models] + lines[end_index:]) else: raise ValueError("The main README model list is not properly sorted. Run `make fix-copies` to fix this.")
null
12,156
from typing import List, Dict, Any import argparse import gc import logging import os import re import time from collections import defaultdict, OrderedDict from glob import glob from pathlib import Path from tqdm import tqdm import torch from scripts.utils import load_and_pop_last_optimizer_state logger = logging.getLogger(__name__) def consolidate_shard_weights( shard_weights: List[Dict[str, torch.Tensor]], shard_metadata: List[Dict[str, Any]], with_module_buffers: bool = True, strict: bool = True, ) -> Dict[str, torch.Tensor]: def _get_shard_number(x) -> int: def consolidate_model_parallel_part1( metadata, names, strict, weights, parts=2, no_stitch_megatron=False ): def consolidate_model_parallel_part2(all_parts_consolidated): def find_num_parts(names) -> int: def load_and_pop_last_optimizer_state(pth): def consolidate_fsdp_shards( pth_prefix: str, save_prefix=None, strict=False, new_arch_name=None, no_stitch_megatron=False, megatron_part=None, ) -> str: if pth_prefix.endswith(".pt"): pth_prefix = pth_prefix[:-3] if save_prefix is None: save_prefix = pth_prefix + "_consolidated" # .pt' all_ckpt_files = list( sorted(glob(f"{pth_prefix}*shard*.pt"), key=_get_shard_number) ) if megatron_part is not None: no_stitch_megatron = True all_ckpt_files = [ x for x in all_ckpt_files if f"model_part-{megatron_part}" in x ] assert all_ckpt_files, f"no paths matched {pth_prefix}*shard*.pt" weights = [] metadata = [] expert_paths = [] expert_dest_paths = [] expert_ranks = [] names = [] dense = True t0 = time.time() for p in tqdm(all_ckpt_files): names.append(Path(p).name) if re.search(r"rank-(\d+)", os.path.basename(p)): # expert checkpoint expert_paths.append(p) r = re.search(r"rank-(\d+)", os.path.basename(p)).groups()[0] assert r not in expert_ranks expert_ranks.append(r) expert_dest_paths.append(f"{save_prefix}-rank-{r}.pt") else: ckpt = load_and_pop_last_optimizer_state(p) weights.append(ckpt["model"]) metadata.append(ckpt["shard_metadata"]) assert weights, f"all files were considered experts: {all_ckpt_files}" do_consolidate = True if "decoder.embed_tokens.weight" in weights[0].keys(): shape = weights[0]["decoder.embed_tokens.weight"].shape logger.info( f"This ckpt does not seem sharded. I see unflat params! like " f"decoder.embed_tokens.weight shaped {shape}. Will just copy files " f"and remove optim_state." ) do_consolidate = False if do_consolidate: num_parts = find_num_parts(names) if num_parts: #consolidated_weights = consolidate_model_parallel( # metadata, # names, # strict, # weights, # parts=num_parts, # no_stitch_megatron=no_stitch_megatron, #) print("- Part 1: consolidate Zero-3 shards.") consolidated_weights = consolidate_model_parallel_part1( metadata, names, strict, weights, parts=num_parts, no_stitch_megatron=no_stitch_megatron, ) del weights, metadata gc.collect() if not no_stitch_megatron: print("- Part 2: consolidate model-parallel parts.") consolidated_weights = consolidate_model_parallel_part2( consolidated_weights) else: print("FSDP.consolidate_shard_weights") consolidated_weights = consolidate_shard_weights( shard_weights=weights, shard_metadata=metadata, strict=strict ) #del weights, metadata #gc.collect() done_consolidate = time.time() print(f"Done consolidating after {done_consolidate-t0//60} minutes") else: consolidated_weights = weights[0] if new_arch_name is not None: ckpt["cfg"]["model"]._name = new_arch_name if dense: def save_checkpoint(weights_to_save, prefix): ckpt_consolidated = dict( model=weights_to_save, cfg=ckpt["cfg"], extra_state=ckpt["extra_state"], optimizer_history=ckpt["optimizer_history"], args=ckpt.get("args"), ) save_path = f"{prefix}.pt" print(f"- Saving to {save_path} ...") torch.save(ckpt_consolidated, save_path) print(f"Done saving after {(time.time() - t0) // 60} minutes") return save_path if no_stitch_megatron: saved_paths = [] for part_id, part_consolidated_weights in consolidated_weights.items(): saved_paths.append( save_checkpoint( part_consolidated_weights, f"{save_prefix}-model_part-{part_id}" ) ) return saved_paths return save_checkpoint(consolidated_weights, save_prefix) ckpt_shared = dict( model=consolidated_weights, cfg=ckpt["cfg"], extra_state=ckpt["extra_state"], optimizer_history=ckpt["optimizer_history"], args=ckpt["args"], ) print("saving..") torch.save(ckpt_shared, f"{save_prefix}-shared.pt") print(f"Done saving. Total time: {time.time()-t0//60} minutes, ") # Process experts for src, dst in tqdm( list(zip(expert_paths, expert_dest_paths)), desc="expert files" ): ckpt = load_and_pop_last_optimizer_state(src) if do_consolidate: expert_wt = consolidate_shard_weights( shard_weights=[ckpt["model"]], shard_metadata=[ckpt["shard_metadata"]], strict=False, ) ckpt = dict( model=expert_wt, cfg=ckpt["cfg"], extra_state=ckpt["extra_state"], optimizer_history=ckpt["optimizer_history"], args=ckpt["args"], ) torch.save(ckpt, dst) logger.info(f"saved consolidated MoE with prefix {save_prefix}.pt") return f"{save_prefix}.pt"
null
12,157
from typing import List, Dict, Any import argparse import gc import logging import os import re import time from collections import defaultdict, OrderedDict from glob import glob from pathlib import Path from tqdm import tqdm import torch from scripts.utils import load_and_pop_last_optimizer_state def consolidate_shard_weights( shard_weights: List[Dict[str, torch.Tensor]], shard_metadata: List[Dict[str, Any]], with_module_buffers: bool = True, strict: bool = True, ) -> Dict[str, torch.Tensor]: """ Given a list of weights and meta data associated to N shards, reconstruct the weights of an equivalent consolidated (non-sharded) state dict. Module parameters are consolidated using the shard metadata. Module buffers are taken from shard 0: this assumes that module buffers are either synchronized or that the shard 0 value is valid for all shards. If this behavior is not correct for your module (for instance if buffers needs to be all-reduced instead), you can disable it with `with_module_buffers=False`. This method is used to re-assemble checkpoints of shards without having to instantiate FSDP wrappers with the world size (i.e. large number of GPUs) originally used to save the shards. Args: shard_weights (List[Dict[str, torch.Tensor]]): List of dictionaries that contains sharded weights from each rank. shard_metadata (List[Dict[str, Any]]): List of dictionaries that contains metadata from each shard. See `local_metadata_dict` above. with_module_buffers (bool): If shard 0's buffer should be returned in the consolidated weight dict. Default: True. strict (bool): allow incomplete shard weights. if True, every key in the metadata must be present in the weights. """ if len(shard_weights) != len(shard_metadata) or not len(shard_weights): raise ValueError("Require metadata for each shard and non-empty shards") consolidated_weights = {} original_world_size = len(shard_weights) # For every FSDP instance. for fsdp_obj_idx, metadata in enumerate(shard_metadata[0]["param_metadata"]): fsdp_path = metadata["fsdp_path"] params = metadata["params"] # For every this-FSDP-owned param, flattened or not. for backing_param_name, v in params.items(): in_state_dict_key = ".".join([fsdp_path, backing_param_name]) if fsdp_path else backing_param_name # Get full param back with pad removed. if in_state_dict_key not in shard_weights[0] and (not strict): continue shards = [] for rank in range(original_world_size): shard = shard_weights[rank][in_state_dict_key] pad = shard_metadata[rank]["param_metadata"][fsdp_obj_idx]["params"][backing_param_name]["padding"] shards.append(_unpad(shard, pad)) if metadata["no_broadcast_optim_state"]: break full_param = torch.cat(shards, dim=0) # (Potentially), split the full param and create original params. names, shapes, numels, _ = v.values() assert sum(numels) == full_param.size(0) for n, t, s in zip(names, full_param.split(numels), shapes): out_state_dict_key = ".".join([fsdp_path, n]) if fsdp_path else n consolidated_weights[out_state_dict_key] = t.view(s) # copy shared parameters for src_path, dest_path in metadata["shared_param_info"]: consolidated_weights[dest_path] = consolidated_weights[src_path] # Deal with the buffers, which are not parameters and are not sharded by FSDP # and therefore are replicated among the different shards. # We take the values of the first shard (this assumes that there is some form # of synchronization between shards or that all shards buffers are equivalent). if with_module_buffers: for buffer_name in shard_metadata[0]["buffer_names"]: if buffer_name not in shard_weights[0] and (not strict): continue consolidated_weights[buffer_name] = shard_weights[0][buffer_name] return consolidated_weights def glue_megatron_parts(model_parts): glued_model = OrderedDict() def assert_all_close(key): for part_id in range(len(model_parts)): if not torch.allclose(model_parts[part_id][key], model_parts[0][key]): err = ( (model_parts[part_id][key] - model_parts[0][key]) .float() .abs() .max() .item() ) logger.info(f"max discrepancy {key}: {err}") for key in model_parts[0]: print(f"Glue the key {key}...") if "qkv" in key: # Bias of CP gets concatenated if key.endswith("bias"): k, v, q = handle_qkv_proj(model_parts, key) else: assert key.endswith("weight") k, v, q = handle_qkv_proj(model_parts, key) glued_model[key.replace("qkv", "k")] = k glued_model[key.replace("qkv", "v")] = v glued_model[key.replace("qkv", "q")] = q elif "ffn_layernorm" in key: glued_model[key] = torch.cat( [model_parts[part_id][key] for part_id in range(len(model_parts))] ) elif "layer_norm" in key: assert_all_close(key) glued_model[key] = model_parts[0][key] elif "fc1" in key or "k_proj" in key or "q_proj" in key or "v_proj" in key: # Bias of CP gets concatenated if key.endswith("bias"): glued_bias = torch.cat( [model_parts[part_id][key] for part_id in range(len(model_parts))] ) glued_model[key] = glued_bias # weights of CP gets concatenated along dim 0 else: assert key.endswith("weight") glued_weight = torch.cat( [model_parts[part_id][key] for part_id in range(len(model_parts))], dim=0, ) glued_model[key] = glued_weight # FC1 is CP # FC2 is RP elif "fc2" in key or "out_proj" in key: # Bias of RP gets replicated if key.endswith("bias"): assert_all_close(key) glued_model[key] = model_parts[0][key] # weights of RP gets concatenated along dim 1 else: assert key.endswith("weight") glued_weight = torch.cat( [model_parts[part_id][key] for part_id in range(len(model_parts))], dim=1, ) glued_model[key] = glued_weight elif "embed_tokens.weight" in key: glued_weight = torch.cat( [model_parts[part_id][key] for part_id in range(len(model_parts))], dim=0, ) glued_model[key] = glued_weight elif "embed_positions" in key: if "_float_tensor" in key: # Assume embed positions are non learned ie.e sinusoidal glued_model[key] = torch.zeros([1]) else: assert_all_close(key) glued_model[key] = model_parts[0][key] elif "version" in key: glued_model[key] = model_parts[0][key] else: assert_all_close(key) glued_model[key] = model_parts[0][key] assert len(glued_model.keys()) >= len(model_parts[0].keys()) # Consolidate ffn_layernorm.lns.weight.{part_id} -> ffn_layernorm.weight handle_legacy_ln_(glued_model, len(model_parts)) assert "decoder.layers.0.ffn_layernorm.lns.0.weight" not in glued_model print("- Done with consolidating model parallelism parts. See a summary below:") for key in glued_model: print(f" key: {key}, shape: {glued_model[key].shape}") return glued_model def consolidate_model_parallel( metadata, names, strict, weights, parts=2, no_stitch_megatron=False ): model_parts = defaultdict(list) metadata_parts = defaultdict(list) for i, n in enumerate(names): for p in range(parts): if f"part-{p}" in n: model_parts[p].append(weights[i]) metadata_parts[p].append(metadata[i]) all_parts_consolidated = defaultdict(list) for k, v in tqdm(model_parts.items()): print(f"Processing part: {k}, with {len(v)} shards...") part_weights = consolidate_shard_weights( shard_weights=v, shard_metadata=metadata_parts[k], strict=strict ) all_parts_consolidated[k] = part_weights if no_stitch_megatron: return all_parts_consolidated model = glue_megatron_parts(all_parts_consolidated) return model
null
12,158
import time import argparse import os import numpy as np from scripts.utils import torch_load_cpu def save_numpy(weight_dict, to_folder): os.makedirs(to_folder, exist_ok=True) for tensor_name, tensor in weight_dict.items(): print(f"- Writing tensor {tensor_name} with shape {tensor.shape}") t = tensor.cpu().detach().numpy() with open(to_folder + "/" + tensor_name, "wb") as g: np.save(g, t)
null
12,159
import argparse import dataclasses import math import numpy as np import pulp from flexgen.compression import CompressionConfig from flexgen.opt_config import get_opt_config from flexgen.flex_opt import Policy from flexgen.utils import GB, T alpha_g = 0.8 alpha_c = 0.8 alpha_n = 0.8 def solve(config, solve_lp, args): # # debug # code = [] # policies = [] # throughputs = [] # for nb in range(1, 240, 5): # gbs = 8 # bls = gbs * nb # status, policy, throughput, _ = solve_lp(config, bls, gbs, verbose=0) # code.append(status) # policies.append(policy) # throughputs.append(throughput) # print(code) # print(policies[-3:]) # print(["{0:0.2f}".format(x[0]) for x in throughputs]) debug = False if args["wg"] or args["wc"] or args["cg"] or \ args["cc"] or args["hg"] or args["hc"]: debug = True percent = [args["wg"], args["wc"], args["cg"], args["cc"], args["hg"], args["hc"]] if args["percent"] is not None: debug = True percent = args["percent"] compress_w = args["compress_w"] best_policy = None max_throughput = 0 gbs = 1 while True: if args["gbs"] is not None: gbs = args["gbs"] if args["num_gb"] is not None: status, policy, (throughput, _, _), _ = solve_lp( config, gbs * args["num_gb"], gbs, compress_w=compress_w, verbose=0, debug=debug, percent=percent) if status == -1: break if status == 1: best_policy, max_throughput = best(best_policy, max_throughput, policy, throughput) else: nb_ub = get_nb_ub(config, gbs, solve_lp, compress_w=compress_w, debug=debug, percent=percent) if nb_ub == 0: break prev_throughput = 0 for nb in range(1, nb_ub + 1): _, policy, (throughput, _, _), _ = solve_lp(config, gbs * nb, gbs, compress_w=compress_w, verbose=0, debug=debug, percent=percent) if throughput < prev_throughput: break prev_throughput = throughput best_policy, max_throughput = best(best_policy, max_throughput, policy, throughput) if args["gbs"] is not None: break if gbs < 4: gbs += 1 else: gbs *= 2 if best_policy is not None: _, _, _, _ = solve_lp(config, best_policy.gpu_batch_size * best_policy.num_gpu_batches, best_policy.gpu_batch_size, compress_w=compress_w, verbose=True, debug=debug, percent=percent) return best_policy, max_throughput class CompressionConfig: """Group-wise quantization.""" num_bits: int group_size: int group_dim: int symmetric: bool enabled: bool = True class Policy: gpu_batch_size: int num_gpu_batches: int # percent = a means a% w_gpu_percent: float w_cpu_percent: float cache_gpu_percent: float cache_cpu_percent: float act_gpu_percent: float act_cpu_percent: float # Whether to overlap the I/O and compute overlap: bool # Whether to separate attention and mlp as two layers sep_layer: bool # Whether to use pinned memory for weights on CPU pin_weight: bool # Whether to compute attention on CPU cpu_cache_compute: bool # Sparsity of attention weights attn_sparsity: float # Compress weights with group-wise quantization compress_weight: bool comp_weight_config: CompressionConfig # Compress KV cache with group-wise quantization compress_cache: bool comp_cache_config: CompressionConfig def w_disk_percent(self): return 100 - self.w_gpu_percent - self.w_cpu_percent def cache_disk_percent(self): return 100 - self.cache_gpu_percent - self.cache_cpu_percent def act_disk_percent(self): return 100 - self.act_gpu_percent - self.act_cpu_percent GB = 1 << 30 T = 1e12 def solve_lp(config, bls, gbs, compress_w=False, verbose=1, debug=False, percent=None): assert bls > 0 and gbs > 0 assert bls >= gbs and bls % gbs == 0 ## Constants s = config.s n = config.n l = config.l h1 = config.h1 h2 = config.h2 nh = config.nh gmem = config.gmem * alpha_g cmem = config.cmem * alpha_c nmem = config.nmem * alpha_n ctog_bdw = config.ctog_bdw gtoc_bdw_cache = config.gtoc_bdw_cache gtoc_bdw_hidden = config.gtoc_bdw_hidden dtoc_bdw = config.dtoc_bdw ctod_bdw_cache_p = config.ctod_bdw_cache_p ctod_bdw_hidden_p = config.ctod_bdw_hidden_p ctod_bdw_g = config.ctod_bdw_g mm_flops_p = config.mm_flops_p mm_flops_g = config.mm_flops_g bmm_flops_p = config.bmm_flops_p bmm_flops_g = config.bmm_flops_g cpu_flops = config.cpu_flops c1 = config.c1 c2 = config.c2 c3 = config.c3 ## Create Problem prob = pulp.LpProblem('storage', sense=pulp.LpMinimize) ## Create variables for cost T = pulp.LpVariable("T", lowBound=0) Tpre = pulp.LpVariable("Tpre_i", lowBound=0) Tgen = pulp.LpVariable("Tgen_i", lowBound=0) ctogp = pulp.LpVariable("ctog_i^p", lowBound=0) gtocp = pulp.LpVariable("gtoc_i^p", lowBound=0) ctodp = pulp.LpVariable("ctod_i^p", lowBound=0) dtocp = pulp.LpVariable("dtoc_i^p", lowBound=0) compp = pulp.LpVariable("comp_i^p", lowBound=0) ctogg = pulp.LpVariable("ctog_i^g", lowBound=0) gtocg = pulp.LpVariable("gtoc_i^g", lowBound=0) ctodg = pulp.LpVariable("ctod_i^g", lowBound=0) dtocg = pulp.LpVariable("dtoc_i^g", lowBound=0) compg = pulp.LpVariable("comp_i^g", lowBound=0) wg = pulp.LpVariable("wg", lowBound=0) wc = pulp.LpVariable("wc", lowBound=0) wn = pulp.LpVariable("wn", lowBound=0) cg = pulp.LpVariable("cg", lowBound=0) cc = pulp.LpVariable("cc", lowBound=0) cn = pulp.LpVariable("cn", lowBound=0) hg = pulp.LpVariable("hg", lowBound=0) hc = pulp.LpVariable("hc", lowBound=0) hn = pulp.LpVariable("hn", lowBound=0) ## Set objective # Minimize T/bls prob += T * (1 / bls) # layer weight size wi = 8 * h1 ** 2 + 4 * h1 * h2 if compress_w: wi = wi / 4 if debug: ## DEBUG assert percent is not None if percent[0] is not None: prob += wg == percent[0] / 100 if percent[1] is not None: prob += wc == percent[1] / 100 if percent[2] is not None: prob += cg == percent[2] / 100 if percent[3] is not None: prob += cc == percent[3] / 100 if percent[4] is not None: prob += hg == percent[4] / 100 if percent[5] is not None: prob += hc == percent[5] / 100 # --------------- Add constraints ------------------- prob += wg + wc + wn == 1 prob += cg + cc + cn == 1 prob += hg + hc + hn == 1 ## temporay hack, as the current runtime does not support hidden on disk prob += hg + hc == 1 prob += T == Tpre * l + Tgen * (n-1) * l # # Tpre = max(ctogp, gtocp, dtocp, ctodp, compp) # prob += Tpre >= ctogp # prob += Tpre >= gtocp # prob += Tpre >= dtocp # prob += Tpre >= ctodp # prob += Tpre >= compp # Tpre = max(ctogp + dtocp, gtocp + ctodp, compp) prob += Tpre >= ctogp + dtocp prob += Tpre >= gtocp + ctodp prob += Tpre >= compp # ctogp = (weight_ctogp + hidden_ctogp) / ctog_bdw prob += ctogp == (1 / ctog_bdw) * (wi * (wc + wn) + 2 * s * h1 * bls * (hc + hn)) # gtocp = (cache_gtocp + hidden_gtocp) / gtoc_bdw prob += gtocp == (1 / gtoc_bdw_cache) * (4 * (s + 1) * h1 * bls * (cc + cn)) \ + (1 / gtoc_bdw_hidden) * 2 * s * h1 * bls * (hc + hn) # dtocp = (weight_dtocp + hidden_dtocp) / dtoc_bdw prob += dtocp == (1 / dtoc_bdw) * (wi * wn + 2 * s * h1 * bls * hn) # ctodp = (cache_ctodp + hidden_ctodp) / ctod_bdw prob += ctodp == (1 / ctod_bdw_cache_p) * 4 * bls * (s + 1) * h1 * cn \ + (1 / ctod_bdw_hidden_p) * 2 * s * h1 * bls * hn # compp = gpu_compp prob += compp == (1 / mm_flops_p) * bls * (8 * s * h1 ** 2 + 4 * s * h1 * h2) \ + (1 / bmm_flops_p) * 4 * bls * s ** 2 * h1 # # Tgen = max(ctogg, gtocg, dtocg, ctodg, compg) # prob += Tgen >= ctogg # prob += Tgen >= gtocg # prob += Tgen >= dtocg # prob += Tgen >= ctodg # prob += Tgen >= compg # Tgen = ctogg + max(gtocg, dtocg, ctodg, compg) prob += Tgen >= gtocg + ctogg prob += Tgen >= dtocg + ctogg prob += Tgen >= ctodg + ctogg prob += Tgen >= compg + ctogg # ctogg = (weight_ctogg + hidden_ctogg) / ctog_bdw prob += ctogg == (1 / ctog_bdw) * (wi * (wc + wn) + 2 * h1 * bls * (hc + hn)) # gtocg = hidden_gtocg / gtoc_bdw prob += gtocg == (1 / gtoc_bdw_hidden) * 2 * h1 * bls * (hc + hn) # dtocg = (cache_dtocg + weight_dtocg + hidden_dtocg) / dtoc_bdw prob += dtocg == (1 / dtoc_bdw) * (4 * bls * (s + n / 2) * h1 * cn + 2 * h1 * bls * hn) \ + (1 / (dtoc_bdw * 0.95)) * wi * wn # ctodg = (cache_ctodg + hidden_ctodg) / ctod_bdw prob += ctodg == (1 / ctod_bdw_g) * (4 * bls * h1 * cn + 2 * h1 * bls * hn) # compg = gpu_compg + cpu_compg # non-linear cpu_flops cpu_flops_real = cpu_flops * np.maximum(0.1, 1 + c1 * (max(0, math.log2(64 / gbs)) * max(0, math.log2(4096 / h1))) - c2 * max(0, math.log2(64 / gbs)) - c3 * max(0, math.log2(4096 / h1))) prob += compg == (1 / mm_flops_g) * bls * (8 * h1 ** 2 + 4 * h1 * h2) \ + (1 / bmm_flops_g) * 4 * bls * (s + n / 2) * h1 * cg \ + (1 / cpu_flops_real) * 4 * bls * (s + n / 2) * h1 * (cc + cn) ## Create variables for peak memory constraints gpu_home_p = pulp.LpVariable("gpu_home^p", lowBound=0) gpu_w_p = pulp.LpVariable("gpu_w^p", lowBound=0) gpu_home_g = pulp.LpVariable("gpu_home^g", lowBound=0) gpu_w_g = pulp.LpVariable("gpu_w^g", lowBound=0) interp = pulp.LpVariable("inter_gpu_working_p", lowBound=0) qkvp = pulp.LpVariable("qkvp", lowBound=0) att1p = pulp.LpVariable("att1p", lowBound=0) att2p = pulp.LpVariable("att2p", lowBound=0) outputp = pulp.LpVariable("outputp", lowBound=0) mlp1p = pulp.LpVariable("mlp1p", lowBound=0) mlp2p = pulp.LpVariable("mlp2p", lowBound=0) interg = pulp.LpVariable("inter_gpu_working_g", lowBound=0) qkvg = pulp.LpVariable("qkvg", lowBound=0) att1g = pulp.LpVariable("att1g", lowBound=0) att2g = pulp.LpVariable("att2g", lowBound=0) outputg = pulp.LpVariable("outputg", lowBound=0) mlp1g = pulp.LpVariable("mlp1g", lowBound=0) mlp2g = pulp.LpVariable("mlp2g", lowBound=0) cpu_home_p = pulp.LpVariable("cpu_home^p", lowBound=0) cpu_w_p = pulp.LpVariable("cpu_w^p", lowBound=0) cpu_home_g = pulp.LpVariable("cpu_home^g", lowBound=0) cpu_w_g = pulp.LpVariable("cpu_w^g", lowBound=0) nvme_peak = pulp.LpVariable("nvme_peak", lowBound=0) ## GPU peak memory constaints prob += gpu_home_p == wi * l * wg + 2 * s * h1 * bls * hg + 4 * (s + n) * h1 * bls * l * cg prob += interp == 8 * gbs * s * h1 \ + gbs * (2 * s * h1 + 2 * nh * s ** 2) \ + gbs * (2 * s * h1) \ + 4 * gbs * s * h1 \ + 2 * gbs * s * h2 \ + 2 * gbs * s * h1 prob += gpu_w_p == 2 * wi * (1 - wg) + 2 * s * h1 * gbs * (1 - hg) \ + interp # prob += (gpu_home_p * 1.2 + gpu_w_p) + 0.5 * GB <= gmem prob += gpu_home_p + gpu_w_p <= gmem # prob += gpu_home_p == wi * l * wg + 2 * s * h1 * bls * hg + 4 * (s + n) * h1 * bls * l * cg # prob += gpu_w_p == 2 * wi * (1 - wg) + 2 * s * h1 * gbs * (1 - hg) + interp # prob += interp >= qkvp # prob += interp >= att1p # prob += interp >= att2p # prob += interp >= outputp # prob += interp >= mlp1p # prob += interp >= mlp2p # prob += qkvp == 8 * gbs * s * h1 # prob += att1p == gbs * (2 * s * h1 + 2 * s * h1 + 2 * nh * s ** 2) # prob += att2p == gbs * (2 * nh * s ** 2 + 2 * s * h1 + 2 * s * h1) # prob += outputp == 4 * gbs * s * h1 # prob += mlp1p == 2 * gbs * s * (h1 + h2) # prob += mlp2p == 2 * gbs * s * (h2 + h1) # prob += gpu_home_p + gpu_w_p <= gmem prob += gpu_home_g == wi * l * wg + 2 * h1 * bls * hg + 4 * (s + n) * h1 * bls * l * cg prob += interg == 8 * gbs * h1 \ + gbs * (2 * h1 + 2 * (s + n) * h1 + 2 * nh * (s + n)) * cg \ + gbs * (2 * (s + n) * h1 + 2 * h1) * cg \ + 4 * gbs * h1 \ + 2 * gbs * h2 \ + 2 * gbs * h1 prob += gpu_w_g == 2 * wi * (1 - wg) + 2 * h1 * gbs * (1 - hg) \ + 2 * 2 * gbs * (s + n) * h1 * cg \ + interg # prob += (gpu_home_g * 1.2 + gpu_w_g) + 0.5 * GB <= gmem prob += gpu_home_g + gpu_w_g <= gmem # prob += gpu_home_g == wi * l * wg + 2 * h1 * bls * hg + 4 * (s + n) * h1 * bls * l * cg # prob += gpu_w_g == 2 * wi * (1 - wg) + 2 * s * h1 * gbs * (1 - hg) + interg # prob += interg >= qkvg # prob += interg >= att1g # prob += interg >= att2g # prob += interg >= outputg # prob += interg >= mlp1g # prob += interg >= mlp2g # prob += qkvg == 8 * gbs * h1 # prob += att1g == gbs * (2 * h1 + 2 * (s + n) * h1 + 2 * nh * (s + n)) * cg # prob += att2g == gbs * (2 * nh * (s + n) + 2 * (s + n) * h1 + 2 * h1) * cg # prob += outputg == 4 * gbs * h1 # prob += mlp1g == 2 * gbs * (h1 + h2) # prob += mlp2g == 2 * gbs * (h2 + h1) # prob += gpu_home_g + gpu_w_g <= gmem ## CPU peak memory constraints prob += cpu_home_p == wi * l * wc + 2 * s * h1 * bls * hc + 4 * s * h1 * bls * l * cc prob += cpu_w_p == wi * (1 - wg) + 2 * s * h1 * gbs * (1 - hg) prob += cpu_home_p + cpu_w_p <= cmem prob += cpu_home_g == wi * l * wc + 2 * h1 * bls * hc + 4 * (s + n) * h1 * bls * l * cc prob += cpu_w_g == wi * wn + 4 * h1 * gbs * hn + 8 * (s + n) * h1 * gbs * cn + 2 * nh * (s + n) * gbs + 2 * h1 * gbs prob += cpu_home_g + cpu_w_g <= cmem ## NVMe peak memory constraints prob += nvme_peak == wi * l * wn + 2 * s * h1 * bls * hn + 4 * (s + n) * h1 * bls * l * cn prob += nvme_peak <= nmem # ------------ Finish add constraints --------------- ## Optimize model solver = pulp.PULP_CBC_CMD(msg=False) status = prob.solve(solver) if status == -1: return status, None, (0, -1, -1), None # gpu_peak_p = pulp.value(gpu_home_p) * 1.2 + pulp.value(gpu_w_p) + 0.5 * GB # gpu_peak_g = pulp.value(gpu_home_g) * 1.2 + pulp.value(gpu_w_g) + 0.5 * GB gpu_peak_p = pulp.value(gpu_home_p) + pulp.value(gpu_w_p) gpu_peak_g = pulp.value(gpu_home_g) + pulp.value(gpu_w_g) cpu_peak_p = pulp.value(cpu_home_p) + pulp.value(cpu_w_p) cpu_peak_g = pulp.value(cpu_home_g) + pulp.value(cpu_w_g) throughput = bls * n / pulp.value(T) tpre = pulp.value(Tpre) tpre_tot = tpre * l tgen = pulp.value(Tgen) tgen_tot = tgen * (n-1) * l ## print solution if verbose: print(f"status: {status}") print(f"weights size: {wi * l / GB:.4f} GB") print(f"ctogp = {pulp.value(ctogp):.4f} s " f"gtocp = {pulp.value(gtocp):.4f} s " f"dtocp = {pulp.value(dtocp):.4f} s " f"ctodp = {pulp.value(ctodp):.4f} s " f"compp = {pulp.value(compp):.4f} s") print(f"Tpre = {pulp.value(Tpre):.3f} s") print(f"Tpre * l: {tpre:.4f} * {l} = {tpre_tot:.4f}") print(f"ctogg = {pulp.value(ctogg):.4f} s " f"gtocg = {pulp.value(gtocg):.4f} s " f"dtocg = {pulp.value(dtocg):.4f} s " f"ctodg = {pulp.value(ctodg):.4f} s " f"compg = {pulp.value(compg):.4f} s") print(f"cache dtocg: {4 * bls * (s + n / 2) * h1 * pulp.value(cn) / dtoc_bdw:.2f} " f"weights dtocg: {wi * pulp.value(wn) / dtoc_bdw:.2f}") print(f"Tgen = {pulp.value(Tgen):.3f} s") print(f"Tgen * (n-1) * l: " f"{tgen:.4f} * {n-1} * {l} = {tgen_tot:.4f}") print(f"gpu peak mem (prefill): {gpu_peak_p / GB:.3f} GB / {gmem / alpha_g / GB:.3f} GB") print(f"gpu peak mem (gen): {gpu_peak_g / GB:.3f} GB / {gmem / alpha_g / GB:.3f} GB") print(f"cpu peak mem (prefill): {cpu_peak_p / GB:.3f} GB / {cmem / alpha_c / GB:.3f} GB") print(f"cpu peak mem (gen): {cpu_peak_g / GB:.3f} GB / {cmem / alpha_c / GB:.3f} GB") print(f"cpu_home_g: {pulp.value(cpu_home_g) / GB:.2f} GB") print(f"cpu_w_g: {pulp.value(cpu_w_g) / GB:.2f} GB") print(f"nvme peak mem: {pulp.value(nvme_peak) / GB:.3f} GB / {nmem / alpha_n / GB:.3f} GB") print(f"wg = {pulp.value(wg):.2f} " f"wc = {pulp.value(wc):.2f} " f"wn = {pulp.value(wn):.2f}") print(f"cg = {pulp.value(cg):.2f} " f"cc = {pulp.value(cc):.2f} " f"cn = {pulp.value(cn):.2f}") print(f"hg = {pulp.value(hg):.2f} " f"hc = {pulp.value(hc):.2f} " f"hn = {pulp.value(hn):.2f}") print(f"T = {pulp.value(T)} s " f"generated = {bls * n} tokens") print(f"throughput = {throughput:.2f} token/s") policy = Policy(gbs, bls // gbs, pulp.value(wg), pulp.value(wc), pulp.value(cg), pulp.value(cc), pulp.value(hg), pulp.value(hc), overlap=True, sep_layer=False, pin_weight=False, cpu_cache_compute=True, attn_sparsity=1, compress_weight=False, comp_weight_config= CompressionConfig(num_bits=4, group_size=64, group_dim=0, symmetric=False), compress_cache=False, comp_cache_config= CompressionConfig(num_bits=4, group_size=64, group_dim=2, symmetric=False)) return status, policy, (throughput, tpre_tot, tgen_tot), (gpu_peak_p, gpu_peak_g)
null
12,160
import re def replace_url(match): pr_number = match.group(1) return f"[#{pr_number}](https://github.com/gee-community/geemap/pull/{pr_number})"
null
12,161
import os import platform from subprocess import DEVNULL, STDOUT, check_call import json The provided code snippet includes necessary dependencies for implementing the `set_heroku_vars` function. Write a Python function `def set_heroku_vars(token_name="EARTHENGINE_TOKEN")` to solve the following problem: Extracts Earth Engine token from the local computer and sets it as an environment variable on heroku. Args: token_name (str, optional): Name of the Earth Engine token. Defaults to 'EARTHENGINE_TOKEN'. Here is the function: def set_heroku_vars(token_name="EARTHENGINE_TOKEN"): """Extracts Earth Engine token from the local computer and sets it as an environment variable on heroku. Args: token_name (str, optional): Name of the Earth Engine token. Defaults to 'EARTHENGINE_TOKEN'. """ try: ee_token_dir = os.path.expanduser("~/.config/earthengine/") ee_token_file = os.path.join(ee_token_dir, "credentials") if not os.path.exists(ee_token_file): print("The credentials file does not exist.") else: with open(ee_token_file) as f: content = json.loads(f.read()) token = content["access_token"] secret = "{}={}".format(token_name, token) if platform.system() == "Windows": check_call( ["heroku", "config:set", secret], stdout=DEVNULL, stderr=STDOUT, shell=True, ) else: check_call( ["heroku", "config:set", secret], stdout=DEVNULL, stderr=STDOUT, ) except Exception as e: print(e) return
Extracts Earth Engine token from the local computer and sets it as an environment variable on heroku. Args: token_name (str, optional): Name of the Earth Engine token. Defaults to 'EARTHENGINE_TOKEN'.
12,162
import os import shutil import urllib.request from collections import deque from pathlib import Path import pkg_resources from .common import * def js_to_python( in_file, out_file=None, use_qgis=True, github_repo=None, show_map=True, import_geemap=False, Map="m", ): """Converts an Earth Engine JavaScript to Python script. Args: in_file (str): File path of the input JavaScript. out_file (str, optional): File path of the output Python script. Defaults to None. use_qgis (bool, optional): Whether to add "from ee_plugin import Map \n" to the output script. Defaults to True. github_repo (str, optional): GitHub repo url. Defaults to None. show_map (bool, optional): Whether to add "Map" to the output script. Defaults to True. import_geemap (bool, optional): Whether to add "import geemap" to the output script. Defaults to False. Map (str, optional): The name of the map variable. Defaults to "m". Returns: list: Python script """ in_file = os.path.abspath(in_file) if out_file is None: out_file = in_file.replace(".js", ".py") root_dir = os.path.dirname(os.path.abspath(__file__)) if not os.path.isfile(in_file): in_file = os.path.join(root_dir, in_file) if not os.path.isfile(out_file): out_file = os.path.join(root_dir, out_file) is_python = False # add_github_url = False if use_qgis and import_geemap: raise Exception( "use_qgis and import_geemap cannot be both True. Please set one of them to False." ) import_str = "" if use_qgis: import_str = "from ee_plugin import Map\n" if import_geemap: import_str = f"import geemap\n\n{Map} = geemap.Map()\n" github_url = "" if github_repo is not None: github_url = "# GitHub URL: " + github_repo + in_file + "\n\n" math_import = False math_import_str = "" lines = [] with open(in_file, encoding="utf-8") as f: lines = f.readlines() math_import = use_math(lines) for line in lines: line = line.strip() if line == "import ee": is_python = True if math_import: math_import_str = "import math\n" output = "" if is_python: # only update the GitHub URL if it is already a GEE Python script output = github_url + "".join(map(str, lines)) else: # deal with JavaScript header = github_url + "import ee \n" + math_import_str + import_str # function_defs = [] output = header + "\n" with open(in_file, encoding="utf-8") as f: lines = f.readlines() # print('Processing {}'.format(in_file)) lines = check_map_functions(lines) for index, line in enumerate(lines): if ("/* color" in line) and ("*/" in line): line = ( line[: line.index("/*")].lstrip() + line[(line.index("*/") + 2) :] ) if ( ("= function" in line) or ("=function" in line) or line.strip().startswith("function") ): try: bracket_index = line.index("{") except Exception as e: print( f"An error occurred when processing {in_file}. The closing curly bracket could not be found in Line {index+1}: {line}. Please reformat the function definition and make sure that both the opening and closing curly brackets appear on the same line as the function keyword. " ) return ( matching_line_index, matching_char_index, ) = find_matching_bracket(lines, index, bracket_index) line = line[:bracket_index] + line[bracket_index + 1 :] if matching_line_index == index: line = ( line[:matching_char_index] + line[matching_char_index + 1 :] ) else: tmp_line = lines[matching_line_index] lines[matching_line_index] = ( tmp_line[:matching_char_index] + tmp_line[matching_char_index + 1 :] ) line = ( line.replace(" = function", "") .replace("=function", "") .replace("function ", "") ) if line.lstrip().startswith("//"): line = line.replace("//", "").lstrip() line = ( " " * (len(line) - len(line.lstrip())) + "# def " + line.strip() + ":" ) else: line = ( " " * (len(line) - len(line.lstrip())) + "def " + line.strip() + ":" ) elif "{" in line: bracket_index = line.index("{") ( matching_line_index, matching_char_index, ) = find_matching_bracket(lines, index, bracket_index) if (matching_line_index == index) and (":" in line): pass elif ("for (" in line) or ("for(" in line): line = convert_for_loop(line) lines[index] = line bracket_index = line.index("{") ( matching_line_index, matching_char_index, ) = find_matching_bracket(lines, index, bracket_index) tmp_line = lines[matching_line_index] lines[matching_line_index] = ( tmp_line[:matching_char_index] + tmp_line[matching_char_index + 1 :] ) line = line.replace("{", "") if line is None: line = "" line = line.replace("//", "#") line = line.replace("var ", "", 1) line = line.replace("/*", "#") line = line.replace("*/", "#") line = line.replace("true", "True").replace("false", "False") line = line.replace("null", "None") line = line.replace(".or", ".Or") line = line.replace(".and", ".And") line = line.replace(".not", ".Not") line = line.replace("visualize({", "visualize(**{") line = line.replace("Math.PI", "math.pi") line = line.replace("Math.", "math.") line = line.replace("= new", "=") line = line.replace("Map.", f"{Map}.") line = line.rstrip() if ".style(" in line and ".style(**" not in line: line = line.replace(".style(", ".style(**") if line.endswith("+"): line = line + " \\" elif line.endswith(";"): line = line[:-1] if line.lstrip().startswith("*"): line = line.replace("*", "#") if ( (":" in line) and (not line.strip().startswith("#")) and (not line.strip().startswith("def")) and (not line.strip().startswith(".")) ): line = format_params(line) if ( index < (len(lines) - 1) and line.lstrip().startswith("#") and lines[index + 1].lstrip().startswith(".") ): line = "" if line.lstrip().startswith("."): if "#" in line: line = line[: line.index("#")] output = output.rstrip() + " " + "\\" + "\n" + line + "\n" else: output += line + "\n" if show_map: output += Map out_dir = os.path.dirname(out_file) if not os.path.exists(out_dir): os.makedirs(out_dir) with open(out_file, "w") as f: f.write(output) return output import os The provided code snippet includes necessary dependencies for implementing the `js_to_python_dir` function. Write a Python function `def js_to_python_dir( in_dir, out_dir=None, use_qgis=True, github_repo=None, import_geemap=False, Map="m" )` to solve the following problem: Converts all Earth Engine JavaScripts in a folder recursively to Python scripts. Args: in_dir (str): The input folder containing Earth Engine JavaScripts. out_dir (str, optional): The output folder containing Earth Engine Python scripts. Defaults to None. use_qgis (bool, optional): Whether to add "from ee_plugin import Map \n" to the output script. Defaults to True. github_repo (str, optional): GitHub repo url. Defaults to None. import_geemap (bool, optional): Whether to add "import geemap" to the output script. Defaults to False. Map (str, optional): The name of the map variable. Defaults to "m". Here is the function: def js_to_python_dir( in_dir, out_dir=None, use_qgis=True, github_repo=None, import_geemap=False, Map="m" ): """Converts all Earth Engine JavaScripts in a folder recursively to Python scripts. Args: in_dir (str): The input folder containing Earth Engine JavaScripts. out_dir (str, optional): The output folder containing Earth Engine Python scripts. Defaults to None. use_qgis (bool, optional): Whether to add "from ee_plugin import Map \n" to the output script. Defaults to True. github_repo (str, optional): GitHub repo url. Defaults to None. import_geemap (bool, optional): Whether to add "import geemap" to the output script. Defaults to False. Map (str, optional): The name of the map variable. Defaults to "m". """ print("Converting Earth Engine JavaScripts to Python scripts...\n") in_dir = os.path.abspath(in_dir) if out_dir is None: out_dir = in_dir elif not os.path.exists(out_dir): out_dir = os.path.abspath(out_dir) os.makedirs(out_dir) else: out_dir = os.path.abspath(out_dir) files = list(Path(in_dir).rglob("*.js")) for index, in_file in enumerate(files): print(f"Processing {index + 1}/{len(files)}: {in_file}") # if use_qgis: # out_file = os.path.splitext(in_file)[0] + "_qgis.py" # else: out_file = os.path.splitext(in_file)[0] + "_geemap.py" out_file = out_file.replace(in_dir, out_dir) js_to_python( in_file, out_file, use_qgis, github_repo, import_geemap=import_geemap, Map=Map, ) # print("Output Python script folder: {}".format(out_dir))
Converts all Earth Engine JavaScripts in a folder recursively to Python scripts. Args: in_dir (str): The input folder containing Earth Engine JavaScripts. out_dir (str, optional): The output folder containing Earth Engine Python scripts. Defaults to None. use_qgis (bool, optional): Whether to add "from ee_plugin import Map \n" to the output script. Defaults to True. github_repo (str, optional): GitHub repo url. Defaults to None. import_geemap (bool, optional): Whether to add "import geemap" to the output script. Defaults to False. Map (str, optional): The name of the map variable. Defaults to "m".
12,163
import os import shutil import urllib.request from collections import deque from pathlib import Path import pkg_resources from .common import * import os import shutil The provided code snippet includes necessary dependencies for implementing the `get_js_examples` function. Write a Python function `def get_js_examples(out_dir=None)` to solve the following problem: Gets Earth Engine JavaScript examples from the geemap package. Args: out_dir (str, optional): The folder to copy the JavaScript examples to. Defaults to None. Returns: str: The folder containing the JavaScript examples. Here is the function: def get_js_examples(out_dir=None): """Gets Earth Engine JavaScript examples from the geemap package. Args: out_dir (str, optional): The folder to copy the JavaScript examples to. Defaults to None. Returns: str: The folder containing the JavaScript examples. """ pkg_dir = os.path.dirname(pkg_resources.resource_filename("geemap", "geemap.py")) example_dir = os.path.join(pkg_dir, "data") js_dir = os.path.join(example_dir, "javascripts") files = list(Path(js_dir).rglob("*.js")) if out_dir is None: out_dir = js_dir else: if not os.path.exists(out_dir): os.makedirs(out_dir) for file in files: basename = os.path.basename(file) out_path = os.path.join(out_dir, basename) shutil.copyfile(file, out_path) return out_dir
Gets Earth Engine JavaScript examples from the geemap package. Args: out_dir (str, optional): The folder to copy the JavaScript examples to. Defaults to None. Returns: str: The folder containing the JavaScript examples.
12,164
import os import shutil import urllib.request from collections import deque from pathlib import Path import pkg_resources from .common import * def py_to_ipynb( in_file, template_file=None, out_file=None, github_username=None, github_repo=None, Map="m", ): """Converts Earth Engine Python script to Jupyter notebook. Args: in_file (str): Input Earth Engine Python script. template_file (str): Input Jupyter notebook template. out_file (str, optional)): Output Jupyter notebook. github_username (str, optional): GitHub username. Defaults to None. github_repo (str, optional): GitHub repo name. Defaults to None. Map (str, optional): The name of the map variable. Defaults to "m". """ in_file = os.path.abspath(in_file) if template_file is None: template_file = get_nb_template() if out_file is None: out_file = os.path.splitext(in_file)[0] + ".ipynb" out_py_file = os.path.splitext(out_file)[0] + "_tmp.py" out_dir = os.path.dirname(out_file) if not os.path.exists(out_dir): os.makedirs(out_dir) if out_dir == os.path.dirname(in_file): out_py_file = os.path.splitext(out_file)[0] + "_tmp.py" content = remove_qgis_import(in_file, Map=Map) if content[-1].strip() == "Map": content = content[:-1] header = template_header(template_file) footer = template_footer(template_file) if (github_username is not None) and (github_repo is not None): out_py_path = str(out_file).split("/") index = out_py_path.index(github_repo) out_py_relative_path = "/".join(out_py_path[index + 1 :]) out_ipynb_relative_path = out_py_relative_path.replace(".py", ".ipynb") new_header = [] for index, line in enumerate(header): if index < 9: # Change Google Colab and binder URLs line = line.replace("giswqs", github_username) line = line.replace("geemap", github_repo) line = line.replace( "examples/template/template.ipynb", out_ipynb_relative_path ) new_header.append(line) header = new_header if content is not None: out_text = header + content + footer else: out_text = header + footer out_text = out_text[:-1] + [out_text[-1].strip()] if not os.path.exists(os.path.dirname(out_py_file)): os.makedirs(os.path.dirname(out_py_file)) with open(out_py_file, "w") as f: f.writelines(out_text) try: # command = 'ipynb-py-convert ' + out_py_file + ' ' + out_file command = 'ipynb-py-convert "{}" "{}"'.format(out_py_file, out_file) print(os.popen(command).read().rstrip()) # os.popen(command) except Exception as e: print("Please install ipynb-py-convert using the following command:\n") print("pip install ipynb-py-convert") raise Exception(e) try: os.remove(out_py_file) except Exception as e: print(e) import os The provided code snippet includes necessary dependencies for implementing the `py_to_ipynb_dir` function. Write a Python function `def py_to_ipynb_dir( in_dir, template_file=None, out_dir=None, github_username=None, github_repo=None, Map="m", )` to solve the following problem: Converts Earth Engine Python scripts in a folder recursively to Jupyter notebooks. Args: in_dir (str): Input folder containing Earth Engine Python scripts. out_dir str, optional): Output folder. Defaults to None. template_file (str): Input jupyter notebook template file. github_username (str, optional): GitHub username. Defaults to None. github_repo (str, optional): GitHub repo name. Defaults to None. Map (str, optional): The name of the map variable. Defaults to "m". Here is the function: def py_to_ipynb_dir( in_dir, template_file=None, out_dir=None, github_username=None, github_repo=None, Map="m", ): """Converts Earth Engine Python scripts in a folder recursively to Jupyter notebooks. Args: in_dir (str): Input folder containing Earth Engine Python scripts. out_dir str, optional): Output folder. Defaults to None. template_file (str): Input jupyter notebook template file. github_username (str, optional): GitHub username. Defaults to None. github_repo (str, optional): GitHub repo name. Defaults to None. Map (str, optional): The name of the map variable. Defaults to "m". """ print("Converting Earth Engine Python scripts to Jupyter notebooks ...\n") in_dir = os.path.abspath(in_dir) files = [] qgis_files = list(Path(in_dir).rglob("*_geemap.py")) py_files = list(Path(in_dir).rglob("*.py")) if len(qgis_files) == len(py_files) / 2: files = qgis_files else: files = py_files if out_dir is None: out_dir = in_dir elif not os.path.exists(out_dir): out_dir = os.path.abspath(out_dir) os.makedirs(out_dir) else: out_dir = os.path.abspath(out_dir) for index, file in enumerate(files): in_file = str(file) out_file = ( in_file.replace(in_dir, out_dir) .replace("_qgis", "") .replace(".py", ".ipynb") ) print(f"Processing {index + 1}/{len(files)}: {in_file}") py_to_ipynb(in_file, template_file, out_file, github_username, github_repo, Map)
Converts Earth Engine Python scripts in a folder recursively to Jupyter notebooks. Args: in_dir (str): Input folder containing Earth Engine Python scripts. out_dir str, optional): Output folder. Defaults to None. template_file (str): Input jupyter notebook template file. github_username (str, optional): GitHub username. Defaults to None. github_repo (str, optional): GitHub repo name. Defaults to None. Map (str, optional): The name of the map variable. Defaults to "m".
12,165
import os import shutil import urllib.request from collections import deque from pathlib import Path import pkg_resources from .common import * def execute_notebook(in_file): """Executes a Jupyter notebook and save output cells Args: in_file (str): Input Jupyter notebook. """ # command = 'jupyter nbconvert --to notebook --execute ' + in_file + ' --inplace' command = 'jupyter nbconvert --to notebook --execute "{}" --inplace'.format(in_file) print(os.popen(command).read().rstrip()) # os.popen(command) import os The provided code snippet includes necessary dependencies for implementing the `execute_notebook_dir` function. Write a Python function `def execute_notebook_dir(in_dir)` to solve the following problem: Executes all Jupyter notebooks in the given directory recursively and save output cells. Args: in_dir (str): Input folder containing notebooks. Here is the function: def execute_notebook_dir(in_dir): """Executes all Jupyter notebooks in the given directory recursively and save output cells. Args: in_dir (str): Input folder containing notebooks. """ print("Executing Earth Engine Jupyter notebooks ...\n") in_dir = os.path.abspath(in_dir) files = list(Path(in_dir).rglob("*.ipynb")) count = len(files) if files is not None: for index, file in enumerate(files): in_file = str(file) print(f"Processing {index + 1}/{count}: {file} ...") execute_notebook(in_file)
Executes all Jupyter notebooks in the given directory recursively and save output cells. Args: in_dir (str): Input folder containing notebooks.
12,166
import os import shutil import urllib.request from collections import deque from pathlib import Path import pkg_resources from .common import * def update_nb_header(in_file, github_username=None, github_repo=None): """Updates notebook header (binder and Google Colab URLs). Args: in_file (str): The input Jupyter notebook. github_username (str, optional): GitHub username. Defaults to None. github_repo (str, optional): GitHub repo name. Defaults to None. """ if github_username is None: github_username = "giswqs" if github_repo is None: github_repo = "geemap" index = in_file.index(github_repo) file_relative_path = in_file[index + len(github_repo) + 1 :] output_lines = [] with open(in_file, encoding="utf-8") as f: lines = f.readlines() start_line_index = 2 start_char_index = lines[start_line_index].index("{") matching_line_index, _ = find_matching_bracket( lines, start_line_index, start_char_index ) header = lines[:matching_line_index] content = lines[matching_line_index:] new_header = [] search_string = "" for line in header: line = line.replace("giswqs", github_username) line = line.replace("geemap", github_repo) if "master?filepath=" in line: search_string = "master?filepath=" start_index = line.index(search_string) + len(search_string) end_index = line.index(".ipynb") + 6 relative_path = line[start_index:end_index] line = line.replace(relative_path, file_relative_path) elif "/master/" in line: search_string = "/master/" start_index = line.index(search_string) + len(search_string) end_index = line.index(".ipynb") + 6 relative_path = line[start_index:end_index] line = line.replace(relative_path, file_relative_path) new_header.append(line) output_lines = new_header + content with open(in_file, "w") as f: f.writelines(output_lines) The provided code snippet includes necessary dependencies for implementing the `update_nb_header_dir` function. Write a Python function `def update_nb_header_dir(in_dir, github_username=None, github_repo=None)` to solve the following problem: Updates header (binder and Google Colab URLs) of all notebooks in a folder . Args: in_dir (str): The input directory containing Jupyter notebooks. github_username (str, optional): GitHub username. Defaults to None. github_repo (str, optional): GitHub repo name. Defaults to None. Here is the function: def update_nb_header_dir(in_dir, github_username=None, github_repo=None): """Updates header (binder and Google Colab URLs) of all notebooks in a folder . Args: in_dir (str): The input directory containing Jupyter notebooks. github_username (str, optional): GitHub username. Defaults to None. github_repo (str, optional): GitHub repo name. Defaults to None. """ files = list(Path(in_dir).rglob("*.ipynb")) for index, file in enumerate(files): file = str(file) if ".ipynb_checkpoints" in file: del files[index] count = len(files) if files is not None: for index, file in enumerate(files): in_file = str(file) print(f"Processing {index + 1}/{count}: {file} ...") update_nb_header(in_file, github_username, github_repo)
Updates header (binder and Google Colab URLs) of all notebooks in a folder . Args: in_dir (str): The input directory containing Jupyter notebooks. github_username (str, optional): GitHub username. Defaults to None. github_repo (str, optional): GitHub repo name. Defaults to None.
12,167
import os import shutil import urllib.request from collections import deque from pathlib import Path import pkg_resources from .common import * import os import urllib.request The provided code snippet includes necessary dependencies for implementing the `download_gee_app` function. Write a Python function `def download_gee_app(url, out_file=None)` to solve the following problem: Downloads JavaScript source code from a GEE App Args: url (str): The URL of the GEE App. out_file (str, optional): The output file path for the downloaded JavaScript. Defaults to None. Here is the function: def download_gee_app(url, out_file=None): """Downloads JavaScript source code from a GEE App Args: url (str): The URL of the GEE App. out_file (str, optional): The output file path for the downloaded JavaScript. Defaults to None. """ cwd = os.getcwd() out_file_name = os.path.basename(url) + ".js" out_file_path = os.path.join(cwd, out_file_name) items = url.split("/") items[3] = "javascript" items[4] = items[4] + "-modules.json" json_url = "/".join(items) print(f"The json url: {json_url}") if out_file is not None: out_file_path = out_file if not out_file_path.endswith("js"): out_file_path += ".js" out_dir = os.path.dirname(out_file_path) if not os.path.exists(out_dir): os.makedirs(out_dir) json_path = out_file_path + "on" try: urllib.request.urlretrieve(json_url, json_path) except Exception: raise Exception("The URL is invalid. Please double check the URL.") with open(out_file_path, "w") as f1: with open(json_path, encoding="utf-8") as f2: lines = f2.readlines() for line in lines: # print(line) items = line.split("\\n") for index, item in enumerate(items): if (index > 0) and (index < (len(items) - 1)): item = item.replace('\\"', '"') item = item.replace(r"\\", "\n") item = item.replace("\\r", "") f1.write(item + "\n") os.remove(json_path) print(f"The JavaScript is saved at: {out_file_path}")
Downloads JavaScript source code from a GEE App Args: url (str): The URL of the GEE App. out_file (str, optional): The output file path for the downloaded JavaScript. Defaults to None.
12,168
import functools import IPython from IPython.core.display import HTML, display import ee import ipytree import ipywidgets from . import common from traceback import format_tb def _set_css_in_cell_output(info): display( HTML( """ <style> .geemap-dark { --jp-widgets-color: white; --jp-widgets-label-color: white; --jp-ui-font-color1: white; --jp-layout-color2: #454545; background-color: #383838; } .geemap-dark .jupyter-button { --jp-layout-color3: #383838; } .geemap-colab { background-color: var(--colab-primary-surface-color, white); } .geemap-colab .jupyter-button { --jp-layout-color3: var(--colab-primary-surface-color, white); } </style> """ ) )
null
12,169
import logging import os import subprocess import sys import warnings from collections.abc import Iterable from io import BytesIO import ee import matplotlib as mpl import matplotlib.patches as patches import matplotlib.pyplot as plt import numpy as np import requests from matplotlib import cm, colors from matplotlib import font_manager as mfonts from .basemaps import custom_tiles The provided code snippet includes necessary dependencies for implementing the `check_dependencies` function. Write a Python function `def check_dependencies()` to solve the following problem: Helper function to check dependencies used for cartoee Dependencies not included in main geemap are: cartopy, PIL, and scipys raises: Exception: when conda is not found in path Exception: when auto install fails to install/import packages Here is the function: def check_dependencies(): """Helper function to check dependencies used for cartoee Dependencies not included in main geemap are: cartopy, PIL, and scipys raises: Exception: when conda is not found in path Exception: when auto install fails to install/import packages """ import importlib # check if conda in in path and available to use is_conda = os.path.exists(os.path.join(sys.prefix, "conda-meta")) # raise error if conda not found if not is_conda: raise Exception( "Auto installation requires `conda`. Please install conda using the following instructions before use: https://docs.conda.io/projects/conda/en/latest/user-guide/install/" ) # list of dependencies to check, ordered in decreasing complexity # i.e. cartopy install should install PIL dependencies = ["cartopy", "pillow", "scipy"] # loop through dependency list and check if we can import module # if not try to install # install fail will be silent to continue through others if there is a failure # correct install will be checked later for dependency in dependencies: try: # see if we can import importlib.import_module(dependency) except ImportError: # change the dependency name if it is PIL # import vs install names are different for PIL... # dependency = dependency if dependency is not "PIL" else "pillow" # print info if not installed logging.info( f"The {dependency} package is not installed. Trying install..." ) logging.info(f"Installing {dependency} ...") # run the command cmd = f"conda install -c conda-forge {dependency} -y" proc = subprocess.Popen( cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, ) # send command out, _ = proc.communicate() logging.info(out.decode()) # second pass through dependencies to check if everything was installed correctly failed = [] for dependency in dependencies: try: importlib.import_module(dependency) except ImportError: # append failed imports failed.append(dependency) # check if there were any failed imports after trying install if len(failed) > 0: failed_str = ",".join(failed) raise Exception( f"Auto installation failed...the following dependencies were not installed '{failed_str}'" ) else: logging.info("All dependencies are successfully imported/installed!") return
Helper function to check dependencies used for cartoee Dependencies not included in main geemap are: cartopy, PIL, and scipys raises: Exception: when conda is not found in path Exception: when auto install fails to install/import packages
12,170
import logging import os import subprocess import sys import warnings from collections.abc import Iterable from io import BytesIO import ee import matplotlib as mpl import matplotlib.patches as patches import matplotlib.pyplot as plt import numpy as np import requests from matplotlib import cm, colors from matplotlib import font_manager as mfonts from .basemaps import custom_tiles The provided code snippet includes necessary dependencies for implementing the `add_colorbar` function. Write a Python function `def add_colorbar( ax, vis_params, loc=None, cmap="gray", discrete=False, label=None, **kwargs )` to solve the following problem: Add a colorbar to the map based on visualization parameters provided args: ax (cartopy.mpl.geoaxes.GeoAxesSubplot | cartopy.mpl.geoaxes.GeoAxes): required cartopy GeoAxesSubplot object to add image overlay to loc (str, optional): string specifying the position vis_params (dict, optional): visualization parameters as a dictionary. See https://developers.google.com/earth-engine/guides/image_visualization for options. **kwargs: remaining keyword arguments are passed to colorbar() raises: Warning: If 'discrete' is true when "palette" key is not in visParams ValueError: If `ax` is not of type cartopy.mpl.geoaxes.GeoAxesSubplot ValueError: If 'cmap' or "palette" key in visParams is not provided ValueError: If "min" in visParams is not of type scalar ValueError: If "max" in visParams is not of type scalar ValueError: If 'loc' or 'cax' keywords are not provided ValueError: If 'loc' is not of type str or does not equal available options Here is the function: def add_colorbar( ax, vis_params, loc=None, cmap="gray", discrete=False, label=None, **kwargs ): """ Add a colorbar to the map based on visualization parameters provided args: ax (cartopy.mpl.geoaxes.GeoAxesSubplot | cartopy.mpl.geoaxes.GeoAxes): required cartopy GeoAxesSubplot object to add image overlay to loc (str, optional): string specifying the position vis_params (dict, optional): visualization parameters as a dictionary. See https://developers.google.com/earth-engine/guides/image_visualization for options. **kwargs: remaining keyword arguments are passed to colorbar() raises: Warning: If 'discrete' is true when "palette" key is not in visParams ValueError: If `ax` is not of type cartopy.mpl.geoaxes.GeoAxesSubplot ValueError: If 'cmap' or "palette" key in visParams is not provided ValueError: If "min" in visParams is not of type scalar ValueError: If "max" in visParams is not of type scalar ValueError: If 'loc' or 'cax' keywords are not provided ValueError: If 'loc' is not of type str or does not equal available options """ if type(ax) not in [GeoAxes, GeoAxesSubplot]: raise ValueError( "provided axes not of type cartopy.mpl.geoaxes.GeoAxes " "or cartopy.mpl.geoaxes.GeoAxesSubplot" ) if loc: if (type(loc) == str) and (loc in ["left", "right", "bottom", "top"]): if "posOpts" not in kwargs: posOpts = { "left": [0.01, 0.25, 0.02, 0.5], "right": [0.88, 0.25, 0.02, 0.5], "bottom": [0.25, 0.15, 0.5, 0.02], "top": [0.25, 0.88, 0.5, 0.02], } else: posOpts = { "left": kwargs["posOpts"], "right": kwargs["posOpts"], "bottom": kwargs["posOpts"], "top": kwargs["posOpts"], } del kwargs["posOpts"] cax = ax.figure.add_axes(posOpts[loc]) if loc == "left": mpl.pyplot.subplots_adjust(left=0.18) elif loc == "right": mpl.pyplot.subplots_adjust(right=0.85) else: pass else: raise ValueError( 'provided loc not of type str. options are "left", ' '"top", "right", or "bottom"' ) elif "cax" in kwargs: cax = kwargs["cax"] kwargs = {key: kwargs[key] for key in kwargs.keys() if key != "cax"} else: raise ValueError("loc or cax keywords must be specified") vis_keys = list(vis_params.keys()) if vis_params: if "min" in vis_params: vmin = vis_params["min"] if type(vmin) not in (int, float): raise ValueError("provided min value not of scalar type") else: vmin = 0 if "max" in vis_params: vmax = vis_params["max"] if type(vmax) not in (int, float): raise ValueError("provided max value not of scalar type") else: vmax = 1 if "opacity" in vis_params: alpha = vis_params["opacity"] if type(alpha) not in (int, float): raise ValueError("provided opacity value of not type scalar") elif "alpha" in kwargs: alpha = kwargs["alpha"] else: alpha = 1 if cmap is not None: if discrete: warnings.warn( 'discrete keyword used when "palette" key is ' "supplied with visParams, creating a continuous " "colorbar..." ) cmap = mpl.pyplot.get_cmap(cmap) norm = mpl.colors.Normalize(vmin=vmin, vmax=vmax) if "palette" in vis_keys: hexcodes = vis_params["palette"] hexcodes = [i if i[0] == "#" else "#" + i for i in hexcodes] if discrete: cmap = mpl.colors.ListedColormap(hexcodes) vals = np.linspace(vmin, vmax, cmap.N + 1) norm = mpl.colors.BoundaryNorm(vals, cmap.N) else: cmap = mpl.colors.LinearSegmentedColormap.from_list( "custom", hexcodes, N=256 ) norm = mpl.colors.Normalize(vmin=vmin, vmax=vmax) elif cmap is not None: if discrete: warnings.warn( 'discrete keyword used when "palette" key is ' "supplied with visParams, creating a continuous " "colorbar..." ) cmap = mpl.pyplot.get_cmap(cmap) norm = mpl.colors.Normalize(vmin=vmin, vmax=vmax) else: raise ValueError( 'cmap keyword or "palette" key in visParams must be provided' ) tick_font_size = None if "tick_font_size" in kwargs: tick_font_size = kwargs.pop("tick_font_size") label_font_family = None if "label_font_family" in kwargs: label_font_family = kwargs.pop("label_font_family") label_font_size = None if "label_font_size" in kwargs: label_font_size = kwargs.pop("label_font_size") cb = mpl.colorbar.ColorbarBase(cax, norm=norm, alpha=alpha, cmap=cmap, **kwargs) if label is not None: if label_font_size is not None and label_font_family is not None: cb.set_label(label, fontsize=label_font_size, family=label_font_family) elif label_font_size is not None and label_font_family is None: cb.set_label(label, fontsize=label_font_size) elif label_font_size is None and label_font_family is not None: cb.set_label(label, family=label_font_family) else: cb.set_label(label) elif "bands" in vis_keys: cb.set_label(vis_params["bands"]) if tick_font_size is not None: cb.ax.tick_params(labelsize=tick_font_size)
Add a colorbar to the map based on visualization parameters provided args: ax (cartopy.mpl.geoaxes.GeoAxesSubplot | cartopy.mpl.geoaxes.GeoAxes): required cartopy GeoAxesSubplot object to add image overlay to loc (str, optional): string specifying the position vis_params (dict, optional): visualization parameters as a dictionary. See https://developers.google.com/earth-engine/guides/image_visualization for options. **kwargs: remaining keyword arguments are passed to colorbar() raises: Warning: If 'discrete' is true when "palette" key is not in visParams ValueError: If `ax` is not of type cartopy.mpl.geoaxes.GeoAxesSubplot ValueError: If 'cmap' or "palette" key in visParams is not provided ValueError: If "min" in visParams is not of type scalar ValueError: If "max" in visParams is not of type scalar ValueError: If 'loc' or 'cax' keywords are not provided ValueError: If 'loc' is not of type str or does not equal available options
12,171
import logging import os import subprocess import sys import warnings from collections.abc import Iterable from io import BytesIO import ee import matplotlib as mpl import matplotlib.patches as patches import matplotlib.pyplot as plt import numpy as np import requests from matplotlib import cm, colors from matplotlib import font_manager as mfonts from .basemaps import custom_tiles The provided code snippet includes necessary dependencies for implementing the `bbox_to_extent` function. Write a Python function `def bbox_to_extent(bbox)` to solve the following problem: Helper function to reorder a list of coordinates from [W,S,E,N] to [W,E,S,N] args: bbox (list[float]): list (or tuple) or coordinates in the order of [W,S,E,N] returns: extent (tuple[float]): tuple of coordinates in the order of [W,E,S,N] Here is the function: def bbox_to_extent(bbox): """Helper function to reorder a list of coordinates from [W,S,E,N] to [W,E,S,N] args: bbox (list[float]): list (or tuple) or coordinates in the order of [W,S,E,N] returns: extent (tuple[float]): tuple of coordinates in the order of [W,E,S,N] """ return (bbox[0], bbox[2], bbox[1], bbox[3])
Helper function to reorder a list of coordinates from [W,S,E,N] to [W,E,S,N] args: bbox (list[float]): list (or tuple) or coordinates in the order of [W,S,E,N] returns: extent (tuple[float]): tuple of coordinates in the order of [W,E,S,N]
12,172
import logging import os import subprocess import sys import warnings from collections.abc import Iterable from io import BytesIO import ee import matplotlib as mpl import matplotlib.patches as patches import matplotlib.pyplot as plt import numpy as np import requests from matplotlib import cm, colors from matplotlib import font_manager as mfonts from .basemaps import custom_tiles The provided code snippet includes necessary dependencies for implementing the `pad_view` function. Write a Python function `def pad_view(ax, factor=0.05)` to solve the following problem: Function to pad area around the view extent of a map, used for visual appeal args: ax (cartopy.mpl.geoaxes.GeoAxesSubplot | cartopy.mpl.geoaxes.GeoAxes): required cartopy GeoAxesSubplot object to pad view extent factor (float | list[float], optional): factor to pad view extent accepts float [0-1] of a list of floats which will be interpreted at [xfactor, yfactor] Here is the function: def pad_view(ax, factor=0.05): """Function to pad area around the view extent of a map, used for visual appeal args: ax (cartopy.mpl.geoaxes.GeoAxesSubplot | cartopy.mpl.geoaxes.GeoAxes): required cartopy GeoAxesSubplot object to pad view extent factor (float | list[float], optional): factor to pad view extent accepts float [0-1] of a list of floats which will be interpreted at [xfactor, yfactor] """ view_extent = ax.get_extent() if isinstance(factor, Iterable): xfactor, yfactor = factor else: xfactor, yfactor = factor, factor x_diff = view_extent[1] - view_extent[0] y_diff = view_extent[3] - view_extent[2] xmin = view_extent[0] - (x_diff * xfactor) xmax = view_extent[1] + (x_diff * xfactor) ymin = view_extent[2] - (y_diff * yfactor) ymax = view_extent[3] + (y_diff * yfactor) ax.set_ylim(ymin, ymax) ax.set_xlim(xmin, xmax) return
Function to pad area around the view extent of a map, used for visual appeal args: ax (cartopy.mpl.geoaxes.GeoAxesSubplot | cartopy.mpl.geoaxes.GeoAxes): required cartopy GeoAxesSubplot object to pad view extent factor (float | list[float], optional): factor to pad view extent accepts float [0-1] of a list of floats which will be interpreted at [xfactor, yfactor]
12,173
import logging import os import subprocess import sys import warnings from collections.abc import Iterable from io import BytesIO import ee import matplotlib as mpl import matplotlib.patches as patches import matplotlib.pyplot as plt import numpy as np import requests from matplotlib import cm, colors from matplotlib import font_manager as mfonts from .basemaps import custom_tiles def convert_SI(val, unit_in, unit_out): """Unit converter. Args: val (float): The value to convert. unit_in (str): The input unit. unit_out (str): The output unit. Returns: float: The value after unit conversion. """ SI = { "cm": 0.01, "m": 1.0, "km": 1000.0, "inch": 0.0254, "foot": 0.3048, "mile": 1609.34, } return val * SI[unit_in] / SI[unit_out] The provided code snippet includes necessary dependencies for implementing the `add_scale_bar` function. Write a Python function `def add_scale_bar( ax, metric_distance=4, unit="km", at_x=(0.05, 0.5), at_y=(0.08, 0.11), max_stripes=5, ytick_label_margins=0.25, fontsize=8, font_weight="bold", rotation=0, zorder=999, paddings={"xmin": 0.05, "xmax": 0.05, "ymin": 1.5, "ymax": 0.5}, bbox_kwargs={"facecolor": "white", "edgecolor": "black", "alpha": 0.5}, )` to solve the following problem: Add a scale bar to the map. Args: ax (cartopy.mpl.geoaxes.GeoAxesSubplot | cartopy.mpl.geoaxes.GeoAxes): required cartopy GeoAxesSubplot object. metric_distance (int | float, optional): length in meters of each region of the scale bar. Default to 4. unit (str, optional): scale bar distance unit. Default to "km" at_x (float, optional): target axes X coordinates (0..1) of box (= left, right). Default to (0.05, 0.2). at_y (float, optional): axes Y coordinates (0..1) of box (= lower, upper). Default to (0.08, 0.11). max_stripes (int, optional): typical/maximum number of black+white regions. Default to 5. ytick_label_margins (float, optional): Location of distance labels on the Y axis. Default to 0.25. fontsize (int, optional): scale bar text size. Default to 8. font_weight (str, optional):font weight. Default to 'bold'. rotation (int, optional): rotation of the length labels for each region of the scale bar. Default to 0. zorder (float, optional): z order of the text bounding box. paddings (dict, optional): boundaries of the box that contains the scale bar. bbox_kwargs (dict, optional): style of the box containing the scale bar. Here is the function: def add_scale_bar( ax, metric_distance=4, unit="km", at_x=(0.05, 0.5), at_y=(0.08, 0.11), max_stripes=5, ytick_label_margins=0.25, fontsize=8, font_weight="bold", rotation=0, zorder=999, paddings={"xmin": 0.05, "xmax": 0.05, "ymin": 1.5, "ymax": 0.5}, bbox_kwargs={"facecolor": "white", "edgecolor": "black", "alpha": 0.5}, ): """ Add a scale bar to the map. Args: ax (cartopy.mpl.geoaxes.GeoAxesSubplot | cartopy.mpl.geoaxes.GeoAxes): required cartopy GeoAxesSubplot object. metric_distance (int | float, optional): length in meters of each region of the scale bar. Default to 4. unit (str, optional): scale bar distance unit. Default to "km" at_x (float, optional): target axes X coordinates (0..1) of box (= left, right). Default to (0.05, 0.2). at_y (float, optional): axes Y coordinates (0..1) of box (= lower, upper). Default to (0.08, 0.11). max_stripes (int, optional): typical/maximum number of black+white regions. Default to 5. ytick_label_margins (float, optional): Location of distance labels on the Y axis. Default to 0.25. fontsize (int, optional): scale bar text size. Default to 8. font_weight (str, optional):font weight. Default to 'bold'. rotation (int, optional): rotation of the length labels for each region of the scale bar. Default to 0. zorder (float, optional): z order of the text bounding box. paddings (dict, optional): boundaries of the box that contains the scale bar. bbox_kwargs (dict, optional): style of the box containing the scale bar. """ warnings.filterwarnings("ignore") # -------------------------------------------------------------------------- # Auxiliary functions def _crs_coord_project(crs_target, xcoords, ycoords, crs_source): """metric coordinates (x, y) from cartopy.crs_source""" axes_coords = crs_target.transform_points(crs_source, xcoords, ycoords) return axes_coords def _add_bbox(ax, list_of_patches, paddings={}, bbox_kwargs={}): """ Description: This helper function adds a box behind the scalebar: Code inspired by: https://stackoverflow.com/questions/17086847/box-around-text-in-matplotlib """ zorder = list_of_patches[0].get_zorder() - 1 xmin = min([t.get_window_extent().xmin for t in list_of_patches]) xmax = max([t.get_window_extent().xmax for t in list_of_patches]) ymin = min([t.get_window_extent().ymin for t in list_of_patches]) ymax = max([t.get_window_extent().ymax for t in list_of_patches]) xmin, ymin = ax.transData.inverted().transform((xmin, ymin)) xmax, ymax = ax.transData.inverted().transform((xmax, ymax)) xmin = xmin - ((xmax - xmin) * paddings["xmin"]) ymin = ymin - ((ymax - ymin) * paddings["ymin"]) xmax = xmax + ((xmax - xmin) * paddings["xmax"]) ymax = ymax + ((ymax - ymin) * paddings["ymax"]) width = xmax - xmin height = ymax - ymin # Setting xmin according to height rect = patches.Rectangle( (xmin, ymin), width, height, facecolor=bbox_kwargs["facecolor"], edgecolor=bbox_kwargs["edgecolor"], alpha=bbox_kwargs["alpha"], transform=ax.projection, fill=True, clip_on=False, zorder=zorder, ) ax.add_patch(rect) return ax # -------------------------------------------------------------------------- old_proj = ax.projection ax.projection = ccrs.PlateCarree() # Set a planar (metric) projection for the centroid of a given axes projection: # First get centroid lon and lat coordinates: lon_0, lon_1, lat_0, lat_1 = ax.get_extent(ax.projection.as_geodetic()) central_lon = np.mean([lon_0, lon_1]) central_lat = np.mean([lat_0, lat_1]) # Second: set the planar (metric) projection centered in the centroid of the axes; # Centroid coordinates must be in lon/lat. proj = ccrs.EquidistantConic( central_longitude=central_lon, central_latitude=central_lat ) # fetch axes coordinates in meters x0, _, y0, y1 = ax.get_extent(proj) ymean = np.mean([y0, y1]) # set target rectangle in-visible-area (aka 'Axes') coordinates axfrac_ini, _ = at_x ayfrac_ini, ayfrac_final = at_y # choose exact X points as sensible grid ticks with Axis 'ticker' helper converted_metric_distance = convert_SI(metric_distance, unit, "m") xcoords = [] ycoords = [] xlabels = [] for i in range(0, 1 + max_stripes): dx = (converted_metric_distance * i) + x0 xlabels.append(metric_distance * i) xcoords.append(dx) ycoords.append(ymean) # Convertin to arrays: xcoords = np.asanyarray(xcoords) ycoords = np.asanyarray(ycoords) # Ensuring that the coordinate projection is in degrees: x_targets, _, _ = _crs_coord_project(ax.projection, xcoords, ycoords, proj).T x_targets = [x + (axfrac_ini * (lon_1 - lon_0)) for x in x_targets] # Checking x_ticks in axes projection coordinates # print('x_targets', x_targets) # Setting transform for plotting transform = ax.projection # grab min+max for limits xl0, xl1 = x_targets[0], x_targets[-1] # calculate Axes Y coordinates of box top+bottom yl0, yl1 = [ lat_0 + ay_frac * (lat_1 - lat_0) for ay_frac in [ayfrac_ini, ayfrac_final] ] # calculate Axes Y distance of ticks + label margins y_margin = (yl1 - yl0) * ytick_label_margins # fill black/white 'stripes' and draw their boundaries fill_colors = ["black", "white"] i_color = 0 filled_boxs = [] for xi0, xi1 in zip(x_targets[:-1], x_targets[1:]): # fill region filled_box = plt.fill( (xi0, xi1, xi1, xi0, xi0), (yl0, yl0, yl1, yl1, yl0), fill_colors[i_color], transform=transform, clip_on=False, zorder=zorder, ) filled_boxs.append(filled_box[0]) # draw boundary plt.plot( (xi0, xi1, xi1, xi0, xi0), (yl0, yl0, yl1, yl1, yl0), "black", clip_on=False, transform=transform, zorder=zorder, ) i_color = 1 - i_color # adding boxes _add_bbox(ax, filled_boxs, bbox_kwargs=bbox_kwargs, paddings=paddings) # add short tick lines for x in x_targets: plt.plot( (x, x), (yl0, yl0 - y_margin), "black", transform=transform, zorder=zorder, clip_on=False, ) # add a scale legend unit font_props = mfonts.FontProperties(size=fontsize, weight=font_weight) plt.text( 0.5 * (xl0 + xl1), yl1 + y_margin, unit, color="black", verticalalignment="bottom", horizontalalignment="center", fontproperties=font_props, transform=transform, clip_on=False, zorder=zorder, ) # add numeric labels for x, xlabel in zip(x_targets, xlabels): # print("Label set in: ", x, yl0 - 2 * y_margin) plt.text( x, yl0 - 2 * y_margin, "{:g}".format((xlabel)), verticalalignment="top", horizontalalignment="center", fontproperties=font_props, transform=transform, rotation=rotation, clip_on=False, zorder=zorder + 1, # bbox=dict(facecolor='red', alpha=0.5) # this would add a box only around the xticks ) # Adjusting figure borders to ensure that the scalebar is within its limits ax.projection = old_proj ax.get_figure().canvas.draw() # fig.tight_layout()
Add a scale bar to the map. Args: ax (cartopy.mpl.geoaxes.GeoAxesSubplot | cartopy.mpl.geoaxes.GeoAxes): required cartopy GeoAxesSubplot object. metric_distance (int | float, optional): length in meters of each region of the scale bar. Default to 4. unit (str, optional): scale bar distance unit. Default to "km" at_x (float, optional): target axes X coordinates (0..1) of box (= left, right). Default to (0.05, 0.2). at_y (float, optional): axes Y coordinates (0..1) of box (= lower, upper). Default to (0.08, 0.11). max_stripes (int, optional): typical/maximum number of black+white regions. Default to 5. ytick_label_margins (float, optional): Location of distance labels on the Y axis. Default to 0.25. fontsize (int, optional): scale bar text size. Default to 8. font_weight (str, optional):font weight. Default to 'bold'. rotation (int, optional): rotation of the length labels for each region of the scale bar. Default to 0. zorder (float, optional): z order of the text bounding box. paddings (dict, optional): boundaries of the box that contains the scale bar. bbox_kwargs (dict, optional): style of the box containing the scale bar.
12,174
import logging import os import subprocess import sys import warnings from collections.abc import Iterable from io import BytesIO import ee import matplotlib as mpl import matplotlib.patches as patches import matplotlib.pyplot as plt import numpy as np import requests from matplotlib import cm, colors from matplotlib import font_manager as mfonts from .basemaps import custom_tiles def create_legend( linewidth=None, linestyle=None, color=None, marker=None, markersize=None, markeredgewidth=None, markeredgecolor=None, markerfacecolor=None, markerfacecoloralt=None, fillstyle=None, antialiased=None, dash_capstyle=None, solid_capstyle=None, dash_joinstyle=None, solid_joinstyle=None, pickradius=5, drawstyle=None, markevery=None, **kwargs, ): if linewidth is None and marker is None: raise ValueError("Either linewidth or marker must be specified.")
null
12,175
import logging import os import subprocess import sys import warnings from collections.abc import Iterable from io import BytesIO import ee import matplotlib as mpl import matplotlib.patches as patches import matplotlib.pyplot as plt import numpy as np import requests from matplotlib import cm, colors from matplotlib import font_manager as mfonts from .basemaps import custom_tiles The provided code snippet includes necessary dependencies for implementing the `add_legend` function. Write a Python function `def add_legend( ax, legend_elements=None, loc="lower right", font_size=14, font_weight="normal", font_color="black", font_family=None, title=None, title_fontize=16, title_fontproperties=None, **kwargs, )` to solve the following problem: Adds a legend to the map. The legend elements can be formatted as: legend_elements = [Line2D([], [], color='#00ffff', lw=2, label='Coastline'), Line2D([], [], marker='o', color='#A8321D', label='City', markerfacecolor='#A8321D', markersize=10, ls ='')] For more legend properties, see: https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.legend.html Args: ax (cartopy.mpl.geoaxes.GeoAxesSubplot | cartopy.mpl.geoaxes.GeoAxes): required cartopy GeoAxesSubplot object. legend_elements (list, optional): A list of legend elements. Defaults to None. loc (str, optional): Location of the legend, can be any of ['upper left', 'upper right', 'lower left', 'lower right']. Defaults to "lower right". font_size(int|string, optional): Font size. Either an absolute font size or an relative value of 'xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large'. defaults to 14. font_weight(string|int, optional): Font weight. A numeric value in the range 0-1000 or one of 'ultralight', 'light', 'normal' (default), 'regular', 'book', 'medium', 'roman', 'semibold', 'demibold', 'demi', 'bold', 'heavy', 'extra bold', 'black'. Defaults to 'normal'. font_color(str, optional): Text color. Defaults to "black". font_family(string, optional): Name of font family. Set to a font family like 'SimHei' if you want to show Chinese in the legend. Defaults to None. Raises: Exception: If the legend fails to add. Here is the function: def add_legend( ax, legend_elements=None, loc="lower right", font_size=14, font_weight="normal", font_color="black", font_family=None, title=None, title_fontize=16, title_fontproperties=None, **kwargs, ): """Adds a legend to the map. The legend elements can be formatted as: legend_elements = [Line2D([], [], color='#00ffff', lw=2, label='Coastline'), Line2D([], [], marker='o', color='#A8321D', label='City', markerfacecolor='#A8321D', markersize=10, ls ='')] For more legend properties, see: https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.legend.html Args: ax (cartopy.mpl.geoaxes.GeoAxesSubplot | cartopy.mpl.geoaxes.GeoAxes): required cartopy GeoAxesSubplot object. legend_elements (list, optional): A list of legend elements. Defaults to None. loc (str, optional): Location of the legend, can be any of ['upper left', 'upper right', 'lower left', 'lower right']. Defaults to "lower right". font_size(int|string, optional): Font size. Either an absolute font size or an relative value of 'xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large'. defaults to 14. font_weight(string|int, optional): Font weight. A numeric value in the range 0-1000 or one of 'ultralight', 'light', 'normal' (default), 'regular', 'book', 'medium', 'roman', 'semibold', 'demibold', 'demi', 'bold', 'heavy', 'extra bold', 'black'. Defaults to 'normal'. font_color(str, optional): Text color. Defaults to "black". font_family(string, optional): Name of font family. Set to a font family like 'SimHei' if you want to show Chinese in the legend. Defaults to None. Raises: Exception: If the legend fails to add. """ from matplotlib.lines import Line2D if title_fontize is not None and (title_fontproperties is not None): raise ValueError("title_fontize and title_fontproperties cannot be both set.") elif title_fontize is not None: kwargs["title_fontsize"] = title_fontize elif title_fontproperties is not None: kwargs["title_fontproperties"] = title_fontproperties try: if legend_elements is None: legend_elements = [ Line2D([], [], color="#00ffff", lw=2, label="Coastline"), Line2D( [], [], marker="o", color="#A8321D", label="City", markerfacecolor="#A8321D", markersize=10, ls="", ), ] if font_family is not None: fontdict = {"family": font_family, "size": font_size, "weight": font_weight} else: fontdict = {"size": font_size, "weight": font_weight} leg = ax.legend( handles=legend_elements, loc=loc, prop=fontdict, title=title, **kwargs, ) # Change font color If default color is changed. if font_color != "black": for text in leg.get_texts(): text.set_color(font_color) return except Exception as e: raise Exception(e)
Adds a legend to the map. The legend elements can be formatted as: legend_elements = [Line2D([], [], color='#00ffff', lw=2, label='Coastline'), Line2D([], [], marker='o', color='#A8321D', label='City', markerfacecolor='#A8321D', markersize=10, ls ='')] For more legend properties, see: https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.legend.html Args: ax (cartopy.mpl.geoaxes.GeoAxesSubplot | cartopy.mpl.geoaxes.GeoAxes): required cartopy GeoAxesSubplot object. legend_elements (list, optional): A list of legend elements. Defaults to None. loc (str, optional): Location of the legend, can be any of ['upper left', 'upper right', 'lower left', 'lower right']. Defaults to "lower right". font_size(int|string, optional): Font size. Either an absolute font size or an relative value of 'xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large'. defaults to 14. font_weight(string|int, optional): Font weight. A numeric value in the range 0-1000 or one of 'ultralight', 'light', 'normal' (default), 'regular', 'book', 'medium', 'roman', 'semibold', 'demibold', 'demi', 'bold', 'heavy', 'extra bold', 'black'. Defaults to 'normal'. font_color(str, optional): Text color. Defaults to "black". font_family(string, optional): Name of font family. Set to a font family like 'SimHei' if you want to show Chinese in the legend. Defaults to None. Raises: Exception: If the legend fails to add.
12,176
import logging import os import subprocess import sys import warnings from collections.abc import Iterable from io import BytesIO import ee import matplotlib as mpl import matplotlib.patches as patches import matplotlib.pyplot as plt import numpy as np import requests from matplotlib import cm, colors from matplotlib import font_manager as mfonts from .basemaps import custom_tiles def get_map(ee_object, proj=None, basemap=None, zoom_level=2, **kwargs): """ Wrapper function to create a new cartopy plot with project and adds Earth Engine image results Args: ee_object (ee.Image | ee.FeatureCollection): Earth Engine image result to plot proj (cartopy.crs, optional): Cartopy projection that determines the projection of the resulting plot. By default uses an equirectangular projection, PlateCarree basemap (str, optional): Basemap to use. It can be one of ["ROADMAP", "SATELLITE", "TERRAIN", "HYBRID"] or cartopy.io.img_tiles, such as cimgt.StamenTerrain(). Defaults to None. See https://scitools.org.uk/cartopy/docs/v0.19/cartopy/io/img_tiles.html zoom_level (int, optional): Zoom level of the basemap. Defaults to 2. **kwargs: remaining keyword arguments are passed to addLayer() Returns: ax (cartopy.mpl.geoaxes.GeoAxesSubplot): cartopy GeoAxesSubplot object with Earth Engine results displayed """ if ( isinstance(ee_object, ee.geometry.Geometry) or isinstance(ee_object, ee.feature.Feature) or isinstance(ee_object, ee.featurecollection.FeatureCollection) ): features = ee.FeatureCollection(ee_object) if "style" in kwargs and kwargs["style"] is not None: style = kwargs["style"] else: style = {} props = features.first().propertyNames().getInfo() if "style" in props: ee_object = features.style(**{"styleProperty": "style"}) else: ee_object = features.style(**style) elif isinstance(ee_object, ee.imagecollection.ImageCollection): ee_object = ee_object.mosaic() if proj is None: proj = ccrs.PlateCarree() if "style" in kwargs: del kwargs["style"] ax = mpl.pyplot.axes(projection=proj) if basemap is not None: if isinstance(basemap, str): if basemap.upper() in ["ROADMAP", "SATELLITE", "TERRAIN", "HYBRID"]: basemap = cimgt.GoogleTiles( url=custom_tiles["xyz"][basemap.upper()]["url"] ) try: ax.add_image(basemap, zoom_level) except Exception as e: print("Failed to add basemap: ", e) add_layer(ax, ee_object, **kwargs) return ax def add_gridlines( ax, interval=None, n_ticks=None, xs=None, ys=None, buffer_out=True, xtick_rotation="horizontal", ytick_rotation="horizontal", **kwargs, ): """Helper function to add gridlines and format ticks to map args: ax (cartopy.mpl.geoaxes.GeoAxesSubplot | cartopy.mpl.geoaxes.GeoAxes): required cartopy GeoAxesSubplot object to add the gridlines to interval (float | list[float], optional): float specifying an interval at which to create gridlines, units are decimal degrees. lists will be interpreted a [x_interval, y_interval]. default = None n_ticks (int | list[int], optional): integer specifying number gridlines to create within map extent. lists will be interpreted a [nx, ny]. default = None xs (list, optional): list of x coordinates to create gridlines. default = None ys (list, optional): list of y coordinates to create gridlines. default = None buffer_out (boolean, optional): boolean option to buffer out the extent to insure coordinates created cover map extent. default=true xtick_rotation (str | float, optional): ytick_rotation (str | float, optional): **kwargs: remaining keyword arguments are passed to gridlines() raises: ValueError: if all interval, n_ticks, or (xs,ys) are set to None """ view_extent = ax.get_extent() extent = view_extent if xs is not None: xmain = xs elif interval is not None: if isinstance(interval, Iterable): xspace = interval[0] else: xspace = interval if buffer_out: extent = _buffer_box(extent, xspace) xmain = np.arange(extent[0], extent[1] + xspace, xspace) elif n_ticks is not None: if isinstance(n_ticks, Iterable): n_x = n_ticks[0] else: n_x = n_ticks xmain = np.linspace(extent[0], extent[1], n_x) else: raise ValueError( "one of variables interval, n_ticks, or xs must be defined. If you would like default gridlines, please use `ax.gridlines()`" ) if ys is not None: ymain = ys elif interval is not None: if isinstance(interval, Iterable): yspace = interval[1] else: yspace = interval if buffer_out: extent = _buffer_box(extent, yspace) ymain = np.arange(extent[2], extent[3] + yspace, yspace) elif n_ticks is not None: if isinstance(n_ticks, Iterable): n_y = n_ticks[1] else: n_y = n_ticks ymain = np.linspace(extent[2], extent[3], n_y) else: raise ValueError( "one of variables interval, n_ticks, or ys must be defined. If you would like default gridlines, please use `ax.gridlines()`" ) ax.gridlines(xlocs=xmain, ylocs=ymain, **kwargs) xin = xmain[(xmain >= view_extent[0]) & (xmain <= view_extent[1])] yin = ymain[(ymain >= view_extent[2]) & (ymain <= view_extent[3])] # set tick labels ax.set_xticks(xin, crs=ccrs.PlateCarree()) ax.set_yticks(yin, crs=ccrs.PlateCarree()) ax.set_xticklabels(xin, rotation=xtick_rotation, ha="center") ax.set_yticklabels(yin, rotation=ytick_rotation, va="center") ax.xaxis.set_major_formatter(LONGITUDE_FORMATTER) ax.yaxis.set_major_formatter(LATITUDE_FORMATTER) return def add_north_arrow( ax, text="N", xy=(0.1, 0.1), arrow_length=0.1, text_color="black", arrow_color="black", fontsize=20, width=5, headwidth=15, ha="center", va="center", ): """Add a north arrow to the map. Args: ax (cartopy.mpl.geoaxes.GeoAxesSubplot | cartopy.mpl.geoaxes.GeoAxes): required cartopy GeoAxesSubplot object. text (str, optional): Text for north arrow. Defaults to "N". xy (tuple, optional): Location of the north arrow. Each number representing the percentage length of the map from the lower-left cornor. Defaults to (0.1, 0.1). arrow_length (float, optional): Length of the north arrow. Defaults to 0.1 (10% length of the map). text_color (str, optional): Text color. Defaults to "black". arrow_color (str, optional): North arrow color. Defaults to "black". fontsize (int, optional): Text font size. Defaults to 20. width (int, optional): Width of the north arrow. Defaults to 5. headwidth (int, optional): head width of the north arrow. Defaults to 15. ha (str, optional): Horizontal alignment. Defaults to "center". va (str, optional): Vertical alignment. Defaults to "center". """ ax.annotate( text, xy=xy, xytext=(xy[0], xy[1] - arrow_length), color=text_color, arrowprops=dict(facecolor=arrow_color, width=width, headwidth=headwidth), ha=ha, va=va, fontsize=fontsize, xycoords=ax.transAxes, ) return def add_scale_bar_lite( ax, length=None, xy=(0.5, 0.05), linewidth=3, fontsize=20, color="black", unit="km", ha="center", va="bottom", ): """Add a lite version of scale bar to the map. Reference: https://stackoverflow.com/a/50674451/2676166 Args: ax (cartopy.mpl.geoaxes.GeoAxesSubplot | cartopy.mpl.geoaxes.GeoAxes): required cartopy GeoAxesSubplot object. length ([type], optional): Length of the scale car. Defaults to None. xy (tuple, optional): Location of the north arrow. Each number representing the percentage length of the map from the lower-left cornor. Defaults to (0.1, 0.1). linewidth (int, optional): Line width of the scale bar. Defaults to 3. fontsize (int, optional): Text font size. Defaults to 20. color (str, optional): Color for the scale bar. Defaults to "black". unit (str, optional): Length unit for the scale bar. Defaults to "km". ha (str, optional): Horizontal alignment. Defaults to "center". va (str, optional): Vertical alignment. Defaults to "bottom". """ allow_units = ["cm", "m", "km", "inch", "foot", "mile"] if unit not in allow_units: print( "The unit must be one of the following: {}".format(", ".join(allow_units)) ) return num = length # Get the limits of the axis in lat long llx0, llx1, lly0, lly1 = ax.get_extent(ccrs.PlateCarree()) # Make tmc horizontally centred on the middle of the map, # vertically at scale bar location sbllx = (llx1 + llx0) / 2 sblly = lly0 + (lly1 - lly0) * xy[1] tmc = ccrs.TransverseMercator(sbllx, sblly, approx=True) # Get the extent of the plotted area in coordinates in metres x0, x1, y0, y1 = ax.get_extent(tmc) # Turn the specified scalebar location into coordinates in metres sbx = x0 + (x1 - x0) * xy[0] sby = y0 + (y1 - y0) * xy[1] # Calculate a scale bar length if none has been given # (There's probably a more pythonic way of rounding the number but this works) if not length: length = (x1 - x0) / 5000 # in km ndim = int(np.floor(np.log10(length))) # number of digits in number length = round(length, -ndim) # round to 1sf # Returns numbers starting with the list def scale_number(x): if str(x)[0] in ["1", "2", "5"]: return int(x) else: return scale_number(x - 10**ndim) length = scale_number(length) num = length else: length = convert_SI(length, unit, "km") # Generate the x coordinate for the ends of the scalebar bar_xs = [sbx - length * 500, sbx + length * 500] # Plot the scalebar ax.plot(bar_xs, [sby, sby], transform=tmc, color=color, linewidth=linewidth) # Plot the scalebar label ax.text( sbx, sby, str(num) + " " + unit, transform=tmc, horizontalalignment=ha, verticalalignment=va, color=color, fontsize=fontsize, ) return def savefig(fig, fname, dpi="figure", bbox_inches="tight", **kwargs): """Save figure to file. It wraps the matplotlib.pyplot.savefig() function. See https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.savefig.html for more details. Args: fig (matplotlib.figure.Figure): The figure to save. fname (str): A path to a file, or a Python file-like object. dpi (int | str, optional): The resolution in dots per inch. If 'figure', use the figure's dpi value. Defaults to 'figure'. bbox_inches (str, optional): Bounding box in inches: only the given portion of the figure is saved. If 'tight', try to figure out the tight bbox of the figure. kwargs (dict, optional): Additional keyword arguments are passed on to the savefig() method. """ fig.savefig(fname=fname, dpi=dpi, bbox_inches=bbox_inches, **kwargs) The provided code snippet includes necessary dependencies for implementing the `get_image_collection_gif` function. Write a Python function `def get_image_collection_gif( ee_ic, out_dir, out_gif, vis_params, region, cmap=None, proj=None, fps=10, mp4=False, grid_interval=None, plot_title="", date_format="YYYY-MM-dd", fig_size=(10, 10), dpi_plot=100, file_format="png", north_arrow_dict={}, scale_bar_dict={}, verbose=True, )` to solve the following problem: Download all the images in an image collection and use them to generate a gif/video. Args: ee_ic (object): ee.ImageCollection out_dir (str): The output directory of images and video. out_gif (str): The name of the gif file. vis_params (dict): Visualization parameters as a dictionary. region (list | tuple): Geospatial region of the image to render in format [E,S,W,N]. fps (int, optional): Video frames per second. Defaults to 10. mp4 (bool, optional): Whether to create mp4 video. grid_interval (float | tuple[float]): Float specifying an interval at which to create gridlines, units are decimal degrees. lists will be interpreted a (x_interval, y_interval), such as (0.1, 0.1). Defaults to None. plot_title (str): Plot title. Defaults to "". date_format (str, optional): A pattern, as described at http://joda-time.sourceforge.net/apidocs/org/joda/time/format/DateTimeFormat.html. Defaults to "YYYY-MM-dd". fig_size (tuple, optional): Size of the figure. dpi_plot (int, optional): The resolution in dots per inch of the plot. file_format (str, optional): Either 'png' or 'jpg'. north_arrow_dict (dict, optional): Parameters for the north arrow. See https://geemap.org/cartoee/#geemap.cartoee.add_north_arrow. Defaults to {}. scale_bar_dict (dict, optional): Parameters for the scale bar. See https://geemap.org/cartoee/#geemap.cartoee.add_scale_bar. Defaults. to {}. verbose (bool, optional): Whether or not to print text when the program is running. Defaults to True. Here is the function: def get_image_collection_gif( ee_ic, out_dir, out_gif, vis_params, region, cmap=None, proj=None, fps=10, mp4=False, grid_interval=None, plot_title="", date_format="YYYY-MM-dd", fig_size=(10, 10), dpi_plot=100, file_format="png", north_arrow_dict={}, scale_bar_dict={}, verbose=True, ): """Download all the images in an image collection and use them to generate a gif/video. Args: ee_ic (object): ee.ImageCollection out_dir (str): The output directory of images and video. out_gif (str): The name of the gif file. vis_params (dict): Visualization parameters as a dictionary. region (list | tuple): Geospatial region of the image to render in format [E,S,W,N]. fps (int, optional): Video frames per second. Defaults to 10. mp4 (bool, optional): Whether to create mp4 video. grid_interval (float | tuple[float]): Float specifying an interval at which to create gridlines, units are decimal degrees. lists will be interpreted a (x_interval, y_interval), such as (0.1, 0.1). Defaults to None. plot_title (str): Plot title. Defaults to "". date_format (str, optional): A pattern, as described at http://joda-time.sourceforge.net/apidocs/org/joda/time/format/DateTimeFormat.html. Defaults to "YYYY-MM-dd". fig_size (tuple, optional): Size of the figure. dpi_plot (int, optional): The resolution in dots per inch of the plot. file_format (str, optional): Either 'png' or 'jpg'. north_arrow_dict (dict, optional): Parameters for the north arrow. See https://geemap.org/cartoee/#geemap.cartoee.add_north_arrow. Defaults to {}. scale_bar_dict (dict, optional): Parameters for the scale bar. See https://geemap.org/cartoee/#geemap.cartoee.add_scale_bar. Defaults. to {}. verbose (bool, optional): Whether or not to print text when the program is running. Defaults to True. """ from .geemap import png_to_gif, jpg_to_gif out_dir = os.path.abspath(out_dir) if not os.path.exists(out_dir): os.makedirs(out_dir) out_gif = os.path.join(out_dir, out_gif) count = int(ee_ic.size().getInfo()) names = ee_ic.aggregate_array("system:index").getInfo() images = ee_ic.toList(count) dates = ee_ic.aggregate_array("system:time_start") dates = dates.map(lambda d: ee.Date(d).format(date_format)).getInfo() digits = len(str(len(dates))) # list of file name img_list = [] for i, date in enumerate(dates): image = ee.Image(images.get(i)) name = str(i + 1).zfill(digits) + "." + file_format out_img = os.path.join(out_dir, name) img_list.append(out_img) if verbose: print(f"Downloading {i+1}/{count}: {name} ...") # Size plot fig = plt.figure(figsize=fig_size) # Set the facecolor fig.patch.set_facecolor("white") # Plot image ax = get_map(image, region=region, vis_params=vis_params, cmap=cmap, proj=proj) # Add grid if grid_interval is not None: add_gridlines(ax, interval=grid_interval, linestyle=":") # Add title if len(plot_title) > 0: ax.set_title(label=plot_title + " " + date + "\n", fontsize=15) # Add scale bar if len(scale_bar_dict) > 0: add_scale_bar_lite(ax, **scale_bar_dict) # Add north arrow if len(north_arrow_dict) > 0: add_north_arrow(ax, **north_arrow_dict) # Save plot plt.savefig( fname=out_img, dpi=dpi_plot, bbox_inches="tight", facecolor=fig.get_facecolor(), ) plt.clf() plt.close() out_gif = os.path.abspath(out_gif) if file_format == "png": png_to_gif(out_dir, out_gif, fps) elif file_format == "jpg": jpg_to_gif(out_dir, out_gif, fps) if verbose: print(f"GIF saved to {out_gif}") if mp4: video_filename = out_gif.replace(".gif", ".mp4") try: import cv2 except ImportError: print("Installing opencv-python ...") subprocess.check_call(["python", "-m", "pip", "install", "opencv-python"]) import cv2 # Video file name output_video_file_name = os.path.join(out_dir, video_filename) frame = cv2.imread(img_list[0]) height, width, _ = frame.shape frame_size = (width, height) fps_video = fps # Make mp4 fourcc = cv2.VideoWriter_fourcc(*"mp4v") # Function def convert_frames_to_video( input_list, output_video_file_name, fps_video, frame_size ): """Convert frames to video Args: input_list (list): Downloaded Image Name List. output_video_file_name (str): The name of the video file in the image directory. fps_video (int): Video frames per second. frame_size (tuple): Frame size. """ out = cv2.VideoWriter(output_video_file_name, fourcc, fps_video, frame_size) num_frames = len(input_list) for i in range(num_frames): img_path = input_list[i] img = cv2.imread(img_path) out.write(img) out.release() cv2.destroyAllWindows() # Use function convert_frames_to_video( input_list=img_list, output_video_file_name=output_video_file_name, fps_video=fps_video, frame_size=frame_size, ) if verbose: print(f"MP4 saved to {output_video_file_name}")
Download all the images in an image collection and use them to generate a gif/video. Args: ee_ic (object): ee.ImageCollection out_dir (str): The output directory of images and video. out_gif (str): The name of the gif file. vis_params (dict): Visualization parameters as a dictionary. region (list | tuple): Geospatial region of the image to render in format [E,S,W,N]. fps (int, optional): Video frames per second. Defaults to 10. mp4 (bool, optional): Whether to create mp4 video. grid_interval (float | tuple[float]): Float specifying an interval at which to create gridlines, units are decimal degrees. lists will be interpreted a (x_interval, y_interval), such as (0.1, 0.1). Defaults to None. plot_title (str): Plot title. Defaults to "". date_format (str, optional): A pattern, as described at http://joda-time.sourceforge.net/apidocs/org/joda/time/format/DateTimeFormat.html. Defaults to "YYYY-MM-dd". fig_size (tuple, optional): Size of the figure. dpi_plot (int, optional): The resolution in dots per inch of the plot. file_format (str, optional): Either 'png' or 'jpg'. north_arrow_dict (dict, optional): Parameters for the north arrow. See https://geemap.org/cartoee/#geemap.cartoee.add_north_arrow. Defaults to {}. scale_bar_dict (dict, optional): Parameters for the scale bar. See https://geemap.org/cartoee/#geemap.cartoee.add_scale_bar. Defaults. to {}. verbose (bool, optional): Whether or not to print text when the program is running. Defaults to True.
12,177
import os The provided code snippet includes necessary dependencies for implementing the `ee_table_to_legend` function. Write a Python function `def ee_table_to_legend(in_table, out_file)` to solve the following problem: Converts an Earth Engine color table to a dictionary Args: in_table (str): The input file path (*.txt) to the Earth Engine color table. out_file (str): The output file path (*.txt) to the legend dictionary. Here is the function: def ee_table_to_legend(in_table, out_file): """Converts an Earth Engine color table to a dictionary Args: in_table (str): The input file path (*.txt) to the Earth Engine color table. out_file (str): The output file path (*.txt) to the legend dictionary. """ # pkg_dir = os.path.dirname(pkg_resources.resource_filename("geemap", "geemap.py")) # ee_legend_table = os.path.join(pkg_dir, "data/template/ee_legend_table.txt") if not os.path.exists(in_table): print("The class table does not exist.") out_file = os.path.abspath(out_file) if not os.path.exists(os.path.dirname(out_file)): os.makedirs(os.path.dirname(out_file)) legend_dict = {} with open(in_table) as f: lines = f.readlines() for index, line in enumerate(lines): if index > 0: items = line.split("\t") items = [item.strip() for item in items] color = items[1] key = items[0] + " " + items[2] legend_dict[key] = color out_lines = [] out_lines.append("{\n") for key in legend_dict.keys(): line = "\t'{}': '{}',\n".format(key, legend_dict[key]) out_lines.append(line) out_lines[-1] = out_lines[-1].rstrip()[:-1] + "\n" out_lines.append("}\n") with open(out_file, "w") as f: f.writelines(out_lines)
Converts an Earth Engine color table to a dictionary Args: in_table (str): The input file path (*.txt) to the Earth Engine color table. out_file (str): The output file path (*.txt) to the legend dictionary.
12,178
import datetime import glob import io import os import shutil import ee from .common import * from typing import Union, List import os The provided code snippet includes necessary dependencies for implementing the `merge_gifs` function. Write a Python function `def merge_gifs(in_gifs, out_gif)` to solve the following problem: Merge multiple gifs into one. Args: in_gifs (str | list): The input gifs as a list or a directory path. out_gif (str): The output gif. Raises: Exception: Raise exception when gifsicle is not installed. Here is the function: def merge_gifs(in_gifs, out_gif): """Merge multiple gifs into one. Args: in_gifs (str | list): The input gifs as a list or a directory path. out_gif (str): The output gif. Raises: Exception: Raise exception when gifsicle is not installed. """ import glob try: if isinstance(in_gifs, str) and os.path.isdir(in_gifs): in_gifs = glob.glob(os.path.join(in_gifs, "*.gif")) elif not isinstance(in_gifs, list): raise Exception("in_gifs must be a list.") in_gifs = " ".join(in_gifs) cmd = f"gifsicle {in_gifs} > {out_gif}" os.system(cmd) except Exception as e: print( "gifsicle is not installed. Run 'sudo apt-get install -y gifsicle' to install it." ) print(e)
Merge multiple gifs into one. Args: in_gifs (str | list): The input gifs as a list or a directory path. out_gif (str): The output gif. Raises: Exception: Raise exception when gifsicle is not installed.
12,179
import datetime import glob import io import os import shutil import ee from .common import * from typing import Union, List def create_timelapse( collection, start_date, end_date, region=None, bands=None, frequency="year", reducer="median", date_format=None, out_gif=None, palette=None, vis_params=None, dimensions=768, frames_per_second=10, crs="EPSG:3857", overlay_data=None, overlay_color="black", overlay_width=1, overlay_opacity=1.0, title=None, title_xy=("2%", "90%"), add_text=True, text_xy=("2%", "2%"), text_sequence=None, font_type="arial.ttf", font_size=20, font_color="white", add_progress_bar=True, progress_bar_color="white", progress_bar_height=5, add_colorbar=False, colorbar_width=6.0, colorbar_height=0.4, colorbar_label=None, colorbar_label_size=12, colorbar_label_weight="normal", colorbar_tick_size=10, colorbar_bg_color=None, colorbar_orientation="horizontal", colorbar_dpi="figure", colorbar_xy=None, colorbar_size=(300, 300), loop=0, mp4=False, fading=False, parallel_scale=1, step=1, ): """Create a timelapse from any ee.ImageCollection. Args: collection (str | ee.ImageCollection): The collection of images to create a timeseries from. It can be a string representing the collection ID or an ee.ImageCollection object. start_date (str): The start date of the timeseries. It must be formatted like this: 'YYYY-MM-dd'. end_date (str): The end date of the timeseries. It must be formatted like this: 'YYYY-MM-dd'. region (ee.Geometry, optional): The region to use to filter the collection of images. It must be an ee.Geometry object. Defaults to None. bands (list, optional): A list of band names to use in the timelapse. Defaults to None. frequency (str, optional): The frequency of the timeseries. It must be one of the following: 'year', 'month', 'day', 'hour', 'minute', 'second'. Defaults to 'year'. reducer (str, optional): The reducer to use to reduce the collection of images to a single value. It can be one of the following: 'median', 'mean', 'min', 'max', 'variance', 'sum'. Defaults to 'median'. drop_empty (bool, optional): Whether to drop empty images from the timeseries. Defaults to True. date_format (str, optional): A pattern, as described at http://joda-time.sourceforge.net/apidocs/org/joda/time/format/DateTimeFormat.html. Defaults to 'YYYY-MM-dd'. out_gif (str): The output gif file path. Defaults to None. palette (list, optional): A list of colors to render a single-band image in the timelapse. Defaults to None. vis_params (dict, optional): A dictionary of visualization parameters to use in the timelapse. Defaults to None. See more at https://developers.google.com/earth-engine/guides/image_visualization. dimensions (int, optional): a number or pair of numbers (in format 'WIDTHxHEIGHT') Maximum dimensions of the thumbnail to render, in pixels. If only one number is passed, it is used as the maximum, and the other dimension is computed by proportional scaling. Defaults to 768. frames_per_second (int, optional): Animation speed. Defaults to 10. crs (str, optional): The coordinate reference system to use. Defaults to "EPSG:3857". overlay_data (int, str, list, optional): Administrative boundary to be drawn on the timelapse. Defaults to None. overlay_color (str, optional): Color for the overlay data. Can be any color name or hex color code. Defaults to 'black'. overlay_width (int, optional): Width of the overlay. Defaults to 1. overlay_opacity (float, optional): Opacity of the overlay. Defaults to 1.0. title (str, optional): The title of the timelapse. Defaults to None. title_xy (tuple, optional): Lower left corner of the title. It can be formatted like this: (10, 10) or ('15%', '25%'). Defaults to None. add_text (bool, optional): Whether to add animated text to the timelapse. Defaults to True. title_xy (tuple, optional): Lower left corner of the text sequency. It can be formatted like this: (10, 10) or ('15%', '25%'). Defaults to None. text_sequence (int, str, list, optional): Text to be drawn. It can be an integer number, a string, or a list of strings. Defaults to None. font_type (str, optional): Font type. Defaults to "arial.ttf". font_size (int, optional): Font size. Defaults to 20. font_color (str, optional): Font color. It can be a string (e.g., 'red'), rgb tuple (e.g., (255, 127, 0)), or hex code (e.g., '#ff00ff'). Defaults to '#000000'. add_progress_bar (bool, optional): Whether to add a progress bar at the bottom of the GIF. Defaults to True. progress_bar_color (str, optional): Color for the progress bar. Defaults to 'white'. progress_bar_height (int, optional): Height of the progress bar. Defaults to 5. add_colorbar (bool, optional): Whether to add a colorbar to the timelapse. Defaults to False. colorbar_width (float, optional): Width of the colorbar. Defaults to 6.0. colorbar_height (float, optional): Height of the colorbar. Defaults to 0.4. colorbar_label (str, optional): Label for the colorbar. Defaults to None. colorbar_label_size (int, optional): Font size for the colorbar label. Defaults to 12. colorbar_label_weight (str, optional): Font weight for the colorbar label. Defaults to 'normal'. colorbar_tick_size (int, optional): Font size for the colorbar ticks. Defaults to 10. colorbar_bg_color (str, optional): Background color for the colorbar, can be color like "white", "black". Defaults to None. colorbar_orientation (str, optional): Orientation of the colorbar. Defaults to 'horizontal'. colorbar_dpi (str, optional): DPI for the colorbar, can be numbers like 100, 300. Defaults to 'figure'. colorbar_xy (tuple, optional): Lower left corner of the colorbar. It can be formatted like this: (10, 10) or ('15%', '25%'). Defaults to None. colorbar_size (tuple, optional): Size of the colorbar. It can be formatted like this: (300, 300). Defaults to (300, 300). loop (int, optional): Controls how many times the animation repeats. The default, 1, means that the animation will play once and then stop (displaying the last frame). A value of 0 means that the animation will repeat forever. Defaults to 0. mp4 (bool, optional): Whether to create an mp4 file. Defaults to False. fading (int | bool, optional): If True, add fading effect to the timelapse. Defaults to False, no fading. To add fading effect, set it to True (1 second fading duration) or to an integer value (fading duration). parallel_scale (int, optional): A scaling factor used to limit memory use; using a larger parallel_scale (e.g. 2 or 4) may enable computations that run out of memory with the default. Defaults to 1. step (int, optional): The step size to use when creating the date sequence. Defaults to 1. Returns: str: File path to the timelapse gif. """ import geemap.colormaps as cm if not isinstance(collection, ee.ImageCollection): if isinstance(collection, str): collection = ee.ImageCollection(collection) else: raise Exception( "The collection must be an ee.ImageCollection object or asset id." ) col = create_timeseries( collection, start_date, end_date, region=region, bands=bands, frequency=frequency, reducer=reducer, drop_empty=True, date_format=date_format, parallel_scale=parallel_scale, step=step, ) # rename the bands to remove the '_reducer' characters from the band names. col = col.map( lambda img: img.rename( img.bandNames().map(lambda name: ee.String(name).replace(f"_{reducer}", "")) ) ) if out_gif is None: out_gif = temp_file_path(".gif") else: out_gif = check_file_path(out_gif) out_dir = os.path.dirname(out_gif) if bands is None: names = col.first().bandNames().getInfo() if len(names) < 3: bands = [names[0]] else: bands = names[:3][::-1] elif isinstance(bands, str): bands = [bands] elif not isinstance(bands, list): raise Exception("The bands must be a string or a list of strings.") if isinstance(palette, str): palette = cm.get_palette(palette, 15) elif isinstance(palette, list) or isinstance(palette, tuple): pass elif palette is not None: raise Exception("The palette must be a string or a list of strings.") if vis_params is None: img = col.first().select(bands) scale = collection.first().select(0).projection().nominalScale().multiply(10) min_value = min( image_min_value(img, region=region, scale=scale).getInfo().values() ) max_value = max( image_max_value(img, region=region, scale=scale).getInfo().values() ) vis_params = {"bands": bands, "min": min_value, "max": max_value} if len(bands) == 1: if palette is not None: vis_params["palette"] = palette else: vis_params["palette"] = cm.palettes.ndvi elif isinstance(vis_params, dict): if "bands" not in vis_params: vis_params["bands"] = bands if "min" not in vis_params: img = col.first().select(bands) scale = ( collection.first().select(0).projection().nominalScale().multiply(10) ) vis_params["min"] = min( image_min_value(img, region=region, scale=scale).getInfo().values() ) if "max" not in vis_params: img = col.first().select(bands) scale = ( collection.first().select(0).projection().nominalScale().multiply(10) ) vis_params["max"] = max( image_max_value(img, region=region, scale=scale).getInfo().values() ) if palette is None and (len(bands) == 1) and ("palette" not in vis_params): vis_params["palette"] = cm.palettes.ndvi elif palette is not None and ("palette" not in vis_params): vis_params["palette"] = palette if len(bands) > 1 and "palette" in vis_params: del vis_params["palette"] else: raise Exception("The vis_params must be a dictionary.") col = col.select(bands).map( lambda img: img.visualize(**vis_params).set( { "system:time_start": img.get("system:time_start"), "system:date": img.get("system:date"), } ) ) if overlay_data is not None: col = add_overlay( col, overlay_data, overlay_color, overlay_width, overlay_opacity ) video_args = {} video_args["dimensions"] = dimensions video_args["region"] = region video_args["framesPerSecond"] = frames_per_second video_args["crs"] = crs video_args["min"] = 0 video_args["max"] = 255 # if crs is not None: # video_args["crs"] = crs if "palette" in vis_params or len(bands) > 1: video_args["bands"] = ["vis-red", "vis-green", "vis-blue"] else: video_args["bands"] = ["vis-gray"] if ( isinstance(dimensions, int) and dimensions > 768 or isinstance(dimensions, str) and any(dim > 768 for dim in list(map(int, dimensions.split("x")))) ): count = col.size().getInfo() basename = os.path.basename(out_gif)[:-4] names = [ os.path.join( out_dir, f"{basename}_{str(i+1).zfill(int(len(str(count))))}.jpg" ) for i in range(count) ] get_image_collection_thumbnails( col, out_dir, vis_params={ "min": 0, "max": 255, "bands": video_args["bands"], }, dimensions=dimensions, names=names, ) make_gif( names, out_gif, fps=frames_per_second, loop=loop, mp4=False, clean_up=True, ) else: download_ee_video(col, video_args, out_gif) if title is not None and isinstance(title, str): add_text_to_gif( out_gif, out_gif, xy=title_xy, text_sequence=title, font_type=font_type, font_size=font_size, font_color=font_color, add_progress_bar=add_progress_bar, progress_bar_color=progress_bar_color, progress_bar_height=progress_bar_height, duration=1000 / frames_per_second, loop=loop, ) if add_text: if text_sequence is None: text_sequence = col.aggregate_array("system:date").getInfo() add_text_to_gif( out_gif, out_gif, xy=text_xy, text_sequence=text_sequence, font_type=font_type, font_size=font_size, font_color=font_color, add_progress_bar=add_progress_bar, progress_bar_color=progress_bar_color, progress_bar_height=progress_bar_height, duration=1000 / frames_per_second, loop=loop, ) if add_colorbar: colorbar = save_colorbar( None, colorbar_width, colorbar_height, vis_params["min"], vis_params["max"], vis_params["palette"], label=colorbar_label, label_size=colorbar_label_size, label_weight=colorbar_label_weight, tick_size=colorbar_tick_size, bg_color=colorbar_bg_color, orientation=colorbar_orientation, dpi=colorbar_dpi, show_colorbar=False, ) add_image_to_gif(out_gif, out_gif, colorbar, colorbar_xy, colorbar_size) if os.path.exists(out_gif): reduce_gif_size(out_gif) if isinstance(fading, bool): fading = int(fading) if fading > 0: gif_fading(out_gif, out_gif, duration=fading, verbose=False) if mp4: out_mp4 = out_gif.replace(".gif", ".mp4") gif_to_mp4(out_gif, out_mp4) return out_gif import datetime import ee The provided code snippet includes necessary dependencies for implementing the `naip_timelapse` function. Write a Python function `def naip_timelapse( roi, start_year=2003, end_year=None, out_gif=None, bands=None, palette=None, vis_params=None, dimensions=768, frames_per_second=3, crs="EPSG:3857", overlay_data=None, overlay_color="black", overlay_width=1, overlay_opacity=1.0, title=None, title_xy=("2%", "90%"), add_text=True, text_xy=("2%", "2%"), text_sequence=None, font_type="arial.ttf", font_size=20, font_color="white", add_progress_bar=True, progress_bar_color="white", progress_bar_height=5, loop=0, mp4=False, fading=False, step=1, )` to solve the following problem: Create a timelapse from NAIP imagery. Args: roi (ee.Geometry): The region to use to filter the collection of images. It must be an ee.Geometry object. Defaults to None. start_year (int | str, optional): The start year of the timeseries. It must be formatted like this: 'YYYY'. Defaults to 2003. end_year (int | str, optional): The end year of the timeseries. It must be formatted like this: 'YYYY'. Defaults to None, which will use the current year. out_gif (str): The output gif file path. Defaults to None. bands (list, optional): A list of band names to use in the timelapse. Defaults to None. palette (list, optional): A list of colors to render a single-band image in the timelapse. Defaults to None. vis_params (dict, optional): A dictionary of visualization parameters to use in the timelapse. Defaults to None. See more at https://developers.google.com/earth-engine/guides/image_visualization. dimensions (int, optional): a number or pair of numbers (in format 'WIDTHxHEIGHT') Maximum dimensions of the thumbnail to render, in pixels. If only one number is passed, it is used as the maximum, and the other dimension is computed by proportional scaling. Defaults to 768. frames_per_second (int, optional): Animation speed. Defaults to 10. crs (str, optional): The coordinate reference system to use. Defaults to "EPSG:3857". overlay_data (int, str, list, optional): Administrative boundary to be drawn on the timelapse. Defaults to None. overlay_color (str, optional): Color for the overlay data. Can be any color name or hex color code. Defaults to 'black'. overlay_width (int, optional): Width of the overlay. Defaults to 1. overlay_opacity (float, optional): Opacity of the overlay. Defaults to 1.0. title (str, optional): The title of the timelapse. Defaults to None. title_xy (tuple, optional): Lower left corner of the title. It can be formatted like this: (10, 10) or ('15%', '25%'). Defaults to None. add_text (bool, optional): Whether to add animated text to the timelapse. Defaults to True. title_xy (tuple, optional): Lower left corner of the text sequency. It can be formatted like this: (10, 10) or ('15%', '25%'). Defaults to None. text_sequence (int, str, list, optional): Text to be drawn. It can be an integer number, a string, or a list of strings. Defaults to None. font_type (str, optional): Font type. Defaults to "arial.ttf". font_size (int, optional): Font size. Defaults to 20. font_color (str, optional): Font color. It can be a string (e.g., 'red'), rgb tuple (e.g., (255, 127, 0)), or hex code (e.g., '#ff00ff'). Defaults to '#000000'. add_progress_bar (bool, optional): Whether to add a progress bar at the bottom of the GIF. Defaults to True. progress_bar_color (str, optional): Color for the progress bar. Defaults to 'white'. progress_bar_height (int, optional): Height of the progress bar. Defaults to 5. loop (int, optional): Controls how many times the animation repeats. The default, 1, means that the animation will play once and then stop (displaying the last frame). A value of 0 means that the animation will repeat forever. Defaults to 0. mp4 (bool, optional): Whether to create an mp4 file. Defaults to False. fading (int | bool, optional): If True, add fading effect to the timelapse. Defaults to False, no fading. To add fading effect, set it to True (1 second fading duration) or to an integer value (fading duration). step (int, optional): The step size to use when creating the date sequence. Defaults to 1. Returns: str: File path to the timelapse gif. Here is the function: def naip_timelapse( roi, start_year=2003, end_year=None, out_gif=None, bands=None, palette=None, vis_params=None, dimensions=768, frames_per_second=3, crs="EPSG:3857", overlay_data=None, overlay_color="black", overlay_width=1, overlay_opacity=1.0, title=None, title_xy=("2%", "90%"), add_text=True, text_xy=("2%", "2%"), text_sequence=None, font_type="arial.ttf", font_size=20, font_color="white", add_progress_bar=True, progress_bar_color="white", progress_bar_height=5, loop=0, mp4=False, fading=False, step=1, ): """Create a timelapse from NAIP imagery. Args: roi (ee.Geometry): The region to use to filter the collection of images. It must be an ee.Geometry object. Defaults to None. start_year (int | str, optional): The start year of the timeseries. It must be formatted like this: 'YYYY'. Defaults to 2003. end_year (int | str, optional): The end year of the timeseries. It must be formatted like this: 'YYYY'. Defaults to None, which will use the current year. out_gif (str): The output gif file path. Defaults to None. bands (list, optional): A list of band names to use in the timelapse. Defaults to None. palette (list, optional): A list of colors to render a single-band image in the timelapse. Defaults to None. vis_params (dict, optional): A dictionary of visualization parameters to use in the timelapse. Defaults to None. See more at https://developers.google.com/earth-engine/guides/image_visualization. dimensions (int, optional): a number or pair of numbers (in format 'WIDTHxHEIGHT') Maximum dimensions of the thumbnail to render, in pixels. If only one number is passed, it is used as the maximum, and the other dimension is computed by proportional scaling. Defaults to 768. frames_per_second (int, optional): Animation speed. Defaults to 10. crs (str, optional): The coordinate reference system to use. Defaults to "EPSG:3857". overlay_data (int, str, list, optional): Administrative boundary to be drawn on the timelapse. Defaults to None. overlay_color (str, optional): Color for the overlay data. Can be any color name or hex color code. Defaults to 'black'. overlay_width (int, optional): Width of the overlay. Defaults to 1. overlay_opacity (float, optional): Opacity of the overlay. Defaults to 1.0. title (str, optional): The title of the timelapse. Defaults to None. title_xy (tuple, optional): Lower left corner of the title. It can be formatted like this: (10, 10) or ('15%', '25%'). Defaults to None. add_text (bool, optional): Whether to add animated text to the timelapse. Defaults to True. title_xy (tuple, optional): Lower left corner of the text sequency. It can be formatted like this: (10, 10) or ('15%', '25%'). Defaults to None. text_sequence (int, str, list, optional): Text to be drawn. It can be an integer number, a string, or a list of strings. Defaults to None. font_type (str, optional): Font type. Defaults to "arial.ttf". font_size (int, optional): Font size. Defaults to 20. font_color (str, optional): Font color. It can be a string (e.g., 'red'), rgb tuple (e.g., (255, 127, 0)), or hex code (e.g., '#ff00ff'). Defaults to '#000000'. add_progress_bar (bool, optional): Whether to add a progress bar at the bottom of the GIF. Defaults to True. progress_bar_color (str, optional): Color for the progress bar. Defaults to 'white'. progress_bar_height (int, optional): Height of the progress bar. Defaults to 5. loop (int, optional): Controls how many times the animation repeats. The default, 1, means that the animation will play once and then stop (displaying the last frame). A value of 0 means that the animation will repeat forever. Defaults to 0. mp4 (bool, optional): Whether to create an mp4 file. Defaults to False. fading (int | bool, optional): If True, add fading effect to the timelapse. Defaults to False, no fading. To add fading effect, set it to True (1 second fading duration) or to an integer value (fading duration). step (int, optional): The step size to use when creating the date sequence. Defaults to 1. Returns: str: File path to the timelapse gif. """ try: if end_year is None: end_year = datetime.datetime.now().year collection = ee.ImageCollection("USDA/NAIP/DOQQ") start_date = str(start_year) + "-01-01" end_date = str(end_year) + "-12-31" frequency = "year" reducer = "median" date_format = "YYYY" if bands is not None and isinstance(bands, list) and "N" in bands: collection = collection.filter( ee.Filter.listContains("system:band_names", "N") ) return create_timelapse( collection, start_date, end_date, roi, bands, frequency, reducer, date_format, out_gif, palette, vis_params, dimensions, frames_per_second, crs, overlay_data, overlay_color, overlay_width, overlay_opacity, title, title_xy, add_text, text_xy, text_sequence, font_type, font_size, font_color, add_progress_bar, progress_bar_color, progress_bar_height, loop=loop, mp4=mp4, fading=fading, step=step, ) except Exception as e: raise Exception(e)
Create a timelapse from NAIP imagery. Args: roi (ee.Geometry): The region to use to filter the collection of images. It must be an ee.Geometry object. Defaults to None. start_year (int | str, optional): The start year of the timeseries. It must be formatted like this: 'YYYY'. Defaults to 2003. end_year (int | str, optional): The end year of the timeseries. It must be formatted like this: 'YYYY'. Defaults to None, which will use the current year. out_gif (str): The output gif file path. Defaults to None. bands (list, optional): A list of band names to use in the timelapse. Defaults to None. palette (list, optional): A list of colors to render a single-band image in the timelapse. Defaults to None. vis_params (dict, optional): A dictionary of visualization parameters to use in the timelapse. Defaults to None. See more at https://developers.google.com/earth-engine/guides/image_visualization. dimensions (int, optional): a number or pair of numbers (in format 'WIDTHxHEIGHT') Maximum dimensions of the thumbnail to render, in pixels. If only one number is passed, it is used as the maximum, and the other dimension is computed by proportional scaling. Defaults to 768. frames_per_second (int, optional): Animation speed. Defaults to 10. crs (str, optional): The coordinate reference system to use. Defaults to "EPSG:3857". overlay_data (int, str, list, optional): Administrative boundary to be drawn on the timelapse. Defaults to None. overlay_color (str, optional): Color for the overlay data. Can be any color name or hex color code. Defaults to 'black'. overlay_width (int, optional): Width of the overlay. Defaults to 1. overlay_opacity (float, optional): Opacity of the overlay. Defaults to 1.0. title (str, optional): The title of the timelapse. Defaults to None. title_xy (tuple, optional): Lower left corner of the title. It can be formatted like this: (10, 10) or ('15%', '25%'). Defaults to None. add_text (bool, optional): Whether to add animated text to the timelapse. Defaults to True. title_xy (tuple, optional): Lower left corner of the text sequency. It can be formatted like this: (10, 10) or ('15%', '25%'). Defaults to None. text_sequence (int, str, list, optional): Text to be drawn. It can be an integer number, a string, or a list of strings. Defaults to None. font_type (str, optional): Font type. Defaults to "arial.ttf". font_size (int, optional): Font size. Defaults to 20. font_color (str, optional): Font color. It can be a string (e.g., 'red'), rgb tuple (e.g., (255, 127, 0)), or hex code (e.g., '#ff00ff'). Defaults to '#000000'. add_progress_bar (bool, optional): Whether to add a progress bar at the bottom of the GIF. Defaults to True. progress_bar_color (str, optional): Color for the progress bar. Defaults to 'white'. progress_bar_height (int, optional): Height of the progress bar. Defaults to 5. loop (int, optional): Controls how many times the animation repeats. The default, 1, means that the animation will play once and then stop (displaying the last frame). A value of 0 means that the animation will repeat forever. Defaults to 0. mp4 (bool, optional): Whether to create an mp4 file. Defaults to False. fading (int | bool, optional): If True, add fading effect to the timelapse. Defaults to False, no fading. To add fading effect, set it to True (1 second fading duration) or to an integer value (fading duration). step (int, optional): The step size to use when creating the date sequence. Defaults to 1. Returns: str: File path to the timelapse gif.
12,180
import datetime import glob import io import os import shutil import ee from .common import * from typing import Union, List import datetime import ee def ee_to_geojson(ee_object, filename=None, indent=2, **kwargs): """Converts Earth Engine object to geojson. Args: ee_object (object): An Earth Engine object. filename (str, optional): The file path to save the geojson. Defaults to None. Returns: object: GeoJSON object. """ try: if ( isinstance(ee_object, ee.Geometry) or isinstance(ee_object, ee.Feature) or isinstance(ee_object, ee.FeatureCollection) ): json_object = ee_object.getInfo() if filename is not None: filename = os.path.abspath(filename) if not os.path.exists(os.path.dirname(filename)): os.makedirs(os.path.dirname(filename)) with open(filename, "w") as f: f.write(json.dumps(json_object, indent=indent, **kwargs) + "\n") else: return json_object else: print("Could not convert the Earth Engine object to geojson") except Exception as e: raise Exception(e) def date_sequence(start, end, unit, date_format="YYYY-MM-dd", step=1): """Creates a date sequence. Args: start (str): The start date, e.g., '2000-01-01'. end (str): The end date, e.g., '2000-12-31'. unit (str): One of 'year', 'quarter', 'month' 'week', 'day', 'hour', 'minute', or 'second'. date_format (str, optional): A pattern, as described at http://joda-time.sourceforge.net/apidocs/org/joda/time/format/DateTimeFormat.html. Defaults to 'YYYY-MM-dd'. step (int, optional): The step size. Defaults to 1. Returns: ee.List: A list of date sequence. """ def get_quarter(d): return str((int(d[5:7]) - 1) // 3 * 3 + 1).zfill(2) def get_monday(d): date_obj = datetime.datetime.strptime(d, "%Y-%m-%d") start_of_week = date_obj - datetime.timedelta(days=date_obj.weekday()) return start_of_week.strftime("%Y-%m-%d") if unit == "year": start = start[:4] + "-01-01" elif unit == "month": start = start[:7] + "-01" elif unit == "quarter": start = start[:5] + get_quarter(start) + "-01" elif unit == "week": start = get_monday(start) start_date = ee.Date(start) end_date = ee.Date(end) if unit != "quarter": count = ee.Number(end_date.difference(start_date, unit)).toInt() num_seq = ee.List.sequence(0, count) if step > 1: num_seq = num_seq.slice(0, num_seq.size(), step) date_seq = num_seq.map( lambda d: start_date.advance(d, unit).format(date_format) ) else: unit = "month" count = ee.Number(end_date.difference(start_date, unit)).divide(3).toInt() num_seq = ee.List.sequence(0, count.multiply(3), 3) date_seq = num_seq.map( lambda d: start_date.advance(d, unit).format(date_format) ) return date_seq def adjust_longitude(in_fc): """Adjusts longitude if it is less than -180 or greater than 180. Args: in_fc (dict): The input dictionary containing coordinates. Returns: dict: A dictionary containing the converted longitudes """ try: keys = in_fc.keys() if "geometry" in keys: coordinates = in_fc["geometry"]["coordinates"] if in_fc["geometry"]["type"] == "Point": longitude = coordinates[0] if longitude < -180: longitude = 360 + longitude elif longitude > 180: longitude = longitude - 360 in_fc["geometry"]["coordinates"][0] = longitude elif in_fc["geometry"]["type"] == "Polygon": for index1, item in enumerate(coordinates): for index2, element in enumerate(item): longitude = element[0] if longitude < -180: longitude = 360 + longitude elif longitude > 180: longitude = longitude - 360 in_fc["geometry"]["coordinates"][index1][index2][0] = longitude elif in_fc["geometry"]["type"] == "LineString": for index, element in enumerate(coordinates): longitude = element[0] if longitude < -180: longitude = 360 + longitude elif longitude > 180: longitude = longitude - 360 in_fc["geometry"]["coordinates"][index][0] = longitude elif "type" in keys: coordinates = in_fc["coordinates"] if in_fc["type"] == "Point": longitude = coordinates[0] if longitude < -180: longitude = 360 + longitude elif longitude > 180: longitude = longitude - 360 in_fc["coordinates"][0] = longitude elif in_fc["type"] == "Polygon": for index1, item in enumerate(coordinates): for index2, element in enumerate(item): longitude = element[0] if longitude < -180: longitude = 360 + longitude elif longitude > 180: longitude = longitude - 360 in_fc["coordinates"][index1][index2][0] = longitude elif in_fc["type"] == "LineString": for index, element in enumerate(coordinates): longitude = element[0] if longitude < -180: longitude = 360 + longitude elif longitude > 180: longitude = longitude - 360 in_fc["coordinates"][index][0] = longitude return in_fc except Exception as e: print(e) return None def get_current_year(): """Get the current year. Returns: int: The current year. """ today = datetime.date.today() return today.year The provided code snippet includes necessary dependencies for implementing the `sentinel2_timeseries_legacy` function. Write a Python function `def sentinel2_timeseries_legacy( roi=None, start_year=2015, end_year=None, start_date="01-01", end_date="12-31", apply_fmask=True, frequency="year", date_format=None, )` to solve the following problem: Generates an annual Sentinel 2 ImageCollection. This algorithm is adapted from https://gist.github.com/jdbcode/76b9ac49faf51627ebd3ff988e10adbc. A huge thank you to Justin Braaten for sharing his fantastic work. Images include both level 1C and level 2A imagery. Args: roi (object, optional): Region of interest to create the timelapse. Defaults to None. start_year (int, optional): Starting year for the timelapse. Defaults to 2015. end_year (int, optional): Ending year for the timelapse. Defaults to None, which will use the current year. start_date (str, optional): Starting date (month-day) each year for filtering ImageCollection. Defaults to '01-01'. end_date (str, optional): Ending date (month-day) each year for filtering ImageCollection. Defaults to '12-31'. apply_fmask (bool, optional): Whether to apply Fmask (Function of mask) for automated clouds, cloud shadows, snow, and water masking. frequency (str, optional): Frequency of the timelapse. Defaults to 'year'. date_format (str, optional): Format of the date. Defaults to None. Returns: object: Returns an ImageCollection containing annual Sentinel 2 images. Here is the function: def sentinel2_timeseries_legacy( roi=None, start_year=2015, end_year=None, start_date="01-01", end_date="12-31", apply_fmask=True, frequency="year", date_format=None, ): """Generates an annual Sentinel 2 ImageCollection. This algorithm is adapted from https://gist.github.com/jdbcode/76b9ac49faf51627ebd3ff988e10adbc. A huge thank you to Justin Braaten for sharing his fantastic work. Images include both level 1C and level 2A imagery. Args: roi (object, optional): Region of interest to create the timelapse. Defaults to None. start_year (int, optional): Starting year for the timelapse. Defaults to 2015. end_year (int, optional): Ending year for the timelapse. Defaults to None, which will use the current year. start_date (str, optional): Starting date (month-day) each year for filtering ImageCollection. Defaults to '01-01'. end_date (str, optional): Ending date (month-day) each year for filtering ImageCollection. Defaults to '12-31'. apply_fmask (bool, optional): Whether to apply Fmask (Function of mask) for automated clouds, cloud shadows, snow, and water masking. frequency (str, optional): Frequency of the timelapse. Defaults to 'year'. date_format (str, optional): Format of the date. Defaults to None. Returns: object: Returns an ImageCollection containing annual Sentinel 2 images. """ ################################################################################ ################################################################################ # Input and output parameters. import re # import datetime if end_year is None: end_year = datetime.date.today().year if roi is None: # roi = ee.Geometry.Polygon( # [[[-180, -80], # [-180, 80], # [180, 80], # [180, -80], # [-180, -80]]], None, False) roi = ee.Geometry.Polygon( [ [ [-115.471773, 35.892718], [-115.471773, 36.409454], [-114.271283, 36.409454], [-114.271283, 35.892718], [-115.471773, 35.892718], ] ], None, False, ) if not isinstance(roi, ee.Geometry): try: roi = roi.geometry() except Exception as e: print("Could not convert the provided roi to ee.Geometry") print(e) return # Adjusts longitudes less than -180 degrees or greater than 180 degrees. geojson = ee_to_geojson(roi) geojson = adjust_longitude(geojson) roi = ee.Geometry(geojson) feq_dict = { "year": "YYYY", "month": "YYYY-MM", "quarter": "YYYY-MM", } if date_format is None: date_format = feq_dict[frequency] if frequency not in feq_dict: raise ValueError("frequency must be year, quarter, or month.") ################################################################################ # Setup vars to get dates. if ( isinstance(start_year, int) and (start_year >= 2015) and (start_year <= get_current_year()) ): pass else: print("The start year must be an integer >= 2015.") return if ( isinstance(end_year, int) and (end_year >= 2015) and (end_year <= get_current_year()) ): pass else: print(f"The end year must be an integer <= {get_current_year()}.") return if re.match(r"[0-9]{2}-[0-9]{2}", start_date) and re.match( r"[0-9]{2}-[0-9]{2}", end_date ): pass else: print("The start data and end date must be month-day, such as 06-10, 09-20") return try: datetime.datetime(int(start_year), int(start_date[:2]), int(start_date[3:5])) datetime.datetime(int(end_year), int(end_date[:2]), int(end_date[3:5])) except Exception as e: raise ValueError("The input dates are invalid.") try: start_test = datetime.datetime( int(start_year), int(start_date[:2]), int(start_date[3:5]) ) end_test = datetime.datetime( int(end_year), int(end_date[:2]), int(end_date[3:5]) ) if start_test > end_test: raise ValueError("Start date must be prior to end date") except Exception as e: raise Exception(e) def days_between(d1, d2): d1 = datetime.datetime.strptime(d1, "%Y-%m-%d") d2 = datetime.datetime.strptime(d2, "%Y-%m-%d") return abs((d2 - d1).days) n_days = days_between( str(start_year) + "-" + start_date, str(start_year) + "-" + end_date ) start_month = int(start_date[:2]) start_day = int(start_date[3:5]) # start_date = str(start_year) + "-" + start_date # end_date = str(end_year) + "-" + end_date # # Define a collection filter by date, bounds, and quality. # def colFilter(col, aoi): # , startDate, endDate): # return(col.filterBounds(aoi)) # Get Sentinel 2 collections, both Level-1C (top of atmophere) and Level-2A (surface reflectance) MSILCcol = ee.ImageCollection("COPERNICUS/S2") MSI2Acol = ee.ImageCollection("COPERNICUS/S2_SR") # Define a collection filter by date, bounds, and quality. def colFilter(col, roi, start_date, end_date): return col.filterBounds(roi).filterDate(start_date, end_date) # .filter('CLOUD_COVER < 5') # .filter('GEOMETRIC_RMSE_MODEL < 15') # .filter('IMAGE_QUALITY == 9 || IMAGE_QUALITY_OLI == 9')) # Function to get and rename bands of interest from MSI def renameMSI(img): return img.select( ["B2", "B3", "B4", "B5", "B6", "B7", "B8", "B8A", "B11", "B12", "QA60"], [ "Blue", "Green", "Red", "Red Edge 1", "Red Edge 2", "Red Edge 3", "NIR", "Red Edge 4", "SWIR1", "SWIR2", "QA60", ], ) # Add NBR for LandTrendr segmentation. def calcNbr(img): return img.addBands( img.normalizedDifference(["NIR", "SWIR2"]).multiply(-10000).rename("NBR") ).int16() # Define function to mask out clouds and cloud shadows in images. # Use CFmask band included in USGS Landsat SR image product. def fmask(img): cloudOpaqueBitMask = 1 << 10 cloudCirrusBitMask = 1 << 11 qa = img.select("QA60") mask = ( qa.bitwiseAnd(cloudOpaqueBitMask) .eq(0) .And(qa.bitwiseAnd(cloudCirrusBitMask).eq(0)) ) return img.updateMask(mask) # Define function to prepare MSI images. def prepMSI(img): orig = img img = renameMSI(img) if apply_fmask: img = fmask(img) return ee.Image(img.copyProperties(orig, orig.propertyNames())).resample( "bicubic" ) # Get annual median collection. def getAnnualComp(y): startDate = ee.Date.fromYMD( ee.Number(y), ee.Number(start_month), ee.Number(start_day) ) endDate = startDate.advance(ee.Number(n_days), "day") # Filter collections and prepare them for merging. MSILCcoly = colFilter(MSILCcol, roi, startDate, endDate).map(prepMSI) MSI2Acoly = colFilter(MSI2Acol, roi, startDate, endDate).map(prepMSI) # Merge the collections. col = MSILCcoly.merge(MSI2Acoly) yearImg = col.median() nBands = yearImg.bandNames().size() yearImg = ee.Image(ee.Algorithms.If(nBands, yearImg, dummyImg)) return calcNbr(yearImg).set( { "year": y, "system:time_start": startDate.millis(), "nBands": nBands, "system:date": ee.Date(startDate).format(date_format), } ) # Get quarterly median collection. def getQuarterlyComp(startDate): startDate = ee.Date(startDate) endDate = startDate.advance(3, "month") # Filter collections and prepare them for merging. MSILCcoly = colFilter(MSILCcol, roi, startDate, endDate).map(prepMSI) MSI2Acoly = colFilter(MSI2Acol, roi, startDate, endDate).map(prepMSI) # Merge the collections. col = MSILCcoly.merge(MSI2Acoly) yearImg = col.median() nBands = yearImg.bandNames().size() yearImg = ee.Image(ee.Algorithms.If(nBands, yearImg, dummyImg)) return calcNbr(yearImg).set( { "system:time_start": startDate.millis(), "nBands": nBands, "system:date": ee.Date(startDate).format(date_format), } ) # Get monthly median collection. def getMonthlyComp(startDate): startDate = ee.Date(startDate) endDate = startDate.advance(1, "month") # Filter collections and prepare them for merging. MSILCcoly = colFilter(MSILCcol, roi, startDate, endDate).map(prepMSI) MSI2Acoly = colFilter(MSI2Acol, roi, startDate, endDate).map(prepMSI) # Merge the collections. col = MSILCcoly.merge(MSI2Acoly) yearImg = col.median() nBands = yearImg.bandNames().size() yearImg = ee.Image(ee.Algorithms.If(nBands, yearImg, dummyImg)) return calcNbr(yearImg).set( { "system:time_start": startDate.millis(), "nBands": nBands, "system:date": ee.Date(startDate).format(date_format), } ) ################################################################################ # Make a dummy image for missing years. bandNames = ee.List( [ "Blue", "Green", "Red", "Red Edge 1", "Red Edge 2", "Red Edge 3", "NIR", "Red Edge 4", "SWIR1", "SWIR2", "QA60", ] ) fillerValues = ee.List.repeat(0, bandNames.size()) dummyImg = ee.Image.constant(fillerValues).rename(bandNames).selfMask().int16() # ################################################################################ # # Get a list of years # years = ee.List.sequence(start_year, end_year) # ################################################################################ # # Make list of annual image composites. # imgList = years.map(getAnnualComp) if frequency == "year": years = ee.List.sequence(start_year, end_year) imgList = years.map(getAnnualComp) elif frequency == "quarter": quarters = date_sequence( str(start_year) + "-01-01", str(end_year) + "-12-31", "quarter", date_format ) imgList = quarters.map(getQuarterlyComp) elif frequency == "month": months = date_sequence( str(start_year) + "-01-01", str(end_year) + "-12-31", "month", date_format ) imgList = months.map(getMonthlyComp) # Convert image composite list to collection imgCol = ee.ImageCollection.fromImages(imgList) imgCol = imgCol.map(lambda img: img.clip(roi)) return imgCol
Generates an annual Sentinel 2 ImageCollection. This algorithm is adapted from https://gist.github.com/jdbcode/76b9ac49faf51627ebd3ff988e10adbc. A huge thank you to Justin Braaten for sharing his fantastic work. Images include both level 1C and level 2A imagery. Args: roi (object, optional): Region of interest to create the timelapse. Defaults to None. start_year (int, optional): Starting year for the timelapse. Defaults to 2015. end_year (int, optional): Ending year for the timelapse. Defaults to None, which will use the current year. start_date (str, optional): Starting date (month-day) each year for filtering ImageCollection. Defaults to '01-01'. end_date (str, optional): Ending date (month-day) each year for filtering ImageCollection. Defaults to '12-31'. apply_fmask (bool, optional): Whether to apply Fmask (Function of mask) for automated clouds, cloud shadows, snow, and water masking. frequency (str, optional): Frequency of the timelapse. Defaults to 'year'. date_format (str, optional): Format of the date. Defaults to None. Returns: object: Returns an ImageCollection containing annual Sentinel 2 images.
12,181
import datetime import glob import io import os import shutil import ee from .common import * from typing import Union, List import datetime import ee def date_sequence(start, end, unit, date_format="YYYY-MM-dd", step=1): """Creates a date sequence. Args: start (str): The start date, e.g., '2000-01-01'. end (str): The end date, e.g., '2000-12-31'. unit (str): One of 'year', 'quarter', 'month' 'week', 'day', 'hour', 'minute', or 'second'. date_format (str, optional): A pattern, as described at http://joda-time.sourceforge.net/apidocs/org/joda/time/format/DateTimeFormat.html. Defaults to 'YYYY-MM-dd'. step (int, optional): The step size. Defaults to 1. Returns: ee.List: A list of date sequence. """ def get_quarter(d): return str((int(d[5:7]) - 1) // 3 * 3 + 1).zfill(2) def get_monday(d): date_obj = datetime.datetime.strptime(d, "%Y-%m-%d") start_of_week = date_obj - datetime.timedelta(days=date_obj.weekday()) return start_of_week.strftime("%Y-%m-%d") if unit == "year": start = start[:4] + "-01-01" elif unit == "month": start = start[:7] + "-01" elif unit == "quarter": start = start[:5] + get_quarter(start) + "-01" elif unit == "week": start = get_monday(start) start_date = ee.Date(start) end_date = ee.Date(end) if unit != "quarter": count = ee.Number(end_date.difference(start_date, unit)).toInt() num_seq = ee.List.sequence(0, count) if step > 1: num_seq = num_seq.slice(0, num_seq.size(), step) date_seq = num_seq.map( lambda d: start_date.advance(d, unit).format(date_format) ) else: unit = "month" count = ee.Number(end_date.difference(start_date, unit)).divide(3).toInt() num_seq = ee.List.sequence(0, count.multiply(3), 3) date_seq = num_seq.map( lambda d: start_date.advance(d, unit).format(date_format) ) return date_seq The provided code snippet includes necessary dependencies for implementing the `landsat_timeseries_legacy` function. Write a Python function `def landsat_timeseries_legacy( roi=None, start_year=1984, end_year=2021, start_date="06-10", end_date="09-20", apply_fmask=True, frequency="year", date_format=None, )` to solve the following problem: Generates an annual Landsat ImageCollection. This algorithm is adapted from https://gist.github.com/jdbcode/76b9ac49faf51627ebd3ff988e10adbc. A huge thank you to Justin Braaten for sharing his fantastic work. Args: roi (object, optional): Region of interest to create the timelapse. Defaults to None. start_year (int, optional): Starting year for the timelapse. Defaults to 1984. end_year (int, optional): Ending year for the timelapse. Defaults to 2021. start_date (str, optional): Starting date (month-day) each year for filtering ImageCollection. Defaults to '06-10'. end_date (str, optional): Ending date (month-day) each year for filtering ImageCollection. Defaults to '09-20'. apply_fmask (bool, optional): Whether to apply Fmask (Function of mask) for automated clouds, cloud shadows, snow, and water masking. frequency (str, optional): Frequency of the timelapse. Defaults to 'year'. date_format (str, optional): Format of the date. Defaults to None. Returns: object: Returns an ImageCollection containing annual Landsat images. Here is the function: def landsat_timeseries_legacy( roi=None, start_year=1984, end_year=2021, start_date="06-10", end_date="09-20", apply_fmask=True, frequency="year", date_format=None, ): """Generates an annual Landsat ImageCollection. This algorithm is adapted from https://gist.github.com/jdbcode/76b9ac49faf51627ebd3ff988e10adbc. A huge thank you to Justin Braaten for sharing his fantastic work. Args: roi (object, optional): Region of interest to create the timelapse. Defaults to None. start_year (int, optional): Starting year for the timelapse. Defaults to 1984. end_year (int, optional): Ending year for the timelapse. Defaults to 2021. start_date (str, optional): Starting date (month-day) each year for filtering ImageCollection. Defaults to '06-10'. end_date (str, optional): Ending date (month-day) each year for filtering ImageCollection. Defaults to '09-20'. apply_fmask (bool, optional): Whether to apply Fmask (Function of mask) for automated clouds, cloud shadows, snow, and water masking. frequency (str, optional): Frequency of the timelapse. Defaults to 'year'. date_format (str, optional): Format of the date. Defaults to None. Returns: object: Returns an ImageCollection containing annual Landsat images. """ ################################################################################ # Input and output parameters. import re # import datetime if roi is None: roi = ee.Geometry.Polygon( [ [ [-115.471773, 35.892718], [-115.471773, 36.409454], [-114.271283, 36.409454], [-114.271283, 35.892718], [-115.471773, 35.892718], ] ], None, False, ) if not isinstance(roi, ee.Geometry): try: roi = roi.geometry() except Exception as e: print("Could not convert the provided roi to ee.Geometry") print(e) return feq_dict = { "year": "YYYY", "month": "YYYY-MM", "quarter": "YYYY-MM", } if date_format is None: date_format = feq_dict[frequency] if frequency not in feq_dict: raise ValueError("frequency must be year, quarter, or month.") ################################################################################ # Setup vars to get dates. if isinstance(start_year, int) and (start_year >= 1984) and (start_year < 2021): pass else: print("The start year must be an integer >= 1984.") return if isinstance(end_year, int) and (end_year > 1984) and (end_year <= 2021): pass else: print("The end year must be an integer <= 2021.") return if re.match(r"[0-9]{2}-[0-9]{2}", start_date) and re.match( r"[0-9]{2}-[0-9]{2}", end_date ): pass else: print("The start date and end date must be month-day, such as 06-10, 09-20") return try: datetime.datetime(int(start_year), int(start_date[:2]), int(start_date[3:5])) datetime.datetime(int(end_year), int(end_date[:2]), int(end_date[3:5])) except Exception as e: print("The input dates are invalid.") raise Exception(e) def days_between(d1, d2): d1 = datetime.datetime.strptime(d1, "%Y-%m-%d") d2 = datetime.datetime.strptime(d2, "%Y-%m-%d") return abs((d2 - d1).days) n_days = days_between( str(start_year) + "-" + start_date, str(start_year) + "-" + end_date ) start_month = int(start_date[:2]) start_day = int(start_date[3:5]) # start_date = str(start_year) + "-" + start_date # end_date = str(end_year) + "-" + end_date # # Define a collection filter by date, bounds, and quality. # def colFilter(col, aoi): # , startDate, endDate): # return(col.filterBounds(aoi)) # Landsat collection preprocessingEnabled # Get Landsat surface reflectance collections for OLI, ETM+ and TM sensors. LC08col = ee.ImageCollection("LANDSAT/LC08/C01/T1_SR") LE07col = ee.ImageCollection("LANDSAT/LE07/C01/T1_SR") LT05col = ee.ImageCollection("LANDSAT/LT05/C01/T1_SR") LT04col = ee.ImageCollection("LANDSAT/LT04/C01/T1_SR") # Define a collection filter by date, bounds, and quality. def colFilter(col, roi, start_date, end_date): return col.filterBounds(roi).filterDate(start_date, end_date) # .filter('CLOUD_COVER < 5') # .filter('GEOMETRIC_RMSE_MODEL < 15') # .filter('IMAGE_QUALITY == 9 || IMAGE_QUALITY_OLI == 9')) # Function to get and rename bands of interest from OLI. def renameOli(img): return img.select( ["B2", "B3", "B4", "B5", "B6", "B7", "pixel_qa"], ["Blue", "Green", "Red", "NIR", "SWIR1", "SWIR2", "pixel_qa"], ) # Function to get and rename bands of interest from ETM+. def renameEtm(img): return img.select( ["B1", "B2", "B3", "B4", "B5", "B7", "pixel_qa"], ["Blue", "Green", "Red", "NIR", "SWIR1", "SWIR2", "pixel_qa"], ) # Add NBR for LandTrendr segmentation. def calcNbr(img): return img.addBands( img.normalizedDifference(["NIR", "SWIR2"]).multiply(-10000).rename("NBR") ).int16() # Define function to mask out clouds and cloud shadows in images. # Use CFmask band included in USGS Landsat SR image product. def fmask(img): cloudShadowBitMask = 1 << 3 cloudsBitMask = 1 << 5 qa = img.select("pixel_qa") mask = ( qa.bitwiseAnd(cloudShadowBitMask) .eq(0) .And(qa.bitwiseAnd(cloudsBitMask).eq(0)) ) return img.updateMask(mask) # Define function to prepare OLI images. def prepOli(img): orig = img img = renameOli(img) if apply_fmask: img = fmask(img) return ee.Image(img.copyProperties(orig, orig.propertyNames())).resample( "bicubic" ) # Define function to prepare ETM+ images. def prepEtm(img): orig = img img = renameEtm(img) if apply_fmask: img = fmask(img) return ee.Image(img.copyProperties(orig, orig.propertyNames())).resample( "bicubic" ) # Get annual median collection. def getAnnualComp(y): startDate = ee.Date.fromYMD( ee.Number(y), ee.Number(start_month), ee.Number(start_day) ) endDate = startDate.advance(ee.Number(n_days), "day") # Filter collections and prepare them for merging. LC08coly = colFilter(LC08col, roi, startDate, endDate).map(prepOli) LE07coly = colFilter(LE07col, roi, startDate, endDate).map(prepEtm) LT05coly = colFilter(LT05col, roi, startDate, endDate).map(prepEtm) LT04coly = colFilter(LT04col, roi, startDate, endDate).map(prepEtm) # Merge the collections. col = LC08coly.merge(LE07coly).merge(LT05coly).merge(LT04coly) yearImg = col.median() nBands = yearImg.bandNames().size() yearImg = ee.Image(ee.Algorithms.If(nBands, yearImg, dummyImg)) return calcNbr(yearImg).set( { "year": y, "system:time_start": startDate.millis(), "nBands": nBands, "system:date": ee.Date(startDate).format(date_format), } ) # Get monthly median collection. def getMonthlyComp(startDate): startDate = ee.Date(startDate) endDate = startDate.advance(1, "month") # Filter collections and prepare them for merging. LC08coly = colFilter(LC08col, roi, startDate, endDate).map(prepOli) LE07coly = colFilter(LE07col, roi, startDate, endDate).map(prepEtm) LT05coly = colFilter(LT05col, roi, startDate, endDate).map(prepEtm) LT04coly = colFilter(LT04col, roi, startDate, endDate).map(prepEtm) # Merge the collections. col = LC08coly.merge(LE07coly).merge(LT05coly).merge(LT04coly) monthImg = col.median() nBands = monthImg.bandNames().size() monthImg = ee.Image(ee.Algorithms.If(nBands, monthImg, dummyImg)) return calcNbr(monthImg).set( { "system:time_start": startDate.millis(), "nBands": nBands, "system:date": ee.Date(startDate).format(date_format), } ) # Get quarterly median collection. def getQuarterlyComp(startDate): startDate = ee.Date(startDate) endDate = startDate.advance(3, "month") # Filter collections and prepare them for merging. LC08coly = colFilter(LC08col, roi, startDate, endDate).map(prepOli) LE07coly = colFilter(LE07col, roi, startDate, endDate).map(prepEtm) LT05coly = colFilter(LT05col, roi, startDate, endDate).map(prepEtm) LT04coly = colFilter(LT04col, roi, startDate, endDate).map(prepEtm) # Merge the collections. col = LC08coly.merge(LE07coly).merge(LT05coly).merge(LT04coly) quarter = col.median() nBands = quarter.bandNames().size() quarter = ee.Image(ee.Algorithms.If(nBands, quarter, dummyImg)) return calcNbr(quarter).set( { "system:time_start": startDate.millis(), "nBands": nBands, "system:date": ee.Date(startDate).format(date_format), } ) ################################################################################ # Make a dummy image for missing years. bandNames = ee.List(["Blue", "Green", "Red", "NIR", "SWIR1", "SWIR2", "pixel_qa"]) fillerValues = ee.List.repeat(0, bandNames.size()) dummyImg = ee.Image.constant(fillerValues).rename(bandNames).selfMask().int16() # ################################################################################ # # Get a list of years # years = ee.List.sequence(start_year, end_year) # ################################################################################ # # Make list of annual image composites. # imgList = years.map(getAnnualComp) if frequency == "year": years = ee.List.sequence(start_year, end_year) imgList = years.map(getAnnualComp) elif frequency == "quarter": quarters = date_sequence( str(start_year) + "-01-01", str(end_year) + "-12-31", "quarter", date_format ) imgList = quarters.map(getQuarterlyComp) elif frequency == "month": months = date_sequence( str(start_year) + "-01-01", str(end_year) + "-12-31", "month", date_format ) imgList = months.map(getMonthlyComp) # Convert image composite list to collection imgCol = ee.ImageCollection.fromImages(imgList) imgCol = imgCol.map( lambda img: img.clip(roi).set({"coordinates": roi.coordinates()}) ) return imgCol # ################################################################################ # # Run LandTrendr. # lt = ee.Algorithms.TemporalSegmentation.LandTrendr( # timeSeries=imgCol.select(['NBR', 'SWIR1', 'NIR', 'Green']), # maxSegments=10, # spikeThreshold=0.7, # vertexCountOvershoot=3, # preventOneYearRecovery=True, # recoveryThreshold=0.5, # pvalThreshold=0.05, # bestModelProportion=0.75, # minObservationsNeeded=6) # ################################################################################ # # Get fitted imagery. This starts export tasks. # def getYearStr(year): # return(ee.String('yr_').cat(ee.Algorithms.String(year).slice(0,4))) # yearsStr = years.map(getYearStr) # r = lt.select(['SWIR1_fit']).arrayFlatten([yearsStr]).toShort() # g = lt.select(['NIR_fit']).arrayFlatten([yearsStr]).toShort() # b = lt.select(['Green_fit']).arrayFlatten([yearsStr]).toShort() # for i, c in zip([r, g, b], ['r', 'g', 'b']): # descr = 'mamore-river-'+c # name = 'users/user/'+descr # print(name) # task = ee.batch.Export.image.toAsset( # image=i, # region=roi.getInfo()['coordinates'], # assetId=name, # description=descr, # scale=30, # crs='EPSG:3857', # maxPixels=1e13) # task.start()
Generates an annual Landsat ImageCollection. This algorithm is adapted from https://gist.github.com/jdbcode/76b9ac49faf51627ebd3ff988e10adbc. A huge thank you to Justin Braaten for sharing his fantastic work. Args: roi (object, optional): Region of interest to create the timelapse. Defaults to None. start_year (int, optional): Starting year for the timelapse. Defaults to 1984. end_year (int, optional): Ending year for the timelapse. Defaults to 2021. start_date (str, optional): Starting date (month-day) each year for filtering ImageCollection. Defaults to '06-10'. end_date (str, optional): Ending date (month-day) each year for filtering ImageCollection. Defaults to '09-20'. apply_fmask (bool, optional): Whether to apply Fmask (Function of mask) for automated clouds, cloud shadows, snow, and water masking. frequency (str, optional): Frequency of the timelapse. Defaults to 'year'. date_format (str, optional): Format of the date. Defaults to None. Returns: object: Returns an ImageCollection containing annual Landsat images.
12,182
import datetime import glob import io import os import shutil import ee from .common import * from typing import Union, List def add_overlay( collection: ee.ImageCollection, overlay_data: Union[str, ee.Geometry, ee.FeatureCollection], color: str = "black", width: int = 1, opacity: float = 1.0, region: Union[ee.Geometry, ee.FeatureCollection] = None, ) -> ee.ImageCollection: """Adds an overlay to an image collection. Args: collection (ee.ImageCollection): The image collection to add the overlay to. overlay_data (str | ee.Geometry | ee.FeatureCollection): The overlay data to add to the image collection. It can be an HTTP URL to a GeoJSON file. color (str, optional): The color of the overlay. Defaults to 'black'. width (int, optional): The width of the overlay. Defaults to 1. opacity (float, optional): The opacity of the overlay. Defaults to 1.0. region (ee.Geometry | ee.FeatureCollection, optional): The region of interest to add the overlay to. Defaults to None. Returns: ee.ImageCollection: An ImageCollection with the overlay added. """ # Some common administrative boundaries. public_assets = ["continents", "countries", "us_states", "china"] if not isinstance(collection, ee.ImageCollection): raise Exception("The collection must be an ee.ImageCollection.") if not isinstance(overlay_data, ee.FeatureCollection): if isinstance(overlay_data, str): try: if overlay_data.lower() in public_assets: overlay_data = ee.FeatureCollection( f"users/giswqs/public/{overlay_data.lower()}" ) elif overlay_data.startswith("http") and overlay_data.endswith( ".geojson" ): overlay_data = geojson_to_ee(overlay_data) else: overlay_data = ee.FeatureCollection(overlay_data) except Exception as e: print( "The overlay_data must be a valid ee.FeatureCollection, a valid ee.FeatureCollection asset id, or http url to a geojson file." ) raise Exception(e) elif isinstance(overlay_data, ee.Feature): overlay_data = ee.FeatureCollection([overlay_data]) elif isinstance(overlay_data, ee.Geometry): overlay_data = ee.FeatureCollection([ee.Feature(overlay_data)]) else: raise Exception( "The overlay_data must be a valid ee.FeatureCollection or a valid ee.FeatureCollection asset id." ) try: if region is not None: overlay_data = overlay_data.filterBounds(region) empty = ee.Image().byte() image = empty.paint( **{ "featureCollection": overlay_data, "color": 1, "width": width, } ).visualize(**{"palette": check_color(color), "opacity": opacity}) blend_col = collection.map( lambda img: img.blend(image).set( "system:time_start", img.get("system:time_start") ) ) return blend_col except Exception as e: print("Error in add_overlay:") raise Exception(e) def make_gif( images: Union[List[str], str], out_gif: str, ext: str = "jpg", fps: int = 10, loop: int = 0, mp4: bool = False, clean_up: bool = False, ) -> None: """Creates a gif from a list of images. Args: images (list | str): The list of images or input directory to create the gif from. out_gif (str): File path to the output gif. ext (str, optional): The extension of the images. Defaults to 'jpg'. fps (int, optional): The frames per second of the gif. Defaults to 10. loop (int, optional): The number of times to loop the gif. Defaults to 0. mp4 (bool, optional): Whether to convert the gif to mp4. Defaults to False. """ if isinstance(images, str) and os.path.isdir(images): images = list(glob.glob(os.path.join(images, f"*.{ext}"))) if len(images) == 0: raise ValueError("No images found in the input directory.") elif not isinstance(images, list): raise ValueError("images must be a list or a path to the image directory.") images.sort() frames = [Image.open(image) for image in images] frame_one = frames[0] frame_one.save( out_gif, format="GIF", append_images=frames, save_all=True, duration=int(1000 / fps), loop=loop, ) if mp4: if not is_tool("ffmpeg"): print("ffmpeg is not installed on your computer.") return if os.path.exists(out_gif): out_mp4 = out_gif.replace(".gif", ".mp4") cmd = f"ffmpeg -loglevel error -i {out_gif} -vcodec libx264 -crf 25 -pix_fmt yuv420p {out_mp4}" os.system(cmd) if not os.path.exists(out_mp4): raise Exception(f"Failed to create mp4 file.") if clean_up: for image in images: os.remove(image) def gif_to_mp4(in_gif, out_mp4): """Converts a gif to mp4. Args: in_gif (str): The input gif file. out_mp4 (str): The output mp4 file. """ from PIL import Image if not os.path.exists(in_gif): raise FileNotFoundError(f"{in_gif} does not exist.") out_mp4 = os.path.abspath(out_mp4) if not out_mp4.endswith(".mp4"): out_mp4 = out_mp4 + ".mp4" if not os.path.exists(os.path.dirname(out_mp4)): os.makedirs(os.path.dirname(out_mp4)) if not is_tool("ffmpeg"): print("ffmpeg is not installed on your computer.") return width, height = Image.open(in_gif).size if width % 2 == 0 and height % 2 == 0: cmd = f"ffmpeg -loglevel error -i {in_gif} -vcodec libx264 -crf 25 -pix_fmt yuv420p {out_mp4}" os.system(cmd) else: width += width % 2 height += height % 2 cmd = f"ffmpeg -loglevel error -i {in_gif} -vf scale={width}:{height} -vcodec libx264 -crf 25 -pix_fmt yuv420p {out_mp4}" os.system(cmd) if not os.path.exists(out_mp4): raise Exception(f"Failed to create mp4 file.") def gif_fading(in_gif, out_gif, duration=1, verbose=True): """Fade in/out the gif. Args: in_gif (str): The input gif file. Can be a directory path or http URL, e.g., "https://i.imgur.com/ZWSZC5z.gif" out_gif (str): The output gif file. duration (float, optional): The duration of the fading. Defaults to 1. verbose (bool, optional): Whether to print the progress. Defaults to True. Raises: FileNotFoundError: Raise exception when the input gif does not exist. Exception: Raise exception when ffmpeg is not installed. """ import glob import tempfile current_dir = os.getcwd() if isinstance(in_gif, str) and in_gif.startswith("http"): ext = os.path.splitext(in_gif)[1] file_path = temp_file_path(ext) download_from_url(in_gif, file_path, verbose=verbose) in_gif = file_path in_gif = os.path.abspath(in_gif) if not in_gif.endswith(".gif"): raise Exception("in_gif must be a gif file.") if " " in in_gif: raise Exception("The filename cannot contain spaces.") out_gif = os.path.abspath(out_gif) if not os.path.exists(os.path.dirname(out_gif)): os.makedirs(os.path.dirname(out_gif)) if not os.path.exists(in_gif): raise FileNotFoundError(f"{in_gif} does not exist.") basename = os.path.basename(in_gif).replace(".gif", "") temp_dir = os.path.join(tempfile.gettempdir(), basename) if os.path.exists(temp_dir): shutil.rmtree(temp_dir) gif_to_png(in_gif, temp_dir, verbose=verbose) os.chdir(temp_dir) images = list(glob.glob(os.path.join(temp_dir, "*.png"))) count = len(images) files = [] for i in range(1, count + 1): files.append(f"-loop 1 -t {duration} -i {i}.png") inputs = " ".join(files) filters = [] for i in range(1, count): if i == 1: filters.append( f"\"[1:v][0:v]blend=all_expr='A*(if(gte(T,3),1,T/3))+B*(1-(if(gte(T,3),1,T/3)))'[v0];" ) else: filters.append( f"[{i}:v][{i-1}:v]blend=all_expr='A*(if(gte(T,3),1,T/3))+B*(1-(if(gte(T,3),1,T/3)))'[v{i-1}];" ) last_filter = "" for i in range(count - 1): last_filter += f"[v{i}]" last_filter += f'concat=n={count-1}:v=1:a=0[v]" -map "[v]"' filters.append(last_filter) filters = " ".join(filters) cmd = f"ffmpeg -y -loglevel error {inputs} -filter_complex {filters} {out_gif}" # if fade >= duration: # duration = fade + 1 # files = [] # for i in range(1, count + 1): # files.append(f"-framerate {framerate} -loop 1 -t {duration} -i {i}.png") # inputs = " ".join(files) # filters = [] # for i in range(count): # if i == 0: # filters.append(f'"[0:v]fade=t=out:st=4:d={fade}[v0];') # else: # filters.append( # f"[{i}:v]fade=t=in:st=0:d={fade},fade=t=out:st=4:d={fade}[v{i}];" # ) # last_filter = "" # for i in range(count): # last_filter += f"[v{i}]" # last_filter += f"concat=n={count}:v=1:a=0,split[v0][v1];" # filters.append(last_filter) # palette = f'[v0]palettegen[p];[v1][p]paletteuse[v]" -map "[v]"' # filters.append(palette) # filters = " ".join(filters) # cmd = f"ffmpeg -y {inputs} -filter_complex {filters} {out_gif}" os.system(cmd) try: shutil.rmtree(temp_dir) except Exception as e: print(e) os.chdir(current_dir) def add_text_to_gif( in_gif, out_gif, xy=None, text_sequence=None, font_type="arial.ttf", font_size=20, font_color="#000000", add_progress_bar=True, progress_bar_color="white", progress_bar_height=5, duration=100, loop=0, ): """Adds animated text to a GIF image. Args: in_gif (str): The file path to the input GIF image. out_gif (str): The file path to the output GIF image. xy (tuple, optional): Top left corner of the text. It can be formatted like this: (10, 10) or ('15%', '25%'). Defaults to None. text_sequence (int, str, list, optional): Text to be drawn. It can be an integer number, a string, or a list of strings. Defaults to None. font_type (str, optional): Font type. Defaults to "arial.ttf". font_size (int, optional): Font size. Defaults to 20. font_color (str, optional): Font color. It can be a string (e.g., 'red'), rgb tuple (e.g., (255, 127, 0)), or hex code (e.g., '#ff00ff'). Defaults to '#000000'. add_progress_bar (bool, optional): Whether to add a progress bar at the bottom of the GIF. Defaults to True. progress_bar_color (str, optional): Color for the progress bar. Defaults to 'white'. progress_bar_height (int, optional): Height of the progress bar. Defaults to 5. duration (int, optional): controls how long each frame will be displayed for, in milliseconds. It is the inverse of the frame rate. Setting it to 100 milliseconds gives 10 frames per second. You can decrease the duration to give a smoother animation.. Defaults to 100. loop (int, optional): controls how many times the animation repeats. The default, 1, means that the animation will play once and then stop (displaying the last frame). A value of 0 means that the animation will repeat forever. Defaults to 0. """ # import io import warnings import pkg_resources from PIL import Image, ImageDraw, ImageFont, ImageSequence warnings.simplefilter("ignore") pkg_dir = os.path.dirname(pkg_resources.resource_filename("geemap", "geemap.py")) default_font = os.path.join(pkg_dir, "data/fonts/arial.ttf") in_gif = os.path.abspath(in_gif) out_gif = os.path.abspath(out_gif) if not os.path.exists(in_gif): print("The input gif file does not exist.") return if not os.path.exists(os.path.dirname(out_gif)): os.makedirs(os.path.dirname(out_gif)) if font_type == "arial.ttf": font = ImageFont.truetype(default_font, font_size) elif font_type == "alibaba.otf": default_font = os.path.join(pkg_dir, "data/fonts/alibaba.otf") font = ImageFont.truetype(default_font, font_size) else: try: font_list = system_fonts(show_full_path=True) font_names = [os.path.basename(f) for f in font_list] if (font_type in font_list) or (font_type in font_names): font = ImageFont.truetype(font_type, font_size) else: print( "The specified font type could not be found on your system. Using the default font instead." ) font = ImageFont.truetype(default_font, font_size) except Exception as e: print(e) font = ImageFont.truetype(default_font, font_size) color = check_color(font_color) progress_bar_color = check_color(progress_bar_color) try: image = Image.open(in_gif) except Exception as e: print("An error occurred while opening the gif.") print(e) return count = image.n_frames W, H = image.size progress_bar_widths = [i * 1.0 / count * W for i in range(1, count + 1)] progress_bar_shapes = [ [(0, H - progress_bar_height), (x, H)] for x in progress_bar_widths ] if xy is None: # default text location is 5% width and 5% height of the image. xy = (int(0.05 * W), int(0.05 * H)) elif (xy is not None) and (not isinstance(xy, tuple)) and (len(xy) == 2): print("xy must be a tuple, e.g., (10, 10), ('10%', '10%')") return elif all(isinstance(item, int) for item in xy) and (len(xy) == 2): x, y = xy if (x > 0) and (x < W) and (y > 0) and (y < H): pass else: print( f"xy is out of bounds. x must be within [0, {W}], and y must be within [0, {H}]" ) return elif all(isinstance(item, str) for item in xy) and (len(xy) == 2): x, y = xy if ("%" in x) and ("%" in y): try: x = int(float(x.replace("%", "")) / 100.0 * W) y = int(float(y.replace("%", "")) / 100.0 * H) xy = (x, y) except Exception: raise Exception( "The specified xy is invalid. It must be formatted like this ('10%', '10%')" ) else: print( "The specified xy is invalid. It must be formatted like this: (10, 10) or ('10%', '10%')" ) return if text_sequence is None: text = [str(x) for x in range(1, count + 1)] elif isinstance(text_sequence, int): text = [str(x) for x in range(text_sequence, text_sequence + count + 1)] elif isinstance(text_sequence, str): try: text_sequence = int(text_sequence) text = [str(x) for x in range(text_sequence, text_sequence + count + 1)] except Exception: text = [text_sequence] * count elif isinstance(text_sequence, list) and len(text_sequence) != count: print( f"The length of the text sequence must be equal to the number ({count}) of frames in the gif." ) return else: text = [str(x) for x in text_sequence] try: frames = [] # Loop over each frame in the animated image for index, frame in enumerate(ImageSequence.Iterator(image)): # Draw the text on the frame frame = frame.convert("RGB") draw = ImageDraw.Draw(frame) # w, h = draw.textsize(text[index]) draw.text(xy, text[index], font=font, fill=color) if add_progress_bar: draw.rectangle(progress_bar_shapes[index], fill=progress_bar_color) del draw b = io.BytesIO() frame.save(b, format="GIF") frame = Image.open(b) frames.append(frame) # https://www.pythoninformer.com/python-libraries/pillow/creating-animated-gif/ # Save the frames as a new image frames[0].save( out_gif, save_all=True, append_images=frames[1:], duration=duration, loop=loop, optimize=True, ) except Exception as e: print(e) def reduce_gif_size(in_gif, out_gif=None): """Reduces a GIF image using ffmpeg. Args: in_gif (str): The input file path to the GIF image. out_gif (str, optional): The output file path to the GIF image. Defaults to None. """ import ffmpeg import warnings warnings.filterwarnings("ignore") if not is_tool("ffmpeg"): print("ffmpeg is not installed on your computer.") return if not os.path.exists(in_gif): print("The input gif file does not exist.") return if out_gif is None: out_gif = in_gif elif not os.path.exists(os.path.dirname(out_gif)): os.makedirs(os.path.dirname(out_gif)) if in_gif == out_gif: tmp_gif = in_gif.replace(".gif", "_tmp.gif") shutil.copyfile(in_gif, tmp_gif) stream = ffmpeg.input(tmp_gif) stream = ffmpeg.output(stream, in_gif, loglevel="quiet").overwrite_output() ffmpeg.run(stream) os.remove(tmp_gif) else: stream = ffmpeg.input(in_gif) stream = ffmpeg.output(stream, out_gif, loglevel="quiet").overwrite_output() ffmpeg.run(stream) def landsat_timeseries( roi=None, start_year=1984, end_year=None, start_date="06-10", end_date="09-20", apply_fmask=True, frequency="year", date_format=None, step=1, ): """Generates an annual Landsat ImageCollection. This algorithm is adapted from https://gist.github.com/jdbcode/76b9ac49faf51627ebd3ff988e10adbc. A huge thank you to Justin Braaten for sharing his fantastic work. Args: roi (object, optional): Region of interest to create the timelapse. Defaults to None. start_year (int, optional): Starting year for the timelapse. Defaults to 1984. end_year (int, optional): Ending year for the timelapse. Defaults to None, which means the current year. start_date (str, optional): Starting date (month-day) each year for filtering ImageCollection. Defaults to '06-10'. end_date (str, optional): Ending date (month-day) each year for filtering ImageCollection. Defaults to '09-20'. apply_fmask (bool, optional): Whether to apply Fmask (Function of mask) for automated clouds, cloud shadows, snow, and water masking. frequency (str, optional): Frequency of the timelapse. Defaults to 'year'. date_format (str, optional): Format of the date. Defaults to None. step (int, optional): The step size to use when creating the date sequence. Defaults to 1. Returns: object: Returns an ImageCollection containing annual Landsat images. """ # Input and output parameters. import re if roi is None: roi = ee.Geometry.Polygon( [ [ [-115.471773, 35.892718], [-115.471773, 36.409454], [-114.271283, 36.409454], [-114.271283, 35.892718], [-115.471773, 35.892718], ] ], None, False, ) if end_year is None: end_year = get_current_year() if not isinstance(roi, ee.Geometry): try: roi = roi.geometry() except Exception as e: print("Could not convert the provided roi to ee.Geometry") print(e) return feq_dict = { "year": "YYYY", "month": "YYYY-MM", "quarter": "YYYY-MM", } if date_format is None: date_format = feq_dict[frequency] if frequency not in feq_dict: raise ValueError("frequency must be year, quarter, or month.") # Setup vars to get dates. if ( isinstance(start_year, int) and (start_year >= 1984) and (start_year < get_current_year()) ): pass else: print("The start year must be an integer >= 1984.") return if ( isinstance(end_year, int) and (end_year > 1984) and (end_year <= get_current_year()) ): pass else: print(f"The end year must be an integer <= {get_current_year()}.") return if re.match(r"[0-9]{2}-[0-9]{2}", start_date) and re.match( r"[0-9]{2}-[0-9]{2}", end_date ): pass else: print("The start date and end date must be month-day, such as 06-10, 09-20") return try: datetime.datetime(int(start_year), int(start_date[:2]), int(start_date[3:5])) datetime.datetime(int(end_year), int(end_date[:2]), int(end_date[3:5])) except Exception as e: print("The input dates are invalid.") raise Exception(e) def days_between(d1, d2): d1 = datetime.datetime.strptime(d1, "%Y-%m-%d") d2 = datetime.datetime.strptime(d2, "%Y-%m-%d") return abs((d2 - d1).days) n_days = days_between( str(start_year) + "-" + start_date, str(start_year) + "-" + end_date ) start_month = int(start_date[:2]) start_day = int(start_date[3:5]) # Landsat collection preprocessingEnabled # Get Landsat surface reflectance collections for OLI, ETM+ and TM sensors. LC09col = ee.ImageCollection("LANDSAT/LC09/C02/T1_L2") LC08col = ee.ImageCollection("LANDSAT/LC08/C02/T1_L2") LE07col = ee.ImageCollection("LANDSAT/LE07/C02/T1_L2") LT05col = ee.ImageCollection("LANDSAT/LT05/C02/T1_L2") LT04col = ee.ImageCollection("LANDSAT/LT04/C02/T1_L2") # Define a collection filter by date, bounds, and quality. def colFilter(col, roi, start_date, end_date): return col.filterBounds(roi).filterDate(start_date, end_date) # Function to get and rename bands of interest from OLI. def renameOli(img): return img.select( ["SR_B2", "SR_B3", "SR_B4", "SR_B5", "SR_B6", "SR_B7"], ["Blue", "Green", "Red", "NIR", "SWIR1", "SWIR2"], ) # Function to get and rename bands of interest from ETM+. def renameEtm(img): return img.select( ["SR_B1", "SR_B2", "SR_B3", "SR_B4", "SR_B5", "SR_B7"], ["Blue", "Green", "Red", "NIR", "SWIR1", "SWIR2"], ) def fmask(image): # see https://developers.google.com/earth-engine/datasets/catalog/LANDSAT_LC09_C02_T1_L2 # Bit 0 - Fill # Bit 1 - Dilated Cloud # Bit 2 - Cirrus # Bit 3 - Cloud # Bit 4 - Cloud Shadow qaMask = image.select("QA_PIXEL").bitwiseAnd(int("11111", 2)).eq(0) # Apply the scaling factors to the appropriate bands. opticalBands = image.select("SR_B.").multiply(0.0000275).add(-0.2) # Replace the original bands with the scaled ones and apply the masks. return image.addBands(opticalBands, None, True).updateMask(qaMask) # Define function to prepare OLI images. def prepOli(img): orig = img if apply_fmask: img = fmask(img) else: img = img.select("SR_B.").multiply(0.0000275).add(-0.2) img = renameOli(img) return ee.Image(img.copyProperties(orig, orig.propertyNames())).resample( "bicubic" ) # Define function to prepare ETM+ images. def prepEtm(img): orig = img if apply_fmask: img = fmask(img) else: img = img.select("SR_B.").multiply(0.0000275).add(-0.2) img = renameEtm(img) return ee.Image(img.copyProperties(orig, orig.propertyNames())).resample( "bicubic" ) # Get annual median collection. def getAnnualComp(y): startDate = ee.Date.fromYMD( ee.Number(y), ee.Number(start_month), ee.Number(start_day) ) endDate = startDate.advance(ee.Number(n_days), "day") # Filter collections and prepare them for merging. LC09coly = colFilter(LC09col, roi, startDate, endDate).map(prepOli) LC08coly = colFilter(LC08col, roi, startDate, endDate).map(prepOli) LE07coly = colFilter(LE07col, roi, startDate, endDate).map(prepEtm) LT05coly = colFilter(LT05col, roi, startDate, endDate).map(prepEtm) LT04coly = colFilter(LT04col, roi, startDate, endDate).map(prepEtm) # Merge the collections. col = LC09coly.merge(LC08coly).merge(LE07coly).merge(LT05coly).merge(LT04coly) yearImg = col.median() nBands = yearImg.bandNames().size() yearImg = ee.Image(ee.Algorithms.If(nBands, yearImg, dummyImg)) return yearImg.set( { "year": y, "system:time_start": startDate.millis(), "nBands": nBands, "system:date": ee.Date(startDate).format(date_format), } ) # Get monthly median collection. def getMonthlyComp(startDate): startDate = ee.Date(startDate) endDate = startDate.advance(1, "month") # Filter collections and prepare them for merging. LC09coly = colFilter(LC09col, roi, startDate, endDate).map(prepOli) LC08coly = colFilter(LC08col, roi, startDate, endDate).map(prepOli) LE07coly = colFilter(LE07col, roi, startDate, endDate).map(prepEtm) LT05coly = colFilter(LT05col, roi, startDate, endDate).map(prepEtm) LT04coly = colFilter(LT04col, roi, startDate, endDate).map(prepEtm) # Merge the collections. col = LC09coly.merge(LC08coly).merge(LE07coly).merge(LT05coly).merge(LT04coly) monthImg = col.median() nBands = monthImg.bandNames().size() monthImg = ee.Image(ee.Algorithms.If(nBands, monthImg, dummyImg)) return monthImg.set( { "system:time_start": startDate.millis(), "nBands": nBands, "system:date": ee.Date(startDate).format(date_format), } ) # Get quarterly median collection. def getQuarterlyComp(startDate): startDate = ee.Date(startDate) endDate = startDate.advance(3, "month") # Filter collections and prepare them for merging. LC09coly = colFilter(LC09col, roi, startDate, endDate).map(prepOli) LC08coly = colFilter(LC08col, roi, startDate, endDate).map(prepOli) LE07coly = colFilter(LE07col, roi, startDate, endDate).map(prepEtm) LT05coly = colFilter(LT05col, roi, startDate, endDate).map(prepEtm) LT04coly = colFilter(LT04col, roi, startDate, endDate).map(prepEtm) # Merge the collections. col = LC09coly.merge(LC08coly).merge(LE07coly).merge(LT05coly).merge(LT04coly) quarter = col.median() nBands = quarter.bandNames().size() quarter = ee.Image(ee.Algorithms.If(nBands, quarter, dummyImg)) return quarter.set( { "system:time_start": startDate.millis(), "nBands": nBands, "system:date": ee.Date(startDate).format(date_format), } ) # Make a dummy image for missing years. bandNames = ee.List(["Blue", "Green", "Red", "NIR", "SWIR1", "SWIR2", "pixel_qa"]) fillerValues = ee.List.repeat(0, bandNames.size()) dummyImg = ee.Image.constant(fillerValues).rename(bandNames).selfMask().int16() # Make list of /quarterly/monthly image composites. if frequency == "year": years = ee.List.sequence(start_year, end_year, step) imgList = years.map(getAnnualComp) elif frequency == "quarter": quarters = date_sequence( str(start_year) + "-01-01", str(end_year) + "-12-31", "quarter", date_format, step, ) imgList = quarters.map(getQuarterlyComp) elif frequency == "month": months = date_sequence( str(start_year) + "-01-01", str(end_year) + "-12-31", "month", date_format, step, ) imgList = months.map(getMonthlyComp) # Convert image composite list to collection imgCol = ee.ImageCollection.fromImages(imgList) imgCol = imgCol.map( lambda img: img.clip(roi).set({"coordinates": roi.coordinates()}) ) return imgCol def landsat_ts_norm_diff(collection, bands=["Green", "SWIR1"], threshold=0): """Computes a normalized difference index based on a Landsat timeseries. Args: collection (ee.ImageCollection): A Landsat timeseries. bands (list, optional): The bands to use for computing normalized difference. Defaults to ['Green', 'SWIR1']. threshold (float, optional): The threshold to extract features. Defaults to 0. Returns: ee.ImageCollection: An ImageCollection containing images with values greater than the specified threshold. """ nd_images = collection.map( lambda img: img.normalizedDifference(bands) .gt(threshold) .copyProperties(img, img.propertyNames()) ) return nd_images def landsat_ts_norm_diff_gif( collection, out_gif=None, vis_params=None, palette=["black", "blue"], dimensions=768, frames_per_second=10, mp4=False, ): """[summary] Args: collection (ee.ImageCollection): The normalized difference Landsat timeseires. out_gif (str, optional): File path to the output animated GIF. Defaults to None. vis_params (dict, optional): Visualization parameters. Defaults to None. palette (list, optional): The palette to use for visualizing the timelapse. Defaults to ['black', 'blue']. The first color in the list is the background color. dimensions (int, optional): a number or pair of numbers (in format 'WIDTHxHEIGHT') Maximum dimensions of the thumbnail to render, in pixels. If only one number is passed, it is used as the maximum, and the other dimension is computed by proportional scaling. Defaults to 768. frames_per_second (int, optional): Animation speed. Defaults to 10. mp4 (bool, optional): If True, the output gif will be converted to mp4. Defaults to False. Returns: str: File path to the output animated GIF. """ coordinates = ee.Image(collection.first()).get("coordinates") roi = ee.Geometry.Polygon(coordinates, None, False) if out_gif is None: out_dir = os.path.join(os.path.expanduser("~"), "Downloads") filename = "landsat_ts_nd_" + random_string() + ".gif" out_gif = os.path.join(out_dir, filename) elif not out_gif.endswith(".gif"): raise Exception("The output file must end with .gif") bands = ["nd"] if vis_params is None: vis_params = {} vis_params["bands"] = bands vis_params["palette"] = palette video_args = vis_params.copy() video_args["dimensions"] = dimensions video_args["region"] = roi video_args["framesPerSecond"] = frames_per_second video_args["crs"] = "EPSG:3857" if "bands" not in video_args.keys(): video_args["bands"] = bands download_ee_video(collection, video_args, out_gif) if os.path.exists(out_gif): reduce_gif_size(out_gif) if mp4: out_mp4 = out_gif.replace(".gif", ".mp4") gif_to_mp4(out_gif, out_mp4) import os import ee def get_image_collection_thumbnails( ee_object, out_dir, vis_params, dimensions=500, region=None, format="jpg", names=None, verbose=True, timeout=300, proxies=None, ): """Download thumbnails for all images in an ImageCollection. Args: ee_object (object): The ee.ImageCollection instance. out_dir ([str): The output directory to store thumbnails. vis_params (dict): The visualization parameters. dimensions (int, optional):(a number or pair of numbers in format WIDTHxHEIGHT) Maximum dimensions of the thumbnail to render, in pixels. If only one number is passed, it is used as the maximum, and the other dimension is computed by proportional scaling. Defaults to 500. region (object, optional): Geospatial region of the image to render, it may be an ee.Geometry, GeoJSON, or an array of lat/lon points (E,S,W,N). If not set the default is the bounds image. Defaults to None. format (str, optional): Either 'png' or 'jpg'. Default to 'jpg'. names (list, optional): The list of output file names. Defaults to None. verbose (bool, optional): Whether or not to print hints. Defaults to True. timeout (int, optional): The number of seconds after which the request will be terminated. Defaults to 300. proxies (dict, optional): A dictionary of proxy servers to use for the request. Defaults to None. """ if not isinstance(ee_object, ee.ImageCollection): print("The ee_object must be an ee.ImageCollection.") raise TypeError("The ee_object must be an ee.Image.") if format not in ["png", "jpg"]: raise ValueError("The output image format must be png or jpg.") if not os.path.exists(out_dir): os.makedirs(out_dir) try: count = int(ee_object.size().getInfo()) if verbose: print(f"Total number of images: {count}\n") if (names is not None) and (len(names) != count): print("The number of names is not equal to the number of images.") return if names is None: names = ee_object.aggregate_array("system:index").getInfo() images = ee_object.toList(count) for i in range(0, count): image = ee.Image(images.get(i)) name = str(names[i]) ext = os.path.splitext(name)[1][1:] if ext != format: name = name + "." + format out_img = os.path.join(out_dir, name) if verbose: print(f"Downloading {i+1}/{count}: {name} ...") get_image_thumbnail( image, out_img, vis_params, dimensions, region, format, timeout=timeout, proxies=proxies, ) except Exception as e: print(e) def download_ee_video(collection, video_args, out_gif, timeout=300, proxies=None): """Downloads a video thumbnail as a GIF image from Earth Engine. Args: collection (object): An ee.ImageCollection. video_args (object): Parameters for expring the video thumbnail. out_gif (str): File path to the output GIF. timeout (int, optional): The number of seconds the request will be timed out. Defaults to 300. proxies (dict, optional): A dictionary of proxy servers to use. Defaults to None. """ out_gif = os.path.abspath(out_gif) if not out_gif.endswith(".gif"): print("The output file must have an extension of .gif.") return if not os.path.exists(os.path.dirname(out_gif)): os.makedirs(os.path.dirname(out_gif)) if "region" in video_args.keys(): roi = video_args["region"] if not isinstance(roi, ee.Geometry): try: roi = roi.geometry() except Exception as e: print("Could not convert the provided roi to ee.Geometry") print(e) return video_args["region"] = roi if "dimensions" not in video_args: video_args["dimensions"] = 768 try: print("Generating URL...") url = collection.getVideoThumbURL(video_args) print(f"Downloading GIF image from {url}\nPlease wait ...") r = requests.get(url, stream=True, timeout=timeout, proxies=proxies) if r.status_code != 200: print("An error occurred while downloading.") print(r.json()["error"]["message"]) return else: with open(out_gif, "wb") as fd: for chunk in r.iter_content(chunk_size=1024): fd.write(chunk) print(f"The GIF image has been saved to: {out_gif}") except Exception as e: print(e) def temp_file_path(extension): """Returns a temporary file path. Args: extension (str): The file extension. Returns: str: The temporary file path. """ import tempfile import uuid if not extension.startswith("."): extension = "." + extension file_id = str(uuid.uuid4()) file_path = os.path.join(tempfile.gettempdir(), f"{file_id}{extension}") return file_path def get_current_year(): """Get the current year. Returns: int: The current year. """ today = datetime.date.today() return today.year The provided code snippet includes necessary dependencies for implementing the `landsat_timelapse` function. Write a Python function `def landsat_timelapse( roi=None, out_gif=None, start_year=1984, end_year=None, start_date="06-10", end_date="09-20", bands=["NIR", "Red", "Green"], vis_params=None, dimensions=768, frames_per_second=5, crs="EPSG:3857", apply_fmask=True, nd_bands=None, nd_threshold=0, nd_palette=["black", "blue"], overlay_data=None, overlay_color="black", overlay_width=1, overlay_opacity=1.0, frequency="year", date_format=None, title=None, title_xy=("2%", "90%"), add_text=True, text_xy=("2%", "2%"), text_sequence=None, font_type="arial.ttf", font_size=20, font_color="white", add_progress_bar=True, progress_bar_color="white", progress_bar_height=5, loop=0, mp4=False, fading=False, step=1, )` to solve the following problem: Generates a Landsat timelapse GIF image. This function is adapted from https://emaprlab.users.earthengine.app/view/lt-gee-time-series-animator. A huge thank you to Justin Braaten for sharing his fantastic work. Args: roi (object, optional): Region of interest to create the timelapse. Defaults to None. out_gif (str, optional): File path to the output animated GIF. Defaults to None. start_year (int, optional): Starting year for the timelapse. Defaults to 1984. end_year (int, optional): Ending year for the timelapse. Defaults to None, which will use the current year. start_date (str, optional): Starting date (month-day) each year for filtering ImageCollection. Defaults to '06-10'. end_date (str, optional): Ending date (month-day) each year for filtering ImageCollection. Defaults to '09-20'. bands (list, optional): Three bands selected from ['Blue', 'Green', 'Red', 'NIR', 'SWIR1', 'SWIR2', 'pixel_qa']. Defaults to ['NIR', 'Red', 'Green']. vis_params (dict, optional): Visualization parameters. Defaults to None. dimensions (int, optional): a number or pair of numbers (in format 'WIDTHxHEIGHT') Maximum dimensions of the thumbnail to render, in pixels. If only one number is passed, it is used as the maximum, and the other dimension is computed by proportional scaling. Defaults to 768. frames_per_second (int, optional): Animation speed. Defaults to 5. crs (str, optional): The coordinate reference system to use. Defaults to "EPSG:3857". apply_fmask (bool, optional): Whether to apply Fmask (Function of mask) for automated clouds, cloud shadows, snow, and water masking. nd_bands (list, optional): A list of names specifying the bands to use, e.g., ['Green', 'SWIR1']. The normalized difference is computed as (first − second) / (first + second). Note that negative input values are forced to 0 so that the result is confined to the range (-1, 1). nd_threshold (float, optional): The threshold for extracting pixels from the normalized difference band. nd_palette (list, optional): The color palette to use for displaying the normalized difference band. overlay_data (int, str, list, optional): Administrative boundary to be drawn on the timelapse. Defaults to None. overlay_color (str, optional): Color for the overlay data. Can be any color name or hex color code. Defaults to 'black'. overlay_width (int, optional): Line width of the overlay. Defaults to 1. overlay_opacity (float, optional): Opacity of the overlay. Defaults to 1.0. frequency (str, optional): Frequency of the timelapse. Defaults to 'year'. date_format (str, optional): Date format for the timelapse. Defaults to None. title (str, optional): The title of the timelapse. Defaults to None. title_xy (tuple, optional): Lower left corner of the title. It can be formatted like this: (10, 10) or ('15%', '25%'). Defaults to None. add_text (bool, optional): Whether to add animated text to the timelapse. Defaults to True. title_xy (tuple, optional): Lower left corner of the text sequency. It can be formatted like this: (10, 10) or ('15%', '25%'). Defaults to None. text_sequence (int, str, list, optional): Text to be drawn. It can be an integer number, a string, or a list of strings. Defaults to None. font_type (str, optional): Font type. Defaults to "arial.ttf". font_size (int, optional): Font size. Defaults to 20. font_color (str, optional): Font color. It can be a string (e.g., 'red'), rgb tuple (e.g., (255, 127, 0)), or hex code (e.g., '#ff00ff'). Defaults to '#000000'. add_progress_bar (bool, optional): Whether to add a progress bar at the bottom of the GIF. Defaults to True. progress_bar_color (str, optional): Color for the progress bar. Defaults to 'white'. progress_bar_height (int, optional): Height of the progress bar. Defaults to 5. loop (int, optional): Controls how many times the animation repeats. The default, 1, means that the animation will play once and then stop (displaying the last frame). A value of 0 means that the animation will repeat forever. Defaults to 0. mp4 (bool, optional): Whether to convert the GIF to MP4. Defaults to False. fading (int | bool, optional): If True, add fading effect to the timelapse. Defaults to False, no fading. To add fading effect, set it to True (1 second fading duration) or to an integer value (fading duration). step (int, optional): Step size for the timelapse. Defaults to 1. Returns: str: File path to the output GIF image. Here is the function: def landsat_timelapse( roi=None, out_gif=None, start_year=1984, end_year=None, start_date="06-10", end_date="09-20", bands=["NIR", "Red", "Green"], vis_params=None, dimensions=768, frames_per_second=5, crs="EPSG:3857", apply_fmask=True, nd_bands=None, nd_threshold=0, nd_palette=["black", "blue"], overlay_data=None, overlay_color="black", overlay_width=1, overlay_opacity=1.0, frequency="year", date_format=None, title=None, title_xy=("2%", "90%"), add_text=True, text_xy=("2%", "2%"), text_sequence=None, font_type="arial.ttf", font_size=20, font_color="white", add_progress_bar=True, progress_bar_color="white", progress_bar_height=5, loop=0, mp4=False, fading=False, step=1, ): """Generates a Landsat timelapse GIF image. This function is adapted from https://emaprlab.users.earthengine.app/view/lt-gee-time-series-animator. A huge thank you to Justin Braaten for sharing his fantastic work. Args: roi (object, optional): Region of interest to create the timelapse. Defaults to None. out_gif (str, optional): File path to the output animated GIF. Defaults to None. start_year (int, optional): Starting year for the timelapse. Defaults to 1984. end_year (int, optional): Ending year for the timelapse. Defaults to None, which will use the current year. start_date (str, optional): Starting date (month-day) each year for filtering ImageCollection. Defaults to '06-10'. end_date (str, optional): Ending date (month-day) each year for filtering ImageCollection. Defaults to '09-20'. bands (list, optional): Three bands selected from ['Blue', 'Green', 'Red', 'NIR', 'SWIR1', 'SWIR2', 'pixel_qa']. Defaults to ['NIR', 'Red', 'Green']. vis_params (dict, optional): Visualization parameters. Defaults to None. dimensions (int, optional): a number or pair of numbers (in format 'WIDTHxHEIGHT') Maximum dimensions of the thumbnail to render, in pixels. If only one number is passed, it is used as the maximum, and the other dimension is computed by proportional scaling. Defaults to 768. frames_per_second (int, optional): Animation speed. Defaults to 5. crs (str, optional): The coordinate reference system to use. Defaults to "EPSG:3857". apply_fmask (bool, optional): Whether to apply Fmask (Function of mask) for automated clouds, cloud shadows, snow, and water masking. nd_bands (list, optional): A list of names specifying the bands to use, e.g., ['Green', 'SWIR1']. The normalized difference is computed as (first − second) / (first + second). Note that negative input values are forced to 0 so that the result is confined to the range (-1, 1). nd_threshold (float, optional): The threshold for extracting pixels from the normalized difference band. nd_palette (list, optional): The color palette to use for displaying the normalized difference band. overlay_data (int, str, list, optional): Administrative boundary to be drawn on the timelapse. Defaults to None. overlay_color (str, optional): Color for the overlay data. Can be any color name or hex color code. Defaults to 'black'. overlay_width (int, optional): Line width of the overlay. Defaults to 1. overlay_opacity (float, optional): Opacity of the overlay. Defaults to 1.0. frequency (str, optional): Frequency of the timelapse. Defaults to 'year'. date_format (str, optional): Date format for the timelapse. Defaults to None. title (str, optional): The title of the timelapse. Defaults to None. title_xy (tuple, optional): Lower left corner of the title. It can be formatted like this: (10, 10) or ('15%', '25%'). Defaults to None. add_text (bool, optional): Whether to add animated text to the timelapse. Defaults to True. title_xy (tuple, optional): Lower left corner of the text sequency. It can be formatted like this: (10, 10) or ('15%', '25%'). Defaults to None. text_sequence (int, str, list, optional): Text to be drawn. It can be an integer number, a string, or a list of strings. Defaults to None. font_type (str, optional): Font type. Defaults to "arial.ttf". font_size (int, optional): Font size. Defaults to 20. font_color (str, optional): Font color. It can be a string (e.g., 'red'), rgb tuple (e.g., (255, 127, 0)), or hex code (e.g., '#ff00ff'). Defaults to '#000000'. add_progress_bar (bool, optional): Whether to add a progress bar at the bottom of the GIF. Defaults to True. progress_bar_color (str, optional): Color for the progress bar. Defaults to 'white'. progress_bar_height (int, optional): Height of the progress bar. Defaults to 5. loop (int, optional): Controls how many times the animation repeats. The default, 1, means that the animation will play once and then stop (displaying the last frame). A value of 0 means that the animation will repeat forever. Defaults to 0. mp4 (bool, optional): Whether to convert the GIF to MP4. Defaults to False. fading (int | bool, optional): If True, add fading effect to the timelapse. Defaults to False, no fading. To add fading effect, set it to True (1 second fading duration) or to an integer value (fading duration). step (int, optional): Step size for the timelapse. Defaults to 1. Returns: str: File path to the output GIF image. """ if roi is None: roi = ee.Geometry.Polygon( [ [ [-115.471773, 35.892718], [-115.471773, 36.409454], [-114.271283, 36.409454], [-114.271283, 35.892718], [-115.471773, 35.892718], ] ], None, False, ) elif isinstance(roi, ee.Feature) or isinstance(roi, ee.FeatureCollection): roi = roi.geometry() elif isinstance(roi, ee.Geometry): pass else: raise ValueError("The provided roi is invalid. It must be an ee.Geometry") if out_gif is None: out_gif = temp_file_path(".gif") elif not out_gif.endswith(".gif"): raise ValueError("The output file must end with .gif") else: out_gif = os.path.abspath(out_gif) out_dir = os.path.dirname(out_gif) if not os.path.exists(out_dir): os.makedirs(out_dir) if end_year is None: end_year = get_current_year() allowed_bands = ["Blue", "Green", "Red", "NIR", "SWIR1", "SWIR2", "pixel_qa"] if len(bands) == 3 and all(x in allowed_bands for x in bands): pass else: raise Exception( "You can only select 3 bands from the following: {}".format( ", ".join(allowed_bands) ) ) if nd_bands is not None: if len(nd_bands) == 2 and all(x in allowed_bands[:-1] for x in nd_bands): pass else: raise Exception( "You can only select two bands from the following: {}".format( ", ".join(allowed_bands[:-1]) ) ) try: if vis_params is None: vis_params = {} vis_params["bands"] = bands vis_params["min"] = 0 vis_params["max"] = 0.4 vis_params["gamma"] = [1, 1, 1] raw_col = landsat_timeseries( roi, start_year, end_year, start_date, end_date, apply_fmask, frequency, date_format, step, ) col = raw_col.select(bands).map( lambda img: img.visualize(**vis_params).set( { "system:time_start": img.get("system:time_start"), "system:date": img.get("system:date"), } ) ) if overlay_data is not None: col = add_overlay( col, overlay_data, overlay_color, overlay_width, overlay_opacity ) if ( isinstance(dimensions, int) and dimensions > 768 or isinstance(dimensions, str) and any(dim > 768 for dim in list(map(int, dimensions.split("x")))) ): count = col.size().getInfo() basename = os.path.basename(out_gif)[:-4] names = [ os.path.join( out_dir, f"{basename}_{str(i+1).zfill(int(len(str(count))))}.jpg" ) for i in range(count) ] get_image_collection_thumbnails( col, out_dir, vis_params={ "min": 0, "max": 255, "bands": ["vis-red", "vis-green", "vis-blue"], }, dimensions=dimensions, names=names, ) make_gif( names, out_gif, fps=frames_per_second, loop=loop, mp4=False, clean_up=True, ) else: video_args = vis_params.copy() video_args["dimensions"] = dimensions video_args["region"] = roi video_args["framesPerSecond"] = frames_per_second video_args["crs"] = crs video_args["bands"] = ["vis-red", "vis-green", "vis-blue"] video_args["min"] = 0 video_args["max"] = 255 download_ee_video(col, video_args, out_gif) if os.path.exists(out_gif): if title is not None and isinstance(title, str): add_text_to_gif( out_gif, out_gif, xy=title_xy, text_sequence=title, font_type=font_type, font_size=font_size, font_color=font_color, add_progress_bar=add_progress_bar, progress_bar_color=progress_bar_color, progress_bar_height=progress_bar_height, duration=1000 / frames_per_second, loop=loop, ) if add_text: if text_sequence is None: text_sequence = col.aggregate_array("system:date").getInfo() add_text_to_gif( out_gif, out_gif, xy=text_xy, text_sequence=text_sequence, font_type=font_type, font_size=font_size, font_color=font_color, add_progress_bar=add_progress_bar, progress_bar_color=progress_bar_color, progress_bar_height=progress_bar_height, duration=1000 / frames_per_second, loop=loop, ) if nd_bands is not None: nd_images = landsat_ts_norm_diff( raw_col, bands=nd_bands, threshold=nd_threshold ) out_nd_gif = out_gif.replace(".gif", "_nd.gif") landsat_ts_norm_diff_gif( nd_images, out_gif=out_nd_gif, vis_params=None, palette=nd_palette, dimensions=dimensions, frames_per_second=frames_per_second, ) if os.path.exists(out_gif): reduce_gif_size(out_gif) if isinstance(fading, bool): fading = int(fading) if fading > 0: gif_fading(out_gif, out_gif, duration=fading, verbose=False) if mp4: out_mp4 = out_gif.replace(".gif", ".mp4") gif_to_mp4(out_gif, out_mp4) return out_gif except Exception as e: raise Exception(e)
Generates a Landsat timelapse GIF image. This function is adapted from https://emaprlab.users.earthengine.app/view/lt-gee-time-series-animator. A huge thank you to Justin Braaten for sharing his fantastic work. Args: roi (object, optional): Region of interest to create the timelapse. Defaults to None. out_gif (str, optional): File path to the output animated GIF. Defaults to None. start_year (int, optional): Starting year for the timelapse. Defaults to 1984. end_year (int, optional): Ending year for the timelapse. Defaults to None, which will use the current year. start_date (str, optional): Starting date (month-day) each year for filtering ImageCollection. Defaults to '06-10'. end_date (str, optional): Ending date (month-day) each year for filtering ImageCollection. Defaults to '09-20'. bands (list, optional): Three bands selected from ['Blue', 'Green', 'Red', 'NIR', 'SWIR1', 'SWIR2', 'pixel_qa']. Defaults to ['NIR', 'Red', 'Green']. vis_params (dict, optional): Visualization parameters. Defaults to None. dimensions (int, optional): a number or pair of numbers (in format 'WIDTHxHEIGHT') Maximum dimensions of the thumbnail to render, in pixels. If only one number is passed, it is used as the maximum, and the other dimension is computed by proportional scaling. Defaults to 768. frames_per_second (int, optional): Animation speed. Defaults to 5. crs (str, optional): The coordinate reference system to use. Defaults to "EPSG:3857". apply_fmask (bool, optional): Whether to apply Fmask (Function of mask) for automated clouds, cloud shadows, snow, and water masking. nd_bands (list, optional): A list of names specifying the bands to use, e.g., ['Green', 'SWIR1']. The normalized difference is computed as (first − second) / (first + second). Note that negative input values are forced to 0 so that the result is confined to the range (-1, 1). nd_threshold (float, optional): The threshold for extracting pixels from the normalized difference band. nd_palette (list, optional): The color palette to use for displaying the normalized difference band. overlay_data (int, str, list, optional): Administrative boundary to be drawn on the timelapse. Defaults to None. overlay_color (str, optional): Color for the overlay data. Can be any color name or hex color code. Defaults to 'black'. overlay_width (int, optional): Line width of the overlay. Defaults to 1. overlay_opacity (float, optional): Opacity of the overlay. Defaults to 1.0. frequency (str, optional): Frequency of the timelapse. Defaults to 'year'. date_format (str, optional): Date format for the timelapse. Defaults to None. title (str, optional): The title of the timelapse. Defaults to None. title_xy (tuple, optional): Lower left corner of the title. It can be formatted like this: (10, 10) or ('15%', '25%'). Defaults to None. add_text (bool, optional): Whether to add animated text to the timelapse. Defaults to True. title_xy (tuple, optional): Lower left corner of the text sequency. It can be formatted like this: (10, 10) or ('15%', '25%'). Defaults to None. text_sequence (int, str, list, optional): Text to be drawn. It can be an integer number, a string, or a list of strings. Defaults to None. font_type (str, optional): Font type. Defaults to "arial.ttf". font_size (int, optional): Font size. Defaults to 20. font_color (str, optional): Font color. It can be a string (e.g., 'red'), rgb tuple (e.g., (255, 127, 0)), or hex code (e.g., '#ff00ff'). Defaults to '#000000'. add_progress_bar (bool, optional): Whether to add a progress bar at the bottom of the GIF. Defaults to True. progress_bar_color (str, optional): Color for the progress bar. Defaults to 'white'. progress_bar_height (int, optional): Height of the progress bar. Defaults to 5. loop (int, optional): Controls how many times the animation repeats. The default, 1, means that the animation will play once and then stop (displaying the last frame). A value of 0 means that the animation will repeat forever. Defaults to 0. mp4 (bool, optional): Whether to convert the GIF to MP4. Defaults to False. fading (int | bool, optional): If True, add fading effect to the timelapse. Defaults to False, no fading. To add fading effect, set it to True (1 second fading duration) or to an integer value (fading duration). step (int, optional): Step size for the timelapse. Defaults to 1. Returns: str: File path to the output GIF image.
12,183
import datetime import glob import io import os import shutil import ee from .common import * from typing import Union, List def add_overlay( collection: ee.ImageCollection, overlay_data: Union[str, ee.Geometry, ee.FeatureCollection], color: str = "black", width: int = 1, opacity: float = 1.0, region: Union[ee.Geometry, ee.FeatureCollection] = None, ) -> ee.ImageCollection: """Adds an overlay to an image collection. Args: collection (ee.ImageCollection): The image collection to add the overlay to. overlay_data (str | ee.Geometry | ee.FeatureCollection): The overlay data to add to the image collection. It can be an HTTP URL to a GeoJSON file. color (str, optional): The color of the overlay. Defaults to 'black'. width (int, optional): The width of the overlay. Defaults to 1. opacity (float, optional): The opacity of the overlay. Defaults to 1.0. region (ee.Geometry | ee.FeatureCollection, optional): The region of interest to add the overlay to. Defaults to None. Returns: ee.ImageCollection: An ImageCollection with the overlay added. """ # Some common administrative boundaries. public_assets = ["continents", "countries", "us_states", "china"] if not isinstance(collection, ee.ImageCollection): raise Exception("The collection must be an ee.ImageCollection.") if not isinstance(overlay_data, ee.FeatureCollection): if isinstance(overlay_data, str): try: if overlay_data.lower() in public_assets: overlay_data = ee.FeatureCollection( f"users/giswqs/public/{overlay_data.lower()}" ) elif overlay_data.startswith("http") and overlay_data.endswith( ".geojson" ): overlay_data = geojson_to_ee(overlay_data) else: overlay_data = ee.FeatureCollection(overlay_data) except Exception as e: print( "The overlay_data must be a valid ee.FeatureCollection, a valid ee.FeatureCollection asset id, or http url to a geojson file." ) raise Exception(e) elif isinstance(overlay_data, ee.Feature): overlay_data = ee.FeatureCollection([overlay_data]) elif isinstance(overlay_data, ee.Geometry): overlay_data = ee.FeatureCollection([ee.Feature(overlay_data)]) else: raise Exception( "The overlay_data must be a valid ee.FeatureCollection or a valid ee.FeatureCollection asset id." ) try: if region is not None: overlay_data = overlay_data.filterBounds(region) empty = ee.Image().byte() image = empty.paint( **{ "featureCollection": overlay_data, "color": 1, "width": width, } ).visualize(**{"palette": check_color(color), "opacity": opacity}) blend_col = collection.map( lambda img: img.blend(image).set( "system:time_start", img.get("system:time_start") ) ) return blend_col except Exception as e: print("Error in add_overlay:") raise Exception(e) def make_gif( images: Union[List[str], str], out_gif: str, ext: str = "jpg", fps: int = 10, loop: int = 0, mp4: bool = False, clean_up: bool = False, ) -> None: """Creates a gif from a list of images. Args: images (list | str): The list of images or input directory to create the gif from. out_gif (str): File path to the output gif. ext (str, optional): The extension of the images. Defaults to 'jpg'. fps (int, optional): The frames per second of the gif. Defaults to 10. loop (int, optional): The number of times to loop the gif. Defaults to 0. mp4 (bool, optional): Whether to convert the gif to mp4. Defaults to False. """ if isinstance(images, str) and os.path.isdir(images): images = list(glob.glob(os.path.join(images, f"*.{ext}"))) if len(images) == 0: raise ValueError("No images found in the input directory.") elif not isinstance(images, list): raise ValueError("images must be a list or a path to the image directory.") images.sort() frames = [Image.open(image) for image in images] frame_one = frames[0] frame_one.save( out_gif, format="GIF", append_images=frames, save_all=True, duration=int(1000 / fps), loop=loop, ) if mp4: if not is_tool("ffmpeg"): print("ffmpeg is not installed on your computer.") return if os.path.exists(out_gif): out_mp4 = out_gif.replace(".gif", ".mp4") cmd = f"ffmpeg -loglevel error -i {out_gif} -vcodec libx264 -crf 25 -pix_fmt yuv420p {out_mp4}" os.system(cmd) if not os.path.exists(out_mp4): raise Exception(f"Failed to create mp4 file.") if clean_up: for image in images: os.remove(image) def gif_to_mp4(in_gif, out_mp4): """Converts a gif to mp4. Args: in_gif (str): The input gif file. out_mp4 (str): The output mp4 file. """ from PIL import Image if not os.path.exists(in_gif): raise FileNotFoundError(f"{in_gif} does not exist.") out_mp4 = os.path.abspath(out_mp4) if not out_mp4.endswith(".mp4"): out_mp4 = out_mp4 + ".mp4" if not os.path.exists(os.path.dirname(out_mp4)): os.makedirs(os.path.dirname(out_mp4)) if not is_tool("ffmpeg"): print("ffmpeg is not installed on your computer.") return width, height = Image.open(in_gif).size if width % 2 == 0 and height % 2 == 0: cmd = f"ffmpeg -loglevel error -i {in_gif} -vcodec libx264 -crf 25 -pix_fmt yuv420p {out_mp4}" os.system(cmd) else: width += width % 2 height += height % 2 cmd = f"ffmpeg -loglevel error -i {in_gif} -vf scale={width}:{height} -vcodec libx264 -crf 25 -pix_fmt yuv420p {out_mp4}" os.system(cmd) if not os.path.exists(out_mp4): raise Exception(f"Failed to create mp4 file.") def gif_fading(in_gif, out_gif, duration=1, verbose=True): """Fade in/out the gif. Args: in_gif (str): The input gif file. Can be a directory path or http URL, e.g., "https://i.imgur.com/ZWSZC5z.gif" out_gif (str): The output gif file. duration (float, optional): The duration of the fading. Defaults to 1. verbose (bool, optional): Whether to print the progress. Defaults to True. Raises: FileNotFoundError: Raise exception when the input gif does not exist. Exception: Raise exception when ffmpeg is not installed. """ import glob import tempfile current_dir = os.getcwd() if isinstance(in_gif, str) and in_gif.startswith("http"): ext = os.path.splitext(in_gif)[1] file_path = temp_file_path(ext) download_from_url(in_gif, file_path, verbose=verbose) in_gif = file_path in_gif = os.path.abspath(in_gif) if not in_gif.endswith(".gif"): raise Exception("in_gif must be a gif file.") if " " in in_gif: raise Exception("The filename cannot contain spaces.") out_gif = os.path.abspath(out_gif) if not os.path.exists(os.path.dirname(out_gif)): os.makedirs(os.path.dirname(out_gif)) if not os.path.exists(in_gif): raise FileNotFoundError(f"{in_gif} does not exist.") basename = os.path.basename(in_gif).replace(".gif", "") temp_dir = os.path.join(tempfile.gettempdir(), basename) if os.path.exists(temp_dir): shutil.rmtree(temp_dir) gif_to_png(in_gif, temp_dir, verbose=verbose) os.chdir(temp_dir) images = list(glob.glob(os.path.join(temp_dir, "*.png"))) count = len(images) files = [] for i in range(1, count + 1): files.append(f"-loop 1 -t {duration} -i {i}.png") inputs = " ".join(files) filters = [] for i in range(1, count): if i == 1: filters.append( f"\"[1:v][0:v]blend=all_expr='A*(if(gte(T,3),1,T/3))+B*(1-(if(gte(T,3),1,T/3)))'[v0];" ) else: filters.append( f"[{i}:v][{i-1}:v]blend=all_expr='A*(if(gte(T,3),1,T/3))+B*(1-(if(gte(T,3),1,T/3)))'[v{i-1}];" ) last_filter = "" for i in range(count - 1): last_filter += f"[v{i}]" last_filter += f'concat=n={count-1}:v=1:a=0[v]" -map "[v]"' filters.append(last_filter) filters = " ".join(filters) cmd = f"ffmpeg -y -loglevel error {inputs} -filter_complex {filters} {out_gif}" # if fade >= duration: # duration = fade + 1 # files = [] # for i in range(1, count + 1): # files.append(f"-framerate {framerate} -loop 1 -t {duration} -i {i}.png") # inputs = " ".join(files) # filters = [] # for i in range(count): # if i == 0: # filters.append(f'"[0:v]fade=t=out:st=4:d={fade}[v0];') # else: # filters.append( # f"[{i}:v]fade=t=in:st=0:d={fade},fade=t=out:st=4:d={fade}[v{i}];" # ) # last_filter = "" # for i in range(count): # last_filter += f"[v{i}]" # last_filter += f"concat=n={count}:v=1:a=0,split[v0][v1];" # filters.append(last_filter) # palette = f'[v0]palettegen[p];[v1][p]paletteuse[v]" -map "[v]"' # filters.append(palette) # filters = " ".join(filters) # cmd = f"ffmpeg -y {inputs} -filter_complex {filters} {out_gif}" os.system(cmd) try: shutil.rmtree(temp_dir) except Exception as e: print(e) os.chdir(current_dir) def add_text_to_gif( in_gif, out_gif, xy=None, text_sequence=None, font_type="arial.ttf", font_size=20, font_color="#000000", add_progress_bar=True, progress_bar_color="white", progress_bar_height=5, duration=100, loop=0, ): """Adds animated text to a GIF image. Args: in_gif (str): The file path to the input GIF image. out_gif (str): The file path to the output GIF image. xy (tuple, optional): Top left corner of the text. It can be formatted like this: (10, 10) or ('15%', '25%'). Defaults to None. text_sequence (int, str, list, optional): Text to be drawn. It can be an integer number, a string, or a list of strings. Defaults to None. font_type (str, optional): Font type. Defaults to "arial.ttf". font_size (int, optional): Font size. Defaults to 20. font_color (str, optional): Font color. It can be a string (e.g., 'red'), rgb tuple (e.g., (255, 127, 0)), or hex code (e.g., '#ff00ff'). Defaults to '#000000'. add_progress_bar (bool, optional): Whether to add a progress bar at the bottom of the GIF. Defaults to True. progress_bar_color (str, optional): Color for the progress bar. Defaults to 'white'. progress_bar_height (int, optional): Height of the progress bar. Defaults to 5. duration (int, optional): controls how long each frame will be displayed for, in milliseconds. It is the inverse of the frame rate. Setting it to 100 milliseconds gives 10 frames per second. You can decrease the duration to give a smoother animation.. Defaults to 100. loop (int, optional): controls how many times the animation repeats. The default, 1, means that the animation will play once and then stop (displaying the last frame). A value of 0 means that the animation will repeat forever. Defaults to 0. """ # import io import warnings import pkg_resources from PIL import Image, ImageDraw, ImageFont, ImageSequence warnings.simplefilter("ignore") pkg_dir = os.path.dirname(pkg_resources.resource_filename("geemap", "geemap.py")) default_font = os.path.join(pkg_dir, "data/fonts/arial.ttf") in_gif = os.path.abspath(in_gif) out_gif = os.path.abspath(out_gif) if not os.path.exists(in_gif): print("The input gif file does not exist.") return if not os.path.exists(os.path.dirname(out_gif)): os.makedirs(os.path.dirname(out_gif)) if font_type == "arial.ttf": font = ImageFont.truetype(default_font, font_size) elif font_type == "alibaba.otf": default_font = os.path.join(pkg_dir, "data/fonts/alibaba.otf") font = ImageFont.truetype(default_font, font_size) else: try: font_list = system_fonts(show_full_path=True) font_names = [os.path.basename(f) for f in font_list] if (font_type in font_list) or (font_type in font_names): font = ImageFont.truetype(font_type, font_size) else: print( "The specified font type could not be found on your system. Using the default font instead." ) font = ImageFont.truetype(default_font, font_size) except Exception as e: print(e) font = ImageFont.truetype(default_font, font_size) color = check_color(font_color) progress_bar_color = check_color(progress_bar_color) try: image = Image.open(in_gif) except Exception as e: print("An error occurred while opening the gif.") print(e) return count = image.n_frames W, H = image.size progress_bar_widths = [i * 1.0 / count * W for i in range(1, count + 1)] progress_bar_shapes = [ [(0, H - progress_bar_height), (x, H)] for x in progress_bar_widths ] if xy is None: # default text location is 5% width and 5% height of the image. xy = (int(0.05 * W), int(0.05 * H)) elif (xy is not None) and (not isinstance(xy, tuple)) and (len(xy) == 2): print("xy must be a tuple, e.g., (10, 10), ('10%', '10%')") return elif all(isinstance(item, int) for item in xy) and (len(xy) == 2): x, y = xy if (x > 0) and (x < W) and (y > 0) and (y < H): pass else: print( f"xy is out of bounds. x must be within [0, {W}], and y must be within [0, {H}]" ) return elif all(isinstance(item, str) for item in xy) and (len(xy) == 2): x, y = xy if ("%" in x) and ("%" in y): try: x = int(float(x.replace("%", "")) / 100.0 * W) y = int(float(y.replace("%", "")) / 100.0 * H) xy = (x, y) except Exception: raise Exception( "The specified xy is invalid. It must be formatted like this ('10%', '10%')" ) else: print( "The specified xy is invalid. It must be formatted like this: (10, 10) or ('10%', '10%')" ) return if text_sequence is None: text = [str(x) for x in range(1, count + 1)] elif isinstance(text_sequence, int): text = [str(x) for x in range(text_sequence, text_sequence + count + 1)] elif isinstance(text_sequence, str): try: text_sequence = int(text_sequence) text = [str(x) for x in range(text_sequence, text_sequence + count + 1)] except Exception: text = [text_sequence] * count elif isinstance(text_sequence, list) and len(text_sequence) != count: print( f"The length of the text sequence must be equal to the number ({count}) of frames in the gif." ) return else: text = [str(x) for x in text_sequence] try: frames = [] # Loop over each frame in the animated image for index, frame in enumerate(ImageSequence.Iterator(image)): # Draw the text on the frame frame = frame.convert("RGB") draw = ImageDraw.Draw(frame) # w, h = draw.textsize(text[index]) draw.text(xy, text[index], font=font, fill=color) if add_progress_bar: draw.rectangle(progress_bar_shapes[index], fill=progress_bar_color) del draw b = io.BytesIO() frame.save(b, format="GIF") frame = Image.open(b) frames.append(frame) # https://www.pythoninformer.com/python-libraries/pillow/creating-animated-gif/ # Save the frames as a new image frames[0].save( out_gif, save_all=True, append_images=frames[1:], duration=duration, loop=loop, optimize=True, ) except Exception as e: print(e) def reduce_gif_size(in_gif, out_gif=None): """Reduces a GIF image using ffmpeg. Args: in_gif (str): The input file path to the GIF image. out_gif (str, optional): The output file path to the GIF image. Defaults to None. """ import ffmpeg import warnings warnings.filterwarnings("ignore") if not is_tool("ffmpeg"): print("ffmpeg is not installed on your computer.") return if not os.path.exists(in_gif): print("The input gif file does not exist.") return if out_gif is None: out_gif = in_gif elif not os.path.exists(os.path.dirname(out_gif)): os.makedirs(os.path.dirname(out_gif)) if in_gif == out_gif: tmp_gif = in_gif.replace(".gif", "_tmp.gif") shutil.copyfile(in_gif, tmp_gif) stream = ffmpeg.input(tmp_gif) stream = ffmpeg.output(stream, in_gif, loglevel="quiet").overwrite_output() ffmpeg.run(stream) os.remove(tmp_gif) else: stream = ffmpeg.input(in_gif) stream = ffmpeg.output(stream, out_gif, loglevel="quiet").overwrite_output() ffmpeg.run(stream) def landsat_timeseries( roi=None, start_year=1984, end_year=None, start_date="06-10", end_date="09-20", apply_fmask=True, frequency="year", date_format=None, step=1, ): """Generates an annual Landsat ImageCollection. This algorithm is adapted from https://gist.github.com/jdbcode/76b9ac49faf51627ebd3ff988e10adbc. A huge thank you to Justin Braaten for sharing his fantastic work. Args: roi (object, optional): Region of interest to create the timelapse. Defaults to None. start_year (int, optional): Starting year for the timelapse. Defaults to 1984. end_year (int, optional): Ending year for the timelapse. Defaults to None, which means the current year. start_date (str, optional): Starting date (month-day) each year for filtering ImageCollection. Defaults to '06-10'. end_date (str, optional): Ending date (month-day) each year for filtering ImageCollection. Defaults to '09-20'. apply_fmask (bool, optional): Whether to apply Fmask (Function of mask) for automated clouds, cloud shadows, snow, and water masking. frequency (str, optional): Frequency of the timelapse. Defaults to 'year'. date_format (str, optional): Format of the date. Defaults to None. step (int, optional): The step size to use when creating the date sequence. Defaults to 1. Returns: object: Returns an ImageCollection containing annual Landsat images. """ # Input and output parameters. import re if roi is None: roi = ee.Geometry.Polygon( [ [ [-115.471773, 35.892718], [-115.471773, 36.409454], [-114.271283, 36.409454], [-114.271283, 35.892718], [-115.471773, 35.892718], ] ], None, False, ) if end_year is None: end_year = get_current_year() if not isinstance(roi, ee.Geometry): try: roi = roi.geometry() except Exception as e: print("Could not convert the provided roi to ee.Geometry") print(e) return feq_dict = { "year": "YYYY", "month": "YYYY-MM", "quarter": "YYYY-MM", } if date_format is None: date_format = feq_dict[frequency] if frequency not in feq_dict: raise ValueError("frequency must be year, quarter, or month.") # Setup vars to get dates. if ( isinstance(start_year, int) and (start_year >= 1984) and (start_year < get_current_year()) ): pass else: print("The start year must be an integer >= 1984.") return if ( isinstance(end_year, int) and (end_year > 1984) and (end_year <= get_current_year()) ): pass else: print(f"The end year must be an integer <= {get_current_year()}.") return if re.match(r"[0-9]{2}-[0-9]{2}", start_date) and re.match( r"[0-9]{2}-[0-9]{2}", end_date ): pass else: print("The start date and end date must be month-day, such as 06-10, 09-20") return try: datetime.datetime(int(start_year), int(start_date[:2]), int(start_date[3:5])) datetime.datetime(int(end_year), int(end_date[:2]), int(end_date[3:5])) except Exception as e: print("The input dates are invalid.") raise Exception(e) def days_between(d1, d2): d1 = datetime.datetime.strptime(d1, "%Y-%m-%d") d2 = datetime.datetime.strptime(d2, "%Y-%m-%d") return abs((d2 - d1).days) n_days = days_between( str(start_year) + "-" + start_date, str(start_year) + "-" + end_date ) start_month = int(start_date[:2]) start_day = int(start_date[3:5]) # Landsat collection preprocessingEnabled # Get Landsat surface reflectance collections for OLI, ETM+ and TM sensors. LC09col = ee.ImageCollection("LANDSAT/LC09/C02/T1_L2") LC08col = ee.ImageCollection("LANDSAT/LC08/C02/T1_L2") LE07col = ee.ImageCollection("LANDSAT/LE07/C02/T1_L2") LT05col = ee.ImageCollection("LANDSAT/LT05/C02/T1_L2") LT04col = ee.ImageCollection("LANDSAT/LT04/C02/T1_L2") # Define a collection filter by date, bounds, and quality. def colFilter(col, roi, start_date, end_date): return col.filterBounds(roi).filterDate(start_date, end_date) # Function to get and rename bands of interest from OLI. def renameOli(img): return img.select( ["SR_B2", "SR_B3", "SR_B4", "SR_B5", "SR_B6", "SR_B7"], ["Blue", "Green", "Red", "NIR", "SWIR1", "SWIR2"], ) # Function to get and rename bands of interest from ETM+. def renameEtm(img): return img.select( ["SR_B1", "SR_B2", "SR_B3", "SR_B4", "SR_B5", "SR_B7"], ["Blue", "Green", "Red", "NIR", "SWIR1", "SWIR2"], ) def fmask(image): # see https://developers.google.com/earth-engine/datasets/catalog/LANDSAT_LC09_C02_T1_L2 # Bit 0 - Fill # Bit 1 - Dilated Cloud # Bit 2 - Cirrus # Bit 3 - Cloud # Bit 4 - Cloud Shadow qaMask = image.select("QA_PIXEL").bitwiseAnd(int("11111", 2)).eq(0) # Apply the scaling factors to the appropriate bands. opticalBands = image.select("SR_B.").multiply(0.0000275).add(-0.2) # Replace the original bands with the scaled ones and apply the masks. return image.addBands(opticalBands, None, True).updateMask(qaMask) # Define function to prepare OLI images. def prepOli(img): orig = img if apply_fmask: img = fmask(img) else: img = img.select("SR_B.").multiply(0.0000275).add(-0.2) img = renameOli(img) return ee.Image(img.copyProperties(orig, orig.propertyNames())).resample( "bicubic" ) # Define function to prepare ETM+ images. def prepEtm(img): orig = img if apply_fmask: img = fmask(img) else: img = img.select("SR_B.").multiply(0.0000275).add(-0.2) img = renameEtm(img) return ee.Image(img.copyProperties(orig, orig.propertyNames())).resample( "bicubic" ) # Get annual median collection. def getAnnualComp(y): startDate = ee.Date.fromYMD( ee.Number(y), ee.Number(start_month), ee.Number(start_day) ) endDate = startDate.advance(ee.Number(n_days), "day") # Filter collections and prepare them for merging. LC09coly = colFilter(LC09col, roi, startDate, endDate).map(prepOli) LC08coly = colFilter(LC08col, roi, startDate, endDate).map(prepOli) LE07coly = colFilter(LE07col, roi, startDate, endDate).map(prepEtm) LT05coly = colFilter(LT05col, roi, startDate, endDate).map(prepEtm) LT04coly = colFilter(LT04col, roi, startDate, endDate).map(prepEtm) # Merge the collections. col = LC09coly.merge(LC08coly).merge(LE07coly).merge(LT05coly).merge(LT04coly) yearImg = col.median() nBands = yearImg.bandNames().size() yearImg = ee.Image(ee.Algorithms.If(nBands, yearImg, dummyImg)) return yearImg.set( { "year": y, "system:time_start": startDate.millis(), "nBands": nBands, "system:date": ee.Date(startDate).format(date_format), } ) # Get monthly median collection. def getMonthlyComp(startDate): startDate = ee.Date(startDate) endDate = startDate.advance(1, "month") # Filter collections and prepare them for merging. LC09coly = colFilter(LC09col, roi, startDate, endDate).map(prepOli) LC08coly = colFilter(LC08col, roi, startDate, endDate).map(prepOli) LE07coly = colFilter(LE07col, roi, startDate, endDate).map(prepEtm) LT05coly = colFilter(LT05col, roi, startDate, endDate).map(prepEtm) LT04coly = colFilter(LT04col, roi, startDate, endDate).map(prepEtm) # Merge the collections. col = LC09coly.merge(LC08coly).merge(LE07coly).merge(LT05coly).merge(LT04coly) monthImg = col.median() nBands = monthImg.bandNames().size() monthImg = ee.Image(ee.Algorithms.If(nBands, monthImg, dummyImg)) return monthImg.set( { "system:time_start": startDate.millis(), "nBands": nBands, "system:date": ee.Date(startDate).format(date_format), } ) # Get quarterly median collection. def getQuarterlyComp(startDate): startDate = ee.Date(startDate) endDate = startDate.advance(3, "month") # Filter collections and prepare them for merging. LC09coly = colFilter(LC09col, roi, startDate, endDate).map(prepOli) LC08coly = colFilter(LC08col, roi, startDate, endDate).map(prepOli) LE07coly = colFilter(LE07col, roi, startDate, endDate).map(prepEtm) LT05coly = colFilter(LT05col, roi, startDate, endDate).map(prepEtm) LT04coly = colFilter(LT04col, roi, startDate, endDate).map(prepEtm) # Merge the collections. col = LC09coly.merge(LC08coly).merge(LE07coly).merge(LT05coly).merge(LT04coly) quarter = col.median() nBands = quarter.bandNames().size() quarter = ee.Image(ee.Algorithms.If(nBands, quarter, dummyImg)) return quarter.set( { "system:time_start": startDate.millis(), "nBands": nBands, "system:date": ee.Date(startDate).format(date_format), } ) # Make a dummy image for missing years. bandNames = ee.List(["Blue", "Green", "Red", "NIR", "SWIR1", "SWIR2", "pixel_qa"]) fillerValues = ee.List.repeat(0, bandNames.size()) dummyImg = ee.Image.constant(fillerValues).rename(bandNames).selfMask().int16() # Make list of /quarterly/monthly image composites. if frequency == "year": years = ee.List.sequence(start_year, end_year, step) imgList = years.map(getAnnualComp) elif frequency == "quarter": quarters = date_sequence( str(start_year) + "-01-01", str(end_year) + "-12-31", "quarter", date_format, step, ) imgList = quarters.map(getQuarterlyComp) elif frequency == "month": months = date_sequence( str(start_year) + "-01-01", str(end_year) + "-12-31", "month", date_format, step, ) imgList = months.map(getMonthlyComp) # Convert image composite list to collection imgCol = ee.ImageCollection.fromImages(imgList) imgCol = imgCol.map( lambda img: img.clip(roi).set({"coordinates": roi.coordinates()}) ) return imgCol def landsat_ts_norm_diff(collection, bands=["Green", "SWIR1"], threshold=0): """Computes a normalized difference index based on a Landsat timeseries. Args: collection (ee.ImageCollection): A Landsat timeseries. bands (list, optional): The bands to use for computing normalized difference. Defaults to ['Green', 'SWIR1']. threshold (float, optional): The threshold to extract features. Defaults to 0. Returns: ee.ImageCollection: An ImageCollection containing images with values greater than the specified threshold. """ nd_images = collection.map( lambda img: img.normalizedDifference(bands) .gt(threshold) .copyProperties(img, img.propertyNames()) ) return nd_images def landsat_ts_norm_diff_gif( collection, out_gif=None, vis_params=None, palette=["black", "blue"], dimensions=768, frames_per_second=10, mp4=False, ): """[summary] Args: collection (ee.ImageCollection): The normalized difference Landsat timeseires. out_gif (str, optional): File path to the output animated GIF. Defaults to None. vis_params (dict, optional): Visualization parameters. Defaults to None. palette (list, optional): The palette to use for visualizing the timelapse. Defaults to ['black', 'blue']. The first color in the list is the background color. dimensions (int, optional): a number or pair of numbers (in format 'WIDTHxHEIGHT') Maximum dimensions of the thumbnail to render, in pixels. If only one number is passed, it is used as the maximum, and the other dimension is computed by proportional scaling. Defaults to 768. frames_per_second (int, optional): Animation speed. Defaults to 10. mp4 (bool, optional): If True, the output gif will be converted to mp4. Defaults to False. Returns: str: File path to the output animated GIF. """ coordinates = ee.Image(collection.first()).get("coordinates") roi = ee.Geometry.Polygon(coordinates, None, False) if out_gif is None: out_dir = os.path.join(os.path.expanduser("~"), "Downloads") filename = "landsat_ts_nd_" + random_string() + ".gif" out_gif = os.path.join(out_dir, filename) elif not out_gif.endswith(".gif"): raise Exception("The output file must end with .gif") bands = ["nd"] if vis_params is None: vis_params = {} vis_params["bands"] = bands vis_params["palette"] = palette video_args = vis_params.copy() video_args["dimensions"] = dimensions video_args["region"] = roi video_args["framesPerSecond"] = frames_per_second video_args["crs"] = "EPSG:3857" if "bands" not in video_args.keys(): video_args["bands"] = bands download_ee_video(collection, video_args, out_gif) if os.path.exists(out_gif): reduce_gif_size(out_gif) if mp4: out_mp4 = out_gif.replace(".gif", ".mp4") gif_to_mp4(out_gif, out_mp4) import os import ee def get_image_collection_thumbnails( ee_object, out_dir, vis_params, dimensions=500, region=None, format="jpg", names=None, verbose=True, timeout=300, proxies=None, ): """Download thumbnails for all images in an ImageCollection. Args: ee_object (object): The ee.ImageCollection instance. out_dir ([str): The output directory to store thumbnails. vis_params (dict): The visualization parameters. dimensions (int, optional):(a number or pair of numbers in format WIDTHxHEIGHT) Maximum dimensions of the thumbnail to render, in pixels. If only one number is passed, it is used as the maximum, and the other dimension is computed by proportional scaling. Defaults to 500. region (object, optional): Geospatial region of the image to render, it may be an ee.Geometry, GeoJSON, or an array of lat/lon points (E,S,W,N). If not set the default is the bounds image. Defaults to None. format (str, optional): Either 'png' or 'jpg'. Default to 'jpg'. names (list, optional): The list of output file names. Defaults to None. verbose (bool, optional): Whether or not to print hints. Defaults to True. timeout (int, optional): The number of seconds after which the request will be terminated. Defaults to 300. proxies (dict, optional): A dictionary of proxy servers to use for the request. Defaults to None. """ if not isinstance(ee_object, ee.ImageCollection): print("The ee_object must be an ee.ImageCollection.") raise TypeError("The ee_object must be an ee.Image.") if format not in ["png", "jpg"]: raise ValueError("The output image format must be png or jpg.") if not os.path.exists(out_dir): os.makedirs(out_dir) try: count = int(ee_object.size().getInfo()) if verbose: print(f"Total number of images: {count}\n") if (names is not None) and (len(names) != count): print("The number of names is not equal to the number of images.") return if names is None: names = ee_object.aggregate_array("system:index").getInfo() images = ee_object.toList(count) for i in range(0, count): image = ee.Image(images.get(i)) name = str(names[i]) ext = os.path.splitext(name)[1][1:] if ext != format: name = name + "." + format out_img = os.path.join(out_dir, name) if verbose: print(f"Downloading {i+1}/{count}: {name} ...") get_image_thumbnail( image, out_img, vis_params, dimensions, region, format, timeout=timeout, proxies=proxies, ) except Exception as e: print(e) def download_ee_video(collection, video_args, out_gif, timeout=300, proxies=None): """Downloads a video thumbnail as a GIF image from Earth Engine. Args: collection (object): An ee.ImageCollection. video_args (object): Parameters for expring the video thumbnail. out_gif (str): File path to the output GIF. timeout (int, optional): The number of seconds the request will be timed out. Defaults to 300. proxies (dict, optional): A dictionary of proxy servers to use. Defaults to None. """ out_gif = os.path.abspath(out_gif) if not out_gif.endswith(".gif"): print("The output file must have an extension of .gif.") return if not os.path.exists(os.path.dirname(out_gif)): os.makedirs(os.path.dirname(out_gif)) if "region" in video_args.keys(): roi = video_args["region"] if not isinstance(roi, ee.Geometry): try: roi = roi.geometry() except Exception as e: print("Could not convert the provided roi to ee.Geometry") print(e) return video_args["region"] = roi if "dimensions" not in video_args: video_args["dimensions"] = 768 try: print("Generating URL...") url = collection.getVideoThumbURL(video_args) print(f"Downloading GIF image from {url}\nPlease wait ...") r = requests.get(url, stream=True, timeout=timeout, proxies=proxies) if r.status_code != 200: print("An error occurred while downloading.") print(r.json()["error"]["message"]) return else: with open(out_gif, "wb") as fd: for chunk in r.iter_content(chunk_size=1024): fd.write(chunk) print(f"The GIF image has been saved to: {out_gif}") except Exception as e: print(e) def temp_file_path(extension): """Returns a temporary file path. Args: extension (str): The file extension. Returns: str: The temporary file path. """ import tempfile import uuid if not extension.startswith("."): extension = "." + extension file_id = str(uuid.uuid4()) file_path = os.path.join(tempfile.gettempdir(), f"{file_id}{extension}") return file_path def get_current_year(): """Get the current year. Returns: int: The current year. """ today = datetime.date.today() return today.year The provided code snippet includes necessary dependencies for implementing the `landsat_timelapse_legacy` function. Write a Python function `def landsat_timelapse_legacy( roi=None, out_gif=None, start_year=1984, end_year=None, start_date="06-10", end_date="09-20", bands=["NIR", "Red", "Green"], vis_params=None, dimensions=768, frames_per_second=5, crs="EPSG:3857", apply_fmask=True, nd_bands=None, nd_threshold=0, nd_palette=["black", "blue"], overlay_data=None, overlay_color="black", overlay_width=1, overlay_opacity=1.0, frequency="year", date_format=None, title=None, title_xy=("2%", "90%"), add_text=True, text_xy=("2%", "2%"), text_sequence=None, font_type="arial.ttf", font_size=20, font_color="white", add_progress_bar=True, progress_bar_color="white", progress_bar_height=5, loop=0, mp4=False, fading=False, )` to solve the following problem: Generates a Landsat timelapse GIF image. This function is adapted from https://emaprlab.users.earthengine.app/view/lt-gee-time-series-animator. A huge thank you to Justin Braaten for sharing his fantastic work. Args: roi (object, optional): Region of interest to create the timelapse. Defaults to None. out_gif (str, optional): File path to the output animated GIF. Defaults to None. start_year (int, optional): Starting year for the timelapse. Defaults to 1984. end_year (int, optional): Ending year for the timelapse. Defaults to None, which means the current year. start_date (str, optional): Starting date (month-day) each year for filtering ImageCollection. Defaults to '06-10'. end_date (str, optional): Ending date (month-day) each year for filtering ImageCollection. Defaults to '09-20'. bands (list, optional): Three bands selected from ['Blue', 'Green', 'Red', 'NIR', 'SWIR1', 'SWIR2', 'pixel_qa']. Defaults to ['NIR', 'Red', 'Green']. vis_params (dict, optional): Visualization parameters. Defaults to None. dimensions (int, optional): a number or pair of numbers (in format 'WIDTHxHEIGHT') Maximum dimensions of the thumbnail to render, in pixels. If only one number is passed, it is used as the maximum, and the other dimension is computed by proportional scaling. Defaults to 768. frames_per_second (int, optional): Animation speed. Defaults to 5. crs (str, optional): The coordinate reference system to use. Defaults to "EPSG:3857". apply_fmask (bool, optional): Whether to apply Fmask (Function of mask) for automated clouds, cloud shadows, snow, and water masking. nd_bands (list, optional): A list of names specifying the bands to use, e.g., ['Green', 'SWIR1']. The normalized difference is computed as (first − second) / (first + second). Note that negative input values are forced to 0 so that the result is confined to the range (-1, 1). nd_threshold (float, optional): The threshold for extracting pixels from the normalized difference band. nd_palette (list, optional): The color palette to use for displaying the normalized difference band. overlay_data (int, str, list, optional): Administrative boundary to be drawn on the timelapse. Defaults to None. overlay_color (str, optional): Color for the overlay data. Can be any color name or hex color code. Defaults to 'black'. overlay_width (int, optional): Line width of the overlay. Defaults to 1. overlay_opacity (float, optional): Opacity of the overlay. Defaults to 1.0. frequency (str, optional): Frequency of the timelapse. Defaults to 'year'. date_format (str, optional): Date format for the timelapse. Defaults to None. title (str, optional): The title of the timelapse. Defaults to None. title_xy (tuple, optional): Lower left corner of the title. It can be formatted like this: (10, 10) or ('15%', '25%'). Defaults to None. add_text (bool, optional): Whether to add animated text to the timelapse. Defaults to True. title_xy (tuple, optional): Lower left corner of the text sequency. It can be formatted like this: (10, 10) or ('15%', '25%'). Defaults to None. text_sequence (int, str, list, optional): Text to be drawn. It can be an integer number, a string, or a list of strings. Defaults to None. font_type (str, optional): Font type. Defaults to "arial.ttf". font_size (int, optional): Font size. Defaults to 20. font_color (str, optional): Font color. It can be a string (e.g., 'red'), rgb tuple (e.g., (255, 127, 0)), or hex code (e.g., '#ff00ff'). Defaults to '#000000'. add_progress_bar (bool, optional): Whether to add a progress bar at the bottom of the GIF. Defaults to True. progress_bar_color (str, optional): Color for the progress bar. Defaults to 'white'. progress_bar_height (int, optional): Height of the progress bar. Defaults to 5. loop (int, optional): Controls how many times the animation repeats. The default, 1, means that the animation will play once and then stop (displaying the last frame). A value of 0 means that the animation will repeat forever. Defaults to 0. mp4 (bool, optional): Whether to convert the GIF to MP4. Defaults to False. fading (int | bool, optional): If True, add fading effect to the timelapse. Defaults to False, no fading. To add fading effect, set it to True (1 second fading duration) or to an integer value (fading duration). Returns: str: File path to the output GIF image. Here is the function: def landsat_timelapse_legacy( roi=None, out_gif=None, start_year=1984, end_year=None, start_date="06-10", end_date="09-20", bands=["NIR", "Red", "Green"], vis_params=None, dimensions=768, frames_per_second=5, crs="EPSG:3857", apply_fmask=True, nd_bands=None, nd_threshold=0, nd_palette=["black", "blue"], overlay_data=None, overlay_color="black", overlay_width=1, overlay_opacity=1.0, frequency="year", date_format=None, title=None, title_xy=("2%", "90%"), add_text=True, text_xy=("2%", "2%"), text_sequence=None, font_type="arial.ttf", font_size=20, font_color="white", add_progress_bar=True, progress_bar_color="white", progress_bar_height=5, loop=0, mp4=False, fading=False, ): """Generates a Landsat timelapse GIF image. This function is adapted from https://emaprlab.users.earthengine.app/view/lt-gee-time-series-animator. A huge thank you to Justin Braaten for sharing his fantastic work. Args: roi (object, optional): Region of interest to create the timelapse. Defaults to None. out_gif (str, optional): File path to the output animated GIF. Defaults to None. start_year (int, optional): Starting year for the timelapse. Defaults to 1984. end_year (int, optional): Ending year for the timelapse. Defaults to None, which means the current year. start_date (str, optional): Starting date (month-day) each year for filtering ImageCollection. Defaults to '06-10'. end_date (str, optional): Ending date (month-day) each year for filtering ImageCollection. Defaults to '09-20'. bands (list, optional): Three bands selected from ['Blue', 'Green', 'Red', 'NIR', 'SWIR1', 'SWIR2', 'pixel_qa']. Defaults to ['NIR', 'Red', 'Green']. vis_params (dict, optional): Visualization parameters. Defaults to None. dimensions (int, optional): a number or pair of numbers (in format 'WIDTHxHEIGHT') Maximum dimensions of the thumbnail to render, in pixels. If only one number is passed, it is used as the maximum, and the other dimension is computed by proportional scaling. Defaults to 768. frames_per_second (int, optional): Animation speed. Defaults to 5. crs (str, optional): The coordinate reference system to use. Defaults to "EPSG:3857". apply_fmask (bool, optional): Whether to apply Fmask (Function of mask) for automated clouds, cloud shadows, snow, and water masking. nd_bands (list, optional): A list of names specifying the bands to use, e.g., ['Green', 'SWIR1']. The normalized difference is computed as (first − second) / (first + second). Note that negative input values are forced to 0 so that the result is confined to the range (-1, 1). nd_threshold (float, optional): The threshold for extracting pixels from the normalized difference band. nd_palette (list, optional): The color palette to use for displaying the normalized difference band. overlay_data (int, str, list, optional): Administrative boundary to be drawn on the timelapse. Defaults to None. overlay_color (str, optional): Color for the overlay data. Can be any color name or hex color code. Defaults to 'black'. overlay_width (int, optional): Line width of the overlay. Defaults to 1. overlay_opacity (float, optional): Opacity of the overlay. Defaults to 1.0. frequency (str, optional): Frequency of the timelapse. Defaults to 'year'. date_format (str, optional): Date format for the timelapse. Defaults to None. title (str, optional): The title of the timelapse. Defaults to None. title_xy (tuple, optional): Lower left corner of the title. It can be formatted like this: (10, 10) or ('15%', '25%'). Defaults to None. add_text (bool, optional): Whether to add animated text to the timelapse. Defaults to True. title_xy (tuple, optional): Lower left corner of the text sequency. It can be formatted like this: (10, 10) or ('15%', '25%'). Defaults to None. text_sequence (int, str, list, optional): Text to be drawn. It can be an integer number, a string, or a list of strings. Defaults to None. font_type (str, optional): Font type. Defaults to "arial.ttf". font_size (int, optional): Font size. Defaults to 20. font_color (str, optional): Font color. It can be a string (e.g., 'red'), rgb tuple (e.g., (255, 127, 0)), or hex code (e.g., '#ff00ff'). Defaults to '#000000'. add_progress_bar (bool, optional): Whether to add a progress bar at the bottom of the GIF. Defaults to True. progress_bar_color (str, optional): Color for the progress bar. Defaults to 'white'. progress_bar_height (int, optional): Height of the progress bar. Defaults to 5. loop (int, optional): Controls how many times the animation repeats. The default, 1, means that the animation will play once and then stop (displaying the last frame). A value of 0 means that the animation will repeat forever. Defaults to 0. mp4 (bool, optional): Whether to convert the GIF to MP4. Defaults to False. fading (int | bool, optional): If True, add fading effect to the timelapse. Defaults to False, no fading. To add fading effect, set it to True (1 second fading duration) or to an integer value (fading duration). Returns: str: File path to the output GIF image. """ if end_year is None: end_year = get_current_year() if roi is None: roi = ee.Geometry.Polygon( [ [ [-115.471773, 35.892718], [-115.471773, 36.409454], [-114.271283, 36.409454], [-114.271283, 35.892718], [-115.471773, 35.892718], ] ], None, False, ) elif isinstance(roi, ee.Feature) or isinstance(roi, ee.FeatureCollection): roi = roi.geometry() elif isinstance(roi, ee.Geometry): pass else: raise ValueError("The provided roi is invalid. It must be an ee.Geometry") if out_gif is None: out_gif = temp_file_path(".gif") elif not out_gif.endswith(".gif"): raise ValueError("The output file must end with .gif") else: out_gif = os.path.abspath(out_gif) out_dir = os.path.dirname(out_gif) if not os.path.exists(out_dir): os.makedirs(out_dir) allowed_bands = ["Blue", "Green", "Red", "NIR", "SWIR1", "SWIR2", "pixel_qa"] if len(bands) == 3 and all(x in allowed_bands for x in bands): pass else: raise Exception( "You can only select 3 bands from the following: {}".format( ", ".join(allowed_bands) ) ) if nd_bands is not None: if len(nd_bands) == 2 and all(x in allowed_bands[:-1] for x in nd_bands): pass else: raise Exception( "You can only select two bands from the following: {}".format( ", ".join(allowed_bands[:-1]) ) ) try: if vis_params is None: vis_params = {} vis_params["bands"] = bands vis_params["min"] = 0 vis_params["max"] = 4000 vis_params["gamma"] = [1, 1, 1] raw_col = landsat_timeseries( roi, start_year, end_year, start_date, end_date, apply_fmask, frequency, date_format, ) col = raw_col.select(bands).map( lambda img: img.visualize(**vis_params).set( { "system:time_start": img.get("system:time_start"), "system:date": img.get("system:date"), } ) ) if overlay_data is not None: col = add_overlay( col, overlay_data, overlay_color, overlay_width, overlay_opacity ) if ( isinstance(dimensions, int) and dimensions > 768 or isinstance(dimensions, str) and any(dim > 768 for dim in list(map(int, dimensions.split("x")))) ): count = col.size().getInfo() basename = os.path.basename(out_gif)[:-4] names = [ os.path.join( out_dir, f"{basename}_{str(i+1).zfill(int(len(str(count))))}.jpg" ) for i in range(count) ] get_image_collection_thumbnails( col, out_dir, vis_params={ "min": 0, "max": 255, "bands": ["vis-red", "vis-green", "vis-blue"], }, dimensions=dimensions, names=names, ) make_gif( names, out_gif, fps=frames_per_second, loop=loop, mp4=False, clean_up=True, ) else: video_args = vis_params.copy() video_args["dimensions"] = dimensions video_args["region"] = roi video_args["framesPerSecond"] = frames_per_second video_args["crs"] = crs video_args["bands"] = ["vis-red", "vis-green", "vis-blue"] video_args["min"] = 0 video_args["max"] = 255 download_ee_video(col, video_args, out_gif) if os.path.exists(out_gif): if title is not None and isinstance(title, str): add_text_to_gif( out_gif, out_gif, xy=title_xy, text_sequence=title, font_type=font_type, font_size=font_size, font_color=font_color, add_progress_bar=add_progress_bar, progress_bar_color=progress_bar_color, progress_bar_height=progress_bar_height, duration=1000 / frames_per_second, loop=loop, ) if add_text: if text_sequence is None: text_sequence = col.aggregate_array("system:date").getInfo() add_text_to_gif( out_gif, out_gif, xy=text_xy, text_sequence=text_sequence, font_type=font_type, font_size=font_size, font_color=font_color, add_progress_bar=add_progress_bar, progress_bar_color=progress_bar_color, progress_bar_height=progress_bar_height, duration=1000 / frames_per_second, loop=loop, ) if nd_bands is not None: nd_images = landsat_ts_norm_diff( raw_col, bands=nd_bands, threshold=nd_threshold ) out_nd_gif = out_gif.replace(".gif", "_nd.gif") landsat_ts_norm_diff_gif( nd_images, out_gif=out_nd_gif, vis_params=None, palette=nd_palette, dimensions=dimensions, frames_per_second=frames_per_second, ) if os.path.exists(out_gif): reduce_gif_size(out_gif) if isinstance(fading, bool): fading = int(fading) if fading > 0: gif_fading(out_gif, out_gif, duration=fading, verbose=False) if mp4: out_mp4 = out_gif.replace(".gif", ".mp4") gif_to_mp4(out_gif, out_mp4) return out_gif except Exception as e: raise Exception(e)
Generates a Landsat timelapse GIF image. This function is adapted from https://emaprlab.users.earthengine.app/view/lt-gee-time-series-animator. A huge thank you to Justin Braaten for sharing his fantastic work. Args: roi (object, optional): Region of interest to create the timelapse. Defaults to None. out_gif (str, optional): File path to the output animated GIF. Defaults to None. start_year (int, optional): Starting year for the timelapse. Defaults to 1984. end_year (int, optional): Ending year for the timelapse. Defaults to None, which means the current year. start_date (str, optional): Starting date (month-day) each year for filtering ImageCollection. Defaults to '06-10'. end_date (str, optional): Ending date (month-day) each year for filtering ImageCollection. Defaults to '09-20'. bands (list, optional): Three bands selected from ['Blue', 'Green', 'Red', 'NIR', 'SWIR1', 'SWIR2', 'pixel_qa']. Defaults to ['NIR', 'Red', 'Green']. vis_params (dict, optional): Visualization parameters. Defaults to None. dimensions (int, optional): a number or pair of numbers (in format 'WIDTHxHEIGHT') Maximum dimensions of the thumbnail to render, in pixels. If only one number is passed, it is used as the maximum, and the other dimension is computed by proportional scaling. Defaults to 768. frames_per_second (int, optional): Animation speed. Defaults to 5. crs (str, optional): The coordinate reference system to use. Defaults to "EPSG:3857". apply_fmask (bool, optional): Whether to apply Fmask (Function of mask) for automated clouds, cloud shadows, snow, and water masking. nd_bands (list, optional): A list of names specifying the bands to use, e.g., ['Green', 'SWIR1']. The normalized difference is computed as (first − second) / (first + second). Note that negative input values are forced to 0 so that the result is confined to the range (-1, 1). nd_threshold (float, optional): The threshold for extracting pixels from the normalized difference band. nd_palette (list, optional): The color palette to use for displaying the normalized difference band. overlay_data (int, str, list, optional): Administrative boundary to be drawn on the timelapse. Defaults to None. overlay_color (str, optional): Color for the overlay data. Can be any color name or hex color code. Defaults to 'black'. overlay_width (int, optional): Line width of the overlay. Defaults to 1. overlay_opacity (float, optional): Opacity of the overlay. Defaults to 1.0. frequency (str, optional): Frequency of the timelapse. Defaults to 'year'. date_format (str, optional): Date format for the timelapse. Defaults to None. title (str, optional): The title of the timelapse. Defaults to None. title_xy (tuple, optional): Lower left corner of the title. It can be formatted like this: (10, 10) or ('15%', '25%'). Defaults to None. add_text (bool, optional): Whether to add animated text to the timelapse. Defaults to True. title_xy (tuple, optional): Lower left corner of the text sequency. It can be formatted like this: (10, 10) or ('15%', '25%'). Defaults to None. text_sequence (int, str, list, optional): Text to be drawn. It can be an integer number, a string, or a list of strings. Defaults to None. font_type (str, optional): Font type. Defaults to "arial.ttf". font_size (int, optional): Font size. Defaults to 20. font_color (str, optional): Font color. It can be a string (e.g., 'red'), rgb tuple (e.g., (255, 127, 0)), or hex code (e.g., '#ff00ff'). Defaults to '#000000'. add_progress_bar (bool, optional): Whether to add a progress bar at the bottom of the GIF. Defaults to True. progress_bar_color (str, optional): Color for the progress bar. Defaults to 'white'. progress_bar_height (int, optional): Height of the progress bar. Defaults to 5. loop (int, optional): Controls how many times the animation repeats. The default, 1, means that the animation will play once and then stop (displaying the last frame). A value of 0 means that the animation will repeat forever. Defaults to 0. mp4 (bool, optional): Whether to convert the GIF to MP4. Defaults to False. fading (int | bool, optional): If True, add fading effect to the timelapse. Defaults to False, no fading. To add fading effect, set it to True (1 second fading duration) or to an integer value (fading duration). Returns: str: File path to the output GIF image.
12,184
import datetime import glob import io import os import shutil import ee from .common import * from typing import Union, List def add_overlay( collection: ee.ImageCollection, overlay_data: Union[str, ee.Geometry, ee.FeatureCollection], color: str = "black", width: int = 1, opacity: float = 1.0, region: Union[ee.Geometry, ee.FeatureCollection] = None, ) -> ee.ImageCollection: """Adds an overlay to an image collection. Args: collection (ee.ImageCollection): The image collection to add the overlay to. overlay_data (str | ee.Geometry | ee.FeatureCollection): The overlay data to add to the image collection. It can be an HTTP URL to a GeoJSON file. color (str, optional): The color of the overlay. Defaults to 'black'. width (int, optional): The width of the overlay. Defaults to 1. opacity (float, optional): The opacity of the overlay. Defaults to 1.0. region (ee.Geometry | ee.FeatureCollection, optional): The region of interest to add the overlay to. Defaults to None. Returns: ee.ImageCollection: An ImageCollection with the overlay added. """ # Some common administrative boundaries. public_assets = ["continents", "countries", "us_states", "china"] if not isinstance(collection, ee.ImageCollection): raise Exception("The collection must be an ee.ImageCollection.") if not isinstance(overlay_data, ee.FeatureCollection): if isinstance(overlay_data, str): try: if overlay_data.lower() in public_assets: overlay_data = ee.FeatureCollection( f"users/giswqs/public/{overlay_data.lower()}" ) elif overlay_data.startswith("http") and overlay_data.endswith( ".geojson" ): overlay_data = geojson_to_ee(overlay_data) else: overlay_data = ee.FeatureCollection(overlay_data) except Exception as e: print( "The overlay_data must be a valid ee.FeatureCollection, a valid ee.FeatureCollection asset id, or http url to a geojson file." ) raise Exception(e) elif isinstance(overlay_data, ee.Feature): overlay_data = ee.FeatureCollection([overlay_data]) elif isinstance(overlay_data, ee.Geometry): overlay_data = ee.FeatureCollection([ee.Feature(overlay_data)]) else: raise Exception( "The overlay_data must be a valid ee.FeatureCollection or a valid ee.FeatureCollection asset id." ) try: if region is not None: overlay_data = overlay_data.filterBounds(region) empty = ee.Image().byte() image = empty.paint( **{ "featureCollection": overlay_data, "color": 1, "width": width, } ).visualize(**{"palette": check_color(color), "opacity": opacity}) blend_col = collection.map( lambda img: img.blend(image).set( "system:time_start", img.get("system:time_start") ) ) return blend_col except Exception as e: print("Error in add_overlay:") raise Exception(e) def make_gif( images: Union[List[str], str], out_gif: str, ext: str = "jpg", fps: int = 10, loop: int = 0, mp4: bool = False, clean_up: bool = False, ) -> None: """Creates a gif from a list of images. Args: images (list | str): The list of images or input directory to create the gif from. out_gif (str): File path to the output gif. ext (str, optional): The extension of the images. Defaults to 'jpg'. fps (int, optional): The frames per second of the gif. Defaults to 10. loop (int, optional): The number of times to loop the gif. Defaults to 0. mp4 (bool, optional): Whether to convert the gif to mp4. Defaults to False. """ if isinstance(images, str) and os.path.isdir(images): images = list(glob.glob(os.path.join(images, f"*.{ext}"))) if len(images) == 0: raise ValueError("No images found in the input directory.") elif not isinstance(images, list): raise ValueError("images must be a list or a path to the image directory.") images.sort() frames = [Image.open(image) for image in images] frame_one = frames[0] frame_one.save( out_gif, format="GIF", append_images=frames, save_all=True, duration=int(1000 / fps), loop=loop, ) if mp4: if not is_tool("ffmpeg"): print("ffmpeg is not installed on your computer.") return if os.path.exists(out_gif): out_mp4 = out_gif.replace(".gif", ".mp4") cmd = f"ffmpeg -loglevel error -i {out_gif} -vcodec libx264 -crf 25 -pix_fmt yuv420p {out_mp4}" os.system(cmd) if not os.path.exists(out_mp4): raise Exception(f"Failed to create mp4 file.") if clean_up: for image in images: os.remove(image) def gif_to_mp4(in_gif, out_mp4): """Converts a gif to mp4. Args: in_gif (str): The input gif file. out_mp4 (str): The output mp4 file. """ from PIL import Image if not os.path.exists(in_gif): raise FileNotFoundError(f"{in_gif} does not exist.") out_mp4 = os.path.abspath(out_mp4) if not out_mp4.endswith(".mp4"): out_mp4 = out_mp4 + ".mp4" if not os.path.exists(os.path.dirname(out_mp4)): os.makedirs(os.path.dirname(out_mp4)) if not is_tool("ffmpeg"): print("ffmpeg is not installed on your computer.") return width, height = Image.open(in_gif).size if width % 2 == 0 and height % 2 == 0: cmd = f"ffmpeg -loglevel error -i {in_gif} -vcodec libx264 -crf 25 -pix_fmt yuv420p {out_mp4}" os.system(cmd) else: width += width % 2 height += height % 2 cmd = f"ffmpeg -loglevel error -i {in_gif} -vf scale={width}:{height} -vcodec libx264 -crf 25 -pix_fmt yuv420p {out_mp4}" os.system(cmd) if not os.path.exists(out_mp4): raise Exception(f"Failed to create mp4 file.") def gif_fading(in_gif, out_gif, duration=1, verbose=True): """Fade in/out the gif. Args: in_gif (str): The input gif file. Can be a directory path or http URL, e.g., "https://i.imgur.com/ZWSZC5z.gif" out_gif (str): The output gif file. duration (float, optional): The duration of the fading. Defaults to 1. verbose (bool, optional): Whether to print the progress. Defaults to True. Raises: FileNotFoundError: Raise exception when the input gif does not exist. Exception: Raise exception when ffmpeg is not installed. """ import glob import tempfile current_dir = os.getcwd() if isinstance(in_gif, str) and in_gif.startswith("http"): ext = os.path.splitext(in_gif)[1] file_path = temp_file_path(ext) download_from_url(in_gif, file_path, verbose=verbose) in_gif = file_path in_gif = os.path.abspath(in_gif) if not in_gif.endswith(".gif"): raise Exception("in_gif must be a gif file.") if " " in in_gif: raise Exception("The filename cannot contain spaces.") out_gif = os.path.abspath(out_gif) if not os.path.exists(os.path.dirname(out_gif)): os.makedirs(os.path.dirname(out_gif)) if not os.path.exists(in_gif): raise FileNotFoundError(f"{in_gif} does not exist.") basename = os.path.basename(in_gif).replace(".gif", "") temp_dir = os.path.join(tempfile.gettempdir(), basename) if os.path.exists(temp_dir): shutil.rmtree(temp_dir) gif_to_png(in_gif, temp_dir, verbose=verbose) os.chdir(temp_dir) images = list(glob.glob(os.path.join(temp_dir, "*.png"))) count = len(images) files = [] for i in range(1, count + 1): files.append(f"-loop 1 -t {duration} -i {i}.png") inputs = " ".join(files) filters = [] for i in range(1, count): if i == 1: filters.append( f"\"[1:v][0:v]blend=all_expr='A*(if(gte(T,3),1,T/3))+B*(1-(if(gte(T,3),1,T/3)))'[v0];" ) else: filters.append( f"[{i}:v][{i-1}:v]blend=all_expr='A*(if(gte(T,3),1,T/3))+B*(1-(if(gte(T,3),1,T/3)))'[v{i-1}];" ) last_filter = "" for i in range(count - 1): last_filter += f"[v{i}]" last_filter += f'concat=n={count-1}:v=1:a=0[v]" -map "[v]"' filters.append(last_filter) filters = " ".join(filters) cmd = f"ffmpeg -y -loglevel error {inputs} -filter_complex {filters} {out_gif}" # if fade >= duration: # duration = fade + 1 # files = [] # for i in range(1, count + 1): # files.append(f"-framerate {framerate} -loop 1 -t {duration} -i {i}.png") # inputs = " ".join(files) # filters = [] # for i in range(count): # if i == 0: # filters.append(f'"[0:v]fade=t=out:st=4:d={fade}[v0];') # else: # filters.append( # f"[{i}:v]fade=t=in:st=0:d={fade},fade=t=out:st=4:d={fade}[v{i}];" # ) # last_filter = "" # for i in range(count): # last_filter += f"[v{i}]" # last_filter += f"concat=n={count}:v=1:a=0,split[v0][v1];" # filters.append(last_filter) # palette = f'[v0]palettegen[p];[v1][p]paletteuse[v]" -map "[v]"' # filters.append(palette) # filters = " ".join(filters) # cmd = f"ffmpeg -y {inputs} -filter_complex {filters} {out_gif}" os.system(cmd) try: shutil.rmtree(temp_dir) except Exception as e: print(e) os.chdir(current_dir) def add_text_to_gif( in_gif, out_gif, xy=None, text_sequence=None, font_type="arial.ttf", font_size=20, font_color="#000000", add_progress_bar=True, progress_bar_color="white", progress_bar_height=5, duration=100, loop=0, ): """Adds animated text to a GIF image. Args: in_gif (str): The file path to the input GIF image. out_gif (str): The file path to the output GIF image. xy (tuple, optional): Top left corner of the text. It can be formatted like this: (10, 10) or ('15%', '25%'). Defaults to None. text_sequence (int, str, list, optional): Text to be drawn. It can be an integer number, a string, or a list of strings. Defaults to None. font_type (str, optional): Font type. Defaults to "arial.ttf". font_size (int, optional): Font size. Defaults to 20. font_color (str, optional): Font color. It can be a string (e.g., 'red'), rgb tuple (e.g., (255, 127, 0)), or hex code (e.g., '#ff00ff'). Defaults to '#000000'. add_progress_bar (bool, optional): Whether to add a progress bar at the bottom of the GIF. Defaults to True. progress_bar_color (str, optional): Color for the progress bar. Defaults to 'white'. progress_bar_height (int, optional): Height of the progress bar. Defaults to 5. duration (int, optional): controls how long each frame will be displayed for, in milliseconds. It is the inverse of the frame rate. Setting it to 100 milliseconds gives 10 frames per second. You can decrease the duration to give a smoother animation.. Defaults to 100. loop (int, optional): controls how many times the animation repeats. The default, 1, means that the animation will play once and then stop (displaying the last frame). A value of 0 means that the animation will repeat forever. Defaults to 0. """ # import io import warnings import pkg_resources from PIL import Image, ImageDraw, ImageFont, ImageSequence warnings.simplefilter("ignore") pkg_dir = os.path.dirname(pkg_resources.resource_filename("geemap", "geemap.py")) default_font = os.path.join(pkg_dir, "data/fonts/arial.ttf") in_gif = os.path.abspath(in_gif) out_gif = os.path.abspath(out_gif) if not os.path.exists(in_gif): print("The input gif file does not exist.") return if not os.path.exists(os.path.dirname(out_gif)): os.makedirs(os.path.dirname(out_gif)) if font_type == "arial.ttf": font = ImageFont.truetype(default_font, font_size) elif font_type == "alibaba.otf": default_font = os.path.join(pkg_dir, "data/fonts/alibaba.otf") font = ImageFont.truetype(default_font, font_size) else: try: font_list = system_fonts(show_full_path=True) font_names = [os.path.basename(f) for f in font_list] if (font_type in font_list) or (font_type in font_names): font = ImageFont.truetype(font_type, font_size) else: print( "The specified font type could not be found on your system. Using the default font instead." ) font = ImageFont.truetype(default_font, font_size) except Exception as e: print(e) font = ImageFont.truetype(default_font, font_size) color = check_color(font_color) progress_bar_color = check_color(progress_bar_color) try: image = Image.open(in_gif) except Exception as e: print("An error occurred while opening the gif.") print(e) return count = image.n_frames W, H = image.size progress_bar_widths = [i * 1.0 / count * W for i in range(1, count + 1)] progress_bar_shapes = [ [(0, H - progress_bar_height), (x, H)] for x in progress_bar_widths ] if xy is None: # default text location is 5% width and 5% height of the image. xy = (int(0.05 * W), int(0.05 * H)) elif (xy is not None) and (not isinstance(xy, tuple)) and (len(xy) == 2): print("xy must be a tuple, e.g., (10, 10), ('10%', '10%')") return elif all(isinstance(item, int) for item in xy) and (len(xy) == 2): x, y = xy if (x > 0) and (x < W) and (y > 0) and (y < H): pass else: print( f"xy is out of bounds. x must be within [0, {W}], and y must be within [0, {H}]" ) return elif all(isinstance(item, str) for item in xy) and (len(xy) == 2): x, y = xy if ("%" in x) and ("%" in y): try: x = int(float(x.replace("%", "")) / 100.0 * W) y = int(float(y.replace("%", "")) / 100.0 * H) xy = (x, y) except Exception: raise Exception( "The specified xy is invalid. It must be formatted like this ('10%', '10%')" ) else: print( "The specified xy is invalid. It must be formatted like this: (10, 10) or ('10%', '10%')" ) return if text_sequence is None: text = [str(x) for x in range(1, count + 1)] elif isinstance(text_sequence, int): text = [str(x) for x in range(text_sequence, text_sequence + count + 1)] elif isinstance(text_sequence, str): try: text_sequence = int(text_sequence) text = [str(x) for x in range(text_sequence, text_sequence + count + 1)] except Exception: text = [text_sequence] * count elif isinstance(text_sequence, list) and len(text_sequence) != count: print( f"The length of the text sequence must be equal to the number ({count}) of frames in the gif." ) return else: text = [str(x) for x in text_sequence] try: frames = [] # Loop over each frame in the animated image for index, frame in enumerate(ImageSequence.Iterator(image)): # Draw the text on the frame frame = frame.convert("RGB") draw = ImageDraw.Draw(frame) # w, h = draw.textsize(text[index]) draw.text(xy, text[index], font=font, fill=color) if add_progress_bar: draw.rectangle(progress_bar_shapes[index], fill=progress_bar_color) del draw b = io.BytesIO() frame.save(b, format="GIF") frame = Image.open(b) frames.append(frame) # https://www.pythoninformer.com/python-libraries/pillow/creating-animated-gif/ # Save the frames as a new image frames[0].save( out_gif, save_all=True, append_images=frames[1:], duration=duration, loop=loop, optimize=True, ) except Exception as e: print(e) def reduce_gif_size(in_gif, out_gif=None): """Reduces a GIF image using ffmpeg. Args: in_gif (str): The input file path to the GIF image. out_gif (str, optional): The output file path to the GIF image. Defaults to None. """ import ffmpeg import warnings warnings.filterwarnings("ignore") if not is_tool("ffmpeg"): print("ffmpeg is not installed on your computer.") return if not os.path.exists(in_gif): print("The input gif file does not exist.") return if out_gif is None: out_gif = in_gif elif not os.path.exists(os.path.dirname(out_gif)): os.makedirs(os.path.dirname(out_gif)) if in_gif == out_gif: tmp_gif = in_gif.replace(".gif", "_tmp.gif") shutil.copyfile(in_gif, tmp_gif) stream = ffmpeg.input(tmp_gif) stream = ffmpeg.output(stream, in_gif, loglevel="quiet").overwrite_output() ffmpeg.run(stream) os.remove(tmp_gif) else: stream = ffmpeg.input(in_gif) stream = ffmpeg.output(stream, out_gif, loglevel="quiet").overwrite_output() ffmpeg.run(stream) def sentinel1_defaults(): from datetime import date year = date.today().year roi = ee.Geometry.Polygon( [ [ [-115.471773, 35.892718], [-115.471773, 36.409454], [-114.271283, 36.409454], [-114.271283, 35.892718], [-115.471773, 35.892718], ] ], None, False, ) return year, roi def sentinel1_timeseries( roi=None, start_year=2015, end_year=None, start_date="01-01", end_date="12-31", frequency="year", clip=False, band="VV", **kwargs, ): """ Generates a Sentinel 1 ImageCollection, based on mean composites following a steady frequency (f.e. 1 image per month) Adapted from https://code.earthengine.google.com/?scriptPath=Examples:Datasets/COPERNICUS_S1_GRD Args: roi (object, optional): Region of interest to create the timelapse. Defaults to a polygon partially covering Las Vegas and Lake Mead. start_year (int, optional): Starting year for the timelapse. Defaults to 2015. end_year (int, optional): Ending year for the timelapse. Defaults to current year. start_date (str, optional): Starting date (month-day) each year for filtering ImageCollection. Defaults to '01-01'. end_date (str, optional): Ending date (month-day) each year for filtering ImageCollection. Defaults to '12-31'. frequency (str, optional): Frequency of the timelapse. Defaults to 'year'. Can be 'year', 'quarter' or 'month'. band (str): Collection band. Can be one of ['HH','HV','VV','VH']. Defaults to 'VV' which is most commonly available on land. **kwargs: Arguments for sentinel1_filtering(). Returns: object: Returns an ImageCollection of Sentinel 1 images. """ CURRENT_YEAR, ROI_DEFAULT = sentinel1_defaults() roi = roi or ROI_DEFAULT end_year = end_year or CURRENT_YEAR roi = valid_roi(roi) start = f"{start_year}-{start_date}" end = f"{end_year}-{end_date}" dates = date_sequence(start, end, frequency) col = ee.ImageCollection("COPERNICUS/S1_GRD").filterBounds(roi) col = sentinel1_filtering(col, band=band, **kwargs).select(band) n = 1 if frequency == "quarter": n = 3 frequency = "month" def transform(date): # coll, frequency start = date end = ee.Date(date).advance(n, frequency).advance(-1, "day") return ( col.filterDate(start, end) .mean() .set( { "system:time_start": ee.Date(start).millis(), "system:time_end": ee.Date(end).millis(), "system:date": start, } ) ) imgList = dates.map(lambda date: transform(date)) imgColl = ee.ImageCollection.fromImages(imgList) if clip: imgColl = imgColl.map(lambda img: img.clip(roi)) return imgColl import os def random_string(string_length=3): """Generates a random string of fixed length. Args: string_length (int, optional): Fixed length. Defaults to 3. Returns: str: A random string """ import random import string # random.seed(1001) letters = string.ascii_lowercase return "".join(random.choice(letters) for i in range(string_length)) def get_image_collection_thumbnails( ee_object, out_dir, vis_params, dimensions=500, region=None, format="jpg", names=None, verbose=True, timeout=300, proxies=None, ): """Download thumbnails for all images in an ImageCollection. Args: ee_object (object): The ee.ImageCollection instance. out_dir ([str): The output directory to store thumbnails. vis_params (dict): The visualization parameters. dimensions (int, optional):(a number or pair of numbers in format WIDTHxHEIGHT) Maximum dimensions of the thumbnail to render, in pixels. If only one number is passed, it is used as the maximum, and the other dimension is computed by proportional scaling. Defaults to 500. region (object, optional): Geospatial region of the image to render, it may be an ee.Geometry, GeoJSON, or an array of lat/lon points (E,S,W,N). If not set the default is the bounds image. Defaults to None. format (str, optional): Either 'png' or 'jpg'. Default to 'jpg'. names (list, optional): The list of output file names. Defaults to None. verbose (bool, optional): Whether or not to print hints. Defaults to True. timeout (int, optional): The number of seconds after which the request will be terminated. Defaults to 300. proxies (dict, optional): A dictionary of proxy servers to use for the request. Defaults to None. """ if not isinstance(ee_object, ee.ImageCollection): print("The ee_object must be an ee.ImageCollection.") raise TypeError("The ee_object must be an ee.Image.") if format not in ["png", "jpg"]: raise ValueError("The output image format must be png or jpg.") if not os.path.exists(out_dir): os.makedirs(out_dir) try: count = int(ee_object.size().getInfo()) if verbose: print(f"Total number of images: {count}\n") if (names is not None) and (len(names) != count): print("The number of names is not equal to the number of images.") return if names is None: names = ee_object.aggregate_array("system:index").getInfo() images = ee_object.toList(count) for i in range(0, count): image = ee.Image(images.get(i)) name = str(names[i]) ext = os.path.splitext(name)[1][1:] if ext != format: name = name + "." + format out_img = os.path.join(out_dir, name) if verbose: print(f"Downloading {i+1}/{count}: {name} ...") get_image_thumbnail( image, out_img, vis_params, dimensions, region, format, timeout=timeout, proxies=proxies, ) except Exception as e: print(e) def download_ee_video(collection, video_args, out_gif, timeout=300, proxies=None): """Downloads a video thumbnail as a GIF image from Earth Engine. Args: collection (object): An ee.ImageCollection. video_args (object): Parameters for expring the video thumbnail. out_gif (str): File path to the output GIF. timeout (int, optional): The number of seconds the request will be timed out. Defaults to 300. proxies (dict, optional): A dictionary of proxy servers to use. Defaults to None. """ out_gif = os.path.abspath(out_gif) if not out_gif.endswith(".gif"): print("The output file must have an extension of .gif.") return if not os.path.exists(os.path.dirname(out_gif)): os.makedirs(os.path.dirname(out_gif)) if "region" in video_args.keys(): roi = video_args["region"] if not isinstance(roi, ee.Geometry): try: roi = roi.geometry() except Exception as e: print("Could not convert the provided roi to ee.Geometry") print(e) return video_args["region"] = roi if "dimensions" not in video_args: video_args["dimensions"] = 768 try: print("Generating URL...") url = collection.getVideoThumbURL(video_args) print(f"Downloading GIF image from {url}\nPlease wait ...") r = requests.get(url, stream=True, timeout=timeout, proxies=proxies) if r.status_code != 200: print("An error occurred while downloading.") print(r.json()["error"]["message"]) return else: with open(out_gif, "wb") as fd: for chunk in r.iter_content(chunk_size=1024): fd.write(chunk) print(f"The GIF image has been saved to: {out_gif}") except Exception as e: print(e) The provided code snippet includes necessary dependencies for implementing the `sentinel1_timelapse_legacy` function. Write a Python function `def sentinel1_timelapse_legacy( roi=None, out_gif=None, start_year=2015, end_year=None, start_date="01-01", end_date="12-31", vis_params=None, dimensions=768, frames_per_second=5, crs="EPSG:3857", overlay_data=None, overlay_color="black", overlay_width=1, overlay_opacity=1.0, frequency="year", title=None, title_xy=("2%", "90%"), add_text=True, text_xy=("2%", "2%"), text_sequence=None, font_type="arial.ttf", font_size=20, font_color="white", add_progress_bar=True, progress_bar_color="white", progress_bar_height=5, loop=0, mp4=False, fading=False, )` to solve the following problem: Generates a Sentinel-1 timelapse animated GIF or MP4. Args: roi (object, optional): Region of interest to create the timelapse. Defaults to LV & Lake Mead. out_gif (str, optional): File path to the output animated GIF. Defaults to Downloads\s1_ts_*.gif. start_year (int, optional): Starting year for the timelapse. Defaults to 2015. end_year (int, optional): Ending year for the timelapse. Defaults to current year. start_date (str, optional): Starting date (month-day) each year for filtering ImageCollection. Defaults to '01-01'. end_date (str, optional): Ending date (month-day) each year for filtering ImageCollection. Defaults to '12-31'. vis_params (dict, optional): Visualization parameters. Defaults to {'min':-18, 'max': -4}. dimensions (int, optional): a number or pair of numbers (in format 'WIDTHxHEIGHT') Maximum dimensions of the thumbnail to render, in pixels. If only one number is passed, it is used as the maximum, and the other dimension is computed by proportional scaling. Defaults to 768. frames_per_second (int, optional): Animation speed. Defaults to 5. crs (str, optional): Coordinate reference system. Defaults to 'EPSG:3857'. overlay_data (int, str, list, optional): Administrative boundary to be drawn on the timelapse. Defaults to None. overlay_color (str, optional): Color for the overlay data. Can be any color name or hex color code. Defaults to 'black'. overlay_width (int, optional): Line width of the overlay. Defaults to 1. overlay_opacity (float, optional): Opacity of the overlay. Defaults to 1.0. frequency (str, optional): Frequency of the timelapse. Defaults to 'year'. Can be year, quarter or month. title (str, optional): The title of the timelapse. Defaults to None. title_xy (tuple, optional): Lower left corner of the title. It can be formatted like this: (10, 10) or ('15%', '25%'). Defaults to None. add_text (bool, optional): Whether to add animated text to the timelapse. Defaults to True. title_xy (tuple, optional): Lower left corner of the text sequency. It can be formatted like this: (10, 10) or ('15%', '25%'). Defaults to None. text_sequence (int, str, list, optional): Text to be drawn. It can be an integer number, a string, or a list of strings. Defaults to image start dates. font_type (str, optional): Font type. Defaults to "arial.ttf". font_size (int, optional): Font size. Defaults to 20. font_color (str, optional): Font color. It can be a string (e.g., 'red'), rgb tuple (e.g., (255, 127, 0)), or hex code (e.g., '#ff00ff'). Defaults to 'white'. add_progress_bar (bool, optional): Whether to add a progress bar at the bottom of the GIF. Defaults to True. progress_bar_color (str, optional): Color for the progress bar. Defaults to 'white'. progress_bar_height (int, optional): Height of the progress bar. Defaults to 5. loop (int, optional): Controls how many times the animation repeats. The default, 1, means that the animation will play once and then stop (displaying the last frame). A value of 0 means that the animation will repeat forever. Defaults to 0. mp4 (bool, optional): Whether to convert the GIF to MP4. Defaults to False. fading (int | bool, optional): If True, add fading effect to the timelapse. Defaults to False, no fading. To add fading effect, set it to True (1 second fading duration) or to an integer value (fading duration). Returns: str: File path to the output GIF image. Here is the function: def sentinel1_timelapse_legacy( roi=None, out_gif=None, start_year=2015, end_year=None, start_date="01-01", end_date="12-31", vis_params=None, dimensions=768, frames_per_second=5, crs="EPSG:3857", overlay_data=None, overlay_color="black", overlay_width=1, overlay_opacity=1.0, frequency="year", title=None, title_xy=("2%", "90%"), add_text=True, text_xy=("2%", "2%"), text_sequence=None, font_type="arial.ttf", font_size=20, font_color="white", add_progress_bar=True, progress_bar_color="white", progress_bar_height=5, loop=0, mp4=False, fading=False, ): """Generates a Sentinel-1 timelapse animated GIF or MP4. Args: roi (object, optional): Region of interest to create the timelapse. Defaults to LV & Lake Mead. out_gif (str, optional): File path to the output animated GIF. Defaults to Downloads\s1_ts_*.gif. start_year (int, optional): Starting year for the timelapse. Defaults to 2015. end_year (int, optional): Ending year for the timelapse. Defaults to current year. start_date (str, optional): Starting date (month-day) each year for filtering ImageCollection. Defaults to '01-01'. end_date (str, optional): Ending date (month-day) each year for filtering ImageCollection. Defaults to '12-31'. vis_params (dict, optional): Visualization parameters. Defaults to {'min':-18, 'max': -4}. dimensions (int, optional): a number or pair of numbers (in format 'WIDTHxHEIGHT') Maximum dimensions of the thumbnail to render, in pixels. If only one number is passed, it is used as the maximum, and the other dimension is computed by proportional scaling. Defaults to 768. frames_per_second (int, optional): Animation speed. Defaults to 5. crs (str, optional): Coordinate reference system. Defaults to 'EPSG:3857'. overlay_data (int, str, list, optional): Administrative boundary to be drawn on the timelapse. Defaults to None. overlay_color (str, optional): Color for the overlay data. Can be any color name or hex color code. Defaults to 'black'. overlay_width (int, optional): Line width of the overlay. Defaults to 1. overlay_opacity (float, optional): Opacity of the overlay. Defaults to 1.0. frequency (str, optional): Frequency of the timelapse. Defaults to 'year'. Can be year, quarter or month. title (str, optional): The title of the timelapse. Defaults to None. title_xy (tuple, optional): Lower left corner of the title. It can be formatted like this: (10, 10) or ('15%', '25%'). Defaults to None. add_text (bool, optional): Whether to add animated text to the timelapse. Defaults to True. title_xy (tuple, optional): Lower left corner of the text sequency. It can be formatted like this: (10, 10) or ('15%', '25%'). Defaults to None. text_sequence (int, str, list, optional): Text to be drawn. It can be an integer number, a string, or a list of strings. Defaults to image start dates. font_type (str, optional): Font type. Defaults to "arial.ttf". font_size (int, optional): Font size. Defaults to 20. font_color (str, optional): Font color. It can be a string (e.g., 'red'), rgb tuple (e.g., (255, 127, 0)), or hex code (e.g., '#ff00ff'). Defaults to 'white'. add_progress_bar (bool, optional): Whether to add a progress bar at the bottom of the GIF. Defaults to True. progress_bar_color (str, optional): Color for the progress bar. Defaults to 'white'. progress_bar_height (int, optional): Height of the progress bar. Defaults to 5. loop (int, optional): Controls how many times the animation repeats. The default, 1, means that the animation will play once and then stop (displaying the last frame). A value of 0 means that the animation will repeat forever. Defaults to 0. mp4 (bool, optional): Whether to convert the GIF to MP4. Defaults to False. fading (int | bool, optional): If True, add fading effect to the timelapse. Defaults to False, no fading. To add fading effect, set it to True (1 second fading duration) or to an integer value (fading duration). Returns: str: File path to the output GIF image. """ CURRENT_YEAR, ROI_DEFAULT = sentinel1_defaults() roi = roi or ROI_DEFAULT end_year = end_year or CURRENT_YEAR col = sentinel1_timeseries( roi=roi, start_year=start_year, end_year=end_year, start_date=start_date, end_date=end_date, frequency=frequency, clip=True, ) vis_params = vis_params or {"min": -25, "max": 5} if out_gif is None: out_dir = os.path.join(os.path.expanduser("~"), "Downloads") filename = "s1_ts_" + random_string() + ".gif" out_gif = os.path.join(out_dir, filename) elif not out_gif.endswith(".gif"): print("The output file must end with .gif") return else: out_gif = os.path.abspath(out_gif) out_dir = os.path.dirname(out_gif) if not os.path.exists(out_dir): os.makedirs(out_dir) if overlay_data is not None: col = add_overlay( col, overlay_data, overlay_color, overlay_width, overlay_opacity ) if ( isinstance(dimensions, int) and dimensions > 768 or isinstance(dimensions, str) and any(dim > 768 for dim in list(map(int, dimensions.split("x")))) ): count = col.size().getInfo() basename = os.path.basename(out_gif)[:-4] names = [ os.path.join( out_dir, f"{basename}_{str(i+1).zfill(int(len(str(count))))}.jpg" ) for i in range(count) ] get_image_collection_thumbnails( col, out_dir, vis_params=vis_params, dimensions=dimensions, names=names, ) make_gif( names, out_gif, fps=frames_per_second, loop=loop, mp4=False, clean_up=True, ) else: video_args = vis_params.copy() video_args["dimensions"] = dimensions video_args["region"] = roi video_args["framesPerSecond"] = frames_per_second video_args["crs"] = crs video_args["min"] = vis_params["min"] video_args["max"] = vis_params["max"] download_ee_video(col, video_args, out_gif) if os.path.exists(out_gif): if title is not None and isinstance(title, str): add_text_to_gif( out_gif, out_gif, xy=title_xy, text_sequence=title, font_type=font_type, font_size=font_size, font_color=font_color, add_progress_bar=add_progress_bar, progress_bar_color=progress_bar_color, progress_bar_height=progress_bar_height, duration=1000 / frames_per_second, loop=loop, ) if add_text: if text_sequence is None: text_sequence = col.aggregate_array("system:date").getInfo() add_text_to_gif( out_gif, out_gif, xy=text_xy, text_sequence=text_sequence, font_type=font_type, font_size=font_size, font_color=font_color, add_progress_bar=add_progress_bar, progress_bar_color=progress_bar_color, progress_bar_height=progress_bar_height, duration=1000 / frames_per_second, loop=loop, ) if os.path.exists(out_gif): reduce_gif_size(out_gif) if isinstance(fading, bool): fading = int(fading) if fading > 0: gif_fading(out_gif, out_gif, duration=fading, verbose=False) if mp4: out_mp4 = out_gif.replace(".gif", ".mp4") gif_to_mp4(out_gif, out_mp4) return out_gif
Generates a Sentinel-1 timelapse animated GIF or MP4. Args: roi (object, optional): Region of interest to create the timelapse. Defaults to LV & Lake Mead. out_gif (str, optional): File path to the output animated GIF. Defaults to Downloads\s1_ts_*.gif. start_year (int, optional): Starting year for the timelapse. Defaults to 2015. end_year (int, optional): Ending year for the timelapse. Defaults to current year. start_date (str, optional): Starting date (month-day) each year for filtering ImageCollection. Defaults to '01-01'. end_date (str, optional): Ending date (month-day) each year for filtering ImageCollection. Defaults to '12-31'. vis_params (dict, optional): Visualization parameters. Defaults to {'min':-18, 'max': -4}. dimensions (int, optional): a number or pair of numbers (in format 'WIDTHxHEIGHT') Maximum dimensions of the thumbnail to render, in pixels. If only one number is passed, it is used as the maximum, and the other dimension is computed by proportional scaling. Defaults to 768. frames_per_second (int, optional): Animation speed. Defaults to 5. crs (str, optional): Coordinate reference system. Defaults to 'EPSG:3857'. overlay_data (int, str, list, optional): Administrative boundary to be drawn on the timelapse. Defaults to None. overlay_color (str, optional): Color for the overlay data. Can be any color name or hex color code. Defaults to 'black'. overlay_width (int, optional): Line width of the overlay. Defaults to 1. overlay_opacity (float, optional): Opacity of the overlay. Defaults to 1.0. frequency (str, optional): Frequency of the timelapse. Defaults to 'year'. Can be year, quarter or month. title (str, optional): The title of the timelapse. Defaults to None. title_xy (tuple, optional): Lower left corner of the title. It can be formatted like this: (10, 10) or ('15%', '25%'). Defaults to None. add_text (bool, optional): Whether to add animated text to the timelapse. Defaults to True. title_xy (tuple, optional): Lower left corner of the text sequency. It can be formatted like this: (10, 10) or ('15%', '25%'). Defaults to None. text_sequence (int, str, list, optional): Text to be drawn. It can be an integer number, a string, or a list of strings. Defaults to image start dates. font_type (str, optional): Font type. Defaults to "arial.ttf". font_size (int, optional): Font size. Defaults to 20. font_color (str, optional): Font color. It can be a string (e.g., 'red'), rgb tuple (e.g., (255, 127, 0)), or hex code (e.g., '#ff00ff'). Defaults to 'white'. add_progress_bar (bool, optional): Whether to add a progress bar at the bottom of the GIF. Defaults to True. progress_bar_color (str, optional): Color for the progress bar. Defaults to 'white'. progress_bar_height (int, optional): Height of the progress bar. Defaults to 5. loop (int, optional): Controls how many times the animation repeats. The default, 1, means that the animation will play once and then stop (displaying the last frame). A value of 0 means that the animation will repeat forever. Defaults to 0. mp4 (bool, optional): Whether to convert the GIF to MP4. Defaults to False. fading (int | bool, optional): If True, add fading effect to the timelapse. Defaults to False, no fading. To add fading effect, set it to True (1 second fading duration) or to an integer value (fading duration). Returns: str: File path to the output GIF image.
12,185
import datetime import glob import io import os import shutil import ee from .common import * from typing import Union, List def add_overlay( collection: ee.ImageCollection, overlay_data: Union[str, ee.Geometry, ee.FeatureCollection], color: str = "black", width: int = 1, opacity: float = 1.0, region: Union[ee.Geometry, ee.FeatureCollection] = None, ) -> ee.ImageCollection: """Adds an overlay to an image collection. Args: collection (ee.ImageCollection): The image collection to add the overlay to. overlay_data (str | ee.Geometry | ee.FeatureCollection): The overlay data to add to the image collection. It can be an HTTP URL to a GeoJSON file. color (str, optional): The color of the overlay. Defaults to 'black'. width (int, optional): The width of the overlay. Defaults to 1. opacity (float, optional): The opacity of the overlay. Defaults to 1.0. region (ee.Geometry | ee.FeatureCollection, optional): The region of interest to add the overlay to. Defaults to None. Returns: ee.ImageCollection: An ImageCollection with the overlay added. """ # Some common administrative boundaries. public_assets = ["continents", "countries", "us_states", "china"] if not isinstance(collection, ee.ImageCollection): raise Exception("The collection must be an ee.ImageCollection.") if not isinstance(overlay_data, ee.FeatureCollection): if isinstance(overlay_data, str): try: if overlay_data.lower() in public_assets: overlay_data = ee.FeatureCollection( f"users/giswqs/public/{overlay_data.lower()}" ) elif overlay_data.startswith("http") and overlay_data.endswith( ".geojson" ): overlay_data = geojson_to_ee(overlay_data) else: overlay_data = ee.FeatureCollection(overlay_data) except Exception as e: print( "The overlay_data must be a valid ee.FeatureCollection, a valid ee.FeatureCollection asset id, or http url to a geojson file." ) raise Exception(e) elif isinstance(overlay_data, ee.Feature): overlay_data = ee.FeatureCollection([overlay_data]) elif isinstance(overlay_data, ee.Geometry): overlay_data = ee.FeatureCollection([ee.Feature(overlay_data)]) else: raise Exception( "The overlay_data must be a valid ee.FeatureCollection or a valid ee.FeatureCollection asset id." ) try: if region is not None: overlay_data = overlay_data.filterBounds(region) empty = ee.Image().byte() image = empty.paint( **{ "featureCollection": overlay_data, "color": 1, "width": width, } ).visualize(**{"palette": check_color(color), "opacity": opacity}) blend_col = collection.map( lambda img: img.blend(image).set( "system:time_start", img.get("system:time_start") ) ) return blend_col except Exception as e: print("Error in add_overlay:") raise Exception(e) def make_gif( images: Union[List[str], str], out_gif: str, ext: str = "jpg", fps: int = 10, loop: int = 0, mp4: bool = False, clean_up: bool = False, ) -> None: """Creates a gif from a list of images. Args: images (list | str): The list of images or input directory to create the gif from. out_gif (str): File path to the output gif. ext (str, optional): The extension of the images. Defaults to 'jpg'. fps (int, optional): The frames per second of the gif. Defaults to 10. loop (int, optional): The number of times to loop the gif. Defaults to 0. mp4 (bool, optional): Whether to convert the gif to mp4. Defaults to False. """ if isinstance(images, str) and os.path.isdir(images): images = list(glob.glob(os.path.join(images, f"*.{ext}"))) if len(images) == 0: raise ValueError("No images found in the input directory.") elif not isinstance(images, list): raise ValueError("images must be a list or a path to the image directory.") images.sort() frames = [Image.open(image) for image in images] frame_one = frames[0] frame_one.save( out_gif, format="GIF", append_images=frames, save_all=True, duration=int(1000 / fps), loop=loop, ) if mp4: if not is_tool("ffmpeg"): print("ffmpeg is not installed on your computer.") return if os.path.exists(out_gif): out_mp4 = out_gif.replace(".gif", ".mp4") cmd = f"ffmpeg -loglevel error -i {out_gif} -vcodec libx264 -crf 25 -pix_fmt yuv420p {out_mp4}" os.system(cmd) if not os.path.exists(out_mp4): raise Exception(f"Failed to create mp4 file.") if clean_up: for image in images: os.remove(image) def gif_to_mp4(in_gif, out_mp4): """Converts a gif to mp4. Args: in_gif (str): The input gif file. out_mp4 (str): The output mp4 file. """ from PIL import Image if not os.path.exists(in_gif): raise FileNotFoundError(f"{in_gif} does not exist.") out_mp4 = os.path.abspath(out_mp4) if not out_mp4.endswith(".mp4"): out_mp4 = out_mp4 + ".mp4" if not os.path.exists(os.path.dirname(out_mp4)): os.makedirs(os.path.dirname(out_mp4)) if not is_tool("ffmpeg"): print("ffmpeg is not installed on your computer.") return width, height = Image.open(in_gif).size if width % 2 == 0 and height % 2 == 0: cmd = f"ffmpeg -loglevel error -i {in_gif} -vcodec libx264 -crf 25 -pix_fmt yuv420p {out_mp4}" os.system(cmd) else: width += width % 2 height += height % 2 cmd = f"ffmpeg -loglevel error -i {in_gif} -vf scale={width}:{height} -vcodec libx264 -crf 25 -pix_fmt yuv420p {out_mp4}" os.system(cmd) if not os.path.exists(out_mp4): raise Exception(f"Failed to create mp4 file.") def gif_fading(in_gif, out_gif, duration=1, verbose=True): """Fade in/out the gif. Args: in_gif (str): The input gif file. Can be a directory path or http URL, e.g., "https://i.imgur.com/ZWSZC5z.gif" out_gif (str): The output gif file. duration (float, optional): The duration of the fading. Defaults to 1. verbose (bool, optional): Whether to print the progress. Defaults to True. Raises: FileNotFoundError: Raise exception when the input gif does not exist. Exception: Raise exception when ffmpeg is not installed. """ import glob import tempfile current_dir = os.getcwd() if isinstance(in_gif, str) and in_gif.startswith("http"): ext = os.path.splitext(in_gif)[1] file_path = temp_file_path(ext) download_from_url(in_gif, file_path, verbose=verbose) in_gif = file_path in_gif = os.path.abspath(in_gif) if not in_gif.endswith(".gif"): raise Exception("in_gif must be a gif file.") if " " in in_gif: raise Exception("The filename cannot contain spaces.") out_gif = os.path.abspath(out_gif) if not os.path.exists(os.path.dirname(out_gif)): os.makedirs(os.path.dirname(out_gif)) if not os.path.exists(in_gif): raise FileNotFoundError(f"{in_gif} does not exist.") basename = os.path.basename(in_gif).replace(".gif", "") temp_dir = os.path.join(tempfile.gettempdir(), basename) if os.path.exists(temp_dir): shutil.rmtree(temp_dir) gif_to_png(in_gif, temp_dir, verbose=verbose) os.chdir(temp_dir) images = list(glob.glob(os.path.join(temp_dir, "*.png"))) count = len(images) files = [] for i in range(1, count + 1): files.append(f"-loop 1 -t {duration} -i {i}.png") inputs = " ".join(files) filters = [] for i in range(1, count): if i == 1: filters.append( f"\"[1:v][0:v]blend=all_expr='A*(if(gte(T,3),1,T/3))+B*(1-(if(gte(T,3),1,T/3)))'[v0];" ) else: filters.append( f"[{i}:v][{i-1}:v]blend=all_expr='A*(if(gte(T,3),1,T/3))+B*(1-(if(gte(T,3),1,T/3)))'[v{i-1}];" ) last_filter = "" for i in range(count - 1): last_filter += f"[v{i}]" last_filter += f'concat=n={count-1}:v=1:a=0[v]" -map "[v]"' filters.append(last_filter) filters = " ".join(filters) cmd = f"ffmpeg -y -loglevel error {inputs} -filter_complex {filters} {out_gif}" # if fade >= duration: # duration = fade + 1 # files = [] # for i in range(1, count + 1): # files.append(f"-framerate {framerate} -loop 1 -t {duration} -i {i}.png") # inputs = " ".join(files) # filters = [] # for i in range(count): # if i == 0: # filters.append(f'"[0:v]fade=t=out:st=4:d={fade}[v0];') # else: # filters.append( # f"[{i}:v]fade=t=in:st=0:d={fade},fade=t=out:st=4:d={fade}[v{i}];" # ) # last_filter = "" # for i in range(count): # last_filter += f"[v{i}]" # last_filter += f"concat=n={count}:v=1:a=0,split[v0][v1];" # filters.append(last_filter) # palette = f'[v0]palettegen[p];[v1][p]paletteuse[v]" -map "[v]"' # filters.append(palette) # filters = " ".join(filters) # cmd = f"ffmpeg -y {inputs} -filter_complex {filters} {out_gif}" os.system(cmd) try: shutil.rmtree(temp_dir) except Exception as e: print(e) os.chdir(current_dir) def add_text_to_gif( in_gif, out_gif, xy=None, text_sequence=None, font_type="arial.ttf", font_size=20, font_color="#000000", add_progress_bar=True, progress_bar_color="white", progress_bar_height=5, duration=100, loop=0, ): """Adds animated text to a GIF image. Args: in_gif (str): The file path to the input GIF image. out_gif (str): The file path to the output GIF image. xy (tuple, optional): Top left corner of the text. It can be formatted like this: (10, 10) or ('15%', '25%'). Defaults to None. text_sequence (int, str, list, optional): Text to be drawn. It can be an integer number, a string, or a list of strings. Defaults to None. font_type (str, optional): Font type. Defaults to "arial.ttf". font_size (int, optional): Font size. Defaults to 20. font_color (str, optional): Font color. It can be a string (e.g., 'red'), rgb tuple (e.g., (255, 127, 0)), or hex code (e.g., '#ff00ff'). Defaults to '#000000'. add_progress_bar (bool, optional): Whether to add a progress bar at the bottom of the GIF. Defaults to True. progress_bar_color (str, optional): Color for the progress bar. Defaults to 'white'. progress_bar_height (int, optional): Height of the progress bar. Defaults to 5. duration (int, optional): controls how long each frame will be displayed for, in milliseconds. It is the inverse of the frame rate. Setting it to 100 milliseconds gives 10 frames per second. You can decrease the duration to give a smoother animation.. Defaults to 100. loop (int, optional): controls how many times the animation repeats. The default, 1, means that the animation will play once and then stop (displaying the last frame). A value of 0 means that the animation will repeat forever. Defaults to 0. """ # import io import warnings import pkg_resources from PIL import Image, ImageDraw, ImageFont, ImageSequence warnings.simplefilter("ignore") pkg_dir = os.path.dirname(pkg_resources.resource_filename("geemap", "geemap.py")) default_font = os.path.join(pkg_dir, "data/fonts/arial.ttf") in_gif = os.path.abspath(in_gif) out_gif = os.path.abspath(out_gif) if not os.path.exists(in_gif): print("The input gif file does not exist.") return if not os.path.exists(os.path.dirname(out_gif)): os.makedirs(os.path.dirname(out_gif)) if font_type == "arial.ttf": font = ImageFont.truetype(default_font, font_size) elif font_type == "alibaba.otf": default_font = os.path.join(pkg_dir, "data/fonts/alibaba.otf") font = ImageFont.truetype(default_font, font_size) else: try: font_list = system_fonts(show_full_path=True) font_names = [os.path.basename(f) for f in font_list] if (font_type in font_list) or (font_type in font_names): font = ImageFont.truetype(font_type, font_size) else: print( "The specified font type could not be found on your system. Using the default font instead." ) font = ImageFont.truetype(default_font, font_size) except Exception as e: print(e) font = ImageFont.truetype(default_font, font_size) color = check_color(font_color) progress_bar_color = check_color(progress_bar_color) try: image = Image.open(in_gif) except Exception as e: print("An error occurred while opening the gif.") print(e) return count = image.n_frames W, H = image.size progress_bar_widths = [i * 1.0 / count * W for i in range(1, count + 1)] progress_bar_shapes = [ [(0, H - progress_bar_height), (x, H)] for x in progress_bar_widths ] if xy is None: # default text location is 5% width and 5% height of the image. xy = (int(0.05 * W), int(0.05 * H)) elif (xy is not None) and (not isinstance(xy, tuple)) and (len(xy) == 2): print("xy must be a tuple, e.g., (10, 10), ('10%', '10%')") return elif all(isinstance(item, int) for item in xy) and (len(xy) == 2): x, y = xy if (x > 0) and (x < W) and (y > 0) and (y < H): pass else: print( f"xy is out of bounds. x must be within [0, {W}], and y must be within [0, {H}]" ) return elif all(isinstance(item, str) for item in xy) and (len(xy) == 2): x, y = xy if ("%" in x) and ("%" in y): try: x = int(float(x.replace("%", "")) / 100.0 * W) y = int(float(y.replace("%", "")) / 100.0 * H) xy = (x, y) except Exception: raise Exception( "The specified xy is invalid. It must be formatted like this ('10%', '10%')" ) else: print( "The specified xy is invalid. It must be formatted like this: (10, 10) or ('10%', '10%')" ) return if text_sequence is None: text = [str(x) for x in range(1, count + 1)] elif isinstance(text_sequence, int): text = [str(x) for x in range(text_sequence, text_sequence + count + 1)] elif isinstance(text_sequence, str): try: text_sequence = int(text_sequence) text = [str(x) for x in range(text_sequence, text_sequence + count + 1)] except Exception: text = [text_sequence] * count elif isinstance(text_sequence, list) and len(text_sequence) != count: print( f"The length of the text sequence must be equal to the number ({count}) of frames in the gif." ) return else: text = [str(x) for x in text_sequence] try: frames = [] # Loop over each frame in the animated image for index, frame in enumerate(ImageSequence.Iterator(image)): # Draw the text on the frame frame = frame.convert("RGB") draw = ImageDraw.Draw(frame) # w, h = draw.textsize(text[index]) draw.text(xy, text[index], font=font, fill=color) if add_progress_bar: draw.rectangle(progress_bar_shapes[index], fill=progress_bar_color) del draw b = io.BytesIO() frame.save(b, format="GIF") frame = Image.open(b) frames.append(frame) # https://www.pythoninformer.com/python-libraries/pillow/creating-animated-gif/ # Save the frames as a new image frames[0].save( out_gif, save_all=True, append_images=frames[1:], duration=duration, loop=loop, optimize=True, ) except Exception as e: print(e) def reduce_gif_size(in_gif, out_gif=None): """Reduces a GIF image using ffmpeg. Args: in_gif (str): The input file path to the GIF image. out_gif (str, optional): The output file path to the GIF image. Defaults to None. """ import ffmpeg import warnings warnings.filterwarnings("ignore") if not is_tool("ffmpeg"): print("ffmpeg is not installed on your computer.") return if not os.path.exists(in_gif): print("The input gif file does not exist.") return if out_gif is None: out_gif = in_gif elif not os.path.exists(os.path.dirname(out_gif)): os.makedirs(os.path.dirname(out_gif)) if in_gif == out_gif: tmp_gif = in_gif.replace(".gif", "_tmp.gif") shutil.copyfile(in_gif, tmp_gif) stream = ffmpeg.input(tmp_gif) stream = ffmpeg.output(stream, in_gif, loglevel="quiet").overwrite_output() ffmpeg.run(stream) os.remove(tmp_gif) else: stream = ffmpeg.input(in_gif) stream = ffmpeg.output(stream, out_gif, loglevel="quiet").overwrite_output() ffmpeg.run(stream) def sentinel2_timeseries( roi, start_year=2015, end_year=None, start_date="01-01", end_date="12-31", bands=None, mask_cloud=True, cloud_pct=30, frequency="year", reducer="median", drop_empty=True, date_format=None, parallel_scale=1, step=1, ): """Generates an annual Sentinel 2 ImageCollection. This algorithm is adapted from https://gist.github.com/jdbcode/76b9ac49faf51627ebd3ff988e10adbc. A huge thank you to Justin Braaten for sharing his fantastic work. Images include both level 1C and level 2A imagery. Args: roi (object, optional): Region of interest to create the timelapse. Defaults to None. start_year (int, optional): Starting year for the timelapse. Defaults to 2015. end_year (int, optional): Ending year for the timelapse. Defaults to None, which will use the current year. start_date (str, optional): Starting date (month-day) each year for filtering ImageCollection. Defaults to '01-01'. mask_cloud (bool, optional): Whether to mask clouds. Defaults to True. end_date (str, optional): Ending date (month-day) each year for filtering ImageCollection. Defaults to '12-31'. bands (list, optional): The list of bands to use to create the timeseries. It must be a list of strings. Defaults to None. cloud_pct (int, optional): Maximum cloud percentage to include in the timelapse. Defaults to 30. frequency (str, optional): Frequency of the timelapse. Defaults to 'year'. reducer (str, optional): The reducer to use to reduce the collection of images to a single value. It can be one of the following: 'median', 'mean', 'min', 'max', 'variance', 'sum'. Defaults to 'median'. drop_empty (bool, optional): Whether to drop empty images from the timeseries. Defaults to True. date_format (str, optional): Format of the date. Defaults to None. parallel_scale (int, optional): A scaling factor used to limit memory use; using a larger parallel_scale (e.g. 2 or 4) may enable computations that run out of memory with the default. Defaults to 1. step (int, optional): The step size to use when creating the date sequence. Defaults to 1. Returns: object: Returns an ImageCollection containing annual Sentinel 2 images. """ if end_year is None: end_year = datetime.date.today().year def maskS2clouds(image): qa = image.select("QA60") # Bits 10 and 11 are clouds and cirrus, respectively. cloudBitMask = 1 << 10 cirrusBitMask = 1 << 11 # Both flags should be set to zero, indicating clear conditions. mask = qa.bitwiseAnd(cloudBitMask).eq(0).And(qa.bitwiseAnd(cirrusBitMask).eq(0)) return ( image.updateMask(mask) .divide(10000) .set(image.toDictionary(image.propertyNames())) ) start = f"{start_year}-{start_date}" end = f"{end_year}-{end_date}" doy_start = ee.Number.parse(ee.Date(start).format("D")) doy_end = ee.Number.parse(ee.Date(end).format("D")) collection = ( ee.ImageCollection("COPERNICUS/S2_HARMONIZED") .filterDate(start, end) .filter(ee.Filter.calendarRange(doy_start, doy_end, "day_of_year")) .filter(ee.Filter.lt("CLOUDY_PIXEL_PERCENTAGE", cloud_pct)) .filterBounds(roi) ) if mask_cloud: collection = collection.map(maskS2clouds) else: collection = collection.map( lambda img: img.divide(10000).set(img.toDictionary(img.propertyNames())) ) if bands is not None: allowed_bands = { "Blue": "B2", "Green": "B3", "Red": "B4", "Red Edge 1": "B5", "Red Edge 2": "B6", "Red Edge 3": "B7", "NIR": "B8", "Red Edge 4": "B8A", "SWIR1": "B11", "SWIR2": "B12", "QA60": "QA60", } for index, band in enumerate(bands): if band in allowed_bands: bands[index] = allowed_bands[band] collection = collection.select(bands) ts = create_timeseries( collection, start, end, roi, bands, frequency, reducer, drop_empty, date_format, parallel_scale, step, ) return ts import datetime import os import ee def random_string(string_length=3): """Generates a random string of fixed length. Args: string_length (int, optional): Fixed length. Defaults to 3. Returns: str: A random string """ import random import string # random.seed(1001) letters = string.ascii_lowercase return "".join(random.choice(letters) for i in range(string_length)) def get_image_collection_thumbnails( ee_object, out_dir, vis_params, dimensions=500, region=None, format="jpg", names=None, verbose=True, timeout=300, proxies=None, ): """Download thumbnails for all images in an ImageCollection. Args: ee_object (object): The ee.ImageCollection instance. out_dir ([str): The output directory to store thumbnails. vis_params (dict): The visualization parameters. dimensions (int, optional):(a number or pair of numbers in format WIDTHxHEIGHT) Maximum dimensions of the thumbnail to render, in pixels. If only one number is passed, it is used as the maximum, and the other dimension is computed by proportional scaling. Defaults to 500. region (object, optional): Geospatial region of the image to render, it may be an ee.Geometry, GeoJSON, or an array of lat/lon points (E,S,W,N). If not set the default is the bounds image. Defaults to None. format (str, optional): Either 'png' or 'jpg'. Default to 'jpg'. names (list, optional): The list of output file names. Defaults to None. verbose (bool, optional): Whether or not to print hints. Defaults to True. timeout (int, optional): The number of seconds after which the request will be terminated. Defaults to 300. proxies (dict, optional): A dictionary of proxy servers to use for the request. Defaults to None. """ if not isinstance(ee_object, ee.ImageCollection): print("The ee_object must be an ee.ImageCollection.") raise TypeError("The ee_object must be an ee.Image.") if format not in ["png", "jpg"]: raise ValueError("The output image format must be png or jpg.") if not os.path.exists(out_dir): os.makedirs(out_dir) try: count = int(ee_object.size().getInfo()) if verbose: print(f"Total number of images: {count}\n") if (names is not None) and (len(names) != count): print("The number of names is not equal to the number of images.") return if names is None: names = ee_object.aggregate_array("system:index").getInfo() images = ee_object.toList(count) for i in range(0, count): image = ee.Image(images.get(i)) name = str(names[i]) ext = os.path.splitext(name)[1][1:] if ext != format: name = name + "." + format out_img = os.path.join(out_dir, name) if verbose: print(f"Downloading {i+1}/{count}: {name} ...") get_image_thumbnail( image, out_img, vis_params, dimensions, region, format, timeout=timeout, proxies=proxies, ) except Exception as e: print(e) def download_ee_video(collection, video_args, out_gif, timeout=300, proxies=None): """Downloads a video thumbnail as a GIF image from Earth Engine. Args: collection (object): An ee.ImageCollection. video_args (object): Parameters for expring the video thumbnail. out_gif (str): File path to the output GIF. timeout (int, optional): The number of seconds the request will be timed out. Defaults to 300. proxies (dict, optional): A dictionary of proxy servers to use. Defaults to None. """ out_gif = os.path.abspath(out_gif) if not out_gif.endswith(".gif"): print("The output file must have an extension of .gif.") return if not os.path.exists(os.path.dirname(out_gif)): os.makedirs(os.path.dirname(out_gif)) if "region" in video_args.keys(): roi = video_args["region"] if not isinstance(roi, ee.Geometry): try: roi = roi.geometry() except Exception as e: print("Could not convert the provided roi to ee.Geometry") print(e) return video_args["region"] = roi if "dimensions" not in video_args: video_args["dimensions"] = 768 try: print("Generating URL...") url = collection.getVideoThumbURL(video_args) print(f"Downloading GIF image from {url}\nPlease wait ...") r = requests.get(url, stream=True, timeout=timeout, proxies=proxies) if r.status_code != 200: print("An error occurred while downloading.") print(r.json()["error"]["message"]) return else: with open(out_gif, "wb") as fd: for chunk in r.iter_content(chunk_size=1024): fd.write(chunk) print(f"The GIF image has been saved to: {out_gif}") except Exception as e: print(e) The provided code snippet includes necessary dependencies for implementing the `sentinel2_timelapse` function. Write a Python function `def sentinel2_timelapse( roi=None, out_gif=None, start_year=2015, end_year=None, start_date="06-10", end_date="09-20", bands=["NIR", "Red", "Green"], vis_params=None, dimensions=768, frames_per_second=5, crs="EPSG:3857", apply_fmask=True, cloud_pct=30, overlay_data=None, overlay_color="black", overlay_width=1, overlay_opacity=1.0, frequency="year", date_format=None, title=None, title_xy=("2%", "90%"), add_text=True, text_xy=("2%", "2%"), text_sequence=None, font_type="arial.ttf", font_size=20, font_color="white", add_progress_bar=True, progress_bar_color="white", progress_bar_height=5, loop=0, mp4=False, fading=False, step=1, **kwargs, )` to solve the following problem: Generates a Sentinel-2 timelapse GIF image. This function is adapted from https://emaprlab.users.earthengine.app/view/lt-gee-time-series-animator. A huge thank you to Justin Braaten for sharing his fantastic work. Args: roi (object, optional): Region of interest to create the timelapse. Defaults to None. out_gif (str, optional): File path to the output animated GIF. Defaults to None. start_year (int, optional): Starting year for the timelapse. Defaults to 2015. end_year (int, optional): Ending year for the timelapse. Defaults to None, which means the current year. start_date (str, optional): Starting date (month-day) each year for filtering ImageCollection. Defaults to '06-10'. end_date (str, optional): Ending date (month-day) each year for filtering ImageCollection. Defaults to '09-20'. bands (list, optional): Three bands selected from ['Blue', 'Green', 'Red', 'NIR', 'SWIR1', 'SWIR2', 'Red Edge 1', 'Red Edge 2', 'Red Edge 3', 'Red Edge 4']. Defaults to ['NIR', 'Red', 'Green']. vis_params (dict, optional): Visualization parameters. Defaults to None. dimensions (int, optional): a number or pair of numbers (in format 'WIDTHxHEIGHT') Maximum dimensions of the thumbnail to render, in pixels. If only one number is passed, it is used as the maximum, and the other dimension is computed by proportional scaling. Defaults to 768. frames_per_second (int, optional): Animation speed. Defaults to 10. crs (str, optional): Coordinate reference system. Defaults to 'EPSG:3857'. apply_fmask (bool, optional): Whether to apply Fmask (Function of mask) for automated clouds, cloud shadows, snow, and water masking. cloud_pct (int, optional): Maximum percentage of cloud coverage allowed. Defaults to 30. overlay_data (int, str, list, optional): Administrative boundary to be drawn on the timelapse. Defaults to None. overlay_color (str, optional): Color for the overlay data. Can be any color name or hex color code. Defaults to 'black'. overlay_width (int, optional): Line width of the overlay. Defaults to 1. overlay_opacity (float, optional): Opacity of the overlay. Defaults to 1.0. frequency (str, optional): Frequency of the timelapse. Defaults to 'year'. date_format (str, optional): Date format for the timelapse. Defaults to None. title (str, optional): The title of the timelapse. Defaults to None. title_xy (tuple, optional): Lower left corner of the title. It can be formatted like this: (10, 10) or ('15%', '25%'). Defaults to None. add_text (bool, optional): Whether to add animated text to the timelapse. Defaults to True. title_xy (tuple, optional): Lower left corner of the text sequency. It can be formatted like this: (10, 10) or ('15%', '25%'). Defaults to None. text_sequence (int, str, list, optional): Text to be drawn. It can be an integer number, a string, or a list of strings. Defaults to None. font_type (str, optional): Font type. Defaults to "arial.ttf". font_size (int, optional): Font size. Defaults to 20. font_color (str, optional): Font color. It can be a string (e.g., 'red'), rgb tuple (e.g., (255, 127, 0)), or hex code (e.g., '#ff00ff'). Defaults to '#000000'. add_progress_bar (bool, optional): Whether to add a progress bar at the bottom of the GIF. Defaults to True. progress_bar_color (str, optional): Color for the progress bar. Defaults to 'white'. progress_bar_height (int, optional): Height of the progress bar. Defaults to 5. loop (int, optional): Controls how many times the animation repeats. The default, 1, means that the animation will play once and then stop (displaying the last frame). A value of 0 means that the animation will repeat forever. Defaults to 0. mp4 (bool, optional): Whether to convert the GIF to MP4. Defaults to False. fading (int | bool, optional): If True, add fading effect to the timelapse. Defaults to False, no fading. To add fading effect, set it to True (1 second fading duration) or to an integer value (fading duration). step (int, optional): Step size for selecting images. Defaults to 1. kwargs (optional): Additional arguments to pass the geemap.create_timeseries() function. Returns: str: File path to the output GIF image. Here is the function: def sentinel2_timelapse( roi=None, out_gif=None, start_year=2015, end_year=None, start_date="06-10", end_date="09-20", bands=["NIR", "Red", "Green"], vis_params=None, dimensions=768, frames_per_second=5, crs="EPSG:3857", apply_fmask=True, cloud_pct=30, overlay_data=None, overlay_color="black", overlay_width=1, overlay_opacity=1.0, frequency="year", date_format=None, title=None, title_xy=("2%", "90%"), add_text=True, text_xy=("2%", "2%"), text_sequence=None, font_type="arial.ttf", font_size=20, font_color="white", add_progress_bar=True, progress_bar_color="white", progress_bar_height=5, loop=0, mp4=False, fading=False, step=1, **kwargs, ): """Generates a Sentinel-2 timelapse GIF image. This function is adapted from https://emaprlab.users.earthengine.app/view/lt-gee-time-series-animator. A huge thank you to Justin Braaten for sharing his fantastic work. Args: roi (object, optional): Region of interest to create the timelapse. Defaults to None. out_gif (str, optional): File path to the output animated GIF. Defaults to None. start_year (int, optional): Starting year for the timelapse. Defaults to 2015. end_year (int, optional): Ending year for the timelapse. Defaults to None, which means the current year. start_date (str, optional): Starting date (month-day) each year for filtering ImageCollection. Defaults to '06-10'. end_date (str, optional): Ending date (month-day) each year for filtering ImageCollection. Defaults to '09-20'. bands (list, optional): Three bands selected from ['Blue', 'Green', 'Red', 'NIR', 'SWIR1', 'SWIR2', 'Red Edge 1', 'Red Edge 2', 'Red Edge 3', 'Red Edge 4']. Defaults to ['NIR', 'Red', 'Green']. vis_params (dict, optional): Visualization parameters. Defaults to None. dimensions (int, optional): a number or pair of numbers (in format 'WIDTHxHEIGHT') Maximum dimensions of the thumbnail to render, in pixels. If only one number is passed, it is used as the maximum, and the other dimension is computed by proportional scaling. Defaults to 768. frames_per_second (int, optional): Animation speed. Defaults to 10. crs (str, optional): Coordinate reference system. Defaults to 'EPSG:3857'. apply_fmask (bool, optional): Whether to apply Fmask (Function of mask) for automated clouds, cloud shadows, snow, and water masking. cloud_pct (int, optional): Maximum percentage of cloud coverage allowed. Defaults to 30. overlay_data (int, str, list, optional): Administrative boundary to be drawn on the timelapse. Defaults to None. overlay_color (str, optional): Color for the overlay data. Can be any color name or hex color code. Defaults to 'black'. overlay_width (int, optional): Line width of the overlay. Defaults to 1. overlay_opacity (float, optional): Opacity of the overlay. Defaults to 1.0. frequency (str, optional): Frequency of the timelapse. Defaults to 'year'. date_format (str, optional): Date format for the timelapse. Defaults to None. title (str, optional): The title of the timelapse. Defaults to None. title_xy (tuple, optional): Lower left corner of the title. It can be formatted like this: (10, 10) or ('15%', '25%'). Defaults to None. add_text (bool, optional): Whether to add animated text to the timelapse. Defaults to True. title_xy (tuple, optional): Lower left corner of the text sequency. It can be formatted like this: (10, 10) or ('15%', '25%'). Defaults to None. text_sequence (int, str, list, optional): Text to be drawn. It can be an integer number, a string, or a list of strings. Defaults to None. font_type (str, optional): Font type. Defaults to "arial.ttf". font_size (int, optional): Font size. Defaults to 20. font_color (str, optional): Font color. It can be a string (e.g., 'red'), rgb tuple (e.g., (255, 127, 0)), or hex code (e.g., '#ff00ff'). Defaults to '#000000'. add_progress_bar (bool, optional): Whether to add a progress bar at the bottom of the GIF. Defaults to True. progress_bar_color (str, optional): Color for the progress bar. Defaults to 'white'. progress_bar_height (int, optional): Height of the progress bar. Defaults to 5. loop (int, optional): Controls how many times the animation repeats. The default, 1, means that the animation will play once and then stop (displaying the last frame). A value of 0 means that the animation will repeat forever. Defaults to 0. mp4 (bool, optional): Whether to convert the GIF to MP4. Defaults to False. fading (int | bool, optional): If True, add fading effect to the timelapse. Defaults to False, no fading. To add fading effect, set it to True (1 second fading duration) or to an integer value (fading duration). step (int, optional): Step size for selecting images. Defaults to 1. kwargs (optional): Additional arguments to pass the geemap.create_timeseries() function. Returns: str: File path to the output GIF image. """ if end_year is None: end_year = datetime.datetime.now().year if roi is None: roi = ee.Geometry.Polygon( [ [ [-115.471773, 35.892718], [-115.471773, 36.409454], [-114.271283, 36.409454], [-114.271283, 35.892718], [-115.471773, 35.892718], ] ], None, False, ) elif isinstance(roi, ee.Feature) or isinstance(roi, ee.FeatureCollection): roi = roi.geometry() elif isinstance(roi, ee.Geometry): pass else: print("The provided roi is invalid. It must be an ee.Geometry") return if out_gif is None: out_dir = os.path.join(os.path.expanduser("~"), "Downloads") filename = "s2_ts_" + random_string() + ".gif" out_gif = os.path.join(out_dir, filename) elif not out_gif.endswith(".gif"): print("The output file must end with .gif") return else: out_gif = os.path.abspath(out_gif) out_dir = os.path.dirname(out_gif) if not os.path.exists(out_dir): os.makedirs(out_dir) allowed_bands = { "Blue": "B2", "Green": "B3", "Red": "B4", "Red Edge 1": "B5", "Red Edge 2": "B6", "Red Edge 3": "B7", "NIR": "B8", "Red Edge 4": "B8A", "SWIR1": "B11", "SWIR2": "B12", "QA60": "QA60", } if bands is None: bands = ["SWIR1", "NIR", "Red"] for index, band in enumerate(bands): if band in allowed_bands: bands[index] = allowed_bands[band] if len(bands) == 3: pass else: raise Exception( "You can only select 3 bands from the following: {}".format( ", ".join(allowed_bands) ) ) try: if vis_params is None: vis_params = {} vis_params["bands"] = bands vis_params["min"] = 0 vis_params["max"] = 0.4 vis_params["gamma"] = [1, 1, 1] if "reducer" not in kwargs: kwargs["reducer"] = "median" if "drop_empty" not in kwargs: kwargs["drop_empty"] = True if "parallel_scale" not in kwargs: kwargs["parallel_scale"] = 1 kwargs["date_format"] = date_format col = sentinel2_timeseries( roi, start_year, end_year, start_date, end_date, bands, apply_fmask, cloud_pct, frequency, step=step, **kwargs, ) col = col.select(bands).map( lambda img: img.visualize(**vis_params).set( { "system:time_start": img.get("system:time_start"), "system:date": img.get("system:date"), } ) ) if overlay_data is not None: col = add_overlay( col, overlay_data, overlay_color, overlay_width, overlay_opacity ) if ( isinstance(dimensions, int) and dimensions > 768 or isinstance(dimensions, str) and any(dim > 768 for dim in list(map(int, dimensions.split("x")))) ): count = col.size().getInfo() basename = os.path.basename(out_gif)[:-4] names = [ os.path.join( out_dir, f"{basename}_{str(i+1).zfill(int(len(str(count))))}.jpg" ) for i in range(count) ] get_image_collection_thumbnails( col, out_dir, vis_params={ "min": 0, "max": 255, "bands": ["vis-red", "vis-green", "vis-blue"], }, dimensions=dimensions, names=names, ) make_gif( names, out_gif, fps=frames_per_second, loop=loop, mp4=False, clean_up=True, ) else: video_args = vis_params.copy() video_args["dimensions"] = dimensions video_args["region"] = roi video_args["framesPerSecond"] = frames_per_second video_args["crs"] = crs video_args["bands"] = ["vis-red", "vis-green", "vis-blue"] video_args["min"] = 0 video_args["max"] = 255 download_ee_video(col, video_args, out_gif) if os.path.exists(out_gif): if title is not None and isinstance(title, str): add_text_to_gif( out_gif, out_gif, xy=title_xy, text_sequence=title, font_type=font_type, font_size=font_size, font_color=font_color, add_progress_bar=add_progress_bar, progress_bar_color=progress_bar_color, progress_bar_height=progress_bar_height, duration=1000 / frames_per_second, loop=loop, ) if add_text: if text_sequence is None: text_sequence = col.aggregate_array("system:date").getInfo() add_text_to_gif( out_gif, out_gif, xy=text_xy, text_sequence=text_sequence, font_type=font_type, font_size=font_size, font_color=font_color, add_progress_bar=add_progress_bar, progress_bar_color=progress_bar_color, progress_bar_height=progress_bar_height, duration=1000 / frames_per_second, loop=loop, ) if os.path.exists(out_gif): reduce_gif_size(out_gif) if isinstance(fading, bool): fading = int(fading) if fading > 0: gif_fading(out_gif, out_gif, duration=fading, verbose=False) if mp4: out_mp4 = out_gif.replace(".gif", ".mp4") gif_to_mp4(out_gif, out_mp4) return out_gif except Exception as e: print(e)
Generates a Sentinel-2 timelapse GIF image. This function is adapted from https://emaprlab.users.earthengine.app/view/lt-gee-time-series-animator. A huge thank you to Justin Braaten for sharing his fantastic work. Args: roi (object, optional): Region of interest to create the timelapse. Defaults to None. out_gif (str, optional): File path to the output animated GIF. Defaults to None. start_year (int, optional): Starting year for the timelapse. Defaults to 2015. end_year (int, optional): Ending year for the timelapse. Defaults to None, which means the current year. start_date (str, optional): Starting date (month-day) each year for filtering ImageCollection. Defaults to '06-10'. end_date (str, optional): Ending date (month-day) each year for filtering ImageCollection. Defaults to '09-20'. bands (list, optional): Three bands selected from ['Blue', 'Green', 'Red', 'NIR', 'SWIR1', 'SWIR2', 'Red Edge 1', 'Red Edge 2', 'Red Edge 3', 'Red Edge 4']. Defaults to ['NIR', 'Red', 'Green']. vis_params (dict, optional): Visualization parameters. Defaults to None. dimensions (int, optional): a number or pair of numbers (in format 'WIDTHxHEIGHT') Maximum dimensions of the thumbnail to render, in pixels. If only one number is passed, it is used as the maximum, and the other dimension is computed by proportional scaling. Defaults to 768. frames_per_second (int, optional): Animation speed. Defaults to 10. crs (str, optional): Coordinate reference system. Defaults to 'EPSG:3857'. apply_fmask (bool, optional): Whether to apply Fmask (Function of mask) for automated clouds, cloud shadows, snow, and water masking. cloud_pct (int, optional): Maximum percentage of cloud coverage allowed. Defaults to 30. overlay_data (int, str, list, optional): Administrative boundary to be drawn on the timelapse. Defaults to None. overlay_color (str, optional): Color for the overlay data. Can be any color name or hex color code. Defaults to 'black'. overlay_width (int, optional): Line width of the overlay. Defaults to 1. overlay_opacity (float, optional): Opacity of the overlay. Defaults to 1.0. frequency (str, optional): Frequency of the timelapse. Defaults to 'year'. date_format (str, optional): Date format for the timelapse. Defaults to None. title (str, optional): The title of the timelapse. Defaults to None. title_xy (tuple, optional): Lower left corner of the title. It can be formatted like this: (10, 10) or ('15%', '25%'). Defaults to None. add_text (bool, optional): Whether to add animated text to the timelapse. Defaults to True. title_xy (tuple, optional): Lower left corner of the text sequency. It can be formatted like this: (10, 10) or ('15%', '25%'). Defaults to None. text_sequence (int, str, list, optional): Text to be drawn. It can be an integer number, a string, or a list of strings. Defaults to None. font_type (str, optional): Font type. Defaults to "arial.ttf". font_size (int, optional): Font size. Defaults to 20. font_color (str, optional): Font color. It can be a string (e.g., 'red'), rgb tuple (e.g., (255, 127, 0)), or hex code (e.g., '#ff00ff'). Defaults to '#000000'. add_progress_bar (bool, optional): Whether to add a progress bar at the bottom of the GIF. Defaults to True. progress_bar_color (str, optional): Color for the progress bar. Defaults to 'white'. progress_bar_height (int, optional): Height of the progress bar. Defaults to 5. loop (int, optional): Controls how many times the animation repeats. The default, 1, means that the animation will play once and then stop (displaying the last frame). A value of 0 means that the animation will repeat forever. Defaults to 0. mp4 (bool, optional): Whether to convert the GIF to MP4. Defaults to False. fading (int | bool, optional): If True, add fading effect to the timelapse. Defaults to False, no fading. To add fading effect, set it to True (1 second fading duration) or to an integer value (fading duration). step (int, optional): Step size for selecting images. Defaults to 1. kwargs (optional): Additional arguments to pass the geemap.create_timeseries() function. Returns: str: File path to the output GIF image.
12,186
import datetime import glob import io import os import shutil import ee from .common import * from typing import Union, List def add_overlay( collection: ee.ImageCollection, overlay_data: Union[str, ee.Geometry, ee.FeatureCollection], color: str = "black", width: int = 1, opacity: float = 1.0, region: Union[ee.Geometry, ee.FeatureCollection] = None, ) -> ee.ImageCollection: """Adds an overlay to an image collection. Args: collection (ee.ImageCollection): The image collection to add the overlay to. overlay_data (str | ee.Geometry | ee.FeatureCollection): The overlay data to add to the image collection. It can be an HTTP URL to a GeoJSON file. color (str, optional): The color of the overlay. Defaults to 'black'. width (int, optional): The width of the overlay. Defaults to 1. opacity (float, optional): The opacity of the overlay. Defaults to 1.0. region (ee.Geometry | ee.FeatureCollection, optional): The region of interest to add the overlay to. Defaults to None. Returns: ee.ImageCollection: An ImageCollection with the overlay added. """ # Some common administrative boundaries. public_assets = ["continents", "countries", "us_states", "china"] if not isinstance(collection, ee.ImageCollection): raise Exception("The collection must be an ee.ImageCollection.") if not isinstance(overlay_data, ee.FeatureCollection): if isinstance(overlay_data, str): try: if overlay_data.lower() in public_assets: overlay_data = ee.FeatureCollection( f"users/giswqs/public/{overlay_data.lower()}" ) elif overlay_data.startswith("http") and overlay_data.endswith( ".geojson" ): overlay_data = geojson_to_ee(overlay_data) else: overlay_data = ee.FeatureCollection(overlay_data) except Exception as e: print( "The overlay_data must be a valid ee.FeatureCollection, a valid ee.FeatureCollection asset id, or http url to a geojson file." ) raise Exception(e) elif isinstance(overlay_data, ee.Feature): overlay_data = ee.FeatureCollection([overlay_data]) elif isinstance(overlay_data, ee.Geometry): overlay_data = ee.FeatureCollection([ee.Feature(overlay_data)]) else: raise Exception( "The overlay_data must be a valid ee.FeatureCollection or a valid ee.FeatureCollection asset id." ) try: if region is not None: overlay_data = overlay_data.filterBounds(region) empty = ee.Image().byte() image = empty.paint( **{ "featureCollection": overlay_data, "color": 1, "width": width, } ).visualize(**{"palette": check_color(color), "opacity": opacity}) blend_col = collection.map( lambda img: img.blend(image).set( "system:time_start", img.get("system:time_start") ) ) return blend_col except Exception as e: print("Error in add_overlay:") raise Exception(e) def gif_to_mp4(in_gif, out_mp4): """Converts a gif to mp4. Args: in_gif (str): The input gif file. out_mp4 (str): The output mp4 file. """ from PIL import Image if not os.path.exists(in_gif): raise FileNotFoundError(f"{in_gif} does not exist.") out_mp4 = os.path.abspath(out_mp4) if not out_mp4.endswith(".mp4"): out_mp4 = out_mp4 + ".mp4" if not os.path.exists(os.path.dirname(out_mp4)): os.makedirs(os.path.dirname(out_mp4)) if not is_tool("ffmpeg"): print("ffmpeg is not installed on your computer.") return width, height = Image.open(in_gif).size if width % 2 == 0 and height % 2 == 0: cmd = f"ffmpeg -loglevel error -i {in_gif} -vcodec libx264 -crf 25 -pix_fmt yuv420p {out_mp4}" os.system(cmd) else: width += width % 2 height += height % 2 cmd = f"ffmpeg -loglevel error -i {in_gif} -vf scale={width}:{height} -vcodec libx264 -crf 25 -pix_fmt yuv420p {out_mp4}" os.system(cmd) if not os.path.exists(out_mp4): raise Exception(f"Failed to create mp4 file.") def gif_fading(in_gif, out_gif, duration=1, verbose=True): """Fade in/out the gif. Args: in_gif (str): The input gif file. Can be a directory path or http URL, e.g., "https://i.imgur.com/ZWSZC5z.gif" out_gif (str): The output gif file. duration (float, optional): The duration of the fading. Defaults to 1. verbose (bool, optional): Whether to print the progress. Defaults to True. Raises: FileNotFoundError: Raise exception when the input gif does not exist. Exception: Raise exception when ffmpeg is not installed. """ import glob import tempfile current_dir = os.getcwd() if isinstance(in_gif, str) and in_gif.startswith("http"): ext = os.path.splitext(in_gif)[1] file_path = temp_file_path(ext) download_from_url(in_gif, file_path, verbose=verbose) in_gif = file_path in_gif = os.path.abspath(in_gif) if not in_gif.endswith(".gif"): raise Exception("in_gif must be a gif file.") if " " in in_gif: raise Exception("The filename cannot contain spaces.") out_gif = os.path.abspath(out_gif) if not os.path.exists(os.path.dirname(out_gif)): os.makedirs(os.path.dirname(out_gif)) if not os.path.exists(in_gif): raise FileNotFoundError(f"{in_gif} does not exist.") basename = os.path.basename(in_gif).replace(".gif", "") temp_dir = os.path.join(tempfile.gettempdir(), basename) if os.path.exists(temp_dir): shutil.rmtree(temp_dir) gif_to_png(in_gif, temp_dir, verbose=verbose) os.chdir(temp_dir) images = list(glob.glob(os.path.join(temp_dir, "*.png"))) count = len(images) files = [] for i in range(1, count + 1): files.append(f"-loop 1 -t {duration} -i {i}.png") inputs = " ".join(files) filters = [] for i in range(1, count): if i == 1: filters.append( f"\"[1:v][0:v]blend=all_expr='A*(if(gte(T,3),1,T/3))+B*(1-(if(gte(T,3),1,T/3)))'[v0];" ) else: filters.append( f"[{i}:v][{i-1}:v]blend=all_expr='A*(if(gte(T,3),1,T/3))+B*(1-(if(gte(T,3),1,T/3)))'[v{i-1}];" ) last_filter = "" for i in range(count - 1): last_filter += f"[v{i}]" last_filter += f'concat=n={count-1}:v=1:a=0[v]" -map "[v]"' filters.append(last_filter) filters = " ".join(filters) cmd = f"ffmpeg -y -loglevel error {inputs} -filter_complex {filters} {out_gif}" # if fade >= duration: # duration = fade + 1 # files = [] # for i in range(1, count + 1): # files.append(f"-framerate {framerate} -loop 1 -t {duration} -i {i}.png") # inputs = " ".join(files) # filters = [] # for i in range(count): # if i == 0: # filters.append(f'"[0:v]fade=t=out:st=4:d={fade}[v0];') # else: # filters.append( # f"[{i}:v]fade=t=in:st=0:d={fade},fade=t=out:st=4:d={fade}[v{i}];" # ) # last_filter = "" # for i in range(count): # last_filter += f"[v{i}]" # last_filter += f"concat=n={count}:v=1:a=0,split[v0][v1];" # filters.append(last_filter) # palette = f'[v0]palettegen[p];[v1][p]paletteuse[v]" -map "[v]"' # filters.append(palette) # filters = " ".join(filters) # cmd = f"ffmpeg -y {inputs} -filter_complex {filters} {out_gif}" os.system(cmd) try: shutil.rmtree(temp_dir) except Exception as e: print(e) os.chdir(current_dir) def add_text_to_gif( in_gif, out_gif, xy=None, text_sequence=None, font_type="arial.ttf", font_size=20, font_color="#000000", add_progress_bar=True, progress_bar_color="white", progress_bar_height=5, duration=100, loop=0, ): """Adds animated text to a GIF image. Args: in_gif (str): The file path to the input GIF image. out_gif (str): The file path to the output GIF image. xy (tuple, optional): Top left corner of the text. It can be formatted like this: (10, 10) or ('15%', '25%'). Defaults to None. text_sequence (int, str, list, optional): Text to be drawn. It can be an integer number, a string, or a list of strings. Defaults to None. font_type (str, optional): Font type. Defaults to "arial.ttf". font_size (int, optional): Font size. Defaults to 20. font_color (str, optional): Font color. It can be a string (e.g., 'red'), rgb tuple (e.g., (255, 127, 0)), or hex code (e.g., '#ff00ff'). Defaults to '#000000'. add_progress_bar (bool, optional): Whether to add a progress bar at the bottom of the GIF. Defaults to True. progress_bar_color (str, optional): Color for the progress bar. Defaults to 'white'. progress_bar_height (int, optional): Height of the progress bar. Defaults to 5. duration (int, optional): controls how long each frame will be displayed for, in milliseconds. It is the inverse of the frame rate. Setting it to 100 milliseconds gives 10 frames per second. You can decrease the duration to give a smoother animation.. Defaults to 100. loop (int, optional): controls how many times the animation repeats. The default, 1, means that the animation will play once and then stop (displaying the last frame). A value of 0 means that the animation will repeat forever. Defaults to 0. """ # import io import warnings import pkg_resources from PIL import Image, ImageDraw, ImageFont, ImageSequence warnings.simplefilter("ignore") pkg_dir = os.path.dirname(pkg_resources.resource_filename("geemap", "geemap.py")) default_font = os.path.join(pkg_dir, "data/fonts/arial.ttf") in_gif = os.path.abspath(in_gif) out_gif = os.path.abspath(out_gif) if not os.path.exists(in_gif): print("The input gif file does not exist.") return if not os.path.exists(os.path.dirname(out_gif)): os.makedirs(os.path.dirname(out_gif)) if font_type == "arial.ttf": font = ImageFont.truetype(default_font, font_size) elif font_type == "alibaba.otf": default_font = os.path.join(pkg_dir, "data/fonts/alibaba.otf") font = ImageFont.truetype(default_font, font_size) else: try: font_list = system_fonts(show_full_path=True) font_names = [os.path.basename(f) for f in font_list] if (font_type in font_list) or (font_type in font_names): font = ImageFont.truetype(font_type, font_size) else: print( "The specified font type could not be found on your system. Using the default font instead." ) font = ImageFont.truetype(default_font, font_size) except Exception as e: print(e) font = ImageFont.truetype(default_font, font_size) color = check_color(font_color) progress_bar_color = check_color(progress_bar_color) try: image = Image.open(in_gif) except Exception as e: print("An error occurred while opening the gif.") print(e) return count = image.n_frames W, H = image.size progress_bar_widths = [i * 1.0 / count * W for i in range(1, count + 1)] progress_bar_shapes = [ [(0, H - progress_bar_height), (x, H)] for x in progress_bar_widths ] if xy is None: # default text location is 5% width and 5% height of the image. xy = (int(0.05 * W), int(0.05 * H)) elif (xy is not None) and (not isinstance(xy, tuple)) and (len(xy) == 2): print("xy must be a tuple, e.g., (10, 10), ('10%', '10%')") return elif all(isinstance(item, int) for item in xy) and (len(xy) == 2): x, y = xy if (x > 0) and (x < W) and (y > 0) and (y < H): pass else: print( f"xy is out of bounds. x must be within [0, {W}], and y must be within [0, {H}]" ) return elif all(isinstance(item, str) for item in xy) and (len(xy) == 2): x, y = xy if ("%" in x) and ("%" in y): try: x = int(float(x.replace("%", "")) / 100.0 * W) y = int(float(y.replace("%", "")) / 100.0 * H) xy = (x, y) except Exception: raise Exception( "The specified xy is invalid. It must be formatted like this ('10%', '10%')" ) else: print( "The specified xy is invalid. It must be formatted like this: (10, 10) or ('10%', '10%')" ) return if text_sequence is None: text = [str(x) for x in range(1, count + 1)] elif isinstance(text_sequence, int): text = [str(x) for x in range(text_sequence, text_sequence + count + 1)] elif isinstance(text_sequence, str): try: text_sequence = int(text_sequence) text = [str(x) for x in range(text_sequence, text_sequence + count + 1)] except Exception: text = [text_sequence] * count elif isinstance(text_sequence, list) and len(text_sequence) != count: print( f"The length of the text sequence must be equal to the number ({count}) of frames in the gif." ) return else: text = [str(x) for x in text_sequence] try: frames = [] # Loop over each frame in the animated image for index, frame in enumerate(ImageSequence.Iterator(image)): # Draw the text on the frame frame = frame.convert("RGB") draw = ImageDraw.Draw(frame) # w, h = draw.textsize(text[index]) draw.text(xy, text[index], font=font, fill=color) if add_progress_bar: draw.rectangle(progress_bar_shapes[index], fill=progress_bar_color) del draw b = io.BytesIO() frame.save(b, format="GIF") frame = Image.open(b) frames.append(frame) # https://www.pythoninformer.com/python-libraries/pillow/creating-animated-gif/ # Save the frames as a new image frames[0].save( out_gif, save_all=True, append_images=frames[1:], duration=duration, loop=loop, optimize=True, ) except Exception as e: print(e) def reduce_gif_size(in_gif, out_gif=None): """Reduces a GIF image using ffmpeg. Args: in_gif (str): The input file path to the GIF image. out_gif (str, optional): The output file path to the GIF image. Defaults to None. """ import ffmpeg import warnings warnings.filterwarnings("ignore") if not is_tool("ffmpeg"): print("ffmpeg is not installed on your computer.") return if not os.path.exists(in_gif): print("The input gif file does not exist.") return if out_gif is None: out_gif = in_gif elif not os.path.exists(os.path.dirname(out_gif)): os.makedirs(os.path.dirname(out_gif)) if in_gif == out_gif: tmp_gif = in_gif.replace(".gif", "_tmp.gif") shutil.copyfile(in_gif, tmp_gif) stream = ffmpeg.input(tmp_gif) stream = ffmpeg.output(stream, in_gif, loglevel="quiet").overwrite_output() ffmpeg.run(stream) os.remove(tmp_gif) else: stream = ffmpeg.input(in_gif) stream = ffmpeg.output(stream, out_gif, loglevel="quiet").overwrite_output() ffmpeg.run(stream) def goes_timeseries( start_date="2021-10-24T14:00:00", end_date="2021-10-25T01:00:00", data="GOES-17", scan="full_disk", region=None, show_night=[False, "a_mode"], ): """Create a time series of GOES data. The code is adapted from Justin Braaten's code: https://code.earthengine.google.com/57245f2d3d04233765c42fb5ef19c1f4. Credits to Justin Braaten. See also https://jstnbraaten.medium.com/goes-in-earth-engine-53fbc8783c16 Args: start_date (str, optional): The start date of the time series. Defaults to "2021-10-24T14:00:00". end_date (str, optional): The end date of the time series. Defaults to "2021-10-25T01:00:00". data (str, optional): The GOES satellite data to use. Defaults to "GOES-17". scan (str, optional): The GOES scan to use. Defaults to "full_disk". region (ee.Geometry, optional): The region of interest. Defaults to None. show_night (list, optional): Show the clouds at night through [True, "a_mode"] o [True, "b_mode"]. Defaults to [False, "a_mode"] Raises: ValueError: The data must be either GOES-16 or GOES-17. ValueError: The scan must be either full_disk, conus, or mesoscale. Returns: ee.ImageCollection: GOES timeseries. """ if data not in ["GOES-16", "GOES-17"]: raise ValueError("The data must be either GOES-16 or GOES-17.") if scan.lower() not in ["full_disk", "conus", "mesoscale"]: raise ValueError("The scan must be either full_disk, conus, or mesoscale.") scan_types = { "full_disk": "MCMIPF", "conus": "MCMIPC", "mesoscale": "MCMIPM", } col = ee.ImageCollection(f"NOAA/GOES/{data[-2:]}/{scan_types[scan.lower()]}") if region is None: region = ee.Geometry.Polygon( [ [ [-159.5954379282731, 60.40883060191719], [-159.5954379282731, 24.517881970830725], [-114.2438754282731, 24.517881970830725], [-114.2438754282731, 60.40883060191719], ] ], None, False, ) # Applies scaling factors. def applyScaleAndOffset(img): def getFactorImg(factorNames): factorList = img.toDictionary().select(factorNames).values() return ee.Image.constant(factorList) scaleImg = getFactorImg(["CMI_C.._scale"]) offsetImg = getFactorImg(["CMI_C.._offset"]) scaled = img.select("CMI_C..").multiply(scaleImg).add(offsetImg) return img.addBands(**{"srcImg": scaled, "overwrite": True}) # Adds a synthetic green band. def addGreenBand(img): green = img.expression( "CMI_GREEN = 0.45 * red + 0.10 * nir + 0.45 * blue", { "blue": img.select("CMI_C01"), "red": img.select("CMI_C02"), "nir": img.select("CMI_C03"), }, ) return img.addBands(green) # Show at clouds at night (a-mode) def showNighta(img): # Make normalized infrared IR_n = img.select("CMI_C13").unitScale(ee.Number(90), ee.Number(313)) IR_n = IR_n.expression( "ir_p = (1 -IR_n)/1.4", { "IR_n": IR_n.select("CMI_C13"), }, ) # Add infrared to rgb bands R_ir = img.select("CMI_C02").max(IR_n) G_ir = img.select("CMI_GREEN").max(IR_n) B_ir = img.select("CMI_C01").max(IR_n) return img.addBands([R_ir, G_ir, B_ir], overwrite=True) # Show at clouds at night (b-mode) def showNightb(img): night = img.select("CMI_C03").unitScale(0, 0.016).subtract(1).multiply(-1) cmi11 = img.select("CMI_C11").unitScale(100, 310) cmi13 = img.select("CMI_C13").unitScale(100, 300) cmi15 = img.select("CMI_C15").unitScale(100, 310) iNight = cmi15.addBands([cmi13, cmi11]).clamp(0, 1).subtract(1).multiply(-1) iRGBNight = iNight.visualize(**{"min": 0, "max": 1, "gamma": 1.4}).updateMask( night ) iRGB = img.visualize( **{ "bands": ["CMI_C02", "CMI_C03", "CMI_C01"], "min": 0.15, "max": 1, "gamma": 1.4, } ) return iRGB.blend(iRGBNight).set( "system:time_start", img.get("system:time_start") ) # Scales select bands for visualization. def scaleForVis(img): return ( img.select(["CMI_C01", "CMI_GREEN", "CMI_C02", "CMI_C03", "CMI_C05"]) .resample("bicubic") .log10() .interpolate([-1.6, 0.176], [0, 1], "clamp") .unmask(0) .set("system:time_start", img.get("system:time_start")) ) # Wraps previous functions. def processForVis(img): if show_night[0]: if show_night[1] == "a_mode": return scaleForVis(showNighta(addGreenBand(applyScaleAndOffset(img)))) else: return showNightb(applyScaleAndOffset(img)) else: return scaleForVis(addGreenBand(applyScaleAndOffset(img))) return col.filterDate(start_date, end_date).filterBounds(region).map(processForVis) import os import ee def random_string(string_length=3): """Generates a random string of fixed length. Args: string_length (int, optional): Fixed length. Defaults to 3. Returns: str: A random string """ import random import string # random.seed(1001) letters = string.ascii_lowercase return "".join(random.choice(letters) for i in range(string_length)) def download_ee_video(collection, video_args, out_gif, timeout=300, proxies=None): """Downloads a video thumbnail as a GIF image from Earth Engine. Args: collection (object): An ee.ImageCollection. video_args (object): Parameters for expring the video thumbnail. out_gif (str): File path to the output GIF. timeout (int, optional): The number of seconds the request will be timed out. Defaults to 300. proxies (dict, optional): A dictionary of proxy servers to use. Defaults to None. """ out_gif = os.path.abspath(out_gif) if not out_gif.endswith(".gif"): print("The output file must have an extension of .gif.") return if not os.path.exists(os.path.dirname(out_gif)): os.makedirs(os.path.dirname(out_gif)) if "region" in video_args.keys(): roi = video_args["region"] if not isinstance(roi, ee.Geometry): try: roi = roi.geometry() except Exception as e: print("Could not convert the provided roi to ee.Geometry") print(e) return video_args["region"] = roi if "dimensions" not in video_args: video_args["dimensions"] = 768 try: print("Generating URL...") url = collection.getVideoThumbURL(video_args) print(f"Downloading GIF image from {url}\nPlease wait ...") r = requests.get(url, stream=True, timeout=timeout, proxies=proxies) if r.status_code != 200: print("An error occurred while downloading.") print(r.json()["error"]["message"]) return else: with open(out_gif, "wb") as fd: for chunk in r.iter_content(chunk_size=1024): fd.write(chunk) print(f"The GIF image has been saved to: {out_gif}") except Exception as e: print(e) def image_dates(img_col, date_format="YYYY-MM-dd"): """Get image dates of all images in an ImageCollection. Args: img_col (object): ee.ImageCollection date_format (str, optional): A pattern, as described at http://joda-time.sourceforge.net/apidocs/org/joda/time/format/DateTimeFormat.html; if omitted will use ISO standard date formatting. Defaults to 'YYYY-MM-dd'. Returns: object: ee.List """ dates = img_col.aggregate_array("system:time_start") new_dates = dates.map(lambda d: ee.Date(d).format(date_format)) return new_dates The provided code snippet includes necessary dependencies for implementing the `goes_timelapse` function. Write a Python function `def goes_timelapse( roi=None, out_gif=None, start_date="2021-10-24T14:00:00", end_date="2021-10-25T01:00:00", data="GOES-17", scan="full_disk", bands=["CMI_C02", "CMI_GREEN", "CMI_C01"], dimensions=768, framesPerSecond=10, date_format="YYYY-MM-dd HH:mm", xy=("3%", "3%"), text_sequence=None, font_type="arial.ttf", font_size=20, font_color="#ffffff", add_progress_bar=True, progress_bar_color="white", progress_bar_height=5, loop=0, crs=None, overlay_data=None, overlay_color="black", overlay_width=1, overlay_opacity=1.0, mp4=False, fading=False, **kwargs, )` to solve the following problem: Create a timelapse of GOES data. The code is adapted from Justin Braaten's code: https://code.earthengine.google.com/57245f2d3d04233765c42fb5ef19c1f4. Credits to Justin Braaten. See also https://jstnbraaten.medium.com/goes-in-earth-engine-53fbc8783c16 Args: roi (ee.Geometry, optional): The region of interest. Defaults to None. out_gif (str): The file path to save the gif. start_date (str, optional): The start date of the time series. Defaults to "2021-10-24T14:00:00". end_date (str, optional): The end date of the time series. Defaults to "2021-10-25T01:00:00". data (str, optional): The GOES satellite data to use. Defaults to "GOES-17". scan (str, optional): The GOES scan to use. Defaults to "full_disk". bands (list, optional): The bands to visualize. Defaults to ["CMI_C02", "CMI_GREEN", "CMI_C01"]. dimensions (int, optional): a number or pair of numbers (in format 'WIDTHxHEIGHT') Maximum dimensions of the thumbnail to render, in pixels. If only one number is passed, it is used as the maximum, and the other dimension is computed by proportional scaling. Defaults to 768. frames_per_second (int, optional): Animation speed. Defaults to 10. date_format (str, optional): The date format to use. Defaults to "YYYY-MM-dd HH:mm". xy (tuple, optional): Top left corner of the text. It can be formatted like this: (10, 10) or ('15%', '25%'). Defaults to None. text_sequence (int, str, list, optional): Text to be drawn. It can be an integer number, a string, or a list of strings. Defaults to None. font_type (str, optional): Font type. Defaults to "arial.ttf". font_size (int, optional): Font size. Defaults to 20. font_color (str, optional): Font color. It can be a string (e.g., 'red'), rgb tuple (e.g., (255, 127, 0)), or hex code (e.g., '#ff00ff'). Defaults to '#000000'. add_progress_bar (bool, optional): Whether to add a progress bar at the bottom of the GIF. Defaults to True. progress_bar_color (str, optional): Color for the progress bar. Defaults to 'white'. progress_bar_height (int, optional): Height of the progress bar. Defaults to 5. loop (int, optional): controls how many times the animation repeats. The default, 1, means that the animation will play once and then stop (displaying the last frame). A value of 0 means that the animation will repeat forever. Defaults to 0. crs (str, optional): The coordinate reference system to use, e.g., "EPSG:3857". Defaults to None. overlay_data (int, str, list, optional): Administrative boundary to be drawn on the timelapse. Defaults to None. overlay_color (str, optional): Color for the overlay data. Can be any color name or hex color code. Defaults to 'black'. overlay_width (int, optional): Line width of the overlay. Defaults to 1. overlay_opacity (float, optional): Opacity of the overlay. Defaults to 1.0. mp4 (bool, optional): Whether to save the animation as an mp4 file. Defaults to False. fading (int | bool, optional): If True, add fading effect to the timelapse. Defaults to False, no fading. To add fading effect, set it to True (1 second fading duration) or to an integer value (fading duration). Raises: Exception: Raise exception. Here is the function: def goes_timelapse( roi=None, out_gif=None, start_date="2021-10-24T14:00:00", end_date="2021-10-25T01:00:00", data="GOES-17", scan="full_disk", bands=["CMI_C02", "CMI_GREEN", "CMI_C01"], dimensions=768, framesPerSecond=10, date_format="YYYY-MM-dd HH:mm", xy=("3%", "3%"), text_sequence=None, font_type="arial.ttf", font_size=20, font_color="#ffffff", add_progress_bar=True, progress_bar_color="white", progress_bar_height=5, loop=0, crs=None, overlay_data=None, overlay_color="black", overlay_width=1, overlay_opacity=1.0, mp4=False, fading=False, **kwargs, ): """Create a timelapse of GOES data. The code is adapted from Justin Braaten's code: https://code.earthengine.google.com/57245f2d3d04233765c42fb5ef19c1f4. Credits to Justin Braaten. See also https://jstnbraaten.medium.com/goes-in-earth-engine-53fbc8783c16 Args: roi (ee.Geometry, optional): The region of interest. Defaults to None. out_gif (str): The file path to save the gif. start_date (str, optional): The start date of the time series. Defaults to "2021-10-24T14:00:00". end_date (str, optional): The end date of the time series. Defaults to "2021-10-25T01:00:00". data (str, optional): The GOES satellite data to use. Defaults to "GOES-17". scan (str, optional): The GOES scan to use. Defaults to "full_disk". bands (list, optional): The bands to visualize. Defaults to ["CMI_C02", "CMI_GREEN", "CMI_C01"]. dimensions (int, optional): a number or pair of numbers (in format 'WIDTHxHEIGHT') Maximum dimensions of the thumbnail to render, in pixels. If only one number is passed, it is used as the maximum, and the other dimension is computed by proportional scaling. Defaults to 768. frames_per_second (int, optional): Animation speed. Defaults to 10. date_format (str, optional): The date format to use. Defaults to "YYYY-MM-dd HH:mm". xy (tuple, optional): Top left corner of the text. It can be formatted like this: (10, 10) or ('15%', '25%'). Defaults to None. text_sequence (int, str, list, optional): Text to be drawn. It can be an integer number, a string, or a list of strings. Defaults to None. font_type (str, optional): Font type. Defaults to "arial.ttf". font_size (int, optional): Font size. Defaults to 20. font_color (str, optional): Font color. It can be a string (e.g., 'red'), rgb tuple (e.g., (255, 127, 0)), or hex code (e.g., '#ff00ff'). Defaults to '#000000'. add_progress_bar (bool, optional): Whether to add a progress bar at the bottom of the GIF. Defaults to True. progress_bar_color (str, optional): Color for the progress bar. Defaults to 'white'. progress_bar_height (int, optional): Height of the progress bar. Defaults to 5. loop (int, optional): controls how many times the animation repeats. The default, 1, means that the animation will play once and then stop (displaying the last frame). A value of 0 means that the animation will repeat forever. Defaults to 0. crs (str, optional): The coordinate reference system to use, e.g., "EPSG:3857". Defaults to None. overlay_data (int, str, list, optional): Administrative boundary to be drawn on the timelapse. Defaults to None. overlay_color (str, optional): Color for the overlay data. Can be any color name or hex color code. Defaults to 'black'. overlay_width (int, optional): Line width of the overlay. Defaults to 1. overlay_opacity (float, optional): Opacity of the overlay. Defaults to 1.0. mp4 (bool, optional): Whether to save the animation as an mp4 file. Defaults to False. fading (int | bool, optional): If True, add fading effect to the timelapse. Defaults to False, no fading. To add fading effect, set it to True (1 second fading duration) or to an integer value (fading duration). Raises: Exception: Raise exception. """ try: if "region" in kwargs: roi = kwargs["region"] if out_gif is None: out_gif = os.path.abspath(f"goes_{random_string(3)}.gif") visParams = { "bands": bands, "min": 0, "max": 0.8, } col = goes_timeseries(start_date, end_date, data, scan, roi) col = col.select(bands).map( lambda img: img.visualize(**visParams).set( { "system:time_start": img.get("system:time_start"), } ) ) if overlay_data is not None: col = add_overlay( col, overlay_data, overlay_color, overlay_width, overlay_opacity ) if roi is None: roi = ee.Geometry.Polygon( [ [ [-159.5954, 60.4088], [-159.5954, 24.5178], [-114.2438, 24.5178], [-114.2438, 60.4088], ] ], None, False, ) if crs is None: crs = col.first().projection() videoParams = { "bands": ["vis-red", "vis-green", "vis-blue"], "min": 0, "max": 255, "dimensions": dimensions, "framesPerSecond": framesPerSecond, "region": roi, "crs": crs, } if text_sequence is None: text_sequence = image_dates(col, date_format=date_format).getInfo() download_ee_video(col, videoParams, out_gif) if os.path.exists(out_gif): add_text_to_gif( out_gif, out_gif, xy, text_sequence, font_type, font_size, font_color, add_progress_bar, progress_bar_color, progress_bar_height, duration=1000 / framesPerSecond, loop=loop, ) try: reduce_gif_size(out_gif) if isinstance(fading, bool): fading = int(fading) if fading > 0: gif_fading(out_gif, out_gif, duration=fading, verbose=False) except Exception as _: pass if mp4: out_mp4 = out_gif.replace(".gif", ".mp4") gif_to_mp4(out_gif, out_mp4) return out_gif except Exception as e: raise Exception(e)
Create a timelapse of GOES data. The code is adapted from Justin Braaten's code: https://code.earthengine.google.com/57245f2d3d04233765c42fb5ef19c1f4. Credits to Justin Braaten. See also https://jstnbraaten.medium.com/goes-in-earth-engine-53fbc8783c16 Args: roi (ee.Geometry, optional): The region of interest. Defaults to None. out_gif (str): The file path to save the gif. start_date (str, optional): The start date of the time series. Defaults to "2021-10-24T14:00:00". end_date (str, optional): The end date of the time series. Defaults to "2021-10-25T01:00:00". data (str, optional): The GOES satellite data to use. Defaults to "GOES-17". scan (str, optional): The GOES scan to use. Defaults to "full_disk". bands (list, optional): The bands to visualize. Defaults to ["CMI_C02", "CMI_GREEN", "CMI_C01"]. dimensions (int, optional): a number or pair of numbers (in format 'WIDTHxHEIGHT') Maximum dimensions of the thumbnail to render, in pixels. If only one number is passed, it is used as the maximum, and the other dimension is computed by proportional scaling. Defaults to 768. frames_per_second (int, optional): Animation speed. Defaults to 10. date_format (str, optional): The date format to use. Defaults to "YYYY-MM-dd HH:mm". xy (tuple, optional): Top left corner of the text. It can be formatted like this: (10, 10) or ('15%', '25%'). Defaults to None. text_sequence (int, str, list, optional): Text to be drawn. It can be an integer number, a string, or a list of strings. Defaults to None. font_type (str, optional): Font type. Defaults to "arial.ttf". font_size (int, optional): Font size. Defaults to 20. font_color (str, optional): Font color. It can be a string (e.g., 'red'), rgb tuple (e.g., (255, 127, 0)), or hex code (e.g., '#ff00ff'). Defaults to '#000000'. add_progress_bar (bool, optional): Whether to add a progress bar at the bottom of the GIF. Defaults to True. progress_bar_color (str, optional): Color for the progress bar. Defaults to 'white'. progress_bar_height (int, optional): Height of the progress bar. Defaults to 5. loop (int, optional): controls how many times the animation repeats. The default, 1, means that the animation will play once and then stop (displaying the last frame). A value of 0 means that the animation will repeat forever. Defaults to 0. crs (str, optional): The coordinate reference system to use, e.g., "EPSG:3857". Defaults to None. overlay_data (int, str, list, optional): Administrative boundary to be drawn on the timelapse. Defaults to None. overlay_color (str, optional): Color for the overlay data. Can be any color name or hex color code. Defaults to 'black'. overlay_width (int, optional): Line width of the overlay. Defaults to 1. overlay_opacity (float, optional): Opacity of the overlay. Defaults to 1.0. mp4 (bool, optional): Whether to save the animation as an mp4 file. Defaults to False. fading (int | bool, optional): If True, add fading effect to the timelapse. Defaults to False, no fading. To add fading effect, set it to True (1 second fading duration) or to an integer value (fading duration). Raises: Exception: Raise exception.
12,187
import datetime import glob import io import os import shutil import ee from .common import * from typing import Union, List def add_overlay( collection: ee.ImageCollection, overlay_data: Union[str, ee.Geometry, ee.FeatureCollection], color: str = "black", width: int = 1, opacity: float = 1.0, region: Union[ee.Geometry, ee.FeatureCollection] = None, ) -> ee.ImageCollection: """Adds an overlay to an image collection. Args: collection (ee.ImageCollection): The image collection to add the overlay to. overlay_data (str | ee.Geometry | ee.FeatureCollection): The overlay data to add to the image collection. It can be an HTTP URL to a GeoJSON file. color (str, optional): The color of the overlay. Defaults to 'black'. width (int, optional): The width of the overlay. Defaults to 1. opacity (float, optional): The opacity of the overlay. Defaults to 1.0. region (ee.Geometry | ee.FeatureCollection, optional): The region of interest to add the overlay to. Defaults to None. Returns: ee.ImageCollection: An ImageCollection with the overlay added. """ # Some common administrative boundaries. public_assets = ["continents", "countries", "us_states", "china"] if not isinstance(collection, ee.ImageCollection): raise Exception("The collection must be an ee.ImageCollection.") if not isinstance(overlay_data, ee.FeatureCollection): if isinstance(overlay_data, str): try: if overlay_data.lower() in public_assets: overlay_data = ee.FeatureCollection( f"users/giswqs/public/{overlay_data.lower()}" ) elif overlay_data.startswith("http") and overlay_data.endswith( ".geojson" ): overlay_data = geojson_to_ee(overlay_data) else: overlay_data = ee.FeatureCollection(overlay_data) except Exception as e: print( "The overlay_data must be a valid ee.FeatureCollection, a valid ee.FeatureCollection asset id, or http url to a geojson file." ) raise Exception(e) elif isinstance(overlay_data, ee.Feature): overlay_data = ee.FeatureCollection([overlay_data]) elif isinstance(overlay_data, ee.Geometry): overlay_data = ee.FeatureCollection([ee.Feature(overlay_data)]) else: raise Exception( "The overlay_data must be a valid ee.FeatureCollection or a valid ee.FeatureCollection asset id." ) try: if region is not None: overlay_data = overlay_data.filterBounds(region) empty = ee.Image().byte() image = empty.paint( **{ "featureCollection": overlay_data, "color": 1, "width": width, } ).visualize(**{"palette": check_color(color), "opacity": opacity}) blend_col = collection.map( lambda img: img.blend(image).set( "system:time_start", img.get("system:time_start") ) ) return blend_col except Exception as e: print("Error in add_overlay:") raise Exception(e) def gif_to_mp4(in_gif, out_mp4): """Converts a gif to mp4. Args: in_gif (str): The input gif file. out_mp4 (str): The output mp4 file. """ from PIL import Image if not os.path.exists(in_gif): raise FileNotFoundError(f"{in_gif} does not exist.") out_mp4 = os.path.abspath(out_mp4) if not out_mp4.endswith(".mp4"): out_mp4 = out_mp4 + ".mp4" if not os.path.exists(os.path.dirname(out_mp4)): os.makedirs(os.path.dirname(out_mp4)) if not is_tool("ffmpeg"): print("ffmpeg is not installed on your computer.") return width, height = Image.open(in_gif).size if width % 2 == 0 and height % 2 == 0: cmd = f"ffmpeg -loglevel error -i {in_gif} -vcodec libx264 -crf 25 -pix_fmt yuv420p {out_mp4}" os.system(cmd) else: width += width % 2 height += height % 2 cmd = f"ffmpeg -loglevel error -i {in_gif} -vf scale={width}:{height} -vcodec libx264 -crf 25 -pix_fmt yuv420p {out_mp4}" os.system(cmd) if not os.path.exists(out_mp4): raise Exception(f"Failed to create mp4 file.") def gif_fading(in_gif, out_gif, duration=1, verbose=True): """Fade in/out the gif. Args: in_gif (str): The input gif file. Can be a directory path or http URL, e.g., "https://i.imgur.com/ZWSZC5z.gif" out_gif (str): The output gif file. duration (float, optional): The duration of the fading. Defaults to 1. verbose (bool, optional): Whether to print the progress. Defaults to True. Raises: FileNotFoundError: Raise exception when the input gif does not exist. Exception: Raise exception when ffmpeg is not installed. """ import glob import tempfile current_dir = os.getcwd() if isinstance(in_gif, str) and in_gif.startswith("http"): ext = os.path.splitext(in_gif)[1] file_path = temp_file_path(ext) download_from_url(in_gif, file_path, verbose=verbose) in_gif = file_path in_gif = os.path.abspath(in_gif) if not in_gif.endswith(".gif"): raise Exception("in_gif must be a gif file.") if " " in in_gif: raise Exception("The filename cannot contain spaces.") out_gif = os.path.abspath(out_gif) if not os.path.exists(os.path.dirname(out_gif)): os.makedirs(os.path.dirname(out_gif)) if not os.path.exists(in_gif): raise FileNotFoundError(f"{in_gif} does not exist.") basename = os.path.basename(in_gif).replace(".gif", "") temp_dir = os.path.join(tempfile.gettempdir(), basename) if os.path.exists(temp_dir): shutil.rmtree(temp_dir) gif_to_png(in_gif, temp_dir, verbose=verbose) os.chdir(temp_dir) images = list(glob.glob(os.path.join(temp_dir, "*.png"))) count = len(images) files = [] for i in range(1, count + 1): files.append(f"-loop 1 -t {duration} -i {i}.png") inputs = " ".join(files) filters = [] for i in range(1, count): if i == 1: filters.append( f"\"[1:v][0:v]blend=all_expr='A*(if(gte(T,3),1,T/3))+B*(1-(if(gte(T,3),1,T/3)))'[v0];" ) else: filters.append( f"[{i}:v][{i-1}:v]blend=all_expr='A*(if(gte(T,3),1,T/3))+B*(1-(if(gte(T,3),1,T/3)))'[v{i-1}];" ) last_filter = "" for i in range(count - 1): last_filter += f"[v{i}]" last_filter += f'concat=n={count-1}:v=1:a=0[v]" -map "[v]"' filters.append(last_filter) filters = " ".join(filters) cmd = f"ffmpeg -y -loglevel error {inputs} -filter_complex {filters} {out_gif}" # if fade >= duration: # duration = fade + 1 # files = [] # for i in range(1, count + 1): # files.append(f"-framerate {framerate} -loop 1 -t {duration} -i {i}.png") # inputs = " ".join(files) # filters = [] # for i in range(count): # if i == 0: # filters.append(f'"[0:v]fade=t=out:st=4:d={fade}[v0];') # else: # filters.append( # f"[{i}:v]fade=t=in:st=0:d={fade},fade=t=out:st=4:d={fade}[v{i}];" # ) # last_filter = "" # for i in range(count): # last_filter += f"[v{i}]" # last_filter += f"concat=n={count}:v=1:a=0,split[v0][v1];" # filters.append(last_filter) # palette = f'[v0]palettegen[p];[v1][p]paletteuse[v]" -map "[v]"' # filters.append(palette) # filters = " ".join(filters) # cmd = f"ffmpeg -y {inputs} -filter_complex {filters} {out_gif}" os.system(cmd) try: shutil.rmtree(temp_dir) except Exception as e: print(e) os.chdir(current_dir) def add_text_to_gif( in_gif, out_gif, xy=None, text_sequence=None, font_type="arial.ttf", font_size=20, font_color="#000000", add_progress_bar=True, progress_bar_color="white", progress_bar_height=5, duration=100, loop=0, ): """Adds animated text to a GIF image. Args: in_gif (str): The file path to the input GIF image. out_gif (str): The file path to the output GIF image. xy (tuple, optional): Top left corner of the text. It can be formatted like this: (10, 10) or ('15%', '25%'). Defaults to None. text_sequence (int, str, list, optional): Text to be drawn. It can be an integer number, a string, or a list of strings. Defaults to None. font_type (str, optional): Font type. Defaults to "arial.ttf". font_size (int, optional): Font size. Defaults to 20. font_color (str, optional): Font color. It can be a string (e.g., 'red'), rgb tuple (e.g., (255, 127, 0)), or hex code (e.g., '#ff00ff'). Defaults to '#000000'. add_progress_bar (bool, optional): Whether to add a progress bar at the bottom of the GIF. Defaults to True. progress_bar_color (str, optional): Color for the progress bar. Defaults to 'white'. progress_bar_height (int, optional): Height of the progress bar. Defaults to 5. duration (int, optional): controls how long each frame will be displayed for, in milliseconds. It is the inverse of the frame rate. Setting it to 100 milliseconds gives 10 frames per second. You can decrease the duration to give a smoother animation.. Defaults to 100. loop (int, optional): controls how many times the animation repeats. The default, 1, means that the animation will play once and then stop (displaying the last frame). A value of 0 means that the animation will repeat forever. Defaults to 0. """ # import io import warnings import pkg_resources from PIL import Image, ImageDraw, ImageFont, ImageSequence warnings.simplefilter("ignore") pkg_dir = os.path.dirname(pkg_resources.resource_filename("geemap", "geemap.py")) default_font = os.path.join(pkg_dir, "data/fonts/arial.ttf") in_gif = os.path.abspath(in_gif) out_gif = os.path.abspath(out_gif) if not os.path.exists(in_gif): print("The input gif file does not exist.") return if not os.path.exists(os.path.dirname(out_gif)): os.makedirs(os.path.dirname(out_gif)) if font_type == "arial.ttf": font = ImageFont.truetype(default_font, font_size) elif font_type == "alibaba.otf": default_font = os.path.join(pkg_dir, "data/fonts/alibaba.otf") font = ImageFont.truetype(default_font, font_size) else: try: font_list = system_fonts(show_full_path=True) font_names = [os.path.basename(f) for f in font_list] if (font_type in font_list) or (font_type in font_names): font = ImageFont.truetype(font_type, font_size) else: print( "The specified font type could not be found on your system. Using the default font instead." ) font = ImageFont.truetype(default_font, font_size) except Exception as e: print(e) font = ImageFont.truetype(default_font, font_size) color = check_color(font_color) progress_bar_color = check_color(progress_bar_color) try: image = Image.open(in_gif) except Exception as e: print("An error occurred while opening the gif.") print(e) return count = image.n_frames W, H = image.size progress_bar_widths = [i * 1.0 / count * W for i in range(1, count + 1)] progress_bar_shapes = [ [(0, H - progress_bar_height), (x, H)] for x in progress_bar_widths ] if xy is None: # default text location is 5% width and 5% height of the image. xy = (int(0.05 * W), int(0.05 * H)) elif (xy is not None) and (not isinstance(xy, tuple)) and (len(xy) == 2): print("xy must be a tuple, e.g., (10, 10), ('10%', '10%')") return elif all(isinstance(item, int) for item in xy) and (len(xy) == 2): x, y = xy if (x > 0) and (x < W) and (y > 0) and (y < H): pass else: print( f"xy is out of bounds. x must be within [0, {W}], and y must be within [0, {H}]" ) return elif all(isinstance(item, str) for item in xy) and (len(xy) == 2): x, y = xy if ("%" in x) and ("%" in y): try: x = int(float(x.replace("%", "")) / 100.0 * W) y = int(float(y.replace("%", "")) / 100.0 * H) xy = (x, y) except Exception: raise Exception( "The specified xy is invalid. It must be formatted like this ('10%', '10%')" ) else: print( "The specified xy is invalid. It must be formatted like this: (10, 10) or ('10%', '10%')" ) return if text_sequence is None: text = [str(x) for x in range(1, count + 1)] elif isinstance(text_sequence, int): text = [str(x) for x in range(text_sequence, text_sequence + count + 1)] elif isinstance(text_sequence, str): try: text_sequence = int(text_sequence) text = [str(x) for x in range(text_sequence, text_sequence + count + 1)] except Exception: text = [text_sequence] * count elif isinstance(text_sequence, list) and len(text_sequence) != count: print( f"The length of the text sequence must be equal to the number ({count}) of frames in the gif." ) return else: text = [str(x) for x in text_sequence] try: frames = [] # Loop over each frame in the animated image for index, frame in enumerate(ImageSequence.Iterator(image)): # Draw the text on the frame frame = frame.convert("RGB") draw = ImageDraw.Draw(frame) # w, h = draw.textsize(text[index]) draw.text(xy, text[index], font=font, fill=color) if add_progress_bar: draw.rectangle(progress_bar_shapes[index], fill=progress_bar_color) del draw b = io.BytesIO() frame.save(b, format="GIF") frame = Image.open(b) frames.append(frame) # https://www.pythoninformer.com/python-libraries/pillow/creating-animated-gif/ # Save the frames as a new image frames[0].save( out_gif, save_all=True, append_images=frames[1:], duration=duration, loop=loop, optimize=True, ) except Exception as e: print(e) def reduce_gif_size(in_gif, out_gif=None): """Reduces a GIF image using ffmpeg. Args: in_gif (str): The input file path to the GIF image. out_gif (str, optional): The output file path to the GIF image. Defaults to None. """ import ffmpeg import warnings warnings.filterwarnings("ignore") if not is_tool("ffmpeg"): print("ffmpeg is not installed on your computer.") return if not os.path.exists(in_gif): print("The input gif file does not exist.") return if out_gif is None: out_gif = in_gif elif not os.path.exists(os.path.dirname(out_gif)): os.makedirs(os.path.dirname(out_gif)) if in_gif == out_gif: tmp_gif = in_gif.replace(".gif", "_tmp.gif") shutil.copyfile(in_gif, tmp_gif) stream = ffmpeg.input(tmp_gif) stream = ffmpeg.output(stream, in_gif, loglevel="quiet").overwrite_output() ffmpeg.run(stream) os.remove(tmp_gif) else: stream = ffmpeg.input(in_gif) stream = ffmpeg.output(stream, out_gif, loglevel="quiet").overwrite_output() ffmpeg.run(stream) def goes_fire_timeseries( start_date="2020-09-05T15:00", end_date="2020-09-06T02:00", data="GOES-17", scan="full_disk", region=None, merge=True, ): """Create a time series of GOES Fire data. The code is adapted from Justin Braaten's code: https://code.earthengine.google.com/8a083a7fb13b95ad4ba148ed9b65475e. Credits to Justin Braaten. See also https://jstnbraaten.medium.com/goes-in-earth-engine-53fbc8783c16 Args: start_date (str, optional): The start date of the time series. Defaults to "2020-09-05T15:00". end_date (str, optional): The end date of the time series. Defaults to "2020-09-06T02:00". data (str, optional): The GOES satellite data to use. Defaults to "GOES-17". scan (str, optional): The GOES scan to use. Defaults to "full_disk". region (ee.Geometry, optional): The region of interest. Defaults to None. merge (bool, optional): Whether to merge the fire timeseries with GOES CMI timeseries. Defaults to True. Raises: ValueError: The data must be either GOES-16 or GOES-17. ValueError: The scan must be either full_disk or conus. Returns: ee.ImageCollection: GOES fire timeseries. """ if data not in ["GOES-16", "GOES-17"]: raise ValueError("The data must be either GOES-16 or GOES-17.") if scan.lower() not in ["full_disk", "conus"]: raise ValueError("The scan must be either full_disk or conus.") scan_types = { "full_disk": "FDCF", "conus": "FDCC", } if region is None: region = ee.Geometry.BBox(-123.17, 36.56, -118.22, 40.03) # Get the fire/hotspot characterization dataset. col = ee.ImageCollection(f"NOAA/GOES/{data[-2:]}/{scan_types[scan.lower()]}") fdcCol = col.filterDate(start_date, end_date) # Identify fire-detected pixels of medium to high confidence. fireMaskCodes = [10, 30, 11, 31, 12, 32, 13, 33, 14, 34, 15, 35] confVals = [1.0, 1.0, 0.9, 0.9, 0.8, 0.8, 0.5, 0.5, 0.3, 0.3, 0.1, 0.1] defaultConfVal = 0 def fdcVis(img): confImg = img.remap(fireMaskCodes, confVals, defaultConfVal, "Mask") return ( confImg.gte(0.3) .selfMask() .set("system:time_start", img.get("system:time_start")) ) fdcVisCol = fdcCol.map(fdcVis) if not merge: return fdcVisCol else: geosVisCol = goes_timeseries(start_date, end_date, data, scan, region) # Join the fire collection to the CMI collection. joinFilter = ee.Filter.equals( **{"leftField": "system:time_start", "rightField": "system:time_start"} ) joinedCol = ee.Join.saveFirst("match").apply(geosVisCol, fdcVisCol, joinFilter) def overlayVis(img): cmi = ee.Image(img).visualize( **{ "bands": ["CMI_C02", "CMI_GREEN", "CMI_C01"], "min": 0, "max": 0.8, "gamma": 0.8, } ) fdc = ee.Image(img.get("match")).visualize( **{"palette": ["ff5349"], "min": 0, "max": 1, "opacity": 0.7} ) return cmi.blend(fdc).set("system:time_start", img.get("system:time_start")) cmiFdcVisCol = ee.ImageCollection(joinedCol.map(overlayVis)) return cmiFdcVisCol import os import ee def random_string(string_length=3): """Generates a random string of fixed length. Args: string_length (int, optional): Fixed length. Defaults to 3. Returns: str: A random string """ import random import string # random.seed(1001) letters = string.ascii_lowercase return "".join(random.choice(letters) for i in range(string_length)) def download_ee_video(collection, video_args, out_gif, timeout=300, proxies=None): """Downloads a video thumbnail as a GIF image from Earth Engine. Args: collection (object): An ee.ImageCollection. video_args (object): Parameters for expring the video thumbnail. out_gif (str): File path to the output GIF. timeout (int, optional): The number of seconds the request will be timed out. Defaults to 300. proxies (dict, optional): A dictionary of proxy servers to use. Defaults to None. """ out_gif = os.path.abspath(out_gif) if not out_gif.endswith(".gif"): print("The output file must have an extension of .gif.") return if not os.path.exists(os.path.dirname(out_gif)): os.makedirs(os.path.dirname(out_gif)) if "region" in video_args.keys(): roi = video_args["region"] if not isinstance(roi, ee.Geometry): try: roi = roi.geometry() except Exception as e: print("Could not convert the provided roi to ee.Geometry") print(e) return video_args["region"] = roi if "dimensions" not in video_args: video_args["dimensions"] = 768 try: print("Generating URL...") url = collection.getVideoThumbURL(video_args) print(f"Downloading GIF image from {url}\nPlease wait ...") r = requests.get(url, stream=True, timeout=timeout, proxies=proxies) if r.status_code != 200: print("An error occurred while downloading.") print(r.json()["error"]["message"]) return else: with open(out_gif, "wb") as fd: for chunk in r.iter_content(chunk_size=1024): fd.write(chunk) print(f"The GIF image has been saved to: {out_gif}") except Exception as e: print(e) def image_dates(img_col, date_format="YYYY-MM-dd"): """Get image dates of all images in an ImageCollection. Args: img_col (object): ee.ImageCollection date_format (str, optional): A pattern, as described at http://joda-time.sourceforge.net/apidocs/org/joda/time/format/DateTimeFormat.html; if omitted will use ISO standard date formatting. Defaults to 'YYYY-MM-dd'. Returns: object: ee.List """ dates = img_col.aggregate_array("system:time_start") new_dates = dates.map(lambda d: ee.Date(d).format(date_format)) return new_dates The provided code snippet includes necessary dependencies for implementing the `goes_fire_timelapse` function. Write a Python function `def goes_fire_timelapse( roi=None, out_gif=None, start_date="2020-09-05T15:00", end_date="2020-09-06T02:00", data="GOES-17", scan="full_disk", dimensions=768, framesPerSecond=10, date_format="YYYY-MM-dd HH:mm", xy=("3%", "3%"), text_sequence=None, font_type="arial.ttf", font_size=20, font_color="#ffffff", add_progress_bar=True, progress_bar_color="white", progress_bar_height=5, loop=0, crs=None, overlay_data=None, overlay_color="#000000", overlay_width=1, overlay_opacity=1.0, mp4=False, fading=False, **kwargs, )` to solve the following problem: Create a timelapse of GOES fire data. The code is adapted from Justin Braaten's code: https://code.earthengine.google.com/8a083a7fb13b95ad4ba148ed9b65475e. Credits to Justin Braaten. See also https://jstnbraaten.medium.com/goes-in-earth-engine-53fbc8783c16 Args: out_gif (str): The file path to save the gif. start_date (str, optional): The start date of the time series. Defaults to "2021-10-24T14:00:00". end_date (str, optional): The end date of the time series. Defaults to "2021-10-25T01:00:00". data (str, optional): The GOES satellite data to use. Defaults to "GOES-17". scan (str, optional): The GOES scan to use. Defaults to "full_disk". region (ee.Geometry, optional): The region of interest. Defaults to None. dimensions (int, optional): a number or pair of numbers (in format 'WIDTHxHEIGHT') Maximum dimensions of the thumbnail to render, in pixels. If only one number is passed, it is used as the maximum, and the other dimension is computed by proportional scaling. Defaults to 768. frames_per_second (int, optional): Animation speed. Defaults to 10. date_format (str, optional): The date format to use. Defaults to "YYYY-MM-dd HH:mm". xy (tuple, optional): Top left corner of the text. It can be formatted like this: (10, 10) or ('15%', '25%'). Defaults to None. text_sequence (int, str, list, optional): Text to be drawn. It can be an integer number, a string, or a list of strings. Defaults to None. font_type (str, optional): Font type. Defaults to "arial.ttf". font_size (int, optional): Font size. Defaults to 20. font_color (str, optional): Font color. It can be a string (e.g., 'red'), rgb tuple (e.g., (255, 127, 0)), or hex code (e.g., '#ff00ff'). Defaults to '#000000'. add_progress_bar (bool, optional): Whether to add a progress bar at the bottom of the GIF. Defaults to True. progress_bar_color (str, optional): Color for the progress bar. Defaults to 'white'. progress_bar_height (int, optional): Height of the progress bar. Defaults to 5. loop (int, optional): controls how many times the animation repeats. The default, 1, means that the animation will play once and then stop (displaying the last frame). A value of 0 means that the animation will repeat forever. Defaults to 0. crs (str, optional): The coordinate reference system to use, e.g., "EPSG:3857". Defaults to None. overlay_data (int, str, list, optional): Administrative boundary to be drawn on the timelapse. Defaults to None. overlay_color (str, optional): Color for the overlay data. Can be any color name or hex color code. Defaults to 'black'. overlay_width (int, optional): Width of the overlay. Defaults to 1. overlay_opacity (float, optional): Opacity of the overlay. Defaults to 1.0. mp4 (bool, optional): Whether to convert the GIF to MP4. Defaults to False. fading (int | bool, optional): If True, add fading effect to the timelapse. Defaults to False, no fading. To add fading effect, set it to True (1 second fading duration) or to an integer value (fading duration). Raises: Exception: Raise exception. Here is the function: def goes_fire_timelapse( roi=None, out_gif=None, start_date="2020-09-05T15:00", end_date="2020-09-06T02:00", data="GOES-17", scan="full_disk", dimensions=768, framesPerSecond=10, date_format="YYYY-MM-dd HH:mm", xy=("3%", "3%"), text_sequence=None, font_type="arial.ttf", font_size=20, font_color="#ffffff", add_progress_bar=True, progress_bar_color="white", progress_bar_height=5, loop=0, crs=None, overlay_data=None, overlay_color="#000000", overlay_width=1, overlay_opacity=1.0, mp4=False, fading=False, **kwargs, ): """Create a timelapse of GOES fire data. The code is adapted from Justin Braaten's code: https://code.earthengine.google.com/8a083a7fb13b95ad4ba148ed9b65475e. Credits to Justin Braaten. See also https://jstnbraaten.medium.com/goes-in-earth-engine-53fbc8783c16 Args: out_gif (str): The file path to save the gif. start_date (str, optional): The start date of the time series. Defaults to "2021-10-24T14:00:00". end_date (str, optional): The end date of the time series. Defaults to "2021-10-25T01:00:00". data (str, optional): The GOES satellite data to use. Defaults to "GOES-17". scan (str, optional): The GOES scan to use. Defaults to "full_disk". region (ee.Geometry, optional): The region of interest. Defaults to None. dimensions (int, optional): a number or pair of numbers (in format 'WIDTHxHEIGHT') Maximum dimensions of the thumbnail to render, in pixels. If only one number is passed, it is used as the maximum, and the other dimension is computed by proportional scaling. Defaults to 768. frames_per_second (int, optional): Animation speed. Defaults to 10. date_format (str, optional): The date format to use. Defaults to "YYYY-MM-dd HH:mm". xy (tuple, optional): Top left corner of the text. It can be formatted like this: (10, 10) or ('15%', '25%'). Defaults to None. text_sequence (int, str, list, optional): Text to be drawn. It can be an integer number, a string, or a list of strings. Defaults to None. font_type (str, optional): Font type. Defaults to "arial.ttf". font_size (int, optional): Font size. Defaults to 20. font_color (str, optional): Font color. It can be a string (e.g., 'red'), rgb tuple (e.g., (255, 127, 0)), or hex code (e.g., '#ff00ff'). Defaults to '#000000'. add_progress_bar (bool, optional): Whether to add a progress bar at the bottom of the GIF. Defaults to True. progress_bar_color (str, optional): Color for the progress bar. Defaults to 'white'. progress_bar_height (int, optional): Height of the progress bar. Defaults to 5. loop (int, optional): controls how many times the animation repeats. The default, 1, means that the animation will play once and then stop (displaying the last frame). A value of 0 means that the animation will repeat forever. Defaults to 0. crs (str, optional): The coordinate reference system to use, e.g., "EPSG:3857". Defaults to None. overlay_data (int, str, list, optional): Administrative boundary to be drawn on the timelapse. Defaults to None. overlay_color (str, optional): Color for the overlay data. Can be any color name or hex color code. Defaults to 'black'. overlay_width (int, optional): Width of the overlay. Defaults to 1. overlay_opacity (float, optional): Opacity of the overlay. Defaults to 1.0. mp4 (bool, optional): Whether to convert the GIF to MP4. Defaults to False. fading (int | bool, optional): If True, add fading effect to the timelapse. Defaults to False, no fading. To add fading effect, set it to True (1 second fading duration) or to an integer value (fading duration). Raises: Exception: Raise exception. """ try: if "region" in kwargs: roi = kwargs["region"] if out_gif is None: out_gif = os.path.abspath(f"goes_fire_{random_string(3)}.gif") if roi is None: roi = ee.Geometry.BBox(-123.17, 36.56, -118.22, 40.03) col = goes_fire_timeseries(start_date, end_date, data, scan, roi) if overlay_data is not None: col = add_overlay( col, overlay_data, overlay_color, overlay_width, overlay_opacity ) # visParams = { # "bands": ["CMI_C02", "CMI_GREEN", "CMI_C01"], # "min": 0, # "max": 0.8, # "dimensions": dimensions, # "framesPerSecond": framesPerSecond, # "region": region, # "crs": col.first().projection(), # } if crs is None: crs = col.first().projection() cmiFdcVisParams = { "dimensions": dimensions, "framesPerSecond": framesPerSecond, "region": roi, "crs": crs, } if text_sequence is None: text_sequence = image_dates(col, date_format=date_format).getInfo() download_ee_video(col, cmiFdcVisParams, out_gif) if os.path.exists(out_gif): add_text_to_gif( out_gif, out_gif, xy, text_sequence, font_type, font_size, font_color, add_progress_bar, progress_bar_color, progress_bar_height, duration=1000 / framesPerSecond, loop=loop, ) try: reduce_gif_size(out_gif) if isinstance(fading, bool): fading = int(fading) if fading > 0: gif_fading(out_gif, out_gif, duration=fading, verbose=False) except Exception as _: pass if mp4: out_mp4 = out_gif.replace(".gif", ".mp4") gif_to_mp4(out_gif, out_mp4) return out_gif except Exception as e: raise Exception(e)
Create a timelapse of GOES fire data. The code is adapted from Justin Braaten's code: https://code.earthengine.google.com/8a083a7fb13b95ad4ba148ed9b65475e. Credits to Justin Braaten. See also https://jstnbraaten.medium.com/goes-in-earth-engine-53fbc8783c16 Args: out_gif (str): The file path to save the gif. start_date (str, optional): The start date of the time series. Defaults to "2021-10-24T14:00:00". end_date (str, optional): The end date of the time series. Defaults to "2021-10-25T01:00:00". data (str, optional): The GOES satellite data to use. Defaults to "GOES-17". scan (str, optional): The GOES scan to use. Defaults to "full_disk". region (ee.Geometry, optional): The region of interest. Defaults to None. dimensions (int, optional): a number or pair of numbers (in format 'WIDTHxHEIGHT') Maximum dimensions of the thumbnail to render, in pixels. If only one number is passed, it is used as the maximum, and the other dimension is computed by proportional scaling. Defaults to 768. frames_per_second (int, optional): Animation speed. Defaults to 10. date_format (str, optional): The date format to use. Defaults to "YYYY-MM-dd HH:mm". xy (tuple, optional): Top left corner of the text. It can be formatted like this: (10, 10) or ('15%', '25%'). Defaults to None. text_sequence (int, str, list, optional): Text to be drawn. It can be an integer number, a string, or a list of strings. Defaults to None. font_type (str, optional): Font type. Defaults to "arial.ttf". font_size (int, optional): Font size. Defaults to 20. font_color (str, optional): Font color. It can be a string (e.g., 'red'), rgb tuple (e.g., (255, 127, 0)), or hex code (e.g., '#ff00ff'). Defaults to '#000000'. add_progress_bar (bool, optional): Whether to add a progress bar at the bottom of the GIF. Defaults to True. progress_bar_color (str, optional): Color for the progress bar. Defaults to 'white'. progress_bar_height (int, optional): Height of the progress bar. Defaults to 5. loop (int, optional): controls how many times the animation repeats. The default, 1, means that the animation will play once and then stop (displaying the last frame). A value of 0 means that the animation will repeat forever. Defaults to 0. crs (str, optional): The coordinate reference system to use, e.g., "EPSG:3857". Defaults to None. overlay_data (int, str, list, optional): Administrative boundary to be drawn on the timelapse. Defaults to None. overlay_color (str, optional): Color for the overlay data. Can be any color name or hex color code. Defaults to 'black'. overlay_width (int, optional): Width of the overlay. Defaults to 1. overlay_opacity (float, optional): Opacity of the overlay. Defaults to 1.0. mp4 (bool, optional): Whether to convert the GIF to MP4. Defaults to False. fading (int | bool, optional): If True, add fading effect to the timelapse. Defaults to False, no fading. To add fading effect, set it to True (1 second fading duration) or to an integer value (fading duration). Raises: Exception: Raise exception.
12,188
import datetime import glob import io import os import shutil import ee from .common import * from typing import Union, List def add_overlay( collection: ee.ImageCollection, overlay_data: Union[str, ee.Geometry, ee.FeatureCollection], color: str = "black", width: int = 1, opacity: float = 1.0, region: Union[ee.Geometry, ee.FeatureCollection] = None, ) -> ee.ImageCollection: """Adds an overlay to an image collection. Args: collection (ee.ImageCollection): The image collection to add the overlay to. overlay_data (str | ee.Geometry | ee.FeatureCollection): The overlay data to add to the image collection. It can be an HTTP URL to a GeoJSON file. color (str, optional): The color of the overlay. Defaults to 'black'. width (int, optional): The width of the overlay. Defaults to 1. opacity (float, optional): The opacity of the overlay. Defaults to 1.0. region (ee.Geometry | ee.FeatureCollection, optional): The region of interest to add the overlay to. Defaults to None. Returns: ee.ImageCollection: An ImageCollection with the overlay added. """ # Some common administrative boundaries. public_assets = ["continents", "countries", "us_states", "china"] if not isinstance(collection, ee.ImageCollection): raise Exception("The collection must be an ee.ImageCollection.") if not isinstance(overlay_data, ee.FeatureCollection): if isinstance(overlay_data, str): try: if overlay_data.lower() in public_assets: overlay_data = ee.FeatureCollection( f"users/giswqs/public/{overlay_data.lower()}" ) elif overlay_data.startswith("http") and overlay_data.endswith( ".geojson" ): overlay_data = geojson_to_ee(overlay_data) else: overlay_data = ee.FeatureCollection(overlay_data) except Exception as e: print( "The overlay_data must be a valid ee.FeatureCollection, a valid ee.FeatureCollection asset id, or http url to a geojson file." ) raise Exception(e) elif isinstance(overlay_data, ee.Feature): overlay_data = ee.FeatureCollection([overlay_data]) elif isinstance(overlay_data, ee.Geometry): overlay_data = ee.FeatureCollection([ee.Feature(overlay_data)]) else: raise Exception( "The overlay_data must be a valid ee.FeatureCollection or a valid ee.FeatureCollection asset id." ) try: if region is not None: overlay_data = overlay_data.filterBounds(region) empty = ee.Image().byte() image = empty.paint( **{ "featureCollection": overlay_data, "color": 1, "width": width, } ).visualize(**{"palette": check_color(color), "opacity": opacity}) blend_col = collection.map( lambda img: img.blend(image).set( "system:time_start", img.get("system:time_start") ) ) return blend_col except Exception as e: print("Error in add_overlay:") raise Exception(e) def gif_to_mp4(in_gif, out_mp4): """Converts a gif to mp4. Args: in_gif (str): The input gif file. out_mp4 (str): The output mp4 file. """ from PIL import Image if not os.path.exists(in_gif): raise FileNotFoundError(f"{in_gif} does not exist.") out_mp4 = os.path.abspath(out_mp4) if not out_mp4.endswith(".mp4"): out_mp4 = out_mp4 + ".mp4" if not os.path.exists(os.path.dirname(out_mp4)): os.makedirs(os.path.dirname(out_mp4)) if not is_tool("ffmpeg"): print("ffmpeg is not installed on your computer.") return width, height = Image.open(in_gif).size if width % 2 == 0 and height % 2 == 0: cmd = f"ffmpeg -loglevel error -i {in_gif} -vcodec libx264 -crf 25 -pix_fmt yuv420p {out_mp4}" os.system(cmd) else: width += width % 2 height += height % 2 cmd = f"ffmpeg -loglevel error -i {in_gif} -vf scale={width}:{height} -vcodec libx264 -crf 25 -pix_fmt yuv420p {out_mp4}" os.system(cmd) if not os.path.exists(out_mp4): raise Exception(f"Failed to create mp4 file.") def gif_fading(in_gif, out_gif, duration=1, verbose=True): """Fade in/out the gif. Args: in_gif (str): The input gif file. Can be a directory path or http URL, e.g., "https://i.imgur.com/ZWSZC5z.gif" out_gif (str): The output gif file. duration (float, optional): The duration of the fading. Defaults to 1. verbose (bool, optional): Whether to print the progress. Defaults to True. Raises: FileNotFoundError: Raise exception when the input gif does not exist. Exception: Raise exception when ffmpeg is not installed. """ import glob import tempfile current_dir = os.getcwd() if isinstance(in_gif, str) and in_gif.startswith("http"): ext = os.path.splitext(in_gif)[1] file_path = temp_file_path(ext) download_from_url(in_gif, file_path, verbose=verbose) in_gif = file_path in_gif = os.path.abspath(in_gif) if not in_gif.endswith(".gif"): raise Exception("in_gif must be a gif file.") if " " in in_gif: raise Exception("The filename cannot contain spaces.") out_gif = os.path.abspath(out_gif) if not os.path.exists(os.path.dirname(out_gif)): os.makedirs(os.path.dirname(out_gif)) if not os.path.exists(in_gif): raise FileNotFoundError(f"{in_gif} does not exist.") basename = os.path.basename(in_gif).replace(".gif", "") temp_dir = os.path.join(tempfile.gettempdir(), basename) if os.path.exists(temp_dir): shutil.rmtree(temp_dir) gif_to_png(in_gif, temp_dir, verbose=verbose) os.chdir(temp_dir) images = list(glob.glob(os.path.join(temp_dir, "*.png"))) count = len(images) files = [] for i in range(1, count + 1): files.append(f"-loop 1 -t {duration} -i {i}.png") inputs = " ".join(files) filters = [] for i in range(1, count): if i == 1: filters.append( f"\"[1:v][0:v]blend=all_expr='A*(if(gte(T,3),1,T/3))+B*(1-(if(gte(T,3),1,T/3)))'[v0];" ) else: filters.append( f"[{i}:v][{i-1}:v]blend=all_expr='A*(if(gte(T,3),1,T/3))+B*(1-(if(gte(T,3),1,T/3)))'[v{i-1}];" ) last_filter = "" for i in range(count - 1): last_filter += f"[v{i}]" last_filter += f'concat=n={count-1}:v=1:a=0[v]" -map "[v]"' filters.append(last_filter) filters = " ".join(filters) cmd = f"ffmpeg -y -loglevel error {inputs} -filter_complex {filters} {out_gif}" # if fade >= duration: # duration = fade + 1 # files = [] # for i in range(1, count + 1): # files.append(f"-framerate {framerate} -loop 1 -t {duration} -i {i}.png") # inputs = " ".join(files) # filters = [] # for i in range(count): # if i == 0: # filters.append(f'"[0:v]fade=t=out:st=4:d={fade}[v0];') # else: # filters.append( # f"[{i}:v]fade=t=in:st=0:d={fade},fade=t=out:st=4:d={fade}[v{i}];" # ) # last_filter = "" # for i in range(count): # last_filter += f"[v{i}]" # last_filter += f"concat=n={count}:v=1:a=0,split[v0][v1];" # filters.append(last_filter) # palette = f'[v0]palettegen[p];[v1][p]paletteuse[v]" -map "[v]"' # filters.append(palette) # filters = " ".join(filters) # cmd = f"ffmpeg -y {inputs} -filter_complex {filters} {out_gif}" os.system(cmd) try: shutil.rmtree(temp_dir) except Exception as e: print(e) os.chdir(current_dir) def add_text_to_gif( in_gif, out_gif, xy=None, text_sequence=None, font_type="arial.ttf", font_size=20, font_color="#000000", add_progress_bar=True, progress_bar_color="white", progress_bar_height=5, duration=100, loop=0, ): """Adds animated text to a GIF image. Args: in_gif (str): The file path to the input GIF image. out_gif (str): The file path to the output GIF image. xy (tuple, optional): Top left corner of the text. It can be formatted like this: (10, 10) or ('15%', '25%'). Defaults to None. text_sequence (int, str, list, optional): Text to be drawn. It can be an integer number, a string, or a list of strings. Defaults to None. font_type (str, optional): Font type. Defaults to "arial.ttf". font_size (int, optional): Font size. Defaults to 20. font_color (str, optional): Font color. It can be a string (e.g., 'red'), rgb tuple (e.g., (255, 127, 0)), or hex code (e.g., '#ff00ff'). Defaults to '#000000'. add_progress_bar (bool, optional): Whether to add a progress bar at the bottom of the GIF. Defaults to True. progress_bar_color (str, optional): Color for the progress bar. Defaults to 'white'. progress_bar_height (int, optional): Height of the progress bar. Defaults to 5. duration (int, optional): controls how long each frame will be displayed for, in milliseconds. It is the inverse of the frame rate. Setting it to 100 milliseconds gives 10 frames per second. You can decrease the duration to give a smoother animation.. Defaults to 100. loop (int, optional): controls how many times the animation repeats. The default, 1, means that the animation will play once and then stop (displaying the last frame). A value of 0 means that the animation will repeat forever. Defaults to 0. """ # import io import warnings import pkg_resources from PIL import Image, ImageDraw, ImageFont, ImageSequence warnings.simplefilter("ignore") pkg_dir = os.path.dirname(pkg_resources.resource_filename("geemap", "geemap.py")) default_font = os.path.join(pkg_dir, "data/fonts/arial.ttf") in_gif = os.path.abspath(in_gif) out_gif = os.path.abspath(out_gif) if not os.path.exists(in_gif): print("The input gif file does not exist.") return if not os.path.exists(os.path.dirname(out_gif)): os.makedirs(os.path.dirname(out_gif)) if font_type == "arial.ttf": font = ImageFont.truetype(default_font, font_size) elif font_type == "alibaba.otf": default_font = os.path.join(pkg_dir, "data/fonts/alibaba.otf") font = ImageFont.truetype(default_font, font_size) else: try: font_list = system_fonts(show_full_path=True) font_names = [os.path.basename(f) for f in font_list] if (font_type in font_list) or (font_type in font_names): font = ImageFont.truetype(font_type, font_size) else: print( "The specified font type could not be found on your system. Using the default font instead." ) font = ImageFont.truetype(default_font, font_size) except Exception as e: print(e) font = ImageFont.truetype(default_font, font_size) color = check_color(font_color) progress_bar_color = check_color(progress_bar_color) try: image = Image.open(in_gif) except Exception as e: print("An error occurred while opening the gif.") print(e) return count = image.n_frames W, H = image.size progress_bar_widths = [i * 1.0 / count * W for i in range(1, count + 1)] progress_bar_shapes = [ [(0, H - progress_bar_height), (x, H)] for x in progress_bar_widths ] if xy is None: # default text location is 5% width and 5% height of the image. xy = (int(0.05 * W), int(0.05 * H)) elif (xy is not None) and (not isinstance(xy, tuple)) and (len(xy) == 2): print("xy must be a tuple, e.g., (10, 10), ('10%', '10%')") return elif all(isinstance(item, int) for item in xy) and (len(xy) == 2): x, y = xy if (x > 0) and (x < W) and (y > 0) and (y < H): pass else: print( f"xy is out of bounds. x must be within [0, {W}], and y must be within [0, {H}]" ) return elif all(isinstance(item, str) for item in xy) and (len(xy) == 2): x, y = xy if ("%" in x) and ("%" in y): try: x = int(float(x.replace("%", "")) / 100.0 * W) y = int(float(y.replace("%", "")) / 100.0 * H) xy = (x, y) except Exception: raise Exception( "The specified xy is invalid. It must be formatted like this ('10%', '10%')" ) else: print( "The specified xy is invalid. It must be formatted like this: (10, 10) or ('10%', '10%')" ) return if text_sequence is None: text = [str(x) for x in range(1, count + 1)] elif isinstance(text_sequence, int): text = [str(x) for x in range(text_sequence, text_sequence + count + 1)] elif isinstance(text_sequence, str): try: text_sequence = int(text_sequence) text = [str(x) for x in range(text_sequence, text_sequence + count + 1)] except Exception: text = [text_sequence] * count elif isinstance(text_sequence, list) and len(text_sequence) != count: print( f"The length of the text sequence must be equal to the number ({count}) of frames in the gif." ) return else: text = [str(x) for x in text_sequence] try: frames = [] # Loop over each frame in the animated image for index, frame in enumerate(ImageSequence.Iterator(image)): # Draw the text on the frame frame = frame.convert("RGB") draw = ImageDraw.Draw(frame) # w, h = draw.textsize(text[index]) draw.text(xy, text[index], font=font, fill=color) if add_progress_bar: draw.rectangle(progress_bar_shapes[index], fill=progress_bar_color) del draw b = io.BytesIO() frame.save(b, format="GIF") frame = Image.open(b) frames.append(frame) # https://www.pythoninformer.com/python-libraries/pillow/creating-animated-gif/ # Save the frames as a new image frames[0].save( out_gif, save_all=True, append_images=frames[1:], duration=duration, loop=loop, optimize=True, ) except Exception as e: print(e) def reduce_gif_size(in_gif, out_gif=None): """Reduces a GIF image using ffmpeg. Args: in_gif (str): The input file path to the GIF image. out_gif (str, optional): The output file path to the GIF image. Defaults to None. """ import ffmpeg import warnings warnings.filterwarnings("ignore") if not is_tool("ffmpeg"): print("ffmpeg is not installed on your computer.") return if not os.path.exists(in_gif): print("The input gif file does not exist.") return if out_gif is None: out_gif = in_gif elif not os.path.exists(os.path.dirname(out_gif)): os.makedirs(os.path.dirname(out_gif)) if in_gif == out_gif: tmp_gif = in_gif.replace(".gif", "_tmp.gif") shutil.copyfile(in_gif, tmp_gif) stream = ffmpeg.input(tmp_gif) stream = ffmpeg.output(stream, in_gif, loglevel="quiet").overwrite_output() ffmpeg.run(stream) os.remove(tmp_gif) else: stream = ffmpeg.input(in_gif) stream = ffmpeg.output(stream, out_gif, loglevel="quiet").overwrite_output() ffmpeg.run(stream) def modis_ndvi_doy_ts( data="Terra", band="NDVI", start_date=None, end_date=None, region=None ): """Create MODIS NDVI timeseries. The source code is adapted from https://developers.google.com/earth-engine/tutorials/community/modis-ndvi-time-series-animation. Args: data (str, optional): Either "Terra" or "Aqua". Defaults to "Terra". band (str, optional): Either the "NDVI" or "EVI" band. Defaults to "NDVI". start_date (str, optional): The start date used to filter the image collection, e.g., "2013-01-01". Defaults to None. end_date (str, optional): The end date used to filter the image collection. Defaults to None. region (ee.Geometry, optional): The geometry used to filter the image collection. Defaults to None. Returns: ee.ImageCollection: The MODIS NDVI time series. """ if data not in ["Terra", "Aqua"]: raise Exception("data must be 'Terra' or 'Aqua'.") if band not in ["NDVI", "EVI"]: raise Exception("band must be 'NDVI' or 'EVI'.") if region is not None: if isinstance(region, ee.Geometry) or isinstance(region, ee.FeatureCollection): pass else: raise Exception("region must be an ee.Geometry or ee.FeatureCollection.") if data == "Terra": col = ee.ImageCollection("MODIS/006/MOD13A2").select(band) else: col = ee.ImageCollection("MODIS/006/MYD13A2").select(band) if (start_date is not None) and (end_date is not None): col = col.filterDate(start_date, end_date) def set_doy(img): doy = ee.Date(img.get("system:time_start")).getRelative("day", "year") return img.set("doy", doy) col = col.map(set_doy) # Get a collection of distinct images by 'doy'. distinctDOY = col.filterDate("2013-01-01", "2014-01-01") # Define a filter that identifies which images from the complete # collection match the DOY from the distinct DOY collection. filter = ee.Filter.equals(**{"leftField": "doy", "rightField": "doy"}) # Define a join. join = ee.Join.saveAll("doy_matches") # Apply the join and convert the resulting FeatureCollection to an # ImageCollection. joinCol = ee.ImageCollection(join.apply(distinctDOY, col, filter)) # Apply median reduction among matching DOY collections. def match_doy(img): doyCol = ee.ImageCollection.fromImages(img.get("doy_matches")) return doyCol.reduce(ee.Reducer.median()) comp = joinCol.map(match_doy) if region is not None: return comp.map(lambda img: img.clip(region)) else: return comp import os import ee def random_string(string_length=3): """Generates a random string of fixed length. Args: string_length (int, optional): Fixed length. Defaults to 3. Returns: str: A random string """ import random import string # random.seed(1001) letters = string.ascii_lowercase return "".join(random.choice(letters) for i in range(string_length)) def download_ee_video(collection, video_args, out_gif, timeout=300, proxies=None): """Downloads a video thumbnail as a GIF image from Earth Engine. Args: collection (object): An ee.ImageCollection. video_args (object): Parameters for expring the video thumbnail. out_gif (str): File path to the output GIF. timeout (int, optional): The number of seconds the request will be timed out. Defaults to 300. proxies (dict, optional): A dictionary of proxy servers to use. Defaults to None. """ out_gif = os.path.abspath(out_gif) if not out_gif.endswith(".gif"): print("The output file must have an extension of .gif.") return if not os.path.exists(os.path.dirname(out_gif)): os.makedirs(os.path.dirname(out_gif)) if "region" in video_args.keys(): roi = video_args["region"] if not isinstance(roi, ee.Geometry): try: roi = roi.geometry() except Exception as e: print("Could not convert the provided roi to ee.Geometry") print(e) return video_args["region"] = roi if "dimensions" not in video_args: video_args["dimensions"] = 768 try: print("Generating URL...") url = collection.getVideoThumbURL(video_args) print(f"Downloading GIF image from {url}\nPlease wait ...") r = requests.get(url, stream=True, timeout=timeout, proxies=proxies) if r.status_code != 200: print("An error occurred while downloading.") print(r.json()["error"]["message"]) return else: with open(out_gif, "wb") as fd: for chunk in r.iter_content(chunk_size=1024): fd.write(chunk) print(f"The GIF image has been saved to: {out_gif}") except Exception as e: print(e) The provided code snippet includes necessary dependencies for implementing the `modis_ndvi_timelapse` function. Write a Python function `def modis_ndvi_timelapse( roi=None, out_gif=None, data="Terra", band="NDVI", start_date=None, end_date=None, dimensions=768, framesPerSecond=10, crs="EPSG:3857", xy=("3%", "3%"), text_sequence=None, font_type="arial.ttf", font_size=20, font_color="#ffffff", add_progress_bar=True, progress_bar_color="white", progress_bar_height=5, loop=0, overlay_data=None, overlay_color="black", overlay_width=1, overlay_opacity=1.0, mp4=False, fading=False, **kwargs, )` to solve the following problem: Create MODIS NDVI timelapse. The source code is adapted from https://developers.google.com/earth-engine/tutorials/community/modis-ndvi-time-series-animation. Args: roi (ee.Geometry, optional): The geometry used to filter the image collection. Defaults to None. out_gif (str): The output gif file path. Defaults to None. data (str, optional): Either "Terra" or "Aqua". Defaults to "Terra". band (str, optional): Either the "NDVI" or "EVI" band. Defaults to "NDVI". start_date (str, optional): The start date used to filter the image collection, e.g., "2013-01-01". Defaults to None. end_date (str, optional): The end date used to filter the image collection. Defaults to None. dimensions (int, optional): a number or pair of numbers (in format 'WIDTHxHEIGHT') Maximum dimensions of the thumbnail to render, in pixels. If only one number is passed, it is used as the maximum, and the other dimension is computed by proportional scaling. Defaults to 768. frames_per_second (int, optional): Animation speed. Defaults to 10. crs (str, optional): The coordinate reference system to use. Defaults to "EPSG:3857". xy (tuple, optional): Top left corner of the text. It can be formatted like this: (10, 10) or ('15%', '25%'). Defaults to None. text_sequence (int, str, list, optional): Text to be drawn. It can be an integer number, a string, or a list of strings. Defaults to None. font_type (str, optional): Font type. Defaults to "arial.ttf". font_size (int, optional): Font size. Defaults to 20. font_color (str, optional): Font color. It can be a string (e.g., 'red'), rgb tuple (e.g., (255, 127, 0)), or hex code (e.g., '#ff00ff'). Defaults to '#000000'. add_progress_bar (bool, optional): Whether to add a progress bar at the bottom of the GIF. Defaults to True. progress_bar_color (str, optional): Color for the progress bar. Defaults to 'white'. progress_bar_height (int, optional): Height of the progress bar. Defaults to 5. loop (int, optional): controls how many times the animation repeats. The default, 1, means that the animation will play once and then stop (displaying the last frame). A value of 0 means that the animation will repeat forever. Defaults to 0. overlay_data (int, str, list, optional): Administrative boundary to be drawn on the timelapse. Defaults to None. overlay_color (str, optional): Color for the overlay data. Can be any color name or hex color code. Defaults to 'black'. overlay_width (int, optional): Width of the overlay. Defaults to 1. overlay_opacity (float, optional): Opacity of the overlay. Defaults to 1.0. mp4 (bool, optional): Whether to convert the output gif to mp4. Defaults to False. fading (int | bool, optional): If True, add fading effect to the timelapse. Defaults to False, no fading. To add fading effect, set it to True (1 second fading duration) or to an integer value (fading duration). Here is the function: def modis_ndvi_timelapse( roi=None, out_gif=None, data="Terra", band="NDVI", start_date=None, end_date=None, dimensions=768, framesPerSecond=10, crs="EPSG:3857", xy=("3%", "3%"), text_sequence=None, font_type="arial.ttf", font_size=20, font_color="#ffffff", add_progress_bar=True, progress_bar_color="white", progress_bar_height=5, loop=0, overlay_data=None, overlay_color="black", overlay_width=1, overlay_opacity=1.0, mp4=False, fading=False, **kwargs, ): """Create MODIS NDVI timelapse. The source code is adapted from https://developers.google.com/earth-engine/tutorials/community/modis-ndvi-time-series-animation. Args: roi (ee.Geometry, optional): The geometry used to filter the image collection. Defaults to None. out_gif (str): The output gif file path. Defaults to None. data (str, optional): Either "Terra" or "Aqua". Defaults to "Terra". band (str, optional): Either the "NDVI" or "EVI" band. Defaults to "NDVI". start_date (str, optional): The start date used to filter the image collection, e.g., "2013-01-01". Defaults to None. end_date (str, optional): The end date used to filter the image collection. Defaults to None. dimensions (int, optional): a number or pair of numbers (in format 'WIDTHxHEIGHT') Maximum dimensions of the thumbnail to render, in pixels. If only one number is passed, it is used as the maximum, and the other dimension is computed by proportional scaling. Defaults to 768. frames_per_second (int, optional): Animation speed. Defaults to 10. crs (str, optional): The coordinate reference system to use. Defaults to "EPSG:3857". xy (tuple, optional): Top left corner of the text. It can be formatted like this: (10, 10) or ('15%', '25%'). Defaults to None. text_sequence (int, str, list, optional): Text to be drawn. It can be an integer number, a string, or a list of strings. Defaults to None. font_type (str, optional): Font type. Defaults to "arial.ttf". font_size (int, optional): Font size. Defaults to 20. font_color (str, optional): Font color. It can be a string (e.g., 'red'), rgb tuple (e.g., (255, 127, 0)), or hex code (e.g., '#ff00ff'). Defaults to '#000000'. add_progress_bar (bool, optional): Whether to add a progress bar at the bottom of the GIF. Defaults to True. progress_bar_color (str, optional): Color for the progress bar. Defaults to 'white'. progress_bar_height (int, optional): Height of the progress bar. Defaults to 5. loop (int, optional): controls how many times the animation repeats. The default, 1, means that the animation will play once and then stop (displaying the last frame). A value of 0 means that the animation will repeat forever. Defaults to 0. overlay_data (int, str, list, optional): Administrative boundary to be drawn on the timelapse. Defaults to None. overlay_color (str, optional): Color for the overlay data. Can be any color name or hex color code. Defaults to 'black'. overlay_width (int, optional): Width of the overlay. Defaults to 1. overlay_opacity (float, optional): Opacity of the overlay. Defaults to 1.0. mp4 (bool, optional): Whether to convert the output gif to mp4. Defaults to False. fading (int | bool, optional): If True, add fading effect to the timelapse. Defaults to False, no fading. To add fading effect, set it to True (1 second fading duration) or to an integer value (fading duration). """ if roi is None: roi = ee.Geometry.Polygon( [ [ [-18.6983, 38.1446], [-18.6983, -36.1630], [52.2293, -36.1630], [52.2293, 38.1446], ] ], None, False, ) if out_gif is None: out_gif = os.path.abspath(f"modis_ndvi_{random_string(3)}.gif") try: col = modis_ndvi_doy_ts(data, band, start_date, end_date, roi) # Define RGB visualization parameters. visParams = { "min": 0.0, "max": 9000.0, "palette": [ "FFFFFF", "CE7E45", "DF923D", "F1B555", "FCD163", "99B718", "74A901", "66A000", "529400", "3E8601", "207401", "056201", "004C00", "023B01", "012E01", "011D01", "011301", ], } # Create RGB visualization images for use as animation frames. rgbVis = col.map(lambda img: img.visualize(**visParams).clip(roi)) if overlay_data is not None: rgbVis = add_overlay( rgbVis, overlay_data, overlay_color, overlay_width, overlay_opacity, roi, ) # Define GIF visualization arguments. videoArgs = { "region": roi, "dimensions": dimensions, "crs": crs, "framesPerSecond": framesPerSecond, } download_ee_video(rgbVis, videoArgs, out_gif) if text_sequence is None: text = rgbVis.aggregate_array("system:index").getInfo() text_sequence = [d.replace("_", "-")[5:] for d in text] if os.path.exists(out_gif): add_text_to_gif( out_gif, out_gif, xy, text_sequence, font_type, font_size, font_color, add_progress_bar, progress_bar_color, progress_bar_height, duration=1000 / framesPerSecond, loop=loop, ) try: reduce_gif_size(out_gif) if isinstance(fading, bool): fading = int(fading) if fading > 0: gif_fading(out_gif, out_gif, duration=fading, verbose=False) except Exception as _: pass if mp4: out_mp4 = out_gif.replace(".gif", ".mp4") gif_to_mp4(out_gif, out_mp4) return out_gif except Exception as e: raise Exception(e)
Create MODIS NDVI timelapse. The source code is adapted from https://developers.google.com/earth-engine/tutorials/community/modis-ndvi-time-series-animation. Args: roi (ee.Geometry, optional): The geometry used to filter the image collection. Defaults to None. out_gif (str): The output gif file path. Defaults to None. data (str, optional): Either "Terra" or "Aqua". Defaults to "Terra". band (str, optional): Either the "NDVI" or "EVI" band. Defaults to "NDVI". start_date (str, optional): The start date used to filter the image collection, e.g., "2013-01-01". Defaults to None. end_date (str, optional): The end date used to filter the image collection. Defaults to None. dimensions (int, optional): a number or pair of numbers (in format 'WIDTHxHEIGHT') Maximum dimensions of the thumbnail to render, in pixels. If only one number is passed, it is used as the maximum, and the other dimension is computed by proportional scaling. Defaults to 768. frames_per_second (int, optional): Animation speed. Defaults to 10. crs (str, optional): The coordinate reference system to use. Defaults to "EPSG:3857". xy (tuple, optional): Top left corner of the text. It can be formatted like this: (10, 10) or ('15%', '25%'). Defaults to None. text_sequence (int, str, list, optional): Text to be drawn. It can be an integer number, a string, or a list of strings. Defaults to None. font_type (str, optional): Font type. Defaults to "arial.ttf". font_size (int, optional): Font size. Defaults to 20. font_color (str, optional): Font color. It can be a string (e.g., 'red'), rgb tuple (e.g., (255, 127, 0)), or hex code (e.g., '#ff00ff'). Defaults to '#000000'. add_progress_bar (bool, optional): Whether to add a progress bar at the bottom of the GIF. Defaults to True. progress_bar_color (str, optional): Color for the progress bar. Defaults to 'white'. progress_bar_height (int, optional): Height of the progress bar. Defaults to 5. loop (int, optional): controls how many times the animation repeats. The default, 1, means that the animation will play once and then stop (displaying the last frame). A value of 0 means that the animation will repeat forever. Defaults to 0. overlay_data (int, str, list, optional): Administrative boundary to be drawn on the timelapse. Defaults to None. overlay_color (str, optional): Color for the overlay data. Can be any color name or hex color code. Defaults to 'black'. overlay_width (int, optional): Width of the overlay. Defaults to 1. overlay_opacity (float, optional): Opacity of the overlay. Defaults to 1.0. mp4 (bool, optional): Whether to convert the output gif to mp4. Defaults to False. fading (int | bool, optional): If True, add fading effect to the timelapse. Defaults to False, no fading. To add fading effect, set it to True (1 second fading duration) or to an integer value (fading duration).
12,189
import datetime import glob import io import os import shutil import ee from .common import * from typing import Union, List def create_timelapse( collection, start_date, end_date, region=None, bands=None, frequency="year", reducer="median", date_format=None, out_gif=None, palette=None, vis_params=None, dimensions=768, frames_per_second=10, crs="EPSG:3857", overlay_data=None, overlay_color="black", overlay_width=1, overlay_opacity=1.0, title=None, title_xy=("2%", "90%"), add_text=True, text_xy=("2%", "2%"), text_sequence=None, font_type="arial.ttf", font_size=20, font_color="white", add_progress_bar=True, progress_bar_color="white", progress_bar_height=5, add_colorbar=False, colorbar_width=6.0, colorbar_height=0.4, colorbar_label=None, colorbar_label_size=12, colorbar_label_weight="normal", colorbar_tick_size=10, colorbar_bg_color=None, colorbar_orientation="horizontal", colorbar_dpi="figure", colorbar_xy=None, colorbar_size=(300, 300), loop=0, mp4=False, fading=False, parallel_scale=1, step=1, ): """Create a timelapse from any ee.ImageCollection. Args: collection (str | ee.ImageCollection): The collection of images to create a timeseries from. It can be a string representing the collection ID or an ee.ImageCollection object. start_date (str): The start date of the timeseries. It must be formatted like this: 'YYYY-MM-dd'. end_date (str): The end date of the timeseries. It must be formatted like this: 'YYYY-MM-dd'. region (ee.Geometry, optional): The region to use to filter the collection of images. It must be an ee.Geometry object. Defaults to None. bands (list, optional): A list of band names to use in the timelapse. Defaults to None. frequency (str, optional): The frequency of the timeseries. It must be one of the following: 'year', 'month', 'day', 'hour', 'minute', 'second'. Defaults to 'year'. reducer (str, optional): The reducer to use to reduce the collection of images to a single value. It can be one of the following: 'median', 'mean', 'min', 'max', 'variance', 'sum'. Defaults to 'median'. drop_empty (bool, optional): Whether to drop empty images from the timeseries. Defaults to True. date_format (str, optional): A pattern, as described at http://joda-time.sourceforge.net/apidocs/org/joda/time/format/DateTimeFormat.html. Defaults to 'YYYY-MM-dd'. out_gif (str): The output gif file path. Defaults to None. palette (list, optional): A list of colors to render a single-band image in the timelapse. Defaults to None. vis_params (dict, optional): A dictionary of visualization parameters to use in the timelapse. Defaults to None. See more at https://developers.google.com/earth-engine/guides/image_visualization. dimensions (int, optional): a number or pair of numbers (in format 'WIDTHxHEIGHT') Maximum dimensions of the thumbnail to render, in pixels. If only one number is passed, it is used as the maximum, and the other dimension is computed by proportional scaling. Defaults to 768. frames_per_second (int, optional): Animation speed. Defaults to 10. crs (str, optional): The coordinate reference system to use. Defaults to "EPSG:3857". overlay_data (int, str, list, optional): Administrative boundary to be drawn on the timelapse. Defaults to None. overlay_color (str, optional): Color for the overlay data. Can be any color name or hex color code. Defaults to 'black'. overlay_width (int, optional): Width of the overlay. Defaults to 1. overlay_opacity (float, optional): Opacity of the overlay. Defaults to 1.0. title (str, optional): The title of the timelapse. Defaults to None. title_xy (tuple, optional): Lower left corner of the title. It can be formatted like this: (10, 10) or ('15%', '25%'). Defaults to None. add_text (bool, optional): Whether to add animated text to the timelapse. Defaults to True. title_xy (tuple, optional): Lower left corner of the text sequency. It can be formatted like this: (10, 10) or ('15%', '25%'). Defaults to None. text_sequence (int, str, list, optional): Text to be drawn. It can be an integer number, a string, or a list of strings. Defaults to None. font_type (str, optional): Font type. Defaults to "arial.ttf". font_size (int, optional): Font size. Defaults to 20. font_color (str, optional): Font color. It can be a string (e.g., 'red'), rgb tuple (e.g., (255, 127, 0)), or hex code (e.g., '#ff00ff'). Defaults to '#000000'. add_progress_bar (bool, optional): Whether to add a progress bar at the bottom of the GIF. Defaults to True. progress_bar_color (str, optional): Color for the progress bar. Defaults to 'white'. progress_bar_height (int, optional): Height of the progress bar. Defaults to 5. add_colorbar (bool, optional): Whether to add a colorbar to the timelapse. Defaults to False. colorbar_width (float, optional): Width of the colorbar. Defaults to 6.0. colorbar_height (float, optional): Height of the colorbar. Defaults to 0.4. colorbar_label (str, optional): Label for the colorbar. Defaults to None. colorbar_label_size (int, optional): Font size for the colorbar label. Defaults to 12. colorbar_label_weight (str, optional): Font weight for the colorbar label. Defaults to 'normal'. colorbar_tick_size (int, optional): Font size for the colorbar ticks. Defaults to 10. colorbar_bg_color (str, optional): Background color for the colorbar, can be color like "white", "black". Defaults to None. colorbar_orientation (str, optional): Orientation of the colorbar. Defaults to 'horizontal'. colorbar_dpi (str, optional): DPI for the colorbar, can be numbers like 100, 300. Defaults to 'figure'. colorbar_xy (tuple, optional): Lower left corner of the colorbar. It can be formatted like this: (10, 10) or ('15%', '25%'). Defaults to None. colorbar_size (tuple, optional): Size of the colorbar. It can be formatted like this: (300, 300). Defaults to (300, 300). loop (int, optional): Controls how many times the animation repeats. The default, 1, means that the animation will play once and then stop (displaying the last frame). A value of 0 means that the animation will repeat forever. Defaults to 0. mp4 (bool, optional): Whether to create an mp4 file. Defaults to False. fading (int | bool, optional): If True, add fading effect to the timelapse. Defaults to False, no fading. To add fading effect, set it to True (1 second fading duration) or to an integer value (fading duration). parallel_scale (int, optional): A scaling factor used to limit memory use; using a larger parallel_scale (e.g. 2 or 4) may enable computations that run out of memory with the default. Defaults to 1. step (int, optional): The step size to use when creating the date sequence. Defaults to 1. Returns: str: File path to the timelapse gif. """ import geemap.colormaps as cm if not isinstance(collection, ee.ImageCollection): if isinstance(collection, str): collection = ee.ImageCollection(collection) else: raise Exception( "The collection must be an ee.ImageCollection object or asset id." ) col = create_timeseries( collection, start_date, end_date, region=region, bands=bands, frequency=frequency, reducer=reducer, drop_empty=True, date_format=date_format, parallel_scale=parallel_scale, step=step, ) # rename the bands to remove the '_reducer' characters from the band names. col = col.map( lambda img: img.rename( img.bandNames().map(lambda name: ee.String(name).replace(f"_{reducer}", "")) ) ) if out_gif is None: out_gif = temp_file_path(".gif") else: out_gif = check_file_path(out_gif) out_dir = os.path.dirname(out_gif) if bands is None: names = col.first().bandNames().getInfo() if len(names) < 3: bands = [names[0]] else: bands = names[:3][::-1] elif isinstance(bands, str): bands = [bands] elif not isinstance(bands, list): raise Exception("The bands must be a string or a list of strings.") if isinstance(palette, str): palette = cm.get_palette(palette, 15) elif isinstance(palette, list) or isinstance(palette, tuple): pass elif palette is not None: raise Exception("The palette must be a string or a list of strings.") if vis_params is None: img = col.first().select(bands) scale = collection.first().select(0).projection().nominalScale().multiply(10) min_value = min( image_min_value(img, region=region, scale=scale).getInfo().values() ) max_value = max( image_max_value(img, region=region, scale=scale).getInfo().values() ) vis_params = {"bands": bands, "min": min_value, "max": max_value} if len(bands) == 1: if palette is not None: vis_params["palette"] = palette else: vis_params["palette"] = cm.palettes.ndvi elif isinstance(vis_params, dict): if "bands" not in vis_params: vis_params["bands"] = bands if "min" not in vis_params: img = col.first().select(bands) scale = ( collection.first().select(0).projection().nominalScale().multiply(10) ) vis_params["min"] = min( image_min_value(img, region=region, scale=scale).getInfo().values() ) if "max" not in vis_params: img = col.first().select(bands) scale = ( collection.first().select(0).projection().nominalScale().multiply(10) ) vis_params["max"] = max( image_max_value(img, region=region, scale=scale).getInfo().values() ) if palette is None and (len(bands) == 1) and ("palette" not in vis_params): vis_params["palette"] = cm.palettes.ndvi elif palette is not None and ("palette" not in vis_params): vis_params["palette"] = palette if len(bands) > 1 and "palette" in vis_params: del vis_params["palette"] else: raise Exception("The vis_params must be a dictionary.") col = col.select(bands).map( lambda img: img.visualize(**vis_params).set( { "system:time_start": img.get("system:time_start"), "system:date": img.get("system:date"), } ) ) if overlay_data is not None: col = add_overlay( col, overlay_data, overlay_color, overlay_width, overlay_opacity ) video_args = {} video_args["dimensions"] = dimensions video_args["region"] = region video_args["framesPerSecond"] = frames_per_second video_args["crs"] = crs video_args["min"] = 0 video_args["max"] = 255 # if crs is not None: # video_args["crs"] = crs if "palette" in vis_params or len(bands) > 1: video_args["bands"] = ["vis-red", "vis-green", "vis-blue"] else: video_args["bands"] = ["vis-gray"] if ( isinstance(dimensions, int) and dimensions > 768 or isinstance(dimensions, str) and any(dim > 768 for dim in list(map(int, dimensions.split("x")))) ): count = col.size().getInfo() basename = os.path.basename(out_gif)[:-4] names = [ os.path.join( out_dir, f"{basename}_{str(i+1).zfill(int(len(str(count))))}.jpg" ) for i in range(count) ] get_image_collection_thumbnails( col, out_dir, vis_params={ "min": 0, "max": 255, "bands": video_args["bands"], }, dimensions=dimensions, names=names, ) make_gif( names, out_gif, fps=frames_per_second, loop=loop, mp4=False, clean_up=True, ) else: download_ee_video(col, video_args, out_gif) if title is not None and isinstance(title, str): add_text_to_gif( out_gif, out_gif, xy=title_xy, text_sequence=title, font_type=font_type, font_size=font_size, font_color=font_color, add_progress_bar=add_progress_bar, progress_bar_color=progress_bar_color, progress_bar_height=progress_bar_height, duration=1000 / frames_per_second, loop=loop, ) if add_text: if text_sequence is None: text_sequence = col.aggregate_array("system:date").getInfo() add_text_to_gif( out_gif, out_gif, xy=text_xy, text_sequence=text_sequence, font_type=font_type, font_size=font_size, font_color=font_color, add_progress_bar=add_progress_bar, progress_bar_color=progress_bar_color, progress_bar_height=progress_bar_height, duration=1000 / frames_per_second, loop=loop, ) if add_colorbar: colorbar = save_colorbar( None, colorbar_width, colorbar_height, vis_params["min"], vis_params["max"], vis_params["palette"], label=colorbar_label, label_size=colorbar_label_size, label_weight=colorbar_label_weight, tick_size=colorbar_tick_size, bg_color=colorbar_bg_color, orientation=colorbar_orientation, dpi=colorbar_dpi, show_colorbar=False, ) add_image_to_gif(out_gif, out_gif, colorbar, colorbar_xy, colorbar_size) if os.path.exists(out_gif): reduce_gif_size(out_gif) if isinstance(fading, bool): fading = int(fading) if fading > 0: gif_fading(out_gif, out_gif, duration=fading, verbose=False) if mp4: out_mp4 = out_gif.replace(".gif", ".mp4") gif_to_mp4(out_gif, out_mp4) return out_gif def modis_ocean_color_timeseries( satellite, start_date, end_date, region=None, bands=None, frequency="year", reducer="median", drop_empty=True, date_format=None, parallel_scale=1, ): """Creates a ocean color timeseries from MODIS. https://developers.google.com/earth-engine/datasets/catalog/NASA_OCEANDATA_MODIS-Aqua_L3SMI Args: satellite (str): The satellite to use, can be either "Terra" or "Aqua". start_date (str): The start date of the timeseries. It must be formatted like this: 'YYYY-MM-dd'. end_date (str): The end date of the timeseries. It must be formatted like this: 'YYYY-MM-dd'. region (ee.Geometry, optional): The region to use to filter the collection of images. It must be an ee.Geometry object. Defaults to None. bands (list, optional): The list of bands to use to create the timeseries. It must be a list of strings. Defaults to None. frequency (str, optional): The frequency of the timeseries. It must be one of the following: 'year', 'month', 'day'. Defaults to 'year'. reducer (str, optional): The reducer to use to reduce the collection of images to a single value. It can be one of the following: 'median', 'mean', 'min', 'max', 'variance', 'sum'. Defaults to 'median'. drop_empty (bool, optional): Whether to drop empty images from the timeseries. Defaults to True. date_format (str, optional): A pattern, as described at http://joda-time.sourceforge.net/apidocs/org/joda/time/format/DateTimeFormat.html. Defaults to 'YYYY-MM-dd'. parallel_scale (int, optional): A scaling factor used to limit memory use; using a larger parallel_scale (e.g. 2 or 4) may enable computations that run out of memory with the default. Defaults to 1. Returns: ee.ImageCollection: The timeseries. """ if satellite not in ["Terra", "Aqua"]: raise Exception("Satellite must be 'Terra' or 'Aqua'.") allowed_frequency = ["year", "quarter", "month", "week", "day"] if frequency not in allowed_frequency: raise Exception( "Frequency must be one of the following: {}".format(allowed_frequency) ) if region is not None: if isinstance(region, ee.Geometry) or isinstance(region, ee.FeatureCollection): pass else: raise Exception("region must be an ee.Geometry or ee.FeatureCollection.") col = ee.ImageCollection(f"NASA/OCEANDATA/MODIS-{satellite}/L3SMI").filterDate( start_date, end_date ) ts = create_timeseries( col, start_date, end_date, region, bands, frequency, reducer, drop_empty, date_format, parallel_scale, ) return ts import ee The provided code snippet includes necessary dependencies for implementing the `modis_ocean_color_timelapse` function. Write a Python function `def modis_ocean_color_timelapse( satellite, start_date, end_date, roi=None, bands=None, frequency="year", reducer="median", date_format=None, out_gif=None, palette="coolwarm", vis_params=None, dimensions=768, frames_per_second=5, crs="EPSG:3857", overlay_data=None, overlay_color="black", overlay_width=1, overlay_opacity=1.0, title=None, title_xy=("2%", "90%"), add_text=True, text_xy=("2%", "2%"), text_sequence=None, font_type="arial.ttf", font_size=20, font_color="white", add_progress_bar=True, progress_bar_color="white", progress_bar_height=5, add_colorbar=True, colorbar_width=6.0, colorbar_height=0.4, colorbar_label="Sea Surface Temperature (°C)", colorbar_label_size=12, colorbar_label_weight="normal", colorbar_tick_size=10, colorbar_bg_color="white", colorbar_orientation="horizontal", colorbar_dpi="figure", colorbar_xy=None, colorbar_size=(300, 300), loop=0, mp4=False, fading=False, )` to solve the following problem: Creates a ocean color timelapse from MODIS. https://developers.google.com/earth-engine/datasets/catalog/NASA_OCEANDATA_MODIS-Aqua_L3SMI Args: satellite (str): The satellite to use, can be either "Terra" or "Aqua". start_date (str): The start date of the timeseries. It must be formatted like this: 'YYYY-MM-dd'. end_date (str): The end date of the timeseries. It must be formatted like this: 'YYYY-MM-dd'. roi (ee.Geometry, optional): The region to use to filter the collection of images. It must be an ee.Geometry object. Defaults to None. bands (list, optional): A list of band names to use in the timelapse. Defaults to None. frequency (str, optional): The frequency of the timeseries. It must be one of the following: 'year', 'month', 'day', 'hour', 'minute', 'second'. Defaults to 'year'. reducer (str, optional): The reducer to use to reduce the collection of images to a single value. It can be one of the following: 'median', 'mean', 'min', 'max', 'variance', 'sum'. Defaults to 'median'. drop_empty (bool, optional): Whether to drop empty images from the timeseries. Defaults to True. date_format (str, optional): A pattern, as described at http://joda-time.sourceforge.net/apidocs/org/joda/time/format/DateTimeFormat.html. Defaults to 'YYYY-MM-dd'. out_gif (str): The output gif file path. Defaults to None. palette (list, optional): A list of colors to render a single-band image in the timelapse. Defaults to None. vis_params (dict, optional): A dictionary of visualization parameters to use in the timelapse. Defaults to None. See more at https://developers.google.com/earth-engine/guides/image_visualization. dimensions (int, optional): a number or pair of numbers (in format 'WIDTHxHEIGHT') Maximum dimensions of the thumbnail to render, in pixels. If only one number is passed, it is used as the maximum, and the other dimension is computed by proportional scaling. Defaults to 768. frames_per_second (int, optional): Animation speed. Defaults to 10. crs (str, optional): The coordinate reference system to use. Defaults to "EPSG:3857". overlay_data (int, str, list, optional): Administrative boundary to be drawn on the timelapse. Defaults to None. overlay_color (str, optional): Color for the overlay data. Can be any color name or hex color code. Defaults to 'black'. overlay_width (int, optional): Width of the overlay. Defaults to 1. overlay_opacity (float, optional): Opacity of the overlay. Defaults to 1.0. title (str, optional): The title of the timelapse. Defaults to None. title_xy (tuple, optional): Lower left corner of the title. It can be formatted like this: (10, 10) or ('15%', '25%'). Defaults to None. add_text (bool, optional): Whether to add animated text to the timelapse. Defaults to True. title_xy (tuple, optional): Lower left corner of the text sequency. It can be formatted like this: (10, 10) or ('15%', '25%'). Defaults to None. text_sequence (int, str, list, optional): Text to be drawn. It can be an integer number, a string, or a list of strings. Defaults to None. font_type (str, optional): Font type. Defaults to "arial.ttf". font_size (int, optional): Font size. Defaults to 20. font_color (str, optional): Font color. It can be a string (e.g., 'red'), rgb tuple (e.g., (255, 127, 0)), or hex code (e.g., '#ff00ff'). Defaults to '#000000'. add_progress_bar (bool, optional): Whether to add a progress bar at the bottom of the GIF. Defaults to True. progress_bar_color (str, optional): Color for the progress bar. Defaults to 'white'. progress_bar_height (int, optional): Height of the progress bar. Defaults to 5. add_colorbar (bool, optional): Whether to add a colorbar to the timelapse. Defaults to False. colorbar_width (float, optional): Width of the colorbar. Defaults to 6.0. colorbar_height (float, optional): Height of the colorbar. Defaults to 0.4. colorbar_label (str, optional): Label for the colorbar. Defaults to None. colorbar_label_size (int, optional): Font size for the colorbar label. Defaults to 12. colorbar_label_weight (str, optional): Font weight for the colorbar label. Defaults to 'normal'. colorbar_tick_size (int, optional): Font size for the colorbar ticks. Defaults to 10. colorbar_bg_color (str, optional): Background color for the colorbar, can be color like "white", "black". Defaults to None. colorbar_orientation (str, optional): Orientation of the colorbar. Defaults to 'horizontal'. colorbar_dpi (str, optional): DPI for the colorbar, can be numbers like 100, 300. Defaults to 'figure'. colorbar_xy (tuple, optional): Lower left corner of the colorbar. It can be formatted like this: (10, 10) or ('15%', '25%'). Defaults to None. colorbar_size (tuple, optional): Size of the colorbar. It can be formatted like this: (300, 300). Defaults to (300, 300). loop (int, optional): Controls how many times the animation repeats. The default, 1, means that the animation will play once and then stop (displaying the last frame). A value of 0 means that the animation will repeat forever. Defaults to 0. mp4 (bool, optional): Whether to create an mp4 file. Defaults to False. fading (int | bool, optional): If True, add fading effect to the timelapse. Defaults to False, no fading. To add fading effect, set it to True (1 second fading duration) or to an integer value (fading duration). Returns: str: File path to the timelapse gif. Here is the function: def modis_ocean_color_timelapse( satellite, start_date, end_date, roi=None, bands=None, frequency="year", reducer="median", date_format=None, out_gif=None, palette="coolwarm", vis_params=None, dimensions=768, frames_per_second=5, crs="EPSG:3857", overlay_data=None, overlay_color="black", overlay_width=1, overlay_opacity=1.0, title=None, title_xy=("2%", "90%"), add_text=True, text_xy=("2%", "2%"), text_sequence=None, font_type="arial.ttf", font_size=20, font_color="white", add_progress_bar=True, progress_bar_color="white", progress_bar_height=5, add_colorbar=True, colorbar_width=6.0, colorbar_height=0.4, colorbar_label="Sea Surface Temperature (°C)", colorbar_label_size=12, colorbar_label_weight="normal", colorbar_tick_size=10, colorbar_bg_color="white", colorbar_orientation="horizontal", colorbar_dpi="figure", colorbar_xy=None, colorbar_size=(300, 300), loop=0, mp4=False, fading=False, ): """Creates a ocean color timelapse from MODIS. https://developers.google.com/earth-engine/datasets/catalog/NASA_OCEANDATA_MODIS-Aqua_L3SMI Args: satellite (str): The satellite to use, can be either "Terra" or "Aqua". start_date (str): The start date of the timeseries. It must be formatted like this: 'YYYY-MM-dd'. end_date (str): The end date of the timeseries. It must be formatted like this: 'YYYY-MM-dd'. roi (ee.Geometry, optional): The region to use to filter the collection of images. It must be an ee.Geometry object. Defaults to None. bands (list, optional): A list of band names to use in the timelapse. Defaults to None. frequency (str, optional): The frequency of the timeseries. It must be one of the following: 'year', 'month', 'day', 'hour', 'minute', 'second'. Defaults to 'year'. reducer (str, optional): The reducer to use to reduce the collection of images to a single value. It can be one of the following: 'median', 'mean', 'min', 'max', 'variance', 'sum'. Defaults to 'median'. drop_empty (bool, optional): Whether to drop empty images from the timeseries. Defaults to True. date_format (str, optional): A pattern, as described at http://joda-time.sourceforge.net/apidocs/org/joda/time/format/DateTimeFormat.html. Defaults to 'YYYY-MM-dd'. out_gif (str): The output gif file path. Defaults to None. palette (list, optional): A list of colors to render a single-band image in the timelapse. Defaults to None. vis_params (dict, optional): A dictionary of visualization parameters to use in the timelapse. Defaults to None. See more at https://developers.google.com/earth-engine/guides/image_visualization. dimensions (int, optional): a number or pair of numbers (in format 'WIDTHxHEIGHT') Maximum dimensions of the thumbnail to render, in pixels. If only one number is passed, it is used as the maximum, and the other dimension is computed by proportional scaling. Defaults to 768. frames_per_second (int, optional): Animation speed. Defaults to 10. crs (str, optional): The coordinate reference system to use. Defaults to "EPSG:3857". overlay_data (int, str, list, optional): Administrative boundary to be drawn on the timelapse. Defaults to None. overlay_color (str, optional): Color for the overlay data. Can be any color name or hex color code. Defaults to 'black'. overlay_width (int, optional): Width of the overlay. Defaults to 1. overlay_opacity (float, optional): Opacity of the overlay. Defaults to 1.0. title (str, optional): The title of the timelapse. Defaults to None. title_xy (tuple, optional): Lower left corner of the title. It can be formatted like this: (10, 10) or ('15%', '25%'). Defaults to None. add_text (bool, optional): Whether to add animated text to the timelapse. Defaults to True. title_xy (tuple, optional): Lower left corner of the text sequency. It can be formatted like this: (10, 10) or ('15%', '25%'). Defaults to None. text_sequence (int, str, list, optional): Text to be drawn. It can be an integer number, a string, or a list of strings. Defaults to None. font_type (str, optional): Font type. Defaults to "arial.ttf". font_size (int, optional): Font size. Defaults to 20. font_color (str, optional): Font color. It can be a string (e.g., 'red'), rgb tuple (e.g., (255, 127, 0)), or hex code (e.g., '#ff00ff'). Defaults to '#000000'. add_progress_bar (bool, optional): Whether to add a progress bar at the bottom of the GIF. Defaults to True. progress_bar_color (str, optional): Color for the progress bar. Defaults to 'white'. progress_bar_height (int, optional): Height of the progress bar. Defaults to 5. add_colorbar (bool, optional): Whether to add a colorbar to the timelapse. Defaults to False. colorbar_width (float, optional): Width of the colorbar. Defaults to 6.0. colorbar_height (float, optional): Height of the colorbar. Defaults to 0.4. colorbar_label (str, optional): Label for the colorbar. Defaults to None. colorbar_label_size (int, optional): Font size for the colorbar label. Defaults to 12. colorbar_label_weight (str, optional): Font weight for the colorbar label. Defaults to 'normal'. colorbar_tick_size (int, optional): Font size for the colorbar ticks. Defaults to 10. colorbar_bg_color (str, optional): Background color for the colorbar, can be color like "white", "black". Defaults to None. colorbar_orientation (str, optional): Orientation of the colorbar. Defaults to 'horizontal'. colorbar_dpi (str, optional): DPI for the colorbar, can be numbers like 100, 300. Defaults to 'figure'. colorbar_xy (tuple, optional): Lower left corner of the colorbar. It can be formatted like this: (10, 10) or ('15%', '25%'). Defaults to None. colorbar_size (tuple, optional): Size of the colorbar. It can be formatted like this: (300, 300). Defaults to (300, 300). loop (int, optional): Controls how many times the animation repeats. The default, 1, means that the animation will play once and then stop (displaying the last frame). A value of 0 means that the animation will repeat forever. Defaults to 0. mp4 (bool, optional): Whether to create an mp4 file. Defaults to False. fading (int | bool, optional): If True, add fading effect to the timelapse. Defaults to False, no fading. To add fading effect, set it to True (1 second fading duration) or to an integer value (fading duration). Returns: str: File path to the timelapse gif. """ collection = modis_ocean_color_timeseries( satellite, start_date, end_date, roi, bands, frequency, reducer, date_format ) if bands is None: bands = ["sst"] if len(bands) == 1 and palette is None: palette = "coolwarm" if roi is None: roi = ee.Geometry.BBox(-99.755133, 18.316722, -79.761194, 31.206929) out_gif = create_timelapse( collection, start_date, end_date, roi, bands, frequency, reducer, date_format, out_gif, palette, vis_params, dimensions, frames_per_second, crs, overlay_data, overlay_color, overlay_width, overlay_opacity, title, title_xy, add_text, text_xy, text_sequence, font_type, font_size, font_color, add_progress_bar, progress_bar_color, progress_bar_height, add_colorbar, colorbar_width, colorbar_height, colorbar_label, colorbar_label_size, colorbar_label_weight, colorbar_tick_size, colorbar_bg_color, colorbar_orientation, colorbar_dpi, colorbar_xy, colorbar_size, loop, mp4, fading, ) return out_gif
Creates a ocean color timelapse from MODIS. https://developers.google.com/earth-engine/datasets/catalog/NASA_OCEANDATA_MODIS-Aqua_L3SMI Args: satellite (str): The satellite to use, can be either "Terra" or "Aqua". start_date (str): The start date of the timeseries. It must be formatted like this: 'YYYY-MM-dd'. end_date (str): The end date of the timeseries. It must be formatted like this: 'YYYY-MM-dd'. roi (ee.Geometry, optional): The region to use to filter the collection of images. It must be an ee.Geometry object. Defaults to None. bands (list, optional): A list of band names to use in the timelapse. Defaults to None. frequency (str, optional): The frequency of the timeseries. It must be one of the following: 'year', 'month', 'day', 'hour', 'minute', 'second'. Defaults to 'year'. reducer (str, optional): The reducer to use to reduce the collection of images to a single value. It can be one of the following: 'median', 'mean', 'min', 'max', 'variance', 'sum'. Defaults to 'median'. drop_empty (bool, optional): Whether to drop empty images from the timeseries. Defaults to True. date_format (str, optional): A pattern, as described at http://joda-time.sourceforge.net/apidocs/org/joda/time/format/DateTimeFormat.html. Defaults to 'YYYY-MM-dd'. out_gif (str): The output gif file path. Defaults to None. palette (list, optional): A list of colors to render a single-band image in the timelapse. Defaults to None. vis_params (dict, optional): A dictionary of visualization parameters to use in the timelapse. Defaults to None. See more at https://developers.google.com/earth-engine/guides/image_visualization. dimensions (int, optional): a number or pair of numbers (in format 'WIDTHxHEIGHT') Maximum dimensions of the thumbnail to render, in pixels. If only one number is passed, it is used as the maximum, and the other dimension is computed by proportional scaling. Defaults to 768. frames_per_second (int, optional): Animation speed. Defaults to 10. crs (str, optional): The coordinate reference system to use. Defaults to "EPSG:3857". overlay_data (int, str, list, optional): Administrative boundary to be drawn on the timelapse. Defaults to None. overlay_color (str, optional): Color for the overlay data. Can be any color name or hex color code. Defaults to 'black'. overlay_width (int, optional): Width of the overlay. Defaults to 1. overlay_opacity (float, optional): Opacity of the overlay. Defaults to 1.0. title (str, optional): The title of the timelapse. Defaults to None. title_xy (tuple, optional): Lower left corner of the title. It can be formatted like this: (10, 10) or ('15%', '25%'). Defaults to None. add_text (bool, optional): Whether to add animated text to the timelapse. Defaults to True. title_xy (tuple, optional): Lower left corner of the text sequency. It can be formatted like this: (10, 10) or ('15%', '25%'). Defaults to None. text_sequence (int, str, list, optional): Text to be drawn. It can be an integer number, a string, or a list of strings. Defaults to None. font_type (str, optional): Font type. Defaults to "arial.ttf". font_size (int, optional): Font size. Defaults to 20. font_color (str, optional): Font color. It can be a string (e.g., 'red'), rgb tuple (e.g., (255, 127, 0)), or hex code (e.g., '#ff00ff'). Defaults to '#000000'. add_progress_bar (bool, optional): Whether to add a progress bar at the bottom of the GIF. Defaults to True. progress_bar_color (str, optional): Color for the progress bar. Defaults to 'white'. progress_bar_height (int, optional): Height of the progress bar. Defaults to 5. add_colorbar (bool, optional): Whether to add a colorbar to the timelapse. Defaults to False. colorbar_width (float, optional): Width of the colorbar. Defaults to 6.0. colorbar_height (float, optional): Height of the colorbar. Defaults to 0.4. colorbar_label (str, optional): Label for the colorbar. Defaults to None. colorbar_label_size (int, optional): Font size for the colorbar label. Defaults to 12. colorbar_label_weight (str, optional): Font weight for the colorbar label. Defaults to 'normal'. colorbar_tick_size (int, optional): Font size for the colorbar ticks. Defaults to 10. colorbar_bg_color (str, optional): Background color for the colorbar, can be color like "white", "black". Defaults to None. colorbar_orientation (str, optional): Orientation of the colorbar. Defaults to 'horizontal'. colorbar_dpi (str, optional): DPI for the colorbar, can be numbers like 100, 300. Defaults to 'figure'. colorbar_xy (tuple, optional): Lower left corner of the colorbar. It can be formatted like this: (10, 10) or ('15%', '25%'). Defaults to None. colorbar_size (tuple, optional): Size of the colorbar. It can be formatted like this: (300, 300). Defaults to (300, 300). loop (int, optional): Controls how many times the animation repeats. The default, 1, means that the animation will play once and then stop (displaying the last frame). A value of 0 means that the animation will repeat forever. Defaults to 0. mp4 (bool, optional): Whether to create an mp4 file. Defaults to False. fading (int | bool, optional): If True, add fading effect to the timelapse. Defaults to False, no fading. To add fading effect, set it to True (1 second fading duration) or to an integer value (fading duration). Returns: str: File path to the timelapse gif.
12,190
import datetime import glob import io import os import shutil import ee from .common import * from typing import Union, List def create_timeseries( collection, start_date, end_date, region=None, bands=None, frequency="year", reducer="median", drop_empty=True, date_format=None, parallel_scale=1, step=1, ): """Creates a timeseries from a collection of images by a specified frequency and reducer. Args: collection (str | ee.ImageCollection): The collection of images to create a timeseries from. It can be a string representing the collection ID or an ee.ImageCollection object. start_date (str): The start date of the timeseries. It must be formatted like this: 'YYYY-MM-dd'. end_date (str): The end date of the timeseries. It must be formatted like this: 'YYYY-MM-dd'. region (ee.Geometry, optional): The region to use to filter the collection of images. It must be an ee.Geometry object. Defaults to None. bands (list, optional): The list of bands to use to create the timeseries. It must be a list of strings. Defaults to None. frequency (str, optional): The frequency of the timeseries. It must be one of the following: 'year', 'month', 'day', 'hour', 'minute', 'second'. Defaults to 'year'. reducer (str, optional): The reducer to use to reduce the collection of images to a single value. It can be one of the following: 'median', 'mean', 'min', 'max', 'variance', 'sum'. Defaults to 'median'. drop_empty (bool, optional): Whether to drop empty images from the timeseries. Defaults to True. date_format (str, optional): A pattern, as described at http://joda-time.sourceforge.net/apidocs/org/joda/time/format/DateTimeFormat.html. Defaults to 'YYYY-MM-dd'. parallel_scale (int, optional): A scaling factor used to limit memory use; using a larger parallel_scale (e.g. 2 or 4) may enable computations that run out of memory with the default. Defaults to 1. step (int, optional): The step size to use when creating the date sequence. Defaults to 1. Returns: ee.ImageCollection: The timeseries. """ if not isinstance(collection, ee.ImageCollection): if isinstance(collection, str): collection = ee.ImageCollection(collection) else: raise Exception( "The collection must be an ee.ImageCollection object or asset id." ) if bands is not None: collection = collection.select(bands) else: bands = collection.first().bandNames() feq_dict = { "year": "YYYY", "month": "YYYY-MM", "quarter": "YYYY-MM", "week": "YYYY-MM-dd", "day": "YYYY-MM-dd", "hour": "YYYY-MM-dd HH", "minute": "YYYY-MM-dd HH:mm", "second": "YYYY-MM-dd HH:mm:ss", } if date_format is None: date_format = feq_dict[frequency] dates = date_sequence(start_date, end_date, frequency, date_format, step) try: reducer = eval(f"ee.Reducer.{reducer}()") except Exception as e: print("The provided reducer is invalid.") raise Exception(e) def create_image(date): start = ee.Date(date) if frequency == "quarter": end = start.advance(3, "month") else: end = start.advance(1, frequency) if region is None: sub_col = collection.filterDate(start, end) image = sub_col.reduce(reducer, parallel_scale) else: sub_col = collection.filterDate(start, end).filterBounds(region) image = ee.Image( ee.Algorithms.If( ee.Algorithms.ObjectType(region).equals("FeatureCollection"), sub_col.reduce(reducer, parallel_scale).clipToCollection(region), sub_col.reduce(reducer, parallel_scale).clip(region), ) ) return image.set( { "system:time_start": ee.Date(date).millis(), "system:date": ee.Date(date).format(date_format), "empty": sub_col.limit(1).size().eq(0), } ).rename(bands) try: images = ee.ImageCollection(dates.map(create_image)) if drop_empty: return images.filterMetadata("empty", "equals", 0) else: return images except Exception as e: raise Exception(e) import ee The provided code snippet includes necessary dependencies for implementing the `dynamic_world_timeseries` function. Write a Python function `def dynamic_world_timeseries( region, start_date="2016-01-01", end_date="2021-12-31", cloud_pct=30, frequency="year", reducer="mode", drop_empty=True, date_format=None, return_type="hillshade", parallel_scale=1, )` to solve the following problem: Create Dynamic World timeseries. Args: region (ee.Geometry | ee.FeatureCollection): The region of interest. start_date (str | ee.Date): The start date of the query. Default to "2016-01-01". end_date (str | ee.Date): The end date of the query. Default to "2021-12-31". cloud_pct (int, optional): The cloud percentage threshold (<=). Defaults to 30. frequency (str, optional): The frequency of the timeseries. It must be one of the following: 'year', 'month', 'day', 'hour', 'minute', 'second'. Defaults to 'year'. reducer (str, optional): The reducer to be used. Defaults to "mode". drop_empty (bool, optional): Whether to drop empty images from the timeseries. Defaults to True. date_format (str, optional): A pattern, as described at http://joda-time.sourceforge.net/apidocs/org/joda/time/format/DateTimeFormat.html. Defaults to 'YYYY-MM-dd'. return_type (str, optional): The type of image to be returned. Can be one of 'hillshade', 'visualize', 'class', or 'probability'. Default to "hillshade". parallel_scale (int, optional): A scaling factor used to limit memory use; using a larger parallel_scale (e.g. 2 or 4) may enable computations that run out of memory with the default. Defaults to 1. Returns: ee.ImageCollection: An ImageCollection of the Dynamic World land cover timeseries. Here is the function: def dynamic_world_timeseries( region, start_date="2016-01-01", end_date="2021-12-31", cloud_pct=30, frequency="year", reducer="mode", drop_empty=True, date_format=None, return_type="hillshade", parallel_scale=1, ): """Create Dynamic World timeseries. Args: region (ee.Geometry | ee.FeatureCollection): The region of interest. start_date (str | ee.Date): The start date of the query. Default to "2016-01-01". end_date (str | ee.Date): The end date of the query. Default to "2021-12-31". cloud_pct (int, optional): The cloud percentage threshold (<=). Defaults to 30. frequency (str, optional): The frequency of the timeseries. It must be one of the following: 'year', 'month', 'day', 'hour', 'minute', 'second'. Defaults to 'year'. reducer (str, optional): The reducer to be used. Defaults to "mode". drop_empty (bool, optional): Whether to drop empty images from the timeseries. Defaults to True. date_format (str, optional): A pattern, as described at http://joda-time.sourceforge.net/apidocs/org/joda/time/format/DateTimeFormat.html. Defaults to 'YYYY-MM-dd'. return_type (str, optional): The type of image to be returned. Can be one of 'hillshade', 'visualize', 'class', or 'probability'. Default to "hillshade". parallel_scale (int, optional): A scaling factor used to limit memory use; using a larger parallel_scale (e.g. 2 or 4) may enable computations that run out of memory with the default. Defaults to 1. Returns: ee.ImageCollection: An ImageCollection of the Dynamic World land cover timeseries. """ if return_type not in ["hillshade", "visualize", "class", "probability"]: raise ValueError( f"{return_type} must be one of 'hillshade', 'visualize', 'class', or 'probability'." ) if ( isinstance(region, ee.FeatureCollection) or isinstance(region, ee.Feature) or isinstance(region, ee.Geometry) ): pass else: raise ValueError( f"{region} must be one of ee.FeatureCollection, ee.Feature, or ee.Geometry." ) if cloud_pct < 0 or cloud_pct > 100: raise ValueError(f"{cloud_pct} must be between 0 and 100.") s2 = ( ee.ImageCollection("COPERNICUS/S2_HARMONIZED") .filterDate(start_date, end_date) .filterBounds(region) .filter(ee.Filter.lte("CLOUDY_PIXEL_PERCENTAGE", cloud_pct)) ) ids = s2.aggregate_array("system:index") dw = ee.ImageCollection("GOOGLE/DYNAMICWORLD/V1").filter( ee.Filter.inList("system:index", ids) ) collection = dw.select("label") dwVisParams = { "min": 0, "max": 8, "palette": [ "#419BDF", "#397D49", "#88B053", "#7A87C6", "#E49635", "#DFC35A", "#C4281B", "#A59B8F", "#B39FE1", ], } images = create_timeseries( collection, start_date, end_date, region, None, frequency, reducer, drop_empty, date_format, parallel_scale, ) if return_type == "class": return images elif return_type == "visualize": result = images.map(lambda img: img.visualize(**dwVisParams)) return result else: # Create a Top-1 Probability Hillshade Visualization probabilityBands = [ "water", "trees", "grass", "flooded_vegetation", "crops", "shrub_and_scrub", "built", "bare", "snow_and_ice", ] # Select probability bands probabilityCol = dw.select(probabilityBands) prob_col = create_timeseries( probabilityCol, start_date, end_date, region, None, frequency, "mean", drop_empty, date_format, parallel_scale, ) prob_images = ee.ImageCollection( prob_col.map( lambda img: img.reduce(ee.Reducer.max()).set( "system:time_start", img.get("system:time_start") ) ) ) if return_type == "probability": return prob_images elif return_type == "hillshade": count = prob_images.size() nums = ee.List.sequence(0, count.subtract(1)) def create_hillshade(d): proj = ee.Projection("EPSG:3857").atScale(10) img = ee.Image(images.toList(images.size()).get(d)) prob_img = ee.Image(prob_images.toList(prob_images.size()).get(d)) prob_img = prob_img.setDefaultProjection(proj) top1Confidence = prob_img.multiply(100).int() hillshade = ee.Terrain.hillshade(top1Confidence).divide(255) rgbImage = img.visualize(**dwVisParams).divide(255) probabilityHillshade = rgbImage.multiply(hillshade) return probabilityHillshade.set( "system:time_start", img.get("system:time_start") ) result = ee.ImageCollection(nums.map(create_hillshade)) return result
Create Dynamic World timeseries. Args: region (ee.Geometry | ee.FeatureCollection): The region of interest. start_date (str | ee.Date): The start date of the query. Default to "2016-01-01". end_date (str | ee.Date): The end date of the query. Default to "2021-12-31". cloud_pct (int, optional): The cloud percentage threshold (<=). Defaults to 30. frequency (str, optional): The frequency of the timeseries. It must be one of the following: 'year', 'month', 'day', 'hour', 'minute', 'second'. Defaults to 'year'. reducer (str, optional): The reducer to be used. Defaults to "mode". drop_empty (bool, optional): Whether to drop empty images from the timeseries. Defaults to True. date_format (str, optional): A pattern, as described at http://joda-time.sourceforge.net/apidocs/org/joda/time/format/DateTimeFormat.html. Defaults to 'YYYY-MM-dd'. return_type (str, optional): The type of image to be returned. Can be one of 'hillshade', 'visualize', 'class', or 'probability'. Default to "hillshade". parallel_scale (int, optional): A scaling factor used to limit memory use; using a larger parallel_scale (e.g. 2 or 4) may enable computations that run out of memory with the default. Defaults to 1. Returns: ee.ImageCollection: An ImageCollection of the Dynamic World land cover timeseries.
12,191
import datetime import glob import io import os import shutil import ee from .common import * from typing import Union, List def create_timelapse( collection, start_date, end_date, region=None, bands=None, frequency="year", reducer="median", date_format=None, out_gif=None, palette=None, vis_params=None, dimensions=768, frames_per_second=10, crs="EPSG:3857", overlay_data=None, overlay_color="black", overlay_width=1, overlay_opacity=1.0, title=None, title_xy=("2%", "90%"), add_text=True, text_xy=("2%", "2%"), text_sequence=None, font_type="arial.ttf", font_size=20, font_color="white", add_progress_bar=True, progress_bar_color="white", progress_bar_height=5, add_colorbar=False, colorbar_width=6.0, colorbar_height=0.4, colorbar_label=None, colorbar_label_size=12, colorbar_label_weight="normal", colorbar_tick_size=10, colorbar_bg_color=None, colorbar_orientation="horizontal", colorbar_dpi="figure", colorbar_xy=None, colorbar_size=(300, 300), loop=0, mp4=False, fading=False, parallel_scale=1, step=1, ): """Create a timelapse from any ee.ImageCollection. Args: collection (str | ee.ImageCollection): The collection of images to create a timeseries from. It can be a string representing the collection ID or an ee.ImageCollection object. start_date (str): The start date of the timeseries. It must be formatted like this: 'YYYY-MM-dd'. end_date (str): The end date of the timeseries. It must be formatted like this: 'YYYY-MM-dd'. region (ee.Geometry, optional): The region to use to filter the collection of images. It must be an ee.Geometry object. Defaults to None. bands (list, optional): A list of band names to use in the timelapse. Defaults to None. frequency (str, optional): The frequency of the timeseries. It must be one of the following: 'year', 'month', 'day', 'hour', 'minute', 'second'. Defaults to 'year'. reducer (str, optional): The reducer to use to reduce the collection of images to a single value. It can be one of the following: 'median', 'mean', 'min', 'max', 'variance', 'sum'. Defaults to 'median'. drop_empty (bool, optional): Whether to drop empty images from the timeseries. Defaults to True. date_format (str, optional): A pattern, as described at http://joda-time.sourceforge.net/apidocs/org/joda/time/format/DateTimeFormat.html. Defaults to 'YYYY-MM-dd'. out_gif (str): The output gif file path. Defaults to None. palette (list, optional): A list of colors to render a single-band image in the timelapse. Defaults to None. vis_params (dict, optional): A dictionary of visualization parameters to use in the timelapse. Defaults to None. See more at https://developers.google.com/earth-engine/guides/image_visualization. dimensions (int, optional): a number or pair of numbers (in format 'WIDTHxHEIGHT') Maximum dimensions of the thumbnail to render, in pixels. If only one number is passed, it is used as the maximum, and the other dimension is computed by proportional scaling. Defaults to 768. frames_per_second (int, optional): Animation speed. Defaults to 10. crs (str, optional): The coordinate reference system to use. Defaults to "EPSG:3857". overlay_data (int, str, list, optional): Administrative boundary to be drawn on the timelapse. Defaults to None. overlay_color (str, optional): Color for the overlay data. Can be any color name or hex color code. Defaults to 'black'. overlay_width (int, optional): Width of the overlay. Defaults to 1. overlay_opacity (float, optional): Opacity of the overlay. Defaults to 1.0. title (str, optional): The title of the timelapse. Defaults to None. title_xy (tuple, optional): Lower left corner of the title. It can be formatted like this: (10, 10) or ('15%', '25%'). Defaults to None. add_text (bool, optional): Whether to add animated text to the timelapse. Defaults to True. title_xy (tuple, optional): Lower left corner of the text sequency. It can be formatted like this: (10, 10) or ('15%', '25%'). Defaults to None. text_sequence (int, str, list, optional): Text to be drawn. It can be an integer number, a string, or a list of strings. Defaults to None. font_type (str, optional): Font type. Defaults to "arial.ttf". font_size (int, optional): Font size. Defaults to 20. font_color (str, optional): Font color. It can be a string (e.g., 'red'), rgb tuple (e.g., (255, 127, 0)), or hex code (e.g., '#ff00ff'). Defaults to '#000000'. add_progress_bar (bool, optional): Whether to add a progress bar at the bottom of the GIF. Defaults to True. progress_bar_color (str, optional): Color for the progress bar. Defaults to 'white'. progress_bar_height (int, optional): Height of the progress bar. Defaults to 5. add_colorbar (bool, optional): Whether to add a colorbar to the timelapse. Defaults to False. colorbar_width (float, optional): Width of the colorbar. Defaults to 6.0. colorbar_height (float, optional): Height of the colorbar. Defaults to 0.4. colorbar_label (str, optional): Label for the colorbar. Defaults to None. colorbar_label_size (int, optional): Font size for the colorbar label. Defaults to 12. colorbar_label_weight (str, optional): Font weight for the colorbar label. Defaults to 'normal'. colorbar_tick_size (int, optional): Font size for the colorbar ticks. Defaults to 10. colorbar_bg_color (str, optional): Background color for the colorbar, can be color like "white", "black". Defaults to None. colorbar_orientation (str, optional): Orientation of the colorbar. Defaults to 'horizontal'. colorbar_dpi (str, optional): DPI for the colorbar, can be numbers like 100, 300. Defaults to 'figure'. colorbar_xy (tuple, optional): Lower left corner of the colorbar. It can be formatted like this: (10, 10) or ('15%', '25%'). Defaults to None. colorbar_size (tuple, optional): Size of the colorbar. It can be formatted like this: (300, 300). Defaults to (300, 300). loop (int, optional): Controls how many times the animation repeats. The default, 1, means that the animation will play once and then stop (displaying the last frame). A value of 0 means that the animation will repeat forever. Defaults to 0. mp4 (bool, optional): Whether to create an mp4 file. Defaults to False. fading (int | bool, optional): If True, add fading effect to the timelapse. Defaults to False, no fading. To add fading effect, set it to True (1 second fading duration) or to an integer value (fading duration). parallel_scale (int, optional): A scaling factor used to limit memory use; using a larger parallel_scale (e.g. 2 or 4) may enable computations that run out of memory with the default. Defaults to 1. step (int, optional): The step size to use when creating the date sequence. Defaults to 1. Returns: str: File path to the timelapse gif. """ import geemap.colormaps as cm if not isinstance(collection, ee.ImageCollection): if isinstance(collection, str): collection = ee.ImageCollection(collection) else: raise Exception( "The collection must be an ee.ImageCollection object or asset id." ) col = create_timeseries( collection, start_date, end_date, region=region, bands=bands, frequency=frequency, reducer=reducer, drop_empty=True, date_format=date_format, parallel_scale=parallel_scale, step=step, ) # rename the bands to remove the '_reducer' characters from the band names. col = col.map( lambda img: img.rename( img.bandNames().map(lambda name: ee.String(name).replace(f"_{reducer}", "")) ) ) if out_gif is None: out_gif = temp_file_path(".gif") else: out_gif = check_file_path(out_gif) out_dir = os.path.dirname(out_gif) if bands is None: names = col.first().bandNames().getInfo() if len(names) < 3: bands = [names[0]] else: bands = names[:3][::-1] elif isinstance(bands, str): bands = [bands] elif not isinstance(bands, list): raise Exception("The bands must be a string or a list of strings.") if isinstance(palette, str): palette = cm.get_palette(palette, 15) elif isinstance(palette, list) or isinstance(palette, tuple): pass elif palette is not None: raise Exception("The palette must be a string or a list of strings.") if vis_params is None: img = col.first().select(bands) scale = collection.first().select(0).projection().nominalScale().multiply(10) min_value = min( image_min_value(img, region=region, scale=scale).getInfo().values() ) max_value = max( image_max_value(img, region=region, scale=scale).getInfo().values() ) vis_params = {"bands": bands, "min": min_value, "max": max_value} if len(bands) == 1: if palette is not None: vis_params["palette"] = palette else: vis_params["palette"] = cm.palettes.ndvi elif isinstance(vis_params, dict): if "bands" not in vis_params: vis_params["bands"] = bands if "min" not in vis_params: img = col.first().select(bands) scale = ( collection.first().select(0).projection().nominalScale().multiply(10) ) vis_params["min"] = min( image_min_value(img, region=region, scale=scale).getInfo().values() ) if "max" not in vis_params: img = col.first().select(bands) scale = ( collection.first().select(0).projection().nominalScale().multiply(10) ) vis_params["max"] = max( image_max_value(img, region=region, scale=scale).getInfo().values() ) if palette is None and (len(bands) == 1) and ("palette" not in vis_params): vis_params["palette"] = cm.palettes.ndvi elif palette is not None and ("palette" not in vis_params): vis_params["palette"] = palette if len(bands) > 1 and "palette" in vis_params: del vis_params["palette"] else: raise Exception("The vis_params must be a dictionary.") col = col.select(bands).map( lambda img: img.visualize(**vis_params).set( { "system:time_start": img.get("system:time_start"), "system:date": img.get("system:date"), } ) ) if overlay_data is not None: col = add_overlay( col, overlay_data, overlay_color, overlay_width, overlay_opacity ) video_args = {} video_args["dimensions"] = dimensions video_args["region"] = region video_args["framesPerSecond"] = frames_per_second video_args["crs"] = crs video_args["min"] = 0 video_args["max"] = 255 # if crs is not None: # video_args["crs"] = crs if "palette" in vis_params or len(bands) > 1: video_args["bands"] = ["vis-red", "vis-green", "vis-blue"] else: video_args["bands"] = ["vis-gray"] if ( isinstance(dimensions, int) and dimensions > 768 or isinstance(dimensions, str) and any(dim > 768 for dim in list(map(int, dimensions.split("x")))) ): count = col.size().getInfo() basename = os.path.basename(out_gif)[:-4] names = [ os.path.join( out_dir, f"{basename}_{str(i+1).zfill(int(len(str(count))))}.jpg" ) for i in range(count) ] get_image_collection_thumbnails( col, out_dir, vis_params={ "min": 0, "max": 255, "bands": video_args["bands"], }, dimensions=dimensions, names=names, ) make_gif( names, out_gif, fps=frames_per_second, loop=loop, mp4=False, clean_up=True, ) else: download_ee_video(col, video_args, out_gif) if title is not None and isinstance(title, str): add_text_to_gif( out_gif, out_gif, xy=title_xy, text_sequence=title, font_type=font_type, font_size=font_size, font_color=font_color, add_progress_bar=add_progress_bar, progress_bar_color=progress_bar_color, progress_bar_height=progress_bar_height, duration=1000 / frames_per_second, loop=loop, ) if add_text: if text_sequence is None: text_sequence = col.aggregate_array("system:date").getInfo() add_text_to_gif( out_gif, out_gif, xy=text_xy, text_sequence=text_sequence, font_type=font_type, font_size=font_size, font_color=font_color, add_progress_bar=add_progress_bar, progress_bar_color=progress_bar_color, progress_bar_height=progress_bar_height, duration=1000 / frames_per_second, loop=loop, ) if add_colorbar: colorbar = save_colorbar( None, colorbar_width, colorbar_height, vis_params["min"], vis_params["max"], vis_params["palette"], label=colorbar_label, label_size=colorbar_label_size, label_weight=colorbar_label_weight, tick_size=colorbar_tick_size, bg_color=colorbar_bg_color, orientation=colorbar_orientation, dpi=colorbar_dpi, show_colorbar=False, ) add_image_to_gif(out_gif, out_gif, colorbar, colorbar_xy, colorbar_size) if os.path.exists(out_gif): reduce_gif_size(out_gif) if isinstance(fading, bool): fading = int(fading) if fading > 0: gif_fading(out_gif, out_gif, duration=fading, verbose=False) if mp4: out_mp4 = out_gif.replace(".gif", ".mp4") gif_to_mp4(out_gif, out_mp4) return out_gif def sentinel1_filtering( collection, band="VV", instrumentMode=None, orbitProperties_pass=None, transmitterReceiverPolarisation=None, remove_outliers=True, **kwargs, ): """ Sentinel-1 data is collected with several different instrument configurations, resolutions, band combinations during both ascending and descending orbits. Because of this heterogeneity, it's usually necessary to filter the data down to a homogeneous subset before starting processing. For more details, see https://developers.google.com/earth-engine/guides/sentinel1 Args: collection: A Sentinel1 ImageCollection to filter. band (str): Collection band. Can be one of ['HH','HV','VV','VH']. Defaults to 'VV' which is most commonly available on land. instrumentMode (str, optional): Collection property. Can be one of ['IW','EW','SM']. Defaults to band default availability (IW for ['VV','VH'], EW for ['HH','HV']). IW is typically available for land. EW for icy regions. orbitProperties_pass (str|None, optional): Collection property. Can be one of ['ASCENDING', 'DESCENDING', None]. Default to 'ASCENDING'. Will return mixed property if set to None, which dampen elevation, and increase surface roughness/fractality visibility. transmitterReceiverPolarisation: Collection property List contains this value. Can be one of ['HH','HV','VV','VH']. Defaults to band. remove_outliers (bool, optional): Remove pixels with extreme values (< -30). These can occur near the edge of an image. Default to True. **kwargs (dict, optional): All other arguments will be applied as filters to collection properties. F.e. {'resolution_meters':10} Full list properties: https://developers.google.com/earth-engine/datasets/catalog/COPERNICUS_S1_GRD#image-properties Returns: object: Returns a homogeneous ImageCollection of Sentinel 1 images. """ transmitterReceiverPolarisation = transmitterReceiverPolarisation or band instrumentMode = ( instrumentMode or {"VV": "IW", "VH": "IW", "HH": "EW", "HV": "EW"}[band] ) def remove_outliers(image): if not remove_outliers: return image edge = image.select(band).lt(-30.0) maskedimage = image.mask().And(edge.Not()) return image.updateMask(maskedimage) col = ( collection.filter(ee.Filter.eq("instrumentMode", instrumentMode)) .filter( ee.Filter.listContains( "transmitterReceiverPolarisation", transmitterReceiverPolarisation ) ) .map(remove_outliers) ) for k, v in kwargs.items(): col = col.filter(ee.Filter.eq(k, v)) if orbitProperties_pass: col = col.filter(ee.Filter.eq("orbitProperties_pass", orbitProperties_pass)) return col import datetime import ee The provided code snippet includes necessary dependencies for implementing the `sentinel1_timelapse` function. Write a Python function `def sentinel1_timelapse( roi, out_gif=None, start_year=2015, end_year=None, start_date="01-01", end_date="12-31", bands=["VV"], frequency="year", reducer="median", date_format=None, palette="Greys", vis_params=None, dimensions=768, frames_per_second=10, crs="EPSG:3857", overlay_data=None, overlay_color="black", overlay_width=1, overlay_opacity=1.0, title=None, title_xy=("2%", "90%"), add_text=True, text_xy=("2%", "2%"), text_sequence=None, font_type="arial.ttf", font_size=20, font_color="white", add_progress_bar=True, progress_bar_color="white", progress_bar_height=5, add_colorbar=False, colorbar_width=6.0, colorbar_height=0.4, colorbar_label=None, colorbar_label_size=12, colorbar_label_weight="normal", colorbar_tick_size=10, colorbar_bg_color=None, colorbar_orientation="horizontal", colorbar_dpi="figure", colorbar_xy=None, colorbar_size=(300, 300), loop=0, mp4=False, fading=False, **kwargs, )` to solve the following problem: Create a timelapse from any ee.ImageCollection. Args: roi (ee.Geometry, optional): The region to use to filter the collection of images. It must be an ee.Geometry object. Defaults to None. out_gif (str): The output gif file path. Defaults to None. start_year (int, optional): Starting year for the timelapse. Defaults to 2015. end_year (int, optional): Ending year for the timelapse. Defaults to the current year. start_date (str, optional): Starting date (month-day) each year for filtering ImageCollection. Defaults to '01-01'. end_date (str, optional): Ending date (month-day) each year for filtering ImageCollection. Defaults to '12-31'. bands (list, optional): A list of band names to use in the timelapse. Can be one of ['VV'],['HV'],['VH'],['HH'],['VV','VH'] or ['HH','HV'] frequency (str, optional): The frequency of the timeseries. It must be one of the following: 'year', 'month', 'day', 'hour', 'minute', 'second'. Defaults to 'year'. reducer (str, optional): The reducer to use to reduce the collection of images to a single value. It can be one of the following: 'median', 'mean', 'min', 'max', 'variance', 'sum'. Defaults to 'median'. drop_empty (bool, optional): Whether to drop empty images from the timeseries. Defaults to True. date_format (str, optional): A pattern, as described at http://joda-time.sourceforge.net/apidocs/org/joda/time/format/DateTimeFormat.html. Defaults to 'YYYY-MM-dd'. palette (list, optional): A list of colors to render a single-band image in the timelapse. Defaults to None. vis_params (dict, optional): A dictionary of visualization parameters to use in the timelapse. Defaults to None. See more at https://developers.google.com/earth-engine/guides/image_visualization. dimensions (int, optional): a number or pair of numbers (in format 'WIDTHxHEIGHT') Maximum dimensions of the thumbnail to render, in pixels. If only one number is passed, it is used as the maximum, and the other dimension is computed by proportional scaling. Defaults to 768. frames_per_second (int, optional): Animation speed. Defaults to 10. crs (str, optional): The coordinate reference system to use. Defaults to "EPSG:3857". overlay_data (int, str, list, optional): Administrative boundary to be drawn on the timelapse. Defaults to None. overlay_color (str, optional): Color for the overlay data. Can be any color name or hex color code. Defaults to 'black'. overlay_width (int, optional): Width of the overlay. Defaults to 1. overlay_opacity (float, optional): Opacity of the overlay. Defaults to 1.0. title (str, optional): The title of the timelapse. Defaults to None. title_xy (tuple, optional): Lower left corner of the title. It can be formatted like this: (10, 10) or ('15%', '25%'). Defaults to None. add_text (bool, optional): Whether to add animated text to the timelapse. Defaults to True. title_xy (tuple, optional): Lower left corner of the text sequency. It can be formatted like this: (10, 10) or ('15%', '25%'). Defaults to None. text_sequence (int, str, list, optional): Text to be drawn. It can be an integer number, a string, or a list of strings. Defaults to None. font_type (str, optional): Font type. Defaults to "arial.ttf". font_size (int, optional): Font size. Defaults to 20. font_color (str, optional): Font color. It can be a string (e.g., 'red'), rgb tuple (e.g., (255, 127, 0)), or hex code (e.g., '#ff00ff'). Defaults to '#000000'. add_progress_bar (bool, optional): Whether to add a progress bar at the bottom of the GIF. Defaults to True. progress_bar_color (str, optional): Color for the progress bar. Defaults to 'white'. progress_bar_height (int, optional): Height of the progress bar. Defaults to 5. add_colorbar (bool, optional): Whether to add a colorbar to the timelapse. Defaults to False. colorbar_width (float, optional): Width of the colorbar. Defaults to 6.0. colorbar_height (float, optional): Height of the colorbar. Defaults to 0.4. colorbar_label (str, optional): Label for the colorbar. Defaults to None. colorbar_label_size (int, optional): Font size for the colorbar label. Defaults to 12. colorbar_label_weight (str, optional): Font weight for the colorbar label. Defaults to 'normal'. colorbar_tick_size (int, optional): Font size for the colorbar ticks. Defaults to 10. colorbar_bg_color (str, optional): Background color for the colorbar, can be color like "white", "black". Defaults to None. colorbar_orientation (str, optional): Orientation of the colorbar. Defaults to 'horizontal'. colorbar_dpi (str, optional): DPI for the colorbar, can be numbers like 100, 300. Defaults to 'figure'. colorbar_xy (tuple, optional): Lower left corner of the colorbar. It can be formatted like this: (10, 10) or ('15%', '25%'). Defaults to None. colorbar_size (tuple, optional): Size of the colorbar. It can be formatted like this: (300, 300). Defaults to (300, 300). loop (int, optional): Controls how many times the animation repeats. The default, 1, means that the animation will play once and then stop (displaying the last frame). A value of 0 means that the animation will repeat forever. Defaults to 0. mp4 (bool, optional): Whether to create an mp4 file. Defaults to False. fading (int | bool, optional): If True, add fading effect to the timelapse. Defaults to False, no fading. To add fading effect, set it to True (1 second fading duration) or to an integer value (fading duration). **kwargs: Arguments for sentinel1_filtering(). Same filters will be applied to all bands. Returns: str: File path to the timelapse gif. Here is the function: def sentinel1_timelapse( roi, out_gif=None, start_year=2015, end_year=None, start_date="01-01", end_date="12-31", bands=["VV"], frequency="year", reducer="median", date_format=None, palette="Greys", vis_params=None, dimensions=768, frames_per_second=10, crs="EPSG:3857", overlay_data=None, overlay_color="black", overlay_width=1, overlay_opacity=1.0, title=None, title_xy=("2%", "90%"), add_text=True, text_xy=("2%", "2%"), text_sequence=None, font_type="arial.ttf", font_size=20, font_color="white", add_progress_bar=True, progress_bar_color="white", progress_bar_height=5, add_colorbar=False, colorbar_width=6.0, colorbar_height=0.4, colorbar_label=None, colorbar_label_size=12, colorbar_label_weight="normal", colorbar_tick_size=10, colorbar_bg_color=None, colorbar_orientation="horizontal", colorbar_dpi="figure", colorbar_xy=None, colorbar_size=(300, 300), loop=0, mp4=False, fading=False, **kwargs, ): """Create a timelapse from any ee.ImageCollection. Args: roi (ee.Geometry, optional): The region to use to filter the collection of images. It must be an ee.Geometry object. Defaults to None. out_gif (str): The output gif file path. Defaults to None. start_year (int, optional): Starting year for the timelapse. Defaults to 2015. end_year (int, optional): Ending year for the timelapse. Defaults to the current year. start_date (str, optional): Starting date (month-day) each year for filtering ImageCollection. Defaults to '01-01'. end_date (str, optional): Ending date (month-day) each year for filtering ImageCollection. Defaults to '12-31'. bands (list, optional): A list of band names to use in the timelapse. Can be one of ['VV'],['HV'],['VH'],['HH'],['VV','VH'] or ['HH','HV'] frequency (str, optional): The frequency of the timeseries. It must be one of the following: 'year', 'month', 'day', 'hour', 'minute', 'second'. Defaults to 'year'. reducer (str, optional): The reducer to use to reduce the collection of images to a single value. It can be one of the following: 'median', 'mean', 'min', 'max', 'variance', 'sum'. Defaults to 'median'. drop_empty (bool, optional): Whether to drop empty images from the timeseries. Defaults to True. date_format (str, optional): A pattern, as described at http://joda-time.sourceforge.net/apidocs/org/joda/time/format/DateTimeFormat.html. Defaults to 'YYYY-MM-dd'. palette (list, optional): A list of colors to render a single-band image in the timelapse. Defaults to None. vis_params (dict, optional): A dictionary of visualization parameters to use in the timelapse. Defaults to None. See more at https://developers.google.com/earth-engine/guides/image_visualization. dimensions (int, optional): a number or pair of numbers (in format 'WIDTHxHEIGHT') Maximum dimensions of the thumbnail to render, in pixels. If only one number is passed, it is used as the maximum, and the other dimension is computed by proportional scaling. Defaults to 768. frames_per_second (int, optional): Animation speed. Defaults to 10. crs (str, optional): The coordinate reference system to use. Defaults to "EPSG:3857". overlay_data (int, str, list, optional): Administrative boundary to be drawn on the timelapse. Defaults to None. overlay_color (str, optional): Color for the overlay data. Can be any color name or hex color code. Defaults to 'black'. overlay_width (int, optional): Width of the overlay. Defaults to 1. overlay_opacity (float, optional): Opacity of the overlay. Defaults to 1.0. title (str, optional): The title of the timelapse. Defaults to None. title_xy (tuple, optional): Lower left corner of the title. It can be formatted like this: (10, 10) or ('15%', '25%'). Defaults to None. add_text (bool, optional): Whether to add animated text to the timelapse. Defaults to True. title_xy (tuple, optional): Lower left corner of the text sequency. It can be formatted like this: (10, 10) or ('15%', '25%'). Defaults to None. text_sequence (int, str, list, optional): Text to be drawn. It can be an integer number, a string, or a list of strings. Defaults to None. font_type (str, optional): Font type. Defaults to "arial.ttf". font_size (int, optional): Font size. Defaults to 20. font_color (str, optional): Font color. It can be a string (e.g., 'red'), rgb tuple (e.g., (255, 127, 0)), or hex code (e.g., '#ff00ff'). Defaults to '#000000'. add_progress_bar (bool, optional): Whether to add a progress bar at the bottom of the GIF. Defaults to True. progress_bar_color (str, optional): Color for the progress bar. Defaults to 'white'. progress_bar_height (int, optional): Height of the progress bar. Defaults to 5. add_colorbar (bool, optional): Whether to add a colorbar to the timelapse. Defaults to False. colorbar_width (float, optional): Width of the colorbar. Defaults to 6.0. colorbar_height (float, optional): Height of the colorbar. Defaults to 0.4. colorbar_label (str, optional): Label for the colorbar. Defaults to None. colorbar_label_size (int, optional): Font size for the colorbar label. Defaults to 12. colorbar_label_weight (str, optional): Font weight for the colorbar label. Defaults to 'normal'. colorbar_tick_size (int, optional): Font size for the colorbar ticks. Defaults to 10. colorbar_bg_color (str, optional): Background color for the colorbar, can be color like "white", "black". Defaults to None. colorbar_orientation (str, optional): Orientation of the colorbar. Defaults to 'horizontal'. colorbar_dpi (str, optional): DPI for the colorbar, can be numbers like 100, 300. Defaults to 'figure'. colorbar_xy (tuple, optional): Lower left corner of the colorbar. It can be formatted like this: (10, 10) or ('15%', '25%'). Defaults to None. colorbar_size (tuple, optional): Size of the colorbar. It can be formatted like this: (300, 300). Defaults to (300, 300). loop (int, optional): Controls how many times the animation repeats. The default, 1, means that the animation will play once and then stop (displaying the last frame). A value of 0 means that the animation will repeat forever. Defaults to 0. mp4 (bool, optional): Whether to create an mp4 file. Defaults to False. fading (int | bool, optional): If True, add fading effect to the timelapse. Defaults to False, no fading. To add fading effect, set it to True (1 second fading duration) or to an integer value (fading duration). **kwargs: Arguments for sentinel1_filtering(). Same filters will be applied to all bands. Returns: str: File path to the timelapse gif. """ from datetime import date assert bands in ( ["VV"], ["VH"], ["HH"], ["HV"], ["VV", "VH"], ["HH", "HV"], ["VH", "VV"], ["HV", "HH"], ), "Not all Sentinel1 bands are available together." if bands in (["VH", "VV"], ["HV", "HH"]): bands[0], bands[1] = bands[1], bands[0] band = bands[0] if end_year is None: end_year = date.today().year start = f"{start_year}-{start_date}" end = f"{end_year}-{end_date}" if vis_params is None: vis_params = {"min": -30, "max": 0} collection = ( ee.ImageCollection("COPERNICUS/S1_GRD").filterDate(start, end).filterBounds(roi) ) collection = sentinel1_filtering(collection, band, **kwargs) return create_timelapse( collection, start, end, roi, bands, frequency, reducer, date_format, out_gif, palette, vis_params, dimensions, frames_per_second, crs, overlay_data, overlay_color, overlay_width, overlay_opacity, title, title_xy, add_text, text_xy, text_sequence, font_type, font_size, font_color, add_progress_bar, progress_bar_color, progress_bar_height, add_colorbar, colorbar_width, colorbar_height, colorbar_label, colorbar_label_size, colorbar_label_weight, colorbar_tick_size, colorbar_bg_color, colorbar_orientation, colorbar_dpi, colorbar_xy, colorbar_size, loop, mp4, fading, )
Create a timelapse from any ee.ImageCollection. Args: roi (ee.Geometry, optional): The region to use to filter the collection of images. It must be an ee.Geometry object. Defaults to None. out_gif (str): The output gif file path. Defaults to None. start_year (int, optional): Starting year for the timelapse. Defaults to 2015. end_year (int, optional): Ending year for the timelapse. Defaults to the current year. start_date (str, optional): Starting date (month-day) each year for filtering ImageCollection. Defaults to '01-01'. end_date (str, optional): Ending date (month-day) each year for filtering ImageCollection. Defaults to '12-31'. bands (list, optional): A list of band names to use in the timelapse. Can be one of ['VV'],['HV'],['VH'],['HH'],['VV','VH'] or ['HH','HV'] frequency (str, optional): The frequency of the timeseries. It must be one of the following: 'year', 'month', 'day', 'hour', 'minute', 'second'. Defaults to 'year'. reducer (str, optional): The reducer to use to reduce the collection of images to a single value. It can be one of the following: 'median', 'mean', 'min', 'max', 'variance', 'sum'. Defaults to 'median'. drop_empty (bool, optional): Whether to drop empty images from the timeseries. Defaults to True. date_format (str, optional): A pattern, as described at http://joda-time.sourceforge.net/apidocs/org/joda/time/format/DateTimeFormat.html. Defaults to 'YYYY-MM-dd'. palette (list, optional): A list of colors to render a single-band image in the timelapse. Defaults to None. vis_params (dict, optional): A dictionary of visualization parameters to use in the timelapse. Defaults to None. See more at https://developers.google.com/earth-engine/guides/image_visualization. dimensions (int, optional): a number or pair of numbers (in format 'WIDTHxHEIGHT') Maximum dimensions of the thumbnail to render, in pixels. If only one number is passed, it is used as the maximum, and the other dimension is computed by proportional scaling. Defaults to 768. frames_per_second (int, optional): Animation speed. Defaults to 10. crs (str, optional): The coordinate reference system to use. Defaults to "EPSG:3857". overlay_data (int, str, list, optional): Administrative boundary to be drawn on the timelapse. Defaults to None. overlay_color (str, optional): Color for the overlay data. Can be any color name or hex color code. Defaults to 'black'. overlay_width (int, optional): Width of the overlay. Defaults to 1. overlay_opacity (float, optional): Opacity of the overlay. Defaults to 1.0. title (str, optional): The title of the timelapse. Defaults to None. title_xy (tuple, optional): Lower left corner of the title. It can be formatted like this: (10, 10) or ('15%', '25%'). Defaults to None. add_text (bool, optional): Whether to add animated text to the timelapse. Defaults to True. title_xy (tuple, optional): Lower left corner of the text sequency. It can be formatted like this: (10, 10) or ('15%', '25%'). Defaults to None. text_sequence (int, str, list, optional): Text to be drawn. It can be an integer number, a string, or a list of strings. Defaults to None. font_type (str, optional): Font type. Defaults to "arial.ttf". font_size (int, optional): Font size. Defaults to 20. font_color (str, optional): Font color. It can be a string (e.g., 'red'), rgb tuple (e.g., (255, 127, 0)), or hex code (e.g., '#ff00ff'). Defaults to '#000000'. add_progress_bar (bool, optional): Whether to add a progress bar at the bottom of the GIF. Defaults to True. progress_bar_color (str, optional): Color for the progress bar. Defaults to 'white'. progress_bar_height (int, optional): Height of the progress bar. Defaults to 5. add_colorbar (bool, optional): Whether to add a colorbar to the timelapse. Defaults to False. colorbar_width (float, optional): Width of the colorbar. Defaults to 6.0. colorbar_height (float, optional): Height of the colorbar. Defaults to 0.4. colorbar_label (str, optional): Label for the colorbar. Defaults to None. colorbar_label_size (int, optional): Font size for the colorbar label. Defaults to 12. colorbar_label_weight (str, optional): Font weight for the colorbar label. Defaults to 'normal'. colorbar_tick_size (int, optional): Font size for the colorbar ticks. Defaults to 10. colorbar_bg_color (str, optional): Background color for the colorbar, can be color like "white", "black". Defaults to None. colorbar_orientation (str, optional): Orientation of the colorbar. Defaults to 'horizontal'. colorbar_dpi (str, optional): DPI for the colorbar, can be numbers like 100, 300. Defaults to 'figure'. colorbar_xy (tuple, optional): Lower left corner of the colorbar. It can be formatted like this: (10, 10) or ('15%', '25%'). Defaults to None. colorbar_size (tuple, optional): Size of the colorbar. It can be formatted like this: (300, 300). Defaults to (300, 300). loop (int, optional): Controls how many times the animation repeats. The default, 1, means that the animation will play once and then stop (displaying the last frame). A value of 0 means that the animation will repeat forever. Defaults to 0. mp4 (bool, optional): Whether to create an mp4 file. Defaults to False. fading (int | bool, optional): If True, add fading effect to the timelapse. Defaults to False, no fading. To add fading effect, set it to True (1 second fading duration) or to an integer value (fading duration). **kwargs: Arguments for sentinel1_filtering(). Same filters will be applied to all bands. Returns: str: File path to the timelapse gif.
12,192
import datetime import glob import io import os import shutil import ee from .common import * from typing import Union, List def gif_to_mp4(in_gif, out_mp4): """Converts a gif to mp4. Args: in_gif (str): The input gif file. out_mp4 (str): The output mp4 file. """ from PIL import Image if not os.path.exists(in_gif): raise FileNotFoundError(f"{in_gif} does not exist.") out_mp4 = os.path.abspath(out_mp4) if not out_mp4.endswith(".mp4"): out_mp4 = out_mp4 + ".mp4" if not os.path.exists(os.path.dirname(out_mp4)): os.makedirs(os.path.dirname(out_mp4)) if not is_tool("ffmpeg"): print("ffmpeg is not installed on your computer.") return width, height = Image.open(in_gif).size if width % 2 == 0 and height % 2 == 0: cmd = f"ffmpeg -loglevel error -i {in_gif} -vcodec libx264 -crf 25 -pix_fmt yuv420p {out_mp4}" os.system(cmd) else: width += width % 2 height += height % 2 cmd = f"ffmpeg -loglevel error -i {in_gif} -vf scale={width}:{height} -vcodec libx264 -crf 25 -pix_fmt yuv420p {out_mp4}" os.system(cmd) if not os.path.exists(out_mp4): raise Exception(f"Failed to create mp4 file.") def add_progress_bar_to_gif( in_gif, out_gif, progress_bar_color="blue", progress_bar_height=5, duration=100, loop=0, ): """Adds a progress bar to a GIF image. Args: in_gif (str): The file path to the input GIF image. out_gif (str): The file path to the output GIF image. progress_bar_color (str, optional): Color for the progress bar. Defaults to 'white'. progress_bar_height (int, optional): Height of the progress bar. Defaults to 5. duration (int, optional): controls how long each frame will be displayed for, in milliseconds. It is the inverse of the frame rate. Setting it to 100 milliseconds gives 10 frames per second. You can decrease the duration to give a smoother animation.. Defaults to 100. loop (int, optional): controls how many times the animation repeats. The default, 1, means that the animation will play once and then stop (displaying the last frame). A value of 0 means that the animation will repeat forever. Defaults to 0. """ import io import warnings from PIL import Image, ImageDraw, ImageSequence warnings.simplefilter("ignore") in_gif = os.path.abspath(in_gif) out_gif = os.path.abspath(out_gif) if not os.path.exists(in_gif): print("The input gif file does not exist.") return if not os.path.exists(os.path.dirname(out_gif)): os.makedirs(os.path.dirname(out_gif)) progress_bar_color = check_color(progress_bar_color) try: image = Image.open(in_gif) except Exception as e: raise Exception("An error occurred while opening the gif.") count = image.n_frames W, H = image.size progress_bar_widths = [i * 1.0 / count * W for i in range(1, count + 1)] progress_bar_shapes = [ [(0, H - progress_bar_height), (x, H)] for x in progress_bar_widths ] try: frames = [] # Loop over each frame in the animated image for index, frame in enumerate(ImageSequence.Iterator(image)): # Draw the text on the frame frame = frame.convert("RGB") draw = ImageDraw.Draw(frame) # w, h = draw.textsize(text[index]) draw.rectangle(progress_bar_shapes[index], fill=progress_bar_color) del draw b = io.BytesIO() frame.save(b, format="GIF") frame = Image.open(b) frames.append(frame) # https://www.pythoninformer.com/python-libraries/pillow/creating-animated-gif/ # Save the frames as a new image frames[0].save( out_gif, save_all=True, append_images=frames[1:], duration=duration, loop=loop, optimize=True, ) except Exception as e: raise Exception(e) import os import shutil def png_to_gif(in_dir, out_gif, fps=10, loop=0): """Convert a list of png images to gif. Args: in_dir (str): The input directory containing png images. out_gif (str): The output file path to the gif. fps (int, optional): Frames per second. Defaults to 10. loop (bool, optional): controls how many times the animation repeats. 1 means that the animation will play once and then stop (displaying the last frame). A value of 0 means that the animation will repeat forever. Defaults to 0. Raises: FileNotFoundError: No png images could be found. """ import glob from PIL import Image if not out_gif.endswith(".gif"): raise ValueError("The out_gif must be a gif file.") out_gif = os.path.abspath(out_gif) out_dir = os.path.dirname(out_gif) if not os.path.exists(out_dir): os.makedirs(out_dir) # Create the frames frames = [] imgs = list(glob.glob(os.path.join(in_dir, "*.png"))) imgs.sort() if len(imgs) == 0: raise FileNotFoundError(f"No png could be found in {in_dir}.") for i in imgs: new_frame = Image.open(i) frames.append(new_frame) # Save into a GIF file that loops forever frames[0].save( out_gif, format="GIF", append_images=frames[1:], save_all=True, duration=1000 / fps, loop=loop, ) The provided code snippet includes necessary dependencies for implementing the `vector_to_gif` function. Write a Python function `def vector_to_gif( filename, out_gif, colname, vmin=None, vmax=None, step=1, facecolor="black", figsize=(10, 8), padding=3, title=None, add_text=True, xy=("1%", "1%"), fontsize=20, add_progress_bar=True, progress_bar_color="blue", progress_bar_height=5, dpi=300, fps=10, loop=0, mp4=False, keep_png=False, verbose=True, open_args={}, plot_args={}, )` to solve the following problem: Convert a vector to a gif. This function was inspired by by Johannes Uhl's shapefile2gif repo at https://github.com/johannesuhl/shapefile2gif. Credits to Johannes Uhl. Args: filename (str): The input vector file. Can be a directory path or http URL, e.g., "https://i.imgur.com/ZWSZC5z.gif" out_gif (str): The output gif file. colname (str): The column name of the vector that contains numerical values. vmin (float, optional): The minimum value to filter the data. Defaults to None. vmax (float, optional): The maximum value to filter the data. Defaults to None. step (float, optional): The step to filter the data. Defaults to 1. facecolor (str, optional): The color to visualize the data. Defaults to "black". figsize (tuple, optional): The figure size. Defaults to (10, 8). padding (int, optional): The padding of the figure tight_layout. Defaults to 3. title (str, optional): The title of the figure. Defaults to None. add_text (bool, optional): Whether to add text to the figure. Defaults to True. xy (tuple, optional): The position of the text from the lower-left corner. Defaults to ("1%", "1%"). fontsize (int, optional): The font size of the text. Defaults to 20. add_progress_bar (bool, optional): Whether to add a progress bar to the figure. Defaults to True. progress_bar_color (str, optional): The color of the progress bar. Defaults to "blue". progress_bar_height (int, optional): The height of the progress bar. Defaults to 5. dpi (int, optional): The dpi of the figure. Defaults to 300. fps (int, optional): The frames per second (fps) of the gif. Defaults to 10. loop (int, optional): The number of loops of the gif. Defaults to 0, infinite loop. mp4 (bool, optional): Whether to convert the gif to mp4. Defaults to False. keep_png (bool, optional): Whether to keep the png files. Defaults to False. verbose (bool, optional): Whether to print the progress. Defaults to True. open_args (dict, optional): The arguments for the geopandas.read_file() function. Defaults to {}. plot_args (dict, optional): The arguments for the geopandas.GeoDataFrame.plot() function. Defaults to {}. Here is the function: def vector_to_gif( filename, out_gif, colname, vmin=None, vmax=None, step=1, facecolor="black", figsize=(10, 8), padding=3, title=None, add_text=True, xy=("1%", "1%"), fontsize=20, add_progress_bar=True, progress_bar_color="blue", progress_bar_height=5, dpi=300, fps=10, loop=0, mp4=False, keep_png=False, verbose=True, open_args={}, plot_args={}, ): """Convert a vector to a gif. This function was inspired by by Johannes Uhl's shapefile2gif repo at https://github.com/johannesuhl/shapefile2gif. Credits to Johannes Uhl. Args: filename (str): The input vector file. Can be a directory path or http URL, e.g., "https://i.imgur.com/ZWSZC5z.gif" out_gif (str): The output gif file. colname (str): The column name of the vector that contains numerical values. vmin (float, optional): The minimum value to filter the data. Defaults to None. vmax (float, optional): The maximum value to filter the data. Defaults to None. step (float, optional): The step to filter the data. Defaults to 1. facecolor (str, optional): The color to visualize the data. Defaults to "black". figsize (tuple, optional): The figure size. Defaults to (10, 8). padding (int, optional): The padding of the figure tight_layout. Defaults to 3. title (str, optional): The title of the figure. Defaults to None. add_text (bool, optional): Whether to add text to the figure. Defaults to True. xy (tuple, optional): The position of the text from the lower-left corner. Defaults to ("1%", "1%"). fontsize (int, optional): The font size of the text. Defaults to 20. add_progress_bar (bool, optional): Whether to add a progress bar to the figure. Defaults to True. progress_bar_color (str, optional): The color of the progress bar. Defaults to "blue". progress_bar_height (int, optional): The height of the progress bar. Defaults to 5. dpi (int, optional): The dpi of the figure. Defaults to 300. fps (int, optional): The frames per second (fps) of the gif. Defaults to 10. loop (int, optional): The number of loops of the gif. Defaults to 0, infinite loop. mp4 (bool, optional): Whether to convert the gif to mp4. Defaults to False. keep_png (bool, optional): Whether to keep the png files. Defaults to False. verbose (bool, optional): Whether to print the progress. Defaults to True. open_args (dict, optional): The arguments for the geopandas.read_file() function. Defaults to {}. plot_args (dict, optional): The arguments for the geopandas.GeoDataFrame.plot() function. Defaults to {}. """ import geopandas as gpd import matplotlib.pyplot as plt out_dir = os.path.dirname(out_gif) tmp_dir = os.path.join(out_dir, "tmp_png") if not os.path.exists(tmp_dir): os.makedirs(tmp_dir) if isinstance(filename, str): gdf = gpd.read_file(filename, **open_args) elif isinstance(filename, gpd.GeoDataFrame): gdf = filename else: raise ValueError( "filename must be a string or a geopandas.GeoDataFrame object." ) bbox = gdf.total_bounds if colname not in gdf.columns: raise Exception( f"{colname} is not in the columns of the GeoDataFrame. It must be one of {gdf.columns}" ) values = gdf[colname].unique().tolist() values.sort() if vmin is None: vmin = values[0] if vmax is None: vmax = values[-1] options = range(vmin, vmax + step, step) W = bbox[2] - bbox[0] H = bbox[3] - bbox[1] if xy is None: # default text location is 5% width and 5% height of the image. xy = (int(0.05 * W), int(0.05 * H)) elif (xy is not None) and (not isinstance(xy, tuple)) and (len(xy) == 2): raise Exception("xy must be a tuple, e.g., (10, 10), ('10%', '10%')") elif all(isinstance(item, int) for item in xy) and (len(xy) == 2): x, y = xy if (x > 0) and (x < W) and (y > 0) and (y < H): pass else: print( f"xy is out of bounds. x must be within [0, {W}], and y must be within [0, {H}]" ) return elif all(isinstance(item, str) for item in xy) and (len(xy) == 2): x, y = xy if ("%" in x) and ("%" in y): try: x = float(x.replace("%", "")) / 100.0 * W y = float(y.replace("%", "")) / 100.0 * H except Exception: raise Exception( "The specified xy is invalid. It must be formatted like this ('10%', '10%')" ) else: raise Exception( "The specified xy is invalid. It must be formatted like this: (10, 10) or ('10%', '10%')" ) x = bbox[0] + x y = bbox[1] + y for index, v in enumerate(options): if verbose: print(f"Processing {index+1}/{len(options)}: {v}...") yrdf = gdf[gdf[colname] <= v] fig, ax = plt.subplots() ax = yrdf.plot(facecolor=facecolor, figsize=figsize, **plot_args) ax.set_title(title, fontsize=fontsize) ax.set_axis_off() ax.set_xlim([bbox[0], bbox[2]]) ax.set_ylim([bbox[1], bbox[3]]) if add_text: ax.text(x, y, v, fontsize=fontsize) fig = ax.get_figure() plt.tight_layout(pad=padding) fig.savefig(tmp_dir + os.sep + "%s.png" % v, dpi=dpi) plt.clf() plt.close("all") png_to_gif(tmp_dir, out_gif, fps=fps, loop=loop) if add_progress_bar: add_progress_bar_to_gif( out_gif, out_gif, progress_bar_color, progress_bar_height, duration=1000 / fps, loop=loop, ) if mp4: gif_to_mp4(out_gif, out_gif.replace(".gif", ".mp4")) if not keep_png: shutil.rmtree(tmp_dir) if verbose: print(f"Done. The GIF is saved to {out_gif}.")
Convert a vector to a gif. This function was inspired by by Johannes Uhl's shapefile2gif repo at https://github.com/johannesuhl/shapefile2gif. Credits to Johannes Uhl. Args: filename (str): The input vector file. Can be a directory path or http URL, e.g., "https://i.imgur.com/ZWSZC5z.gif" out_gif (str): The output gif file. colname (str): The column name of the vector that contains numerical values. vmin (float, optional): The minimum value to filter the data. Defaults to None. vmax (float, optional): The maximum value to filter the data. Defaults to None. step (float, optional): The step to filter the data. Defaults to 1. facecolor (str, optional): The color to visualize the data. Defaults to "black". figsize (tuple, optional): The figure size. Defaults to (10, 8). padding (int, optional): The padding of the figure tight_layout. Defaults to 3. title (str, optional): The title of the figure. Defaults to None. add_text (bool, optional): Whether to add text to the figure. Defaults to True. xy (tuple, optional): The position of the text from the lower-left corner. Defaults to ("1%", "1%"). fontsize (int, optional): The font size of the text. Defaults to 20. add_progress_bar (bool, optional): Whether to add a progress bar to the figure. Defaults to True. progress_bar_color (str, optional): The color of the progress bar. Defaults to "blue". progress_bar_height (int, optional): The height of the progress bar. Defaults to 5. dpi (int, optional): The dpi of the figure. Defaults to 300. fps (int, optional): The frames per second (fps) of the gif. Defaults to 10. loop (int, optional): The number of loops of the gif. Defaults to 0, infinite loop. mp4 (bool, optional): Whether to convert the gif to mp4. Defaults to False. keep_png (bool, optional): Whether to keep the png files. Defaults to False. verbose (bool, optional): Whether to print the progress. Defaults to True. open_args (dict, optional): The arguments for the geopandas.read_file() function. Defaults to {}. plot_args (dict, optional): The arguments for the geopandas.GeoDataFrame.plot() function. Defaults to {}.
12,193
import json import os import shutil import urllib.request from pathlib import Path import ipywidgets as widgets import pkg_resources from box import Box from IPython.display import display from .common import download_from_url, ee_data_html, search_ee_data def get_data_csv(): """Gets the file path to the CSV file containing the information about the Earth Engine Data Catalog. Returns: str: File path to the CSV file. """ pkg_dir = os.path.dirname(pkg_resources.resource_filename("geemap", "geemap.py")) template_dir = os.path.join(pkg_dir, "data/template") data_csv = os.path.join(template_dir, "ee_data_catalog.csv") return data_csv def download_from_url(url, out_file_name=None, out_dir=".", unzip=True, verbose=True): """Download a file from a URL (e.g., https://github.com/giswqs/whitebox/raw/master/examples/testdata.zip) Args: url (str): The HTTP URL to download. out_file_name (str, optional): The output file name to use. Defaults to None. out_dir (str, optional): The output directory to use. Defaults to '.'. unzip (bool, optional): Whether to unzip the downloaded file if it is a zip file. Defaults to True. verbose (bool, optional): Whether to display or not the output of the function """ in_file_name = os.path.basename(url) if out_file_name is None: out_file_name = in_file_name out_file_path = os.path.join(os.path.abspath(out_dir), out_file_name) if verbose: print(f"Downloading {url} ...") try: urllib.request.urlretrieve(url, out_file_path) except Exception: raise Exception("The URL is invalid. Please double check the URL.") final_path = out_file_path if unzip: # if it is a zip file if ".zip" in out_file_name: if verbose: print(f"Unzipping {out_file_name} ...") with zipfile.ZipFile(out_file_path, "r") as zip_ref: zip_ref.extractall(out_dir) final_path = os.path.join( os.path.abspath(out_dir), out_file_name.replace(".zip", "") ) # if it is a tar file if ".tar" in out_file_name: if verbose: print(f"Unzipping {out_file_name} ...") with tarfile.open(out_file_path, "r") as tar_ref: with tarfile.open(out_file_path, "r") as tar_ref: def is_within_directory(directory, target): abs_directory = os.path.abspath(directory) abs_target = os.path.abspath(target) prefix = os.path.commonprefix([abs_directory, abs_target]) return prefix == abs_directory def safe_extract( tar, path=".", members=None, *, numeric_owner=False ): for member in tar.getmembers(): member_path = os.path.join(path, member.name) if not is_within_directory(path, member_path): raise Exception("Attempted Path Traversal in Tar File") tar.extractall(path, members, numeric_owner=numeric_owner) safe_extract(tar_ref, out_dir) final_path = os.path.join( os.path.abspath(out_dir), out_file_name.replace(".tar", "") ) if verbose: print(f"Data downloaded to: {final_path}") return The provided code snippet includes necessary dependencies for implementing the `update_data_list` function. Write a Python function `def update_data_list(out_dir=".")` to solve the following problem: Updates the Earth Engine Data Catalog dataset list. Args: out_dir (str, optional): The output directory to save the GitHub repository. Defaults to ".". Raises: Exception: If the CSV file fails to save. Here is the function: def update_data_list(out_dir="."): """Updates the Earth Engine Data Catalog dataset list. Args: out_dir (str, optional): The output directory to save the GitHub repository. Defaults to ".". Raises: Exception: If the CSV file fails to save. """ try: url = ( "https://github.com/samapriya/Earth-Engine-Datasets-List/archive/master.zip" ) filename = "Earth-Engine-Datasets-List-master.zip" dir_name = filename.replace(".zip", "") out_dir = os.path.abspath(out_dir) if not os.path.exists(out_dir): os.makedirs(out_dir) download_from_url( url, out_file_name=filename, out_dir=out_dir, unzip=True, verbose=False ) work_dir = os.path.join(out_dir, dir_name) in_csv = list(Path(work_dir).rglob("*.csv"))[0] out_csv = get_data_csv() shutil.copyfile(in_csv, out_csv) os.remove(os.path.join(out_dir, filename)) shutil.rmtree(os.path.join(out_dir, dir_name)) except Exception as e: raise Exception(e)
Updates the Earth Engine Data Catalog dataset list. Args: out_dir (str, optional): The output directory to save the GitHub repository. Defaults to ".". Raises: Exception: If the CSV file fails to save.
12,194
import json import os import shutil import urllib.request from pathlib import Path import ipywidgets as widgets import pkg_resources from box import Box from IPython.display import display from .common import download_from_url, ee_data_html, search_ee_data def get_data_list(): """Gets a list of Earth Engine datasets. Returns: list: The list of dataset ids. """ datasets = get_ee_stac_list() extra_datasets = get_geemap_data_list() community_datasets = get_community_data_list() return datasets + extra_datasets + community_datasets def merge_dict(dict1, dict2): """Merges two nested dictionaries. Args: dict1 (dict): The first dictionary to merge. dict2 (dict): The second dictionary to merge. Returns: dict: The merged dictionary. """ return {**dict1, **dict2} The provided code snippet includes necessary dependencies for implementing the `get_data_dict` function. Write a Python function `def get_data_dict()` to solve the following problem: Gets the Earth Engine Data Catalog as a nested dictionary. Returns: dict: The nested dictionary containing the information about the Earth Engine Data Catalog. Here is the function: def get_data_dict(): """Gets the Earth Engine Data Catalog as a nested dictionary. Returns: dict: The nested dictionary containing the information about the Earth Engine Data Catalog. """ data_dict = {} datasets = get_data_list() for dataset in datasets: tree_dict = {} items = dataset.split("/") for index, key in enumerate(reversed(items)): if index == 0: tree_dict = {key: dataset} else: tree_dict = {key: tree_dict} data_dict = merge_dict(data_dict, tree_dict) data_dict[dataset.replace("/", "_")] = dataset return data_dict
Gets the Earth Engine Data Catalog as a nested dictionary. Returns: dict: The nested dictionary containing the information about the Earth Engine Data Catalog.
12,195
import json import os import shutil import urllib.request from pathlib import Path import ipywidgets as widgets import pkg_resources from box import Box from IPython.display import display from .common import download_from_url, ee_data_html, search_ee_data def search_ee_data( keywords, regex=False, source="ee", types=None, keys=["id", "provider", "tags", "title"], ): """Searches Earth Engine data catalog. Args: keywords (str | list): Keywords to search for can be id, provider, tag and so on. Split by space if string, e.g. "1 2" becomes ['1','2']. regex (bool, optional): Allow searching for regular expressions. Defaults to false. source (str, optional): Can be 'ee', 'community' or 'all'. Defaults to 'ee'. For more details, see https://github.com/samapriya/awesome-gee-community-datasets/blob/master/community_datasets.json types (list, optional): List of valid collection types. Defaults to None so no filter is applied. A possible filter ['image_collection'] keys (list, optional): List of metadata fields to search from. Defaults to ['id','provider','tags','title'] Returns: list: Returns a list of assets. """ if isinstance(keywords, str): keywords = keywords.split(" ") import re from functools import reduce def search_collection(pattern, dict_): if regex: if any(re.match(pattern, dict_[key]) for key in keys): return dict_ elif any(pattern in dict_[key] for key in keys): return dict_ return {} def search_all(pattern): # updated daily a = "https://raw.githubusercontent.com/samapriya/Earth-Engine-Datasets-List/master/gee_catalog.json" b = "https://raw.githubusercontent.com/samapriya/awesome-gee-community-datasets/master/community_datasets.json" sources = {"ee": [a], "community": [b], "all": [a, b]} matches = [] for link in sources[source]: r = requests.get(link) catalog_list = r.json() matches += [search_collection(pattern, x) for x in catalog_list] matches = [x for x in matches if x] if types: return [x for x in matches if x["type"] in types] return matches try: assets = list( {json.dumps(match) for match in search_all(pattern=k)} for k in keywords ) assets = sorted(list(reduce(set.intersection, assets))) assets = [json.loads(x) for x in assets] results = [] for asset in assets: asset_dates = ( asset.get("start_date", "Unknown") + " - " + asset.get("end_date", "Unknown") ) asset_snippet = asset["id"] if "ee." in asset_snippet: start_index = asset_snippet.index("'") + 1 end_index = asset_snippet.index("'", start_index) asset_id = asset_snippet[start_index:end_index] else: asset_id = asset_snippet asset["dates"] = asset_dates asset["id"] = asset_id asset["uid"] = asset_id.replace("/", "_") results.append(asset) return results except Exception as e: print(e) def ee_data_html(asset): """Generates HTML from an asset to be used in the HTML widget. Args: asset (dict): A dictionary containing an Earth Engine asset. Returns: str: A string containing HTML. """ try: asset_title = asset.get("title", "Unknown") asset_dates = asset.get("dates", "Unknown") ee_id_snippet = asset.get("id", "Unknown") asset_uid = asset.get("uid", None) asset_url = asset.get("asset_url", "") code_url = asset.get("sample_code", None) thumbnail_url = asset.get("thumbnail_url", None) asset_type = asset.get("type", "Unknown") if asset_type == "image": ee_id_snippet = "ee.Image('{}')".format(ee_id_snippet) elif asset_type == "image_collection": ee_id_snippet = "ee.ImageCollection('{}')".format(ee_id_snippet) elif asset_type == "table": ee_id_snippet = "ee.FeatureCollection('{}')".format(ee_id_snippet) if not code_url and asset_uid: coder_url = f"""https://code.earthengine.google.com/?scriptPath=Examples%3ADatasets%2F{asset_uid}""" else: coder_url = code_url ## ee datasets always have a asset_url, and should have a thumbnail catalog = ( bool(asset_url) * f""" <h4>Data Catalog</h4> <p style="margin-left: 40px"><a href="{asset_url.replace('terms-of-use','description')}" target="_blank">Description</a></p> <p style="margin-left: 40px"><a href="{asset_url.replace('terms-of-use','bands')}" target="_blank">Bands</a></p> <p style="margin-left: 40px"><a href="{asset_url.replace('terms-of-use','image-properties')}" target="_blank">Properties</a></p> <p style="margin-left: 40px"><a href="{coder_url}" target="_blank">Example</a></p> """ ) thumbnail = ( bool(thumbnail_url) * f""" <h4>Dataset Thumbnail</h4> <img src="{thumbnail_url}"> """ ) ## only community datasets have a code_url alternative = ( bool(code_url) * f""" <h4>Community Catalog</h4> <p style="margin-left: 40px">{asset.get('provider','Provider unknown')}</p> <p style="margin-left: 40px">{asset.get('tags','Tags unknown')}</p> <p style="margin-left: 40px"><a href="{coder_url}" target="_blank">Example</a></p> """ ) template = f""" <html> <body> <h3>{asset_title}</h3> <h4>Dataset Availability</h4> <p style="margin-left: 40px">{asset_dates}</p> <h4>Earth Engine Snippet</h4> <p style="margin-left: 40px">{ee_id_snippet}</p> {catalog} {alternative} {thumbnail} </body> </html> """ return template except Exception as e: print(e) The provided code snippet includes necessary dependencies for implementing the `get_metadata` function. Write a Python function `def get_metadata(asset_id, source="ee")` to solve the following problem: Gets metadata about an Earth Engine asset. Args: asset_id (str): The Earth Engine asset id. source (str): 'ee', 'community' or 'all'. Raises: Exception: If search fails. Here is the function: def get_metadata(asset_id, source="ee"): """Gets metadata about an Earth Engine asset. Args: asset_id (str): The Earth Engine asset id. source (str): 'ee', 'community' or 'all'. Raises: Exception: If search fails. """ try: ee_assets = search_ee_data(asset_id, source=source) html = ee_data_html(ee_assets[0]) html_widget = widgets.HTML() html_widget.value = html display(html_widget) except Exception as e: raise Exception(e)
Gets metadata about an Earth Engine asset. Args: asset_id (str): The Earth Engine asset id. source (str): 'ee', 'community' or 'all'. Raises: Exception: If search fails.
12,196
import os import ee import folium from box import Box from folium import plugins from branca.element import Figure, JavascriptLink, MacroElement from folium.elements import JSCSSMixin from folium.map import Layer from jinja2 import Template from .basemaps import xyz_to_folium from .common import * from .conversion import * from .ee_tile_layers import * from .legends import builtin_legends from .osm import * from .timelapse import * from .plot import * from . import examples The provided code snippet includes necessary dependencies for implementing the `delete_dp_report` function. Write a Python function `def delete_dp_report(name)` to solve the following problem: Deletes a datapane report. Args: name (str): Name of the report to delete. Here is the function: def delete_dp_report(name): """Deletes a datapane report. Args: name (str): Name of the report to delete. """ try: import datapane as dp reports = dp.Report.list() items = list(reports) names = list(map(lambda item: item["name"], items)) if name in names: report = dp.Report.get(name) url = report.blocks[0]["url"] # print(f'Deleting {url}...') dp.Report.delete(dp.Report.by_id(url)) except Exception as e: print(e) return
Deletes a datapane report. Args: name (str): Name of the report to delete.
12,197
import os import ee import folium from box import Box from folium import plugins from branca.element import Figure, JavascriptLink, MacroElement from folium.elements import JSCSSMixin from folium.map import Layer from jinja2 import Template from .basemaps import xyz_to_folium from .common import * from .conversion import * from .ee_tile_layers import * from .legends import builtin_legends from .osm import * from .timelapse import * from .plot import * from . import examples The provided code snippet includes necessary dependencies for implementing the `delete_dp_reports` function. Write a Python function `def delete_dp_reports()` to solve the following problem: Deletes all datapane reports. Here is the function: def delete_dp_reports(): """Deletes all datapane reports.""" try: import datapane as dp reports = dp.Report.list() for item in reports: print(item["name"]) report = dp.Report.get(item["name"]) url = report.blocks[0]["url"] print(f"Deleting {url}...") dp.Report.delete(dp.Report.by_id(url)) except Exception as e: print(e) return
Deletes all datapane reports.
12,198
import os import ee import folium from box import Box from folium import plugins from branca.element import Figure, JavascriptLink, MacroElement from folium.elements import JSCSSMixin from folium.map import Layer from jinja2 import Template from .basemaps import xyz_to_folium from .common import * from .conversion import * from .ee_tile_layers import * from .legends import builtin_legends from .osm import * from .timelapse import * from .plot import * from . import examples import ee def blend( top_layer, bottom_layer=None, top_vis=None, bottom_vis=None, hillshade=True, expression="a*b", **kwargs, ): """Create a blended image that is a combination of two images, e.g., DEM and hillshade. This function was inspired by Jesse Anderson. See https://github.com/jessjaco/gee-blend. Args: top_layer (ee.Image): The top layer image, e.g., ee.Image("CGIAR/SRTM90_V4") bottom_layer (ee.Image, optional): The bottom layer image. If not specified, it will use the top layer image. top_vis (dict, optional): The top layer image vis parameters as a dictionary. Defaults to None. bottom_vis (dict, optional): The bottom layer image vis parameters as a dictionary. Defaults to None. hillshade (bool, optional): Flag to use hillshade. Defaults to True. expression (str, optional): The expression to use for the blend. Defaults to 'a*b'. Returns: ee.Image: The blended image. """ from box import Box if not isinstance(top_layer, ee.Image): raise ValueError("top_layer must be an ee.Image.") if bottom_layer is None: bottom_layer = top_layer if not isinstance(bottom_layer, ee.Image): raise ValueError("bottom_layer must be an ee.Image.") if top_vis is not None: if not isinstance(top_vis, dict): raise ValueError("top_vis must be a dictionary.") elif "palette" in top_vis and isinstance(top_vis["palette"], Box): try: top_vis["palette"] = top_vis["palette"]["default"] except Exception as e: print("The provided palette is invalid.") raise Exception(e) if bottom_vis is not None: if not isinstance(bottom_vis, dict): raise ValueError("top_vis must be a dictionary.") elif "palette" in bottom_vis and isinstance(bottom_vis["palette"], Box): try: bottom_vis["palette"] = bottom_vis["palette"]["default"] except Exception as e: print("The provided palette is invalid.") raise Exception(e) if top_vis is None: top_bands = top_layer.bandNames().getInfo() top_vis = {"bands": top_bands} if hillshade: top_vis["palette"] = ["006633", "E5FFCC", "662A00", "D8D8D8", "F5F5F5"] top_vis["min"] = 0 top_vis["max"] = 6000 if bottom_vis is None: bottom_bands = bottom_layer.bandNames().getInfo() bottom_vis = {"bands": bottom_bands} if hillshade: bottom_vis["bands"] = ["hillshade"] top = top_layer.visualize(**top_vis).divide(255) if hillshade: bottom = ee.Terrain.hillshade(bottom_layer).visualize(**bottom_vis).divide(255) else: bottom = bottom_layer.visualize(**bottom_vis).divide(255) if "a" not in expression or ("b" not in expression): raise ValueError("expression must contain 'a' and 'b'.") result = ee.Image().expression(expression, {"a": top, "b": bottom}) return result def check_cmap(cmap): """Check the colormap and return a list of colors. Args: cmap (str | list | Box): The colormap to check. Returns: list: A list of colors. """ from box import Box from .colormaps import get_palette if isinstance(cmap, str): try: palette = get_palette(cmap) if isinstance(palette, dict): palette = palette["default"] return palette except Exception as e: try: return check_color(cmap) except Exception as e: raise Exception(f"{cmap} is not a valid colormap.") elif isinstance(cmap, Box): return list(cmap["default"]) elif isinstance(cmap, list) or isinstance(cmap, tuple): return cmap else: raise Exception(f"{cmap} is not a valid colormap.") def mosaic(images, output, merge_args={}, verbose=True, **kwargs): """Mosaics a list of images into a single image. Inspired by https://bit.ly/3A6roDK. Args: images (str | list): An input directory containing images or a list of images. output (str): The output image filepath. merge_args (dict, optional): A dictionary of arguments to pass to the rasterio.merge function. Defaults to {}. verbose (bool, optional): Whether to print progress. Defaults to True. """ from rasterio.merge import merge import rasterio as rio from pathlib import Path output = os.path.abspath(output) if isinstance(images, str): path = Path(images) raster_files = list(path.iterdir()) elif isinstance(images, list): raster_files = images else: raise ValueError("images must be a list of raster files.") raster_to_mosiac = [] if not os.path.exists(os.path.dirname(output)): os.makedirs(os.path.dirname(output)) for index, p in enumerate(raster_files): if verbose: print(f"Reading {index+1}/{len(raster_files)}: {os.path.basename(p)}") raster = rio.open(p, **kwargs) raster_to_mosiac.append(raster) if verbose: print("Merging rasters...") arr, transform = merge(raster_to_mosiac, **merge_args) output_meta = raster.meta.copy() output_meta.update( { "driver": "GTiff", "height": arr.shape[1], "width": arr.shape[2], "transform": transform, } ) with rio.open(output, "w", **output_meta) as m: m.write(arr) import ee import folium import ee The provided code snippet includes necessary dependencies for implementing the `ee_tile_layer` function. Write a Python function `def ee_tile_layer( ee_object, vis_params={}, name="Layer untitled", shown=True, opacity=1.0, **kwargs )` to solve the following problem: Converts and Earth Engine layer to ipyleaflet TileLayer. Args: ee_object (Collection|Feature|Image|MapId): The object to add to the map. vis_params (dict, optional): The visualization parameters. Defaults to {}. name (str, optional): The name of the layer. Defaults to 'Layer untitled'. shown (bool, optional): A flag indicating whether the layer should be on by default. Defaults to True. opacity (float, optional): The layer's opacity represented as a number between 0 and 1. Defaults to 1. Here is the function: def ee_tile_layer( ee_object, vis_params={}, name="Layer untitled", shown=True, opacity=1.0, **kwargs ): """Converts and Earth Engine layer to ipyleaflet TileLayer. Args: ee_object (Collection|Feature|Image|MapId): The object to add to the map. vis_params (dict, optional): The visualization parameters. Defaults to {}. name (str, optional): The name of the layer. Defaults to 'Layer untitled'. shown (bool, optional): A flag indicating whether the layer should be on by default. Defaults to True. opacity (float, optional): The layer's opacity represented as a number between 0 and 1. Defaults to 1. """ image = None if ( not isinstance(ee_object, ee.Image) and not isinstance(ee_object, ee.ImageCollection) and not isinstance(ee_object, ee.FeatureCollection) and not isinstance(ee_object, ee.Feature) and not isinstance(ee_object, ee.Geometry) ): err_str = "\n\nThe image argument in 'addLayer' function must be an instance of one of ee.Image, ee.Geometry, ee.Feature or ee.FeatureCollection." raise AttributeError(err_str) if ( isinstance(ee_object, ee.geometry.Geometry) or isinstance(ee_object, ee.feature.Feature) or isinstance(ee_object, ee.featurecollection.FeatureCollection) ): features = ee.FeatureCollection(ee_object) width = 2 if "width" in vis_params: width = vis_params["width"] color = "000000" if "color" in vis_params: color = vis_params["color"] image_fill = features.style(**{"fillColor": color}).updateMask( ee.Image.constant(0.5) ) image_outline = features.style( **{"color": color, "fillColor": "00000000", "width": width} ) image = image_fill.blend(image_outline) elif isinstance(ee_object, ee.image.Image): image = ee_object elif isinstance(ee_object, ee.imagecollection.ImageCollection): image = ee_object.mosaic() if "palette" in vis_params: if isinstance(vis_params["palette"], Box): try: vis_params["palette"] = vis_params["palette"]["default"] except Exception as e: print("The provided palette is invalid.") raise Exception(e) elif isinstance(vis_params["palette"], str): vis_params["palette"] = check_cmap(vis_params["palette"]) elif not isinstance(vis_params["palette"], list): raise ValueError( "The palette must be a list of colors or a string or a Box object." ) map_id_dict = ee.Image(image).getMapId(vis_params) tile_layer = folium.raster_layers.TileLayer( tiles=map_id_dict["tile_fetcher"].url_format, attr="Google Earth Engine", name=name, overlay=True, control=True, opacity=opacity, show=shown, max_zoom=24, **kwargs, ) return tile_layer
Converts and Earth Engine layer to ipyleaflet TileLayer. Args: ee_object (Collection|Feature|Image|MapId): The object to add to the map. vis_params (dict, optional): The visualization parameters. Defaults to {}. name (str, optional): The name of the layer. Defaults to 'Layer untitled'. shown (bool, optional): A flag indicating whether the layer should be on by default. Defaults to True. opacity (float, optional): The layer's opacity represented as a number between 0 and 1. Defaults to 1.
12,199
import os import ee import folium from box import Box from folium import plugins from branca.element import Figure, JavascriptLink, MacroElement from folium.elements import JSCSSMixin from folium.map import Layer from jinja2 import Template from .basemaps import xyz_to_folium from .common import * from .conversion import * from .ee_tile_layers import * from .legends import builtin_legends from .osm import * from .timelapse import * from .plot import * from . import examples The provided code snippet includes necessary dependencies for implementing the `st_map_center` function. Write a Python function `def st_map_center(lat, lon)` to solve the following problem: Returns the map center coordinates for a given latitude and longitude. If the system variable 'map_center' exists, it is used. Otherwise, the default is returned. Args: lat (float): Latitude. lon (float): Longitude. Raises: Exception: If streamlit is not installed. Returns: list: The map center coordinates. Here is the function: def st_map_center(lat, lon): """Returns the map center coordinates for a given latitude and longitude. If the system variable 'map_center' exists, it is used. Otherwise, the default is returned. Args: lat (float): Latitude. lon (float): Longitude. Raises: Exception: If streamlit is not installed. Returns: list: The map center coordinates. """ try: import streamlit as st if "map_center" in st.session_state: return st.session_state["map_center"] else: return [lat, lon] except Exception as e: raise Exception(e)
Returns the map center coordinates for a given latitude and longitude. If the system variable 'map_center' exists, it is used. Otherwise, the default is returned. Args: lat (float): Latitude. lon (float): Longitude. Raises: Exception: If streamlit is not installed. Returns: list: The map center coordinates.
12,200
import os import ee import folium from box import Box from folium import plugins from branca.element import Figure, JavascriptLink, MacroElement from folium.elements import JSCSSMixin from folium.map import Layer from jinja2 import Template from .basemaps import xyz_to_folium from .common import * from .conversion import * from .ee_tile_layers import * from .legends import builtin_legends from .osm import * from .timelapse import * from .plot import * from . import examples The provided code snippet includes necessary dependencies for implementing the `st_save_bounds` function. Write a Python function `def st_save_bounds(st_component)` to solve the following problem: Saves the map bounds to the session state. Args: map (folium.folium.Map): The map to save the bounds from. Here is the function: def st_save_bounds(st_component): """Saves the map bounds to the session state. Args: map (folium.folium.Map): The map to save the bounds from. """ try: import streamlit as st if st_component is not None: bounds = st_component["bounds"] south = bounds["_southWest"]["lat"] west = bounds["_southWest"]["lng"] north = bounds["_northEast"]["lat"] east = bounds["_northEast"]["lng"] bounds = [[south, west], [north, east]] center = [south + (north - south) / 2, west + (east - west) / 2] st.session_state["map_bounds"] = bounds st.session_state["map_center"] = center except Exception as e: raise Exception(e)
Saves the map bounds to the session state. Args: map (folium.folium.Map): The map to save the bounds from.
12,201
import os import ee import folium from box import Box from folium import plugins from branca.element import Figure, JavascriptLink, MacroElement from folium.elements import JSCSSMixin from folium.map import Layer from jinja2 import Template from .basemaps import xyz_to_folium from .common import * from .conversion import * from .ee_tile_layers import * from .legends import builtin_legends from .osm import * from .timelapse import * from .plot import * from . import examples def linked_maps( rows=2, cols=2, height="400px", ee_objects=[], vis_params=[], labels=[], label_position="topright", **kwargs, ): print("The folium plotting backend does not support this function.")
null
12,202
from .common import check_package def osm_gdf_from_address(address, tags, dist=1000): """Create GeoDataFrame of OSM entities within some distance N, S, E, W of address. Args: address (str): The address to geocode and use as the central point around which to get the geometries. tags (dict): Dict of tags used for finding objects in the selected area. Results returned are the union, not intersection of each individual tag. Each result matches at least one given tag. The dict keys should be OSM tags, (e.g., building, landuse, highway, etc) and the dict values should be either True to retrieve all items with the given tag, or a string to get a single tag-value combination, or a list of strings to get multiple values for the given tag. For example, tags = {‘building’: True} would return all building footprints in the area. tags = {‘amenity’:True, ‘landuse’:[‘retail’,’commercial’], ‘highway’:’bus_stop’} would return all amenities, landuse=retail, landuse=commercial, and highway=bus_stop. dist (int, optional): Distance in meters. Defaults to 1000. Returns: GeoDataFrame: A GeoDataFrame of OSM entities. """ check_package("osmnx", "https://osmnx.readthedocs.io/en/stable/#installation") import osmnx as ox gdf = ox.geometries_from_address(address, tags, dist) return gdf The provided code snippet includes necessary dependencies for implementing the `osm_shp_from_address` function. Write a Python function `def osm_shp_from_address(address, tags, filepath, dist=1000)` to solve the following problem: Download OSM entities within some distance N, S, E, W of address as a shapefile. Args: address (str): The address to geocode and use as the central point around which to get the geometries. tags (dict): Dict of tags used for finding objects in the selected area. Results returned are the union, not intersection of each individual tag. Each result matches at least one given tag. The dict keys should be OSM tags, (e.g., building, landuse, highway, etc) and the dict values should be either True to retrieve all items with the given tag, or a string to get a single tag-value combination, or a list of strings to get multiple values for the given tag. For example, tags = {‘building’: True} would return all building footprints in the area. tags = {‘amenity’:True, ‘landuse’:[‘retail’,’commercial’], ‘highway’:’bus_stop’} would return all amenities, landuse=retail, landuse=commercial, and highway=bus_stop. filepath (str): File path to the output shapefile. dist (int, optional): Distance in meters. Defaults to 1000. Here is the function: def osm_shp_from_address(address, tags, filepath, dist=1000): """Download OSM entities within some distance N, S, E, W of address as a shapefile. Args: address (str): The address to geocode and use as the central point around which to get the geometries. tags (dict): Dict of tags used for finding objects in the selected area. Results returned are the union, not intersection of each individual tag. Each result matches at least one given tag. The dict keys should be OSM tags, (e.g., building, landuse, highway, etc) and the dict values should be either True to retrieve all items with the given tag, or a string to get a single tag-value combination, or a list of strings to get multiple values for the given tag. For example, tags = {‘building’: True} would return all building footprints in the area. tags = {‘amenity’:True, ‘landuse’:[‘retail’,’commercial’], ‘highway’:’bus_stop’} would return all amenities, landuse=retail, landuse=commercial, and highway=bus_stop. filepath (str): File path to the output shapefile. dist (int, optional): Distance in meters. Defaults to 1000. """ gdf = osm_gdf_from_address(address, tags, dist) gdf.to_file(filepath)
Download OSM entities within some distance N, S, E, W of address as a shapefile. Args: address (str): The address to geocode and use as the central point around which to get the geometries. tags (dict): Dict of tags used for finding objects in the selected area. Results returned are the union, not intersection of each individual tag. Each result matches at least one given tag. The dict keys should be OSM tags, (e.g., building, landuse, highway, etc) and the dict values should be either True to retrieve all items with the given tag, or a string to get a single tag-value combination, or a list of strings to get multiple values for the given tag. For example, tags = {‘building’: True} would return all building footprints in the area. tags = {‘amenity’:True, ‘landuse’:[‘retail’,’commercial’], ‘highway’:’bus_stop’} would return all amenities, landuse=retail, landuse=commercial, and highway=bus_stop. filepath (str): File path to the output shapefile. dist (int, optional): Distance in meters. Defaults to 1000.
12,203
from .common import check_package def osm_gdf_from_address(address, tags, dist=1000): """Create GeoDataFrame of OSM entities within some distance N, S, E, W of address. Args: address (str): The address to geocode and use as the central point around which to get the geometries. tags (dict): Dict of tags used for finding objects in the selected area. Results returned are the union, not intersection of each individual tag. Each result matches at least one given tag. The dict keys should be OSM tags, (e.g., building, landuse, highway, etc) and the dict values should be either True to retrieve all items with the given tag, or a string to get a single tag-value combination, or a list of strings to get multiple values for the given tag. For example, tags = {‘building’: True} would return all building footprints in the area. tags = {‘amenity’:True, ‘landuse’:[‘retail’,’commercial’], ‘highway’:’bus_stop’} would return all amenities, landuse=retail, landuse=commercial, and highway=bus_stop. dist (int, optional): Distance in meters. Defaults to 1000. Returns: GeoDataFrame: A GeoDataFrame of OSM entities. """ check_package("osmnx", "https://osmnx.readthedocs.io/en/stable/#installation") import osmnx as ox gdf = ox.geometries_from_address(address, tags, dist) return gdf The provided code snippet includes necessary dependencies for implementing the `osm_geojson_from_address` function. Write a Python function `def osm_geojson_from_address(address, tags, filepath=None, dist=1000)` to solve the following problem: Download OSM entities within some distance N, S, E, W of address as a GeoJSON. Args: address (str): The address to geocode and use as the central point around which to get the geometries. tags (dict): Dict of tags used for finding objects in the selected area. Results returned are the union, not intersection of each individual tag. Each result matches at least one given tag. The dict keys should be OSM tags, (e.g., building, landuse, highway, etc) and the dict values should be either True to retrieve all items with the given tag, or a string to get a single tag-value combination, or a list of strings to get multiple values for the given tag. For example, tags = {‘building’: True} would return all building footprints in the area. tags = {‘amenity’:True, ‘landuse’:[‘retail’,’commercial’], ‘highway’:’bus_stop’} would return all amenities, landuse=retail, landuse=commercial, and highway=bus_stop. filepath (str, optional): File path to the output GeoJSON. Defaults to None. dist (int, optional): Distance in meters. Defaults to 1000. Returns: dict: A GeoJSON dictionary of OSM entities. Here is the function: def osm_geojson_from_address(address, tags, filepath=None, dist=1000): """Download OSM entities within some distance N, S, E, W of address as a GeoJSON. Args: address (str): The address to geocode and use as the central point around which to get the geometries. tags (dict): Dict of tags used for finding objects in the selected area. Results returned are the union, not intersection of each individual tag. Each result matches at least one given tag. The dict keys should be OSM tags, (e.g., building, landuse, highway, etc) and the dict values should be either True to retrieve all items with the given tag, or a string to get a single tag-value combination, or a list of strings to get multiple values for the given tag. For example, tags = {‘building’: True} would return all building footprints in the area. tags = {‘amenity’:True, ‘landuse’:[‘retail’,’commercial’], ‘highway’:’bus_stop’} would return all amenities, landuse=retail, landuse=commercial, and highway=bus_stop. filepath (str, optional): File path to the output GeoJSON. Defaults to None. dist (int, optional): Distance in meters. Defaults to 1000. Returns: dict: A GeoJSON dictionary of OSM entities. """ gdf = osm_gdf_from_address(address, tags, dist) if filepath is not None: gdf.to_file(filepath, driver="GeoJSON") else: return gdf.__geo_interface__
Download OSM entities within some distance N, S, E, W of address as a GeoJSON. Args: address (str): The address to geocode and use as the central point around which to get the geometries. tags (dict): Dict of tags used for finding objects in the selected area. Results returned are the union, not intersection of each individual tag. Each result matches at least one given tag. The dict keys should be OSM tags, (e.g., building, landuse, highway, etc) and the dict values should be either True to retrieve all items with the given tag, or a string to get a single tag-value combination, or a list of strings to get multiple values for the given tag. For example, tags = {‘building’: True} would return all building footprints in the area. tags = {‘amenity’:True, ‘landuse’:[‘retail’,’commercial’], ‘highway’:’bus_stop’} would return all amenities, landuse=retail, landuse=commercial, and highway=bus_stop. filepath (str, optional): File path to the output GeoJSON. Defaults to None. dist (int, optional): Distance in meters. Defaults to 1000. Returns: dict: A GeoJSON dictionary of OSM entities.
12,204
from .common import check_package def osm_gdf_from_place(query, tags, which_result=None, buffer_dist=None): """Create GeoDataFrame of OSM entities within boundaries of geocodable place(s). Args: query (str | dict | list): Query string(s) or structured dict(s) to geocode. tags (dict): Dict of tags used for finding objects in the selected area. Results returned are the union, not intersection of each individual tag. Each result matches at least one given tag. The dict keys should be OSM tags, (e.g., building, landuse, highway, etc) and the dict values should be either True to retrieve all items with the given tag, or a string to get a single tag-value combination, or a list of strings to get multiple values for the given tag. For example, tags = {‘building’: True} would return all building footprints in the area. tags = {‘amenity’:True, ‘landuse’:[‘retail’,’commercial’], ‘highway’:’bus_stop’} would return all amenities, landuse=retail, landuse=commercial, and highway=bus_stop. which_result (int, optional): Which geocoding result to use. if None, auto-select the first (Multi)Polygon or raise an error if OSM doesn't return one. to get the top match regardless of geometry type, set which_result=1. Defaults to None. buffer_dist (float, optional): Distance to buffer around the place geometry, in meters. Defaults to None. Returns: GeoDataFrame: A GeoDataFrame of OSM entities. """ check_package("osmnx", "https://osmnx.readthedocs.io/en/stable/#installation") import osmnx as ox ox.config(use_cache=True, log_console=True) gdf = ox.geometries_from_place(query, tags, which_result, buffer_dist) return gdf The provided code snippet includes necessary dependencies for implementing the `osm_shp_from_place` function. Write a Python function `def osm_shp_from_place(query, tags, filepath, which_result=None, buffer_dist=None)` to solve the following problem: Download OSM entities within boundaries of geocodable place(s) as a shapefile. Args: query (str | dict | list): Query string(s) or structured dict(s) to geocode. tags (dict): Dict of tags used for finding objects in the selected area. Results returned are the union, not intersection of each individual tag. Each result matches at least one given tag. The dict keys should be OSM tags, (e.g., building, landuse, highway, etc) and the dict values should be either True to retrieve all items with the given tag, or a string to get a single tag-value combination, or a list of strings to get multiple values for the given tag. For example, tags = {‘building’: True} would return all building footprints in the area. tags = {‘amenity’:True, ‘landuse’:[‘retail’,’commercial’], ‘highway’:’bus_stop’} would return all amenities, landuse=retail, landuse=commercial, and highway=bus_stop. filepath (str): File path to the output shapefile. which_result (int, optional): Which geocoding result to use. if None, auto-select the first (Multi)Polygon or raise an error if OSM doesn't return one. to get the top match regardless of geometry type, set which_result=1. Defaults to None. buffer_dist (float, optional): Distance to buffer around the place geometry, in meters. Defaults to None. Here is the function: def osm_shp_from_place(query, tags, filepath, which_result=None, buffer_dist=None): """Download OSM entities within boundaries of geocodable place(s) as a shapefile. Args: query (str | dict | list): Query string(s) or structured dict(s) to geocode. tags (dict): Dict of tags used for finding objects in the selected area. Results returned are the union, not intersection of each individual tag. Each result matches at least one given tag. The dict keys should be OSM tags, (e.g., building, landuse, highway, etc) and the dict values should be either True to retrieve all items with the given tag, or a string to get a single tag-value combination, or a list of strings to get multiple values for the given tag. For example, tags = {‘building’: True} would return all building footprints in the area. tags = {‘amenity’:True, ‘landuse’:[‘retail’,’commercial’], ‘highway’:’bus_stop’} would return all amenities, landuse=retail, landuse=commercial, and highway=bus_stop. filepath (str): File path to the output shapefile. which_result (int, optional): Which geocoding result to use. if None, auto-select the first (Multi)Polygon or raise an error if OSM doesn't return one. to get the top match regardless of geometry type, set which_result=1. Defaults to None. buffer_dist (float, optional): Distance to buffer around the place geometry, in meters. Defaults to None. """ gdf = osm_gdf_from_place(query, tags, which_result, buffer_dist) gdf.to_file(filepath)
Download OSM entities within boundaries of geocodable place(s) as a shapefile. Args: query (str | dict | list): Query string(s) or structured dict(s) to geocode. tags (dict): Dict of tags used for finding objects in the selected area. Results returned are the union, not intersection of each individual tag. Each result matches at least one given tag. The dict keys should be OSM tags, (e.g., building, landuse, highway, etc) and the dict values should be either True to retrieve all items with the given tag, or a string to get a single tag-value combination, or a list of strings to get multiple values for the given tag. For example, tags = {‘building’: True} would return all building footprints in the area. tags = {‘amenity’:True, ‘landuse’:[‘retail’,’commercial’], ‘highway’:’bus_stop’} would return all amenities, landuse=retail, landuse=commercial, and highway=bus_stop. filepath (str): File path to the output shapefile. which_result (int, optional): Which geocoding result to use. if None, auto-select the first (Multi)Polygon or raise an error if OSM doesn't return one. to get the top match regardless of geometry type, set which_result=1. Defaults to None. buffer_dist (float, optional): Distance to buffer around the place geometry, in meters. Defaults to None.
12,205
from .common import check_package def osm_gdf_from_place(query, tags, which_result=None, buffer_dist=None): """Create GeoDataFrame of OSM entities within boundaries of geocodable place(s). Args: query (str | dict | list): Query string(s) or structured dict(s) to geocode. tags (dict): Dict of tags used for finding objects in the selected area. Results returned are the union, not intersection of each individual tag. Each result matches at least one given tag. The dict keys should be OSM tags, (e.g., building, landuse, highway, etc) and the dict values should be either True to retrieve all items with the given tag, or a string to get a single tag-value combination, or a list of strings to get multiple values for the given tag. For example, tags = {‘building’: True} would return all building footprints in the area. tags = {‘amenity’:True, ‘landuse’:[‘retail’,’commercial’], ‘highway’:’bus_stop’} would return all amenities, landuse=retail, landuse=commercial, and highway=bus_stop. which_result (int, optional): Which geocoding result to use. if None, auto-select the first (Multi)Polygon or raise an error if OSM doesn't return one. to get the top match regardless of geometry type, set which_result=1. Defaults to None. buffer_dist (float, optional): Distance to buffer around the place geometry, in meters. Defaults to None. Returns: GeoDataFrame: A GeoDataFrame of OSM entities. """ check_package("osmnx", "https://osmnx.readthedocs.io/en/stable/#installation") import osmnx as ox ox.config(use_cache=True, log_console=True) gdf = ox.geometries_from_place(query, tags, which_result, buffer_dist) return gdf The provided code snippet includes necessary dependencies for implementing the `osm_geojson_from_place` function. Write a Python function `def osm_geojson_from_place( query, tags, filepath=None, which_result=None, buffer_dist=None )` to solve the following problem: Download OSM entities within boundaries of geocodable place(s) as a GeoJSON. Args: query (str | dict | list): Query string(s) or structured dict(s) to geocode. tags (dict): Dict of tags used for finding objects in the selected area. Results returned are the union, not intersection of each individual tag. Each result matches at least one given tag. The dict keys should be OSM tags, (e.g., building, landuse, highway, etc) and the dict values should be either True to retrieve all items with the given tag, or a string to get a single tag-value combination, or a list of strings to get multiple values for the given tag. For example, tags = {‘building’: True} would return all building footprints in the area. tags = {‘amenity’:True, ‘landuse’:[‘retail’,’commercial’], ‘highway’:’bus_stop’} would return all amenities, landuse=retail, landuse=commercial, and highway=bus_stop. filepath (str): File path to the output shapefile. which_result (int, optional): Which geocoding result to use. if None, auto-select the first (Multi)Polygon or raise an error if OSM doesn't return one. to get the top match regardless of geometry type, set which_result=1. Defaults to None. buffer_dist (float, optional): Distance to buffer around the place geometry, in meters. Defaults to None. Returns: dict: A GeoJSON dictionary of OSM entities. Here is the function: def osm_geojson_from_place( query, tags, filepath=None, which_result=None, buffer_dist=None ): """Download OSM entities within boundaries of geocodable place(s) as a GeoJSON. Args: query (str | dict | list): Query string(s) or structured dict(s) to geocode. tags (dict): Dict of tags used for finding objects in the selected area. Results returned are the union, not intersection of each individual tag. Each result matches at least one given tag. The dict keys should be OSM tags, (e.g., building, landuse, highway, etc) and the dict values should be either True to retrieve all items with the given tag, or a string to get a single tag-value combination, or a list of strings to get multiple values for the given tag. For example, tags = {‘building’: True} would return all building footprints in the area. tags = {‘amenity’:True, ‘landuse’:[‘retail’,’commercial’], ‘highway’:’bus_stop’} would return all amenities, landuse=retail, landuse=commercial, and highway=bus_stop. filepath (str): File path to the output shapefile. which_result (int, optional): Which geocoding result to use. if None, auto-select the first (Multi)Polygon or raise an error if OSM doesn't return one. to get the top match regardless of geometry type, set which_result=1. Defaults to None. buffer_dist (float, optional): Distance to buffer around the place geometry, in meters. Defaults to None. Returns: dict: A GeoJSON dictionary of OSM entities. """ gdf = osm_gdf_from_place(query, tags, which_result, buffer_dist) if filepath is not None: gdf.to_file(filepath, driver="GeoJSON") else: return gdf.__geo_interface__
Download OSM entities within boundaries of geocodable place(s) as a GeoJSON. Args: query (str | dict | list): Query string(s) or structured dict(s) to geocode. tags (dict): Dict of tags used for finding objects in the selected area. Results returned are the union, not intersection of each individual tag. Each result matches at least one given tag. The dict keys should be OSM tags, (e.g., building, landuse, highway, etc) and the dict values should be either True to retrieve all items with the given tag, or a string to get a single tag-value combination, or a list of strings to get multiple values for the given tag. For example, tags = {‘building’: True} would return all building footprints in the area. tags = {‘amenity’:True, ‘landuse’:[‘retail’,’commercial’], ‘highway’:’bus_stop’} would return all amenities, landuse=retail, landuse=commercial, and highway=bus_stop. filepath (str): File path to the output shapefile. which_result (int, optional): Which geocoding result to use. if None, auto-select the first (Multi)Polygon or raise an error if OSM doesn't return one. to get the top match regardless of geometry type, set which_result=1. Defaults to None. buffer_dist (float, optional): Distance to buffer around the place geometry, in meters. Defaults to None. Returns: dict: A GeoJSON dictionary of OSM entities.
12,206
from .common import check_package def osm_gdf_from_point(center_point, tags, dist=1000): """Create GeoDataFrame of OSM entities within some distance N, S, E, W of a point. Args: center_point (tuple): The (lat, lng) center point around which to get the geometries. tags (dict): Dict of tags used for finding objects in the selected area. Results returned are the union, not intersection of each individual tag. Each result matches at least one given tag. The dict keys should be OSM tags, (e.g., building, landuse, highway, etc) and the dict values should be either True to retrieve all items with the given tag, or a string to get a single tag-value combination, or a list of strings to get multiple values for the given tag. For example, tags = {‘building’: True} would return all building footprints in the area. tags = {‘amenity’:True, ‘landuse’:[‘retail’,’commercial’], ‘highway’:’bus_stop’} would return all amenities, landuse=retail, landuse=commercial, and highway=bus_stop. dist (int, optional): Distance in meters. Defaults to 1000. Returns: GeoDataFrame: A GeoDataFrame of OSM entities. """ check_package("osmnx", "https://osmnx.readthedocs.io/en/stable/#installation") import osmnx as ox gdf = ox.geometries_from_point(center_point, tags, dist) return gdf The provided code snippet includes necessary dependencies for implementing the `osm_shp_from_point` function. Write a Python function `def osm_shp_from_point(center_point, tags, filepath, dist=1000)` to solve the following problem: Download OSM entities within some distance N, S, E, W of point as a shapefile. Args: center_point (tuple): The (lat, lng) center point around which to get the geometries. tags (dict): Dict of tags used for finding objects in the selected area. Results returned are the union, not intersection of each individual tag. Each result matches at least one given tag. The dict keys should be OSM tags, (e.g., building, landuse, highway, etc) and the dict values should be either True to retrieve all items with the given tag, or a string to get a single tag-value combination, or a list of strings to get multiple values for the given tag. For example, tags = {‘building’: True} would return all building footprints in the area. tags = {‘amenity’:True, ‘landuse’:[‘retail’,’commercial’], ‘highway’:’bus_stop’} would return all amenities, landuse=retail, landuse=commercial, and highway=bus_stop. filepath (str): File path to the output shapefile. dist (int, optional): Distance in meters. Defaults to 1000. Here is the function: def osm_shp_from_point(center_point, tags, filepath, dist=1000): """Download OSM entities within some distance N, S, E, W of point as a shapefile. Args: center_point (tuple): The (lat, lng) center point around which to get the geometries. tags (dict): Dict of tags used for finding objects in the selected area. Results returned are the union, not intersection of each individual tag. Each result matches at least one given tag. The dict keys should be OSM tags, (e.g., building, landuse, highway, etc) and the dict values should be either True to retrieve all items with the given tag, or a string to get a single tag-value combination, or a list of strings to get multiple values for the given tag. For example, tags = {‘building’: True} would return all building footprints in the area. tags = {‘amenity’:True, ‘landuse’:[‘retail’,’commercial’], ‘highway’:’bus_stop’} would return all amenities, landuse=retail, landuse=commercial, and highway=bus_stop. filepath (str): File path to the output shapefile. dist (int, optional): Distance in meters. Defaults to 1000. """ gdf = osm_gdf_from_point(center_point, tags, dist) gdf.to_file(filepath)
Download OSM entities within some distance N, S, E, W of point as a shapefile. Args: center_point (tuple): The (lat, lng) center point around which to get the geometries. tags (dict): Dict of tags used for finding objects in the selected area. Results returned are the union, not intersection of each individual tag. Each result matches at least one given tag. The dict keys should be OSM tags, (e.g., building, landuse, highway, etc) and the dict values should be either True to retrieve all items with the given tag, or a string to get a single tag-value combination, or a list of strings to get multiple values for the given tag. For example, tags = {‘building’: True} would return all building footprints in the area. tags = {‘amenity’:True, ‘landuse’:[‘retail’,’commercial’], ‘highway’:’bus_stop’} would return all amenities, landuse=retail, landuse=commercial, and highway=bus_stop. filepath (str): File path to the output shapefile. dist (int, optional): Distance in meters. Defaults to 1000.
12,207
from .common import check_package def osm_gdf_from_point(center_point, tags, dist=1000): """Create GeoDataFrame of OSM entities within some distance N, S, E, W of a point. Args: center_point (tuple): The (lat, lng) center point around which to get the geometries. tags (dict): Dict of tags used for finding objects in the selected area. Results returned are the union, not intersection of each individual tag. Each result matches at least one given tag. The dict keys should be OSM tags, (e.g., building, landuse, highway, etc) and the dict values should be either True to retrieve all items with the given tag, or a string to get a single tag-value combination, or a list of strings to get multiple values for the given tag. For example, tags = {‘building’: True} would return all building footprints in the area. tags = {‘amenity’:True, ‘landuse’:[‘retail’,’commercial’], ‘highway’:’bus_stop’} would return all amenities, landuse=retail, landuse=commercial, and highway=bus_stop. dist (int, optional): Distance in meters. Defaults to 1000. Returns: GeoDataFrame: A GeoDataFrame of OSM entities. """ check_package("osmnx", "https://osmnx.readthedocs.io/en/stable/#installation") import osmnx as ox gdf = ox.geometries_from_point(center_point, tags, dist) return gdf The provided code snippet includes necessary dependencies for implementing the `osm_geojson_from_point` function. Write a Python function `def osm_geojson_from_point(center_point, tags, filepath=None, dist=1000)` to solve the following problem: Download OSM entities within some distance N, S, E, W of point as a GeoJSON. Args: center_point (tuple): The (lat, lng) center point around which to get the geometries. tags (dict): Dict of tags used for finding objects in the selected area. Results returned are the union, not intersection of each individual tag. Each result matches at least one given tag. The dict keys should be OSM tags, (e.g., building, landuse, highway, etc) and the dict values should be either True to retrieve all items with the given tag, or a string to get a single tag-value combination, or a list of strings to get multiple values for the given tag. For example, tags = {‘building’: True} would return all building footprints in the area. tags = {‘amenity’:True, ‘landuse’:[‘retail’,’commercial’], ‘highway’:’bus_stop’} would return all amenities, landuse=retail, landuse=commercial, and highway=bus_stop. filepath (str): File path to the output shapefile. dist (int, optional): Distance in meters. Defaults to 1000. Returns: dict: A GeoJSON dictionary of OSM entities. Here is the function: def osm_geojson_from_point(center_point, tags, filepath=None, dist=1000): """Download OSM entities within some distance N, S, E, W of point as a GeoJSON. Args: center_point (tuple): The (lat, lng) center point around which to get the geometries. tags (dict): Dict of tags used for finding objects in the selected area. Results returned are the union, not intersection of each individual tag. Each result matches at least one given tag. The dict keys should be OSM tags, (e.g., building, landuse, highway, etc) and the dict values should be either True to retrieve all items with the given tag, or a string to get a single tag-value combination, or a list of strings to get multiple values for the given tag. For example, tags = {‘building’: True} would return all building footprints in the area. tags = {‘amenity’:True, ‘landuse’:[‘retail’,’commercial’], ‘highway’:’bus_stop’} would return all amenities, landuse=retail, landuse=commercial, and highway=bus_stop. filepath (str): File path to the output shapefile. dist (int, optional): Distance in meters. Defaults to 1000. Returns: dict: A GeoJSON dictionary of OSM entities. """ gdf = osm_gdf_from_point(center_point, tags, dist) if filepath is not None: gdf.to_file(filepath, driver="GeoJSON") else: return gdf.__geo_interface__
Download OSM entities within some distance N, S, E, W of point as a GeoJSON. Args: center_point (tuple): The (lat, lng) center point around which to get the geometries. tags (dict): Dict of tags used for finding objects in the selected area. Results returned are the union, not intersection of each individual tag. Each result matches at least one given tag. The dict keys should be OSM tags, (e.g., building, landuse, highway, etc) and the dict values should be either True to retrieve all items with the given tag, or a string to get a single tag-value combination, or a list of strings to get multiple values for the given tag. For example, tags = {‘building’: True} would return all building footprints in the area. tags = {‘amenity’:True, ‘landuse’:[‘retail’,’commercial’], ‘highway’:’bus_stop’} would return all amenities, landuse=retail, landuse=commercial, and highway=bus_stop. filepath (str): File path to the output shapefile. dist (int, optional): Distance in meters. Defaults to 1000. Returns: dict: A GeoJSON dictionary of OSM entities.
12,208
from .common import check_package def osm_gdf_from_polygon(polygon, tags): """Create GeoDataFrame of OSM entities within boundaries of a (multi)polygon. Args: polygon (shapely.geometry.Polygon | shapely.geometry.MultiPolygon): Geographic boundaries to fetch geometries within tags (dict): Dict of tags used for finding objects in the selected area. Results returned are the union, not intersection of each individual tag. Each result matches at least one given tag. The dict keys should be OSM tags, (e.g., building, landuse, highway, etc) and the dict values should be either True to retrieve all items with the given tag, or a string to get a single tag-value combination, or a list of strings to get multiple values for the given tag. For example, tags = {‘building’: True} would return all building footprints in the area. tags = {‘amenity’:True, ‘landuse’:[‘retail’,’commercial’], ‘highway’:’bus_stop’} would return all amenities, landuse=retail, landuse=commercial, and highway=bus_stop. Returns: GeoDataFrame: A GeoDataFrame of OSM entities. """ check_package("osmnx", "https://osmnx.readthedocs.io/en/stable/#installation") import osmnx as ox gdf = ox.geometries_from_polygon(polygon, tags) return gdf The provided code snippet includes necessary dependencies for implementing the `osm_shp_from_polygon` function. Write a Python function `def osm_shp_from_polygon(polygon, tags, filepath)` to solve the following problem: Download OSM entities within boundaries of a (multi)polygon as a shapefile. Args: polygon (shapely.geometry.Polygon | shapely.geometry.MultiPolygon): Geographic boundaries to fetch geometries within tags (dict): Dict of tags used for finding objects in the selected area. Results returned are the union, not intersection of each individual tag. Each result matches at least one given tag. The dict keys should be OSM tags, (e.g., building, landuse, highway, etc) and the dict values should be either True to retrieve all items with the given tag, or a string to get a single tag-value combination, or a list of strings to get multiple values for the given tag. For example, tags = {‘building’: True} would return all building footprints in the area. tags = {‘amenity’:True, ‘landuse’:[‘retail’,’commercial’], ‘highway’:’bus_stop’} would return all amenities, landuse=retail, landuse=commercial, and highway=bus_stop. filepath (str): File path to the output shapefile. Here is the function: def osm_shp_from_polygon(polygon, tags, filepath): """Download OSM entities within boundaries of a (multi)polygon as a shapefile. Args: polygon (shapely.geometry.Polygon | shapely.geometry.MultiPolygon): Geographic boundaries to fetch geometries within tags (dict): Dict of tags used for finding objects in the selected area. Results returned are the union, not intersection of each individual tag. Each result matches at least one given tag. The dict keys should be OSM tags, (e.g., building, landuse, highway, etc) and the dict values should be either True to retrieve all items with the given tag, or a string to get a single tag-value combination, or a list of strings to get multiple values for the given tag. For example, tags = {‘building’: True} would return all building footprints in the area. tags = {‘amenity’:True, ‘landuse’:[‘retail’,’commercial’], ‘highway’:’bus_stop’} would return all amenities, landuse=retail, landuse=commercial, and highway=bus_stop. filepath (str): File path to the output shapefile. """ gdf = osm_gdf_from_polygon(polygon, tags) gdf.to_file(filepath)
Download OSM entities within boundaries of a (multi)polygon as a shapefile. Args: polygon (shapely.geometry.Polygon | shapely.geometry.MultiPolygon): Geographic boundaries to fetch geometries within tags (dict): Dict of tags used for finding objects in the selected area. Results returned are the union, not intersection of each individual tag. Each result matches at least one given tag. The dict keys should be OSM tags, (e.g., building, landuse, highway, etc) and the dict values should be either True to retrieve all items with the given tag, or a string to get a single tag-value combination, or a list of strings to get multiple values for the given tag. For example, tags = {‘building’: True} would return all building footprints in the area. tags = {‘amenity’:True, ‘landuse’:[‘retail’,’commercial’], ‘highway’:’bus_stop’} would return all amenities, landuse=retail, landuse=commercial, and highway=bus_stop. filepath (str): File path to the output shapefile.
12,209
from .common import check_package def osm_gdf_from_polygon(polygon, tags): """Create GeoDataFrame of OSM entities within boundaries of a (multi)polygon. Args: polygon (shapely.geometry.Polygon | shapely.geometry.MultiPolygon): Geographic boundaries to fetch geometries within tags (dict): Dict of tags used for finding objects in the selected area. Results returned are the union, not intersection of each individual tag. Each result matches at least one given tag. The dict keys should be OSM tags, (e.g., building, landuse, highway, etc) and the dict values should be either True to retrieve all items with the given tag, or a string to get a single tag-value combination, or a list of strings to get multiple values for the given tag. For example, tags = {‘building’: True} would return all building footprints in the area. tags = {‘amenity’:True, ‘landuse’:[‘retail’,’commercial’], ‘highway’:’bus_stop’} would return all amenities, landuse=retail, landuse=commercial, and highway=bus_stop. Returns: GeoDataFrame: A GeoDataFrame of OSM entities. """ check_package("osmnx", "https://osmnx.readthedocs.io/en/stable/#installation") import osmnx as ox gdf = ox.geometries_from_polygon(polygon, tags) return gdf The provided code snippet includes necessary dependencies for implementing the `osm_geojson_from_polygon` function. Write a Python function `def osm_geojson_from_polygon(polygon, tags, filepath=None)` to solve the following problem: Download OSM entities within boundaries of a (multi)polygon as a GeoJSON. Args: polygon (shapely.geometry.Polygon | shapely.geometry.MultiPolygon): Geographic boundaries to fetch geometries within tags (dict): Dict of tags used for finding objects in the selected area. Results returned are the union, not intersection of each individual tag. Each result matches at least one given tag. The dict keys should be OSM tags, (e.g., building, landuse, highway, etc) and the dict values should be either True to retrieve all items with the given tag, or a string to get a single tag-value combination, or a list of strings to get multiple values for the given tag. For example, tags = {‘building’: True} would return all building footprints in the area. tags = {‘amenity’:True, ‘landuse’:[‘retail’,’commercial’], ‘highway’:’bus_stop’} would return all amenities, landuse=retail, landuse=commercial, and highway=bus_stop. filepath (str, optional): File path to the output GeoJSON. Returns: dict: A GeoJSON dictionary of OSM entities. Here is the function: def osm_geojson_from_polygon(polygon, tags, filepath=None): """Download OSM entities within boundaries of a (multi)polygon as a GeoJSON. Args: polygon (shapely.geometry.Polygon | shapely.geometry.MultiPolygon): Geographic boundaries to fetch geometries within tags (dict): Dict of tags used for finding objects in the selected area. Results returned are the union, not intersection of each individual tag. Each result matches at least one given tag. The dict keys should be OSM tags, (e.g., building, landuse, highway, etc) and the dict values should be either True to retrieve all items with the given tag, or a string to get a single tag-value combination, or a list of strings to get multiple values for the given tag. For example, tags = {‘building’: True} would return all building footprints in the area. tags = {‘amenity’:True, ‘landuse’:[‘retail’,’commercial’], ‘highway’:’bus_stop’} would return all amenities, landuse=retail, landuse=commercial, and highway=bus_stop. filepath (str, optional): File path to the output GeoJSON. Returns: dict: A GeoJSON dictionary of OSM entities. """ gdf = osm_gdf_from_polygon(polygon, tags) if filepath is not None: gdf.to_file(filepath, driver="GeoJSON") else: return gdf.__geo_interface__
Download OSM entities within boundaries of a (multi)polygon as a GeoJSON. Args: polygon (shapely.geometry.Polygon | shapely.geometry.MultiPolygon): Geographic boundaries to fetch geometries within tags (dict): Dict of tags used for finding objects in the selected area. Results returned are the union, not intersection of each individual tag. Each result matches at least one given tag. The dict keys should be OSM tags, (e.g., building, landuse, highway, etc) and the dict values should be either True to retrieve all items with the given tag, or a string to get a single tag-value combination, or a list of strings to get multiple values for the given tag. For example, tags = {‘building’: True} would return all building footprints in the area. tags = {‘amenity’:True, ‘landuse’:[‘retail’,’commercial’], ‘highway’:’bus_stop’} would return all amenities, landuse=retail, landuse=commercial, and highway=bus_stop. filepath (str, optional): File path to the output GeoJSON. Returns: dict: A GeoJSON dictionary of OSM entities.
12,210
from .common import check_package def osm_gdf_from_bbox(north, south, east, west, tags): """Create a GeoDataFrame of OSM entities within a N, S, E, W bounding box. Args: north (float): Northern latitude of bounding box. south (float): Southern latitude of bounding box. east (float): Eastern longitude of bounding box. west (float): Western longitude of bounding box. tags (dict): Dict of tags used for finding objects in the selected area. Results returned are the union, not intersection of each individual tag. Each result matches at least one given tag. The dict keys should be OSM tags, (e.g., building, landuse, highway, etc) and the dict values should be either True to retrieve all items with the given tag, or a string to get a single tag-value combination, or a list of strings to get multiple values for the given tag. For example, tags = {‘building’: True} would return all building footprints in the area. tags = {‘amenity’:True, ‘landuse’:[‘retail’,’commercial’], ‘highway’:’bus_stop’} would return all amenities, landuse=retail, landuse=commercial, and highway=bus_stop. Returns: GeoDataFrame: A GeoDataFrame of OSM entities. """ check_package("osmnx", "https://osmnx.readthedocs.io/en/stable/#installation") import osmnx as ox gdf = ox.geometries_from_bbox(north, south, east, west, tags) return gdf The provided code snippet includes necessary dependencies for implementing the `osm_shp_from_bbox` function. Write a Python function `def osm_shp_from_bbox(north, south, east, west, tags, filepath)` to solve the following problem: Download OSM entities within a N, S, E, W bounding box as a shapefile. Args: north (float): Northern latitude of bounding box. south (float): Southern latitude of bounding box. east (float): Eastern longitude of bounding box. west (float): Western longitude of bounding box. tags (dict): Dict of tags used for finding objects in the selected area. Results returned are the union, not intersection of each individual tag. Each result matches at least one given tag. The dict keys should be OSM tags, (e.g., building, landuse, highway, etc) and the dict values should be either True to retrieve all items with the given tag, or a string to get a single tag-value combination, or a list of strings to get multiple values for the given tag. For example, tags = {‘building’: True} would return all building footprints in the area. tags = {‘amenity’:True, ‘landuse’:[‘retail’,’commercial’], ‘highway’:’bus_stop’} would return all amenities, landuse=retail, landuse=commercial, and highway=bus_stop. filepath (str): File path to the output shapefile. Here is the function: def osm_shp_from_bbox(north, south, east, west, tags, filepath): """Download OSM entities within a N, S, E, W bounding box as a shapefile. Args: north (float): Northern latitude of bounding box. south (float): Southern latitude of bounding box. east (float): Eastern longitude of bounding box. west (float): Western longitude of bounding box. tags (dict): Dict of tags used for finding objects in the selected area. Results returned are the union, not intersection of each individual tag. Each result matches at least one given tag. The dict keys should be OSM tags, (e.g., building, landuse, highway, etc) and the dict values should be either True to retrieve all items with the given tag, or a string to get a single tag-value combination, or a list of strings to get multiple values for the given tag. For example, tags = {‘building’: True} would return all building footprints in the area. tags = {‘amenity’:True, ‘landuse’:[‘retail’,’commercial’], ‘highway’:’bus_stop’} would return all amenities, landuse=retail, landuse=commercial, and highway=bus_stop. filepath (str): File path to the output shapefile. """ gdf = osm_gdf_from_bbox(north, south, east, west, tags) gdf.to_file(filepath)
Download OSM entities within a N, S, E, W bounding box as a shapefile. Args: north (float): Northern latitude of bounding box. south (float): Southern latitude of bounding box. east (float): Eastern longitude of bounding box. west (float): Western longitude of bounding box. tags (dict): Dict of tags used for finding objects in the selected area. Results returned are the union, not intersection of each individual tag. Each result matches at least one given tag. The dict keys should be OSM tags, (e.g., building, landuse, highway, etc) and the dict values should be either True to retrieve all items with the given tag, or a string to get a single tag-value combination, or a list of strings to get multiple values for the given tag. For example, tags = {‘building’: True} would return all building footprints in the area. tags = {‘amenity’:True, ‘landuse’:[‘retail’,’commercial’], ‘highway’:’bus_stop’} would return all amenities, landuse=retail, landuse=commercial, and highway=bus_stop. filepath (str): File path to the output shapefile.
12,211
from .common import check_package def osm_gdf_from_bbox(north, south, east, west, tags): """Create a GeoDataFrame of OSM entities within a N, S, E, W bounding box. Args: north (float): Northern latitude of bounding box. south (float): Southern latitude of bounding box. east (float): Eastern longitude of bounding box. west (float): Western longitude of bounding box. tags (dict): Dict of tags used for finding objects in the selected area. Results returned are the union, not intersection of each individual tag. Each result matches at least one given tag. The dict keys should be OSM tags, (e.g., building, landuse, highway, etc) and the dict values should be either True to retrieve all items with the given tag, or a string to get a single tag-value combination, or a list of strings to get multiple values for the given tag. For example, tags = {‘building’: True} would return all building footprints in the area. tags = {‘amenity’:True, ‘landuse’:[‘retail’,’commercial’], ‘highway’:’bus_stop’} would return all amenities, landuse=retail, landuse=commercial, and highway=bus_stop. Returns: GeoDataFrame: A GeoDataFrame of OSM entities. """ check_package("osmnx", "https://osmnx.readthedocs.io/en/stable/#installation") import osmnx as ox gdf = ox.geometries_from_bbox(north, south, east, west, tags) return gdf The provided code snippet includes necessary dependencies for implementing the `osm_geojson_from_bbox` function. Write a Python function `def osm_geojson_from_bbox(north, south, east, west, tags, filepath=None)` to solve the following problem: Download OSM entities within a N, S, E, W bounding box as a GeoJSON. Args: north (float): Northern latitude of bounding box. south (float): Southern latitude of bounding box. east (float): Eastern longitude of bounding box. west (float): Western longitude of bounding box. tags (dict): Dict of tags used for finding objects in the selected area. Results returned are the union, not intersection of each individual tag. Each result matches at least one given tag. The dict keys should be OSM tags, (e.g., building, landuse, highway, etc) and the dict values should be either True to retrieve all items with the given tag, or a string to get a single tag-value combination, or a list of strings to get multiple values for the given tag. For example, tags = {‘building’: True} would return all building footprints in the area. tags = {‘amenity’:True, ‘landuse’:[‘retail’,’commercial’], ‘highway’:’bus_stop’} would return all amenities, landuse=retail, landuse=commercial, and highway=bus_stop. filepath (str, optional): File path to the output GeoJSON. Returns: dict: A GeoJSON dictionary of OSM entities. Here is the function: def osm_geojson_from_bbox(north, south, east, west, tags, filepath=None): """Download OSM entities within a N, S, E, W bounding box as a GeoJSON. Args: north (float): Northern latitude of bounding box. south (float): Southern latitude of bounding box. east (float): Eastern longitude of bounding box. west (float): Western longitude of bounding box. tags (dict): Dict of tags used for finding objects in the selected area. Results returned are the union, not intersection of each individual tag. Each result matches at least one given tag. The dict keys should be OSM tags, (e.g., building, landuse, highway, etc) and the dict values should be either True to retrieve all items with the given tag, or a string to get a single tag-value combination, or a list of strings to get multiple values for the given tag. For example, tags = {‘building’: True} would return all building footprints in the area. tags = {‘amenity’:True, ‘landuse’:[‘retail’,’commercial’], ‘highway’:’bus_stop’} would return all amenities, landuse=retail, landuse=commercial, and highway=bus_stop. filepath (str, optional): File path to the output GeoJSON. Returns: dict: A GeoJSON dictionary of OSM entities. """ gdf = osm_gdf_from_bbox(north, south, east, west, tags) if filepath is not None: gdf.to_file(filepath, driver="GeoJSON") else: return gdf.__geo_interface__
Download OSM entities within a N, S, E, W bounding box as a GeoJSON. Args: north (float): Northern latitude of bounding box. south (float): Southern latitude of bounding box. east (float): Eastern longitude of bounding box. west (float): Western longitude of bounding box. tags (dict): Dict of tags used for finding objects in the selected area. Results returned are the union, not intersection of each individual tag. Each result matches at least one given tag. The dict keys should be OSM tags, (e.g., building, landuse, highway, etc) and the dict values should be either True to retrieve all items with the given tag, or a string to get a single tag-value combination, or a list of strings to get multiple values for the given tag. For example, tags = {‘building’: True} would return all building footprints in the area. tags = {‘amenity’:True, ‘landuse’:[‘retail’,’commercial’], ‘highway’:’bus_stop’} would return all amenities, landuse=retail, landuse=commercial, and highway=bus_stop. filepath (str, optional): File path to the output GeoJSON. Returns: dict: A GeoJSON dictionary of OSM entities.
12,212
from .common import check_package def check_package(name, URL=""): try: __import__(name.lower()) except Exception: raise ImportError( f"{name} is not installed. Please install it before proceeding. {URL}" ) The provided code snippet includes necessary dependencies for implementing the `osm_gdf_from_xml` function. Write a Python function `def osm_gdf_from_xml(filepath, polygon=None, tags=None)` to solve the following problem: Create a GeoDataFrame of OSM entities in an OSM-formatted XML file. Args: filepath (str): File path to file containing OSM XML data polygon (shapely.geometry.Polygon, optional): Optional geographic boundary to filter objects. Defaults to None. tags (dict): Dict of tags used for finding objects in the selected area. Results returned are the union, not intersection of each individual tag. Each result matches at least one given tag. The dict keys should be OSM tags, (e.g., building, landuse, highway, etc) and the dict values should be either True to retrieve all items with the given tag, or a string to get a single tag-value combination, or a list of strings to get multiple values for the given tag. For example, tags = {‘building’: True} would return all building footprints in the area. tags = {‘amenity’:True, ‘landuse’:[‘retail’,’commercial’], ‘highway’:’bus_stop’} would return all amenities, landuse=retail, landuse=commercial, and highway=bus_stop. Returns: GeoDataFrame: A GeoDataFrame of OSM entities. Here is the function: def osm_gdf_from_xml(filepath, polygon=None, tags=None): """Create a GeoDataFrame of OSM entities in an OSM-formatted XML file. Args: filepath (str): File path to file containing OSM XML data polygon (shapely.geometry.Polygon, optional): Optional geographic boundary to filter objects. Defaults to None. tags (dict): Dict of tags used for finding objects in the selected area. Results returned are the union, not intersection of each individual tag. Each result matches at least one given tag. The dict keys should be OSM tags, (e.g., building, landuse, highway, etc) and the dict values should be either True to retrieve all items with the given tag, or a string to get a single tag-value combination, or a list of strings to get multiple values for the given tag. For example, tags = {‘building’: True} would return all building footprints in the area. tags = {‘amenity’:True, ‘landuse’:[‘retail’,’commercial’], ‘highway’:’bus_stop’} would return all amenities, landuse=retail, landuse=commercial, and highway=bus_stop. Returns: GeoDataFrame: A GeoDataFrame of OSM entities. """ check_package("osmnx", "https://osmnx.readthedocs.io/en/stable/#installation") import osmnx as ox gdf = ox.geometries_from_xml(filepath, polygon, tags) return gdf
Create a GeoDataFrame of OSM entities in an OSM-formatted XML file. Args: filepath (str): File path to file containing OSM XML data polygon (shapely.geometry.Polygon, optional): Optional geographic boundary to filter objects. Defaults to None. tags (dict): Dict of tags used for finding objects in the selected area. Results returned are the union, not intersection of each individual tag. Each result matches at least one given tag. The dict keys should be OSM tags, (e.g., building, landuse, highway, etc) and the dict values should be either True to retrieve all items with the given tag, or a string to get a single tag-value combination, or a list of strings to get multiple values for the given tag. For example, tags = {‘building’: True} would return all building footprints in the area. tags = {‘amenity’:True, ‘landuse’:[‘retail’,’commercial’], ‘highway’:’bus_stop’} would return all amenities, landuse=retail, landuse=commercial, and highway=bus_stop. Returns: GeoDataFrame: A GeoDataFrame of OSM entities.
12,213
from .common import check_package def osm_gdf_from_geocode( query, which_result=None, by_osmid=False, buffer_dist=None, ): """Retrieves place(s) by name or ID from the Nominatim API as a GeoDataFrame. Args: query (str | dict | list): Query string(s) or structured dict(s) to geocode. which_result (INT, optional): Which geocoding result to use. if None, auto-select the first (Multi)Polygon or raise an error if OSM doesn't return one. to get the top match regardless of geometry type, set which_result=1. Defaults to None. by_osmid (bool, optional): If True, handle query as an OSM ID for lookup rather than text search. Defaults to False. buffer_dist (float, optional): Distance to buffer around the place geometry, in meters. Defaults to None. Returns: GeoDataFrame: A GeoPandas GeoDataFrame. """ check_package("osmnx", "https://osmnx.readthedocs.io/en/stable/") import osmnx as ox gdf = ox.geocode_to_gdf(query, which_result, by_osmid, buffer_dist) return gdf The provided code snippet includes necessary dependencies for implementing the `osm_shp_from_geocode` function. Write a Python function `def osm_shp_from_geocode( query, filepath, which_result=None, by_osmid=False, buffer_dist=None, )` to solve the following problem: Download place(s) by name or ID from the Nominatim API as a shapefile. Args: query (str | dict | list): Query string(s) or structured dict(s) to geocode. filepath (str): File path to the output shapefile. which_result (int, optional): Which geocoding result to use. if None, auto-select the first (Multi)Polygon or raise an error if OSM doesn't return one. to get the top match regardless of geometry type, set which_result=1. Defaults to None. by_osmid (bool, optional): If True, handle query as an OSM ID for lookup rather than text search. Defaults to False. buffer_dist (float, optional): Distance to buffer around the place geometry, in meters. Defaults to None. Here is the function: def osm_shp_from_geocode( query, filepath, which_result=None, by_osmid=False, buffer_dist=None, ): """Download place(s) by name or ID from the Nominatim API as a shapefile. Args: query (str | dict | list): Query string(s) or structured dict(s) to geocode. filepath (str): File path to the output shapefile. which_result (int, optional): Which geocoding result to use. if None, auto-select the first (Multi)Polygon or raise an error if OSM doesn't return one. to get the top match regardless of geometry type, set which_result=1. Defaults to None. by_osmid (bool, optional): If True, handle query as an OSM ID for lookup rather than text search. Defaults to False. buffer_dist (float, optional): Distance to buffer around the place geometry, in meters. Defaults to None. """ gdf = osm_gdf_from_geocode(query, which_result, by_osmid, buffer_dist) gdf.to_file(filepath)
Download place(s) by name or ID from the Nominatim API as a shapefile. Args: query (str | dict | list): Query string(s) or structured dict(s) to geocode. filepath (str): File path to the output shapefile. which_result (int, optional): Which geocoding result to use. if None, auto-select the first (Multi)Polygon or raise an error if OSM doesn't return one. to get the top match regardless of geometry type, set which_result=1. Defaults to None. by_osmid (bool, optional): If True, handle query as an OSM ID for lookup rather than text search. Defaults to False. buffer_dist (float, optional): Distance to buffer around the place geometry, in meters. Defaults to None.
12,214
from .common import check_package def osm_gdf_from_geocode( query, which_result=None, by_osmid=False, buffer_dist=None, ): """Retrieves place(s) by name or ID from the Nominatim API as a GeoDataFrame. Args: query (str | dict | list): Query string(s) or structured dict(s) to geocode. which_result (INT, optional): Which geocoding result to use. if None, auto-select the first (Multi)Polygon or raise an error if OSM doesn't return one. to get the top match regardless of geometry type, set which_result=1. Defaults to None. by_osmid (bool, optional): If True, handle query as an OSM ID for lookup rather than text search. Defaults to False. buffer_dist (float, optional): Distance to buffer around the place geometry, in meters. Defaults to None. Returns: GeoDataFrame: A GeoPandas GeoDataFrame. """ check_package("osmnx", "https://osmnx.readthedocs.io/en/stable/") import osmnx as ox gdf = ox.geocode_to_gdf(query, which_result, by_osmid, buffer_dist) return gdf The provided code snippet includes necessary dependencies for implementing the `osm_geojson_from_geocode` function. Write a Python function `def osm_geojson_from_geocode( query, filepath=None, which_result=None, by_osmid=False, buffer_dist=None, )` to solve the following problem: Download place(s) by name or ID from the Nominatim API as a GeoJSON. Args: query (str | dict | list): Query string(s) or structured dict(s) to geocode. filepath (str): File path to the output GeoJSON. which_result (int, optional): Which geocoding result to use. if None, auto-select the first (Multi)Polygon or raise an error if OSM doesn't return one. to get the top match regardless of geometry type, set which_result=1. Defaults to None. by_osmid (bool, optional): If True, handle query as an OSM ID for lookup rather than text search. Defaults to False. buffer_dist (float, optional): Distance to buffer around the place geometry, in meters. Defaults to None. Returns: dict: A GeoJSON dictionary of OSM entities. Here is the function: def osm_geojson_from_geocode( query, filepath=None, which_result=None, by_osmid=False, buffer_dist=None, ): """Download place(s) by name or ID from the Nominatim API as a GeoJSON. Args: query (str | dict | list): Query string(s) or structured dict(s) to geocode. filepath (str): File path to the output GeoJSON. which_result (int, optional): Which geocoding result to use. if None, auto-select the first (Multi)Polygon or raise an error if OSM doesn't return one. to get the top match regardless of geometry type, set which_result=1. Defaults to None. by_osmid (bool, optional): If True, handle query as an OSM ID for lookup rather than text search. Defaults to False. buffer_dist (float, optional): Distance to buffer around the place geometry, in meters. Defaults to None. Returns: dict: A GeoJSON dictionary of OSM entities. """ gdf = osm_gdf_from_geocode(query, which_result, by_osmid, buffer_dist) if filepath is not None: gdf.to_file(filepath, driver="GeoJSON") else: return gdf.__geo_interface__
Download place(s) by name or ID from the Nominatim API as a GeoJSON. Args: query (str | dict | list): Query string(s) or structured dict(s) to geocode. filepath (str): File path to the output GeoJSON. which_result (int, optional): Which geocoding result to use. if None, auto-select the first (Multi)Polygon or raise an error if OSM doesn't return one. to get the top match regardless of geometry type, set which_result=1. Defaults to None. by_osmid (bool, optional): If True, handle query as an OSM ID for lookup rather than text search. Defaults to False. buffer_dist (float, optional): Distance to buffer around the place geometry, in meters. Defaults to None. Returns: dict: A GeoJSON dictionary of OSM entities.
12,215
from .common import check_package The provided code snippet includes necessary dependencies for implementing the `osm_tags_list` function. Write a Python function `def osm_tags_list()` to solve the following problem: Open a browser to see all tags of OSM features. Here is the function: def osm_tags_list(): """Open a browser to see all tags of OSM features.""" import webbrowser webbrowser.open_new_tab("https://wiki.openstreetmap.org/wiki/Map_features")
Open a browser to see all tags of OSM features.
12,216
import multiprocessing as mp import os from functools import partial import ee import numpy as np import pandas as pd def tree_to_string(estimator, feature_names, labels=None, output_mode="INFER"): """Function to convert a sklearn decision tree object to a string format that EE can interpret args: estimator (sklearn.tree.estimator): An estimator consisting of multiple decision tree classifiers. Expects object to contain estimators_ attribute feature_names (Iterable[str]): List of strings that define the name of features (i.e. bands) used to create the model labels (Iterable[numeric]): List of class labels to map outputs to, must be numeric values. If None, then raw outputs will be used. default = None output_mode (str): the output mode of the estimator. Options are "INFER", "CLASSIFIATION", or "REGRESSION" (capitalization does not matter). default = "INFER" returns: tree_str (str): string representation of decision tree estimator raises: RuntimeError: raises run time error when function cannot determine if the estimator is for regression or classification problem """ # extract out the information need to build the tree string n_nodes = estimator.tree_.node_count children_left = estimator.tree_.children_left children_right = estimator.tree_.children_right feature_idx = estimator.tree_.feature impurities = estimator.tree_.impurity n_samples = estimator.tree_.n_node_samples thresholds = estimator.tree_.threshold features = [feature_names[i] for i in feature_idx] raw_vals = np.squeeze(estimator.tree_.value) # first check if user wants to infer output mode # if so, reset the output_mode variable to a valid mode if output_mode == "INFER": if raw_vals.ndim == 2: output_mode = "CLASSIFICATION" elif raw_vals.ndim == 1: output_mode = "REGRESSION" else: raise RuntimeError( "Could not infer the output type from the estimator, please explicitly provide the output_mode " ) # second check on the output mode after the inference if output_mode == "CLASSIFICATION": # take argmax along class axis from values values = raw_vals.argmax(axis=-1) if labels is not None: index_labels = np.unique(values) lookup = {idx: labels[i] for i, idx in enumerate(index_labels)} values = [lookup[v] for v in values] out_type = int elif output_mode == "REGRESSION": # take values and drop un needed axis values = np.around(raw_vals, decimals=6) out_type = float elif output_mode == "PROBABILITY": # calculate fraction of samples of the same class in a leaf # currently only supporting binary classifications # check if n classes == 2 (i.e. binary classes) if raw_vals.shape[-1] != 2: raise ValueError( "shape mismatch: outputs from trees = {raw_vals.shape[-1]} classes, currently probability outputs is support for binary classifications" ) probas = np.around( (raw_vals / np.sum(raw_vals, axis=1)[:, np.newaxis]), decimals=6 ) values = probas[:, -1] out_type = float elif output_mode == "MULTIPROBABILITY": # calculate fraction of samples of the same class in a leaf # this is a 2-d array making the output multidimensional raise NotImplementedError( "Currently multiprobability output is not support, please choose one of the following output modes: ['CLASSIFIATION', 'REGRESSION', 'PROBABILITY' or 'INFER']" ) # probas = np.around( # (raw_vals / np.sum(raw_vals,axis=1)[:,np.newaxis]), # decimals=6 # ) # values = probas.tolist() # out_type = list else: raise RuntimeError( "could not understand estimator type and parse out the values" ) # use iterative pre-order search to extract node depth and leaf information node_ids = np.zeros(shape=n_nodes, dtype=np.int64) node_depth = np.zeros(shape=n_nodes, dtype=np.int64) is_leaves = np.zeros(shape=n_nodes, dtype=bool) stack = [(0, -1)] # seed is the root node id and its parent depth while len(stack) > 0: node_id, parent_depth = stack.pop() node_depth[node_id] = parent_depth + 1 node_ids[node_id] = node_id # If we have a test node if children_left[node_id] != children_right[node_id]: stack.append((children_left[node_id], parent_depth + 1)) stack.append((children_right[node_id], parent_depth + 1)) else: is_leaves[node_id] = True # create a table of the initial structure # each row is a node or leaf df = pd.DataFrame( { "node_id": node_ids, "node_depth": node_depth, "is_leaf": is_leaves, "children_left": children_left, "children_right": children_right, "value": values, "criterion": impurities, "n_samples": n_samples, "threshold": thresholds, "feature_name": features, "sign": ["<="] * n_nodes, }, dtype="object", ) # the table representation does not have lef vs right node structure # so we need to add in right nodes in the correct location # we do this by first calculating which nodes are right and then insert them at the correct index # get a dict of right node rows and assign key based on index where to insert inserts = {} for row in df.itertuples(): child_r = row.children_right if child_r > row.Index: ordered_row = np.array(row) ordered_row[-1] = ">" inserts[child_r] = ordered_row[1:] # drop index value # sort the inserts as to keep track of the additive indexing inserts_sorted = {k: inserts[k] for k in sorted(inserts.keys())} # loop through the row inserts and add to table (array) table_values = df.values for i, k in enumerate(inserts_sorted.keys()): table_values = np.insert(table_values, (k + i), inserts_sorted[k], axis=0) # make the ordered table array into a dataframe # note: df is dtype "object", need to cast later on ordered_df = pd.DataFrame(table_values, columns=df.columns) max_depth = np.max(ordered_df.node_depth.astype(int)) tree_str = f"1) root {n_samples[0]} 9999 9999 ({impurities.sum()})\n" previous_depth = -1 cnts = [] # loop through the nodes and calculate the node number and values per node for row in ordered_df.itertuples(): node_depth = int(row.node_depth) left = int(row.children_left) right = int(row.children_right) if left != right: if row.Index == 0: cnt = 2 elif previous_depth > node_depth: depths = ordered_df.node_depth.values[: row.Index] idx = np.where(depths == node_depth)[0][-1] # cnt = (cnts[row.Index-1] // 2) + 1 cnt = cnts[idx] + 1 elif previous_depth < node_depth: cnt = cnts[row.Index - 1] * 2 elif previous_depth == node_depth: cnt = cnts[row.Index - 1] + 1 if node_depth == (max_depth - 1): value = out_type(ordered_df.iloc[row.Index + 1].value) samps = int(ordered_df.iloc[row.Index + 1].n_samples) criterion = float(ordered_df.iloc[row.Index + 1].criterion) tail = " *\n" else: if ( (bool(ordered_df.loc[ordered_df.node_id == left].iloc[0].is_leaf)) and ( bool( int(row.Index) < int(ordered_df.loc[ordered_df.node_id == left].index[0]) ) ) and (str(row.sign) == "<=") ): rowx = ordered_df.loc[ordered_df.node_id == left].iloc[0] tail = " *\n" value = out_type(rowx.value) samps = int(rowx.n_samples) criterion = float(rowx.criterion) elif ( (bool(ordered_df.loc[ordered_df.node_id == right].iloc[0].is_leaf)) and ( bool( int(row.Index) < int(ordered_df.loc[ordered_df.node_id == right].index[0]) ) ) and (str(row.sign) == ">") ): rowx = ordered_df.loc[ordered_df.node_id == right].iloc[0] tail = " *\n" value = out_type(rowx.value) samps = int(rowx.n_samples) criterion = float(rowx.criterion) else: value = out_type(row.value) samps = int(row.n_samples) criterion = float(row.criterion) tail = "\n" # extract out the information needed in each line spacing = (node_depth + 1) * " " # for pretty printing fname = str(row.feature_name) # name of the feature (i.e. band name) tresh = float(row.threshold) # threshold sign = str(row.sign) tree_str += f"{spacing}{cnt}) {fname} {sign} {tresh:.6f} {samps} {criterion:.4f} {value}{tail}" previous_depth = node_depth cnts.append(cnt) return tree_str The provided code snippet includes necessary dependencies for implementing the `rf_to_strings` function. Write a Python function `def rf_to_strings(estimator, feature_names, processes=2, output_mode="INFER")` to solve the following problem: Function to convert a ensemble of decision trees into a list of strings. Wraps `tree_to_string` args: estimator (sklearn.ensemble.estimator): A decision tree classifier or regressor object created using sklearn feature_names (list[str]): List of strings that define the name of features (i.e. bands) used to create the model processes (int): number of cpu processes to spawn. Increasing processes will improve speed for large models. default = 2 output_mode (str): the output mode of the estimator. Options are "INFER", "CLASSIFIATION", or "REGRESSION" (capitalization does not matter). default = "INFER" returns: trees (list[str]): list of strings where each string represents a decision tree estimator and collectively represent an ensemble decision tree estimator (i.e. RandomForest) Here is the function: def rf_to_strings(estimator, feature_names, processes=2, output_mode="INFER"): """Function to convert a ensemble of decision trees into a list of strings. Wraps `tree_to_string` args: estimator (sklearn.ensemble.estimator): A decision tree classifier or regressor object created using sklearn feature_names (list[str]): List of strings that define the name of features (i.e. bands) used to create the model processes (int): number of cpu processes to spawn. Increasing processes will improve speed for large models. default = 2 output_mode (str): the output mode of the estimator. Options are "INFER", "CLASSIFIATION", or "REGRESSION" (capitalization does not matter). default = "INFER" returns: trees (list[str]): list of strings where each string represents a decision tree estimator and collectively represent an ensemble decision tree estimator (i.e. RandomForest) """ # force output mode to be capital output_mode = output_mode.upper() available_modes = ["INFER", "CLASSIFICATION", "REGRESSION", "PROBABILITY"] if output_mode not in available_modes: raise ValueError( f"The provided output_mode is not available, please provide one from the following list: {available_modes}" ) # extract out the estimator trees estimators = np.squeeze(estimator.estimators_) if output_mode == "INFER": if estimator.criterion in ["gini", "entropy"]: class_labels = estimator.classes_ elif estimator.criterion in ["mse", "mae"]: class_labels = None else: raise RuntimeError( "Could not infer the output type from the estimator, please explicitly provide the output_mode " ) elif output_mode == "CLASSIFICATION": class_labels = estimator.classes_ else: class_labels = None # check that number of processors set to use is not more than available if processes >= mp.cpu_count(): # if so, force to use only cpu count - 1 processes = mp.cpu_count() - 1 # run the tree extraction process in parallel with mp.Pool(processes) as pool: proc = pool.map_async( partial( tree_to_string, feature_names=feature_names, labels=class_labels, output_mode=output_mode, ), estimators, ) trees = list(proc.get()) return trees
Function to convert a ensemble of decision trees into a list of strings. Wraps `tree_to_string` args: estimator (sklearn.ensemble.estimator): A decision tree classifier or regressor object created using sklearn feature_names (list[str]): List of strings that define the name of features (i.e. bands) used to create the model processes (int): number of cpu processes to spawn. Increasing processes will improve speed for large models. default = 2 output_mode (str): the output mode of the estimator. Options are "INFER", "CLASSIFIATION", or "REGRESSION" (capitalization does not matter). default = "INFER" returns: trees (list[str]): list of strings where each string represents a decision tree estimator and collectively represent an ensemble decision tree estimator (i.e. RandomForest)
12,217
import multiprocessing as mp import os from functools import partial import ee import numpy as np import pandas as pd The provided code snippet includes necessary dependencies for implementing the `strings_to_classifier` function. Write a Python function `def strings_to_classifier(trees)` to solve the following problem: Function that takes string representation of decision trees and creates a ee.Classifier that can be used with ee objects args: trees (list[str]): list of string representation of the decision trees returns: classifier (ee.Classifier): ee classifier object representing an ensemble decision tree Here is the function: def strings_to_classifier(trees): """Function that takes string representation of decision trees and creates a ee.Classifier that can be used with ee objects args: trees (list[str]): list of string representation of the decision trees returns: classifier (ee.Classifier): ee classifier object representing an ensemble decision tree """ # convert strings to ee.String objects ee_strings = [ee.String(tree) for tree in trees] # pass list of ee.Strings to an ensemble decision tree classifier (i.e. RandomForest) classifier = ee.Classifier.decisionTreeEnsemble(ee_strings) return classifier
Function that takes string representation of decision trees and creates a ee.Classifier that can be used with ee objects args: trees (list[str]): list of string representation of the decision trees returns: classifier (ee.Classifier): ee classifier object representing an ensemble decision tree
12,218
import multiprocessing as mp import os from functools import partial import ee import numpy as np import pandas as pd The provided code snippet includes necessary dependencies for implementing the `export_trees_to_fc` function. Write a Python function `def export_trees_to_fc(trees, asset_id, description="geemap_rf_export")` to solve the following problem: Function that creates a feature collection with a property tree which contains the string representation of decision trees and exports to ee asset for later use args: trees (list[str]): list of string representation of the decision trees asset_id (str): ee asset id path to export the feature collection to kwargs: description (str): optional description to provide export information. default = "geemap_rf_export" Here is the function: def export_trees_to_fc(trees, asset_id, description="geemap_rf_export"): """Function that creates a feature collection with a property tree which contains the string representation of decision trees and exports to ee asset for later use args: trees (list[str]): list of string representation of the decision trees asset_id (str): ee asset id path to export the feature collection to kwargs: description (str): optional description to provide export information. default = "geemap_rf_export" """ # create a null geometry point. This is needed to properly export the feature collection null_island = ee.Geometry.Point([0, 0]) # create a list of feature over null island # set the tree property as the tree string # encode return values (\n) as #, use to parse later features = [ ee.Feature(null_island, {"tree": tree.replace("\n", "#")}) for tree in trees ] # cast as feature collection fc = ee.FeatureCollection(features) # get export task and start task = ee.batch.Export.table.toAsset( collection=fc, description=description, assetId=asset_id ) task.start()
Function that creates a feature collection with a property tree which contains the string representation of decision trees and exports to ee asset for later use args: trees (list[str]): list of string representation of the decision trees asset_id (str): ee asset id path to export the feature collection to kwargs: description (str): optional description to provide export information. default = "geemap_rf_export"
12,219
import multiprocessing as mp import os from functools import partial import ee import numpy as np import pandas as pd The provided code snippet includes necessary dependencies for implementing the `trees_to_csv` function. Write a Python function `def trees_to_csv(trees, out_csv)` to solve the following problem: Save a list of strings (an ensemble of decision trees) to a CSV file. Args: trees (list): A list of strings (an ensemble of decision trees). out_csv (str): File path to the output csv Here is the function: def trees_to_csv(trees, out_csv): """Save a list of strings (an ensemble of decision trees) to a CSV file. Args: trees (list): A list of strings (an ensemble of decision trees). out_csv (str): File path to the output csv """ out_csv = os.path.abspath(out_csv) with open(out_csv, "w") as f: f.writelines([tree.replace("\n", "#") + "\n" for tree in trees])
Save a list of strings (an ensemble of decision trees) to a CSV file. Args: trees (list): A list of strings (an ensemble of decision trees). out_csv (str): File path to the output csv
12,220
import multiprocessing as mp import os from functools import partial import ee import numpy as np import pandas as pd def fc_to_classifier(fc): """Function that takes a feature collection resulting from `export_trees_to_fc` and creates a ee.Classifier that can be used with ee objects args: fc (ee.FeatureCollection): feature collection that has trees property for each feature that represents the decision tree returns: classifier (ee.Classifier): ee classifier object representing an ensemble decision tree """ # get a list of tree strings from feature collection tree_strings = fc.aggregate_array("tree").map( lambda x: ee.String(x).replace( "#", "\n", "g" ) # expects that # is ecoded to be a return ) # pass list of ee.Strings to an ensemble decision tree classifier (i.e. RandomForest) classifier = ee.Classifier.decisionTreeEnsemble(tree_strings) return classifier The provided code snippet includes necessary dependencies for implementing the `csv_to_classifier` function. Write a Python function `def csv_to_classifier(in_csv)` to solve the following problem: Convert a CSV file containing a list of strings (an ensemble of decision trees) to an ee.Classifier. Args: in_csv (str): File path to the input CSV. Returns: object: ee.Classifier. Here is the function: def csv_to_classifier(in_csv): """Convert a CSV file containing a list of strings (an ensemble of decision trees) to an ee.Classifier. Args: in_csv (str): File path to the input CSV. Returns: object: ee.Classifier. """ in_csv = os.path.join(in_csv) try: with open(in_csv) as f: lines = f.readlines() except FileNotFoundError: print(f"{in_csv} could not be found.") return None null_island = ee.Geometry.Point([0, 0]) features = [ee.Feature(null_island, {"tree": line.strip()}) for line in lines] rf_fc = ee.FeatureCollection(features) classifier = fc_to_classifier(rf_fc) return classifier
Convert a CSV file containing a list of strings (an ensemble of decision trees) to an ee.Classifier. Args: in_csv (str): File path to the input CSV. Returns: object: ee.Classifier.
12,221
import box import ee import folium import ipyleaflet from functools import lru_cache from . import common def _ee_object_to_image(ee_object, vis_params): def _get_tile_url_format(ee_object, vis_params): image = _ee_object_to_image(ee_object, vis_params) map_id_dict = ee.Image(image).getMapId(vis_params) return map_id_dict["tile_fetcher"].url_format
null
12,222
import box import ee import folium import ipyleaflet from functools import lru_cache from . import common def _validate_palette(palette): if isinstance(palette, tuple): palette = list(palette) if isinstance(palette, box.Box): if "default" not in palette: raise ValueError("The provided palette Box object is invalid.") return list(palette["default"]) if isinstance(palette, str): return common.check_cmap(palette) if isinstance(palette, list): return palette raise ValueError("The palette must be a list of colors, a string, or a Box object.") def _validate_vis_params(vis_params): if vis_params is None: return {} if not isinstance(vis_params, dict): raise TypeError("vis_params must be a dictionary") valid_dict = vis_params.copy() if "palette" in valid_dict: valid_dict["palette"] = _validate_palette(valid_dict["palette"]) return valid_dict
null
12,223
import os import numpy as np import pandas as pd import ipywidgets as widgets from .basemaps import xyz_to_plotly from .common import * from .osm import * from . import examples import os import shutil The provided code snippet includes necessary dependencies for implementing the `fix_widget_error` function. Write a Python function `def fix_widget_error()` to solve the following problem: Fix FigureWidget - 'mapbox._derived' Value Error. Adopted from: https://github.com/plotly/plotly.py/issues/2570#issuecomment-738735816 Here is the function: def fix_widget_error(): """ Fix FigureWidget - 'mapbox._derived' Value Error. Adopted from: https://github.com/plotly/plotly.py/issues/2570#issuecomment-738735816 """ import shutil basedatatypesPath = os.path.join( os.path.dirname(os.__file__), "site-packages", "plotly", "basedatatypes.py" ) backup_file = basedatatypesPath.replace(".py", "_bk.py") shutil.copyfile(basedatatypesPath, backup_file) # read basedatatypes.py with open(basedatatypesPath, "r") as f: lines = f.read() find = "if not BaseFigure._is_key_path_compatible(key_path_str, self.layout):" replace = """if not BaseFigure._is_key_path_compatible(key_path_str, self.layout): if key_path_str == "mapbox._derived": return""" # add new text lines = lines.replace(find, replace) # overwrite old 'basedatatypes.py' with open(basedatatypesPath, "w") as f: f.write(lines)
Fix FigureWidget - 'mapbox._derived' Value Error. Adopted from: https://github.com/plotly/plotly.py/issues/2570#issuecomment-738735816
12,224
import collections import os import requests import folium import ipyleaflet import xyzservices from .common import check_package, planet_tiles XYZ_TILES = { "OpenStreetMap": { "url": "https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", "attribution": "OpenStreetMap", "name": "OpenStreetMap", }, "ROADMAP": { "url": "https://server.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer/tile/{z}/{y}/{x}", "attribution": "Esri", "name": "Esri.WorldStreetMap", }, "SATELLITE": { "url": "https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}", "attribution": "Esri", "name": "Esri.WorldImagery", }, "TERRAIN": { "url": "https://server.arcgisonline.com/ArcGIS/rest/services/World_Topo_Map/MapServer/tile/{z}/{y}/{x}", "attribution": "Esri", "name": "Esri.WorldTopoMap", }, "HYBRID": { "url": "https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}", "attribution": "Esri", "name": "Esri.WorldImagery", }, } custom_tiles = {"xyz": XYZ_TILES, "wms": WMS_TILES} def get_xyz_dict(free_only=True, france=False): """Returns a dictionary of xyz services. Args: free_only (bool, optional): Whether to return only free xyz tile services that do not require an access token. Defaults to True. france (bool, optional): Whether to include Geoportail France basemaps. Defaults to False. Returns: dict: A dictionary of xyz services. """ xyz_bunch = xyzservices.providers if free_only: xyz_bunch = xyz_bunch.filter(requires_token=False) if not france: xyz_bunch = xyz_bunch.filter( function=lambda tile: "france" not in dict(tile)["name"].lower() ) xyz_dict = xyz_bunch.flatten() for key, value in xyz_dict.items(): tile = xyzservices.TileProvider(value) if "type" not in tile: tile["type"] = "xyz" xyz_dict[key] = tile xyz_dict = collections.OrderedDict(sorted(xyz_dict.items())) return xyz_dict The provided code snippet includes necessary dependencies for implementing the `xyz_to_leaflet` function. Write a Python function `def xyz_to_leaflet()` to solve the following problem: Convert xyz tile services to ipyleaflet tile layers. Returns: dict: A dictionary of ipyleaflet tile layers. Here is the function: def xyz_to_leaflet(): """Convert xyz tile services to ipyleaflet tile layers. Returns: dict: A dictionary of ipyleaflet tile layers. """ leaflet_dict = {} # Ignore Esri basemaps if they are already in the custom XYZ_TILES. ignore_list = [XYZ_TILES[tile]["name"] for tile in XYZ_TILES] # Add custom tiles. for tile_type, tile_dict in custom_tiles.items(): for tile_provider, tile_info in tile_dict.items(): tile_info["type"] = tile_type leaflet_dict[tile_info["name"]] = tile_info # Add xyzservices.provider tiles. for tile_provider, tile_info in get_xyz_dict().items(): if tile_info["name"] in ignore_list: continue tile_info["url"] = tile_info.build_url() leaflet_dict[tile_info["name"]] = tile_info return leaflet_dict
Convert xyz tile services to ipyleaflet tile layers. Returns: dict: A dictionary of ipyleaflet tile layers.
12,225
import collections import os import requests import folium import ipyleaflet import xyzservices from .common import check_package, planet_tiles XYZ_TILES = { "OpenStreetMap": { "url": "https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", "attribution": "OpenStreetMap", "name": "OpenStreetMap", }, "ROADMAP": { "url": "https://server.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer/tile/{z}/{y}/{x}", "attribution": "Esri", "name": "Esri.WorldStreetMap", }, "SATELLITE": { "url": "https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}", "attribution": "Esri", "name": "Esri.WorldImagery", }, "TERRAIN": { "url": "https://server.arcgisonline.com/ArcGIS/rest/services/World_Topo_Map/MapServer/tile/{z}/{y}/{x}", "attribution": "Esri", "name": "Esri.WorldTopoMap", }, "HYBRID": { "url": "https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}", "attribution": "Esri", "name": "Esri.WorldImagery", }, } custom_tiles = {"xyz": XYZ_TILES, "wms": WMS_TILES} def get_xyz_dict(free_only=True, france=False): """Returns a dictionary of xyz services. Args: free_only (bool, optional): Whether to return only free xyz tile services that do not require an access token. Defaults to True. france (bool, optional): Whether to include Geoportail France basemaps. Defaults to False. Returns: dict: A dictionary of xyz services. """ xyz_bunch = xyzservices.providers if free_only: xyz_bunch = xyz_bunch.filter(requires_token=False) if not france: xyz_bunch = xyz_bunch.filter( function=lambda tile: "france" not in dict(tile)["name"].lower() ) xyz_dict = xyz_bunch.flatten() for key, value in xyz_dict.items(): tile = xyzservices.TileProvider(value) if "type" not in tile: tile["type"] = "xyz" xyz_dict[key] = tile xyz_dict = collections.OrderedDict(sorted(xyz_dict.items())) return xyz_dict def planet_tiles(api_key=None, token_name="PLANET_API_KEY", tile_format="ipyleaflet"): """Generates Planet imagery TileLayer based on an API key. To get a Planet API key, see https://developers.planet.com/quickstart/apis/ Args: api_key (str, optional): The Planet API key. Defaults to None. token_name (str, optional): The environment variable name of the API key. Defaults to "PLANET_API_KEY". tile_format (str, optional): The TileLayer format, can be either ipyleaflet or folium. Defaults to "ipyleaflet". Raises: ValueError: If the tile layer format is invalid. Returns: dict: A dictionary of TileLayer. """ catalog = {} quarterly = planet_quarterly_tiles(api_key, token_name, tile_format) monthly = planet_monthly_tiles(api_key, token_name, tile_format) for key in quarterly: catalog[key] = quarterly[key] for key in monthly: catalog[key] = monthly[key] return catalog The provided code snippet includes necessary dependencies for implementing the `xyz_to_folium` function. Write a Python function `def xyz_to_folium()` to solve the following problem: Convert xyz tile services to folium tile layers. Returns: dict: A dictionary of folium tile layers. Here is the function: def xyz_to_folium(): """Convert xyz tile services to folium tile layers. Returns: dict: A dictionary of folium tile layers. """ folium_dict = {} # Ignore Esri basemaps if they are already in the custom XYZ_TILES. ignore_list = [XYZ_TILES[tile]["name"] for tile in XYZ_TILES] for key, tile in custom_tiles["xyz"].items(): folium_dict[key] = folium.TileLayer( tiles=tile["url"], attr=tile["attribution"], name=tile["name"], overlay=True, control=True, max_zoom=22, ) for key, tile in custom_tiles["wms"].items(): folium_dict[key] = folium.WmsTileLayer( url=tile["url"], layers=tile["layers"], name=tile["name"], attr=tile["attribution"], fmt=tile["format"], transparent=tile["transparent"], overlay=True, control=True, ) for item in get_xyz_dict().values(): if item["name"] in ignore_list: continue folium_dict[item.name] = folium.TileLayer( tiles=item.build_url(), attr=item.attribution, name=item.name, max_zoom=item.get("max_zoom", 22), overlay=True, control=True, ) if os.environ.get("PLANET_API_KEY") is not None: planet_dict = planet_tiles(tile_format="folium") folium_dict.update(planet_dict) return folium_dict
Convert xyz tile services to folium tile layers. Returns: dict: A dictionary of folium tile layers.
12,226
import collections import os import requests import folium import ipyleaflet import xyzservices from .common import check_package, planet_tiles XYZ_TILES = { "OpenStreetMap": { "url": "https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", "attribution": "OpenStreetMap", "name": "OpenStreetMap", }, "ROADMAP": { "url": "https://server.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer/tile/{z}/{y}/{x}", "attribution": "Esri", "name": "Esri.WorldStreetMap", }, "SATELLITE": { "url": "https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}", "attribution": "Esri", "name": "Esri.WorldImagery", }, "TERRAIN": { "url": "https://server.arcgisonline.com/ArcGIS/rest/services/World_Topo_Map/MapServer/tile/{z}/{y}/{x}", "attribution": "Esri", "name": "Esri.WorldTopoMap", }, "HYBRID": { "url": "https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}", "attribution": "Esri", "name": "Esri.WorldImagery", }, } custom_tiles = {"xyz": XYZ_TILES, "wms": WMS_TILES} def get_xyz_dict(free_only=True, france=False): """Returns a dictionary of xyz services. Args: free_only (bool, optional): Whether to return only free xyz tile services that do not require an access token. Defaults to True. france (bool, optional): Whether to include Geoportail France basemaps. Defaults to False. Returns: dict: A dictionary of xyz services. """ xyz_bunch = xyzservices.providers if free_only: xyz_bunch = xyz_bunch.filter(requires_token=False) if not france: xyz_bunch = xyz_bunch.filter( function=lambda tile: "france" not in dict(tile)["name"].lower() ) xyz_dict = xyz_bunch.flatten() for key, value in xyz_dict.items(): tile = xyzservices.TileProvider(value) if "type" not in tile: tile["type"] = "xyz" xyz_dict[key] = tile xyz_dict = collections.OrderedDict(sorted(xyz_dict.items())) return xyz_dict def check_package(name, URL=""): try: __import__(name.lower()) except Exception: raise ImportError( f"{name} is not installed. Please install it before proceeding. {URL}" ) def planet_tiles(api_key=None, token_name="PLANET_API_KEY", tile_format="ipyleaflet"): """Generates Planet imagery TileLayer based on an API key. To get a Planet API key, see https://developers.planet.com/quickstart/apis/ Args: api_key (str, optional): The Planet API key. Defaults to None. token_name (str, optional): The environment variable name of the API key. Defaults to "PLANET_API_KEY". tile_format (str, optional): The TileLayer format, can be either ipyleaflet or folium. Defaults to "ipyleaflet". Raises: ValueError: If the tile layer format is invalid. Returns: dict: A dictionary of TileLayer. """ catalog = {} quarterly = planet_quarterly_tiles(api_key, token_name, tile_format) monthly = planet_monthly_tiles(api_key, token_name, tile_format) for key in quarterly: catalog[key] = quarterly[key] for key in monthly: catalog[key] = monthly[key] return catalog The provided code snippet includes necessary dependencies for implementing the `xyz_to_pydeck` function. Write a Python function `def xyz_to_pydeck()` to solve the following problem: Convert xyz tile services to pydeck custom tile layers. Returns: dict: A dictionary of pydeck tile layers. Here is the function: def xyz_to_pydeck(): """Convert xyz tile services to pydeck custom tile layers. Returns: dict: A dictionary of pydeck tile layers. """ check_package("pydeck", "https://deckgl.readthedocs.io/en/latest/installation.html") import pydeck as pdk pydeck_dict = {} # Ignore Esri basemaps if they are already in the custom XYZ_TILES. ignore_list = [XYZ_TILES[tile]["name"] for tile in XYZ_TILES] for key, tile in custom_tiles["xyz"].items(): url = tile["url"] pydeck_dict[key] = url for key, item in get_xyz_dict().items(): if item["name"] in ignore_list: continue url = item.build_url() pydeck_dict[key] = url if os.environ.get("PLANET_API_KEY") is not None: planet_dict = planet_tiles(tile_format="ipyleaflet") for id_, tile in planet_dict.items(): pydeck_dict[id_] = tile.url pdk.settings.custom_libraries = [ { "libraryName": "MyTileLayerLibrary", "resourceUri": "https://cdn.jsdelivr.net/gh/giswqs/pydeck_myTileLayer@master/dist/bundle.js", } ] for key in pydeck_dict: pydeck_dict[key] = pdk.Layer("MyTileLayer", pydeck_dict[key], key) return pydeck_dict
Convert xyz tile services to pydeck custom tile layers. Returns: dict: A dictionary of pydeck tile layers.
12,227
import collections import os import requests import folium import ipyleaflet import xyzservices from .common import check_package, planet_tiles XYZ_TILES = { "OpenStreetMap": { "url": "https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", "attribution": "OpenStreetMap", "name": "OpenStreetMap", }, "ROADMAP": { "url": "https://server.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer/tile/{z}/{y}/{x}", "attribution": "Esri", "name": "Esri.WorldStreetMap", }, "SATELLITE": { "url": "https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}", "attribution": "Esri", "name": "Esri.WorldImagery", }, "TERRAIN": { "url": "https://server.arcgisonline.com/ArcGIS/rest/services/World_Topo_Map/MapServer/tile/{z}/{y}/{x}", "attribution": "Esri", "name": "Esri.WorldTopoMap", }, "HYBRID": { "url": "https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}", "attribution": "Esri", "name": "Esri.WorldImagery", }, } custom_tiles = {"xyz": XYZ_TILES, "wms": WMS_TILES} def get_xyz_dict(free_only=True, france=False): """Returns a dictionary of xyz services. Args: free_only (bool, optional): Whether to return only free xyz tile services that do not require an access token. Defaults to True. france (bool, optional): Whether to include Geoportail France basemaps. Defaults to False. Returns: dict: A dictionary of xyz services. """ xyz_bunch = xyzservices.providers if free_only: xyz_bunch = xyz_bunch.filter(requires_token=False) if not france: xyz_bunch = xyz_bunch.filter( function=lambda tile: "france" not in dict(tile)["name"].lower() ) xyz_dict = xyz_bunch.flatten() for key, value in xyz_dict.items(): tile = xyzservices.TileProvider(value) if "type" not in tile: tile["type"] = "xyz" xyz_dict[key] = tile xyz_dict = collections.OrderedDict(sorted(xyz_dict.items())) return xyz_dict The provided code snippet includes necessary dependencies for implementing the `xyz_to_plotly` function. Write a Python function `def xyz_to_plotly()` to solve the following problem: Convert xyz tile services to plotly tile layers. Returns: dict: A dictionary of plotly tile layers. Here is the function: def xyz_to_plotly(): """Convert xyz tile services to plotly tile layers. Returns: dict: A dictionary of plotly tile layers. """ plotly_dict = {} # Ignore Esri basemaps if they are already in the custom XYZ_TILES. ignore_list = [XYZ_TILES[tile]["name"] for tile in XYZ_TILES] for key, tile in custom_tiles["xyz"].items(): plotly_dict[key] = { "below": "traces", "sourcetype": "raster", "sourceattribution": tile["attribution"], "source": [tile["url"]], "name": key, } for item in get_xyz_dict().values(): if item["name"] in ignore_list: continue plotly_dict[item.name] = { "below": "traces", "sourcetype": "raster", "sourceattribution": item.attribution, "source": [item.build_url()], "name": item.name, } return plotly_dict
Convert xyz tile services to plotly tile layers. Returns: dict: A dictionary of plotly tile layers.
12,228
import collections import os import requests import folium import ipyleaflet import xyzservices from .common import check_package, planet_tiles The provided code snippet includes necessary dependencies for implementing the `search_qms` function. Write a Python function `def search_qms(keywords, limit=10)` to solve the following problem: Search qms files for keywords. Reference: https://github.com/geopandas/xyzservices/issues/65 Args: keywords (str): Keywords to search for. limit (int): Number of results to return. Here is the function: def search_qms(keywords, limit=10): """Search qms files for keywords. Reference: https://github.com/geopandas/xyzservices/issues/65 Args: keywords (str): Keywords to search for. limit (int): Number of results to return. """ QMS_API = "https://qms.nextgis.com/api/v1/geoservices" services = requests.get( f"{QMS_API}/?search={keywords}&type=tms&epsg=3857&limit={str(limit)}" ) services = services.json() if services["count"] == 0: return None elif services["count"] <= limit: return services["results"] else: return services["results"][:limit]
Search qms files for keywords. Reference: https://github.com/geopandas/xyzservices/issues/65 Args: keywords (str): Keywords to search for. limit (int): Number of results to return.
12,229
import collections import os import requests import folium import ipyleaflet import xyzservices from .common import check_package, planet_tiles def get_qms(service_id): QMS_API = "https://qms.nextgis.com/api/v1/geoservices" service_details = requests.get(f"{QMS_API}/{service_id}") return service_details.json() The provided code snippet includes necessary dependencies for implementing the `qms_to_geemap` function. Write a Python function `def qms_to_geemap(service_id)` to solve the following problem: Convert a qms service to an ipyleaflet tile layer. Args: service_id (str): Service ID. Returns: ipyleaflet.TileLayer: An ipyleaflet tile layer. Here is the function: def qms_to_geemap(service_id): """Convert a qms service to an ipyleaflet tile layer. Args: service_id (str): Service ID. Returns: ipyleaflet.TileLayer: An ipyleaflet tile layer. """ service_details = get_qms(service_id) name = service_details["name"] url = service_details["url"] attribution = service_details["copyright_text"] layer = ipyleaflet.TileLayer(url=url, name=name, attribution=attribution) return layer
Convert a qms service to an ipyleaflet tile layer. Args: service_id (str): Service ID. Returns: ipyleaflet.TileLayer: An ipyleaflet tile layer.
12,230
import csv import datetime import io import json import math import os import requests import shutil import tarfile import urllib.request import warnings import zipfile import ee import ipywidgets as widgets from ipytree import Node, Tree from typing import Union, List, Dict, Optional, Tuple def ee_export_image( ee_object, filename, scale=None, crs=None, crs_transform=None, region=None, dimensions=None, file_per_band=False, format="ZIPPED_GEO_TIFF", unzip=True, unmask_value=None, timeout=300, proxies=None, ): """Exports an ee.Image as a GeoTIFF. Args: ee_object (object): The ee.Image to download. filename (str): Output filename for the exported image. scale (float, optional): A default scale to use for any bands that do not specify one; ignored if crs and crs_transform is specified. Defaults to None. crs (str, optional): A default CRS string to use for any bands that do not explicitly specify one. Defaults to None. crs_transform (list, optional): a default affine transform to use for any bands that do not specify one, of the same format as the crs_transform of bands. Defaults to None. region (object, optional): A polygon specifying a region to download; ignored if crs and crs_transform is specified. Defaults to None. dimensions (list, optional): An optional array of two integers defining the width and height to which the band is cropped. Defaults to None. file_per_band (bool, optional): Whether to produce a different GeoTIFF per band. Defaults to False. format (str, optional): One of: "ZIPPED_GEO_TIFF" (GeoTIFF file(s) wrapped in a zip file, default), "GEO_TIFF" (GeoTIFF file), "NPY" (NumPy binary format). If "GEO_TIFF" or "NPY", filePerBand and all band-level transformations will be ignored. Loading a NumPy output results in a structured array. unzip (bool, optional): Whether to unzip the downloaded file. Defaults to True. unmask_value (float, optional): The value to use for pixels that are masked in the input image. If the exported image contains zero values, you should set the unmask value to a non-zero value so that the zero values are not treated as missing data. Defaults to None. timeout (int, optional): The timeout in seconds for the request. Defaults to 300. proxies (dict, optional): A dictionary of proxy servers to use. Defaults to None. """ if not isinstance(ee_object, ee.Image): print("The ee_object must be an ee.Image.") return if unmask_value is not None: ee_object = ee_object.selfMask().unmask(unmask_value) if isinstance(region, ee.Geometry): ee_object = ee_object.clip(region) elif isinstance(region, ee.FeatureCollection): ee_object = ee_object.clipToCollection(region) filename = os.path.abspath(filename) basename = os.path.basename(filename) name = os.path.splitext(basename)[0] filetype = os.path.splitext(basename)[1][1:].lower() filename_zip = filename.replace(".tif", ".zip") if filetype != "tif": print("The filename must end with .tif") return try: print("Generating URL ...") params = {"name": name, "filePerBand": file_per_band} params["scale"] = scale if region is None: region = ee_object.geometry() if dimensions is not None: params["dimensions"] = dimensions if region is not None: params["region"] = region if crs is not None: params["crs"] = crs if crs_transform is not None: params["crs_transform"] = crs_transform if format != "ZIPPED_GEO_TIFF": params["format"] = format try: url = ee_object.getDownloadURL(params) except Exception as e: print("An error occurred while downloading.") print(e) return print(f"Downloading data from {url}\nPlease wait ...") # Need to initialize r to something because of how we currently handle errors # We should aim to refactor the code such that only one try block is needed r = None r = requests.get(url, stream=True, timeout=timeout, proxies=proxies) if r.status_code != 200: print("An error occurred while downloading.") return with open(filename_zip, "wb") as fd: for chunk in r.iter_content(chunk_size=1024): fd.write(chunk) except Exception as e: print("An error occurred while downloading.") if r is not None: print(r.json()["error"]["message"]) return try: if unzip: with zipfile.ZipFile(filename_zip) as z: z.extractall(os.path.dirname(filename)) os.remove(filename_zip) if file_per_band: print(f"Data downloaded to {os.path.dirname(filename)}") else: print(f"Data downloaded to {filename}") except Exception as e: print(e) The provided code snippet includes necessary dependencies for implementing the `ee_export_image_collection` function. Write a Python function `def ee_export_image_collection( ee_object, out_dir, scale=None, crs=None, crs_transform=None, region=None, dimensions=None, file_per_band=False, format="ZIPPED_GEO_TIFF", unmask_value=None, filenames=None, timeout=300, proxies=None, )` to solve the following problem: Exports an ImageCollection as GeoTIFFs. Args: ee_object (object): The ee.Image to download. out_dir (str): The output directory for the exported images. scale (float, optional): A default scale to use for any bands that do not specify one; ignored if crs and crs_transform is specified. Defaults to None. crs (str, optional): A default CRS string to use for any bands that do not explicitly specify one. Defaults to None. crs_transform (list, optional): a default affine transform to use for any bands that do not specify one, of the same format as the crs_transform of bands. Defaults to None. region (object, optional): A polygon specifying a region to download; ignored if crs and crs_transform is specified. Defaults to None. dimensions (list, optional): An optional array of two integers defining the width and height to which the band is cropped. Defaults to None. file_per_band (bool, optional): Whether to produce a different GeoTIFF per band. Defaults to False. format (str, optional): One of: "ZIPPED_GEO_TIFF" (GeoTIFF file(s) wrapped in a zip file, default), "GEO_TIFF" (GeoTIFF file), "NPY" (NumPy binary format). If "GEO_TIFF" or "NPY", filePerBand and all band-level transformations will be ignored. Loading a NumPy output results in a structured array. unmask_value (float, optional): The value to use for pixels that are masked in the input image. If the exported image contains zero values, you should set the unmask value to a non-zero value so that the zero values are not treated as missing data. Defaults to None. filenames (list | int, optional): A list of filenames to use for the exported images. Defaults to None. timeout (int, optional): The timeout in seconds for the request. Defaults to 300. proxies (dict, optional): A dictionary of proxy servers to use. Defaults to None. Here is the function: def ee_export_image_collection( ee_object, out_dir, scale=None, crs=None, crs_transform=None, region=None, dimensions=None, file_per_band=False, format="ZIPPED_GEO_TIFF", unmask_value=None, filenames=None, timeout=300, proxies=None, ): """Exports an ImageCollection as GeoTIFFs. Args: ee_object (object): The ee.Image to download. out_dir (str): The output directory for the exported images. scale (float, optional): A default scale to use for any bands that do not specify one; ignored if crs and crs_transform is specified. Defaults to None. crs (str, optional): A default CRS string to use for any bands that do not explicitly specify one. Defaults to None. crs_transform (list, optional): a default affine transform to use for any bands that do not specify one, of the same format as the crs_transform of bands. Defaults to None. region (object, optional): A polygon specifying a region to download; ignored if crs and crs_transform is specified. Defaults to None. dimensions (list, optional): An optional array of two integers defining the width and height to which the band is cropped. Defaults to None. file_per_band (bool, optional): Whether to produce a different GeoTIFF per band. Defaults to False. format (str, optional): One of: "ZIPPED_GEO_TIFF" (GeoTIFF file(s) wrapped in a zip file, default), "GEO_TIFF" (GeoTIFF file), "NPY" (NumPy binary format). If "GEO_TIFF" or "NPY", filePerBand and all band-level transformations will be ignored. Loading a NumPy output results in a structured array. unmask_value (float, optional): The value to use for pixels that are masked in the input image. If the exported image contains zero values, you should set the unmask value to a non-zero value so that the zero values are not treated as missing data. Defaults to None. filenames (list | int, optional): A list of filenames to use for the exported images. Defaults to None. timeout (int, optional): The timeout in seconds for the request. Defaults to 300. proxies (dict, optional): A dictionary of proxy servers to use. Defaults to None. """ if not isinstance(ee_object, ee.ImageCollection): print("The ee_object must be an ee.ImageCollection.") return if not os.path.exists(out_dir): os.makedirs(out_dir) try: count = int(ee_object.size().getInfo()) print(f"Total number of images: {count}\n") if filenames is None: filenames = ee_object.aggregate_array("system:index").getInfo() elif isinstance(filenames, int): filenames = [str(f + filenames) for f in range(0, count)] if len(filenames) != count: raise Exception( "The number of filenames must be equal to the number of images." ) filenames = [str(f) + ".tif" for f in filenames if not str(f).endswith(".tif")] for i in range(0, count): image = ee.Image(ee_object.toList(count).get(i)) filename = os.path.join(out_dir, filenames[i]) print(f"Exporting {i + 1}/{count}: {filename}") ee_export_image( image, filename=filename, scale=scale, crs=crs, crs_transform=crs_transform, region=region, dimensions=dimensions, file_per_band=file_per_band, format=format, unmask_value=unmask_value, timeout=timeout, proxies=proxies, ) print("\n") except Exception as e: print(e)
Exports an ImageCollection as GeoTIFFs. Args: ee_object (object): The ee.Image to download. out_dir (str): The output directory for the exported images. scale (float, optional): A default scale to use for any bands that do not specify one; ignored if crs and crs_transform is specified. Defaults to None. crs (str, optional): A default CRS string to use for any bands that do not explicitly specify one. Defaults to None. crs_transform (list, optional): a default affine transform to use for any bands that do not specify one, of the same format as the crs_transform of bands. Defaults to None. region (object, optional): A polygon specifying a region to download; ignored if crs and crs_transform is specified. Defaults to None. dimensions (list, optional): An optional array of two integers defining the width and height to which the band is cropped. Defaults to None. file_per_band (bool, optional): Whether to produce a different GeoTIFF per band. Defaults to False. format (str, optional): One of: "ZIPPED_GEO_TIFF" (GeoTIFF file(s) wrapped in a zip file, default), "GEO_TIFF" (GeoTIFF file), "NPY" (NumPy binary format). If "GEO_TIFF" or "NPY", filePerBand and all band-level transformations will be ignored. Loading a NumPy output results in a structured array. unmask_value (float, optional): The value to use for pixels that are masked in the input image. If the exported image contains zero values, you should set the unmask value to a non-zero value so that the zero values are not treated as missing data. Defaults to None. filenames (list | int, optional): A list of filenames to use for the exported images. Defaults to None. timeout (int, optional): The timeout in seconds for the request. Defaults to 300. proxies (dict, optional): A dictionary of proxy servers to use. Defaults to None.
12,231
import csv import datetime import io import json import math import os import requests import shutil import tarfile import urllib.request import warnings import zipfile import ee import ipywidgets as widgets from ipytree import Node, Tree from typing import Union, List, Dict, Optional, Tuple def ee_export_image_to_drive( image, description="myExportImageTask", folder=None, fileNamePrefix=None, dimensions=None, region=None, scale=None, crs=None, crsTransform=None, maxPixels=None, shardSize=None, fileDimensions=None, skipEmptyTiles=None, fileFormat=None, formatOptions=None, **kwargs, ): """Creates a batch task to export an Image as a raster to Google Drive. Args: image: The image to be exported. description: Human-readable name of the task. folder: The name of a unique folder in your Drive account to export into. Defaults to the root of the drive. fileNamePrefix: The Google Drive filename for the export. Defaults to the name of the task. dimensions: The dimensions of the exported image. Takes either a single positive integer as the maximum dimension or "WIDTHxHEIGHT" where WIDTH and HEIGHT are each positive integers. region: The lon,lat coordinates for a LinearRing or Polygon specifying the region to export. Can be specified as a nested lists of numbers or a serialized string. Defaults to the image's region. scale: The resolution in meters per pixel. Defaults to the native resolution of the image asset unless a crsTransform is specified. crs: The coordinate reference system of the exported image's projection. Defaults to the image's default projection. crsTransform: A comma-separated string of 6 numbers describing the affine transform of the coordinate reference system of the exported image's projection, in the order: xScale, xShearing, xTranslation, yShearing, yScale and yTranslation. Defaults to the image's native CRS transform. maxPixels: The maximum allowed number of pixels in the exported image. The task will fail if the exported region covers more pixels in the specified projection. Defaults to 100,000,000. shardSize: Size in pixels of the tiles in which this image will be computed. Defaults to 256. fileDimensions: The dimensions in pixels of each image file, if the image is too large to fit in a single file. May specify a single number to indicate a square shape, or a tuple of two dimensions to indicate (width,height). Note that the image will still be clipped to the overall image dimensions. Must be a multiple of shardSize. skipEmptyTiles: If true, skip writing empty (i.e. fully-masked) image tiles. Defaults to false. fileFormat: The string file format to which the image is exported. Currently only 'GeoTIFF' and 'TFRecord' are supported, defaults to 'GeoTIFF'. formatOptions: A dictionary of string keys to format specific options. **kwargs: Holds other keyword arguments that may have been deprecated such as 'crs_transform', 'driveFolder', and 'driveFileNamePrefix'. """ if not isinstance(image, ee.Image): raise ValueError("Input image must be an instance of ee.Image") task = ee.batch.Export.image.toDrive( image, description, folder, fileNamePrefix, dimensions, region, scale, crs, crsTransform, maxPixels, shardSize, fileDimensions, skipEmptyTiles, fileFormat, formatOptions, **kwargs, ) task.start() The provided code snippet includes necessary dependencies for implementing the `ee_export_image_collection_to_drive` function. Write a Python function `def ee_export_image_collection_to_drive( ee_object, descriptions=None, folder=None, fileNamePrefix=None, dimensions=None, region=None, scale=None, crs=None, crsTransform=None, maxPixels=None, shardSize=None, fileDimensions=None, skipEmptyTiles=None, fileFormat=None, formatOptions=None, **kwargs, )` to solve the following problem: Creates a batch task to export an ImageCollection as raster images to Google Drive. Args: ee_object: The image collection to export. descriptions: A list of human-readable names of the tasks. folder: The name of a unique folder in your Drive account to export into. Defaults to the root of the drive. fileNamePrefix: The Google Drive filename for the export. Defaults to the name of the task. dimensions: The dimensions of the exported image. Takes either a single positive integer as the maximum dimension or "WIDTHxHEIGHT" where WIDTH and HEIGHT are each positive integers. region: The lon,lat coordinates for a LinearRing or Polygon specifying the region to export. Can be specified as a nested lists of numbers or a serialized string. Defaults to the image's region. scale: The resolution in meters per pixel. Defaults to the native resolution of the image asset unless a crsTransform is specified. crs: The coordinate reference system of the exported image's projection. Defaults to the image's default projection. crsTransform: A comma-separated string of 6 numbers describing the affine transform of the coordinate reference system of the exported image's projection, in the order: xScale, xShearing, xTranslation, yShearing, yScale and yTranslation. Defaults to the image's native CRS transform. maxPixels: The maximum allowed number of pixels in the exported image. The task will fail if the exported region covers more pixels in the specified projection. Defaults to 100,000,000. shardSize: Size in pixels of the tiles in which this image will be computed. Defaults to 256. fileDimensions: The dimensions in pixels of each image file, if the image is too large to fit in a single file. May specify a single number to indicate a square shape, or a tuple of two dimensions to indicate (width,height). Note that the image will still be clipped to the overall image dimensions. Must be a multiple of shardSize. skipEmptyTiles: If true, skip writing empty (i.e. fully-masked) image tiles. Defaults to false. fileFormat: The string file format to which the image is exported. Currently only 'GeoTIFF' and 'TFRecord' are supported, defaults to 'GeoTIFF'. formatOptions: A dictionary of string keys to format specific options. **kwargs: Holds other keyword arguments that may have been deprecated such as 'crs_transform', 'driveFolder', and 'driveFileNamePrefix'. Here is the function: def ee_export_image_collection_to_drive( ee_object, descriptions=None, folder=None, fileNamePrefix=None, dimensions=None, region=None, scale=None, crs=None, crsTransform=None, maxPixels=None, shardSize=None, fileDimensions=None, skipEmptyTiles=None, fileFormat=None, formatOptions=None, **kwargs, ): """Creates a batch task to export an ImageCollection as raster images to Google Drive. Args: ee_object: The image collection to export. descriptions: A list of human-readable names of the tasks. folder: The name of a unique folder in your Drive account to export into. Defaults to the root of the drive. fileNamePrefix: The Google Drive filename for the export. Defaults to the name of the task. dimensions: The dimensions of the exported image. Takes either a single positive integer as the maximum dimension or "WIDTHxHEIGHT" where WIDTH and HEIGHT are each positive integers. region: The lon,lat coordinates for a LinearRing or Polygon specifying the region to export. Can be specified as a nested lists of numbers or a serialized string. Defaults to the image's region. scale: The resolution in meters per pixel. Defaults to the native resolution of the image asset unless a crsTransform is specified. crs: The coordinate reference system of the exported image's projection. Defaults to the image's default projection. crsTransform: A comma-separated string of 6 numbers describing the affine transform of the coordinate reference system of the exported image's projection, in the order: xScale, xShearing, xTranslation, yShearing, yScale and yTranslation. Defaults to the image's native CRS transform. maxPixels: The maximum allowed number of pixels in the exported image. The task will fail if the exported region covers more pixels in the specified projection. Defaults to 100,000,000. shardSize: Size in pixels of the tiles in which this image will be computed. Defaults to 256. fileDimensions: The dimensions in pixels of each image file, if the image is too large to fit in a single file. May specify a single number to indicate a square shape, or a tuple of two dimensions to indicate (width,height). Note that the image will still be clipped to the overall image dimensions. Must be a multiple of shardSize. skipEmptyTiles: If true, skip writing empty (i.e. fully-masked) image tiles. Defaults to false. fileFormat: The string file format to which the image is exported. Currently only 'GeoTIFF' and 'TFRecord' are supported, defaults to 'GeoTIFF'. formatOptions: A dictionary of string keys to format specific options. **kwargs: Holds other keyword arguments that may have been deprecated such as 'crs_transform', 'driveFolder', and 'driveFileNamePrefix'. """ if not isinstance(ee_object, ee.ImageCollection): raise ValueError("The ee_object must be an ee.ImageCollection.") try: count = int(ee_object.size().getInfo()) print(f"Total number of images: {count}\n") if (descriptions is not None) and (len(descriptions) != count): raise ValueError( "The number of descriptions is not equal to the number of images." ) if descriptions is None: descriptions = ee_object.aggregate_array("system:index").getInfo() images = ee_object.toList(count) if os.environ.get("USE_MKDOCS") is not None: # skip if running GitHub CI. return for i in range(0, count): image = ee.Image(images.get(i)) description = descriptions[i] ee_export_image_to_drive( image, description, folder, fileNamePrefix, dimensions, region, scale, crs, crsTransform, maxPixels, shardSize, fileDimensions, skipEmptyTiles, fileFormat, formatOptions, **kwargs, ) except Exception as e: print(e)
Creates a batch task to export an ImageCollection as raster images to Google Drive. Args: ee_object: The image collection to export. descriptions: A list of human-readable names of the tasks. folder: The name of a unique folder in your Drive account to export into. Defaults to the root of the drive. fileNamePrefix: The Google Drive filename for the export. Defaults to the name of the task. dimensions: The dimensions of the exported image. Takes either a single positive integer as the maximum dimension or "WIDTHxHEIGHT" where WIDTH and HEIGHT are each positive integers. region: The lon,lat coordinates for a LinearRing or Polygon specifying the region to export. Can be specified as a nested lists of numbers or a serialized string. Defaults to the image's region. scale: The resolution in meters per pixel. Defaults to the native resolution of the image asset unless a crsTransform is specified. crs: The coordinate reference system of the exported image's projection. Defaults to the image's default projection. crsTransform: A comma-separated string of 6 numbers describing the affine transform of the coordinate reference system of the exported image's projection, in the order: xScale, xShearing, xTranslation, yShearing, yScale and yTranslation. Defaults to the image's native CRS transform. maxPixels: The maximum allowed number of pixels in the exported image. The task will fail if the exported region covers more pixels in the specified projection. Defaults to 100,000,000. shardSize: Size in pixels of the tiles in which this image will be computed. Defaults to 256. fileDimensions: The dimensions in pixels of each image file, if the image is too large to fit in a single file. May specify a single number to indicate a square shape, or a tuple of two dimensions to indicate (width,height). Note that the image will still be clipped to the overall image dimensions. Must be a multiple of shardSize. skipEmptyTiles: If true, skip writing empty (i.e. fully-masked) image tiles. Defaults to false. fileFormat: The string file format to which the image is exported. Currently only 'GeoTIFF' and 'TFRecord' are supported, defaults to 'GeoTIFF'. formatOptions: A dictionary of string keys to format specific options. **kwargs: Holds other keyword arguments that may have been deprecated such as 'crs_transform', 'driveFolder', and 'driveFileNamePrefix'.
12,232
import csv import datetime import io import json import math import os import requests import shutil import tarfile import urllib.request import warnings import zipfile import ee import ipywidgets as widgets from ipytree import Node, Tree from typing import Union, List, Dict, Optional, Tuple def ee_export_image_to_asset( image, description="myExportImageTask", assetId=None, pyramidingPolicy=None, dimensions=None, region=None, scale=None, crs=None, crsTransform=None, maxPixels=None, **kwargs, ): """Creates a task to export an EE Image to an EE Asset. Args: image: The image to be exported. description: Human-readable name of the task. assetId: The destination asset ID. pyramidingPolicy: The pyramiding policy to apply to each band in the image, a dictionary keyed by band name. Values must be one of: "mean", "sample", "min", "max", or "mode". Defaults to "mean". A special key, ".default", may be used to change the default for all bands. dimensions: The dimensions of the exported image. Takes either a single positive integer as the maximum dimension or "WIDTHxHEIGHT" where WIDTH and HEIGHT are each positive integers. region: The lon,lat coordinates for a LinearRing or Polygon specifying the region to export. Can be specified as a nested lists of numbers or a serialized string. Defaults to the image's region. scale: The resolution in meters per pixel. Defaults to the native resolution of the image asset unless a crsTransform is specified. crs: The coordinate reference system of the exported image's projection. Defaults to the image's default projection. crsTransform: A comma-separated string of 6 numbers describing the affine transform of the coordinate reference system of the exported image's projection, in the order: xScale, xShearing, xTranslation, yShearing, yScale and yTranslation. Defaults to the image's native CRS transform. maxPixels: The maximum allowed number of pixels in the exported image. The task will fail if the exported region covers more pixels in the specified projection. Defaults to 100,000,000. **kwargs: Holds other keyword arguments that may have been deprecated such as 'crs_transform'. """ if isinstance(image, ee.Image) or isinstance(image, ee.image.Image): pass else: raise ValueError("Input image must be an instance of ee.Image") if isinstance(assetId, str): if assetId.startswith("users/") or assetId.startswith("projects/"): pass else: assetId = f"{ee_user_id()}/{assetId}" task = ee.batch.Export.image.toAsset( image, description, assetId, pyramidingPolicy, dimensions, region, scale, crs, crsTransform, maxPixels, **kwargs, ) task.start() The provided code snippet includes necessary dependencies for implementing the `ee_export_image_collection_to_asset` function. Write a Python function `def ee_export_image_collection_to_asset( ee_object, descriptions=None, assetIds=None, pyramidingPolicy=None, dimensions=None, region=None, scale=None, crs=None, crsTransform=None, maxPixels=None, **kwargs, )` to solve the following problem: Creates a batch task to export an ImageCollection as raster images to Google Drive. Args: ee_object: The image collection to export. descriptions: A list of human-readable names of the tasks. assetIds: The destination asset ID. pyramidingPolicy: The pyramiding policy to apply to each band in the image, a dictionary keyed by band name. Values must be one of: "mean", "sample", "min", "max", or "mode". Defaults to "mean". A special key, ".default", may be used to change the default for all bands. dimensions: The dimensions of the exported image. Takes either a single positive integer as the maximum dimension or "WIDTHxHEIGHT" where WIDTH and HEIGHT are each positive integers. region: The lon,lat coordinates for a LinearRing or Polygon specifying the region to export. Can be specified as a nested lists of numbers or a serialized string. Defaults to the image's region. scale: The resolution in meters per pixel. Defaults to the native resolution of the image asset unless a crsTransform is specified. crs: The coordinate reference system of the exported image's projection. Defaults to the image's default projection. crsTransform: A comma-separated string of 6 numbers describing the affine transform of the coordinate reference system of the exported image's projection, in the order: xScale, xShearing, xTranslation, yShearing, yScale and yTranslation. Defaults to the image's native CRS transform. maxPixels: The maximum allowed number of pixels in the exported image. The task will fail if the exported region covers more pixels in the specified projection. Defaults to 100,000,000. **kwargs: Holds other keyword arguments that may have been deprecated such as 'crs_transform'. Here is the function: def ee_export_image_collection_to_asset( ee_object, descriptions=None, assetIds=None, pyramidingPolicy=None, dimensions=None, region=None, scale=None, crs=None, crsTransform=None, maxPixels=None, **kwargs, ): """Creates a batch task to export an ImageCollection as raster images to Google Drive. Args: ee_object: The image collection to export. descriptions: A list of human-readable names of the tasks. assetIds: The destination asset ID. pyramidingPolicy: The pyramiding policy to apply to each band in the image, a dictionary keyed by band name. Values must be one of: "mean", "sample", "min", "max", or "mode". Defaults to "mean". A special key, ".default", may be used to change the default for all bands. dimensions: The dimensions of the exported image. Takes either a single positive integer as the maximum dimension or "WIDTHxHEIGHT" where WIDTH and HEIGHT are each positive integers. region: The lon,lat coordinates for a LinearRing or Polygon specifying the region to export. Can be specified as a nested lists of numbers or a serialized string. Defaults to the image's region. scale: The resolution in meters per pixel. Defaults to the native resolution of the image asset unless a crsTransform is specified. crs: The coordinate reference system of the exported image's projection. Defaults to the image's default projection. crsTransform: A comma-separated string of 6 numbers describing the affine transform of the coordinate reference system of the exported image's projection, in the order: xScale, xShearing, xTranslation, yShearing, yScale and yTranslation. Defaults to the image's native CRS transform. maxPixels: The maximum allowed number of pixels in the exported image. The task will fail if the exported region covers more pixels in the specified projection. Defaults to 100,000,000. **kwargs: Holds other keyword arguments that may have been deprecated such as 'crs_transform'. """ if not isinstance(ee_object, ee.ImageCollection): raise ValueError("The ee_object must be an ee.ImageCollection.") try: count = int(ee_object.size().getInfo()) print(f"Total number of images: {count}\n") if (descriptions is not None) and (len(descriptions) != count): print("The number of descriptions is not equal to the number of images.") return if descriptions is None: descriptions = ee_object.aggregate_array("system:index").getInfo() if assetIds is None: assetIds = descriptions images = ee_object.toList(count) if os.environ.get("USE_MKDOCS") is not None: # skip if running GitHub CI. return for i in range(0, count): image = ee.Image(images.get(i)) description = descriptions[i] assetId = assetIds[i] ee_export_image_to_asset( image, description, assetId, pyramidingPolicy, dimensions, region, scale, crs, crsTransform, maxPixels, **kwargs, ) except Exception as e: print(e)
Creates a batch task to export an ImageCollection as raster images to Google Drive. Args: ee_object: The image collection to export. descriptions: A list of human-readable names of the tasks. assetIds: The destination asset ID. pyramidingPolicy: The pyramiding policy to apply to each band in the image, a dictionary keyed by band name. Values must be one of: "mean", "sample", "min", "max", or "mode". Defaults to "mean". A special key, ".default", may be used to change the default for all bands. dimensions: The dimensions of the exported image. Takes either a single positive integer as the maximum dimension or "WIDTHxHEIGHT" where WIDTH and HEIGHT are each positive integers. region: The lon,lat coordinates for a LinearRing or Polygon specifying the region to export. Can be specified as a nested lists of numbers or a serialized string. Defaults to the image's region. scale: The resolution in meters per pixel. Defaults to the native resolution of the image asset unless a crsTransform is specified. crs: The coordinate reference system of the exported image's projection. Defaults to the image's default projection. crsTransform: A comma-separated string of 6 numbers describing the affine transform of the coordinate reference system of the exported image's projection, in the order: xScale, xShearing, xTranslation, yShearing, yScale and yTranslation. Defaults to the image's native CRS transform. maxPixels: The maximum allowed number of pixels in the exported image. The task will fail if the exported region covers more pixels in the specified projection. Defaults to 100,000,000. **kwargs: Holds other keyword arguments that may have been deprecated such as 'crs_transform'.
12,233
import csv import datetime import io import json import math import os import requests import shutil import tarfile import urllib.request import warnings import zipfile import ee import ipywidgets as widgets from ipytree import Node, Tree from typing import Union, List, Dict, Optional, Tuple def ee_export_image_to_cloud_storage( image, description="myExportImageTask", bucket=None, fileNamePrefix=None, dimensions=None, region=None, scale=None, crs=None, crsTransform=None, maxPixels=None, shardSize=None, fileDimensions=None, skipEmptyTiles=None, fileFormat=None, formatOptions=None, **kwargs, ): """Creates a task to export an EE Image to Google Cloud Storage. Args: image: The image to be exported. description: Human-readable name of the task. bucket: The name of a Cloud Storage bucket for the export. fileNamePrefix: Cloud Storage object name prefix for the export. Defaults to the name of the task. dimensions: The dimensions of the exported image. Takes either a single positive integer as the maximum dimension or "WIDTHxHEIGHT" where WIDTH and HEIGHT are each positive integers. region: The lon,lat coordinates for a LinearRing or Polygon specifying the region to export. Can be specified as a nested lists of numbers or a serialized string. Defaults to the image's region. scale: The resolution in meters per pixel. Defaults to the native resolution of the image asset unless a crsTransform is specified. crs: The coordinate reference system of the exported image's projection. Defaults to the image's default projection. crsTransform: A comma-separated string of 6 numbers describing the affine transform of the coordinate reference system of the exported image's projection, in the order: xScale, xShearing, xTranslation, yShearing, yScale and yTranslation. Defaults to the image's native CRS transform. maxPixels: The maximum allowed number of pixels in the exported image. The task will fail if the exported region covers more pixels in the specified projection. Defaults to 100,000,000. shardSize: Size in pixels of the tiles in which this image will be computed. Defaults to 256. fileDimensions: The dimensions in pixels of each image file, if the image is too large to fit in a single file. May specify a single number to indicate a square shape, or a tuple of two dimensions to indicate (width,height). Note that the image will still be clipped to the overall image dimensions. Must be a multiple of shardSize. skipEmptyTiles: If true, skip writing empty (i.e. fully-masked) image tiles. Defaults to false. fileFormat: The string file format to which the image is exported. Currently only 'GeoTIFF' and 'TFRecord' are supported, defaults to 'GeoTIFF'. formatOptions: A dictionary of string keys to format specific options. **kwargs: Holds other keyword arguments that may have been deprecated such as 'crs_transform'. """ if not isinstance(image, ee.Image): raise ValueError("Input image must be an instance of ee.Image") try: task = ee.batch.Export.image.toCloudStorage( image, description, bucket, fileNamePrefix, dimensions, region, scale, crs, crsTransform, maxPixels, shardSize, fileDimensions, skipEmptyTiles, fileFormat, formatOptions, **kwargs, ) task.start() except Exception as e: print(e) The provided code snippet includes necessary dependencies for implementing the `ee_export_image_collection_to_cloud_storage` function. Write a Python function `def ee_export_image_collection_to_cloud_storage( ee_object, descriptions=None, bucket=None, fileNamePrefix=None, dimensions=None, region=None, scale=None, crs=None, crsTransform=None, maxPixels=None, shardSize=None, fileDimensions=None, skipEmptyTiles=None, fileFormat=None, formatOptions=None, **kwargs, )` to solve the following problem: Creates a batch task to export an ImageCollection as raster images to a Google Cloud bucket. Args: ee_object: The image collection to export. descriptions: A list of human-readable names of the tasks. bucket: The name of a Cloud Storage bucket for the export. fileNamePrefix: Cloud Storage object name prefix for the export. Defaults to the name of the task. dimensions: The dimensions of the exported image. Takes either a single positive integer as the maximum dimension or "WIDTHxHEIGHT" where WIDTH and HEIGHT are each positive integers. region: The lon,lat coordinates for a LinearRing or Polygon specifying the region to export. Can be specified as a nested lists of numbers or a serialized string. Defaults to the image's region. scale: The resolution in meters per pixel. Defaults to the native resolution of the image asset unless a crsTransform is specified. crs: The coordinate reference system of the exported image's projection. Defaults to the image's default projection. crsTransform: A comma-separated string of 6 numbers describing the affine transform of the coordinate reference system of the exported image's projection, in the order: xScale, xShearing, xTranslation, yShearing, yScale and yTranslation. Defaults to the image's native CRS transform. maxPixels: The maximum allowed number of pixels in the exported image. The task will fail if the exported region covers more pixels in the specified projection. Defaults to 100,000,000. shardSize: Size in pixels of the tiles in which this image will be computed. Defaults to 256. fileDimensions: The dimensions in pixels of each image file, if the image is too large to fit in a single file. May specify a single number to indicate a square shape, or a tuple of two dimensions to indicate (width,height). Note that the image will still be clipped to the overall image dimensions. Must be a multiple of shardSize. skipEmptyTiles: If true, skip writing empty (i.e. fully-masked) image tiles. Defaults to false. fileFormat: The string file format to which the image is exported. Currently only 'GeoTIFF' and 'TFRecord' are supported, defaults to 'GeoTIFF'. formatOptions: A dictionary of string keys to format specific options. **kwargs: Holds other keyword arguments that may have been deprecated such as 'crs_transform'. Here is the function: def ee_export_image_collection_to_cloud_storage( ee_object, descriptions=None, bucket=None, fileNamePrefix=None, dimensions=None, region=None, scale=None, crs=None, crsTransform=None, maxPixels=None, shardSize=None, fileDimensions=None, skipEmptyTiles=None, fileFormat=None, formatOptions=None, **kwargs, ): """Creates a batch task to export an ImageCollection as raster images to a Google Cloud bucket. Args: ee_object: The image collection to export. descriptions: A list of human-readable names of the tasks. bucket: The name of a Cloud Storage bucket for the export. fileNamePrefix: Cloud Storage object name prefix for the export. Defaults to the name of the task. dimensions: The dimensions of the exported image. Takes either a single positive integer as the maximum dimension or "WIDTHxHEIGHT" where WIDTH and HEIGHT are each positive integers. region: The lon,lat coordinates for a LinearRing or Polygon specifying the region to export. Can be specified as a nested lists of numbers or a serialized string. Defaults to the image's region. scale: The resolution in meters per pixel. Defaults to the native resolution of the image asset unless a crsTransform is specified. crs: The coordinate reference system of the exported image's projection. Defaults to the image's default projection. crsTransform: A comma-separated string of 6 numbers describing the affine transform of the coordinate reference system of the exported image's projection, in the order: xScale, xShearing, xTranslation, yShearing, yScale and yTranslation. Defaults to the image's native CRS transform. maxPixels: The maximum allowed number of pixels in the exported image. The task will fail if the exported region covers more pixels in the specified projection. Defaults to 100,000,000. shardSize: Size in pixels of the tiles in which this image will be computed. Defaults to 256. fileDimensions: The dimensions in pixels of each image file, if the image is too large to fit in a single file. May specify a single number to indicate a square shape, or a tuple of two dimensions to indicate (width,height). Note that the image will still be clipped to the overall image dimensions. Must be a multiple of shardSize. skipEmptyTiles: If true, skip writing empty (i.e. fully-masked) image tiles. Defaults to false. fileFormat: The string file format to which the image is exported. Currently only 'GeoTIFF' and 'TFRecord' are supported, defaults to 'GeoTIFF'. formatOptions: A dictionary of string keys to format specific options. **kwargs: Holds other keyword arguments that may have been deprecated such as 'crs_transform'. """ if not isinstance(ee_object, ee.ImageCollection): raise ValueError("The ee_object must be an ee.ImageCollection.") try: count = int(ee_object.size().getInfo()) print(f"Total number of images: {count}\n") if (descriptions is not None) and (len(descriptions) != count): print("The number of descriptions is not equal to the number of images.") return if descriptions is None: descriptions = ee_object.aggregate_array("system:index").getInfo() images = ee_object.toList(count) if os.environ.get("USE_MKDOCS") is not None: # skip if running GitHub CI. return for i in range(0, count): image = ee.Image(images.get(i)) description = descriptions[i] ee_export_image_to_cloud_storage( image, description, bucket, fileNamePrefix, dimensions, region, scale, crs, crsTransform, maxPixels, shardSize, fileDimensions, skipEmptyTiles, fileFormat, formatOptions, **kwargs, ) except Exception as e: print(e)
Creates a batch task to export an ImageCollection as raster images to a Google Cloud bucket. Args: ee_object: The image collection to export. descriptions: A list of human-readable names of the tasks. bucket: The name of a Cloud Storage bucket for the export. fileNamePrefix: Cloud Storage object name prefix for the export. Defaults to the name of the task. dimensions: The dimensions of the exported image. Takes either a single positive integer as the maximum dimension or "WIDTHxHEIGHT" where WIDTH and HEIGHT are each positive integers. region: The lon,lat coordinates for a LinearRing or Polygon specifying the region to export. Can be specified as a nested lists of numbers or a serialized string. Defaults to the image's region. scale: The resolution in meters per pixel. Defaults to the native resolution of the image asset unless a crsTransform is specified. crs: The coordinate reference system of the exported image's projection. Defaults to the image's default projection. crsTransform: A comma-separated string of 6 numbers describing the affine transform of the coordinate reference system of the exported image's projection, in the order: xScale, xShearing, xTranslation, yShearing, yScale and yTranslation. Defaults to the image's native CRS transform. maxPixels: The maximum allowed number of pixels in the exported image. The task will fail if the exported region covers more pixels in the specified projection. Defaults to 100,000,000. shardSize: Size in pixels of the tiles in which this image will be computed. Defaults to 256. fileDimensions: The dimensions in pixels of each image file, if the image is too large to fit in a single file. May specify a single number to indicate a square shape, or a tuple of two dimensions to indicate (width,height). Note that the image will still be clipped to the overall image dimensions. Must be a multiple of shardSize. skipEmptyTiles: If true, skip writing empty (i.e. fully-masked) image tiles. Defaults to false. fileFormat: The string file format to which the image is exported. Currently only 'GeoTIFF' and 'TFRecord' are supported, defaults to 'GeoTIFF'. formatOptions: A dictionary of string keys to format specific options. **kwargs: Holds other keyword arguments that may have been deprecated such as 'crs_transform'.
12,234
import csv import datetime import io import json import math import os import requests import shutil import tarfile import urllib.request import warnings import zipfile import ee import ipywidgets as widgets from ipytree import Node, Tree from typing import Union, List, Dict, Optional, Tuple def random_string(string_length=3): """Generates a random string of fixed length. Args: string_length (int, optional): Fixed length. Defaults to 3. Returns: str: A random string """ import random import string # random.seed(1001) letters = string.ascii_lowercase return "".join(random.choice(letters) for i in range(string_length)) def filter_polygons(ftr): """Converts GeometryCollection to Polygon/MultiPolygon Args: ftr (object): ee.Feature Returns: object: ee.Feature """ # ee_initialize() geometries = ftr.geometry().geometries() geometries = geometries.map( lambda geo: ee.Feature(ee.Geometry(geo)).set("geoType", ee.Geometry(geo).type()) ) polygons = ( ee.FeatureCollection(geometries) .filter(ee.Filter.eq("geoType", "Polygon")) .geometry() ) return ee.Feature(polygons).copyProperties(ftr) The provided code snippet includes necessary dependencies for implementing the `ee_export_geojson` function. Write a Python function `def ee_export_geojson( ee_object, filename=None, selectors=None, timeout=300, proxies=None )` to solve the following problem: Exports Earth Engine FeatureCollection to geojson. Args: ee_object (object): ee.FeatureCollection to export. filename (str): Output file name. Defaults to None. selectors (list, optional): A list of attributes to export. Defaults to None. timeout (int, optional): Timeout in seconds. Defaults to 300 seconds. proxies (dict, optional): Proxy settings. Defaults to None. Here is the function: def ee_export_geojson( ee_object, filename=None, selectors=None, timeout=300, proxies=None ): """Exports Earth Engine FeatureCollection to geojson. Args: ee_object (object): ee.FeatureCollection to export. filename (str): Output file name. Defaults to None. selectors (list, optional): A list of attributes to export. Defaults to None. timeout (int, optional): Timeout in seconds. Defaults to 300 seconds. proxies (dict, optional): Proxy settings. Defaults to None. """ if not isinstance(ee_object, ee.FeatureCollection): print("The ee_object must be an ee.FeatureCollection.") return if filename is None: out_dir = os.path.join(os.path.expanduser("~"), "Downloads") filename = os.path.join(out_dir, random_string(6) + ".geojson") allowed_formats = ["geojson"] filename = os.path.abspath(filename) basename = os.path.basename(filename) name = os.path.splitext(basename)[0] filetype = os.path.splitext(basename)[1][1:].lower() if not (filetype.lower() in allowed_formats): print("The output file type must be geojson.") return if selectors is None: selectors = ee_object.first().propertyNames().getInfo() selectors = [".geo"] + selectors elif not isinstance(selectors, list): print("selectors must be a list, such as ['attribute1', 'attribute2']") return else: allowed_attributes = ee_object.first().propertyNames().getInfo() for attribute in selectors: if not (attribute in allowed_attributes): print( "Attributes must be one chosen from: {} ".format( ", ".join(allowed_attributes) ) ) return try: # print('Generating URL ...') url = ee_object.getDownloadURL( filetype=filetype, selectors=selectors, filename=name ) # print('Downloading data from {}\nPlease wait ...'.format(url)) r = None r = requests.get(url, stream=True, timeout=timeout, proxies=proxies) if r.status_code != 200: print("An error occurred while downloading. \n Retrying ...") try: new_ee_object = ee_object.map(filter_polygons) print("Generating URL ...") url = new_ee_object.getDownloadURL( filetype=filetype, selectors=selectors, filename=name ) print(f"Downloading data from {url}\nPlease wait ...") r = requests.get(url, stream=True, timeout=timeout, proxies=proxies) except Exception as e: print(e) with open(filename, "wb") as fd: for chunk in r.iter_content(chunk_size=1024): fd.write(chunk) except Exception as e: print("An error occurred while downloading.") if r is not None: print(r.json()["error"]["message"]) return with open(filename) as f: geojson = f.read() return geojson
Exports Earth Engine FeatureCollection to geojson. Args: ee_object (object): ee.FeatureCollection to export. filename (str): Output file name. Defaults to None. selectors (list, optional): A list of attributes to export. Defaults to None. timeout (int, optional): Timeout in seconds. Defaults to 300 seconds. proxies (dict, optional): Proxy settings. Defaults to None.
12,235
import csv import datetime import io import json import math import os import requests import shutil import tarfile import urllib.request import warnings import zipfile import ee import ipywidgets as widgets from ipytree import Node, Tree from typing import Union, List, Dict, Optional, Tuple The provided code snippet includes necessary dependencies for implementing the `ee_export_vector_to_drive` function. Write a Python function `def ee_export_vector_to_drive( collection, description="myExportTableTask", folder=None, fileNamePrefix=None, fileFormat=None, selectors=None, maxVertices=None, **kwargs, )` to solve the following problem: Creates a task to export a FeatureCollection to Drive. Args: collection: The feature collection to be exported. description: Human-readable name of the task. folder: The name of a unique folder in your Drive account to export into. Defaults to the root of the drive. fileNamePrefix: The Google Drive filename for the export. Defaults to the name of the task. fileFormat: The output format: "CSV" (default), "GeoJSON", "KML", "KMZ", "SHP", or "TFRecord". selectors: The list of properties to include in the output, as a list of strings or a comma-separated string. By default, all properties are included. maxVertices: Max number of uncut vertices per geometry; geometries with more vertices will be cut into pieces smaller than this size. **kwargs: Holds other keyword arguments that may have been deprecated such as 'driveFolder' and 'driveFileNamePrefix'. Here is the function: def ee_export_vector_to_drive( collection, description="myExportTableTask", folder=None, fileNamePrefix=None, fileFormat=None, selectors=None, maxVertices=None, **kwargs, ): """Creates a task to export a FeatureCollection to Drive. Args: collection: The feature collection to be exported. description: Human-readable name of the task. folder: The name of a unique folder in your Drive account to export into. Defaults to the root of the drive. fileNamePrefix: The Google Drive filename for the export. Defaults to the name of the task. fileFormat: The output format: "CSV" (default), "GeoJSON", "KML", "KMZ", "SHP", or "TFRecord". selectors: The list of properties to include in the output, as a list of strings or a comma-separated string. By default, all properties are included. maxVertices: Max number of uncut vertices per geometry; geometries with more vertices will be cut into pieces smaller than this size. **kwargs: Holds other keyword arguments that may have been deprecated such as 'driveFolder' and 'driveFileNamePrefix'. """ if not isinstance(collection, ee.FeatureCollection): raise ValueError("The collection must be an ee.FeatureCollection.") allowed_formats = ["csv", "geojson", "kml", "kmz", "shp", "tfrecord"] if not (fileFormat.lower() in allowed_formats): raise ValueError( "The file type must be one of the following: {}".format( ", ".join(allowed_formats) ) ) if os.environ.get("USE_MKDOCS") is not None: # skip if running GitHub CI. return print( f"Exporting {description}... Please check the Task Manager from the JavaScript Code Editor." ) task = ee.batch.Export.table.toDrive( collection, description, folder, fileNamePrefix, fileFormat, selectors, maxVertices, **kwargs, ) task.start()
Creates a task to export a FeatureCollection to Drive. Args: collection: The feature collection to be exported. description: Human-readable name of the task. folder: The name of a unique folder in your Drive account to export into. Defaults to the root of the drive. fileNamePrefix: The Google Drive filename for the export. Defaults to the name of the task. fileFormat: The output format: "CSV" (default), "GeoJSON", "KML", "KMZ", "SHP", or "TFRecord". selectors: The list of properties to include in the output, as a list of strings or a comma-separated string. By default, all properties are included. maxVertices: Max number of uncut vertices per geometry; geometries with more vertices will be cut into pieces smaller than this size. **kwargs: Holds other keyword arguments that may have been deprecated such as 'driveFolder' and 'driveFileNamePrefix'.
12,236
import csv import datetime import io import json import math import os import requests import shutil import tarfile import urllib.request import warnings import zipfile import ee import ipywidgets as widgets from ipytree import Node, Tree from typing import Union, List, Dict, Optional, Tuple def ee_user_id(): """Gets Earth Engine account user id. Returns: str: A string containing the user id. """ # ee_initialize() roots = ee.data.getAssetRoots() if len(roots) == 0: return None else: root = ee.data.getAssetRoots()[0] user_id = root["id"].replace("projects/earthengine-legacy/assets/", "") return user_id The provided code snippet includes necessary dependencies for implementing the `ee_export_vector_to_asset` function. Write a Python function `def ee_export_vector_to_asset( collection, description="myExportTableTask", assetId=None, maxVertices=None, **kwargs, )` to solve the following problem: Creates a task to export a FeatureCollection to Asset. Args: collection: The feature collection to be exported. description: Human-readable name of the task. assetId: The destination asset ID. maxVertices: Max number of uncut vertices per geometry; geometries with more vertices will be cut into pieces smaller than this size. **kwargs: Holds other keyword arguments that may have been deprecated. Here is the function: def ee_export_vector_to_asset( collection, description="myExportTableTask", assetId=None, maxVertices=None, **kwargs, ): """Creates a task to export a FeatureCollection to Asset. Args: collection: The feature collection to be exported. description: Human-readable name of the task. assetId: The destination asset ID. maxVertices: Max number of uncut vertices per geometry; geometries with more vertices will be cut into pieces smaller than this size. **kwargs: Holds other keyword arguments that may have been deprecated. """ if not isinstance(collection, ee.FeatureCollection): raise ValueError("The collection must be an ee.FeatureCollection.") if os.environ.get("USE_MKDOCS") is not None: # skip if running GitHub CI. return if isinstance(assetId, str): if assetId.startswith("users/") or assetId.startswith("projects/"): pass else: assetId = f"{ee_user_id()}/{assetId}" print(assetId) print( f"Exporting {description}... Please check the Task Manager from the JavaScript Code Editor." ) task = ee.batch.Export.table.toAsset( collection, description, assetId, maxVertices, **kwargs, ) task.start()
Creates a task to export a FeatureCollection to Asset. Args: collection: The feature collection to be exported. description: Human-readable name of the task. assetId: The destination asset ID. maxVertices: Max number of uncut vertices per geometry; geometries with more vertices will be cut into pieces smaller than this size. **kwargs: Holds other keyword arguments that may have been deprecated.
12,237
import csv import datetime import io import json import math import os import requests import shutil import tarfile import urllib.request import warnings import zipfile import ee import ipywidgets as widgets from ipytree import Node, Tree from typing import Union, List, Dict, Optional, Tuple The provided code snippet includes necessary dependencies for implementing the `ee_export_vector_to_cloud_storage` function. Write a Python function `def ee_export_vector_to_cloud_storage( collection, description="myExportTableTask", bucket=None, fileNamePrefix=None, fileFormat=None, selectors=None, maxVertices=None, **kwargs, )` to solve the following problem: Creates a task to export a FeatureCollection to Google Cloud Storage. Args: collection: The feature collection to be exported. description: Human-readable name of the task. bucket: The name of a Cloud Storage bucket for the export. fileNamePrefix: Cloud Storage object name prefix for the export. Defaults to the name of the task. fileFormat: The output format: "CSV" (default), "GeoJSON", "KML", "KMZ", "SHP", or "TFRecord". selectors: The list of properties to include in the output, as a list of strings or a comma-separated string. By default, all properties are included. maxVertices: Max number of uncut vertices per geometry; geometries with more vertices will be cut into pieces smaller than this size. **kwargs: Holds other keyword arguments that may have been deprecated such as 'outputBucket'. Here is the function: def ee_export_vector_to_cloud_storage( collection, description="myExportTableTask", bucket=None, fileNamePrefix=None, fileFormat=None, selectors=None, maxVertices=None, **kwargs, ): """Creates a task to export a FeatureCollection to Google Cloud Storage. Args: collection: The feature collection to be exported. description: Human-readable name of the task. bucket: The name of a Cloud Storage bucket for the export. fileNamePrefix: Cloud Storage object name prefix for the export. Defaults to the name of the task. fileFormat: The output format: "CSV" (default), "GeoJSON", "KML", "KMZ", "SHP", or "TFRecord". selectors: The list of properties to include in the output, as a list of strings or a comma-separated string. By default, all properties are included. maxVertices: Max number of uncut vertices per geometry; geometries with more vertices will be cut into pieces smaller than this size. **kwargs: Holds other keyword arguments that may have been deprecated such as 'outputBucket'. """ if not isinstance(collection, ee.FeatureCollection): raise ValueError("The collection must be an ee.FeatureCollection.") allowed_formats = ["csv", "geojson", "kml", "kmz", "shp", "tfrecord"] if not (fileFormat.lower() in allowed_formats): raise ValueError( "The file type must be one of the following: {}".format( ", ".join(allowed_formats) ) ) if os.environ.get("USE_MKDOCS") is not None: # skip if running GitHub CI. return print( f"Exporting {description}... Please check the Task Manager from the JavaScript Code Editor." ) task = ee.batch.Export.table.toCloudStorage( collection, description, bucket, fileNamePrefix, fileFormat, selectors, maxVertices, **kwargs, ) task.start()
Creates a task to export a FeatureCollection to Google Cloud Storage. Args: collection: The feature collection to be exported. description: Human-readable name of the task. bucket: The name of a Cloud Storage bucket for the export. fileNamePrefix: Cloud Storage object name prefix for the export. Defaults to the name of the task. fileFormat: The output format: "CSV" (default), "GeoJSON", "KML", "KMZ", "SHP", or "TFRecord". selectors: The list of properties to include in the output, as a list of strings or a comma-separated string. By default, all properties are included. maxVertices: Max number of uncut vertices per geometry; geometries with more vertices will be cut into pieces smaller than this size. **kwargs: Holds other keyword arguments that may have been deprecated such as 'outputBucket'.