|
| 1 | +import glob |
| 2 | +import os |
| 3 | +from plateauutils.abc.plateau_parser import PlateauParser |
| 4 | +from plateauutils.tile_list.polygon_to_tile_list import PolygonToTileList |
| 5 | +from shapely.geometry import Polygon |
| 6 | +import shutil |
| 7 | +import zipfile |
| 8 | + |
| 9 | + |
| 10 | +class MvtTileParser(PlateauParser): |
| 11 | + """MVTタイルをパースするクラス |
| 12 | +
|
| 13 | + Parameters |
| 14 | + ---------- |
| 15 | + polygon : shapely.geometry.Polygon |
| 16 | + 対象となるポリゴン |
| 17 | + zoom : int |
| 18 | + 対象とするズームレベル |
| 19 | + """ |
| 20 | + |
| 21 | + def __init__(self, polygon: Polygon = None, zoom: int = 15): |
| 22 | + self.zoom = zoom |
| 23 | + super().__init__(polygon) |
| 24 | + |
| 25 | + def parse(self, target_path: str = "") -> list: |
| 26 | + """MVTタイルをパースして、リストを返すメソッド |
| 27 | +
|
| 28 | + Parameters |
| 29 | + ---------- |
| 30 | + target_path : str |
| 31 | + MVTタイル(zip)のパス |
| 32 | +
|
| 33 | + Returns |
| 34 | + ------- |
| 35 | + list |
| 36 | + タイルのパスのリスト |
| 37 | + """ |
| 38 | + # ファイルが存在しないならエラー |
| 39 | + if not os.path.exists(target_path): |
| 40 | + raise FileNotFoundError(f"target_path: {target_path} is not found") |
| 41 | + # zipファイルにターゲットのパスが存在するか確認 |
| 42 | + hit_targets = [] |
| 43 | + with zipfile.ZipFile(target_path) as zip_file: |
| 44 | + for name in zip_file.namelist(): |
| 45 | + for target in self.targets: |
| 46 | + path = os.path.join("luse", target) |
| 47 | + if name.find(path) >= 0: |
| 48 | + hit_targets.append(target) |
| 49 | + if len(hit_targets) == 0: |
| 50 | + raise ValueError(f"target_path: {target_path} is not target") |
| 51 | + # zipファイルを解凍する |
| 52 | + unarchived_dir = target_path.replace(".zip", "") |
| 53 | + shutil.unpack_archive(target_path, unarchived_dir) |
| 54 | + # 返り値を作成 |
| 55 | + return_list = [] |
| 56 | + # 解凍したファイルをパースする |
| 57 | + for target in hit_targets: |
| 58 | + # ファイルパスを作成 |
| 59 | + target_file_path = os.path.join(unarchived_dir, "luse", target) |
| 60 | + for file_path in glob.glob(target_file_path): |
| 61 | + return_list.append(file_path) |
| 62 | + return sorted(return_list) |
| 63 | + |
| 64 | + def download_and_parse(self, url: str = "", target_dir: str = "") -> list: |
| 65 | + """MVTタイルをダウンロードして、タイルのリストを返すメソッド |
| 66 | +
|
| 67 | + Parameters |
| 68 | + ---------- |
| 69 | + url : str |
| 70 | + MVTタイル(zip)のURL |
| 71 | + target_dir : str |
| 72 | + ファイルを展開する先のパス |
| 73 | +
|
| 74 | + Returns |
| 75 | + ------- |
| 76 | + list |
| 77 | + タイルのパスのリスト |
| 78 | + """ |
| 79 | + saved_path = self._download(url, target_dir) |
| 80 | + return self.parse(saved_path) |
| 81 | + |
| 82 | + def _target_list(self, polygon: Polygon = None) -> list: |
| 83 | + # PolygonがNoneならエラー |
| 84 | + if polygon is None: |
| 85 | + raise ValueError("polygon is None") |
| 86 | + # Polygonからタイルのリストを作成 |
| 87 | + tile_list = PolygonToTileList(polygon, self.zoom) |
| 88 | + return tile_list.output() |
0 commit comments