File size: 7,547 Bytes
b294a6e
 
 
 
 
 
 
 
 
 
 
0e9d0f7
 
 
 
b294a6e
 
 
 
 
 
 
 
0e9d0f7
b294a6e
 
 
 
 
 
 
 
 
 
 
0e9d0f7
 
 
 
 
 
 
 
b294a6e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0e9d0f7
 
 
 
b294a6e
0e9d0f7
 
 
 
 
b294a6e
 
 
 
 
 
 
 
0e9d0f7
b294a6e
 
0e9d0f7
b294a6e
0e9d0f7
 
 
b294a6e
0e9d0f7
 
 
 
b294a6e
0e9d0f7
b294a6e
 
 
 
 
 
 
0e9d0f7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b294a6e
 
0e9d0f7
 
 
b294a6e
 
 
0e9d0f7
b294a6e
 
 
0e9d0f7
b294a6e
0e9d0f7
 
b294a6e
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
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()