-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathstitch-osm-tiles.py
executable file
·3235 lines (2811 loc) · 146 KB
/
stitch-osm-tiles.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# -*- coding: utf8 -*-
#
# Copyright (C) 2017 Vangelis Tasoulas <vangelis@tasoulas.net>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# apt-get install python-progressbar python-pgmagick python-wand
from __future__ import print_function
import os
import sys
import shutil
import re
import argparse
import random
import logging
import subprocess
import datetime
import math
import urllib3
import socket
import multiprocessing
import queue
import threading
import time
import configparser
import http.client as httplib
from collections import OrderedDict
import distutils.spawn
import calendar
import progressbar
import pgmagick
from pgmagick import Image as gmImage
import urllib.parse
import mercantile
__all__ = [
'quick_regexp', 'print_', 'is_number',
'trim_list', 'split_strip', 'xfrange',
'executeCommand', 'LOG', 'stitch_osm_tiles',
'get_physical_cores'
]
# TODO: 1. Add -l -r -t -b for left, right, top, bottom tiles to be downloaded (if the user doesn't want to provide the coordinates)
# 2. Cleanup the code and convert the stitch_osm_tiles into a package.
# 3. Add the Drawable*, prepareStitchForPrint, prepareMaverickTiles and prepareOsmandTiles functions in the stitch_osm_tiles class
# 4. Port to python3
__version__ = '1.0.0'
__author__ = 'Vangelis Tasoulas (vangelis@tasoulas.net)'
LOG = logging.getLogger('default.' + __name__)
# ----------------------------------------------------------------------
# Define the providers and the layer available by each provider in an ordered dict!
# Individual layers can override the following parameters: 'tileservers', 'extension', 'zoom_levels'
PROVIDERS = OrderedDict([
('Mapquest', {
'attribution': 'Tiles Courtesy of MapQuest',
'url': 'http://www.mapquest.com',
# The tile servers that serve the tiles for this provider.
'tile_servers': ['https://{alts:a,b,c,d}.tiles.mapbox.com/v4/{layer}/{z}/{x}/{y}.{ext}?access_token=pk.eyJ1IjoibWFwcXVlc3QiLCJhIjoiY2Q2N2RlMmNhY2NiZTRkMzlmZjJmZDk0NWU0ZGJlNTMifQ.mPRiEubbajc6a5y9ISgydg'],
'extension': 'png', # The default extension support by this provider
'zoom_levels': '0-18', # The zoom levels supported by this provider
'layers': OrderedDict([
('mapquest.streets', {
'desc': 'Default MapQuest Style for US'
}),
('mapquest.satellite', {
'desc': 'Satellite MapQuest Style for US'
}),
('mapquest.dark', {
'desc': 'Dark MapQuest Style for US'
}),
('mapquest.streets-mb', {
'desc': 'Default MapQuest Style for the rest of the world (Non-US)'
}),
('mapquest.satellite-mb', {
'desc': 'Satellite MapQuest Style for the rest of the world (Non-US)'
}),
('mapquest.dark-mb', {
'desc': 'Dark MapQuest Style for the rest of the world (Non-US)'
})
])
}),
('Stamen', {
'attribution': 'Map tiles by Stamen Design, under CC BY 3.0. Data by OpenStreetMap, under ODbL',
'url': 'http://maps.stamen.com',
'tile_servers': ['http://{alts:a,b,c,d}.sm.mapstack.stamen.com/{layer}/{z}/{x}/{y}.{ext}'],
'extension': 'png',
'zoom_levels': '0-18',
'layers': OrderedDict([
('toner', {
'desc': "Toner default"
}),
('toner-hybrid', {'desc': ''}),
('toner-labels', {'desc': ''}),
('toner-lines', {'desc': ''}),
('toner-background', {'desc': ''}),
('toner-lite', {'desc': ''}),
('watercolor', {'desc': ''})
])
}),
('Microsoft', {
'attribution': 'Bing Maps Platform',
'url': 'https://www.bing.com/maps',
# When 'dyn_tile_url' exists, that's an indication that the 'tile_servers'
'dyn_tile_url': True,
# provide a dynGetTileUrl(z, x, y, download_counter) function to find the
# correct URL and not the URL itself!
# That means that the tile_servers must be exec'ed and the function
# dynGetTileUrl has to be called in order to get the correct URL.
'tile_servers': ["""
def eqt(z, x, y):
NUM_CHAR = [ '0', '1', '2', '3' ]
tn = list(" " * z)
for i in range(z - 1, -1, -1):
num = (x % 2) | ((y % 2) << 1)
tn[i] = NUM_CHAR[num]
x >>= 1
y >>= 1
return "".join(tn)
def dynGetTileUrl(z, x, y, download_counter):
alts = [0, 1, 2, 3]
alt = download_counter % len(alts)
return "http://{layer}{}.ortho.tiles.virtualearth.net/tiles/{layer}{}.{ext}?g=45".format(alt, eqt(z, x, y))
"""],
'extension': 'png',
'zoom_levels': '1-19',
'layers': OrderedDict([
('maps', {
'name': 'r',
'desc': 'Bing Maps'
}),
('hybrid', {
'name': 'h',
'desc': 'Bing Maps Hybrid',
'extension': 'jpg'
}),
('aerial', {
'name': 'a',
'desc': 'Bing Maps Earth',
'extension': 'jpg'
})
])
}),
('Eniro', {
'attribution': 'Eniro',
'url': 'http://map.eniro.com',
'dyn_tile_url': True,
'tile_servers': ["""
def dynGetTileUrl(z, x, y, download_counter):
return "http://map.eniro.com/geowebcache/service/tms1.0.0/{layer}/{}/{}/{}.{ext}".format(z, x, ((1 << z) - 1 - y))
"""],
'extension':'png',
'zoom_levels':'2-20',
'layers': OrderedDict([
('map', {
'desc': 'Eniro Map (NO,SE,FI,DK,PL)'
}),
('aerial', {
'desc': 'Eniro Aerial (NO,SE,DK)',
'extension': 'jpeg'
}),
('nautical', {
'desc': 'Eniro Nautical (NO,SE)'
})
])
}),
('Finn', {
'attribution': 'finn',
'url': 'https://kart.finn.no/',
# Strange, but finn serves jpeg files with the png extension :D
'tile_servers': ['https://maptiles.finncdn.no/tileService/1.0.3/{layer}/{z}/{x}/{y}.png'],
'extension':'jpg',
'zoom_levels':'1-20',
'layers': OrderedDict([
('norortho', {
'desc': 'Finn aerial map'
}),
('norhybrid', {
'desc': 'Finn aerial with labels',
})
])
}),
('Avinor', {
'attribution': 'Avinor',
'url': 'https://avinor.maps.arcgis.com/apps/webappviewer/index.html?id=bb768577bbaa4a3d8bee9d467480acb6',
'dyn_tile_url': True,
'tile_servers': ["""
def dynGetTileUrl(z, x, y, download_counter):
url = 'https://avigis.avinor.no/agsmap/rest/services/ICAO_500000/MapServer/export?'
# User mercantile to find the bounding box
bbox = mercantile.bounds(x, y, z)
params = {
"dpi": 96,
"transparent": "true",
"format": "png32",
"layers": "show:3",
"bbox": "{},{},{},{}".format(bbox.west, bbox.south, bbox.east, bbox.north),
"bboxSR": 4326, # WGS 84: https://developers.arcgis.com/rest/services-reference/enterprise/export-image.htm
"imageSR": 3857, # Web Mercator (3857): https://developers.arcgis.com/rest/services-reference/enterprise/export-image.htm
"size": "256,256",
"f": "image",
}
return url + urllib.parse.urlencode(params)
"""],
'extension':'png',
'zoom_levels':'2-12',
'layers': OrderedDict([
('icao', {
'desc': 'Norway Aeronautical chart ICAO 500.000'
})
])
}),
('Varsom', {
'attribution': 'varsom',
'url': 'https://www.varsom.no',
'dyn_tile_url': True,
'tile_servers': ["""
def dynGetTileUrl(z, x, y, download_counter):
# Seems like some of the NVE download servers can't offer all the tiles (or takes too long
# to server them), but often choosing a different server serves the tile immediately.
# To get the chance to pick a different server for a given tile, apply a randint to the
# download_counter.
server = ((download_counter + random.randint(0, 3)) % 3) + 2
server = "" if server == 1 else server
# Valid servers are:
# gis.nve.no <- This one is the most terrible. Avoid it!
# gis2.nve.no
# gis3.nve.no
# gis4.nve.no
url = 'https://gis{}.nve.no/arcgis/rest/services/wmts/KastWMTS/MapServer/export?'.format(server)
# User mercantile to find the bounding box
bbox = mercantile.bounds(x, y, z)
params = {
"bbox": "{},{},{},{}".format(bbox.west, bbox.south, bbox.east, bbox.north),
"bboxSR": 4326,
"bbSR": 4326,
"imageSR": 3857,
"f": "image",
"size": "256,256",
"transparent": "true",
}
return url + urllib.parse.urlencode(params)
"""],
'extension':'png',
'zoom_levels':'1-18',
'layers': OrderedDict([
('kast', {
'desc': 'Avalanche risk maps for Norway. Note this is an overlay map.'
})
])
}),
# For more maps of Norway take a look here: https://kartkatalog.geonorge.no
# and here: https://www.norgeskart.no
('Statkart', {
'attribution': 'http://www.kartverket.no/kart/gratis-kartdata/wms-tjenester/',
'url': 'http://www.kartverket.no/data/lage-kart-pa-nett/',
'tile_servers': ['http://opencache.statkart.no/gatekeeper/gk/gk.open_gmaps?layers={layer}&zoom={z}&x={x}&y={y}'],
'extension': 'png',
'zoom_levels': '0-17',
'layers': OrderedDict([
('topo4', {
'desc': 'High Quality Topo Maps of Norway'
}),
('topo4graatone', {
'desc': 'Same as topo4 in Grayscale'
}),
('toporaster3', {
'desc': 'High Quality TopoRaster Maps of Norway'
}),
('europa', {
'desc': 'Main Roads of Whole Europe'
}),
('norges_grunnkart', {
'desc': 'High Quality Base Maps of Norway',
}),
('norges_grunnkart_graatone', {
'desc': 'High Quality Base Maps of Norway in Grayscale'
}),
('sjo_hovedkart2', {
'desc': 'Sea Map of Norway'
}),
('sjokartraster', {
'desc': 'Sea Raster Map of Norway'
}),
# The following URL Works with WMTS
# ('Geocache_UTM33_WGS84', {
# 'desc': '',
# 'tile_servers': ['http://services.geodataonline.no/arcgis/rest/services/Geocache_UTM33_WGS84/GeocacheBasis/MapServer/tile/{z}/{y}/{x}'],
# 'extension': 'jpg'
# }),
('egk', {
'desc': 'Simple map of Norway'
}),
('norgeskart_bakgrunn', {
'desc': 'High quality topographic maps of Norway with many details. Probably the best maps you can find for Norway.',
'zoom_levels': '0-18'
}),
('ut_topo_light', {
'desc': 'DNT Hiking Maps with Contour Lines for Norway',
'tile_servers': ['https://tilesprod.ut.no/tilestache/{layer}/{z}/{x}/{y}.{ext}'],
'extension': 'jpg',
'zoom_levels': '0-16'
}),
('svalbard_topo', {
'attribution': 'finn.no',
'desc': 'Svalbard topographic maps',
'tile_servers': ['https://maptiles{alts:1,2,3,4}.finncdn.no/tileService/1.0.3/normap/{z}/{x}/{y}.png'],
'extension': 'png',
'zoom_levels': '0-17'
}),
])
}),
('topoguide', {
'attribution': 'topoguide',
'url': 'http://www.topoguide.gr',
'dyn_tile_url': False,
'tile_servers': ['http://5.135.161.95/wms/wmsolv3xyz2.php?z={z}&x={x}&y={y}&t={layer}'],
'extension':'png',
'zoom_levels':'7-18',
'layers': OrderedDict([
('gr', {
'name': '15',
'desc': 'Topomaps for Greece with Greek labels'
}),
('en', {
'name': '16',
'desc': 'Topomaps for Greece with English labels'
})
])
}),
# In Nokia maps you can change the ppi=72 to 72, 250, 320 and 500
# And the value "512" is the width/height of each tile and you can change it to either 128, 256 or 512
('Nokia', {
'attribution': 'Nokia maps',
'url': 'https://wego.here.com',
'tile_servers': ['https://{alts:1,2,3,4}.base.maps.api.here.com/maptile/2.1/maptile/afd6f70912/{layer}/{z}/{x}/{y}/256/png8?app_id=xWVIueSv6JL0aJ5xqTxb&app_code=djPZyynKsbTjIUDOBcHZ2g&lg=eng&ppi=250'],
'extension': 'png',
'zoom_levels': '2-18',
'layers': OrderedDict([
('classic-256', {
'name': 'normal.day',
'desc': 'Classic map 256x256 pixels per tile'
}),
('classic-512', {
'name': 'normal.day',
'tile_servers': ['https://{alts:1,2,3,4}.base.maps.api.here.com/maptile/2.1/maptile/afd6f70912/{layer}/{z}/{x}/{y}/512/png8?app_id=xWVIueSv6JL0aJ5xqTxb&app_code=djPZyynKsbTjIUDOBcHZ2g&lg=eng&ppi=250'],
'desc': 'Classic map 512x512 pixels per tile (same number of tiles per zoom level with classic-256, but higher resolution)'
}),
('aerialhybrid-256', {
'name': 'hybrid.day',
'tile_servers': ['https://{alts:1,2,3,4}.aerial.maps.api.here.com/maptile/2.1/maptile/afd6f70912/{layer}/{z}/{x}/{y}/256/png8?app_id=xWVIueSv6JL0aJ5xqTxb&app_code=djPZyynKsbTjIUDOBcHZ2g&lg=eng&ppi=250'],
'desc': 'Aerial map 256x256 pixels per tile'
}),
('aerialhybrid-512', {
'name': 'hybrid.day',
'tile_servers': ['https://{alts:1,2,3,4}.aerial.maps.api.here.com/maptile/2.1/maptile/afd6f70912/{layer}/{z}/{x}/{y}/512/png8?app_id=xWVIueSv6JL0aJ5xqTxb&app_code=djPZyynKsbTjIUDOBcHZ2g&lg=eng&ppi=250'],
'desc': 'Aerial map 512x512 pixels per tile (same number of tiles per zoom level with aerialhybrid-256, but higher resolution)'
})
])
}),
('ArcGIS', {
'attribution': '',
'url': 'http://www.arcgis.com/',
'tile_servers': ['http://server.arcgisonline.com/ArcGIS/rest/services/{layer}/MapServer/tile/{z}/{y}/{x}'],
'extension': 'jpg',
'zoom_levels': '0-17',
'layers': OrderedDict([
('World_Topo_Map', {
'desc': 'World Topo Map'
}),
('World_Street_Map', {
'desc': 'World Street Map'
})
])
}),
('Misc', {
'attribution': '',
'layers': OrderedDict([
('opentopomap', {
'attribution': 'OpenTopoMap',
'url': 'https://opentopomap.org',
'tile_servers': ['https://opentopomap.org/{z}/{x}/{y}.{ext}'],
'extension': 'png',
'zoom_levels': '1-17',
'desc': 'Topo Map with contours from OpenStreetMap data'
}),
('overlay_hiking_paths', {
'attribution': '',
'url': 'https://hiking.waymarkedtrails.org',
'tile_servers': ['https://tile.waymarkedtrails.org/hiking/{z}/{x}/{y}.{ext}'],
'extension': 'png',
'zoom_levels': '1-17',
'desc': 'Waymarkedtrails hiking paths (ex Lonvia hiking)'
})
])
}),
])
# ----------------------------------------------------------------------
def error_and_exit(message):
"""
Prints the "message" and exits with status 1
"""
LOG.error("\nERROR:\n" + message + "\n")
exit(1)
# ----------------------------------------------------------------------
def print_(value_to_be_printed, print_indent=0, spaces_per_indent=4, endl="\n"):
"""
This function, among anything else, it will print dictionaries (even nested ones) in a good looking way
# value_to_be_printed: The only needed argument and it is the
text/number/dictionary to be printed
# print_indent: indentation for the printed text (it is used for
nice looking dictionary prints) (default is 0)
# spaces_per_indent: Defines the number of spaces per indent (default is 4)
# endl: Defines the end of line character (default is \n)
More info here:
http://stackoverflow.com/questions/19473085/create-a-nested-dictionary-for-a-word-python?answertab=active#tab-top
"""
if isinstance(value_to_be_printed, dict):
for key, value in value_to_be_printed.items():
if isinstance(value, dict):
print_('{0}{1!r}:'.format(
print_indent * spaces_per_indent * ' ', key))
print_(value, print_indent + 1)
else:
print_('{0}{1!r}: {2}'.format(print_indent *
spaces_per_indent * ' ', key, value))
else:
string = ('{0}{1}{2}'.format(print_indent *
spaces_per_indent * ' ', value_to_be_printed, endl))
sys.stdout.write(string)
# ----------------------------------------------------------------------
def trim_list(string_list):
"""
This function will parse all the elements from a list of strings (string_list),
and trim leading or trailing white spaces and/or new line characters
"""
return [s.strip() for s in string_list]
# ----------------------------------------------------------------------
def split_strip(string, separator=","):
"""
splits the given string in 'sep' and trims the whitespaces or new lines
returns a list of the splitted stripped strings
If the 'string' is not a string, -1 will be returned
"""
if isinstance(string, str):
return trim_list(string.split(separator))
return -1
# ----------------------------------------------------------------------
def xfrange(start=None, stop=None, step=None):
""" xfrange([start,] stop[, step]) -> generator of floats """
if step is None:
step = 1.0
if stop is None and start != None:
stop = start
start = 0.0
if stop is None and start is None:
print("At least 'stop' should be passed to this function")
raise KeyError
if is_number(start) and is_number(stop) and is_number(step):
while start < stop:
# yield returns a generator object
yield start
start += float(step)
else:
print("Non numeric value. Only numeric values are accepted.")
raise KeyError
# ----------------------------------------------------------------------
def is_number(s, is_int=False):
"""
If is_int=True, returns True if 's' is a valid integer number (positive or negative)
If is_int=False, returns True if 's' is a valid float number (positive or negative)
Returns False if it is not a valid number
"""
try:
if is_int:
int(s)
else:
float(s)
return True
except ValueError:
return False
# ----------------------------------------------------------------------
def get_physical_cores():
"""
Returns the number of actual physical cores, in contrast to
multiprocessing.cpu_count() that return the number of cpu threads.
If hyperthreading is enabled, multiprocessing.cpu_count() will return
twice as many cores than what our system actually has
"""
if sys.platform == "win32":
# If it is windows, use the multiprocessing because
# I don't have windows to test the implementation.
return multiprocessing.cpu_count()
elif sys.platform == "darwin":
# If it is OSX, use the multiprocessing because
# I don't have a MAC to test the implementation.
return multiprocessing.cpu_count()
elif sys.platform.startswith('linux'):
# If it is posix based OS, read /proc/cpuinfo (Linux falls under
# this case and that's the only supported posix OS for the moment)
phys_ids_encountered = []
total_cores = 0
cmd = executeCommand(
['grep', 'physical id\|cpu cores', '/proc/cpuinfo'])
r = quick_regexp()
for line_no in range(len(cmd.getStdout())):
if r.search('physical id\s+:\s+(\d+)', cmd.getStdout()[line_no]):
if not r.groups[0] in phys_ids_encountered:
phys_ids_encountered.append(r.groups[0])
line_no += 1
r.search('cpu cores\s+:\s+(\d+)', cmd.getStdout()[line_no])
total_cores += int(r.groups[0])
else:
line_no += 2
return total_cores
# ----------------------------------------------------------------------
def instantiate_threadpool(threadpool_name, threads, worker, args):
"""
Instantiates a threadpool with 'threads' number 'worker' threads
with the given 'args'.
args must be a tuple.
"""
for i in range(threads):
thread_worker = threading.Thread(target=worker, args=(args))
thread_worker.name = '{}-{}'.format(threadpool_name, i)
LOG.debug("Starting thread worker: {}".format(thread_worker.name))
thread_worker.daemon = True
thread_worker.start()
# ----------------------------------------------------------------------
class quick_regexp(object):
"""
Quick regular expression class, which can be used directly in if() statements in a perl-like fashion.
#### Sample code ####
r = quick_regexp()
if(r.search('pattern (test) (123)', string)):
print(r.groups[0]) # Prints 'test'
print(r.groups[1]) # Prints '123'
"""
# ----------------------------------------------------------------------
def __init__(self):
self.groups = None
self.matched = False
# ----------------------------------------------------------------------
def search(self, pattern, string, flags=0):
match = re.search(pattern, string, flags)
if match:
self.matched = True
if match.groups():
self.groups = re.search(pattern, string, flags).groups()
else:
self.groups = True
else:
self.matched = False
self.groups = None
return self.matched
# ----------------------------------------------------------------------
class executeCommand(object):
"""
Custom class to execute a shell command and
provide to the user, access to the returned
values
"""
def __init__(self, args=None, isUtc=True):
self._stdout = None
self._stderr = None
self._returncode = None
self._timeStartedExecution = None
self._timeFinishedExecution = None
self._args = args
self.isUtc = isUtc
if self._args != None:
self.execute()
def execute(self, args=None):
if args != None:
self._args = args
if self._args != None:
if self.isUtc:
self._timeStartedExecution = datetime.datetime.utcnow()
else:
self._timeStartedExecution = datetime.datetime.now()
p = subprocess.Popen(
self._args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
if self.isUtc:
self._timeFinishedExecution = datetime.datetime.utcnow()
else:
self._timeFinishedExecution = datetime.datetime.now()
self._stdout, self._stderr = p.communicate()
self._returncode = p.returncode
return 1
else:
self._stdout = None
self._stderr = None
self._returncode = None
return 0
def getStdout(self, getList=True, decode=True):
"""
Get the standard output of the executed command
getList: If True, return a list of lines.
Otherwise, return the result as one string
"""
if getList and not decode:
raise BaseException("decode can only be True when getList == True")
if getList:
return self._stdout.decode('utf-8').split('\n')
if decode:
return self._stdout.decode('utf-8')
else:
return self._stdout
def getStderr(self, getList=True, decode=True):
"""
Get the error output of the executed command
getList: If True, return a list of lines.
Otherwise, return the result as one string
"""
if getList and not decode:
raise BaseException("decode can only be True when getList == True")
if getList:
return self._stderr.decode('utf-8').split('\n')
if decode:
return self._stderr.decode('utf-8')
else:
return self._stderr
def getReturnCode(self):
"""
Get the exit/return status of the command
"""
return self._returncode
def getTimeStartedExecution(self, inMicroseconds=False):
"""
Get the time when the execution started
"""
if isinstance(self._timeStartedExecution, datetime.datetime):
if inMicroseconds:
return int(str(calendar.timegm(self._timeStartedExecution.timetuple())) +
str(self._timeStartedExecution.strftime("%f")))
return self._timeStartedExecution
def getTimeFinishedExecution(self, inMicroseconds=False):
"""
Get the time when the execution finished
"""
if isinstance(self._timeFinishedExecution, datetime.datetime):
if inMicroseconds:
return int(str(calendar.timegm(self._timeFinishedExecution.timetuple())) +
str(self._timeFinishedExecution.strftime("%f")))
return self._timeFinishedExecution
# ----------------------------------------------------------------------
########################################
###### Configure logging behavior ######
########################################
# No need to change anything here
def _configureLogging(loglevel):
"""
Configures the default logger.
If the log level is set to NOTSET (0), the
logging is disabled
# More info here: https://docs.python.org/2/howto/logging.html
"""
numeric_log_level = getattr(logging, loglevel.upper(), None)
try:
if not isinstance(numeric_log_level, int):
raise ValueError()
except ValueError:
error_and_exit('Invalid log level: %s\n'
'\tLog level must be set to one of the following:\n'
'\t CRITICAL <- Least verbose\n'
'\t ERROR\n'
'\t WARNING\n'
'\t INFO\n'
'\t DEBUG <- Most verbose' % loglevel)
defaultLogger = logging.getLogger('default')
# If numeric_log_level == 0 (NOTSET), disable logging.
if not numeric_log_level:
numeric_log_level = 1000
defaultLogger.setLevel(numeric_log_level)
logFormatter = logging.Formatter()
defaultHandler = logging.StreamHandler()
defaultHandler.setFormatter(logFormatter)
defaultLogger.addHandler(defaultHandler)
#######################################################
###### Add command line options in this function ######
#######################################################
# Add the user defined command line arguments in this function
class SmartFormatter(argparse.HelpFormatter):
def _split_lines(self, text, width):
# this is the RawTextHelpFormatter._split_lines
if text.startswith('R|'):
return text[2:].splitlines()
return argparse.HelpFormatter._split_lines(self, text, width)
# ----------------------------------------------------------------------
def _command_Line_Options():
"""
Define the accepted command line arguments in this function
Read the documentation of argparse for more advanced command line
argument parsing examples
http://docs.python.org/2/library/argparse.html
"""
parser = argparse.ArgumentParser(
description='OSM Tile Stitcher' + " version " + __version__, formatter_class=SmartFormatter)
parser.add_argument("-v", "--version",
action="version", default=argparse.SUPPRESS,
version=__version__,
help="show program's version number and exit")
loggingGroupOpts = parser.add_argument_group(
'Logging Options', 'List of optional logging options')
loggingGroupOpts.add_argument("-q", "--quiet",
action="store_true",
default=False,
dest="isQuiet",
help="Disable logging in the console. Nothing will be printed.")
loggingGroupOpts.add_argument("--log-level",
action="store",
default="INFO",
dest="loglevel",
metavar="LOG_LEVEL",
help="LOG_LEVEL might be set to: CRITICAL, ERROR, WARNING, INFO, DEBUG. (Default: INFO)")
parser.add_argument("-p", "--project-folder",
action="store",
default='maps_project',
dest="project_folder",
help="Choose a project name. The downloaded data and stitching operations will all be made under this folder.\n"
"Default project folder: 'maps_project'")
parser.add_argument("-z", "--zoom-level",
action="store",
dest="zoom_level",
required=True,
help="The tile zoom level for download. Accepts an integer or a range like '1-10' or '1,4,7-9', for downloading multiple zoom levels for the given coordinates.")
parser.add_argument("-w", "--long1",
action="store",
type=float,
dest="long1",
metavar="W_DEGREES",
required=True,
help="The western (W) longtitude of the bounding box for tile downloading. Accepted values: -180 to 179.999.")
parser.add_argument("-e", "--long2",
action="store",
type=float,
dest="long2",
metavar="E_DEGREES",
required=True,
help="The eastern (E) longtitude of the bounding box for tile downloading. Accepted values: -180 to 179.999.")
parser.add_argument("-n", "--lat1",
action="store",
type=float,
dest="lat1",
metavar="N_DEGREES",
required=True,
help="The northern (N) latitude of the bounding box for tile downloading. Accepted values: -85.05112 to 85.05113.")
parser.add_argument("-s", "--lat2",
action="store",
type=float,
dest="lat2",
metavar="S_DEGREES",
required=True,
help="The southern (S) latitude of the bounding box for tile downloading. Accepted values: -85.05112 to 85.05113.")
parser.add_argument("-o", "--custom-osm-server",
action="store",
dest="custom_osm_server",
metavar="OSM_SERVER_URL",
help="R|The URL of your private tile server. If the URL\n"
"contains the {z}/{x}/{y} placeholders for\n"
"substitution, these will be substituted with the\n"
"corresponding 'zoom level', 'x' and 'y' tiles during\n"
"downloading. If not, '{z}/{x}/{y}.png' will be appended\n"
"after the end of the provided URL. Example custom URL:\n"
"'http://your.osm.server.com/osm/{z}/{x}/{y}.png?token=12345'")
parser.add_argument("-m", "--max-stitch-size-per-side",
action="store",
type=int,
default=10000,
dest="max_resolution_px",
metavar="PIXELS",
help="The horizontal or vertical resolution of the stitched tiles should not exceed the resolution provided by this option in pixels.\n"
"Default size: 10000 px")
parser.add_argument("--save-tile-format",
action="store",
dest="tile_format",
choices=["png", "jpg", "original"],
default="original",
metavar="IMG_FMT",
help="R|The format to save the downloaded tiles.\n"
" Available choices:\n"
" 'png'\n"
" 'jpg'\n"
" 'original' <- This is the default and it will\n"
" just save the tiles in the format\n"
" provided by the provider.")
parser.add_argument("--save-stitched-tile-format",
action="store",
dest="stitched_tile_format",
choices=["png", "jpg"],
default="png",
metavar="IMG_FMT",
help="R|The format to save the stitched tiles.\n"
" Available choices:\n"
" 'png' (default)\n"
" 'jpg'\n")
parser.add_argument("-r", "--retry-failed",
action="store_true",
dest="retry_failed",
help="When the tiles are downloaded, a log file with the tiles that failed to be downloaded is generated."
" If --retry-failed option is used, after the tiles have been downloaded the script will go through"
" this log file and retry to download the failed tiles until the download is successful.")
parser.add_argument("-d", "--skip-downloading",
action="store_true",
dest="skip_downloading",
help="Skip downloading of the original tiles. Use this option ONLY if you are sure that"
" all of the original tiles for the given coordinates have been downloaded successfully."
" The downloading function is also checking the integrity of the files, so it"
" is always a good idea to NOT skip the downloading. Keep in mind that the"
" downloading function will not re-download already downloaded (cached) tiles,"
" so you can always resume downloads.")
parser.add_argument("-k", "--skip-stitching",
action="store_true",
dest="skip_stitching",
help="Skip the stitching of the original tiles onto large tiles.")
parser.add_argument("-c", "--only-calibrate",
action="store_true",
dest="only_calibrate",
help="When this option is enabled, the script will not download or stitch any tiles. Only OziExplorer calibration files will be generated.")
parser.add_argument("--prepare-printout-maps",
action="store_true",
dest="printout",
help="Generates paper friendly maps with a grid and a scale indicator.")
parser.add_argument("--prepare-tiles-for-software",
action="store",
dest="prep_for_soft",
choices=["maverick", "osmand"],
default=None,
metavar="SOFTWARE",
help="R|Prepare tiles in a format that is accepted by different\n"
"software for offline usage.\n"
" Available choices:\n"
" 'maverick'\n"
" 'osmand'")
parser.add_argument("--download-threads",
action="store",
type=int,
default=10,
metavar="DOWN_THREADS",
dest="download_threads",
help="The downloading of the tiles is threaded to speed up the download significantly."
" This option defines the number of concurrent download threads. Default number of download threads: 10")
parser.add_argument("--stitching-threads",
action="store",
type=int,
default=get_physical_cores(),
metavar="STITCH_THREADS",
dest="stitching_threads",
help="The stitching of the tiles is threaded."
" This option defines the number of concurrent stitching threads. Default number of sitching"
" threads corresponds to the number of available cores in your system: {}".format(get_physical_cores()))
parser.add_argument("-t", "--tile-server-provider",
action="store",
dest="tile_server_provider",
metavar="PROVIDER",
default=list(PROVIDERS.keys())[0],
help="R|Choose one of the predefined tile server providers:\n" + '\n'.join([" * " + s for s in PROVIDERS]))
parser.add_argument("-l", "--tile-server-provider-layer",
action="store",
dest="tile_server_provider_layer",
metavar="LAYER",
help="R|Choose one of the available layers for the chosen\n"
"provider. If none is chosen, the first one will be\n"
"used. Layers per provider:\n" + '\n'.join([" * " + s + '\n' + "\n".join([' - ' + l + ' \t# ' + PROVIDERS[s]['layers'][l]['desc'] for l in PROVIDERS[s]['layers']]) for s in PROVIDERS]))
opts = parser.parse_args()
if opts.isQuiet:
opts.loglevel = "NOTSET"
return opts
##################################################
############### WRITE MAIN PROGRAM ###############
##################################################
# ----------------------------------------------------------------------
def expand_zoom_levels(zoom_levels):
"""
The zoom levels is a string composed of comma separated integers
and ranges of integers designated with hyphens.
This function parses this kind of string and returns an array of
all the zoom levels
"""
provided_zoom_levels = split_strip(zoom_levels)
expanded_zoom_levels = []