PopTurk / code /scripts /00_prepare.py
Jyo-K's picture
Upload folder using huggingface_hub
d231962 verified
Raw
History Blame Contribute Delete
3.52 kB
"""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()