poiss / scripts /join_overture.py
feboraz's picture
POISS v1: data, id map, quality scores, join script, card
c8a3706 verified
Raw History Blame Contribute Delete
9.1 kB
"""Recover POI fields for POISS candidates from a live Overture Maps release.
POISS ships Overture GERS identifiers only, so POI content (name, address,
coordinate, categories) has to be joined from Overture itself. The snapshot the
dataset was built on (release 2026-03-18) is past Overture's 60-day retention
window, and Overture reassigns some identifiers when it re-conflates the corpus,
so this script resolves identifiers in two steps:
1. look the identifier up directly in the target release;
2. if it is absent, translate it through ``data/overture_id_map.parquet``
(old id -> current id, derived from the provider record ids the two releases
share) and look the translation up.
Identifiers that survive neither step correspond to POIs Overture has deleted;
they are reported as unresolved rather than silently dropped.
Example
-------
python scripts/join_overture.py \\
--dataset-dir data --split test \\
--release 2026-08-19.0 \\
--out test_pois.parquet
Requires: pyarrow, tqdm (and shapely for latitude/longitude extraction).
"""
import argparse
import glob
import json
import os
import struct
import pyarrow as pa
import pyarrow.dataset as pads
import pyarrow.fs as pafs
import pyarrow.parquet as pq
from tqdm import tqdm
POI_COLUMNS = ["id", "names", "addresses", "categories", "confidence", "geometry"]
BUCKET = "overturemaps-us-west-2"
def load_candidate_ids(dataset_dir, split, limit):
"""Distinct candidate identifiers referenced by the dataset."""
files = sorted(glob.glob(os.path.join(dataset_dir, f"{split}-*.parquet")))
if not files:
raise SystemExit(f"no {split}-*.parquet under {dataset_dir}")
ids, rows = set(), 0
for path in tqdm(files, desc=f"reading {split}"):
table = pq.read_table(path, columns=["candidates"])
for candidates in table.column("candidates"):
ids.update(value.as_py() for value in candidates)
rows += 1
if limit and rows >= limit:
return ids, rows
return ids, rows
def load_id_map(path):
if not path or not os.path.exists(path):
print("no id map supplied: identifiers reassigned by Overture will stay unresolved")
return {}
table = pq.read_table(path, columns=["old_id", "new_id"])
mapping = dict(zip(table.column("old_id").to_pylist(), table.column("new_id").to_pylist()))
print(f"id map entries: {len(mapping)}")
return mapping
def scan_release(release, wanted, region, columns):
"""Fetch POI rows whose identifier is in `wanted` (target id -> dataset id)."""
s3 = pafs.S3FileSystem(anonymous=True, region=region)
prefix = f"{BUCKET}/release/{release}/theme=places/type=place"
files = [f.path for f in s3.get_file_info(pafs.FileSelector(prefix)) if f.size]
if not files:
raise SystemExit(
f"release {release} exposes no files. Overture keeps only the last ~60 days; "
"pick a current release."
)
print(f"{release}: {len(files)} parquet files")
pieces = []
for path in tqdm(files, desc="scanning release"):
table = pads.dataset(path, filesystem=s3, format="parquet").to_table(columns=columns)
# membership tested against a Python set: pyarrow's is_in rebuilds its
# hash table per call, which dominates at tens of millions of values
hits = [i for i, value in enumerate(table.column("id").to_pylist()) if value in wanted]
if hits:
pieces.append(table.take(hits))
return pa.concat_tables(pieces) if pieces else None
def _wkb_point(blob):
"""Minimal WKB point reader, so shapely stays optional."""
if blob is None or len(blob) < 21:
raise ValueError("not a WKB point")
byte_order = "<" if blob[0] == 1 else ">"
geom_type = struct.unpack(byte_order + "I", blob[1:5])[0]
if geom_type & 0xFF != 1:
raise ValueError(f"unsupported WKB geometry type {geom_type}")
x, y = struct.unpack(byte_order + "dd", blob[5:21])
return x, y
def add_coordinates(table):
try:
from shapely import wkb
def parse(blob):
point = wkb.loads(blob)
return point.x, point.y
except ImportError:
parse = _wkb_point
lats, lons = [], []
for blob in table.column("geometry").to_pylist():
try:
x, y = parse(blob)
lats.append(float(y))
lons.append(float(x))
except Exception:
lats.append(None)
lons.append(None)
return table.append_column("latitude", pa.array(lats, pa.float64())).append_column(
"longitude", pa.array(lons, pa.float64())
)
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--dataset-dir", default="data", help="directory holding the split parquet")
ap.add_argument("--split", default="test", choices=["train", "test"])
ap.add_argument("--release", default="2026-08-19.0", help="target Overture release")
ap.add_argument("--id-map", default="data/overture_id_map.parquet")
ap.add_argument("--region", default="us-west-2")
ap.add_argument("--out", required=True, help="output parquet for the POI table")
ap.add_argument("--score-file", default="data/poi_quality_score.parquet",
help="per-POI quality score; set to '' to skip")
ap.add_argument("--report", default=None, help="optional coverage report json")
ap.add_argument("--limit", type=int, default=0, help="cap the number of queries read")
ap.add_argument("--drop-geometry", action="store_true")
args = ap.parse_args()
candidate_ids, queries = load_candidate_ids(args.dataset_dir, args.split, args.limit)
print(f"queries: {queries}, distinct candidate ids: {len(candidate_ids)}")
id_map = load_id_map(args.id_map)
# target identifier -> identifier as it appears in the dataset
wanted = {pid: pid for pid in candidate_ids}
translated = 0
for pid in candidate_ids:
successor = id_map.get(pid)
if successor and successor not in wanted:
wanted[successor] = pid
translated += 1
print(f"identifiers with a mapped successor: {translated}")
columns = POI_COLUMNS
table = scan_release(args.release, wanted, args.region, columns)
if table is None:
raise SystemExit("no candidate POI was found in the target release")
target_ids = table.column("id").to_pylist()
dataset_ids = [wanted[value] for value in target_ids]
# a dataset identifier can hit twice when both it and its mapped successor
# still exist in the target release: keep the direct hit
chosen = {}
for index, (target, original) in enumerate(zip(target_ids, dataset_ids)):
if original not in chosen or target == original:
chosen[original] = index
keep = sorted(chosen.values())
if len(keep) != table.num_rows:
print(f"dropped {table.num_rows - len(keep)} duplicate resolutions")
table = table.take(keep)
target_ids = [target_ids[i] for i in keep]
dataset_ids = [dataset_ids[i] for i in keep]
table = table.append_column("poiss_candidate_id", pa.array(dataset_ids, pa.string()))
table = table.rename_columns(
["overture_id" if name == "id" else name for name in table.column_names]
)
table = add_coordinates(table)
if args.drop_geometry:
table = table.drop(["geometry"])
# the quality score the cross-encoder consumes is not an Overture field: it
# ships with the dataset, keyed by the identifier as it appears in POISS
scored = 0
if args.score_file and os.path.exists(args.score_file):
score_table = pq.read_table(args.score_file)
lookup = dict(
zip(score_table.column("overture_id").to_pylist(),
score_table.column("score").to_pylist())
)
scores = [lookup.get(pid) for pid in dataset_ids]
scored = sum(1 for value in scores if value is not None)
table = table.append_column("quality_score", pa.array(scores, pa.float32()))
print(f"quality score attached for {scored} of {table.num_rows} POIs")
elif args.score_file:
print(f"score file not found at {args.score_file}: skipping quality_score")
resolved = set(dataset_ids)
unresolved = len(candidate_ids) - len(resolved)
report = {
"split": args.split,
"target_release": args.release,
"queries": queries,
"candidate_ids": len(candidate_ids),
"resolved": len(resolved),
"resolved_via_id_map": sum(1 for a, b in zip(target_ids, dataset_ids) if a != b),
"unresolved": unresolved,
"unresolved_pct": round(100 * unresolved / max(1, len(candidate_ids)), 2),
"poi_rows": table.num_rows,
"with_quality_score": scored,
}
print(json.dumps(report, indent=1))
pq.write_table(table, args.out, compression="zstd")
print(f"wrote {args.out}")
if args.report:
with open(args.report, "w") as handle:
json.dump(report, handle, indent=1)
if __name__ == "__main__":
main()