-
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathprocessor.py
More file actions
1980 lines (1666 loc) · 73.4 KB
/
processor.py
File metadata and controls
1980 lines (1666 loc) · 73.4 KB
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
import datetime
import gzip
import html
import json
import logging
import re
import sqlite3
import tarfile
import threading
import time
import zipfile
from importlib import resources
from io import BytesIO
from pathlib import Path
from typing import Any
from urllib.parse import urlparse
from pydantic import BaseModel
from schedule import every, run_pending
from zimscraperlib.download import save_large_file
from zimscraperlib.image import convert_image, resize_image
from zimscraperlib.image.conversion import convert_svg2png
from zimscraperlib.image.probing import format_for
from zimscraperlib.typing import Callback
from zimscraperlib.zim import Creator, metadata
from zimscraperlib.zim.dedup import Deduplicator
from zimscraperlib.zim.filesystem import (
validate_file_creatable,
validate_folder_writable,
)
from maps2zim.constants import (
NAME,
VERSION,
)
from maps2zim.context import Context
from maps2zim.download import stream_file
from maps2zim.errors import NoIllustrationFoundError
from maps2zim.tile_filter import TileFilter
from maps2zim.ui import ConfigModel
from maps2zim.zimconfig import ZimConfig
context = Context.get()
logger = context.logger
LOG_EVERY_SECONDS = 60
class FilteringResult(BaseModel):
dedup_ids: set[int] = set()
redirects: list[tuple[str, str]] = []
filtered_tile_count: int = 0
class SearchPlace(BaseModel):
"""A single place for search indexing."""
geoname_id: str
latitude: float
longitude: float
zoom: int
label: str
feature_code: str
country_code: str
class SearchEntry(BaseModel):
"""Entry in places dictionary mapping name to list of places."""
places: list[SearchPlace]
class Processor:
"""Generates ZIMs based on the user's configuration."""
def __init__(self) -> None:
"""Initializes Processor."""
self.stats_items_done = 0
# we add 1 more items to process so that progress is not 100% at the beginning
# when we do not yet know how many items we have to process and so that we can
# increase counter at the beginning of every for loop, not minding about what
# could happen in the loop in terms of exit conditions
self.stats_items_total = 1
# Semaphore for backpressure: limit items in-flight to 100
self._inflight_semaphore = threading.Semaphore(100)
def run(self) -> Path:
"""Generates a zim for a single document.
Returns the path to the generated ZIM.
"""
try:
return self._run_internal()
except Exception:
logger.error(
f"Problem encountered while processing "
f"{context.current_thread_workitem}"
)
raise
def _run_internal(self) -> Path:
logger.setLevel(level=logging.DEBUG if context.debug else logging.INFO)
if (
context.area != "planet" or context.include_poly_urls
) and not context.default_view:
logger.warning(
"You should pass --default-view arg when using a custom --area or "
"--include_poly_urls value(s), so that default map displayed in the UI "
"is nice."
)
self.zim_config = ZimConfig(
file_name=context.file_name,
name=context.name,
title=context.title,
publisher=context.publisher,
creator=context.creator,
description=context.description,
long_description=context.long_description,
tags=context.tags,
secondary_color=context.secondary_color,
)
# initialize all paths, ensuring they are ok for operation
context.output_folder.mkdir(exist_ok=True)
validate_folder_writable(context.output_folder)
context.tmp_folder.mkdir(exist_ok=True)
validate_folder_writable(context.tmp_folder)
logger.info("Generating ZIM")
# create first progress report and and a timer to update every 10 seconds
self._report_progress()
every(10).seconds.do( # pyright: ignore[reportUnknownMemberType]
self._report_progress
)
self.formatted_config = self.zim_config.format(
{
"name": self.zim_config.name,
"period": datetime.date.today().strftime("%Y-%m"),
}
)
zim_file_name = f"{self.formatted_config.file_name}.zim"
zim_path = context.output_folder / zim_file_name
if zim_path.exists():
if context.overwrite_existing_zim:
zim_path.unlink()
else:
logger.error(f" {zim_path} already exists, aborting.")
raise SystemExit(2)
validate_file_creatable(context.output_folder, zim_file_name)
logger.info(f" Writing to: {zim_path}")
logger.debug(f"User-Agent: {context.wm_user_agent}")
creator = Creator(zim_path, "index.html")
if context.zim_workers is not None:
creator.config_nbworkers(context.zim_workers)
logger.info(" Fetching ZIM illustration...")
zim_illustration = self._fetch_zim_illustration()
logger.debug("Configuring metadata")
creator.config_metadata(
metadata.StandardMetadataList(
Name=metadata.NameMetadata(self.formatted_config.name),
Title=metadata.TitleMetadata(self.formatted_config.title),
Publisher=metadata.PublisherMetadata(self.formatted_config.publisher),
Date=metadata.DateMetadata(
datetime.datetime.now(tz=datetime.UTC).date()
),
Creator=metadata.CreatorMetadata(self.formatted_config.creator),
Description=metadata.DescriptionMetadata(
self.formatted_config.description
),
LongDescription=(
metadata.LongDescriptionMetadata(
self.formatted_config.long_description
)
if self.formatted_config.long_description
else None
),
# As of 2024-09-4 all documentation is in English.
Language=metadata.LanguageMetadata(context.language_iso_639_3),
Tags=(
metadata.TagsMetadata(self.formatted_config.tags)
if self.formatted_config.tags
else None
),
Scraper=metadata.ScraperMetadata(f"{NAME} v{VERSION}"),
Illustration_48x48_at_1=metadata.DefaultIllustrationMetadata(
zim_illustration.getvalue()
),
),
)
# Start creator early to detect problems early.
with creator as creator:
try:
self._add_item_for(
creator,
"favicon.ico",
content=self._fetch_favicon_from_illustration(
zim_illustration
).getvalue(),
)
del zim_illustration
self.run_with_creator(creator)
except Exception:
creator.can_finish = False
raise
if creator.can_finish:
logger.info(f"ZIM creation completed, ZIM is at {zim_path}")
else:
logger.error("ZIM creation failed")
# same reason than self.stats_items_done = 1 at the beginning, we need to add
# a final item to complete the progress
self.stats_items_done += 1
self._report_progress()
return zim_path
def _add_item_for(
self, creator: Creator, path: str, title: str | None = None, **kwargs: Any
) -> None:
"""Wrapper for creator.add_item_for with backpressure.
Blocks when 100 items are already in-flight, releases a slot when
the item is finalized (garbage-collected by libzim).
"""
self._inflight_semaphore.acquire()
existing_callbacks = kwargs.pop("callbacks", None)
callbacks: list[Callback] = []
if existing_callbacks is not None:
if isinstance(existing_callbacks, list):
callbacks.extend(
existing_callbacks # pyright: ignore[reportUnknownArgumentType]
)
else:
callbacks.append(existing_callbacks)
callbacks.append(Callback(func=self._inflight_semaphore.release))
creator.add_item_for(path, title, callbacks=callbacks, **kwargs)
def run_with_creator(self, creator: Creator):
context.current_thread_workitem = "standard files"
logger.info(" Storing configuration...")
self._add_item_for(
creator,
"content/config.json",
content=ConfigModel(
secondary_color=self.zim_config.secondary_color,
zim_name=self.formatted_config.name,
center=(
[context.default_view[0], context.default_view[1]]
if context.default_view
else None
),
zoom=context.default_view[2] if context.default_view else None,
).model_dump_json(by_alias=True, exclude_none=True),
)
count_zimui_files = len(list(context.zimui_dist.rglob("*")))
if count_zimui_files == 0:
raise OSError(f"No Vue.JS UI files found in {context.zimui_dist}")
logger.info(
f"Adding {count_zimui_files} Vue.JS UI files in {context.zimui_dist}"
)
self.stats_items_total += count_zimui_files
for file in context.zimui_dist.rglob("*"):
self.stats_items_done += 1
run_pending()
if file.is_dir():
continue
path = str(Path(file).relative_to(context.zimui_dist))
logger.debug(f"Adding {path} to ZIM")
if path == "index.html": # Change index.html title and add to ZIM
index_html_path = context.zimui_dist / path
self._add_item_for(
creator,
path=path,
content=index_html_path.read_text(encoding="utf-8").replace(
"<title>Vite App</title>",
f"<title>{self.formatted_config.title}</title>",
),
mimetype="text/html",
is_front=True,
)
else:
self._add_item_for(
creator,
path=path,
fpath=file,
is_front=False,
)
context.current_thread_workitem = "about page"
logger.info(" Generating about page...")
self._write_about_html(creator)
context.current_thread_workitem = "download fonts"
self._fetch_fonts_tar_gz()
context.current_thread_workitem = "write fonts"
self._write_fonts(creator)
context.current_thread_workitem = "download natural_earth"
self._fetch_natural_earth_tar_gz()
context.current_thread_workitem = "write natural_earth"
self._write_natural_earth(creator)
context.current_thread_workitem = "download sprites"
self._fetch_sprites_tar_gz()
context.current_thread_workitem = "write sprites"
self._write_sprites(creator)
context.current_thread_workitem = "download mbtiles"
self._fetch_mbtiles()
context.current_thread_workitem = "download styles"
self._fetch_styles_tar_gz()
context.current_thread_workitem = "write styles"
self._write_styles(creator)
context.current_thread_workitem = "tilejson"
self._write_tilejson(creator)
# Initialize tile filter if poly files or zoom filtering is specified
tile_filter: TileFilter | None = None
if context.include_poly_urls or context.include_up_to_zoom is not None:
context.current_thread_workitem = "loading poly files"
# Validate include_up_to_zoom if specified
if context.include_up_to_zoom is not None:
max_zoom = self._get_mbtiles_maxzoom()
if context.include_up_to_zoom >= max_zoom:
raise ValueError(
f"--include_up_to_zoom ({context.include_up_to_zoom}) "
f"must be less than the maximum zoom in mbtiles ({max_zoom})"
)
if context.include_poly_urls:
logger.info(" Downloading and loading .poly file(s) for filtering")
tile_filter = TileFilter(
context.include_poly_urls or "",
max_zoom_no_filter=context.include_up_to_zoom,
)
if context.include_poly_urls:
logger.info(
f" Loaded {tile_filter.polygon_count} polygon(s) for filtering"
)
if context.include_up_to_zoom is not None:
logger.info(
f" Including all tiles up to zoom "
f"level {context.include_up_to_zoom}"
)
context.current_thread_workitem = "download places data"
self._fetch_geonames_zip()
self._fetch_hierarchy_zip()
self._fetch_country_info()
context.current_thread_workitem = "process places data"
places_dict = self._parse_geonames(tile_filter=tile_filter)
# Build reverse mapping for hierarchy traversal
id_to_place = {
p.geoname_id: p for places in places_dict.values() for p in places
}
# Parse hierarchy and country info, then compute disambiguating labels
child_to_parent = self._parse_hierarchy()
iso_to_country = self._parse_country_info()
if child_to_parent:
self._compute_discriminating_labels(
places_dict, id_to_place, child_to_parent, iso_to_country
)
self._write_places(creator, places_dict)
# Free memory
del places_dict
del id_to_place
del child_to_parent
del iso_to_country
# Count items for progress reporting (just totals, no filtering)
dedupl_count, tile_count = self._count_mbtiles_items()
self.stats_items_total += tile_count + dedupl_count
# If filtering is active, collect filtered data in single pass
# filtered_dedup_ids: set[int] | None = None
# filtered_redirects: list[tuple[str, str]] | None = None
filtering_results: FilteringResult | None = None
if tile_filter:
context.current_thread_workitem = "filtering tiles"
# Collect filtered data (dedup IDs and redirects) in single pass
filtering_results = self._collect_filtered_tiles_data(
tile_filter, tile_count
)
# In addition to read all tiles_shallow, we will have to create redirects
self.stats_items_total += len(filtering_results.redirects)
context.current_thread_workitem = "dedupl files"
# Calculate filtered dedup count (items that will actually be added to ZIM)
dedupl_filtered = (
len(filtering_results.dedup_ids)
if filtering_results is not None
else dedupl_count
)
self._write_dedupl_files(
creator,
filtering_results.dedup_ids if filtering_results else None,
dedupl_count, # Pass total for progress logging
dedupl_filtered, # Pass filtered count for ZIM additions
)
context.current_thread_workitem = "tile files"
# Calculate total tile count (use filtered if available, otherwise full)
tile_total = (
len(filtering_results.redirects)
if filtering_results is not None
else tile_count
)
self._write_title_files(
creator,
filtering_results.redirects if filtering_results else None,
tile_total,
)
def _report_progress(self):
"""report progress to stats file"""
logger.info(f" Progress {self.stats_items_done} / {self.stats_items_total}")
if not context.stats_filename:
return
progress = {
"done": self.stats_items_done,
"total": self.stats_items_total,
}
context.stats_filename.write_text(json.dumps(progress, indent=2))
def _fetch_zim_illustration(self) -> BytesIO:
"""Fetch ZIM illustration, convert/resize and return it"""
icon_url = context.illustration_url
try:
logger.debug(f"Downloading {icon_url} illustration")
illustration_content = BytesIO()
stream_file(
icon_url,
byte_stream=illustration_content,
)
illustration_format = format_for(illustration_content, from_suffix=False)
png_illustration = BytesIO()
if illustration_format == "SVG":
logger.debug("Converting SVG illustration to PNG")
convert_svg2png(illustration_content, png_illustration, 48, 48)
elif illustration_format == "PNG":
png_illustration = illustration_content
else:
logger.debug(f"Converting {illustration_format} illustration to PNG")
convert_image(illustration_content, png_illustration, fmt="PNG")
logger.debug("Resizing ZIM illustration")
resize_image(
src=png_illustration,
width=48,
height=48,
method="cover",
)
return png_illustration
except Exception as exc:
raise NoIllustrationFoundError(
f"Failed to retrieve illustration at {icon_url}"
) from exc
def _fetch_favicon_from_illustration(self, illustration: BytesIO) -> BytesIO:
"""Return a converted version of the illustration into favicon"""
favicon = BytesIO()
convert_image(illustration, favicon, fmt="ICO")
logger.debug("Resizing ZIM favicon")
resize_image(
src=favicon,
width=32,
height=32,
method="cover",
)
return favicon
def _fetch_fonts_tar_gz(self):
"""Download fonts tar.gz from OpenFreeMap if not already cached.
If file already exists in assets folder, do nothing.
Otherwise, download from https://assets.openfreemap.com/fonts/ofm.tar.gz
"""
fonts_tar_gz_path = context.assets_folder / "ofm.tar.gz"
# If file already exists, we're done
if fonts_tar_gz_path.exists():
logger.info(
f" using fonts tar.gz already available at {fonts_tar_gz_path}"
)
return
# Create assets folder if it doesn't exist
context.assets_folder.mkdir(parents=True, exist_ok=True)
logger.info(" Downloading fonts from OpenFreeMap")
save_large_file(
"https://assets.openfreemap.com/fonts/ofm.tar.gz",
fpath=fonts_tar_gz_path,
)
logger.info(f" fonts tar.gz saved to {fonts_tar_gz_path}")
def _write_fonts(self, creator: Creator):
"""Extract fonts from tar.gz and add to ZIM under 'fonts' folder.
Extracts the cached fonts tar.gz file and adds all contents to the ZIM
with paths under the 'fonts/' subfolder.
"""
fonts_tar_gz_path = context.assets_folder / "ofm.tar.gz"
logger.info(" Extracting fonts and adding to ZIM")
# Create a deduplicator to detect duplicate natural earth tiles and save space
deduplicator = Deduplicator(creator)
deduplicator.filters.append(re.compile(".*"))
# Extract and add fonts to ZIM
with tarfile.open(fonts_tar_gz_path, "r:gz") as tar:
for member in tar.getmembers():
if member.isfile():
# Extract file content
f = tar.extractfile(member)
if f is not None:
content = f.read()
# Transform path from ofm/{fontstack}/{range}.pbf to
# fonts/{fontstack}/{range}.pbf
relative_path = member.name.replace("ofm/", "", 1)
zim_path = f"fonts/{relative_path}"
deduplicator.add_item_for(
path=zim_path,
content=content,
)
logger.info(" Fonts added to ZIM")
def _fetch_natural_earth_tar_gz(self):
"""Download natural_earth tar.gz from OpenFreeMap if not already cached.
If file already exists in assets folder, do nothing.
Otherwise, download from http://assets.openfreemap.com/natural_earth/ofm.tar.gz
"""
natural_earth_tar_gz_path = context.assets_folder / "natural_earth.tar.gz"
# If file already exists, we're done
if natural_earth_tar_gz_path.exists():
logger.info(
" using natural_earth tar.gz already available at "
f"{natural_earth_tar_gz_path}"
)
return
# Create assets folder if it doesn't exist
context.assets_folder.mkdir(parents=True, exist_ok=True)
logger.info(" Downloading natural_earth from OpenFreeMap")
save_large_file(
"https://assets.openfreemap.com/natural_earth/ofm.tar.gz",
fpath=natural_earth_tar_gz_path,
)
logger.info(f" natural_earth tar.gz saved to {natural_earth_tar_gz_path}")
def _write_natural_earth(self, creator: Creator):
"""Extract natural_earth from tar.gz and add to ZIM.
Extracts the cached natural_earth tar.gz file and adds all contents to the ZIM,
transforming paths from ofm/ne2sr/ to natural_earth/ne2sr/.
"""
natural_earth_tar_gz_path = context.assets_folder / "natural_earth.tar.gz"
logger.info(" Extracting natural_earth and adding to ZIM")
# Create a deduplicator to detect duplicate natural earth tiles and save space
deduplicator = Deduplicator(creator)
deduplicator.filters.append(re.compile(".*"))
# Extract and add natural_earth to ZIM
with tarfile.open(natural_earth_tar_gz_path, "r:gz") as tar:
for member in tar.getmembers():
if member.isfile():
# Extract file content
f = tar.extractfile(member)
if f is not None:
content = f.read()
# Transform path from ofm/ne2sr/... to natural_earth/ne2sr/...
relative_path = member.name.replace("ofm/ne2sr/", "", 1)
zim_path = f"natural_earth/ne2sr/{relative_path}"
deduplicator.add_item_for(
path=zim_path,
content=content,
)
logger.info(" Natural_earth added to ZIM")
def _fetch_geonames_zip(self):
"""Download and extract geonames data from ZIP if not already cached.
Downloads from https://download.geonames.org/export/dump/{region}.zip,
extracts the TSV file, and removes the ZIP file.
The extracted TSV is cached in the assets folder for processing.
"""
geonames_zip_path = context.assets_folder / f"{context.geonames_region}.zip"
geonames_txt_path = context.assets_folder / f"{context.geonames_region}.txt"
# If extracted TSV file already exists, we're done
if geonames_txt_path.exists():
logger.info(
f" using geonames {context.geonames_region} TSV already available at "
f"{geonames_txt_path}"
)
return
# Create assets folder if it doesn't exist
context.assets_folder.mkdir(parents=True, exist_ok=True)
logger.info(
f" Downloading geonames {context.geonames_region} from geonames.org"
)
geonames_url = (
f"https://download.geonames.org/export/dump/{context.geonames_region}.zip"
)
save_large_file(geonames_url, fpath=geonames_zip_path)
logger.info(
f" geonames {context.geonames_region} ZIP saved to {geonames_zip_path}"
)
# Extract TSV file from ZIP
logger.info(f" Extracting {context.geonames_region}.txt from ZIP")
with zipfile.ZipFile(geonames_zip_path, "r") as zip_ref:
# Extract the TSV file (named {region}.txt)
txt_file_name = f"{context.geonames_region}.txt"
if txt_file_name not in zip_ref.namelist():
raise OSError(
f"Could not find {txt_file_name} in geonames ZIP at "
f"{geonames_zip_path}"
)
zip_ref.extract(txt_file_name, context.assets_folder)
# Remove ZIP file to save space
geonames_zip_path.unlink()
logger.info(f" Removed ZIP file, keeping extracted TSV at {geonames_txt_path}")
def _fetch_hierarchy_zip(self):
"""Download and extract geonames hierarchy data from ZIP if not already cached.
Downloads from https://download.geonames.org/export/dump/hierarchy.zip,
extracts the hierarchy.txt file, and removes the ZIP file.
The extracted TSV is cached in the assets folder for processing.
"""
hierarchy_zip_path = context.assets_folder / "hierarchy.zip"
hierarchy_txt_path = context.assets_folder / "hierarchy.txt"
# If extracted TSV file already exists, we're done
if hierarchy_txt_path.exists():
logger.info(
f" using hierarchy TSV already available at {hierarchy_txt_path}"
)
return
# Create assets folder if it doesn't exist
context.assets_folder.mkdir(parents=True, exist_ok=True)
logger.info(" Downloading hierarchy from geonames.org")
hierarchy_url = "https://download.geonames.org/export/dump/hierarchy.zip"
save_large_file(hierarchy_url, fpath=hierarchy_zip_path)
logger.info(f" hierarchy ZIP saved to {hierarchy_zip_path}")
# Extract TSV file from ZIP
logger.info(" Extracting hierarchy.txt from ZIP")
with zipfile.ZipFile(hierarchy_zip_path, "r") as zip_ref:
if "hierarchy.txt" not in zip_ref.namelist():
raise OSError(
f"Could not find hierarchy.txt in ZIP at {hierarchy_zip_path}"
)
zip_ref.extract("hierarchy.txt", context.assets_folder)
# Remove ZIP file to save space
hierarchy_zip_path.unlink()
logger.info(
f" Removed ZIP file, keeping extracted TSV at {hierarchy_txt_path}"
)
def _fetch_country_info(self):
"""Download country info TSV from geonames if not already cached.
Downloads from https://download.geonames.org/export/dump/countryInfo.txt
and caches it in the assets folder.
"""
country_info_path = context.assets_folder / "countryInfo.txt"
# If file already exists, we're done
if country_info_path.exists():
logger.info(
f" using country info already available at {country_info_path}"
)
return
# Create assets folder if it doesn't exist
context.assets_folder.mkdir(parents=True, exist_ok=True)
logger.info(" Downloading country info from geonames.org")
save_large_file(
"https://download.geonames.org/export/dump/countryInfo.txt",
fpath=country_info_path,
)
logger.info(f" country info saved to {country_info_path}")
@staticmethod
def _parse_country_info() -> dict[str, str]:
"""Parse country info TSV and return ISO code to country name mapping.
Format of countryInfo.txt: ISO\t...\tCountry name (5th column)
Comments start with #
Returns:
Dictionary mapping ISO code to country name.
"""
country_info_path = context.assets_folder / "countryInfo.txt"
if not country_info_path.exists():
logger.info(" Country info not available, skipping country name lookup")
return {}
logger.info(" Parsing country info file")
iso_to_country: dict[str, str] = {}
try:
with open(country_info_path, encoding="utf-8") as f:
for line in f:
line_stripped = line.rstrip("\n")
if not line_stripped or line_stripped.startswith("#"):
continue
parts = line_stripped.split("\t")
if len(parts) < 5: # noqa: PLR2004
continue
iso_code = parts[0]
country_name = parts[4]
if iso_code and country_name:
iso_to_country[iso_code] = country_name
logger.debug(f" Loaded {len(iso_to_country)} countries")
return iso_to_country
except Exception as e:
logger.error(f" Error parsing country info: {e}")
return {}
def _fetch_sprites_tar_gz(self):
"""Download sprites tar.gz from OpenFreeMap if not already cached.
If file already exists in assets folder, do nothing.
Otherwise, download from https://assets.openfreemap.com/sprites/ofm_f384.tar.gz
"""
sprites_tar_gz_path = context.assets_folder / "sprites.tar.gz"
# If file already exists, we're done
if sprites_tar_gz_path.exists():
logger.info(
f" using sprites tar.gz already available at {sprites_tar_gz_path}"
)
return
# Create assets folder if it doesn't exist
context.assets_folder.mkdir(parents=True, exist_ok=True)
logger.info(" Downloading sprites from OpenFreeMap")
save_large_file(
"https://assets.openfreemap.com/sprites/ofm_f384.tar.gz",
fpath=sprites_tar_gz_path,
)
logger.info(f" sprites tar.gz saved to {sprites_tar_gz_path}")
def _write_sprites(self, creator: Creator):
"""Extract sprites from tar.gz and add to ZIM under 'sprites/ofm_f384' folder.
Extracts the cached sprites tar.gz file and adds all contents to the ZIM,
transforming paths from ofm_f384/ to sprites/ofm_f384/.
"""
sprites_tar_gz_path = context.assets_folder / "sprites.tar.gz"
logger.info(" Extracting sprites and adding to ZIM")
# Extract and add sprites to ZIM
with tarfile.open(sprites_tar_gz_path, "r:gz") as tar:
for member in tar.getmembers():
if member.isfile():
# Extract file content
f = tar.extractfile(member)
if f is not None:
content = f.read()
# Transform path from ofm_f384/... to sprites/ofm_f384/...
zim_path = f"sprites/{member.name}"
self._add_item_for(
creator,
path=zim_path,
content=content,
)
logger.info(" Sprites added to ZIM")
def _fetch_styles_tar_gz(self):
"""Download styles tar.gz from OpenFreeMap if not already cached.
If file already exists in assets folder, do nothing.
Otherwise, download from https://assets.openfreemap.com/styles/ofm.tar.gz
"""
styles_tar_gz_path = context.assets_folder / "styles.tar.gz"
# If file already exists, we're done
if styles_tar_gz_path.exists():
logger.info(
f" using styles tar.gz already available at {styles_tar_gz_path}"
)
return
# Create assets folder if it doesn't exist
context.assets_folder.mkdir(parents=True, exist_ok=True)
logger.info(" Downloading styles from OpenFreeMap")
save_large_file(
"https://assets.openfreemap.com/styles/ofm.tar.gz",
fpath=styles_tar_gz_path,
)
logger.info(f" styles tar.gz saved to {styles_tar_gz_path}")
def _write_styles(self, creator: Creator):
"""Extract styles from tar.gz and add to ZIM under 'styles' folder.
Extracts the cached styles tar.gz file, modifies JSON files to use relative
paths by replacing the domain with '.', filters layers based on available
mbtiles layers, and adds all contents to the ZIM without the .json extension.
"""
styles_tar_gz_path = context.assets_folder / "styles.tar.gz"
available_layers = self._get_available_layers_from_mbtiles()
logger.info(" Extracting styles and adding to ZIM")
# Extract and add styles to ZIM
with tarfile.open(styles_tar_gz_path, "r:gz") as tar:
for member in tar.getmembers():
if member.isfile():
# Extract file content
f = tar.extractfile(member)
if f is not None:
content = f.read()
# If it's a JSON file, process it
if member.name.endswith(".json"):
# Parse JSON
style_obj = json.loads(content.decode("utf-8"))
# Filter layers based on available mbtiles layers
style_obj = self._filter_style_layers(
style_obj, available_layers
)
# Replace domain with relative path
content = json.dumps(
style_obj, ensure_ascii=False, indent=2
).encode("utf-8")
content = content.replace(
b"https://__TILEJSON_DOMAIN__", b"."
)
# Transform path from ofm/... to styles/...
relative_path = member.name.replace("ofm/", "", 1)
# Remove .json extension from style files
if relative_path.endswith(".json"):
relative_path = relative_path[:-5]
zim_path = f"styles/{relative_path}"
self._add_item_for(
creator,
path=zim_path,
content=content,
)
logger.info(" Styles added to ZIM")
def _get_available_layers_from_mbtiles(self) -> set[str]:
"""Get set of available source-layer names from mbtiles metadata.
Reads the mbtiles database and extracts the list of available layers
from the vector_layers metadata.
"""
mbtiles_path = context.assets_folder / f"{context.area}.mbtiles"
# If mbtiles doesn't exist yet, return empty set
if not mbtiles_path.exists():
return set()
conn = sqlite3.connect(mbtiles_path)
c = conn.cursor()
try:
metadata = dict(c.execute("select name, value from metadata").fetchall())
if "json" in metadata:
metadata_json = json.loads(metadata["json"])
if "vector_layers" in metadata_json:
# Extract all layer IDs from vector_layers
return {layer["id"] for layer in metadata_json["vector_layers"]}
finally:
conn.close()
return set()
@staticmethod
def _filter_style_layers(
style_obj: dict[str, Any], available_layers: set[str]
) -> dict[str, Any]:
"""Remove layers from style that reference non-existent source-layers.
Filters the style's layer array to only include layers that reference
existing source-layers in the mbtiles database.
"""
if "layers" not in style_obj or not available_layers:
return style_obj
filtered_layers: list[Any] = []
for layer in style_obj["layers"]:
# If layer has no source-layer, keep it (e.g., background layers)
if "source-layer" not in layer:
filtered_layers.append(layer)
# If source-layer exists in mbtiles, keep it
elif layer.get("source-layer") in available_layers:
filtered_layers.append(layer)
else:
logger.debug(
f"Removing layer '{layer.get('id')}' - "
f"source-layer '{layer.get('source-layer')}' not found in mbtiles"
)
style_obj["layers"] = filtered_layers
return style_obj
def _count_mbtiles_items(self) -> tuple[int, int]:
"""Count total dedupl and tile items in mbtiles database.
Returns:
Tuple of (dedupl_count, tile_count)
"""
mbtiles_path = context.assets_folder / f"{context.area}.mbtiles"
conn = sqlite3.connect(mbtiles_path)
c = conn.cursor()
try:
logger.info(" Counting tiles")
dedupl_count = c.execute("select count(*) from tiles_data").fetchone()[0]
logger.info(f" Found {dedupl_count} unique tile data entries")
tile_count = c.execute("select count(*) from tiles_shallow").fetchone()[0]
logger.info(f" Found {tile_count} tiles")
return dedupl_count, tile_count
finally:
conn.close()
def _collect_filtered_tiles_data(
self, tile_filter: TileFilter, total_tile_count: int
) -> FilteringResult:
"""Collect dedup IDs and redirect info for filtered tiles.
Performs a single pass through tiles_shallow to collect dedup IDs
and tile redirect information for tiles that pass the filter.
Reports progress every 60 seconds.
Args:
tile_filter: TileFilter object for geographic filtering
total_tile_count: Total number of tiles in tiles_shallow (to avoid recount)
Returns:
Dict with keys:
- dedup_ids: set[int] of dedup IDs to include
- redirects: list of (tile_path, dedup_path) tuples
- filtered_tile_count: number of tiles included