rusackas commented on code in PR #45607:
URL: https://github.com/apache/superset/pull/45607#discussion_r4358021946


##########
superset-frontend/plugins/plugin-chart-country-map/scripts/build_maps.py:
##########
@@ -0,0 +1,173 @@
+#!/usr/bin/env python3
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Regenerates plugin-chart-country-map's GeoJSON files, countries.ts and
+docs/data/countries.json from upstream Natural Earth + community geo
+data - the script equivalent of running every cell in
+`Country Map GeoJSON Generator.ipynb` top to bottom.
+
+By default writes to the same repo-relative locations the notebook
+always has (../src/countries/, ../src/countries.ts,
+../../../../docs/data/countries.json), so `git diff` after a run shows
+exactly what changed - override --out-dir/--countries-ts-path/
+--docs-json-path to redirect output elsewhere for a non-destructive
+dry run.
+
+Usage:
+    python3 build_maps.py
+    python3 build_maps.py --preview --out-dir /tmp/maps-out \\
+        --countries-ts-path /tmp/maps-out/countries.ts \\
+        --docs-json-path /tmp/maps-out/countries.json
+    python3 build_maps.py --countries france,turkey  # just these modules
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import os
+import sys
+
+import geopandas as gpd
+
+_SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
+sys.path.insert(0, _SCRIPT_DIR)
+
+from maps.assemble import purged_countries, resolve_all, validate_catalog  # 
noqa: E402
+from maps.context import BuildContext  # noqa: E402
+from maps.countries import REGISTRY  # noqa: E402
+from maps.data import load_natural_earth  # noqa: E402
+from maps.output import save_geojson  # noqa: E402
+from maps.preview import build_contact_sheet, render_preview  # noqa: E402
+from maps.ts_writer import write_countries_ts, write_docs_json  # noqa: E402
+
+_DEFAULT_OUT_DIR = os.path.join(_SCRIPT_DIR, "..", "src", "countries")
+_DEFAULT_COUNTRIES_TS_PATH = os.path.join(_SCRIPT_DIR, "..", "src", 
"countries.ts")
+_DEFAULT_DOCS_JSON_PATH = os.path.join(
+    _SCRIPT_DIR, "..", "..", "..", "..", "docs", "data", "countries.json"
+)
+
+
+def _parse_args() -> argparse.Namespace:
+    parser = argparse.ArgumentParser(description=__doc__)
+    parser.add_argument("--data-dir", 
default=os.path.expanduser("~/Downloads"))
+    parser.add_argument("--out-dir", default=_DEFAULT_OUT_DIR)
+    parser.add_argument("--countries-ts-path", 
default=_DEFAULT_COUNTRIES_TS_PATH)
+    parser.add_argument("--docs-json-path", default=_DEFAULT_DOCS_JSON_PATH)
+    parser.add_argument(
+        "--countries",
+        help="Comma-separated subset of registered module NAMEs to run "
+        "(default: all registered). The ~190 plain catalog entries that "
+        "don't need a module are always included.",
+    )
+    parser.add_argument(
+        "--preview",
+        action="store_true",
+        help="Also render a PNG thumbnail per output and a contact sheet grid",
+    )
+    parser.add_argument(
+        "--force-download",
+        action="store_true",
+        help="Re-download Natural Earth data even if a same-size cached copy 
exists",
+    )
+    return parser.parse_args()
+
+
+def _purge_stale_files(
+    ctx: BuildContext, built: dict[str, gpd.GeoDataFrame], out_dir: str
+) -> None:
+    for name in purged_countries(ctx, built):
+        stale_path = os.path.join(out_dir, f"{name.replace(' ', '_')}.geojson")
+        if os.path.exists(stale_path):
+            os.remove(stale_path)
+            print(f"Purged {stale_path}: {name} has only one subdivision")
+
+
+def _save_all(
+    ctx: BuildContext,
+    resolved: dict[str, gpd.GeoDataFrame],
+    out_dir: str,
+    preview: bool,
+) -> list[dict[str, object]]:
+    manifest: list[dict[str, object]] = []
+    for name, gdf in sorted(resolved.items()):
+        path = save_geojson(ctx, name, gdf, out_dir)
+        entry = {
+            "name": name,
+            "geojson": os.path.relpath(path, out_dir),
+            "subdivisions": int(gdf["iso_3166_2"].nunique()),
+        }
+        if preview:
+            thumb_path = render_preview(gdf, name, out_dir)
+            entry["thumbnail"] = os.path.relpath(thumb_path, out_dir)
+        manifest.append(entry)
+    return manifest
+
+
+def main() -> None:
+    args = _parse_args()
+    os.makedirs(args.out_dir, exist_ok=True)
+
+    selected = set(args.countries.split(",")) if args.countries else None
+    modules = [m for m in REGISTRY if selected is None or m.NAME in selected]
+    if not modules:
+        raise SystemExit(f"No registered country modules matched: 
{args.countries}")
+
+    print(f"Loading Natural Earth data into {args.data_dir}...")
+    ctx = load_natural_earth(args.data_dir, skip_existing=not 
args.force_download)
+
+    built: dict[str, gpd.GeoDataFrame] = {}
+    for module in modules:
+        print(f"Building {module.NAME}...")
+        built.update(module.build(ctx))
+
+    if selected is None:
+        # Only meaningful once every module has run - a module missing
+        # from a --countries subset would otherwise look "invalid".
+        validate_catalog(ctx, built)
+        _purge_stale_files(ctx, built, args.out_dir)
+
+    resolved = resolve_all(ctx, built)
+    print(f"Resolved {len(resolved)} maps to save")
+
+    manifest = _save_all(ctx, resolved, args.out_dir, args.preview)

Review Comment:
   Good catch. `resolve_all` now takes `include_plain`, and a `--countries` 
subset passes `False`, so only the modules actually built get written.



##########
superset-frontend/plugins/plugin-chart-country-map/scripts/maps/assemble.py:
##########
@@ -0,0 +1,84 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Combines the plain country catalog with the registered per-country
+module overrides into the final set of maps to ship, matching the
+notebook's `get_gdf()` + purge-single-subdivision-countries cells.
+"""
+
+from __future__ import annotations
+
+import geopandas as gpd
+
+from .catalog import COUNTRIES, COUNTRY_NAME_ALIASES
+from .context import BuildContext
+
+
+def get_gdf(
+    ctx: BuildContext, built: dict[str, gpd.GeoDataFrame], name: str
+) -> gpd.GeoDataFrame:
+    """Resolves a single country/map name to its GeoDataFrame: a
+    registered module's output if one exists, otherwise a plain Natural
+    Earth lookup by (aliased) admin name.
+    """
+    if name in built:
+        return built[name].copy()
+
+    alias = COUNTRY_NAME_ALIASES.get(name, name)
+    return ctx.df[ctx.df["admin"].str.lower() == alias].copy()
+
+
+def validate_catalog(ctx: BuildContext, built: dict[str, gpd.GeoDataFrame]) -> 
None:
+    """Raises if a plain catalog entry doesn't resolve to any Natural
+    Earth rows (and isn't covered by a registered module instead).
+    """
+    admins = set(ctx.df["admin"].str.lower().unique())
+    invalid = [
+        name
+        for name in COUNTRIES
+        if name not in built and COUNTRY_NAME_ALIASES.get(name, name) not in 
admins
+    ]
+    if invalid:
+        raise ValueError(f"Following country names are not valid: {invalid}")
+
+
+def purged_countries(
+    ctx: BuildContext, built: dict[str, gpd.GeoDataFrame]
+) -> list[str]:
+    """Plain catalog entries with one subdivision or fewer - useless as a
+    choropleth, so dropped from the output (and any stale file for one
+    should be deleted, in case upstream data used to have more).
+    """
+    return [
+        name
+        for name in COUNTRIES
+        if get_gdf(ctx, built, name)["iso_3166_2"].nunique() <= 1
+    ]
+
+
+def resolve_all(
+    ctx: BuildContext, built: dict[str, gpd.GeoDataFrame]
+) -> dict[str, gpd.GeoDataFrame]:
+    """Returns the final {name: GeoDataFrame} map to save: every plain
+    catalog entry with more than one subdivision (others are dropped -
+    they'd be useless as a choropleth), plus every registered module
+    output (region-variant maps included, even though they aren't in
+    the plain catalog at all).
+    """
+    purged = set(purged_countries(ctx, built))
+    kept_plain = [name for name in COUNTRIES if name not in purged]
+    all_names = sorted(set(kept_plain) | set(built.keys()))

Review Comment:
   Same root cause as the `build_maps.py` thread. A subset build now skips the 
plain catalog entirely, so unbuilt module-managed countries are no longer 
re-resolved from raw Natural Earth.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to