File size: 3,523 Bytes
d231962
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Step 0. Raw TSV -> parquet, plus the small side-tables every later stage needs.

Run once per split, on the college box. Cheap (a few minutes) and it removes the largest
recurring cost in the whole pipeline: re-parsing 10.3M TSV rows in every process that needs
a business name.

WHAT IT WRITES, all under BERX_WORK/prep/<split>/
    source{1,2,3}.parquet   raw columns, row order preserved exactly
    pool.parquet            S2 rows then S3 rows, concatenated - this concatenation order is
                            the contract every embedding matrix and every candidate index in
                            this codebase assumes
    country_s1.npy          per-row country code, for the country-blocked retrieval
    country_pool.npy
    ids.json                id <-> row maps, so a stage can check an index instead of trusting it

The row-order assertion is not defensive padding. Embeddings were produced in source order and
are addressed positionally; a single reordered row shifts every candidate index after it and
produces a submission that is wrong in a way no validator catches.
"""
from __future__ import annotations

import argparse
import json
import os
import sys

import numpy as np
import pandas as pd

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from berx import paths as P  # noqa: E402

COLS = ["entity_id", "business_name", "business_address", "country"]


def read_source(split: str, i: int) -> pd.DataFrame:
    p = P.raw(split, i)
    if p.endswith(".parquet"):
        return pd.read_parquet(p)
    return pd.read_csv(p, sep="\t", dtype=str, keep_default_na=False, na_filter=False)


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--split", default="test", choices=["train", "test"])
    a = ap.parse_args()
    out = P.work("prep", a.split, "_")
    out = os.path.dirname(out)
    os.makedirs(out, exist_ok=True)

    frames = {}
    for i in (1, 2, 3):
        df = read_source(a.split, i)
        missing = [c for c in COLS if c not in df.columns]
        assert not missing, f"source{i} is missing {missing}; got {list(df.columns)}"
        df = df[COLS]
        assert df["entity_id"].is_unique, f"source{i} has duplicate entity_id"
        df.to_parquet(os.path.join(out, f"source{i}.parquet"), index=False)
        frames[i] = df
        print(f"  source{i}: {len(df):>10,} rows  "
              f"{df['country'].value_counts().to_dict()}")

    pool = pd.concat([frames[2], frames[3]], ignore_index=True)
    pool.to_parquet(os.path.join(out, "pool.parquet"), index=False)
    print(f"  pool    : {len(pool):>10,} rows (S2 {len(frames[2]):,} then S3 {len(frames[3]):,})")

    # country codes as small ints; the mapping is written out so nothing has to guess it
    cats = sorted(set(frames[1]["country"]) | set(pool["country"]))
    cmap = {c: i for i, c in enumerate(cats)}
    np.save(os.path.join(out, "country_s1.npy"),
            frames[1]["country"].map(cmap).to_numpy(np.int8))
    np.save(os.path.join(out, "country_pool.npy"),
            pool["country"].map(cmap).to_numpy(np.int8))

    with open(os.path.join(out, "ids.json"), "w") as fh:
        json.dump({"country_map": cmap, "n_s1": len(frames[1]),
                   "n_s2": len(frames[2]), "n_s3": len(frames[3]),
                   "n_pool": len(pool)}, fh, indent=1)

    empt = (pool["business_address"].str.strip() == "").mean()
    print(f"  empty-address rate in pool: {empt:.3%}")
    print(f"  wrote {out}")


if __name__ == "__main__":
    main()