├── .gitignore ├── LICENSE ├── README.md ├── gee_asset_manager ├── __init__.py ├── batch_copy.py ├── batch_info.py ├── batch_remover.py ├── batch_uploader.py ├── config.py ├── logconfig.json ├── metadata_loader.py └── session.py ├── geebam.py ├── requirements.txt ├── setup.py └── tests ├── images ├── 230.tif ├── 263.test.tif ├── 263.tif ├── 4.tif ├── 6.tif └── metadata.csv ├── test_session.py └── test_upload.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | env/ 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | downloads/ 16 | eggs/ 17 | .eggs/ 18 | lib/ 19 | lib64/ 20 | parts/ 21 | sdist/ 22 | var/ 23 | *.egg-info/ 24 | .installed.cfg 25 | *.egg 26 | 27 | # PyInstaller 28 | # Usually these files are written by a python script from a template 29 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 30 | *.manifest 31 | *.spec 32 | 33 | # Installer logs 34 | pip-log.txt 35 | pip-delete-this-directory.txt 36 | 37 | # Unit test / coverage reports 38 | htmlcov/ 39 | .tox/ 40 | .coverage 41 | .coverage.* 42 | .cache 43 | nosetests.xml 44 | coverage.xml 45 | *,cover 46 | .hypothesis/ 47 | 48 | # Translations 49 | *.mo 50 | *.pot 51 | 52 | # Django stuff: 53 | *.log 54 | local_settings.py 55 | 56 | # Flask stuff: 57 | instance/ 58 | .webassets-cache 59 | 60 | # Scrapy stuff: 61 | .scrapy 62 | 63 | # Sphinx documentation 64 | docs/_build/ 65 | 66 | # PyBuilder 67 | target/ 68 | 69 | # IPython Notebook 70 | .ipynb_checkpoints 71 | 72 | # pyenv 73 | .python-version 74 | 75 | # celery beat schedule file 76 | celerybeat-schedule 77 | 78 | # dotenv 79 | .env 80 | 81 | # virtualenv 82 | venv/ 83 | ENV/ 84 | 85 | # Spyder project settings 86 | .spyderproject 87 | 88 | # Rope project settings 89 | .ropeproject 90 | 91 | # log files 92 | .idea/ -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2016 Lukasz Tracewski 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Google Earth Engine Batch Asset Manager 2 | Google Earth Engine Batch Asset Manager ambition is helping user with batch actions on assets. It will be developed on use case basis, so if there's something missing feel free to post a feature request in [Issues](https://github.com/tracek/gee_asset_manager/issues) tab. 3 | 4 | ## Table of contents 5 | * [Installation](#installation) 6 | * [Getting started](#getting-started) 7 | * [Batch uploader](#batch-uploader) 8 | * [Parsing metadata](#parsing-metadata) 9 | * [Usage examples](#usage-examples) 10 | * [Delete a collection with content:](#delete-a-collection-with-content) 11 | * [Upload a directory with images and associate properties with each image:](#upload-a-directory-with-images-and-associate-properties-with-each-image) 12 | 13 | ## Installation 14 | We assume Earth Engine Python API is installed and EE authorised as desribed [here](https://developers.google.com/earth-engine/python_install). To install: 15 | ``` 16 | git clone https://github.com/tracek/gee_asset_manager 17 | cd gee_asset_manager && pip install -e . 18 | ``` 19 | 20 | Installation is an optional step; the application can be also run 21 | directly by executing geebam.py script. The advantage of having it 22 | installed is being able to execute geebam as any command line tool. I 23 | recommend installation within virtual environment. 24 | 25 | ## Getting started 26 | 27 | As usual, to print help: 28 | ``` 29 | geebam -h 30 | 31 | positional arguments: 32 | {delete,upload,cancel,report} 33 | delete Deletes collection and all items inside. Supports 34 | Unix-like wildcards. 35 | upload Batch Asset Uploader. 36 | cancel Cancel all running tasks 37 | report Produce summary of all assets. 38 | 39 | optional arguments: 40 | -h, --help show this help message and exit 41 | -s SERVICE_ACCOUNT, --service-account SERVICE_ACCOUNT 42 | Google Earth Engine service account. 43 | -k PRIVATE_KEY, --private-key PRIVATE_KEY 44 | Google Earth Engine private key file. 45 | ``` 46 | 47 | To obtain help for a specific functionality, simply call it with _help_ 48 | switch, e.g.: `geebam upload -h`. If you didn't install geebam, then you 49 | can run it just by going to _geebam_ directory and running `python 50 | geebam.py [arguments go here]` 51 | 52 | ## Batch uploader 53 | The script creates an Image Collection from GeoTIFFs in your local 54 | directory. By default, the collection name is the same as the local 55 | directory name; with optional parameter you can provide a different 56 | name. Another optional parameter is a path to a CSV file with metadata 57 | for images, which is covered in the next section: 58 | [Parsing metadata](#parsing-metadata). 59 | 60 | 61 | 62 | ``` 63 | geebam upload -h 64 | 65 | usage: geebam upload [-h] --source SOURCE --dest DEST [-m METADATA] [--large] 66 | [--nodata NODATA] [-u USER] [-s SERVICE_ACCOUNT] 67 | [-k PRIVATE_KEY] [-b BUCKET] 68 | 69 | optional arguments: 70 | -h, --help show this help message and exit 71 | 72 | Required named arguments.: 73 | --source SOURCE Path to the directory with images for upload. 74 | --dest DEST Destination. Full path for upload to Google Earth 75 | Engine, e.g. users/pinkiepie/myponycollection 76 | -u USER, --user USER Google account name (gmail address). 77 | 78 | Optional named arguments: 79 | -m METADATA, --metadata METADATA 80 | Path to CSV with metadata. 81 | --large (Advanced) Use multipart upload. Might help if upload 82 | of large files is failing on some systems. Might cause 83 | other issues. 84 | --nodata NODATA The value to burn into the raster as NoData (missing 85 | data) 86 | -b BUCKET, --bucket BUCKET 87 | Google Cloud Storage bucket name 88 | 89 | ``` 90 | 91 | ### Parsing metadata 92 | By metadata we understand here the properties associated with each image. Thanks to these, GEE user can easily filter collection based on specified criteria. The file with metadata should be organised as follows: 93 | 94 | | filename (without extension) | property1 header | property2 header | 95 | |------------------------------|------------------|------------------| 96 | | file1 | value1 | value2 | 97 | | file2 | value3 | value4 | 98 | 99 | Note that header can contain only letters, digits and underscores. 100 | 101 | Example: 102 | 103 | | id_no | class | category | binomial |system:time_start| 104 | |-----------|------------|----------|----------------------|-----------------| 105 | | my_file_1 | GASTROPODA | EN | Aaadonta constricta |1478943081000 | 106 | | my_file_2 | GASTROPODA | CR | Aaadonta irregularis |1478943081000 | 107 | 108 | The corresponding files are my_file_1.tif and my_file_2.tif. With each of the files five properties are associated: id_no, class, category, binomial and system:time_start. The latter is time in Unix epoch format, in milliseconds, as documented in GEE glosary. The program will match the file names from the upload directory with ones provided in the CSV and pass the metadata in JSON format: 109 | 110 | ``` 111 | { id_no: my_file_1, class: GASTROPODA, category: EN, binomial: Aaadonta constricta, system:time_start: 1478943081000} 112 | ``` 113 | 114 | The program will report any illegal fields, it will also complain if not all of the images passed for upload have metadata associated. User can opt to ignore it, in which case some assets will have no properties. 115 | 116 | Having metadata helps in organising your asstets, but is not mandatory - you can skip it. 117 | 118 | ## Usage examples 119 | 120 | ### Delete a collection with content: 121 | 122 | The delete is recursive, meaning it will delete also all children assets: images, collections and folders. Use with caution! 123 | ``` 124 | geebam delete users/pinkiepie/test 125 | ``` 126 | 127 | Console output: 128 | ``` 129 | 2016-07-17 16:14:09,212 :: oauth2client.client :: INFO :: Attempting refresh to obtain initial access_token 130 | 2016-07-17 16:14:09,213 :: oauth2client.client :: INFO :: Refreshing access_token 131 | 2016-07-17 16:14:10,842 :: root :: INFO :: Attempting to delete collection test 132 | 2016-07-17 16:14:16,898 :: root :: INFO :: Collection users/pinkiepie/test removed 133 | ``` 134 | 135 | ### Delete all directories / collections based on a Unix-like pattern 136 | 137 | ``` 138 | geebam delete users/pinkiepie/*weird[0-9]?name* 139 | ``` 140 | 141 | 142 | ### Upload a directory with images to your myfolder/mycollection and associate properties with each image: 143 | ``` 144 | geebam upload -u pinkiepie@gmail.com --source path_to_directory_with_tif -m path_to_metadata.csv --dest users/pinkiepie/myfolder/myponycollection 145 | ``` 146 | The script will prompt the user for Google account password. The program will also check that all properties in path_to_metadata.csv do not contain any illegal characters for GEE. Don't need metadata? Simply skip this option. 147 | 148 | ### Upload a directory with images with specific NoData value to a selected destination 149 | ``` 150 | geebam upload -u pinkiepie@gmail.com --source path_to_directory_with_tif --dest users/pinkiepie/myfolder/myponycollection --nodata 222 151 | ``` 152 | In this case we need to supply full path to the destination, which is helpful when we upload to a shared folder. In the provided example we also burn value 222 into all rasters for missing data (NoData). -------------------------------------------------------------------------------- /gee_asset_manager/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | __author__ = 'Lukasz Tracewski' 4 | __email__ = 'lukasz.tracewski@outlook.com' 5 | VERSION = (0, 1, 6) 6 | __version__ = ".".join([str(x) for x in VERSION]) -------------------------------------------------------------------------------- /gee_asset_manager/batch_copy.py: -------------------------------------------------------------------------------- 1 | import ee 2 | import os 3 | import csv 4 | import logging 5 | 6 | def copy(source, destination): 7 | with open(source, 'r') as f: 8 | reader = csv.reader(f) 9 | for line in reader: 10 | name = line[0] 11 | gme_id = line[1] 12 | gme_path = 'GME/images/' + gme_id 13 | ee_path = os.path.join(destination, name) 14 | logging.info('Copying asset %s to %s', gme_path, ee_path) 15 | try: 16 | ee.data.copyAsset(gme_path, ee_path) 17 | except ee.EEException as e: 18 | with open('failed_batch_copy.csv', 'w') as fout: 19 | fout.write('{},{},{},{}'.format(name, gme_id, ee_path,e)) 20 | 21 | 22 | if __name__ == '__main__': 23 | ee.Initialize() 24 | assets = '/home/tracek/Data/consbio2016/test.csv' 25 | with open(assets, 'r') as f: 26 | reader = csv.reader(f) -------------------------------------------------------------------------------- /gee_asset_manager/batch_info.py: -------------------------------------------------------------------------------- 1 | # Much of the code below has been copied from 2 | # https://github.com/google/earthengine-api/blob/master/python/ee/cli/commands.py 3 | 4 | import sys 5 | import datetime 6 | import csv 7 | import ee 8 | 9 | 10 | class ReportWriter(object): 11 | 12 | def __init__(self, filename=None): 13 | self.total_size = 0 14 | self.writers = [csv.writer(sys.stdout)] 15 | self.writer_fo = None 16 | if filename: 17 | if sys.version_info[0] < 3: 18 | self.writer_fo = open(filename + '.csv', 'wb') 19 | else: 20 | self.writer_fo = open(filename + '.csv', 'w') 21 | self.writers.append(csv.writer(self.writer_fo)) 22 | 23 | def __del__(self): 24 | if self.writer_fo and not self.writer_fo.closed: 25 | self.writer_fo.close() 26 | print('Total size [MB]: {:.2f}'.format(self.total_size)) 27 | 28 | def writerow(self, data): 29 | [writer.writerow(data) for writer in self.writers] 30 | 31 | def report(filename): 32 | ee.Initialize() 33 | assets_root = ee.data.getAssetRoots() 34 | writer = ReportWriter(filename) 35 | writer.writerow(['Asset id', 'Type', 'Size [MB]', 'Time', 'Owners', 'Readers', 'Writers']) 36 | 37 | for asset in assets_root: 38 | # List size+name for every leaf asset, and show totals for non-leaves. 39 | if asset['type'] == ee.data.ASSET_TYPE_FOLDER: 40 | children = ee.data.getList(asset) 41 | for child in children: 42 | _print_size(child, writer) 43 | else: 44 | _print_size(asset, writer) 45 | 46 | def get_datetime_str(epoch): 47 | dt = datetime.datetime.fromtimestamp(epoch / 10**6) # microseconds to seconds 48 | return dt.strftime("%Y-%m-%d %H:%M:%S") 49 | 50 | def _print_size(asset, writer): 51 | asset_info = ee.data.getInfo(asset['id']) 52 | 53 | if 'properties' in asset_info and 'system:asset_size' in asset_info['properties']: 54 | size = asset_info['properties']['system:asset_size'] 55 | else: 56 | size = _get_size(asset) 57 | size = round(size / 1024**2, 2) # size in MB 58 | 59 | type = asset_info['type'] 60 | time = get_datetime_str(asset_info['version']) 61 | 62 | acl = ee.data.getAssetAcl(asset['id']) 63 | owners = ' '.join(acl['owners']) 64 | readers = ' '.join(acl['readers']) 65 | writers = ' '.join(acl['writers']) 66 | 67 | writer.writerow([asset['id'], type, size, time, owners, readers, writers]) 68 | writer.total_size += size 69 | 70 | 71 | def _get_size(asset): 72 | """Returns the size of the given asset in bytes.""" 73 | size_parsers = { 74 | 'Folder': _get_size_folder, 75 | 'ImageCollection': _get_size_image_collection, 76 | } 77 | 78 | if asset['type'] not in size_parsers: 79 | raise ee.EEException( 80 | 'Cannot get size for asset type "%s"' % asset['type']) 81 | 82 | return size_parsers[asset['type']](asset) 83 | 84 | 85 | def _get_size_image(asset): 86 | info = ee.data.getInfo(asset['id']) 87 | 88 | return info['properties']['system:asset_size'] 89 | 90 | 91 | def _get_size_folder(asset): 92 | children = ee.data.getList(asset) 93 | sizes = [_get_size(child) for child in children] 94 | 95 | return sum(sizes) 96 | 97 | 98 | def _get_size_image_collection(asset): 99 | images = ee.ImageCollection(asset['id']) 100 | sizes = images.aggregate_array('system:asset_size') 101 | 102 | return sum(sizes.getInfo()) 103 | 104 | 105 | if __name__ == '__main__': 106 | report(None) -------------------------------------------------------------------------------- /gee_asset_manager/batch_remover.py: -------------------------------------------------------------------------------- 1 | __copyright__ = """ 2 | 3 | Copyright 2016 Lukasz Tracewski 4 | 5 | Licensed under the Apache License, Version 2.0 (the "License"); 6 | you may not use this file except in compliance with the License. 7 | You may obtain a copy of the License at 8 | 9 | http://www.apache.org/licenses/LICENSE-2.0 10 | 11 | Unless required by applicable law or agreed to in writing, software 12 | distributed under the License is distributed on an "AS IS" BASIS, 13 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | See the License for the specific language governing permissions and 15 | limitations under the License. 16 | 17 | """ 18 | __license__ = "Apache 2.0" 19 | 20 | import fnmatch 21 | import logging 22 | import sys 23 | 24 | import ee 25 | 26 | 27 | def delete(asset_path): 28 | root_idx = asset_path.rfind('/') 29 | if root_idx == -1: 30 | logging.warning('Asset not found. Make sure you pass full asset name, e.g. users/pinkiepie/rainbow') 31 | sys.exit(1) 32 | root = asset_path[:root_idx] 33 | all_assets_names = [e['id'] for e in ee.data.getList({'id': root})] 34 | filtered_names = fnmatch.filter(all_assets_names, asset_path) 35 | if not filtered_names: 36 | logging.warning('Nothing to remove. Exiting.') 37 | sys.exit(1) 38 | else: 39 | for path in filtered_names: 40 | __delete_recursive(path) 41 | logging.info('Collection %s removed', path) 42 | 43 | 44 | def __delete_recursive(asset_path): 45 | info = ee.data.getInfo(asset_path) 46 | if not info: 47 | logging.warning('Nothing to delete.') 48 | sys.exit(1) 49 | elif info['type'] == 'Image': 50 | pass 51 | elif info['type'] == 'Folder': 52 | items_in_destination = ee.data.getList({'id': asset_path}) 53 | for item in items_in_destination: 54 | logging.info('Removing items in %s folder', item['id']) 55 | delete(item['id']) 56 | else: 57 | items_in_destination = ee.data.getList({'id': asset_path}) 58 | for item in items_in_destination: 59 | ee.data.deleteAsset(item['id']) 60 | ee.data.deleteAsset(asset_path) 61 | -------------------------------------------------------------------------------- /gee_asset_manager/batch_uploader.py: -------------------------------------------------------------------------------- 1 | __copyright__ = """ 2 | 3 | Copyright 2016 Lukasz Tracewski 4 | 5 | Licensed under the Apache License, Version 2.0 (the "License"); 6 | you may not use this file except in compliance with the License. 7 | You may obtain a copy of the License at 8 | 9 | http://www.apache.org/licenses/LICENSE-2.0 10 | 11 | Unless required by applicable law or agreed to in writing, software 12 | distributed under the License is distributed on an "AS IS" BASIS, 13 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | See the License for the specific language governing permissions and 15 | limitations under the License. 16 | 17 | """ 18 | __license__ = "Apache 2.0" 19 | 20 | import ast 21 | import csv 22 | import getpass 23 | import glob 24 | import logging 25 | import os 26 | import sys 27 | import time 28 | import ee 29 | import retrying 30 | from requests_toolbelt.multipart import encoder 31 | from google.cloud import storage 32 | from .metadata_loader import load_metadata_from_csv, validate_metadata_from_csv 33 | from .session import get_google_session 34 | 35 | 36 | def upload( 37 | user, 38 | source_path, 39 | destination_path, 40 | headless, 41 | metadata_path = None, 42 | multipart_upload = False, 43 | nodata_value = None, 44 | bucket_name = None, 45 | band_names = [], 46 | signal_if_error = False, 47 | tolerate_assets_already_exist = True): 48 | """ 49 | Uploads content of a given directory to GEE. The function first uploads an asset to Google Cloud Storage (GCS) 50 | and then uses ee.data.startIngestion to put it into GEE, Due to GCS intermediate step, users is asked for 51 | Google's account name and password. 52 | 53 | In case any exception happens during the upload, the function will repeat the call a given number of times, after 54 | which the error will be propagated further. 55 | 56 | :param user: name of a Google account 57 | :param source_path: path to a directory 58 | :param destination_path: where to upload (absolute path) 59 | :param metadata_path: (optional) path to file with metadata 60 | :param multipart_upload: (optional) alternative mode op upload - use if the other one fails 61 | :param nodata_value: (optinal) value to burn into raster for missind data in the image 62 | :return: 63 | """ 64 | submitted_tasks_id = {} 65 | 66 | __verify_path_for_upload(destination_path) 67 | 68 | path = os.path.join(os.path.expanduser(source_path), '*.tif') 69 | all_images_paths = glob.glob(path) 70 | 71 | if len(all_images_paths) == 0: 72 | logging.error('%s does not contain any tif images.', path) 73 | sys.exit(1) 74 | 75 | metadata = load_metadata_from_csv(metadata_path) if metadata_path else None 76 | 77 | if user is not None: 78 | password = getpass.getpass() 79 | google_session = get_google_session(url='https://code.earthengine.google.com/', 80 | account_name=user, 81 | password=password, 82 | browser='Chrome', 83 | headless=headless) 84 | else: 85 | storage_client = storage.Client() 86 | 87 | __create_image_collection(destination_path) 88 | 89 | images_for_upload_path = __find_remaining_assets_for_upload( 90 | all_images_paths, 91 | destination_path, 92 | tolerate_assets_already_exist) 93 | 94 | no_images = len(images_for_upload_path) 95 | 96 | if no_images == 0: 97 | logging.error('No images found that match %s. Exiting...', path) 98 | sys.exit(1) 99 | 100 | failed_asset_writer = FailedAssetsWriter() 101 | got_errors = False 102 | 103 | for current_image_no, image_path in enumerate(images_for_upload_path): 104 | logging.info('Processing image %d out of %d: %s', current_image_no+1, no_images, image_path) 105 | filename = __get_filename_from_path(path=image_path) 106 | 107 | asset_full_path = destination_path + '/' + filename 108 | 109 | if metadata and not filename in metadata: 110 | logging.warning("No metadata exists for image %s: it will not be ingested", filename) 111 | failed_asset_writer.writerow([filename, 0, 'Missing metadata']) 112 | continue 113 | 114 | properties = metadata[filename] if metadata else None 115 | 116 | try: 117 | if user is not None: 118 | gsid = __upload_file_gee(session=google_session, 119 | file_path=image_path, 120 | use_multipart=multipart_upload) 121 | else: 122 | gsid = __upload_file_gcs(storage_client, bucket_name, image_path) 123 | 124 | asset_request = __create_asset_request(asset_full_path, gsid, properties, nodata_value, band_names) 125 | 126 | task_id = __start_ingestion_task(asset_request) 127 | submitted_tasks_id[task_id] = filename 128 | __periodic_check(current_image=current_image_no, period=20, tasks=submitted_tasks_id, writer=failed_asset_writer) 129 | except Exception as e: 130 | logging.exception('Upload of %s has failed.', filename) 131 | failed_asset_writer.writerow([filename, 0, str(e)]) 132 | got_errors = True 133 | 134 | __check_for_failed_tasks_and_report(tasks=submitted_tasks_id, writer=failed_asset_writer) 135 | failed_asset_writer.close() 136 | if signal_if_error and got_errors: 137 | sys.exit(1) 138 | 139 | 140 | def __create_asset_request(asset_full_path, gsid, properties, nodata_value, band_names): 141 | if band_names: 142 | band_names = [{'id': name} for name in band_names] 143 | 144 | return {"id": asset_full_path, 145 | "tilesets": [ 146 | {"sources": [ 147 | {"primaryPath": gsid, 148 | "additionalPaths": [] 149 | } 150 | ]} 151 | ], 152 | "bands": band_names, 153 | "properties": properties, 154 | "missingData": {"values": [nodata_value]} 155 | } 156 | 157 | 158 | def __verify_path_for_upload(path): 159 | folder = path[:path.rfind('/')] 160 | response = ee.data.getInfo(folder) 161 | if not response: 162 | logging.error('%s is not a valid destination. Make sure full path is provided e.g. users/user/nameofcollection ' 163 | 'or projects/myproject/myfolder/newcollection and that you have write access there.', path) 164 | sys.exit(1) 165 | 166 | 167 | def __find_remaining_assets_for_upload(path_to_local_assets, path_remote, tolerate_assets_already_exist): 168 | local_assets = [__get_filename_from_path(path) for path in path_to_local_assets] 169 | if __collection_exist(path_remote): 170 | remote_assets = __get_asset_names_from_collection(path_remote) 171 | if len(remote_assets) > 0: 172 | assets_left_for_upload = set(local_assets) - set(remote_assets) 173 | if len(assets_left_for_upload) == 0: 174 | logging.warning('Collection already exists and contains all assets provided for upload. Exiting ...') 175 | if tolerate_assets_already_exist: 176 | sys.exit(0) 177 | else: 178 | sys.exit(1) 179 | 180 | logging.info('Collection already exists. %d assets left for upload to %s.', len(assets_left_for_upload), path_remote) 181 | assets_left_for_upload_full_path = [path for path in path_to_local_assets 182 | if __get_filename_from_path(path) in assets_left_for_upload] 183 | return assets_left_for_upload_full_path 184 | 185 | return path_to_local_assets 186 | 187 | 188 | def retry_if_ee_error(exception): 189 | return isinstance(exception, ee.EEException) 190 | 191 | 192 | @retrying.retry(retry_on_exception=retry_if_ee_error, wait_exponential_multiplier=1000, wait_exponential_max=4000, stop_max_attempt_number=3) 193 | def __start_ingestion_task(asset_request): 194 | task_id = ee.data.newTaskId(1)[0] 195 | _ = ee.data.startIngestion(task_id, asset_request) 196 | return task_id 197 | 198 | 199 | def __validate_metadata(path_for_upload, metadata_path): 200 | validation_result = validate_metadata_from_csv(metadata_path) 201 | keys_in_metadata = {result.keys for result in validation_result} 202 | images_paths = glob.glob(os.path.join(path_for_upload, '*.tif*')) 203 | keys_in_data = {__get_filename_from_path(path) for path in images_paths} 204 | missing_keys = keys_in_data - keys_in_metadata 205 | 206 | if missing_keys: 207 | logging.warning('%d images does not have a corresponding key in metadata', len(missing_keys)) 208 | print('\n'.join(e for e in missing_keys)) 209 | else: 210 | logging.info('All images have metadata available') 211 | 212 | if not validation_result.success: 213 | print('Validation finished with errors. Type "y" to continue, default NO: ') 214 | choice = input().lower() 215 | if choice not in ['y', 'yes']: 216 | logging.info('Application will terminate') 217 | exit(1) 218 | 219 | 220 | def __extract_metadata_for_image(filename, metadata): 221 | if filename in metadata: 222 | return metadata[filename] 223 | else: 224 | logging.warning('Metadata for %s not found', filename) 225 | return None 226 | 227 | 228 | def __get_upload_url(session): 229 | r = session.get("https://code.earthengine.google.com/assets/upload/geturl") 230 | if r.text.startswith('\n'): 231 | logging.error('Login has failed. .') 232 | sys.exit(1) 233 | d = ast.literal_eval(r.text) 234 | return d['url'] 235 | 236 | 237 | @retrying.retry(retry_on_exception=retry_if_ee_error, wait_exponential_multiplier=1000, wait_exponential_max=4000, stop_max_attempt_number=3) 238 | def __upload_file_gee(session, file_path, use_multipart): 239 | with open(file_path, 'rb') as f: 240 | upload_url = __get_upload_url(session) 241 | 242 | if use_multipart: 243 | form = encoder.MultipartEncoder({ 244 | "documents": (file_path, f, "application/octet-stream"), 245 | "composite": "NONE", 246 | }) 247 | headers = {"Prefer": "respond-async", "Content-Type": form.content_type} 248 | resp = session.post(upload_url, headers=headers, data=form) 249 | else: 250 | files = {'file': f} 251 | resp = session.post(upload_url, files=files) 252 | 253 | gsid = resp.json()[0] 254 | 255 | return gsid 256 | 257 | 258 | @retrying.retry(retry_on_exception=retry_if_ee_error, wait_exponential_multiplier=1000, wait_exponential_max=4000, stop_max_attempt_number=3) 259 | def __upload_file_gcs(storage_client, bucket_name, image_path): 260 | bucket = storage_client.get_bucket(bucket_name) 261 | blob_name = __get_filename_from_path(path=image_path) 262 | blob = bucket.blob(blob_name) 263 | 264 | blob.upload_from_filename(image_path) 265 | 266 | url = 'gs://' + bucket_name + '/' + blob_name 267 | 268 | return url 269 | 270 | def __periodic_check(current_image, period, tasks, writer): 271 | if (current_image + 1) % period == 0: 272 | logging.info('Periodic check') 273 | __check_for_failed_tasks_and_report(tasks=tasks, writer=writer) 274 | # Time to check how many tasks are running! 275 | __wait_for_tasks_to_complete(waiting_time=10, no_allowed_tasks_running=20) 276 | 277 | 278 | def __check_for_failed_tasks_and_report(tasks, writer): 279 | if len(tasks) == 0: 280 | return 281 | 282 | statuses = ee.data.getTaskStatus(tasks.keys()) 283 | 284 | for status in statuses: 285 | if status['state'] == 'FAILED': 286 | task_id = status['id'] 287 | filename = tasks[task_id] 288 | error_message = status['error_message'] 289 | writer.writerow([filename, task_id, error_message]) 290 | logging.error('Ingestion of image %s has failed with message %s', filename, error_message) 291 | 292 | tasks.clear() 293 | 294 | 295 | def __get_filename_from_path(path): 296 | return os.path.splitext(os.path.basename(os.path.normpath(path)))[0] 297 | 298 | 299 | def __get_number_of_running_tasks(): 300 | return len([task for task in ee.data.getTaskList() if task['state'] == 'RUNNING']) 301 | 302 | 303 | def __wait_for_tasks_to_complete(waiting_time, no_allowed_tasks_running): 304 | tasks_running = __get_number_of_running_tasks() 305 | while tasks_running > no_allowed_tasks_running: 306 | logging.info('Number of running tasks is %d. Sleeping for %d s until it goes down to %d', 307 | tasks_running, waiting_time, no_allowed_tasks_running) 308 | time.sleep(waiting_time) 309 | tasks_running = __get_number_of_running_tasks() 310 | 311 | 312 | def __collection_exist(path): 313 | return True if ee.data.getInfo(path) else False 314 | 315 | 316 | def __create_image_collection(full_path_to_collection): 317 | if __collection_exist(full_path_to_collection): 318 | logging.warning("Collection %s already exists", full_path_to_collection) 319 | else: 320 | ee.data.createAsset({'type': ee.data.ASSET_TYPE_IMAGE_COLL}, full_path_to_collection) 321 | logging.info('New collection %s created', full_path_to_collection) 322 | 323 | 324 | def __get_asset_names_from_collection(collection_path): 325 | assets_list = ee.data.getList(params={'id': collection_path}) 326 | assets_names = [os.path.basename(asset['id']) for asset in assets_list] 327 | return assets_names 328 | 329 | 330 | class FailedAssetsWriter(object): 331 | 332 | def __init__(self): 333 | self.initialized = False 334 | 335 | def writerow(self, row): 336 | if not self.initialized: 337 | if sys.version_info > (3, 0): 338 | self.failed_upload_file = open('failed_upload.csv', 'w') 339 | else: 340 | self.failed_upload_file = open('failed_upload.csv', 'wb') 341 | self.failed_upload_writer = csv.writer(self.failed_upload_file) 342 | self.failed_upload_writer.writerow(['filename', 'task_id', 'error_msg']) 343 | self.initialized = True 344 | self.failed_upload_writer.writerow(row) 345 | 346 | def close(self): 347 | if self.initialized: 348 | self.failed_upload_file.close() 349 | self.initialized = False 350 | -------------------------------------------------------------------------------- /gee_asset_manager/config.py: -------------------------------------------------------------------------------- 1 | __copyright__ = """ 2 | 3 | Copyright 2016 Lukasz Tracewski 4 | 5 | Licensed under the Apache License, Version 2.0 (the "License"); 6 | you may not use this file except in compliance with the License. 7 | You may obtain a copy of the License at 8 | 9 | http://www.apache.org/licenses/LICENSE-2.0 10 | 11 | Unless required by applicable law or agreed to in writing, software 12 | distributed under the License is distributed on an "AS IS" BASIS, 13 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | See the License for the specific language governing permissions and 15 | limitations under the License. 16 | 17 | """ 18 | __license__ = "Apache 2.0" 19 | 20 | import json 21 | import logging.config 22 | import os 23 | 24 | default_config = { 25 | "version": 1, 26 | "disable_existing_loggers": False, 27 | "formatters": { 28 | "simple": { 29 | "format": "%(asctime)s :: %(name)s :: %(levelname)s :: %(message)s" 30 | } 31 | }, 32 | 33 | "handlers": { 34 | "console": { 35 | "class": "logging.StreamHandler", 36 | "level": "DEBUG", 37 | "formatter": "simple", 38 | "stream": "ext://sys.stdout" 39 | }, 40 | 41 | "info_file_handler": { 42 | "class": "logging.handlers.RotatingFileHandler", 43 | "level": "INFO", 44 | "formatter": "simple", 45 | "filename": "gee_assets_info.log", 46 | "maxBytes": 10485760, 47 | "backupCount": 20, 48 | "encoding": "utf8" 49 | }, 50 | 51 | "error_file_handler": { 52 | "class": "logging.handlers.RotatingFileHandler", 53 | "level": "ERROR", 54 | "formatter": "simple", 55 | "filename": "gee_assets_errors.log", 56 | "maxBytes": 10485760, 57 | "backupCount": 20, 58 | "encoding": "utf8" 59 | } 60 | }, 61 | 62 | "root": { 63 | "level": "INFO", 64 | "handlers": ["console", "info_file_handler", "error_file_handler"] 65 | } 66 | } 67 | 68 | def setup_logging(): 69 | path = os.path.join(os.path.dirname(__file__), 'logconfig.json') 70 | try: 71 | with open(path, 'rt') as f: 72 | config = json.load(f) 73 | except Exception as e: 74 | logging.exception('Could not load logconfig.json. Loading default logging configuration.') 75 | config = default_config 76 | logging.config.dictConfig(config) 77 | -------------------------------------------------------------------------------- /gee_asset_manager/logconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": 1, 3 | "disable_existing_loggers": false, 4 | "formatters": { 5 | "simple": { 6 | "format": "%(asctime)s :: %(name)s :: %(levelname)s :: %(message)s" 7 | } 8 | }, 9 | 10 | "handlers": { 11 | "console": { 12 | "class": "logging.StreamHandler", 13 | "level": "DEBUG", 14 | "formatter": "simple", 15 | "stream": "ext://sys.stdout" 16 | }, 17 | 18 | "info_file_handler": { 19 | "class": "logging.handlers.RotatingFileHandler", 20 | "level": "INFO", 21 | "formatter": "simple", 22 | "filename": "gee_assets_info.log", 23 | "maxBytes": 10485760, 24 | "backupCount": 20, 25 | "encoding": "utf8" 26 | }, 27 | 28 | "error_file_handler": { 29 | "class": "logging.handlers.RotatingFileHandler", 30 | "level": "ERROR", 31 | "formatter": "simple", 32 | "filename": "gee_assets_errors.log", 33 | "maxBytes": 10485760, 34 | "backupCount": 20, 35 | "encoding": "utf8" 36 | } 37 | }, 38 | 39 | "root": { 40 | "level": "INFO", 41 | "handlers": ["console", "info_file_handler", "error_file_handler"] 42 | } 43 | } -------------------------------------------------------------------------------- /gee_asset_manager/metadata_loader.py: -------------------------------------------------------------------------------- 1 | __copyright__ = """ 2 | 3 | Copyright 2016 Lukasz Tracewski 4 | 5 | Licensed under the Apache License, Version 2.0 (the "License"); 6 | you may not use this file except in compliance with the License. 7 | You may obtain a copy of the License at 8 | 9 | http://www.apache.org/licenses/LICENSE-2.0 10 | 11 | Unless required by applicable law or agreed to in writing, software 12 | distributed under the License is distributed on an "AS IS" BASIS, 13 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | See the License for the specific language governing permissions and 15 | limitations under the License. 16 | 17 | """ 18 | __license__ = "Apache 2.0" 19 | 20 | import ast 21 | import collections 22 | import csv 23 | import logging 24 | import re 25 | 26 | ValidationResult = collections.namedtuple('ValidationResult', ['success', 'keys']) 27 | 28 | 29 | class IllegalPropertyName(Exception): 30 | pass 31 | 32 | 33 | def validate_metadata_from_csv(path): 34 | """ 35 | Check if metadata is ok 36 | :param path: 37 | :return: true / false 38 | """ 39 | all_keys = [] 40 | 41 | with open(path, mode='r') as metadata_file: 42 | logging.info('Running metatdata validator for %s', path) 43 | success = True 44 | reader = csv.reader(metadata_file) 45 | header = next(reader) 46 | 47 | if not properties_allowed(properties=header, validator=allowed_property_key): 48 | raise IllegalPropertyName('The header has illegal name.') 49 | 50 | for row in reader: 51 | all_keys.append(row[0]) 52 | if not properties_allowed(properties=row, validator=allowed_property_value): 53 | success = False 54 | 55 | logging.info('Validation successful') if success else logging.error('Validation failed') 56 | 57 | return ValidationResult(success=success, keys=all_keys) 58 | 59 | 60 | def load_metadata_from_csv(path): 61 | """ 62 | Grabs properties from the give csv file. The csv should be organised as follows: 63 | filename (without extension), property1, property2, ... 64 | 65 | Example: 66 | id_no,class,category,binomial 67 | my_file_1,GASTROPODA,EN,Aaadonta constricta 68 | my_file_2,GASTROPODA,CR,Aaadonta irregularis 69 | 70 | The corresponding files are my_file_1.tif and my_file_2.tif. 71 | 72 | The program will turn the above into a json object: 73 | 74 | { id_no: my_file_1, class: GASTROPODA, category: EN, binomial: Aaadonta constricta}, 75 | { id_no: my_file_2, class: GASTROPODA, category: CR, binomial: Aaadonta irregularis} 76 | 77 | :param path to csv: 78 | :return: dictionary of dictionaries 79 | """ 80 | with open(path, mode='r') as metadata_file: 81 | reader = csv.reader(metadata_file) 82 | header = next(reader) 83 | 84 | if not properties_allowed(properties=header, validator=allowed_property_key): 85 | raise IllegalPropertyName() 86 | 87 | metadata = {} 88 | 89 | for row in reader: 90 | # if properties_allowed(properties=row, validator=allowed_property_value): 91 | values = [] 92 | for item in row: 93 | try: 94 | values.append(ast.literal_eval(item)) 95 | except (ValueError, SyntaxError) as e: 96 | values.append(item) 97 | metadata[row[0]] = dict(zip(header, values)) 98 | 99 | return metadata 100 | 101 | 102 | def properties_allowed(properties, validator): 103 | return all(validator(prop) for prop in properties) 104 | 105 | 106 | def allowed_property_key(prop): 107 | google_special_properties = ('system:description', 108 | 'system:provider_url', 109 | 'system:tags', 110 | 'system:time_end', 111 | 'system:time_start', 112 | 'system:title') 113 | 114 | if prop in google_special_properties or re.match("^[A-Za-z0-9_]+$", prop): 115 | return True 116 | else: 117 | logging.warning('Property name %s is invalid. Special properties [system:description, system:provider_url, ' 118 | 'system:tags, system:time_end, system:time_start, system:title] are allowed; other property ' 119 | 'keys must contain only letters, digits and underscores.') 120 | return False 121 | -------------------------------------------------------------------------------- /gee_asset_manager/session.py: -------------------------------------------------------------------------------- 1 | __copyright__ = """ 2 | 3 | Copyright 2019 Lukasz Tracewski 4 | 5 | Licensed under the Apache License, Version 2.0 (the "License"); 6 | you may not use this file except in compliance with the License. 7 | You may obtain a copy of the License at 8 | 9 | http://www.apache.org/licenses/LICENSE-2.0 10 | 11 | Unless required by applicable law or agreed to in writing, software 12 | distributed under the License is distributed on an "AS IS" BASIS, 13 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | See the License for the specific language governing permissions and 15 | limitations under the License. 16 | 17 | """ 18 | __license__ = "Apache 2.0" 19 | 20 | 21 | import time 22 | import logging 23 | import requests 24 | import chromedriver_binary 25 | from selenium import webdriver 26 | from selenium.webdriver.chrome.options import Options 27 | from selenium.webdriver.common.by import By 28 | from selenium.webdriver.support.ui import WebDriverWait 29 | from selenium.webdriver.support import expected_conditions as EC 30 | 31 | 32 | def get_google_session(url: str, account_name: str, password: str, browser: str, headless: bool) -> requests.session: 33 | """ 34 | Get Google session object. The function will use Selenium and selected web driver to login to the 35 | account and create a session object. 36 | :param url: address to use 37 | :param account_name: name of the account (user name) 38 | :param password: password for the account 39 | :param browser: which browser to use 40 | :param headless: run as headless 41 | :return: session object 42 | """ 43 | options = Options() 44 | if headless: 45 | options.add_argument('--headless') 46 | 47 | if browser == 'Chrome': 48 | driver = webdriver.Chrome(options=options) 49 | else: 50 | raise NotImplemented('{} browser is not implemented.'.format(browser)) 51 | 52 | try: 53 | driver.get(url) 54 | driver.implicitly_wait(4) 55 | if headless: 56 | logging.info('Running browser in headless mode') 57 | username_el = driver.find_element_by_xpath('//*[@id="Email"]') 58 | username_el.send_keys(account_name) 59 | driver.find_element_by_id("next").click() 60 | driver.implicitly_wait(4) 61 | password_el = driver.find_element_by_xpath('//*[@id="Passwd"]') 62 | password_el.send_keys(password) 63 | driver.find_element_by_id("signIn").click() 64 | else: 65 | logging.info('Running the browser in normal mode') 66 | username_el = driver.find_element_by_xpath('//*[@id="identifierId"]') 67 | username_el.send_keys(account_name) 68 | driver.find_element_by_id("identifierNext").click() 69 | driver.implicitly_wait(4) 70 | password_el = driver.find_element_by_name("password") 71 | password_el.send_keys(password) 72 | time.sleep(1) 73 | next_el = WebDriverWait(driver, 4).until( 74 | EC.element_to_be_clickable((By.ID, "passwordNext")) 75 | ) 76 | next_el.click() 77 | 78 | gee_code = WebDriverWait(driver, 100).until( 79 | EC.presence_of_element_located((By.XPATH, '//*[@id="logo"]/img')) 80 | ) 81 | 82 | session = _get_session(driver) 83 | finally: 84 | driver.close() 85 | logging.info('Browser closed.') 86 | return session 87 | 88 | 89 | def _get_session(driver): 90 | cookies = driver.get_cookies() 91 | session = requests.session() 92 | for cookie in cookies: 93 | session.cookies.set(cookie['name'], cookie['value']) 94 | return session 95 | 96 | -------------------------------------------------------------------------------- /geebam.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | 3 | __copyright__ = """ 4 | 5 | Copyright 2016 Lukasz Tracewski 6 | 7 | Licensed under the Apache License, Version 2.0 (the "License"); 8 | you may not use this file except in compliance with the License. 9 | You may obtain a copy of the License at 10 | 11 | http://www.apache.org/licenses/LICENSE-2.0 12 | 13 | Unless required by applicable law or agreed to in writing, software 14 | distributed under the License is distributed on an "AS IS" BASIS, 15 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | See the License for the specific language governing permissions and 17 | limitations under the License. 18 | 19 | """ 20 | __license__ = "Apache 2.0" 21 | 22 | import argparse 23 | import logging 24 | import os 25 | 26 | import ee 27 | 28 | from gee_asset_manager.batch_remover import delete 29 | from gee_asset_manager.batch_uploader import upload 30 | from gee_asset_manager.config import setup_logging 31 | from gee_asset_manager.batch_info import report 32 | from gee_asset_manager.batch_copy import copy 33 | 34 | 35 | def cancel_all_running_tasks(): 36 | logging.info('Attempting to cancel all running tasks') 37 | running_tasks = [task for task in ee.data.getTaskList() if task['state'] == 'RUNNING'] 38 | for task in running_tasks: 39 | ee.data.cancelTask(task['id']) 40 | logging.info('Cancel all request completed') 41 | 42 | 43 | def cancel_all_running_tasks_from_parser(args): 44 | cancel_all_running_tasks() 45 | 46 | 47 | def delete_collection_from_parser(args): 48 | delete(args.id) 49 | 50 | 51 | def produce_report(args): 52 | report(args.filename) 53 | 54 | 55 | def batch_copy(args): 56 | copy(args.source, args.dest) 57 | 58 | 59 | def upload_from_parser(args): 60 | upload(user=args.user, 61 | source_path=args.source, 62 | destination_path=args.dest, 63 | headless=args.headless, 64 | metadata_path=args.metadata, 65 | multipart_upload=args.large, 66 | nodata_value=args.nodata, 67 | bucket_name=args.bucket, 68 | band_names=args.bands, 69 | signal_if_error=args.upload_catch_error, 70 | tolerate_assets_already_exist=args.tolerate_assets_already_exist) 71 | 72 | 73 | def _comma_separated_strings(string): 74 | """Parses an input consisting of comma-separated strings. 75 | Slightly modified version of: https://pypkg.com/pypi/earthengine-api/f/ee/cli/commands.py 76 | """ 77 | error_msg = 'Argument should be a comma-separated list of alphanumeric strings (no spaces or other' \ 78 | 'special characters): {}' 79 | values = string.split(',') 80 | for name in values: 81 | if not name.isalnum(): 82 | raise argparse.ArgumentTypeError(error_msg.format(string)) 83 | return values 84 | 85 | 86 | 87 | def main(args=None): 88 | setup_logging() 89 | parser = argparse.ArgumentParser(description='Google Earth Engine Batch Asset Manager') 90 | parser.add_argument('-s', '--service-account', help='Google Earth Engine service account.', required=False) 91 | parser.add_argument('-k', '--private-key', help='Google Earth Engine private key file.', required=False) 92 | 93 | subparsers = parser.add_subparsers() 94 | parser_delete = subparsers.add_parser('delete', help='Deletes collection and all items inside. Supports Unix-like wildcards.') 95 | parser_delete.add_argument('id', help='Full path to asset for deletion. Recursively removes all folders, collections and images.') 96 | parser_delete.set_defaults(func=delete_collection_from_parser) 97 | 98 | parser_upload = subparsers.add_parser('upload', help='Batch Asset Uploader.') 99 | required_named = parser_upload.add_argument_group('Required named arguments.') 100 | required_named.add_argument('--source', help='Path to the directory with images for upload.', required=True) 101 | required_named.add_argument('--dest', help='Destination. Full path for upload to Google Earth Engine, e.g. users/pinkiepie/myponycollection', required=True) 102 | optional_named = parser_upload.add_argument_group('Optional named arguments') 103 | optional_named.add_argument('-m', '--metadata', help='Path to CSV with metadata.') 104 | optional_named.add_argument('--large', action='store_true', help='(Advanced) Use multipart upload. Might help if upload of large ' 105 | 'files is failing on some systems. Might cause other issues.') 106 | optional_named.add_argument('--nodata', type=int, help='The value to burn into the raster as NoData (missing data)') 107 | optional_named.add_argument('--bands', type=_comma_separated_strings, help='Comma-separated list of names to use for the image bands. Spaces' 108 | 'or other special characters are not allowed.') 109 | 110 | required_named.add_argument('-u', '--user', help='Google account name (gmail address).') 111 | optional_named.add_argument('-b', '--bucket', help='Google Cloud Storage bucket name.') 112 | optional_named.add_argument( 113 | '-e', 114 | '--upload-catch-error', 115 | action='store_true', 116 | help='Return exit code 1 when upload catches an error') 117 | optional_named.add_argument( 118 | '-a', 119 | '--tolerate-assets-already-exist', 120 | action='store_true', 121 | help='Return exit 0 when assets already exist') 122 | optional_named.add_argument('--headless', help='Run the browser in headless mode (i.e. no user interface).', action='store_true') 123 | 124 | parser_upload.set_defaults(func=upload_from_parser) 125 | 126 | parser_cancel = subparsers.add_parser('cancel', help='Cancel all running tasks') 127 | parser_cancel.set_defaults(func=cancel_all_running_tasks_from_parser) 128 | 129 | parser_info = subparsers.add_parser('report', help='Produce summary of all assets.') 130 | parser_info.set_defaults(func=produce_report) 131 | parser_info.add_argument('--filename', help='File name for the output CSV (optional)') 132 | 133 | parser_copy = subparsers.add_parser('copy', help='Batch copy of assets. Helps in migrating assets from Google Maps to GEE') 134 | parser_copy.set_defaults(func=batch_copy) 135 | parser_copy.add_argument('--source', help='File with the following structure: [asset name],[asset id in GME]') 136 | parser_copy.add_argument('--dest', help='Full path to the directory or collection in EE') 137 | 138 | args = parser.parse_args() 139 | 140 | if args.service_account: 141 | credentials = ee.ServiceAccountCredentials(args.service_account, args.private_key) 142 | ee.Initialize(credentials) 143 | else: 144 | ee.Initialize() 145 | 146 | if args.private_key is not None: 147 | os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = args.private_key 148 | 149 | if 'func' in args: 150 | args.func(args) 151 | else: 152 | parser.print_help() 153 | 154 | if __name__ == '__main__': 155 | main() -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | earthengine_api 2 | requests 3 | retrying 4 | beautifulsoup4 5 | requests_toolbelt 6 | pytest 7 | future 8 | google-cloud-storage 9 | chromedriver-binary 10 | selenium -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup 2 | 3 | def readme(): 4 | with open('README.md') as f: 5 | return f.read() 6 | 7 | def requirements(): 8 | with open('requirements.txt') as f: 9 | return f.read().splitlines() 10 | 11 | setup( 12 | name='geebam', 13 | version='0.1.5', 14 | packages=['gee_asset_manager'], 15 | package_data={'gee_asset_manager': ['logconfig.json']}, 16 | url='https://github.com/tracek/gee_asset_manager', 17 | license='Apache 2.0', 18 | classifiers=( 19 | 'Development Status :: 3 - Alpha', 20 | 'Intended Audience :: Developers', 21 | 'Intended Audience :: Science/Research', 22 | 'Natural Language :: English', 23 | 'License :: OSI Approved :: Apache Software License', 24 | 'Programming Language :: Python', 25 | 'Programming Language :: Python :: 2.7', 26 | 'Programming Language :: Python :: 3.5', 27 | 'Programming Language :: Python :: 3.6', 28 | 'Operating System :: OS Independent', 29 | 'Topic :: Scientific/Engineering :: GIS', 30 | ), 31 | author='Lukasz Tracewski', 32 | author_email='lukasz.tracewski@outlook.com', 33 | description='Google Earth Engine Batch Assets Manager', 34 | long_description=readme(), 35 | install_requires=requirements(), 36 | entry_points={ 37 | 'console_scripts': [ 38 | 'geebam=geebam:main', 39 | ], 40 | } 41 | ) 42 | -------------------------------------------------------------------------------- /tests/images/230.tif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tracek/gee_asset_manager/80ad23c669ebeb13bc836f9a6a2d088ec3b8a123/tests/images/230.tif -------------------------------------------------------------------------------- /tests/images/263.test.tif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tracek/gee_asset_manager/80ad23c669ebeb13bc836f9a6a2d088ec3b8a123/tests/images/263.test.tif -------------------------------------------------------------------------------- /tests/images/263.tif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tracek/gee_asset_manager/80ad23c669ebeb13bc836f9a6a2d088ec3b8a123/tests/images/263.tif -------------------------------------------------------------------------------- /tests/images/4.tif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tracek/gee_asset_manager/80ad23c669ebeb13bc836f9a6a2d088ec3b8a123/tests/images/4.tif -------------------------------------------------------------------------------- /tests/images/6.tif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tracek/gee_asset_manager/80ad23c669ebeb13bc836f9a6a2d088ec3b8a123/tests/images/6.tif -------------------------------------------------------------------------------- /tests/images/metadata.csv: -------------------------------------------------------------------------------- 1 | id_no,class,category,binomial,system:time_start 2 | 4,GASTROPODA,EN,Aaadonta constricta,1478640090000 3 | 6,GASTROPODA,CR,Aaadonta irregularis,1478640092000 4 | 8,GASTROPODA,CR,Aaadonta pelewana,1478620090000 5 | 16,MAMMALIA,LC,Abrawayaomys ruschii,1478640090000 6 | 18,MAMMALIA,CR,Abrocoma boliviensis,1478640090000 7 | 20,REPTILIA,EN,Abronia montecristoi,1478640090000 8 | 59,GASTROPODA,DD,Acanthinula spinifera,1478640090 9 | 81,ACTINOPTERYGII,VU,Salmo ohridanus,1478640090000 10 | 137,MAMMALIA,LC,Acerodon celebensis,1478640090000 11 | 142,MAMMALIA,VU,Acerodon mackloti,1478640090000 12 | 215,GASTROPODA,VU,Acicula norrisi,1478640090000 13 | 217,GASTROPODA,NT,Acicula hausdorfi,1478640090000 14 | 219,MAMMALIA,VU,Acinonyx jubatus,1478640090000 15 | 230,ACTINOPTERYGII,CR,Acipenser sturio,1478620559000 16 | 263,MAMMALIA,LC,Acomys cahirinus,1478640090000 17 | -------------------------------------------------------------------------------- /tests/test_session.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import ast 3 | import getpass 4 | from gee_asset_manager.session import get_google_session 5 | 6 | 7 | def test_interactive_session(): 8 | username = input('Account name: ') 9 | password = getpass.getpass() 10 | session = get_google_session(url='https://code.earthengine.google.com/', 11 | account_name=username, 12 | password=password, 13 | headless=False) 14 | r = session.get("https://code.earthengine.google.com/assets/upload/geturl") 15 | if r.text.startswith('\n'): 16 | output_filename = 'failed_session.html' 17 | print(f'FAILED. Returned object is an HTML document. Printing the content to {output_filename}') 18 | with open(output_filename, 'w') as f: 19 | f.writelines(r.text) 20 | sys.exit(1) 21 | else: 22 | d = ast.literal_eval(r.text) 23 | url = d['url'] 24 | print(f'SUCCESS! Our url: {url}') -------------------------------------------------------------------------------- /tests/test_upload.py: -------------------------------------------------------------------------------- 1 | import getpass 2 | import logging 3 | import os 4 | import random 5 | import string 6 | 7 | import ee 8 | import pytest 9 | from builtins import input 10 | 11 | from gee_asset_manager.batch_remover import delete 12 | from gee_asset_manager.batch_uploader import upload 13 | 14 | logging.basicConfig(level=logging.INFO) 15 | 16 | 17 | class memoize: 18 | def __init__(self, function): 19 | self.function = function 20 | self.memoized = {} 21 | 22 | def __call__(self, *args): 23 | try: 24 | return self.memoized[args] 25 | except KeyError: 26 | self.memoized[args] = self.function(*args) 27 | return self.memoized[args] 28 | 29 | 30 | def get_random_string(length): 31 | return ''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(length)) 32 | 33 | 34 | @memoize 35 | def mockreturn_pass(): 36 | return input("Password: ") 37 | 38 | 39 | @memoize 40 | def get_username(): 41 | return input("\nUser name: ") 42 | 43 | 44 | @pytest.fixture(scope='module') 45 | def setup_testfolder(): 46 | ee.Initialize() 47 | root = ee.data.getAssetRoots()[0]['id'] 48 | testfolder_name = root + '/test_geebam_' + get_random_string(8) 49 | ee.data.createAsset({'type': ee.data.ASSET_TYPE_FOLDER}, testfolder_name) 50 | logging.info('Setting up test folder %s', testfolder_name) 51 | return testfolder_name 52 | 53 | 54 | def test_upload_with_metadata(monkeypatch, setup_testfolder): 55 | logging.info('Upload test. WARNING. Requires user name and password, which will be passed in open text.') 56 | username = get_username() 57 | monkeypatch.setattr(getpass, 'getpass', mockreturn_pass) 58 | source = os.path.join(os.path.dirname(__file__), 'images') 59 | metadata = os.path.join(os.path.dirname(__file__), 'images', 'metadata.csv') 60 | dest = setup_testfolder + '/test_upload_with_metadata' 61 | multipart = False 62 | nodata = None 63 | logging.info('Testing upload with metadata') 64 | upload(user=username, source_path=source, destination_path=dest, metadata_path=metadata, multipart_upload=multipart, nodata_value=nodata) 65 | 66 | 67 | def test_upload_with_nodata_multipart(monkeypatch, setup_testfolder): 68 | username = get_username() 69 | monkeypatch.setattr(getpass, 'getpass', mockreturn_pass) 70 | source = os.path.join(os.path.dirname(__file__), 'images') 71 | dest = setup_testfolder + '/test_upload_with_nodata_multipart' 72 | multipart = True 73 | nodata = 42 74 | logging.info('Testing upload with nodata and multipart option') 75 | upload(user=username, source_path=source, destination_path=dest, multipart_upload=multipart, nodata_value=nodata) 76 | 77 | 78 | def test_delete(setup_testfolder): 79 | ee.data.createAsset({'type': ee.data.ASSET_TYPE_FOLDER}, setup_testfolder + '/one_more_to_delete') 80 | logging.info('Removing test directory') 81 | delete(setup_testfolder) 82 | info = ee.data.getInfo(setup_testfolder) 83 | assert info == None --------------------------------------------------------------------------------