File size: 9,095 Bytes
c8a3706
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
"""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()