Add import TMS tiles (directory/zip) and tif formatter

This commit is contained in:
parent e39361bd81
commit a5de6f5c91
6 changed files with 127 additions and 19 deletions

View file

@ -1,6 +1,8 @@
import base64
import shutil
import subprocess
import tarfile
import zipfile
from pathlib import Path
from typing import Iterable, Optional
@ -45,11 +47,14 @@ class TileService:
tile_format: str = "png",
web_mercator: bool = True,
extra_args: Optional[Iterable[str]] = None,
scheme: str = "xyz",
) -> Path:
if not source.exists():
raise TileCutError(f"source does not exist: {source}")
if min_zoom < 0 or max_zoom < min_zoom:
raise TileCutError(f"invalid zoom range: {min_zoom}-{max_zoom}")
if tile_format.lower() != "png":
raise TileCutError("current gdal2tiles does not support custom format here; use png")
destination.mkdir(parents=True, exist_ok=True)
@ -60,11 +65,11 @@ class TileService:
f"{min_zoom}-{max_zoom}",
"-r",
resampling,
"-f",
tile_format.lower(),
]
if web_mercator:
cmd += ["-p", "mercator"]
if scheme.lower() == "xyz":
cmd += ["--xyz"]
if extra_args:
cmd += list(extra_args)
cmd += [str(source), str(destination)]
@ -82,4 +87,37 @@ class TileService:
return FileResponse(self.placeholder, media_type="image/png")
return Response(content=DEFAULT_PLACEHOLDER_PNG, media_type="image/png")
def get_tile_response_tms(self, zoom: int, x: int, y: int):
y_converted = (2**zoom - 1) - y
return self.get_tile_response(zoom, x, y_converted)
def unpack_if_archive(self, source: Path) -> Path:
lower = source.suffix.lower()
if lower == ".zip":
dest = self.upload_dir / source.stem
dest.mkdir(parents=True, exist_ok=True)
with zipfile.ZipFile(source, "r") as zf:
zf.extractall(dest)
return dest
if lower in {".tar", ".tgz", ".gz", ".bz2", ".xz"} or source.name.endswith((".tar.gz", ".tar.bz2", ".tar.xz")):
dest = self.upload_dir / source.stem
dest.mkdir(parents=True, exist_ok=True)
with tarfile.open(source, "r:*") as tf:
tf.extractall(dest)
return dest
return source
def copy_tile_tree(self, source_dir: Path, destination: Path) -> None:
if not source_dir.is_dir():
raise TileCutError(
f"tiles directory not found: {source_dir}. Expected folder with {Path('z/x/y.png')} structure or a zip/tar archive."
)
destination.mkdir(parents=True, exist_ok=True)
for item in source_dir.iterdir():
target = destination / item.name
if item.is_dir():
shutil.copytree(item, target, dirs_exist_ok=True)
else:
shutil.copy2(item, target)