diff --git a/CHANGELOG.md b/CHANGELOG.md index 19201b2..fa3b222 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,12 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0. ## [Unreleased] +### Added + +- `side_files` on a converter: sources that are tables to join (e.g. a CSV), not geodata. + They are downloaded with the other sources, left out of the geodata and read with + `read_side_file()`, e.g. in `migrate()`. Per-file conversion passes them to every part. + ### Changed - Converters read a shapefile through its `.shp` only, so its parts (`.shx`, `.dbf`, `.prj`, ...) diff --git a/tests/test_convert.py b/tests/test_convert.py index 3fca411..7e1d6a6 100644 --- a/tests/test_convert.py +++ b/tests/test_convert.py @@ -448,6 +448,91 @@ def test_shapefile_parts_are_read_through_their_shp(tmp_folder): assert read == expected +class SideFileConverter(BaseConverter): + side_files = ("*.csv",) + + def migrate(self, gdf): + # keep_default_na=False: "NA" is a code here, not a missing value + table = self.read_side_file("*.csv", dtype=str, keep_default_na=False) + return gdf.merge(table, on="id", how="left", validate="many_to_one") + + +def _side_file_sources(folder): + import shapely + + gdf = gpd.GeoDataFrame( + {"id": ["1", "2"], "name": ["a", "b"]}, + geometry=[shapely.box(0, 0, 1, 1), shapely.box(2, 0, 3, 1)], + crs="EPSG:4326", + ) + gdf.to_parquet(folder / "fields.parquet") + (folder / "codes.csv").write_text("id,code\n1,NA\n2,GH\n") + return { + str(folder / "fields.parquet"): "fields.parquet", + str(folder / "codes.csv"): "codes.csv", + } + + +def test_side_files_are_read_as_tables_not_as_geodata(tmp_folder): + Converter = type( + "Converter", + (SideFileConverter,), + { + **CONFIG, + "columns": {**CONFIG["columns"], "code": "code"}, + "missing_schemas": { + "properties": {"name": {"type": "string"}, "code": {"type": "string"}} + }, + }, + ) + dest = tmp_folder / "converted.parquet" + Converter().convert(dest, input_files=_side_file_sources(tmp_folder)) + + result = gpd.read_parquet(dest).sort_values("id") + assert result["code"].tolist() == ["NA", "GH"] + + +def test_a_missing_side_file_fails(tmp_folder): + sources = _side_file_sources(tmp_folder) + del sources[str(tmp_folder / "codes.csv")] + Converter = type("Converter", (SideFileConverter,), CONFIG) + + with pytest.raises(ValueError, match=r"No source matches the side file\(s\) \*\.csv"): + Converter().convert(tmp_folder / "converted.parquet", input_files=sources) + + +@pytest.mark.parametrize("side_file", ["*.csv", "codes.csv"]) +def test_a_side_file_in_an_archive_can_be_given_as_glob(tmp_folder, side_file): + import zipfile + + _side_file_sources(tmp_folder) + archive = tmp_folder / "sources.zip" + with zipfile.ZipFile(archive, "w") as zip_file: + zip_file.write(tmp_folder / "fields.parquet", "fields.parquet") + zip_file.write(tmp_folder / "codes.csv", "tables/codes.csv") + Converter = type( + "Converter", + (SideFileConverter,), + { + **CONFIG, + "side_files": (side_file,), + "columns": {**CONFIG["columns"], "code": "code"}, + "missing_schemas": { + "properties": {"name": {"type": "string"}, "code": {"type": "string"}} + }, + "migrate": lambda self, gdf: gdf.merge( + self.read_side_file(side_file, dtype=str, keep_default_na=False), on="id" + ), + }, + ) + dest = tmp_folder / "converted.parquet" + input_files = {str(archive): ["fields.parquet", "tables/*.csv"]} + Converter().convert(dest, input_files=input_files) + + result = gpd.read_parquet(dest).sort_values("id") + assert result["code"].tolist() == ["NA", "GH"] + + @pytest.mark.parametrize("bom", [False, True], ids=["without-bom", "with-bom"]) def test_read_geojson_decodes_utf8(tmp_folder, cp1252_locale, bom): file_path = tmp_folder / "umlaut.json" diff --git a/tests/test_convert_duckdb.py b/tests/test_convert_duckdb.py index 2d12c27..5bc38a4 100644 --- a/tests/test_convert_duckdb.py +++ b/tests/test_convert_duckdb.py @@ -123,6 +123,16 @@ def test_duckdb_converter_extracts_an_archive_without_a_cache(tmp_folder): assert sorted(gpd.read_parquet(dest)["id"]) == ["bowtie", "multi", "square", "with_z"] +def test_duckdb_converter_rejects_side_files(tmp_folder): + src = _source_file(tmp_folder) + SideFileConverter = type("SideFileConverter", (Converter,), {"side_files": ("*.csv",)}) + + with pytest.raises(ValueError, match="don't support side_files"): + SideFileConverter().convert( + tmp_folder / "converted.parquet", input_files={str(src): "source.parquet"} + ) + + def test_duckdb_converter_ignores_hive_style_folders(tmp_folder): source_folder = tmp_folder / "region=north" source_folder.mkdir() diff --git a/tests/test_per_file.py b/tests/test_per_file.py index 802c0b3..23f0d32 100644 --- a/tests/test_per_file.py +++ b/tests/test_per_file.py @@ -1,5 +1,6 @@ import io import sys +import zipfile import geopandas as gpd import multivolumefile @@ -36,6 +37,21 @@ def _source(folder, region): return path +def _write_multivolume_7z(path, file): + measure = io.BytesIO() + with py7zr.SevenZipFile(measure, "w") as archive: + archive.write(file, file.name) + volume_size = len(measure.getvalue()) // 3 + 1 + with multivolumefile.MultiVolume( + str(path), mode="wb", volume=volume_size, ext_digits=3 + ) as volume: + with py7zr.SevenZipFile(volume, "w") as archive: + archive.write(file, file.name) + volumes = sorted(path.parent.glob(path.name + ".*")) + assert len(volumes) > 1, "the archive must span several volumes for this test" + return volumes + + def _capture_log(): # loguru's default sink is bound to stderr at import, so point it at stdout logger.remove() @@ -60,6 +76,61 @@ def test_each_source_is_converted_on_its_own_and_merged(tmp_path, capsys): assert log.count("No variant given") == 1 +class SideFileConverter(Converter): + side_files = ("names.csv",) + columns = {**Converter.columns, "name": "name"} + missing_schemas = {"properties": {"region": {"type": "string"}, "name": {"type": "string"}}} + + def migrate(self, gdf): + return gdf.merge(self.read_side_file("names.csv"), on="region", how="left") + + +def test_side_files_go_with_every_part(tmp_path): + sources = [_source(tmp_path, region) for region in ("a", "b")] + (tmp_path / "names.csv").write_text("region,name\na,Alpha\nb,Beta\n") + + output = tmp_path / "merged.parquet" + input_files = {str(s): s.name for s in sources} | {str(tmp_path / "names.csv"): "names.csv"} + SideFileConverter().convert(str(output), input_files=input_files) + + merged = gpd.read_parquet(output).sort_values("id") + assert merged["name"].tolist() == ["Alpha", "Alpha", "Beta", "Beta"] + + +def test_side_files_in_an_archive_with_geodata_go_with_every_part(tmp_path): + archived = _source(tmp_path, "a") + (tmp_path / "names.csv").write_text("region,name\na,Alpha\nb,Beta\n") + with zipfile.ZipFile(tmp_path / "a.zip", "w") as archive: + archive.write(archived, archived.name) + archive.write(tmp_path / "names.csv", "names.csv") + source = _source(tmp_path, "b") + + output = tmp_path / "merged.parquet" + input_files = {str(tmp_path / "a.zip"): [archived.name, "names.csv"], str(source): source.name} + SideFileConverter().convert(str(output), input_files=input_files) + + merged = gpd.read_parquet(output).sort_values("id") + assert merged["id"].tolist() == ["a-1", "a-2", "b-1", "b-2"] + assert merged["name"].tolist() == ["Alpha", "Alpha", "Beta", "Beta"] + + +def test_side_files_in_a_multivolume_7z_archive_go_with_every_part(tmp_path): + sources = [_source(tmp_path, region) for region in ("a", "b")] + names = tmp_path / "names.csv" + names.write_text("region,name\na,Alpha\nb,Beta\n") + volumes = _write_multivolume_7z(tmp_path / "names.7z", names) + names.unlink() + + output = tmp_path / "merged.parquet" + input_files = {str(s): s.name for s in sources} + input_files |= {str(v): (["names.csv"] if i == 0 else []) for i, v in enumerate(volumes)} + SideFileConverter().convert(str(output), input_files=input_files) + + merged = gpd.read_parquet(output).sort_values("id") + assert merged["id"].tolist() == ["a-1", "a-2", "b-1", "b-2"] + assert merged["name"].tolist() == ["Alpha", "Alpha", "Beta", "Beta"] + + def test_a_single_source_is_converted_directly(tmp_path): source = _source(tmp_path, "a") output = tmp_path / "single.parquet" @@ -71,17 +142,7 @@ def test_a_single_source_is_converted_directly(tmp_path): def test_the_volumes_of_a_7z_archive_are_converted_together(tmp_path): archived = _source(tmp_path, "b") - measure = io.BytesIO() - with py7zr.SevenZipFile(measure, "w") as archive: - archive.write(archived, archived.name) - volume_size = len(measure.getvalue()) // 3 + 1 - with multivolumefile.MultiVolume( - str(tmp_path / "b.7z"), mode="wb", volume=volume_size, ext_digits=3 - ) as volume: - with py7zr.SevenZipFile(volume, "w") as archive: - archive.write(archived, archived.name) - volumes = sorted(tmp_path.glob("b.7z.*")) - assert len(volumes) > 1, "the archive must span several volumes for this test" + volumes = _write_multivolume_7z(tmp_path / "b.7z", archived) archived.unlink() source = _source(tmp_path, "a") diff --git a/vecorel_cli/conversion/base.py b/vecorel_cli/conversion/base.py index fca18c3..f6d9005 100644 --- a/vecorel_cli/conversion/base.py +++ b/vecorel_cli/conversion/base.py @@ -10,6 +10,7 @@ import tarfile import zipfile from copy import copy +from fnmatch import fnmatch from glob import glob from io import StringIO from tempfile import TemporaryDirectory @@ -82,6 +83,10 @@ class BaseConverter(LoggerMixin): # Sent with every download, e.g. a browser User-Agent for a server that refuses others request_headers: dict[str, str] = {} variants: dict[str, Sources] = {} + # File name patterns of sources that are tables to join, not geodata (e.g. "*.csv"): + # read_data() leaves them out, read_side_file() reads them, e.g. in migrate() + side_files: Sequence[str] = () + side_paths: dict[str, str] = {} variant: Optional[str] = None columns: dict[str, str | Sequence[str]] = {} @@ -553,11 +558,7 @@ def get_data( # GDAL reads the other parts of a shapefile next to its .shp if self._is_shapefile_sidecar(path, shapefiles): continue - # e.g. allow "*.shp" to identify the single relevant file without knowing the name in advance - if "*" in path: - lst = glob(path, recursive=True) - assert len(lst) == 1, f"Can not match {path} to a single file" - path = lst[0] + path = self._resolve_glob(path) self.info(f"Reading {path} into GeoDataFrame(s)") is_parquet = path.endswith(".parquet") or path.endswith(".geoparquet") is_json = path.endswith(".json") or path.endswith(".geojson") @@ -602,6 +603,15 @@ def _is_shapefile_sidecar(path, shapefiles): for ext in SHAPEFILE_SIDECARS ) + @staticmethod + def _resolve_glob(path): + # e.g. allow "*.shp" to identify the single relevant file without knowing the name in advance + if "*" in path: + lst = glob(path, recursive=True) + assert len(lst) == 1, f"Can not match {path} to a single file" + path = lst[0] + return path + def read_geojson(self, path, **kwargs): # open_options is shared with gpd.read_parquet() and gpd.read_file(), so a converter # cannot set a default encoding there without breaking the other two readers. @@ -628,7 +638,50 @@ def _normalize_geojson_properties(self, feature): return feature + def is_side_file(self, name: str) -> bool: + name = os.path.basename(name) + return any(fnmatch(name, pattern) for pattern in self.side_files) + + def _split_side_files(self, paths): + self.side_paths = {} + data = [] + for path, uri in paths: + if self.side_files: + path = self._resolve_glob(path) + matches = [p for p in self.side_files if fnmatch(os.path.basename(path), p)] + if not matches: + data.append((path, uri)) + continue + for pattern in matches: + if pattern in self.side_paths: + raise ValueError( + f"Several sources match the side file {pattern}: " + f"{self.side_paths[pattern]}, {path}" + ) + self.side_paths[pattern] = path + missing = [p for p in self.side_files if p not in self.side_paths] + if missing: + raise ValueError(f"No source matches the side file(s) {', '.join(missing)}") + return data + + def read_side_file(self, pattern: str, **kwargs) -> pd.DataFrame: + if pattern not in self.side_paths: + raise ValueError(f"{pattern} is not a side file of {type(self).__name__}") + path = self.side_paths[pattern] + ext = os.path.splitext(path)[1].lower() + if ext in (".csv", ".tsv", ".txt"): + if ext == ".tsv": + kwargs.setdefault("sep", "\t") + return pd.read_csv(path, **kwargs) + if ext in (".parquet", ".geoparquet"): + return pd.read_parquet(path, **kwargs) + if ext == ".json": + return pd.read_json(path, **kwargs) + # e.g. .dbf or .xlsx, through GDAL + return pd.DataFrame(gpd.read_file(path, ignore_geometry=True, **kwargs)) + def read_data(self, paths, **kwargs): + paths = self._split_side_files(paths) gdfs = [] for data, path, uri, layer in self.get_data(paths, **kwargs): # 0. Run migration per file/layer diff --git a/vecorel_cli/conversion/duckdb.py b/vecorel_cli/conversion/duckdb.py index 74fc42b..8549605 100644 --- a/vecorel_cli/conversion/duckdb.py +++ b/vecorel_cli/conversion/duckdb.py @@ -110,6 +110,9 @@ def convert( raise ValueError("If provided, the bounding box must consist of 4 numbers") self._require_one_source_of_urls() + if self.side_files: + # the sources are read in SQL, without the read_data() and migrate() side files need + raise ValueError(f"{type(self).__name__}: DuckDB converters don't support side_files") self._prewarm_schemas() directory = os.path.dirname(output_file) diff --git a/vecorel_cli/conversion/per_file.py b/vecorel_cli/conversion/per_file.py index 1289fd7..3f507f8 100644 --- a/vecorel_cli/conversion/per_file.py +++ b/vecorel_cli/conversion/per_file.py @@ -1,6 +1,7 @@ import os from tempfile import TemporaryDirectory +from ..vecorel.util import name_from_uri from .duckdb import DuckDBBaseConverter @@ -50,4 +51,39 @@ def _split_sources(self, urls) -> list: return [urls] # the volumes of a multi-volume 7z archive can only be extracted together regular, volume_groups = self._group_multivolume_7z(urls) - return [{uri: target} for uri, target in regular.items()] + list(volume_groups.values()) + units = [{u: t} for u, t in regular.items()] + list(volume_groups.values()) + # side files are joined to every source, so each part gets them + side, sources = {}, [] + for unit in units: + side_unit, data_unit = self._split_side_targets(unit) + has_side = self._has_targets(side_unit) + if has_side: + side.update(side_unit) + if self._has_targets(data_unit) or not has_side: + sources.append(data_unit) + return [self._add_side_targets(s, side) for s in sources] + + def _split_side_targets(self, unit): + side, data = {}, {} + for uri, target in unit.items(): + if isinstance(target, list): + # archives stay in both, so that all volumes of a 7z archive are kept together + side[uri] = [n for n in target if self.is_side_file(n)] + data[uri] = [n for n in target if not self.is_side_file(n)] + elif self.is_side_file(target or name_from_uri(uri)): + side[uri] = target + else: + data[uri] = target + return side, data + + @staticmethod + def _has_targets(unit) -> bool: + return any(target != [] for target in unit.values()) + + @staticmethod + def _add_side_targets(source, side): + source = dict(source) + for uri, target in side.items(): + # an archive with side and data targets is listed once, with both + source[uri] = source[uri] + target if uri in source else target + return source