`__
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 |
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 |
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 |
--------------------------------------------------------------------------------