sts-tr-dataset / make_dataset.py
ErenYanic's picture
Merge nursimakgul's 38 scored pairs; dataset is now 81 pairs from two contributors
0e9d0f7 verified
Raw
History Blame Contribute Delete
7.55 kB
"""
Turn the `id2` pairings in raw_sentences.csv into an STS dataset.
Two steps:
1. python3 make_dataset.py extract
Follows the `id2` column, de-duplicates the pairs (a pair marked from
both sides is still one pair) and writes pairs_to_score.csv with an
empty `score` column.
2. python3 make_dataset.py build
Concatenates every scored CSV in SCORED (each contributor's own file) and
writes sts_tr_dataset.parquet with exactly three columns -- sentence1,
sentence2, score -- matching the standard STS format. Pairs duplicated
across contributors are reported and kept only once.
`extract` refuses to overwrite a pairs_to_score.csv that already has scores in
it; pass --force to override. Scoring is hand work and is not recoverable from
raw_sentences.csv.
"""
import argparse
import csv
import re
import sys
from pathlib import Path
import pyarrow as pa
import pyarrow.parquet as pq
HERE = Path(__file__).parent
RAW = HERE / "raw_sentences.csv"
PAIRS = HERE / "pairs_to_score.csv"
OUT = HERE / "sts_tr_dataset.parquet"
# One scored CSV per contributor, each with sentence1, sentence2, score.
# Keeping them as separate files means neither person's scoring can be
# clobbered by the other's, and provenance stays traceable after the merge.
SCORED = [
("Erenyanic", PAIRS),
("nursimakgul", HERE / "sts_data.csv"),
]
SCORE_MIN, SCORE_MAX = 0.0, 5.0
def read_raw():
with open(RAW, encoding="utf-8") as f:
rows = list(csv.DictReader(f))
if "id2" not in rows[0]:
sys.exit("raw_sentences.csv has no id2 column -- nothing to pair.")
return rows
def guard_existing_scores(force):
"""Scoring is hand work. Losing it to an accidental re-run costs hours and
cannot be rebuilt from raw_sentences.csv, which holds no scores."""
if force or not PAIRS.exists():
return
with open(PAIRS, encoding="utf-8") as f:
scored = sum(1 for r in csv.DictReader(f) if (r.get("score") or "").strip())
if scored:
sys.exit(f"{PAIRS.name} already has {scored} scored row(s). "
f"Refusing to overwrite. Re-run with --force if you mean it.")
def extract(force=False):
guard_existing_scores(force)
rows = read_raw()
by_id = {r["id"]: r for r in rows}
seen, pairs, problems = set(), [], []
for r in rows:
target = r["id2"].strip()
if not target:
continue
if target == r["id"]:
problems.append(f"id {r['id']} pairs with itself")
continue
if target not in by_id:
problems.append(f"id {r['id']} -> id2 {target}: no such id")
continue
# A pair marked from both sides is one pair, not two.
key = frozenset({r["id"], target})
if key in seen:
continue
seen.add(key)
# Lower id first, so the output is stable across runs.
a, b = sorted(key, key=int)
pairs.append({
"sentence1": by_id[a]["sentence"],
"sentence2": by_id[b]["sentence"],
"score": "",
"_sort": int(a),
})
if problems:
print("problems found:")
for p in problems:
print(" ", p)
pairs.sort(key=lambda p: p.pop("_sort"))
with open(PAIRS, "w", newline="", encoding="utf-8") as f:
w = csv.DictWriter(f, fieldnames=["sentence1", "sentence2", "score"])
w.writeheader()
w.writerows(pairs)
print(f"{len(pairs)} pairs -> {PAIRS.name}")
print(f"Fill in the `score` column (0-5), then run: python3 {Path(__file__).name} build")
def norm(s):
"""Whitespace- and case-insensitive form, for duplicate detection only."""
return re.sub(r"\s+", " ", (s or "").strip()).lower()
def read_scored(who, path):
"""Validate one contributor's scored CSV and return its rows."""
with open(path, encoding="utf-8") as f:
rows = list(csv.DictReader(f))
out, missing, bad = [], [], []
for i, r in enumerate(rows, 2): # line 2 = first data row
raw = (r.get("score") or "").strip().replace(",", ".")
if not raw:
missing.append(i)
continue
try:
v = float(raw)
except ValueError:
bad.append(f"{path.name} line {i}: {raw!r} is not a number")
continue
if not SCORE_MIN <= v <= SCORE_MAX:
bad.append(f"{path.name} line {i}: {v} outside [{SCORE_MIN}, {SCORE_MAX}]")
continue
s1, s2 = (r.get("sentence1") or "").strip(), (r.get("sentence2") or "").strip()
if not s1 or not s2:
bad.append(f"{path.name} line {i}: empty sentence")
continue
if norm(s1) == norm(s2):
bad.append(f"{path.name} line {i}: sentence1 and sentence2 are identical")
continue
out.append({"sentence1": s1, "sentence2": s2, "score": v, "who": who})
if missing:
sys.exit(f"{path.name}: {len(missing)} row(s) have no score (lines: "
f"{', '.join(map(str, missing[:12]))}"
f"{'...' if len(missing) > 12 else ''}). Fill them in first.")
if bad:
print("invalid rows:")
for b in bad:
print(" ", b)
sys.exit(1)
return out
def build():
merged, seen, dupes = [], {}, []
for who, path in SCORED:
if not path.exists():
print(f"note: {path.name} not found, skipping {who}")
continue
rows = read_scored(who, path)
print(f" {who:12s} {len(rows):>3} pairs from {path.name}")
for r in rows:
# A pair is the same pair regardless of which side each sentence is
# on, so an unordered key catches a pair scored by both people.
key = frozenset({norm(r["sentence1"]), norm(r["sentence2"])})
if key in seen:
first = seen[key]
dupes.append(f"{r['who']} repeats a pair from {first['who']} "
f"(scores {first['score']} vs {r['score']}): "
f"{r['sentence1'][:60]}")
continue
seen[key] = r
merged.append(r)
if not merged:
sys.exit("no scored pairs found.")
if dupes:
print(f"\n{len(dupes)} duplicate pair(s) dropped, first occurrence kept:")
for d in dupes:
print(" ", d)
table = pa.table({
"sentence1": pa.array([r["sentence1"] for r in merged], pa.string()),
"sentence2": pa.array([r["sentence2"] for r in merged], pa.string()),
"score": pa.array([r["score"] for r in merged], pa.float64()),
})
pq.write_table(table, OUT)
scores = [r["score"] for r in merged]
dist = {}
for v in scores:
dist[v] = dist.get(v, 0) + 1
print(f"\n{len(merged)} pairs -> {OUT.name}")
print(f" schema: {', '.join(f'{n}: {t}' for n, t in zip(table.column_names, table.schema.types))}")
print(f" mean score: {sum(scores) / len(scores):.2f}")
print(" distribution:", dict(sorted(dist.items())))
if __name__ == "__main__":
ap = argparse.ArgumentParser(description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("step", choices=["extract", "build"])
ap.add_argument("--force", action="store_true",
help="allow extract to overwrite an already-scored pairs file")
args = ap.parse_args()
if args.step == "extract":
extract(force=args.force)
else:
build()