├── .github ├── write-good.yml ├── ISSUE_TEMPLATE │ ├── custom.md │ ├── feature_request.md │ └── bug_report.md ├── stale.yml └── config.yml ├── jimutmap ├── .gitignore ├── __init__.py ├── file_size.py ├── tiles_sticher.py ├── sanity_checker.py ├── jimutmap.py └── jimutmap_1.py ├── requirements.txt ├── COPYING ├── .gitignore ├── CONTRIBUTORS.md ├── docs ├── source │ ├── LICENSE.rst │ ├── CONTRIBUTORS.rst │ ├── BUG_REPORTS.rst │ ├── REQUIREMENTS.rst │ ├── CONTRIBUTING.rst │ ├── DATASETS.rst │ ├── TODO.rst │ ├── PARAMETERS.rst │ ├── CODE_OF_CONDUCT.rst │ ├── conf.py │ └── INDEX.rst ├── Makefile └── make.bat ├── BUG_REPORTS.md ├── CONTRIBUTING.md ├── DATASETS.md ├── setup.py ├── CHANGELOG.md ├── TODO.md ├── test.py ├── CODE_OF_CONDUCT.md ├── README.md └── LICENSE /.github/write-good.yml: -------------------------------------------------------------------------------- 1 | writeGood: true 2 | alex: true 3 | spellchecker: true 4 | -------------------------------------------------------------------------------- /jimutmap/.gitignore: -------------------------------------------------------------------------------- 1 | # numbers are for selenium drivers, we should ignore them 2 | [0-9]* 3 | *.sqlite 4 | myOutputFolder 5 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | opencv-python 2 | certifi 3 | chardet 4 | chromedriver-autoinstaller 5 | idna 6 | numpy 7 | requests 8 | selenium 9 | tqdm 10 | urllib3 11 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/custom.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Custom issue template 3 | about: Describe this issue template's purpose here. 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | 11 | -------------------------------------------------------------------------------- /COPYING: -------------------------------------------------------------------------------- 1 | The jimutmap code is free software; 2 | you can redistribute it and/or modify 3 | it under the terms of the GNU General 4 | Public License as published by the Free 5 | Software Foundation; either version 3 of 6 | the License, or (at your option) any 7 | later version. 8 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # numbers are for selenium drivers, we should ignore them 2 | [0-9]* 3 | *.png 4 | myOutputFolder_zoom19 5 | *.sqlite 6 | .ipynb_checkpoints 7 | jimutmap/__pycache__ 8 | __pycache__ 9 | notebooks 10 | build 11 | dist 12 | myOutputFolder 13 | .zenodo.json 14 | jimutmap.egg-info 15 | 16 | -------------------------------------------------------------------------------- /CONTRIBUTORS.md: -------------------------------------------------------------------------------- 1 | # Here are the list of awesome contributors 2 | 3 | * Jimut Bahan Pal ([Jimut123](https://github.com/Jimut123)) 4 | * Philip Kahn ([tigerhawkvok](https://github.com/tigerhawkvok)) 5 | * Soumyadeep Sharma ([BeingSoumyadeepSharma](https://github.com/BeingSoumyadeepSharma)) 6 | * Krzysztof Sikorski ([krzychusikorski](https://github.com/krzychusikorski)) 7 | * Sourav Raj ([sourav-raj ](https://github.com/sourav-raj)) 8 | 9 | *** 10 | -------------------------------------------------------------------------------- /docs/source/LICENSE.rst: -------------------------------------------------------------------------------- 1 | LICENSE 2 | ======== 3 | 4 | GNU GENERAL PUBLIC LICENSE 5 | (Version 3, 29 June 2007) 6 | 7 | Copyright (C) 2019-21 `Jimut Bahan Pal `_. 8 | 9 | Everyone is permitted to copy and distribute verbatim copies 10 | of this license document, but changing it is not allowed. 11 | 12 | 13 | A copy of this license can be found `here `_. 14 | 15 | -------------------------------------------------------------------------------- /BUG_REPORTS.md: -------------------------------------------------------------------------------- 1 | # Major Bug Reports 2 | *** 3 | 4 | - [x] *01-04-2022* ***[Robin Cole](https://github.com/robmarkcole)*** - [Iterating over api results in no images downloaded, issue with multiprocessing](https://github.com/Jimut123/jimutmap/issues/16). Temporary fix - use threads=1, if files are not downloading as expected. 5 | - [x] *17-01-2023* ***[Sourav Raj](https://github.com/sourav-raj)*** - [ret_lat_lon function is not giving the correct result for given pixel and zoom](https://github.com/Jimut123/jimutmap/issues/22). 6 | 7 | -------------------------------------------------------------------------------- /docs/source/CONTRIBUTORS.rst: -------------------------------------------------------------------------------- 1 | Here are the list of awesome contributors 2 | ========================================= 3 | 4 | - Jimut Bahan Pal (`Jimut123 `__) 5 | - Philip Kahn (`tigerhawkvok `__) 6 | - Soumyadeep Sharma 7 | (`BeingSoumyadeepSharma `__) 8 | - Krzysztof Sikorski 9 | (`krzychusikorski `__) 10 | - Sourav Raj (`sourav-raj `__) 11 | 12 | -------------- 13 | -------------------------------------------------------------------------------- /docs/source/BUG_REPORTS.rst: -------------------------------------------------------------------------------- 1 | Major Bug Reports 2 | ================= 3 | 4 | -------------- 5 | 6 | - ☒ *01-04-2022* `Robin Cole `__ - 7 | `Iterating over api results in no images downloaded, issue with 8 | multiprocessing `__. 9 | Temporary fix - use threads=1, if files are not downloading as 10 | expected. 11 | - ☒ *17-01-2023* `Sourav Raj `__ - 12 | `ret_lat_lon function is not giving the correct result for given 13 | pixel and zoom `__. 14 | -------------------------------------------------------------------------------- /docs/Makefile: -------------------------------------------------------------------------------- 1 | # Minimal makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line. 5 | SPHINXOPTS = 6 | SPHINXBUILD = sphinx-build 7 | SPHINXPROJ = jimutmap 8 | SOURCEDIR = source 9 | BUILDDIR = build 10 | 11 | # Put it first so that "make" without argument is like "make help". 12 | help: 13 | @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) 14 | 15 | .PHONY: help Makefile 16 | 17 | # Catch-all target: route all unknown targets to Sphinx using the new 18 | # "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). 19 | %: Makefile 20 | @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Is your feature request related to a problem? Please describe.** 11 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] 12 | 13 | **Describe the solution you'd like** 14 | A clear and concise description of what you want to happen. 15 | 16 | **Describe alternatives you've considered** 17 | A clear and concise description of any alternative solutions or features you've considered. 18 | 19 | **Additional context** 20 | Add any other context or screenshots about the feature request here. 21 | -------------------------------------------------------------------------------- /docs/source/REQUIREMENTS.rst: -------------------------------------------------------------------------------- 1 | Requirements 2 | ============ 3 | 4 | * `certifi `_ 5 | * `chardet `_ 6 | * `chromedriver-autoinstaller `_ 7 | * `idna `_ 8 | * `numpy `_ 9 | * `requests `_ 10 | * `selenium `_ 11 | * `tqdm `_ 12 | * `urllib3 `_ 13 | 14 | 15 | The whole list of current requirements can be downloaded from 16 | `requirements.txt `_. -------------------------------------------------------------------------------- /.github/stale.yml: -------------------------------------------------------------------------------- 1 | # Number of days of inactivity before an issue becomes stale 2 | daysUntilStale: 60 3 | # Number of days of inactivity before a stale issue is closed 4 | daysUntilClose: 7 5 | # Issues with these labels will never be considered stale 6 | exemptLabels: 7 | - pinned 8 | - security 9 | # Label to use when marking an issue as stale 10 | staleLabel: wontfix 11 | # Comment to post when marking an issue as stale. Set to `false` to disable 12 | markComment: > 13 | This issue has been automatically marked as stale because it has not had 14 | recent activity. It will be closed if no further activity occurs. Thank you 15 | for your contributions. 16 | # Comment to post when closing a stale issue. Set to `false` to disable 17 | closeComment: false 18 | -------------------------------------------------------------------------------- /jimutmap/__init__.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | # ======================================================== 4 | # This package provides useful tools for data analysts 5 | # and geoscientists for free 6 | # OPEN SOURCED UNDER GPL-V3.0. 7 | # Author : Jimut Bahan Pal | jimutbahanpal@yahoo.com 8 | # Project Website: https://github.com/Jimut123/jimutmap 9 | # pylint: disable = global-statement 10 | # cSpell: words imghdr, tqdm, asinh, jimut, bahan 11 | # ======================================================== 12 | 13 | __name__ = "jimutmap" 14 | __version__ = "1.4.1" 15 | __author__ = "Jimut Bahan Pal | jimutbahanpal@yahoo.com" 16 | __release_date__ = '4-May-2019' 17 | from .jimutmap_1 import api 18 | from .file_size import get_folder_size 19 | from .sanity_checker import sanity_check 20 | from .tiles_sticher import update_stitcher_db, get_bbox_lat_lon, stitch_whole_tile 21 | -------------------------------------------------------------------------------- /docs/make.bat: -------------------------------------------------------------------------------- 1 | @ECHO OFF 2 | 3 | pushd %~dp0 4 | 5 | REM Command file for Sphinx documentation 6 | 7 | if "%SPHINXBUILD%" == "" ( 8 | set SPHINXBUILD=sphinx-build 9 | ) 10 | set SOURCEDIR=source 11 | set BUILDDIR=build 12 | set SPHINXPROJ=jimutmap 13 | 14 | if "%1" == "" goto help 15 | 16 | %SPHINXBUILD% >NUL 2>NUL 17 | if errorlevel 9009 ( 18 | echo. 19 | echo.The 'sphinx-build' command was not found. Make sure you have Sphinx 20 | echo.installed, then set the SPHINXBUILD environment variable to point 21 | echo.to the full path of the 'sphinx-build' executable. Alternatively you 22 | echo.may add the Sphinx directory to PATH. 23 | echo. 24 | echo.If you don't have Sphinx installed, grab it from 25 | echo.http://sphinx-doc.org/ 26 | exit /b 1 27 | ) 28 | 29 | %SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% 30 | goto end 31 | 32 | :help 33 | %SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% 34 | 35 | :end 36 | popd 37 | -------------------------------------------------------------------------------- /.github/config.yml: -------------------------------------------------------------------------------- 1 | # Configuration for welcome - https://github.com/behaviorbot/welcome 2 | 3 | # Configuration for new-issue-welcome - https://github.com/behaviorbot/new-issue-welcome 4 | 5 | # Comment to be posted to on first time issues 6 | newIssueWelcomeComment: > 7 | Thanks for opening your first issue here! Be sure to follow the issue template! 8 | 9 | # Configuration for new-pr-welcome - https://github.com/behaviorbot/new-pr-welcome 10 | 11 | # Comment to be posted to on PRs from first time contributors in your repository 12 | newPRWelcomeComment: > 13 | Thanks for opening this pull request! Please check out our contributing guidelines. 14 | 15 | # Configuration for first-pr-merge - https://github.com/behaviorbot/first-pr-merge 16 | 17 | # Comment to be posted to on pull requests merged by a first time user 18 | firstPRMergeComment: > 19 | Congrats on merging your first pull request! Check the CONTRIBUTORS list! 20 | 21 | # It is recommended to include as many gifs and emojis as possible! 22 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | 2 | Please feel free to raise issues and fix any existing ones. Further details can be found in our [code of conduct](https://github.com/Jimut123/jimutmap/blob/master/CODE_OF_CONDUCT.md). 3 | 4 | ### While making a PR, please make sure you: 5 | - [ ] Always start your PR description with "Fixes #issue_number", if you're fixing an issue. 6 | - [ ] Briefly mention the purpose of the PR, along with the tools/libraries you have used. It would be great if you could be version specific. 7 | - [ ] Briefly mention what logic you used to implement the changes/upgrades. 8 | - [ ] Provide in-code review comments on GitHub to highlight specific LOC if deemed necessary. 9 | - [ ] Please provide snapshots if deemed necessary. 10 | - [ ] Update readme if required. 11 | 12 | ### TODO 13 | 14 | There are various developments that needs to be done in this project. Please 15 | [check TODO](https://github.com/Jimut123/jimutmap/blob/master/TODO.md) if you are willing to contribute in 16 | this repository. 17 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Describe the bug** 11 | A clear and concise description of what the bug is. 12 | 13 | **To Reproduce** 14 | Steps to reproduce the behavior: 15 | 1. Go to '...' 16 | 2. Click on '....' 17 | 3. Scroll down to '....' 18 | 4. See error 19 | 20 | **Expected behavior** 21 | A clear and concise description of what you expected to happen. 22 | 23 | **Screenshots** 24 | If applicable, add screenshots to help explain your problem. 25 | 26 | **Desktop (please complete the following information):** 27 | - OS: [e.g. iOS] 28 | - Browser [e.g. chrome, safari] 29 | - Version [e.g. 22] 30 | 31 | **Smartphone (please complete the following information):** 32 | - Device: [e.g. iPhone6] 33 | - OS: [e.g. iOS8.1] 34 | - Browser [e.g. stock browser, safari] 35 | - Version [e.g. 22] 36 | 37 | **Additional context** 38 | Add any other context about the problem here. 39 | -------------------------------------------------------------------------------- /docs/source/CONTRIBUTING.rst: -------------------------------------------------------------------------------- 1 | Contributing 2 | ************ 3 | 4 | Please feel free to raise issues and fix any existing ones. Further details can be found in our 5 | `code of conduct `_. 6 | 7 | While making a PR 8 | --------------------------------------- 9 | please make sure you: 10 | 11 | - [ ] Always start your PR description with "Fixes #issue_number", if you're fixing an issue. 12 | - [ ] Briefly mention the purpose of the PR, along with the tools/libraries you have used. It would be great if you could be version specific. 13 | - [ ] Briefly mention what logic you used to implement the changes/upgrades. 14 | - [ ] Provide in-code review comments on GitHub to highlight specific LOC if deemed necessary. 15 | - [ ] Please provide snapshots if deemed necessary. 16 | - [ ] Update readme if required. 17 | 18 | TODO 19 | --------------------------------------- 20 | There are various developments that needs to be done in this project. Please 21 | `check TODO `_ if you are willing to contribute in 22 | this repository. 23 | -------------------------------------------------------------------------------- /DATASETS.md: -------------------------------------------------------------------------------- 1 | # Datasets available 2 | 3 | Here are some of the datasets available for ready usage. 4 | 5 | * [Kolkata region, East India](https://github.com/Jimut123/Kolkata_data_jimutmap) - This dataset contains tiles of zoom=19 from latitude 22.35 to 23.1 and longitude 88.0 to 88.6, which contains the major Kolkata area. Download the dataset to get image and road mask pairs. 6 | 7 | * [Delhi region, Central India](https://github.com/Jimut123/Delhi_data_jimutmap) - This dataset contains tiles of zoom=19 from latitude 28.4 to 28.8 and longitude 76.92 to 77.47, which contains the major Delhi area. Download the dataset to get image and road mask pairs. 8 | 9 | * [Chennai region, South India](https://github.com/Jimut123/Chennai_data_jimutmap) - This dataset contains tiles of zoom=19 from latitude 12.77 to 13.28 and longitude 80.10 to 80.35, which contains some part of the greater Chennai area. Download the dataset to get image and road mask pairs. 10 | 11 | * [Mumbai region, Mid-South-Western India](https://github.com/Jimut123/Mumbai_data_jimutmap) - This dataset contains tiles of zoom=19 from latitude 18.88 to 19.30 and longitude 72.75 to 73.14, which contains the major Mumbai area. Download the dataset to get image and road mask pairs. 12 | 13 | 14 | * [Egypt region, North-East Africa](https://github.com/Jimut123/Egypt_data_jimutmap) - This dataset contains tiles of zoom=19 from latitude 28.4 to 28.8 and longitude 28.33 to 29.03, which contains some part of the Egypt area. Download the dataset to get image and road mask pairs. 15 | 16 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | # ======================================================== 2 | # This program fetches tiles from satellites.pro for free. 3 | # OPEN SOURCED UNDER GPL-V3.0. 4 | # Author : Jimut Bahan Pal | jimutbahanpal@yahoo.com 5 | # Project Website: https://github.com/Jimut123/jimutmap 6 | # pylint: disable = global-statement 7 | # cSpell: words imghdr, tqdm, asinh, jimut, bahan 8 | # ======================================================== 9 | 10 | # https://packaging.python.org/en/latest/tutorials/packaging-projects/ 11 | 12 | import setuptools 13 | 14 | with open("README.md", "r") as fh: 15 | long_description = fh.read() 16 | 17 | setuptools.setup( 18 | name="jimutmap", 19 | version="1.4.2", 20 | author="Jimut Bahan Pal and the Jimutmap Contributors", 21 | author_email="jimutbahanpal@yahoo.com", 22 | description="To get enormous amount of map tiles with ease", 23 | long_description=long_description, 24 | long_description_content_type="text/markdown", 25 | url="https://github.com/Jimut123/jimutmap", 26 | install_requires=['certifi==2020.12.5','chardet==4.0.0','chromedriver-autoinstaller==0.2.2','idna==2.10', 27 | 'numpy==1.19.5','requests==2.25.1','selenium==3.141.0','tqdm==4.53.0','urllib3==1.26.5', 28 | 'opencv-python==4.5.5.64'], 29 | packages=setuptools.find_packages(), 30 | classifiers=[ 31 | "Programming Language :: Python :: 3", 32 | "License :: OSI Approved :: MIT License", 33 | "Operating System :: OS Independent", 34 | ], 35 | ) 36 | 37 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog for project jimutmap : maps data API 2 | 3 | All notable changes to this project will be documented in this file. 4 | 5 | The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), 6 | and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). 7 | 8 | ## [Future Plans] 9 | 10 | - More planned - check [TODO](https://github.com/Jimut123/jimutmap/blob/master/TODO.md). 11 | 12 | ## [Unreleased] 13 | 14 | - All feature branch shall be here, which are not yet merged to master 15 | 16 | 17 | ## [1.4.1] - 2022-04-06 18 | 19 | ### Added 20 | - pip 1.4.1 21 | - tiles_sticher.py - to stich tiles that are downloaded in the folder 22 | 23 | 24 | ### Modified 25 | - jimutmap.py - updated the bug, now downloads road tiles with ease 26 | 27 | ## [1.4.0] - 2022-04-04 28 | 29 | ### Added 30 | - pip 1.4.0 31 | - file_size.py - to calculate file/directory size passed to it 32 | - sanity_checker.py - to index all the expected data and to make sure to fetch them via retries. 33 | 34 | ### Modified 35 | - jimutmap.py 36 | 37 | ### Removed 38 | - unnecessary files 39 | 40 | 41 | ## [1.3.9] - 2022-04-29 42 | 43 | ### Added 44 | - pip 1.3.9 45 | - docs - documentation added 46 | 47 | ### Modified 48 | 49 | ### Removed 50 | 51 | 52 | ## [1.3.8] - 2021-02-25 53 | 54 | ### Added 55 | - pip 1.3.8 56 | - major refactoring by Philip Kahn 57 | 58 | ### Modified 59 | - jimutmap.py 60 | 61 | ### Removed 62 | - unnecessary files 63 | 64 | ## [1.2.1] - 2019-05-04 65 | 66 | ### Added 67 | - pip version 1.2.1 68 | 69 | ## [0.0.0] - 2019-02-05 70 | 71 | ### Added 72 | - jimutmap.py 73 | -------------------------------------------------------------------------------- /docs/source/DATASETS.rst: -------------------------------------------------------------------------------- 1 | Datasets available 2 | ================== 3 | 4 | Here are some of the datasets available for ready usage. 5 | 6 | - `Kolkata region, East 7 | India `__ - This 8 | dataset contains tiles of zoom=19 from latitude 22.35 to 23.1 and 9 | longitude 88.0 to 88.6, which contains the major Kolkata area. 10 | Download the dataset to get image and road mask pairs. 11 | 12 | - `Delhi region, Central 13 | India `__ - This 14 | dataset contains tiles of zoom=19 from latitude 28.4 to 28.8 and 15 | longitude 76.92 to 77.47, which contains the major Delhi area. 16 | Download the dataset to get image and road mask pairs. 17 | 18 | - `Chennai region, South 19 | India `__ - This 20 | dataset contains tiles of zoom=19 from latitude 12.77 to 13.28 and 21 | longitude 80.10 to 80.35, which contains some part of the greater 22 | Chennai area. Download the dataset to get image and road mask pairs. 23 | 24 | - `Mumbai region, Mid-South-Western 25 | India `__ - This 26 | dataset contains tiles of zoom=19 from latitude 18.88 to 19.30 and 27 | longitude 72.75 to 73.14, which contains the major Mumbai area. 28 | Download the dataset to get image and road mask pairs. 29 | 30 | - `Egypt region, North-East 31 | Africa `__ - This 32 | dataset contains tiles of zoom=19 from latitude 28.4 to 28.8 and 33 | longitude 28.33 to 29.03, which contains some part of the Egypt area. 34 | Download the dataset to get image and road mask pairs. 35 | -------------------------------------------------------------------------------- /TODO.md: -------------------------------------------------------------------------------- 1 | #### Here are the list of todos **(Open an issue if you want to contribute!)**: 2 | 3 | 4 | - [ ] Stitch tiles by specifying length and breadth of tiles. 5 | - [ ] Get roads route in json format from specified latitude longitudes, this can help the data scientists to create optimal routes from point A to B. 6 | - [ ] Convert all the class of objects present in the map to JSON data via image processing, which can help the geoscientists to process information at a large scale. 7 | - [ ] Find all the unique items that can be present in the map. (Like caffe icon, shop icon, temple icon etc.) 8 | - [ ] Fetch all the necessary objects (shops/caffe etc.) that are queried to in a certain radius of coordinate. 9 | - [ ] Probably use other 3D data to create 3D world from satellite 2D imagery. 10 | - [ ] Create a conda package 11 | 12 | #### Done 13 | 14 | - [x] Generate a high resolution map by assembling tiles, similar to [label-maker](https://github.com/developmentseed/label-maker). 15 | - [x] Probably make a documentation website similar to 16 | - [ ] [GPy](https://gpy.readthedocs.io) 17 | - [x] [requests](https://requests.readthedocs.io) -- with Sphinx theme 18 | - [ ] [AX](https://ax.dev/) 19 | 20 | 21 | ------------------------------------------------------------------------------ 22 | 23 | Note: 24 | 25 | * Probably create a separate module for all these stuffs 26 | 27 | * Also create a separate branch like **feature-name** for each feature, and then after all the tests 28 | and stuffs, merge them to master branch. 29 | 30 | * Maintain the [CHANGELOG.md](https://github.com/Jimut123/jimutmap/blob/master/CHANGELOG.md) in a detailed way from now onwards (Only add significant changes after deploying to master) 31 | 32 | * After a feature is deployed to master, [x] it here. 33 | 34 | * Master should always contain production-ready code for deployment to pip and conda 35 | -------------------------------------------------------------------------------- /docs/source/TODO.rst: -------------------------------------------------------------------------------- 1 | Here are the list of todos **(Open an issue if you want to contribute!)**: 2 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 3 | 4 | - ☐ Stitch tiles by specifying length and breadth of tiles. 5 | - ☐ Get roads route in json format from specified latitude longitudes, 6 | this can help the data scientists to create optimal routes from point 7 | A to B. 8 | - ☐ Convert all the class of objects present in the map to JSON data 9 | via image processing, which can help the geoscientists to process 10 | information at a large scale. 11 | - ☐ Find all the unique items that can be present in the map. (Like 12 | caffe icon, shop icon, temple icon etc.) 13 | - ☐ Fetch all the necessary objects (shops/caffe etc.) that are queried 14 | to in a certain radius of coordinate. 15 | - ☐ Probably use other 3D data to create 3D world from satellite 2D 16 | imagery. 17 | - ☐ Create a conda package 18 | 19 | Done 20 | ^^^^ 21 | 22 | - ☒ Generate a high resolution map by assembling tiles, similar to 23 | `label-maker `__. 24 | - ☒ Probably make a documentation website similar to 25 | 26 | - ☐ `GPy `__ 27 | - ☒ `requests `__ – with Sphinx 28 | theme 29 | - ☐ `AX `__ 30 | 31 | -------------- 32 | 33 | Note: 34 | 35 | - Probably create a separate module for all these stuffs 36 | 37 | - Also create a separate branch like **feature-name** for each feature, 38 | and then after all the tests and stuffs, merge them to master branch. 39 | 40 | - Maintain the 41 | `CHANGELOG.md `__ 42 | in a detailed way from now onwards (Only add significant changes 43 | after deploying to master) 44 | 45 | - After a feature is deployed to master, [x] it here. 46 | 47 | - Master should always contain production-ready code for deployment to 48 | pip and conda 49 | -------------------------------------------------------------------------------- /docs/source/PARAMETERS.rst: -------------------------------------------------------------------------------- 1 | Parameters 2 | ========== 3 | 4 | Here is the full list of configuration parameters you can specify when calling **api** function 5 | 6 | 7 | **min_lat_deg**: float 8 | This is the minimum latitude degree that is passed to the function to capture the tiles. This may also be considered as the left boundary of the bounding box from where the scraping of tiles will start in the apple maps. 9 | 10 | **max_lat_deg**: string 11 | This is the maximum latitude degree that is passed to the function to capture the tiles. This may also be considered as the right boundary of the bounding box from where the scraping of tiles will start in the apple maps. 12 | 13 | **min_lon_deg**: string 14 | This is the minimum longitude degree that is passed to the function to capture the tiles. This may also be considered as the bottom boundary of the bounding box from where the scraping of tiles will start in the apple maps. 15 | 16 | **max_lon_deg**: string 17 | This is the maximum longitude degree that is passed to the function to capture the tiles. This may also be considered as the top boundary of the bounding box from where the scraping of tiles will start in the apple maps. 18 | 19 | **zoom**: string 20 | This is the zoom value given to the map to get the arial imagery, i.e., max = 19 (zoomed in) and min = 0 (zoomed out). 21 | 22 | **verbose**: boolean 23 | This is the output that is displayed on the screen when the process is executing. This helps to keep a faith in the program by tracking the current execution. 24 | 25 | **threads_**: integer 26 | Set according to the number of cores present in your current CPU. Recommended value is **4**. The more the value, the more the pressure on the CPU. 27 | 28 | **container_dir**: string 29 | The container directory where the maps and the corresponding mask tiles will be stored. 30 | 31 | 32 | 33 | 34 | Here is the full list of configuration parameters you can specify when calling **download()** function 35 | 36 | **getMasks**: boolean 37 | We set it to either **True** or **False** for either downloading or not downloading corresponding road mask titles, of the same zoom value. 38 | 39 | 40 | -------------------------------------------------------------------------------- /jimutmap/file_size.py: -------------------------------------------------------------------------------- 1 | # ====================================================== 2 | # This program returns the size of folders/files. 3 | # OPEN SOURCED UNDER GPL-V3.0. 4 | # Author : Jimut Bahan Pal | jimutbahanpal@yahoo.com 5 | # Project Website: https://github.com/Jimut123/jimutmap 6 | # ====================================================== 7 | 8 | # https://stackoverflow.com/questions/1392413/calculating-a-directorys-size-using-python 9 | 10 | from pathlib import Path 11 | 12 | 13 | def get_folder_size(folder): 14 | return ByteSize(sum(file.stat().st_size for file in Path(folder).rglob('*'))) 15 | 16 | 17 | class ByteSize(int): 18 | 19 | _kB = 1024 20 | _suffixes = 'B', 'kB', 'MB', 'GB', 'PB' 21 | 22 | def __new__(cls, *args, **kwargs): 23 | return super().__new__(cls, *args, **kwargs) 24 | 25 | def __init__(self, *args, **kwargs): 26 | self.bytes = self.B = int(self) 27 | self.kilobytes = self.kB = self / self._kB**1 28 | self.megabytes = self.MB = self / self._kB**2 29 | self.gigabytes = self.GB = self / self._kB**3 30 | self.petabytes = self.PB = self / self._kB**4 31 | *suffixes, last = self._suffixes 32 | suffix = next(( 33 | suffix 34 | for suffix in suffixes 35 | if 1 < getattr(self, suffix) < self._kB 36 | ), last) 37 | self.readable = suffix, getattr(self, suffix) 38 | 39 | super().__init__() 40 | 41 | def __str__(self): 42 | return self.__format__('.2f') 43 | 44 | def __repr__(self): 45 | return '{}({})'.format(self.__class__.__name__, super().__repr__()) 46 | 47 | def __format__(self, format_spec): 48 | suffix, val = self.readable 49 | return '{val:{fmt}} {suf}'.format(val=val, fmt=format_spec, suf=suffix) 50 | 51 | def __sub__(self, other): 52 | return self.__class__(super().__sub__(other)) 53 | 54 | def __add__(self, other): 55 | return self.__class__(super().__add__(other)) 56 | 57 | def __mul__(self, other): 58 | return self.__class__(super().__mul__(other)) 59 | 60 | def __rsub__(self, other): 61 | return self.__class__(super().__sub__(other)) 62 | 63 | def __radd__(self, other): 64 | return self.__class__(super().__add__(other)) 65 | 66 | def __rmul__(self, other): 67 | return self.__class__(super().__rmul__(other)) 68 | 69 | 70 | if __name__ == "__main__": 71 | 72 | size = get_folder_size("myOutputFolder") 73 | # print(size) 74 | # print(size.GB) 75 | # print(size.gigabytes) 76 | # print(size.PB) 77 | # print(size.MB) 78 | print(size.B) 79 | -------------------------------------------------------------------------------- /test.py: -------------------------------------------------------------------------------- 1 | 2 | # ====================================================== 3 | # This tests the working of jimutmap package. 4 | # Note this doesnot uses multi-processing 5 | # OPEN SOURCED UNDER GPL-V3.0. 6 | # Author : Jimut Bahan Pal | jimutbahanpal@yahoo.com 7 | # Project Website: https://github.com/Jimut123/jimutmap 8 | # ====================================================== 9 | 10 | # Using map tiles for Kolkata, Baranagar my hometown: 22.645899,88.373889,19 11 | 12 | import os 13 | import glob 14 | import shutil 15 | from jimutmap import api, sanity_check, stitch_whole_tile 16 | 17 | 18 | download_obj = api(min_lat_deg = 22.64, 19 | max_lat_deg = 22.65, 20 | min_lon_deg = 88.37, 21 | max_lon_deg = 88.38, 22 | zoom = 19, 23 | verbose = False, 24 | threads_ = 50, 25 | container_dir = "myOutputFolder") 26 | 27 | # If you don't have Chrome and can't take advantage of the auto access key fetch, set 28 | # a.ac_key = ACCESS_KEY_STRING 29 | # here 30 | 31 | # getMasks = False if you just need the tiles 32 | download_obj.download(getMasks = True) 33 | 34 | # create the object of class jimutmap's api 35 | sanity_obj = api(min_lat_deg = 22.64, 36 | max_lat_deg = 22.65, 37 | min_lon_deg = 88.37, 38 | max_lon_deg = 88.38, 39 | zoom = 19, 40 | verbose = False, 41 | threads_ = 50, 42 | container_dir = "myOutputFolder") 43 | 44 | sanity_check(min_lat_deg = 22.64, 45 | max_lat_deg = 22.65, 46 | min_lon_deg = 88.37, 47 | max_lon_deg = 88.38, 48 | zoom = 19, 49 | verbose = False, 50 | threads_ = 50, 51 | container_dir = "myOutputFolder") 52 | 53 | print("Cleaning up... hold on") 54 | 55 | sqlite_temp_files = glob.glob('*.sqlite*') 56 | 57 | 58 | 59 | # update_stitcher_db("myOutputFolder") 60 | # get_bbox_lat_lon() 61 | stitch_whole_tile(save_name="Kolkata", folder_name="myOutputFolder") 62 | 63 | 64 | print("Temporary sqlite files to be deleted = {} ? ".format(sqlite_temp_files)) 65 | inp = input("(y/N) : ") 66 | if inp == 'y' or inp == 'yes' or inp == 'Y': 67 | for item in sqlite_temp_files: 68 | os.remove(item) 69 | 70 | 71 | 72 | ## Try to remove tree; if failed show an error using try...except on screen 73 | try: 74 | chromdriver_folders = glob.glob('[0-9]*') 75 | print("Temporary chromedriver folders to be deleted = {} ? ".format(chromdriver_folders)) 76 | inp = input("(y/N) : ") 77 | if inp == 'y' or inp == 'yes' or inp == 'Y': 78 | for item in chromdriver_folders: 79 | shutil.rmtree(item) 80 | except OSError as e: 81 | print ("Error: %s - %s." % (e.filename, e.strerror)) 82 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as 6 | contributors and maintainers pledge to making participation in our project and 7 | our community a harassment-free experience for everyone, regardless of age, body 8 | size, disability, ethnicity, sex characteristics, gender identity and expression, 9 | level of experience, education, socio-economic status, nationality, personal 10 | appearance, race, religion, or sexual identity and orientation. 11 | 12 | ## Our Standards 13 | 14 | Examples of behavior that contributes to creating a positive environment 15 | include: 16 | 17 | * Using welcoming and inclusive language 18 | * Being respectful of differing viewpoints and experiences 19 | * Gracefully accepting constructive criticism 20 | * Focusing on what is best for the community 21 | * Showing empathy towards other community members 22 | 23 | Examples of unacceptable behavior by participants include: 24 | 25 | * The use of sexualized language or imagery and unwelcome sexual attention or 26 | advances 27 | * Trolling, insulting/derogatory comments, and personal or political attacks 28 | * Public or private harassment 29 | * Publishing others' private information, such as a physical or electronic 30 | address, without explicit permission 31 | * Other conduct which could reasonably be considered inappropriate in a 32 | professional setting 33 | 34 | ## Our Responsibilities 35 | 36 | Project maintainers are responsible for clarifying the standards of acceptable 37 | behavior and are expected to take appropriate and fair corrective action in 38 | response to any instances of unacceptable behavior. 39 | 40 | Project maintainers have the right and responsibility to remove, edit, or 41 | reject comments, commits, code, wiki edits, issues, and other contributions 42 | that are not aligned to this Code of Conduct, or to ban temporarily or 43 | permanently any contributor for other behaviors that they deem inappropriate, 44 | threatening, offensive, or harmful. 45 | 46 | ## Scope 47 | 48 | This Code of Conduct applies both within project spaces and in public spaces 49 | when an individual is representing the project or its community. Examples of 50 | representing a project or community include using an official project e-mail 51 | address, posting via an official social media account, or acting as an appointed 52 | representative at an online or offline event. Representation of a project may be 53 | further defined and clarified by project maintainers. 54 | 55 | ## Enforcement 56 | 57 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 58 | reported by contacting the project team at jimutbahanpal@yahoo.com. All 59 | complaints will be reviewed and investigated and will result in a response that 60 | is deemed necessary and appropriate to the circumstances. The project team is 61 | obligated to maintain confidentiality with regard to the reporter of an incident. 62 | Further details of specific enforcement policies may be posted separately. 63 | 64 | Project maintainers who do not follow or enforce the Code of Conduct in good 65 | faith may face temporary or permanent repercussions as determined by other 66 | members of the project's leadership. 67 | 68 | ## Attribution 69 | 70 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, 71 | available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html 72 | 73 | [homepage]: https://www.contributor-covenant.org 74 | 75 | For answers to common questions about this code of conduct, see 76 | https://www.contributor-covenant.org/faq 77 | -------------------------------------------------------------------------------- /docs/source/CODE_OF_CONDUCT.rst: -------------------------------------------------------------------------------- 1 | Contributor Covenant Code of Conduct 2 | ==================================== 3 | 4 | Our Pledge 5 | ---------- 6 | 7 | In the interest of fostering an open and welcoming environment, we as 8 | contributors and maintainers pledge to making participation in our 9 | project and our community a harassment-free experience for everyone, 10 | regardless of age, body size, disability, ethnicity, sex 11 | characteristics, gender identity and expression, level of experience, 12 | education, socio-economic status, nationality, personal appearance, 13 | race, religion, or sexual identity and orientation. 14 | 15 | Our Standards 16 | ------------- 17 | 18 | Examples of behavior that contributes to creating a positive environment 19 | include: 20 | 21 | - Using welcoming and inclusive language 22 | - Being respectful of differing viewpoints and experiences 23 | - Gracefully accepting constructive criticism 24 | - Focusing on what is best for the community 25 | - Showing empathy towards other community members 26 | 27 | Examples of unacceptable behavior by participants include: 28 | 29 | - The use of sexualized language or imagery and unwelcome sexual 30 | attention or advances 31 | - Trolling, insulting/derogatory comments, and personal or political 32 | attacks 33 | - Public or private harassment 34 | - Publishing others’ private information, such as a physical or 35 | electronic address, without explicit permission 36 | - Other conduct which could reasonably be considered inappropriate in a 37 | professional setting 38 | 39 | Our Responsibilities 40 | -------------------- 41 | 42 | Project maintainers are responsible for clarifying the standards of 43 | acceptable behavior and are expected to take appropriate and fair 44 | corrective action in response to any instances of unacceptable behavior. 45 | 46 | Project maintainers have the right and responsibility to remove, edit, 47 | or reject comments, commits, code, wiki edits, issues, and other 48 | contributions that are not aligned to this Code of Conduct, or to ban 49 | temporarily or permanently any contributor for other behaviors that they 50 | deem inappropriate, threatening, offensive, or harmful. 51 | 52 | Scope 53 | ----- 54 | 55 | This Code of Conduct applies both within project spaces and in public 56 | spaces when an individual is representing the project or its community. 57 | Examples of representing a project or community include using an 58 | official project e-mail address, posting via an official social media 59 | account, or acting as an appointed representative at an online or 60 | offline event. Representation of a project may be further defined and 61 | clarified by project maintainers. 62 | 63 | Enforcement 64 | ----------- 65 | 66 | Instances of abusive, harassing, or otherwise unacceptable behavior may 67 | be reported by contacting the project team at jimutbahanpal@yahoo.com. 68 | All complaints will be reviewed and investigated and will result in a 69 | response that is deemed necessary and appropriate to the circumstances. 70 | The project team is obligated to maintain confidentiality with regard to 71 | the reporter of an incident. Further details of specific enforcement 72 | policies may be posted separately. 73 | 74 | Project maintainers who do not follow or enforce the Code of Conduct in 75 | good faith may face temporary or permanent repercussions as determined 76 | by other members of the project’s leadership. 77 | 78 | Attribution 79 | ----------- 80 | 81 | This Code of Conduct is adapted from the `Contributor 82 | Covenant `__, version 1.4, 83 | available at 84 | https://www.contributor-covenant.org/version/1/4/code-of-conduct.html 85 | 86 | For answers to common questions about this code of conduct, see 87 | https://www.contributor-covenant.org/faq 88 | -------------------------------------------------------------------------------- /jimutmap/tiles_sticher.py: -------------------------------------------------------------------------------- 1 | 2 | # ====================================================== 3 | # This program stitches tiles fetched by jimutmap. 4 | # Note this doesnot uses multi-processing 5 | # OPEN SOURCED UNDER GPL-V3.0. 6 | # Author : Jimut Bahan Pal | jimutbahanpal@yahoo.com 7 | # Project Website: https://github.com/Jimut123/jimutmap 8 | # ====================================================== 9 | 10 | import cv2 11 | import ssl 12 | import os 13 | import time 14 | import math 15 | import glob 16 | import imghdr 17 | import requests 18 | import sqlite3 19 | import numpy as np 20 | import datetime as dt 21 | from tqdm import tqdm 22 | import multiprocessing 23 | from jimutmap_1 import api 24 | from typing import Tuple 25 | from selenium import webdriver 26 | import chromedriver_autoinstaller 27 | from multiprocessing.pool import ThreadPool 28 | from os.path import join, exists, normpath, relpath 29 | 30 | 31 | def update_stitcher_db(folder_name = "myOutputFolder"): 32 | # this function stiches the whole folder passed to it 33 | 34 | # to take the files present in the folder and update all the entries of the 35 | # sticher database 36 | 37 | # Create table sticher with the coordinates, and the corresponding 38 | # satellite tile and the road tile, id as the primary key xTile_yTile 39 | 40 | cur.execute('''CREATE TABLE IF NOT EXISTS sticher 41 | (id TEXT primary key, xTile INTEGER, yTile INTEGER, satellite_tile INTEGER, road_tile INTEGER )''') 42 | 43 | print("Updating sticher db ...") 44 | 45 | all_files_folder = glob.glob('{}/*'.format(folder_name)) 46 | for tile_name in tqdm(all_files_folder): 47 | if tile_name.count('_') == 1: 48 | # then it is a satellite imagery 49 | xTile_val = str(tile_name.split('_')[0]).split('/')[-1] 50 | yTile_val = str(tile_name.split('_')[-1]).split('.')[0] 51 | create_id = str(xTile_val)+"_"+str(yTile_val) 52 | # print(create_id) 53 | 54 | # create the primary key for tracking values 55 | key_id = str(xTile_val)+"_"+str(yTile_val) 56 | # write the query 57 | query_insert = "INSERT OR IGNORE INTO sticher VALUES ('{}','{}','{}','{}','{}')".format(key_id,xTile_val, yTile_val, 0, 0) 58 | # Insert a row of records 59 | cur.execute(query_insert) 60 | cur.execute('''UPDATE sticher SET satellite_tile = 1 WHERE id = ?''',(str(create_id),)) # set the satellite_tile to 1 61 | 62 | if tile_name.count('_') == 2: 63 | # then it is a road mask 64 | xTile_val = str(tile_name.split('_')[0]).split('/')[-1] 65 | yTile_val = str(tile_name.split('_')[-2]) 66 | 67 | # create the primary key for tracking values 68 | key_id = str(xTile_val)+"_"+str(yTile_val) 69 | # write the query 70 | query_insert = "INSERT OR IGNORE INTO sticher VALUES ('{}','{}','{}','{}','{}')".format(key_id,xTile_val, yTile_val, 0, 0) 71 | # Insert a row of records 72 | cur.execute(query_insert) 73 | 74 | create_id = str(xTile_val)+"_"+str(yTile_val) 75 | # print(create_id) 76 | cur.execute('''UPDATE sticher SET road_tile = 1 WHERE id = ?''',(str(create_id),)) # set the road_tile to 1 77 | con.commit() 78 | 79 | get_sat_0s = cur.execute(''' SELECT * FROM sticher WHERE satellite_tile = 0 ''') 80 | get_sat_0s_val = cur.fetchall() #converts the cursor object to number 81 | total_number_of_sat0s = len(get_sat_0s_val) 82 | print("Total number of satellite images needed to be downloaded = ", total_number_of_sat0s) 83 | 84 | get_road_0s = cur.execute(''' SELECT * FROM sticher WHERE road_tile = 0 ''') 85 | get_road_0s_val = cur.fetchall() #converts the cursor object to number 86 | total_number_of_road0s = len(get_road_0s_val) 87 | print("Total number of satellite images needed to be downloaded = ", total_number_of_road0s) 88 | 89 | # in case if all the files are not present in the database then we need to exit from the program 90 | if total_number_of_sat0s > 0 or total_number_of_road0s > 0: 91 | print("Please download all the tiles properly for this purpose, some tiles may be missing...") 92 | print("Exiting...") 93 | exit() 94 | 95 | 96 | 97 | def get_bbox_lat_lon(): 98 | # this function obtains the maximum, minimum latitudes and longitudes present in the database 99 | print("Calculating bounding boxes for tiles :: ") 100 | get_all_data = cur.execute(''' SELECT * FROM sticher ''') 101 | get_all_data_vals = cur.fetchall() #converts the cursor object to number 102 | total_number_of_data = len(get_all_data_vals) 103 | print("Total number of rows present in the database= ", total_number_of_data) 104 | 105 | get_lat_list = [] 106 | get_lon_list = [] 107 | for item in tqdm(get_all_data_vals): 108 | get_lat_list.append(item[1]) 109 | get_lon_list.append(item[2]) 110 | 111 | min_lat = min(get_lat_list) 112 | max_lat = max(get_lat_list) 113 | 114 | min_lon = min(get_lon_list) 115 | max_lon = max(get_lon_list) 116 | 117 | print("Min lat tile = {}, Max lat tile = {}, Min lon tile = {}, Max lon tile = {}".format(min_lat, max_lat, min_lon, max_lon)) 118 | 119 | return [min_lat, max_lat, min_lon, max_lon] 120 | 121 | 122 | def stitch_whole_tile(save_name="full_tile", folder_name="myOutputFolder"): 123 | # This function stitches the whole tile and saves in _sat.png and _road.png 124 | # firstly update the stitcher databse 125 | update_stitcher_db(folder_name="myOutputFolder") 126 | 127 | # get the bounding box 128 | min_lat, max_lat, min_lon, max_lon = get_bbox_lat_lon() 129 | 130 | diff_lat = max_lat - min_lat 131 | diff_lon = max_lon - min_lon 132 | 133 | print("No. of tiles in latitude = {}, and longitude = {}".format(diff_lat, diff_lon)) 134 | 135 | print("Creating an image of size : {}x{} pixels ...".format(diff_lat*256,diff_lon*256)) 136 | 137 | # stich the satellite imagery tile 138 | 139 | SAT_TILE_FULL = np.zeros([diff_lon*256,diff_lat*256,3]) 140 | 141 | for lat in tqdm(range(min_lat, max_lat)): 142 | for lon in range(min_lon, max_lon): 143 | # stich the tiles together 144 | img_name = folder_name+"/"+str(lat)+"_"+str(lon)+".jpg" 145 | sat_img = cv2.imread(img_name) 146 | # print(sat_img.shape) 147 | x_1 = int(256*(lat-min_lat+1))-256 148 | x_2 = int(256*(lat-min_lat+1)) 149 | 150 | y_1 = int(256*(lon-min_lon+1)-256) 151 | y_2 = int(256*(lon-min_lon+1)) 152 | # print(x_1," ",x_2," ",y_1," ",y_2) 153 | SAT_TILE_FULL[y_1:y_2, x_1:x_2] = sat_img 154 | 155 | sat_save_name = save_name+"_sat.png" 156 | cv2.imwrite(sat_save_name,SAT_TILE_FULL) 157 | 158 | # stich the road imagery tile 159 | 160 | ROAD_TILE_FULL = np.zeros([diff_lon*256,diff_lat*256,3]) 161 | 162 | for lat in tqdm(range(min_lat, max_lat)): 163 | for lon in range(min_lon, max_lon): 164 | # stich the tiles together 165 | img_name = folder_name+"/"+str(lat)+"_"+str(lon)+"_road.png" 166 | sat_img = cv2.imread(img_name) 167 | # print(sat_img.shape) 168 | x_1 = int(256*(lat-min_lat+1))-256 169 | x_2 = int(256*(lat-min_lat+1)) 170 | 171 | y_1 = int(256*(lon-min_lon+1)-256) 172 | y_2 = int(256*(lon-min_lon+1)) 173 | # print(x_1," ",x_2," ",y_1," ",y_2) 174 | ROAD_TILE_FULL[y_1:y_2, x_1:x_2] = sat_img 175 | 176 | sat_save_name = save_name+"_road.png" 177 | cv2.imwrite(sat_save_name,ROAD_TILE_FULL) 178 | 179 | 180 | 181 | 182 | 183 | 184 | 185 | # connect to the temporary database that we shall use 186 | con = sqlite3.connect('sticher.sqlite') 187 | cur = con.cursor() 188 | 189 | if __name__ == "__main__": 190 | # use main function for proper structuing of code 191 | update_stitcher_db("myOutputFolder") -------------------------------------------------------------------------------- /docs/source/conf.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # Configuration file for the Sphinx documentation builder. 4 | # 5 | # This file does only contain a selection of the most common options. For a 6 | # full list see the documentation: 7 | # http://www.sphinx-doc.org/en/master/config 8 | 9 | # -- Path setup -------------------------------------------------------------- 10 | 11 | # If extensions (or modules to document with autodoc) are in another directory, 12 | # add these directories to sys.path here. If the directory is relative to the 13 | # documentation root, use os.path.abspath to make it absolute, like shown here. 14 | # 15 | # import os 16 | # import sys 17 | # sys.path.insert(0, os.path.abspath('.')) 18 | 19 | 20 | 21 | #============================================================================== 22 | 23 | from __future__ import absolute_import 24 | from docutils import nodes 25 | from docutils.parsers.rst import Directive, directives 26 | import sphinx_rtd_theme 27 | 28 | 29 | def align(argument): 30 | """Conversion function for the "align" option.""" 31 | return directives.choice(argument, ('left', 'center', 'right')) 32 | 33 | 34 | class IframeVideo(Directive): 35 | has_content = False 36 | required_arguments = 1 37 | optional_arguments = 0 38 | final_argument_whitespace = False 39 | option_spec = { 40 | 'height': directives.nonnegative_int, 41 | 'width': directives.nonnegative_int, 42 | 'align': align, 43 | } 44 | default_width = 500 45 | default_height = 281 46 | 47 | def run(self): 48 | self.options['video_id'] = directives.uri(self.arguments[0]) 49 | if not self.options.get('width'): 50 | self.options['width'] = self.default_width 51 | if not self.options.get('height'): 52 | self.options['height'] = self.default_height 53 | if not self.options.get('align'): 54 | self.options['align'] = 'left' 55 | return [nodes.raw('', self.html % self.options, format='html')] 56 | 57 | 58 | class Youtube(IframeVideo): 59 | html = '' 63 | 64 | 65 | class Vimeo(IframeVideo): 66 | html = '' 70 | 71 | 72 | def setup(builder): 73 | directives.register_directive('youtube', Youtube) 74 | directives.register_directive('vimeo', Vimeo) 75 | 76 | #============================================================================== 77 | 78 | 79 | # -- Project information ----------------------------------------------------- 80 | 81 | project = 'jimutmap' 82 | copyright = '2019-2023, Jimut Bahan Pal' 83 | author = 'Jimut Bahan pal' 84 | 85 | # The short X.Y version 86 | version = '1.4.2' 87 | # The full version, including alpha/beta/rc tags 88 | release = '1.4.2-stable' 89 | 90 | 91 | # -- General configuration --------------------------------------------------- 92 | 93 | # If your documentation needs a minimal Sphinx version, state it here. 94 | # 95 | # needs_sphinx = '1.0' 96 | 97 | # Add any Sphinx extension module names here, as strings. They can be 98 | # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom 99 | # ones. 100 | extensions = [ 101 | 'sphinx.ext.autodoc', 102 | 'sphinx.ext.doctest', 103 | 'sphinx.ext.intersphinx', 104 | 'sphinx.ext.todo', 105 | 'sphinx.ext.coverage', 106 | 'sphinx.ext.mathjax', 107 | 'sphinx.ext.ifconfig', 108 | 'sphinx.ext.viewcode', 109 | 'sphinx.ext.githubpages', 110 | ] 111 | 112 | # Add any paths that contain templates here, relative to this directory. 113 | templates_path = ['_templates'] 114 | 115 | # The suffix(es) of source filenames. 116 | # You can specify multiple suffix as a list of string: 117 | # 118 | # source_suffix = ['.rst', '.md'] 119 | source_suffix = '.rst' 120 | 121 | # The master toctree document. 122 | master_doc = 'index' 123 | 124 | # The language for content autogenerated by Sphinx. Refer to documentation 125 | # for a list of supported languages. 126 | # 127 | # This is also used if you do content translation via gettext catalogs. 128 | # Usually you set "language" from the command line for these cases. 129 | language = None 130 | 131 | # List of patterns, relative to source directory, that match files and 132 | # directories to ignore when looking for source files. 133 | # This pattern also affects html_static_path and html_extra_path . 134 | exclude_patterns = [] 135 | 136 | # The name of the Pygments (syntax highlighting) style to use. 137 | pygments_style = 'sphinx' 138 | 139 | 140 | # -- Options for HTML output ------------------------------------------------- 141 | 142 | # The theme to use for HTML and HTML Help pages. See the documentation for 143 | # a list of builtin themes. 144 | # 145 | html_theme = 'sphinx_rtd_theme' 146 | 147 | # Theme options are theme-specific and customize the look and feel of a theme 148 | # further. For a list of options available for each theme, see the 149 | # documentation. 150 | # 151 | # html_theme_options = {} 152 | 153 | # Add any paths that contain custom static files (such as style sheets) here, 154 | # relative to this directory. They are copied after the builtin static files, 155 | # so a file named "default.css" will overwrite the builtin "default.css". 156 | html_static_path = ['_static'] 157 | 158 | # Custom sidebar templates, must be a dictionary that maps document names 159 | # to template names. 160 | # 161 | # The default sidebars (for documents that don't match any pattern) are 162 | # defined by theme itself. Builtin themes are using these templates by 163 | # default: ``['localtoc.html', 'relations.html', 'sourcelink.html', 164 | # 'searchbox.html']``. 165 | # 166 | # html_sidebars = {} 167 | 168 | 169 | # -- Options for HTMLHelp output --------------------------------------------- 170 | 171 | # Output file base name for HTML help builder. 172 | htmlhelp_basename = 'jimutmapdoc' 173 | 174 | 175 | # -- Options for LaTeX output ------------------------------------------------ 176 | 177 | latex_elements = { 178 | # The paper size ('letterpaper' or 'a4paper'). 179 | # 180 | # 'papersize': 'letterpaper', 181 | 182 | # The font size ('10pt', '11pt' or '12pt'). 183 | # 184 | # 'pointsize': '10pt', 185 | 186 | # Additional stuff for the LaTeX preamble. 187 | # 188 | # 'preamble': '', 189 | 190 | # Latex figure (float) alignment 191 | # 192 | # 'figure_align': 'htbp', 193 | } 194 | 195 | # Grouping the document tree into LaTeX files. List of tuples 196 | # (source start file, target name, title, 197 | # author, documentclass [howto, manual, or own class]). 198 | latex_documents = [ 199 | (master_doc, 'jimutmap.tex', 'jimutmap Documentation', 200 | 'Jimut Bahan Pal', 'manual'), 201 | ] 202 | 203 | 204 | # -- Options for manual page output ------------------------------------------ 205 | 206 | # One entry per manual page. List of tuples 207 | # (source start file, name, description, authors, manual section). 208 | man_pages = [ 209 | (master_doc, 'jimutmap', 'jimutmap Documentation', 210 | [author], 1) 211 | ] 212 | 213 | 214 | # -- Options for Texinfo output ---------------------------------------------- 215 | 216 | # Grouping the document tree into Texinfo files. List of tuples 217 | # (source start file, target name, title, author, 218 | # dir menu entry, description, category) 219 | texinfo_documents = [ 220 | (master_doc, 'jimutmap', 'jimutmap Documentation', 221 | author, 'jimutmap', 'One line description of project.', 222 | 'Miscellaneous'), 223 | ] 224 | 225 | 226 | # -- Options for Epub output ------------------------------------------------- 227 | 228 | # Bibliographic Dublin Core info. 229 | epub_title = project 230 | epub_author = author 231 | epub_publisher = author 232 | epub_copyright = copyright 233 | 234 | # The unique identifier of the text. This can be a ISBN number 235 | # or the project homepage. 236 | # 237 | # epub_identifier = '' 238 | 239 | # A unique identification for the text. 240 | # 241 | # epub_uid = '' 242 | 243 | # A list of files that should not be packed into the epub file. 244 | epub_exclude_files = ['search.html'] 245 | 246 | 247 | # -- Extension configuration ------------------------------------------------- 248 | 249 | extensions = [ 250 | 251 | "sphinx_rtd_theme", 252 | ] 253 | 254 | # -- Options for intersphinx extension --------------------------------------- 255 | 256 | # Example configuration for intersphinx: refer to the Python standard library. 257 | intersphinx_mapping = {'https://docs.python.org/': None} 258 | 259 | # -- Options for todo extension ---------------------------------------------- 260 | 261 | # If true, `todo` and `todoList` produce output, else they produce nothing. 262 | todo_include_todos = True 263 | 264 | -------------------------------------------------------------------------------- /docs/source/INDEX.rst: -------------------------------------------------------------------------------- 1 | -------------- 2 | 3 | .. image:: https://raw.githubusercontent.com/wiki/jimut123/jimutmap/satellite_data/logo.png 4 | :alt: jimutmap logo 5 | :width: 100 % 6 | :align: center 7 | 8 | The **jimutmap** Documentation 9 | =============================== 10 | 11 | -------------- 12 | 13 | .. container:: 14 | 15 | -------------- 16 | 17 | - `Purpose <#purpose>`__ 18 | - `Need for scraping satellite 19 | data <#need-for-scraping-satellite-data>`__ 20 | - `Installation and Usages <#installation-and-usages>`__ 21 | - `Datasets <#datasets>`__ 22 | - `YouTube video <#youtube-video>`__ 23 | - `Perks <#perks>`__ 24 | - `Additional Note <#additional-note>`__ 25 | - `TODOs <#todos>`__ 26 | - `Contribution <#contribution>`__ 27 | - `LICENSE <#license>`__ 28 | - `BibTeX and citations <#bibtex-and-citations>`__ 29 | 30 | **Note:** I am actively looking for project maintainers who can 31 | volunteer to fix bugs/issues and work on 32 | `TODOs `__, 33 | due to my limited time in maintaining this project. If you want to be a 34 | maintainer, either solve a bug or successfully complete a TODO, then 35 | email me for the role (this process is for selecting valid maintainers). 36 | 37 | 🔁 Purpose 38 | -------------- 39 | 40 | This package collects data from 41 | `satellites.pro `__. It 42 | fetches all the tiles (image and road mask pair) as given by the 43 | parameters provided by the user. This uses an API-key generated at the 44 | time of browsing the map. **There are some future plans for this 45 | project, 46 | check**\ `TODO `__\ **to 47 | see what this will support in the future.** 48 | 49 | The api ``accessKey`` token is automatically fetched if you have Google 50 | Chrome or Chromium installed using ``chromedriver-autoinstaller``. 51 | Otherwise, you'll have to fetch it manually and set the ``ac_key`` 52 | parameter (which can be found out by selecting one tile from Apple Map, 53 | through chrome/firefox by going Developer->Network, looking at the 54 | assets, and finding the part of the link beginning with ``&accessKey=`` 55 | until the next ``&``) every 10-15 mins. 56 | 57 | [`Back to Top <#contents>`__] 58 | 59 | 💡 Need for scraping satellite data 60 | --------------------------------------- 61 | 62 | Well it’s good (best in the world) satellite images, we just need to 63 | give the coordinates (Lat,Lon, and zoom) to get your dataset of high 64 | resolution satellite images! Create your own dataset and apply ML 65 | algorithms :’) 66 | 67 | The scraping API is present, call it and download it. 68 | 69 | [`Back to Top <#contents>`__] 70 | 71 | 🛠 Installation and Usages 72 | ------------------------------ 73 | 74 | :: 75 | 76 | sudo pip3 install jimutmap 77 | 78 | # Install google chrome for chrome driver 79 | wget https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb 80 | sudo apt install ./google-chrome-stable_current_amd64.deb 81 | 82 | # optional for viewing the temporary files generated by internal databases 83 | sudo apt-get install sqlite sqlitebrowser 84 | 85 | Needs to have google chrome web browser in the system. 86 | 87 | For example usage, check 88 | `test.py `__ 89 | 90 | ``python3jimut@jimut:~/Desktop/GIT/jimutmap$ python3 test.py Sorry, 5 -- threads unavailable, using maximum CPU threads : 4 Initializing jimutmap ... Please wait... Sorry, 50 -- threads unavailable, using maximum CPU threads : 4 Initializing jimutmap ... Please wait... 100%|██████████████████████████████████████████████| 20/20 [00:00<00:00, 113.67it/s] Sorry, 50 -- threads unavailable, using maximum CPU threads : 4 Initializing jimutmap ... Please wait... 100%|██████████████████████████████████████████████| 20/20 [00:00<00:00, 722.10it/s] Total satellite images to be downloaded = 210 Total roads tiles to be downloaded = 210 Approx. estimated disk space required = 4.1015625 MB Total number of satellite images needed to be downloaded = 210 Total number of satellite images needed to be downloaded = 210 Batch ============================================================================= 1 =================================================================================== Sorry, 50 -- threads unavailable, using maximum CPU threads : 4 Downloading all the satellite tiles: Updating sanity db ... 100%|████████████████████████████████████████████| 27/27 [00:00<00:00, 13291.81it/s] Total number of satellite images needed to be downloaded = 197 Total number of satellite images needed to be downloaded = 196 Downloading speed == 0.09333877563476563 MiB/s Waiting for 15 seconds... Busy downloading Downloading speed == 0.11976458231608073 MiB/s Waiting for 15 seconds... Busy downloading Downloading speed == 0.01717344919840495 MiB/s Waiting for 15 seconds... Busy downloading Batch ============================================================================= 2 =================================================================================== Downloading all the satellite tiles: Updating sanity db ... 100%|██████████████████████████████████████████| 420/420 [00:00<00:00, 99921.03it/s] Total number of satellite images needed to be downloaded = 0 Total number of satellite images needed to be downloaded = 0 ************************* Download Sucessful ************************* Cleaning up... hold on Updating sticher db ... 100%|██████████████████████████████████████████| 420/420 [00:00<00:00, 24357.17it/s] Total number of satellite images needed to be downloaded = 0 Total number of satellite images needed to be downloaded = 0 Calculating bounding boxes for tiles :: Total number of rows present in the database= 210 100%|█████████████████████████████████████████| 210/210 [00:00<00:00, 528693.78it/s] Min lat tile = 390842, Max lat tile = 390855, Min lon tile = 228264, Max lon tile = 228278 No. of tiles in latitude = 13, and longitude = 14 Creating an image of size : 3328x3584 pixels ... 100%|███████████████████████████████████████████████| 13/13 [00:00<00:00, 28.89it/s] 100%|███████████████████████████████████████████████| 13/13 [00:00<00:00, 42.02it/s] Temporary sqlite files to be deleted = ['temp_sanity.sqlite', 'sticher.sqlite'] ? (y/N) : y Temporary chromedriver folders to be deleted = ['100'] ? (y/N) : y`` 91 | 92 | [`Back to Top <#contents>`__] 93 | 94 | 95 | 📘 Datasets 96 | ============ 97 | 98 | Jimutmap might behave weirdly in some cases. Please check the list of 99 | `datasets 100 | here `__. 101 | 102 | 103 | 104 | [`Back to Top <#contents>`__] 105 | 106 | 📹 YouTube video 107 | -------------------- 108 | 109 | If you are confused with the documentation, please see this video, to 110 | see the scraping in action `Apple Maps API to get enormous amount of 111 | satellite data for free using 112 | Python3 `__. 113 | 114 | [`Back to Top <#contents>`__] 115 | 116 | 📚 Sample of the images downloaded 117 | -------------------------------------- 118 | 119 | .. raw:: html 120 | 121 |
122 | 123 | .. raw:: html 124 | 125 |
126 | 127 | [`Back to Top <#contents>`__] 128 | 129 | :feelsgood: Perks 130 | ^^^^^^^^^^^^^^^^^ 131 | 132 | This is done through parallel proccessing, so this will take maximum 133 | threads available in your CPU, change the code to your own requirements! 134 | 135 | If you want to re-fetch tiles, remember to delete/move tiles after every 136 | fetch request done! Else you won’t get the updated information (tiles) 137 | of satellite data after that tile. It is calculated automatically so 138 | that all the progress remains saved! 139 | 140 | [`Back to Top <#contents>`__] 141 | 142 | 📓 Additional Note 143 | ---------------------- 144 | 145 | This is created for educational and research purposes only! The 146 | `authors `__ 147 | are not liable for any damage to private property. 148 | 149 | [`Back to Top <#contents>`__] 150 | 151 | :atom: TODOs 152 | ----------------- 153 | 154 | Please check 155 | `TODOs `__, 156 | since this project needs collaborators. 157 | 158 | [`Back to Top <#contents>`__] 159 | 160 | ❓ Questions or want to discuss about something ? 161 | ----------------------------------------------------- 162 | 163 | Submit an issue. 164 | 165 | [`Back to Top <#contents>`__] 166 | 167 | 🤝 Contribution 168 | --------------- 169 | 170 | Please see 171 | `Contributing.md `__ 172 | 173 | [`Back to Top <#contents>`__] 174 | 175 | 🛡️ `LICENSE `__ 176 | ------------------------------------------------------------------------- 177 | 178 | :: 179 | 180 | GNU GENERAL PUBLIC LICENSE 181 | Version 3, 29 June 2007 182 | 183 | Copyright (C) 2019-20 Jimut Bahan Pal, 184 | Everyone is permitted to copy and distribute verbatim copies 185 | of this license document, but changing it is not allowed. 186 | 187 | [`Back to Top <#contents>`__] 188 | 189 | 📝 BibTeX and citations 190 | ======================== 191 | 192 | :: 193 | 194 | @misc{jimutmap_2019, 195 | author = {Jimut Bahan Pal}, 196 | title = {jimutmap}, 197 | year = {2019}, 198 | publisher = {GitHub}, 199 | journal = {GitHub repository}, 200 | howpublished = {\url{https://github.com/Jimut123/jimutmap}} 201 | } 202 | 203 | [`Back to Top <#contents>`__] 204 | 205 | 206 | .. toctree:: 207 | :maxdepth: 2 208 | :caption: External Contents: 209 | INDEX 210 | LICENSE 211 | DATASETS 212 | PARAMETERS 213 | REQUIREMENTS 214 | CODE_OF_CONDUCT 215 | CONTRIBUTING 216 | CONTRIBUTORS 217 | BUG_REPORTS 218 | TODO 219 | 220 | -------------------------------------------------------------------------------- /jimutmap/sanity_checker.py: -------------------------------------------------------------------------------- 1 | # ====================================================== 2 | # This program checks the sanity of download. 3 | # OPEN SOURCED UNDER GPL-V3.0. 4 | # Author : Jimut Bahan Pal | jimutbahanpal@yahoo.com 5 | # Project Website: https://github.com/Jimut123/jimutmap 6 | # ====================================================== 7 | 8 | import ssl 9 | import os 10 | import time 11 | import math 12 | import glob 13 | import imghdr 14 | import requests 15 | import sqlite3 16 | import numpy as np 17 | import datetime as dt 18 | from tqdm import tqdm 19 | import multiprocessing 20 | from jimutmap_1 import api 21 | from typing import Tuple 22 | from selenium import webdriver 23 | import chromedriver_autoinstaller 24 | from .file_size import get_folder_size 25 | from multiprocessing.pool import ThreadPool 26 | from os.path import join, exists, normpath, relpath 27 | 28 | 29 | 30 | def generate_summary(): 31 | # Create an approximate analysis of the space required 32 | total_files_downloaded = cur.execute(''' SELECT * FROM sanity ''') 33 | total_files_downloaded_val = cur.fetchall() #converts the cursor object to number 34 | total_number_of_files = len(total_files_downloaded_val) 35 | print("Total satellite images to be downloaded = ",total_number_of_files) 36 | print("Total roads tiles to be downloaded = ",total_number_of_files) 37 | disk_space = 10*2*total_number_of_files/1024 38 | print("Approx. estimated disk space required = {} MB".format(disk_space)) 39 | 40 | 41 | def create_sanity_db(min_lat_deg, max_lat_deg, min_lon_deg, max_lon_deg, latLonResolution=0.0005, verbose=False): 42 | # To save all the expected file names to be downloaded 43 | for i in tqdm(np.arange(min_lat_deg, max_lat_deg, latLonResolution)): 44 | for j in np.arange(min_lon_deg, max_lon_deg, latLonResolution): 45 | xTile, yTile = sanity_obj.ret_xy_tiles(i,j) 46 | # print(xTile," ",yTile) 47 | # create the primary key for tracking values 48 | key_id = str(xTile)+"_"+str(yTile) 49 | # write the query 50 | query_insert = "INSERT OR IGNORE INTO sanity VALUES ('{}','{}','{}','{}','{}')".format(key_id,xTile, yTile, 0, 0) 51 | # Insert a row of records 52 | cur.execute(query_insert) 53 | 54 | 55 | def update_sanity_db(folder_name): 56 | # to take the files present in the folder and update all the entries of the 57 | # sanity database 58 | print("Updating sanity db ...") 59 | all_files_folder = glob.glob('{}/*'.format(folder_name)) 60 | for tile_name in tqdm(all_files_folder): 61 | if tile_name.count('_') == 1: 62 | # then it is a satellite imagery 63 | xTile_val = str(tile_name.split('_')[0]).split('/')[-1] 64 | yTile_val = str(tile_name.split('_')[-1]).split('.')[0] 65 | create_id = str(xTile_val)+"_"+str(yTile_val) 66 | # print(create_id) 67 | cur.execute('''UPDATE sanity SET satellite_tile = 1 WHERE id = ?''',(str(create_id),)) # set the satellite_tile to 1 68 | 69 | if tile_name.count('_') == 2: 70 | # then it is a road mask 71 | xTile_val = str(tile_name.split('_')[0]).split('/')[-1] 72 | yTile_val = str(tile_name.split('_')[-2]) 73 | create_id = str(xTile_val)+"_"+str(yTile_val) 74 | # print(create_id) 75 | cur.execute('''UPDATE sanity SET road_tile = 1 WHERE id = ?''',(str(create_id),)) # set the road_tile to 1 76 | con.commit() 77 | 78 | 79 | 80 | def shall_stop(): 81 | # this function returns 1 if we need to stop, i.e., if all the entries are 1 82 | # which means all the required files are downloaded in the folder specified 83 | # even if one file is missing, we return 0 84 | 85 | # get all the number of 0 entries for satellite imagery 86 | get_sat_0s = cur.execute(''' SELECT * FROM sanity WHERE satellite_tile = 0 ''') 87 | get_sat_0s_val = cur.fetchall() #converts the cursor object to number 88 | total_number_of_sat0s = len(get_sat_0s_val) 89 | print("Total number of satellite images needed to be downloaded = ", total_number_of_sat0s) 90 | 91 | get_road_0s = cur.execute(''' SELECT * FROM sanity WHERE road_tile = 0 ''') 92 | get_road_0s_val = cur.fetchall() #converts the cursor object to number 93 | total_number_of_road0s = len(get_road_0s_val) 94 | print("Total number of satellite images needed to be downloaded = ", total_number_of_road0s) 95 | 96 | if total_number_of_sat0s == 0 and total_number_of_road0s == 0: 97 | return 1 98 | return 0 99 | 100 | 101 | def check_downloading(): 102 | # checks if the multiprocessing tool is still downloading the files or not 103 | # if there is a minute increase in byte size of the folder, we need to wait 104 | # till the multiprocessing thread finishes its execution 105 | get_folder_size_ini = get_folder_size('myOutputFolder') 106 | time.sleep(15) 107 | get_folder_size_final = get_folder_size('myOutputFolder') 108 | diff = get_folder_size_final - get_folder_size_ini 109 | speed_download = diff/(15.0*1024*1024) # get the speed in MB 110 | if diff > 0: 111 | # we need to sleep for 5 seconds again 112 | print("Downloading speed == {} MiB/s ".format(speed_download)) 113 | return 1 114 | return 0 115 | 116 | 117 | def get_sat_img_id(): 118 | # to get all the satellite image ids which are not yet being downloaded 119 | get_sat_0s = cur.execute(''' SELECT id FROM sanity WHERE satellite_tile = 0 ''') 120 | get_sat_0s_val = cur.fetchall() #converts the cursor object to number 121 | # print("Total number of satellite images needed to be downloaded = ", len(get_sat_0s_val)) 122 | get_sat_ids = [] 123 | for item in get_sat_0s_val: 124 | get_sat_ids.append(item[0]) 125 | return get_sat_ids 126 | 127 | 128 | def get_road_img_id(): 129 | # to get all the road tiles image ids which are not yet being downloaded 130 | get_road_0s = cur.execute(''' SELECT * FROM sanity WHERE road_tile = 0 ''') 131 | get_road_0s_val = cur.fetchall() #converts the cursor object to number 132 | # print("Total number of satellite images needed to be downloaded = ", len(get_road_0s_val)) 133 | get_road_ids = [] 134 | for item in get_road_0s_val: 135 | get_road_ids.append(item[0]) 136 | return get_road_ids 137 | 138 | 139 | 140 | 141 | def sanity_check(min_lat_deg, max_lat_deg, min_lon_deg, max_lon_deg, zoom, verbose, threads_, container_dir = "myOutputFolder"): 142 | # This function contains the main loop for checking the sanity of download 143 | # till all the files are downloaded 144 | 145 | # Create table sanity with the coordinates, and the corresponding 146 | # satellite tile and the road tile, id as the primary key xTile_yTile 147 | 148 | cur.execute('''CREATE TABLE IF NOT EXISTS sanity 149 | (id TEXT primary key, xTile INTEGER, yTile INTEGER, satellite_tile INTEGER, road_tile INTEGER )''') 150 | 151 | # check if the files are downloading or not, if so, then wait for certain seconds, 152 | # repeat this till the files stop downloading and then start the next batch of downloads 153 | batch = 1 154 | create_sanity_db(min_lat_deg, max_lat_deg, min_lon_deg, max_lon_deg, latLonResolution=0.0005, verbose=False) 155 | generate_summary() 156 | 157 | while(shall_stop() == 0): 158 | 159 | sat_img_ids = get_sat_img_id() 160 | road_img_ids = get_road_img_id() 161 | # print(sat_img_ids) 162 | # print(road_img_ids) 163 | 164 | 165 | 166 | while(check_downloading()==1): 167 | print("Waiting for 15 seconds... Busy downloading") 168 | 169 | print("Batch ============================================================================= ",batch) 170 | print("===================================================================================") 171 | batch += 1 172 | 173 | # begin the operation here 174 | # url_str = [xtile, ytile] 175 | # TODO 176 | 177 | # To get the maximum number of threads 178 | MAX_CORES = multiprocessing.cpu_count() 179 | if threads_> MAX_CORES: 180 | print("Sorry, {} -- threads unavailable, using maximum CPU threads : {}".format(threads_,MAX_CORES)) 181 | threads_ = MAX_CORES 182 | 183 | LOCKING_LIMIT = threads_ 184 | 185 | tp=None 186 | URL_ALL = [] 187 | print("Downloading all the satellite tiles: ") 188 | for sat_tile_name in sat_img_ids: 189 | xTile = sat_tile_name.split('_')[0] 190 | yTile = sat_tile_name.split('_')[1] 191 | URL_ALL.append([xTile, yTile]) 192 | 193 | # print(URL_ALL) 194 | tp = ThreadPool(LOCKING_LIMIT) 195 | tp.imap_unordered(lambda x: sanity_obj.get_img(x), URL_ALL) #pylint: disable= unnecessary-lambda #cSpell:words imap 196 | tp.close() 197 | 198 | # while(tp is not None): 199 | # print("Waiting for thread to finish downloading satellite tiles") 200 | # time.sleep(5) 201 | update_sanity_db('myOutputFolder') 202 | # Save (commit) the changes 203 | con.commit() 204 | 205 | # continue the loop till there is no file left to download 206 | # generate the summary 207 | 208 | 209 | 210 | # We can also close the connection if we are done with it. 211 | # Just be sure any changes have been committed or they will be lost. 212 | print("************************* Download Sucessful *************************") 213 | con.close() 214 | 215 | 216 | # connect to the temporary database that we shall use 217 | con = sqlite3.connect('temp_sanity.sqlite') 218 | cur = con.cursor() 219 | 220 | # create the object of class jimutmap's api 221 | sanity_obj = api(min_lat_deg = 10, 222 | max_lat_deg = 10.01, 223 | min_lon_deg = 10, 224 | max_lon_deg = 10.01, 225 | zoom = 19, 226 | verbose = False, 227 | threads_ = 5, 228 | container_dir = "myOutputFolder") 229 | 230 | 231 | 232 | if __name__ == "__main__": 233 | # use main function for proper structuing of code 234 | sanity_check(min_lat_deg = 10, 235 | max_lat_deg = 10.01, 236 | min_lon_deg = 10, 237 | max_lon_deg = 10.01, 238 | zoom = 19, 239 | verbose = False, 240 | threads_ = 5, 241 | container_dir = "myOutputFolder") -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------- 2 | 3 |

4 | 5 | ...Bringing Data to Humans 6 |

7 | 8 | -------------------------------------------------------------------- 9 | 10 | 11 |
12 | 13 | 14 | 15 | Documentation Status 16 | 17 | 18 | Downloads per month 19 | 20 | 21 | zenodo 22 | 23 | 24 | 25 |
26 | 27 | *** 28 | 29 | > [!CAUTION] 30 | > **I am actively looking for project maintainers who can volunteer to fix bugs/issues and work on [TODOs](https://github.com/Jimut123/jimutmap/blob/master/TODO.md), due to my limited time in maintaining this project. If you want to be a maintainer, either solve a bug (by making this software work for newer versions of apple maps) or successfully complete a TODO, then email me for the role (this process is for selecting valid maintainers).** 31 | 32 | ### May, 2025: [Please find the AI-generated jimutmap wiki here](https://deepwiki.com/Jimut123/jimutmap/1-overview) 33 | 34 | ## 📋 Contents 35 | 36 | * [Purpose](#purpose) 37 | * [Need for scraping satellite data](#need-for-scraping-satellite-data) 38 | * [Installation and Usages](#installation-and-usages) 39 | * [Some of the example images downloaded at different scales](#some-of-the-example-images-downloaded-at-different-scales) 40 | * [Datasets](#datasets) 41 | * [YouTube video](#youtube-video) 42 | * [Sample of the images downloaded](#sample-of-the-images-downloaded) 43 | * [Perks](#perks) 44 | * [Additional Note](#additional-note) 45 | * [TODOs](#todos) 46 | * [Contribution](#contribution) 47 | * [LICENSE](#license) 48 | * [BibTeX and citations](#bibtex-and-citations) 49 | 50 | 51 | ## 🔁 Purpose 52 | 53 | This package collects data from [satellites.pro](https://satellites.pro/#32.916485,62.578125,4). It fetches all the tiles (image and road mask pair) as given by the parameters provided by the user. This uses an API-key generated at the time of browsing the map. **There are some future plans for this project, check [TODO](https://github.com/Jimut123/jimutmap/blob/master/TODO.md) to see what this will support in the future.** 54 | 55 | The api `accessKey` token is automatically fetched if you have Google Chrome or Chromium installed using `chromedriver-autoinstaller`. Otherwise, you'll have to fetch it manually and set the `ac_key` parameter (which can be found out by selecting one tile from Apple Map, through chrome/firefox by going Developer->Network, looking at the assets, and finding the part of the link beginning with `&accessKey=` until the next `&`) every 10-15 mins. 56 | 57 | [[Back to Top](#contents)] 58 | 59 | 60 | ## 💡 Need for scraping satellite data 61 | 62 | Well it's good (best in the world) satellite images, we just need to give the coordinates (Lat,Lon, and zoom) to get your dataset 63 | of high resolution satellite images! Create your own dataset and apply ML algorithms :') 64 | 65 | 66 | The scraping API is present, call it and download it. 67 | 68 | [[Back to Top](#contents)] 69 | 70 | 71 | ## 🛠 Installation and Usages 72 | 73 | ``` 74 | sudo pip3 install jimutmap 75 | 76 | # Install google chrome for chrome driver 77 | wget https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb 78 | sudo apt install ./google-chrome-stable_current_amd64.deb 79 | 80 | # optional for viewing the temporary files generated by internal databases 81 | sudo apt-get install sqlite sqlitebrowser 82 | ``` 83 | 84 | Needs to have google chrome web browser in the system. 85 | 86 | For example usage, check [test.py](https://github.com/Jimut123/jimutmap/blob/master/test.py) 87 | 88 | ```python3jimut@jimut:~/Desktop/GIT/jimutmap$ python3 test.py 89 | Sorry, 5 -- threads unavailable, using maximum CPU threads : 4 90 | Initializing jimutmap ... Please wait... 91 | Sorry, 50 -- threads unavailable, using maximum CPU threads : 4 92 | Initializing jimutmap ... Please wait... 93 | 100%|██████████████████████████████████████████████| 20/20 [00:00<00:00, 113.67it/s] 94 | Sorry, 50 -- threads unavailable, using maximum CPU threads : 4 95 | Initializing jimutmap ... Please wait... 96 | 100%|██████████████████████████████████████████████| 20/20 [00:00<00:00, 722.10it/s] 97 | Total satellite images to be downloaded = 210 98 | Total roads tiles to be downloaded = 210 99 | Approx. estimated disk space required = 4.1015625 MB 100 | Total number of satellite images needed to be downloaded = 210 101 | Total number of satellite images needed to be downloaded = 210 102 | Batch ============================================================================= 1 103 | =================================================================================== 104 | Sorry, 50 -- threads unavailable, using maximum CPU threads : 4 105 | Downloading all the satellite tiles: 106 | Updating sanity db ... 107 | 100%|████████████████████████████████████████████| 27/27 [00:00<00:00, 13291.81it/s] 108 | Total number of satellite images needed to be downloaded = 197 109 | Total number of satellite images needed to be downloaded = 196 110 | Downloading speed == 0.09333877563476563 MiB/s 111 | Waiting for 15 seconds... Busy downloading 112 | Downloading speed == 0.11976458231608073 MiB/s 113 | Waiting for 15 seconds... Busy downloading 114 | Downloading speed == 0.01717344919840495 MiB/s 115 | Waiting for 15 seconds... Busy downloading 116 | Batch ============================================================================= 2 117 | =================================================================================== 118 | Downloading all the satellite tiles: 119 | Updating sanity db ... 120 | 100%|██████████████████████████████████████████| 420/420 [00:00<00:00, 99921.03it/s] 121 | Total number of satellite images needed to be downloaded = 0 122 | Total number of satellite images needed to be downloaded = 0 123 | ************************* Download Sucessful ************************* 124 | Cleaning up... hold on 125 | Updating sticher db ... 126 | 100%|██████████████████████████████████████████| 420/420 [00:00<00:00, 24357.17it/s] 127 | Total number of satellite images needed to be downloaded = 0 128 | Total number of satellite images needed to be downloaded = 0 129 | Calculating bounding boxes for tiles :: 130 | Total number of rows present in the database= 210 131 | 100%|█████████████████████████████████████████| 210/210 [00:00<00:00, 528693.78it/s] 132 | Min lat tile = 390842, Max lat tile = 390855, Min lon tile = 228264, Max lon tile = 228278 133 | No. of tiles in latitude = 13, and longitude = 14 134 | Creating an image of size : 3328x3584 pixels ... 135 | 100%|███████████████████████████████████████████████| 13/13 [00:00<00:00, 28.89it/s] 136 | 100%|███████████████████████████████████████████████| 13/13 [00:00<00:00, 42.02it/s] 137 | Temporary sqlite files to be deleted = ['temp_sanity.sqlite', 'sticher.sqlite'] ? 138 | (y/N) : y 139 | Temporary chromedriver folders to be deleted = ['100'] ? 140 | (y/N) : y 141 | ``` 142 | 143 | [[Back to Top](#contents)] 144 | 145 | 146 | ## 📚 Some of the example images downloaded at different scales 147 | 148 | | | | | | 149 | |:-------------------------:|:-------------------------:|:-------------------------:|:-------------------------:| 150 | | | | || 151 | | | ||| 152 | | | ||| 153 | 154 | [[Back to Top](#contents)] 155 | 156 | # 📘 Datasets 157 | 158 | Jimutmap might behave weirdly in some cases. Please check the list of [datasets here](https://github.com/Jimut123/jimutmap/blob/master/DATASETS.md). 159 | 160 | ## 📚 Stitched tiles for Kolkata 161 | 162 | | | | 163 | |:-------------------------:|:-------------------------:| 164 | | | | 165 | 166 | [[Back to Top](#contents)] 167 | 168 | 169 | 170 | ## 📹 YouTube video 171 | 172 | If you are confused with the documentation, please see this video, to see the scraping in action [Apple Maps API to get enormous amount of satellite data for free using Python3](https://www.youtube.com/watch?v=voH0qhGXfsU). 173 | 174 | [[Back to Top](#contents)] 175 | 176 | 177 | ## 📚 Sample of the images downloaded 178 | 179 |
180 | img of sat dat 181 |
182 | 183 | [[Back to Top](#contents)] 184 | 185 | 186 | #### :feelsgood: Perks 187 | 188 | This is done through parallel proccessing, so this will take maximum threads available in your CPU, change the 189 | code to your own requirements! 190 | 191 | If you want to re-fetch tiles, remember to delete/move tiles after every fetch request done! Else you won't get the updated information (tiles) of satellite data after that tile. It is calculated automatically so that all the progress remains saved! 192 | 193 | [[Back to Top](#contents)] 194 | 195 | 196 | ## 📓 Additional Note 197 | 198 | This is created for educational and research purposes only! The [authors](https://github.com/Jimut123/jimutmap/blob/master/CONTRIBUTORS.md) are not liable for any damage to private property. 199 | 200 | [[Back to Top](#contents)] 201 | 202 | 203 | ## :atom: TODOs 204 | 205 | Please check [TODOs](https://github.com/Jimut123/jimutmap/blob/master/TODO.md), since this project needs collaborators. 206 | 207 | [[Back to Top](#contents)] 208 | 209 | 210 | ## ❓ Questions or want to discuss about something ? 211 | 212 | Submit an issue. 213 | 214 | [[Back to Top](#contents)] 215 | 216 | 217 | ## 🤝 Contribution 218 | 219 | Please see [Contributing.md](https://github.com/Jimut123/jimutmap/blob/master/CONTRIBUTING.md) 220 | 221 | [[Back to Top](#contents)] 222 | 223 | 224 | ## 🛡️ [LICENSE](https://github.com/Jimut123/jimutmap/blob/master/LICENSE) 225 | ``` 226 | GNU GENERAL PUBLIC LICENSE 227 | Version 3, 29 June 2007 228 | 229 | Copyright (C) 2019-20 Jimut Bahan Pal, 230 | Everyone is permitted to copy and distribute verbatim copies 231 | of this license document, but changing it is not allowed. 232 | ``` 233 | 234 | [[Back to Top](#contents)] 235 | 236 | 237 | # 📝 BibTeX and citations 238 | 239 | ``` 240 | @misc{jimutmap_2019, 241 | author = {Jimut Bahan Pal}, 242 | title = {jimutmap}, 243 | year = {2019}, 244 | publisher = {GitHub}, 245 | journal = {GitHub repository}, 246 | howpublished = {\url{https://github.com/Jimut123/jimutmap}} 247 | } 248 | ``` 249 | 250 | [[Back to Top](#contents)] 251 | -------------------------------------------------------------------------------- /jimutmap/jimutmap.py: -------------------------------------------------------------------------------- 1 | # ======================================================== 2 | # This program fetches tiles from satellites.pro for free. 3 | # OPEN SOURCED UNDER GPL-V3.0. 4 | # Author : Jimut Bahan Pal | jimutbahanpal@yahoo.com 5 | # Project Website: https://github.com/Jimut123/jimutmap 6 | # pylint: disable = global-statement 7 | # cSpell: words imghdr, tqdm, asinh, jimut, bahan 8 | # ======================================================== 9 | 10 | import ssl 11 | import os 12 | import time 13 | import math 14 | import imghdr 15 | import requests 16 | import numpy as np 17 | import datetime as dt 18 | from tqdm import tqdm 19 | import multiprocessing 20 | from typing import Tuple 21 | from selenium import webdriver 22 | import chromedriver_autoinstaller 23 | from multiprocessing.pool import ThreadPool 24 | from os.path import join, exists, normpath, relpath 25 | 26 | 27 | 28 | 29 | 30 | 31 | # Ignore SSL certificate errors 32 | ctx = ssl.create_default_context() 33 | ctx.check_hostname = False 34 | ctx.verify_mode = ssl.CERT_NONE 35 | 36 | headers = { 37 | 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:21.0) Gecko/20100101 Firefox/21.0' 38 | } 39 | 40 | 41 | 42 | 43 | 44 | # To synchronize 45 | 46 | LOCK_VAR = 0 47 | UNLOCK_VAR = 0 48 | LOCKING_LIMIT = 50 # MAX NO OF THREADS 49 | 50 | 51 | class api: 52 | """ 53 | Pull tiles from Apple Maps 54 | """ 55 | def __init__(self, min_lat_deg:float, max_lat_deg:float, min_lon_deg:float, max_lon_deg:float, zoom= 19, ac_key:str= None, verbose:bool= False, threads_:int= 4, container_dir:str= ""): 56 | """ 57 | Parameters 58 | ------------------------------------- 59 | 60 | min_lat_deg: float 61 | max_lat_deg: float 62 | min_lon_deg: float 63 | max_lon_deg: float 64 | 65 | zoom: int 66 | Zoom level. Between 1 and 20. 67 | 68 | ac_key:str (default= None) 69 | Access key to Apple Maps. If not provided, will use a headless Chrome instance to fetch a session key. 70 | 71 | verbose:bool (default= False) 72 | Helpful debugging output 73 | 74 | threads_: int (default= 4) 75 | Thread limit for process. Max depending on CPU cores 76 | 77 | container_dir:str (default= "") 78 | When downloading images, place them in this directory. 79 | It will be created if it does not exist. 80 | """ 81 | global LOCKING_LIMIT 82 | self._acKey = None 83 | self._containerDir = "" 84 | if ac_key is None: 85 | self._getAPIKey() 86 | else: 87 | self.ac_key = ac_key 88 | self.set_bounds(min_lat_deg, max_lat_deg, min_lon_deg, max_lon_deg) 89 | self.zoom = zoom 90 | self.verbose = bool(verbose) 91 | 92 | # To get the maximum number of threads 93 | MAX_CORES = multiprocessing.cpu_count() 94 | if threads_> MAX_CORES: 95 | print("Sorry, {} -- threads unavailable, using maximum CPU threads : {}".format(threads_,MAX_CORES)) 96 | threads_ = MAX_CORES 97 | 98 | LOCKING_LIMIT = threads_ 99 | 100 | if self.verbose: 101 | print(self.ac_key,self.min_lat_deg,self.max_lat_deg,self.min_lon_deg,self.max_lon_deg,self.zoom,self.verbose,LOCKING_LIMIT) 102 | self._getMasks = True 103 | self.container_dir = container_dir 104 | print("Initializing jimutmap ... Please wait...") 105 | 106 | 107 | @property 108 | def container_dir(self) -> str: 109 | """ 110 | Get the output directory 111 | """ 112 | return self._containerDir 113 | 114 | @container_dir.setter 115 | def container_dir(self, newDir:str): 116 | try: 117 | if isinstance(newDir, str) and len(newDir) > 0: 118 | newDir = normpath(relpath(newDir)) 119 | if not exists(newDir): 120 | if self.verbose: 121 | print(f"Creating target directory `{newDir}`") 122 | os.makedirs(newDir) 123 | assert exists(newDir) 124 | self._containerDir = newDir 125 | except Exception: #pylint: disable= broad-except 126 | self._containerDir = "" 127 | 128 | 129 | def set_bounds(self, min_lat_deg:float, max_lat_deg:float, min_lon_deg:float, max_lon_deg:float): 130 | """ 131 | Set the viewport bounds 132 | """ 133 | assert -90 < min_lat_deg < 90 134 | assert -90 < max_lat_deg < 90 135 | assert min_lat_deg < max_lat_deg 136 | assert -180 < min_lon_deg < 180 137 | assert -180 < max_lon_deg < 180 138 | assert min_lon_deg < max_lon_deg 139 | # For compatibility with other funcs, 140 | # explicitly cast to float 141 | self.min_lat_deg = float(min_lat_deg) 142 | self.max_lat_deg = float(max_lat_deg) 143 | self.min_lon_deg = float(min_lon_deg) 144 | self.max_lon_deg = float(max_lon_deg) 145 | 146 | def _getLatBounds(self) -> Tuple[float, float]: 147 | """ 148 | Internal getter for (min, max) latitude 149 | """ 150 | return self.min_lat_deg, self.max_lat_deg 151 | 152 | def _getLonBounds(self) -> Tuple[float, float]: 153 | """ 154 | Internal getter for (min, max) longitude 155 | """ 156 | return self.min_lon_deg, self.max_lon_deg 157 | 158 | @property 159 | def ac_key(self) -> str: 160 | """ 161 | Get or set the internal accessKey for the tile requests 162 | """ 163 | return self._acKey 164 | 165 | @ac_key.setter 166 | def ac_key(self, newACKey:str): 167 | try: 168 | if not newACKey.startswith("&"): 169 | if not newACKey.lower().startswith("a"): 170 | newACKey = f"accessKey={newACKey}" 171 | newACKey = f"&{newACKey}" 172 | self._acKey = newACKey 173 | except (AttributeError, TypeError): 174 | self._acKey = None 175 | if newACKey is not None: 176 | raise ValueError("Invalid AccessKey string") 177 | 178 | def _getAPIKey(self, timeout:float= 60) -> str: 179 | """ 180 | Use a headless Chrome/Chromium instance to scrape the access key 181 | from the data-map-printing-background attribute of Apple Maps. 182 | """ 183 | SAMPLE_KEY = r"1614125879_3642792122889215637_%2F_RwvhYZM5fKknqTdkXih2Wcu3s2f3Xea126uoIuDzUIY%3D" 184 | KEY_START = r"&accessKey=" 185 | chromeDriverPath = chromedriver_autoinstaller.install(cwd= True) 186 | options = webdriver.ChromeOptions() 187 | options.add_argument('headless') 188 | driver = webdriver.Chrome(executable_path= chromeDriverPath, options=options) 189 | driver.get("https://satellites.pro/USA_map#37.405074,-94.284668,5") 190 | keyContents = None 191 | loopStartTime = dt.datetime.now() 192 | while keyContents is None and (dt.datetime.now() - loopStartTime).total_seconds() < timeout: 193 | time.sleep(2.5) 194 | try: 195 | baseMap = driver.find_element_by_css_selector("#map-canvas .leaflet-mapkit-mutant") 196 | mapData = baseMap.get_attribute("data-map-printing-background") 197 | accessKeyStart = mapData.find(KEY_START) 198 | accessKeyEnd = accessKeyStart + int(1.5 * len(SAMPLE_KEY)) 199 | searchForKey = mapData[accessKeyStart:accessKeyEnd] 200 | keyContents = searchForKey[len(KEY_START):] 201 | keyEnd = keyContents.find("&") 202 | keyContents = keyContents[:keyEnd] 203 | except Exception: #pylint: disable= broad-except 204 | keyContents = None 205 | if keyContents is None: 206 | raise TimeoutError(f"Unable to automatically fetch API key in {timeout}s") 207 | self.ac_key = keyContents 208 | return keyContents 209 | 210 | 211 | def ret_xy_tiles(self, lat_deg:float, lon_deg:float) -> Tuple[int, int]: 212 | """ 213 | Parameters 214 | ----------------------- 215 | 216 | lat_deg:float 217 | lon_deg:float 218 | 219 | Returns 220 | ---------------------- 221 | tuple: (xTile, yTile) 222 | """ 223 | n = 2**self.zoom 224 | xTile = n * ((lon_deg + 180) / 360) 225 | lat_rad = lat_deg * math.pi / 180.0 226 | yTile = n * (1 - (math.log(math.tan(lat_rad) + 1/math.cos(lat_rad)) / math.pi)) / 2 227 | return int(xTile),int(yTile) 228 | 229 | def ret_lat_lon(self, xTile:int, yTile:int) -> Tuple[float, float]: 230 | """ 231 | Parameters 232 | ----------------------- 233 | 234 | xTile:int 235 | yTile:int 236 | 237 | Returns 238 | ---------------------- 239 | tuple: (lat, lng) 240 | """ 241 | n = 2**self.zoom 242 | lon_deg = int(xTile)/n * 360.0 - 180.0 243 | # lat_rad = math.atan(math.asinh(math.pi * (1 - 2 * int(yTile)/n))) 244 | lat_rad=2*((math.pi/4)-math.atan(math.exp(-1*math.pi*(1-2* int(yTile)/n)))) 245 | lat_deg = lat_rad * 180.0 / math.pi 246 | return lat_deg, lon_deg 247 | 248 | def make_url(self, lat_deg:float, lon_deg:float): 249 | """ 250 | returns the list of urls when lat, lon, zoom and accessKey is provided 251 | 252 | Parameters 253 | ----------------------- 254 | 255 | lat_deg:float 256 | lon_deg:float 257 | """ 258 | xTile, yTile = self.ret_xy_tiles(lat_deg, lon_deg) 259 | return [xTile, yTile] 260 | 261 | def get_img(self, url_str:str, vNumber:int= 9042, getMask:bool= None, prefix:str= "", _rerun:bool= False): 262 | """ 263 | Get images from the URL provided and save them 264 | 265 | Parameters 266 | -------------------- 267 | url_str:str 268 | The URL to read 269 | 270 | vNumber:int (default= 9042) 271 | The original version of this number was hardcoded as 7072, 272 | which was no longer working. Moved to a kwarg. 273 | 274 | getMask:bool (default= None) 275 | By default, uses the internal self._getMasks variable set 276 | on instantiation. If set to a boolean value, overrides the 277 | current self._getMasks value 278 | 279 | _rerun:bool (default= False) 280 | Internal. Tracks retry status. 281 | """ 282 | global headers, LOCK_VAR, UNLOCK_VAR, LOCKING_LIMIT 283 | if isinstance(getMask, bool): 284 | self._getMasks = getMask 285 | getMask = self._getMasks 286 | if self.verbose: 287 | print(url_str) 288 | UNLOCK_VAR = UNLOCK_VAR + 1 289 | LOCK_VAR = 1 290 | if self.verbose: 291 | print("UNLOCK VAR : ",UNLOCK_VAR) 292 | if UNLOCK_VAR >= LOCKING_LIMIT: 293 | LOCK_VAR = 0 294 | UNLOCK_VAR = 0 295 | if self.verbose: 296 | print("-------- UNLOCKING") 297 | xTile = url_str[0] 298 | yTile = url_str[1] 299 | file_name = join(self.container_dir, f"{prefix}{xTile}_{yTile}.jpg") 300 | try: 301 | assert exists(file_name) 302 | except AssertionError: 303 | try: 304 | # get the image tile and the mask tile for the same 305 | # sample sat tile: https://sat-cdn2.apple-mapkit.com/tile?style=7&size=1&scale=1&z=19&x=390843&y=228270&v=9262&accessKey=1649243787_2102081627305478489_%2F_hIz9LjsZkMj6NE7y%2BimXS9vFQbxfjLBClZR7yqyFtsE%3D&emphasis=standard&tint=light 306 | req_url = f"https://sat-cdn1.apple-mapkit.com/tile?style=7&size=1&scale=1&z={self.zoom}&x={xTile}&y={yTile}&v={vNumber}{self.ac_key}" 307 | if self.verbose: 308 | print(req_url) 309 | r = requests.get(req_url, headers= headers) 310 | try: 311 | if "access denied" in str(r.content).lower(): 312 | if _rerun: 313 | return False 314 | # Refresh the API key 315 | self._getAPIKey() 316 | return self.get_img(url_str, vNumber, getMask, _rerun= True) 317 | except Exception: #pylint: disable= broad-except 318 | pass 319 | with open(file_name, 'wb') as fh: 320 | fh.write(r.content) 321 | if imghdr.what(file_name) == 'jpeg': 322 | if self.verbose: 323 | print(file_name,"JPEG") 324 | else: 325 | os.remove(file_name) 326 | if self.verbose: 327 | print(file_name, "NOT JPEG") 328 | except Exception as e: #pylint: disable= broad-except 329 | if self.verbose: 330 | print(e) 331 | if getMask: 332 | ext = file_name.split('.').pop() 333 | file_name_road = file_name[:-len(ext)-1]+"_road.png" 334 | try: 335 | assert exists(file_name_road) 336 | except AssertionError: 337 | for cdnLevel in range(1, 5): 338 | # change the 2nd auth according to the datetime for downloading the roads masks 339 | today_date = str(dt.date.today()) 340 | year = today_date[0:4] 341 | month = today_date[5:7] 342 | day = today_date[8:10] 343 | env_key = str(year)+str(month)+str(day) 344 | # sample road tile 1: https://cdn3.apple-mapkit.com/ti/tile?country=IN®ion=IN&style=46&size=1&x=390842&y=228268&z=19&scale=1&lang=en&v=2204054&poi=1&accessKey=1649243787_2102081627305478489_%2F_hIz9LjsZkMj6NE7y%2BimXS9vFQbxfjLBClZR7yqyFtsE%3D&emphasis=standard&tint=light 345 | # sample road tile 2: https://cdn4.apple-mapkit.com/ti/tile?country=IN®ion=IN&style=46&size=1&x=296223&y=176608&z=19&scale=1&lang=en&v=2204054&poi=1&accessKey=1649243787_2102081627305478489_%2F_hIz9LjsZkMj6NE7y%2BimXS9vFQbxfjLBClZR7yqyFtsE%3D&emphasis=standard&tint=light 346 | 347 | req_url = f"https://cdn{cdnLevel}.apple-mapkit.com/ti/tile?country=US®ion=US&style=46&size=1&x={xTile}&y={yTile}&z={self.zoom}&scale=1&lang=en&v={env_key}4&poi=1{self.ac_key}&emphasis=standard&tint=light" 348 | try: 349 | # image and mask retrieval 350 | # For the roads data 351 | if self.verbose: 352 | print(req_url) 353 | r = requests.get(req_url, headers= headers) 354 | with open(file_name_road, 'wb') as fh: 355 | fh.write(r.content) 356 | if imghdr.what(file_name_road) == 'png': 357 | if self.verbose: 358 | print(file_name_road,"PNG") 359 | break # Success 360 | else: 361 | os.remove(file_name_road) 362 | if self.verbose: 363 | print(file_name_road,"NOT PNG") 364 | except Exception as e: #pylint: disable= broad-except 365 | if self.verbose: 366 | print(e) 367 | 368 | def download(self, getMasks:bool= False, latLonResolution:float= 0.0005, **kwargs): 369 | """ 370 | Downloads the tiles as initialized. 371 | 372 | Parameters 373 | -------------------------------- 374 | 375 | getMasks:bool (default= False) 376 | Download the road PNG mask tile if true 377 | 378 | latLonResolution:float (default= 0.0005) 379 | The step size to use when creating tiles 380 | 381 | Also accepts kwargs for `get_img`. 382 | """ 383 | self._getMasks = bool(getMasks) 384 | min_lat, max_lat = self._getLatBounds() 385 | min_lon, max_lon = self._getLonBounds() 386 | if (max_lat - min_lat <= latLonResolution) or (max_lon - min_lon <= latLonResolution): 387 | # If we fail this check, then our arange will return no 388 | # results and we'll fetch nothing 389 | raise ValueError(f"Latitude and longitude bounds must be separated by at least the latLonResolution (currently {latLonResolution}). Either shrink the resolution value or increase the separation of your minimum/maximum latitude and longitude.") 390 | 391 | URL_ALL = [] 392 | for i in tqdm(np.arange(min_lat, max_lat, latLonResolution)): 393 | tp = None 394 | for j in np.arange(min_lon, max_lon, latLonResolution): 395 | URL_ALL.append(self.make_url(i,j)) 396 | if self.verbose: 397 | print("ALL URL CREATED! ...") 398 | global LOCK_VAR, UNLOCK_VAR, LOCKING_LIMIT 399 | if LOCK_VAR == 0: 400 | if self.verbose: 401 | print("LOCKING") 402 | LOCK_VAR = 1 403 | UNLOCK_VAR = 0 404 | tp = ThreadPool(LOCKING_LIMIT) 405 | tp.imap_unordered(lambda x: self.get_img(x, **kwargs), URL_ALL) #pylint: disable= unnecessary-lambda #cSpell:words imap 406 | tp.close() 407 | # SEMAPHORE KINDA THINGIE 408 | if UNLOCK_VAR >= LOCKING_LIMIT and tp is not None: 409 | # If we have too many threads running, explicitly call 410 | # a wait on the threads until the most recent 411 | # process has cleared. As a practical matter, this will 412 | # clear _several_ threads and keep up performance 413 | tp.join() 414 | -------------------------------------------------------------------------------- /jimutmap/jimutmap_1.py: -------------------------------------------------------------------------------- 1 | # ======================================================== 2 | # This program fetches tiles from satellites.pro for free. 3 | # OPEN SOURCED UNDER GPL-V3.0. 4 | # Author : Jimut Bahan Pal | jimutbahanpal@yahoo.com 5 | # Project Website: https://github.com/Jimut123/jimutmap 6 | # pylint: disable = global-statement 7 | # cSpell: words imghdr, tqdm, asinh, jimut, bahan 8 | # ======================================================== 9 | 10 | import ssl 11 | import os 12 | import re 13 | import time 14 | import math 15 | import urllib.parse 16 | import requests 17 | import numpy as np 18 | import datetime as dt 19 | from tqdm import tqdm 20 | import multiprocessing 21 | from typing import Tuple 22 | from os.path import join, exists, normpath, relpath 23 | from multiprocessing.pool import ThreadPool 24 | 25 | from selenium.webdriver.common.by import By 26 | from selenium.webdriver.support.ui import WebDriverWait 27 | from selenium.webdriver.support import expected_conditions as EC 28 | from selenium.common.exceptions import TimeoutException 29 | 30 | try: 31 | import undetected_chromedriver as uc 32 | except ImportError: 33 | print("Install: pip install undetected-chromedriver") 34 | exit() 35 | 36 | try: 37 | from PIL import Image, UnidentifiedImageError 38 | except ImportError: 39 | print("Install: pip install Pillow") 40 | exit() 41 | 42 | ctx = ssl.create_default_context() 43 | ctx.check_hostname = False 44 | ctx.verify_mode = ssl.CERT_NONE 45 | 46 | headers = { 47 | 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36' 48 | } 49 | 50 | class api: 51 | def __init__(self, min_lat_deg:float, max_lat_deg:float, min_lon_deg:float, max_lon_deg:float, zoom=19, ac_key:str=None, verbose:bool=False, threads_:int=4, container_dir:str=""): 52 | """ 53 | Parameters 54 | ------------------------------------- 55 | 56 | min_lat_deg: float 57 | max_lat_deg: float 58 | min_lon_deg: float 59 | max_lon_deg: float 60 | 61 | zoom: int 62 | Zoom level. Between 1 and 20. 63 | 64 | ac_key:str (default= None) 65 | Access key to Apple Maps. If not provided, will use a headless Chrome instance to fetch a session key. 66 | 67 | verbose:bool (default= False) 68 | Helpful debugging output 69 | 70 | threads_: int (default= 4) 71 | Thread limit for process. Max depending on CPU cores 72 | 73 | container_dir:str (default= "") 74 | When downloading images, place them in this directory. 75 | It will be created if it does not exist. 76 | """ 77 | self._acKey = None 78 | self._containerDir = "" 79 | self.verbose = bool(verbose) 80 | 81 | if ac_key is None: 82 | self._getAPIKey() 83 | else: 84 | self.ac_key = ac_key 85 | 86 | self.set_bounds(min_lat_deg, max_lat_deg, min_lon_deg, max_lon_deg) 87 | self.zoom = zoom 88 | self.threads = min(threads_, multiprocessing.cpu_count()) 89 | self._getMasks = True 90 | self.container_dir = container_dir 91 | 92 | @property 93 | def container_dir(self): 94 | return self._containerDir 95 | 96 | @container_dir.setter 97 | def container_dir(self, newDir): 98 | try: 99 | if isinstance(newDir, str) and len(newDir) > 0: 100 | newDir = normpath(relpath(newDir)) 101 | if not exists(newDir): 102 | os.makedirs(newDir) 103 | self._containerDir = newDir 104 | except Exception: 105 | self._containerDir = "" 106 | 107 | def set_bounds(self, min_lat_deg, max_lat_deg, min_lon_deg, max_lon_deg): 108 | assert -90 < min_lat_deg < 90 and -90 < max_lat_deg < 90 109 | assert min_lat_deg < max_lat_deg 110 | assert -180 < min_lon_deg < 180 and -180 < max_lon_deg < 180 111 | assert min_lon_deg < max_lon_deg 112 | self.min_lat_deg = float(min_lat_deg) 113 | self.max_lat_deg = float(max_lat_deg) 114 | self.min_lon_deg = float(min_lon_deg) 115 | self.max_lon_deg = float(max_lon_deg) 116 | 117 | def _getLatBounds(self): 118 | return self.min_lat_deg, self.max_lat_deg 119 | 120 | def _getLonBounds(self): 121 | return self.min_lon_deg, self.max_lon_deg 122 | 123 | @property 124 | def ac_key(self): 125 | return self._acKey 126 | 127 | @ac_key.setter 128 | def ac_key(self, newACKey): 129 | try: 130 | if 'accessKey=' in newACKey: 131 | newACKey = newACKey.split('accessKey=')[1] 132 | self._acKey = f"&accessKey={newACKey}" 133 | except (AttributeError, TypeError): 134 | self._acKey = None 135 | if newACKey is not None: 136 | raise ValueError("Invalid AccessKey string") 137 | 138 | def _create_fresh_options(self): 139 | options = uc.ChromeOptions() 140 | options.add_argument("--no-sandbox") 141 | options.add_argument("--disable-dev-shm-usage") 142 | options.add_argument("--disable-gpu") 143 | options.add_argument("--window-size=1920,1080") 144 | options.add_argument("--disable-web-security") 145 | options.add_argument("--disable-features=VizDisplayCompositor") 146 | options.add_argument("--ignore-certificate-errors") 147 | options.add_argument("--ignore-ssl-errors") 148 | options.add_argument("--allow-running-insecure-content") 149 | 150 | prefs = { 151 | "profile.default_content_setting_values": { 152 | "notifications": 2, 153 | "media_stream": 2, 154 | } 155 | } 156 | options.add_experimental_option("prefs", prefs) 157 | return options 158 | 159 | def _getAPIKey(self, timeout: float = 60): 160 | driver = None 161 | 162 | initialization_methods = [ 163 | lambda: uc.Chrome(options=self._create_fresh_options()), 164 | lambda: uc.Chrome(options=self._create_fresh_options(), use_subprocess=True), 165 | lambda: uc.Chrome(options=self._create_fresh_options(), version_main=133), 166 | lambda: uc.Chrome(options=self._create_fresh_options(), version_main=132), 167 | lambda: uc.Chrome(options=self._create_fresh_options(), version_main=134), 168 | lambda: uc.Chrome(options=self._create_fresh_options(), driver_executable_path=None), 169 | ] 170 | 171 | for i, method in enumerate(initialization_methods): 172 | try: 173 | driver = method() 174 | break 175 | except Exception as e: 176 | continue 177 | 178 | if driver is None: 179 | raise Exception("Could not initialize Chrome") 180 | 181 | try: 182 | driver.get("https://satellites.pro/USA_map#37.405074,-94.284668,5") 183 | time.sleep(8) 184 | 185 | driver.execute_script(""" 186 | window.capturedRequests = []; 187 | window.accessKeyExtracted = false; 188 | 189 | function captureURL(url) { 190 | if (url && typeof url === 'string' && 191 | (url.includes('sat-cdn1.apple-mapkit.com/tile') || 192 | url.includes('sat-cdn2.apple-mapkit.com/tile') || 193 | url.includes('sat-cdn3.apple-mapkit.com/tile') || 194 | url.includes('sat-cdn4.apple-mapkit.com/tile')) && 195 | url.includes('accessKey=') && 196 | !window.capturedRequests.includes(url)) { 197 | window.capturedRequests.push(url); 198 | return true; 199 | } 200 | return false; 201 | } 202 | 203 | const originalFetch = window.fetch; 204 | window.fetch = function(...args) { 205 | captureURL(args[0]); 206 | return originalFetch.apply(this, args); 207 | }; 208 | 209 | const originalXHROpen = XMLHttpRequest.prototype.open; 210 | XMLHttpRequest.prototype.open = function(method, url) { 211 | captureURL(url); 212 | return originalXHROpen.apply(this, arguments); 213 | }; 214 | 215 | const observer = new MutationObserver(function(mutations) { 216 | mutations.forEach(function(mutation) { 217 | mutation.addedNodes.forEach(function(node) { 218 | if (node.tagName === 'IMG' && node.src) { 219 | captureURL(node.src); 220 | } 221 | }); 222 | }); 223 | }); 224 | 225 | observer.observe(document.body, { 226 | childList: true, 227 | subtree: true 228 | }); 229 | """) 230 | 231 | strategies = [ 232 | self._zoom_strategy, 233 | self._pan_strategy, 234 | self._click_strategy, 235 | self._scroll_strategy 236 | ] 237 | 238 | for strategy in strategies: 239 | try: 240 | key = strategy(driver) 241 | if key: 242 | return key 243 | except: 244 | continue 245 | 246 | captured_requests = driver.execute_script("return window.capturedRequests;") 247 | for url in captured_requests: 248 | key = self._extract_access_key(url) 249 | if key: 250 | return key 251 | 252 | raise ValueError("Could not extract API key") 253 | 254 | finally: 255 | if driver: 256 | try: 257 | driver.quit() 258 | except: 259 | pass 260 | 261 | def _extract_access_key(self, url): 262 | if 'accessKey=' in url and ('sat-cdn' in url and 'apple-mapkit.com/tile' in url): 263 | match = re.search(r'accessKey=([^&\s]+)', url) 264 | if match: 265 | key = urllib.parse.unquote(match.group(1)) 266 | if len(key) > 10: 267 | self.ac_key = key 268 | return key 269 | return None 270 | 271 | def _zoom_strategy(self, driver): 272 | try: 273 | zoom_button = WebDriverWait(driver, 10).until( 274 | EC.element_to_be_clickable((By.CSS_SELECTOR, "a.leaflet-control-zoom-in")) 275 | ) 276 | for _ in range(7): 277 | zoom_button.click() 278 | time.sleep(2) 279 | 280 | captured_requests = driver.execute_script("return window.capturedRequests;") 281 | for url in captured_requests: 282 | key = self._extract_access_key(url) 283 | if key: 284 | return key 285 | except: 286 | pass 287 | return None 288 | 289 | def _pan_strategy(self, driver): 290 | try: 291 | actions = [ 292 | "window.scrollBy(-400, 0)", 293 | "window.scrollBy(800, 0)", 294 | "window.scrollBy(-400, -400)", 295 | "window.scrollBy(0, 800)", 296 | ] 297 | 298 | for action in actions: 299 | driver.execute_script(action) 300 | time.sleep(2) 301 | 302 | captured_requests = driver.execute_script("return window.capturedRequests;") 303 | for url in captured_requests: 304 | key = self._extract_access_key(url) 305 | if key: 306 | return key 307 | except: 308 | pass 309 | return None 310 | 311 | def _click_strategy(self, driver): 312 | try: 313 | driver.execute_script(""" 314 | const mapElement = document.querySelector('#map, .leaflet-container, .map-container') || document.body; 315 | const rect = mapElement.getBoundingClientRect(); 316 | const centerX = rect.left + rect.width / 2; 317 | const centerY = rect.top + rect.height / 2; 318 | 319 | const positions = [ 320 | [centerX, centerY], 321 | [centerX - 150, centerY - 150], 322 | [centerX + 150, centerY + 150], 323 | [centerX - 200, centerY], 324 | [centerX + 200, centerY] 325 | ]; 326 | 327 | positions.forEach((pos, index) => { 328 | setTimeout(() => { 329 | const event = new MouseEvent('click', { 330 | view: window, 331 | bubbles: true, 332 | cancelable: true, 333 | clientX: pos[0], 334 | clientY: pos[1] 335 | }); 336 | mapElement.dispatchEvent(event); 337 | }, index * 600); 338 | }); 339 | """) 340 | 341 | time.sleep(4) 342 | 343 | captured_requests = driver.execute_script("return window.capturedRequests;") 344 | for url in captured_requests: 345 | key = self._extract_access_key(url) 346 | if key: 347 | return key 348 | except: 349 | pass 350 | return None 351 | 352 | def _scroll_strategy(self, driver): 353 | try: 354 | driver.execute_script(""" 355 | const mapElement = document.querySelector('#map, .leaflet-container, .map-container') || document.body; 356 | 357 | for (let i = 0; i < 6; i++) { 358 | setTimeout(() => { 359 | const wheelEvent = new WheelEvent('wheel', { 360 | view: window, 361 | bubbles: true, 362 | cancelable: true, 363 | deltaY: i % 2 === 0 ? -120 : 120 364 | }); 365 | mapElement.dispatchEvent(wheelEvent); 366 | }, i * 1200); 367 | } 368 | """) 369 | 370 | time.sleep(8) 371 | 372 | captured_requests = driver.execute_script("return window.capturedRequests;") 373 | for url in captured_requests: 374 | key = self._extract_access_key(url) 375 | if key: 376 | return key 377 | except: 378 | pass 379 | return None 380 | 381 | def ret_xy_tiles(self, lat_deg, lon_deg): 382 | n = 2**self.zoom 383 | xTile = n * ((lon_deg + 180) / 360) 384 | lat_rad = math.radians(lat_deg) 385 | yTile = n * (1 - (math.log(math.tan(lat_rad) + 1/math.cos(lat_rad)) / math.pi)) / 2 386 | return int(xTile), int(yTile) 387 | 388 | def get_img(self, tile_coords: Tuple[int, int], vNumber:int=10221, getMask:bool=None, prefix:str="", _rerun:bool=False): 389 | if isinstance(getMask, bool): 390 | self._getMasks = getMask 391 | 392 | xTile, yTile = tile_coords 393 | file_name = join(self.container_dir, f"{prefix}{xTile}_{yTile}.jpg") 394 | 395 | if exists(file_name): 396 | return 397 | 398 | try: 399 | req_url = f"https://sat-cdn1.apple-mapkit.com/tile?style=7&size=1&scale=1&z={self.zoom}&x={xTile}&y={yTile}&v={vNumber}{self.ac_key}" 400 | r = requests.get(req_url, headers=headers) 401 | r.raise_for_status() 402 | 403 | if "access denied" in str(r.content).lower(): 404 | if _rerun: 405 | return 406 | self._getAPIKey() 407 | self.get_img(tile_coords, vNumber, getMask, prefix, _rerun=True) 408 | return 409 | 410 | with open(file_name, 'wb') as fh: 411 | fh.write(r.content) 412 | 413 | try: 414 | with Image.open(file_name) as img: 415 | if img.format != 'JPEG': 416 | os.remove(file_name) 417 | except (UnidentifiedImageError, ValueError): 418 | if exists(file_name): 419 | os.remove(file_name) 420 | 421 | except: 422 | pass 423 | 424 | if self._getMasks: 425 | file_name_road = join(self.container_dir, f"{prefix}{xTile}_{yTile}_road.png") 426 | if exists(file_name_road): 427 | return 428 | 429 | env_key = dt.date.today().strftime('%Y%m%d') 430 | for cdenLevel in range(1, 5): 431 | try: 432 | req_url_road = f"https://cdn{cdenLevel}.apple-mapkit.com/ti/tile?country=US&style=46&size=1&x={xTile}&y={yTile}&z={self.zoom}&scale=1&v={env_key}4&poi=1{self.ac_key}" 433 | r_road = requests.get(req_url_road, headers=headers) 434 | r_road.raise_for_status() 435 | 436 | with open(file_name_road, 'wb') as fh: 437 | fh.write(r_road.content) 438 | 439 | try: 440 | with Image.open(file_name_road) as img: 441 | if img.format == 'PNG': 442 | break 443 | os.remove(file_name_road) 444 | except: 445 | if exists(file_name_road): 446 | os.remove(file_name_road) 447 | except: 448 | continue 449 | 450 | def download(self, getMasks:bool=False, latLonResolution:float=0.0005, **kwargs): 451 | self._getMasks = bool(getMasks) 452 | min_lat, max_lat = self._getLatBounds() 453 | min_lon, max_lon = self._getLonBounds() 454 | 455 | lat_steps = np.arange(min_lat, max_lat, latLonResolution) 456 | lon_steps = np.arange(min_lon, max_lon, latLonResolution) 457 | 458 | unique_tiles = set() 459 | for i in lat_steps: 460 | for j in lon_steps: 461 | unique_tiles.add(self.ret_xy_tiles(i, j)) 462 | 463 | tile_list = list(unique_tiles) 464 | 465 | with ThreadPool(self.threads) as pool: 466 | pbar = tqdm(total=len(tile_list), desc="Downloading Tiles") 467 | for _ in pool.imap_unordered(lambda coords: self.get_img(coords, getMask=getMasks, **kwargs), tile_list): 468 | pbar.update(1) 469 | pbar.close() 470 | 471 | if __name__ == '__main__': 472 | min_latitude = 40.781 473 | max_latitude = 40.783 474 | min_longitude = -73.967 475 | max_longitude = -73.964 476 | 477 | mapper = api( 478 | min_lat_deg=min_latitude, 479 | max_lat_deg=max_latitude, 480 | min_lon_deg=min_longitude, 481 | max_lon_deg=max_longitude, 482 | zoom=19, 483 | threads_=8, 484 | container_dir="map_tiles" 485 | ) 486 | 487 | mapper.download(getMasks=True) 488 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2019-20 Jimut Bahan Pal, 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------