File size: 1,988 Bytes
0cc835c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Label generated sentences blind with one teacher: python label.py gen.jsonl model out.jsonl"""

import sys
import json
import random
import threading
from pathlib import Path
from concurrent.futures import ThreadPoolExecutor

from huggingface_hub import InferenceClient

from labels import label_batch
from hard_cases import CASES

BATCH = 25
gen_path, model, out_path = Path(sys.argv[1]), sys.argv[2], Path(sys.argv[3])
hard = {c[2].strip().lower() for c in CASES}

seen: set[tuple[str, str]] = set()
items: list[tuple[str, str]] = []
for line in gen_path.open():
    request = json.loads(line)
    for sentence in request["sentences"]:
        key = (request["kind"], sentence.strip())
        if key not in seen and sentence.strip().lower() not in hard:
            seen.add(key)
            items.append(key)

done = set()
if out_path.exists():
    done = {(r["kind"], r["text"]) for r in map(json.loads, out_path.open())}
todo = [i for i in items if i not in done]
random.Random(0).shuffle(todo)  # mixes topics and languages inside a batch, so the teacher sees each sentence in varied company
batches = [(kind, [t for k, t in todo if k == kind]) for kind in ("say", "react")]
batches = [(kind, texts[i : i + BATCH]) for kind, texts in batches for i in range(0, len(texts), BATCH)]
print(f"{len(items)} unique sentences, {len(todo)} to label in {len(batches)} batches", flush=True)

client = InferenceClient(provider="auto", timeout=600)
lock = threading.Lock()


def run(batch: tuple[str, list[str]]) -> None:
    kind, texts = batch
    out = label_batch(client, model, kind, texts)
    if out is None:
        print(f"  gave up on a {kind} batch", flush=True)
        return
    with lock, out_path.open("a") as f:
        for text, label in zip(texts, out):
            f.write(json.dumps({"kind": kind, "text": text, **label}, ensure_ascii=False) + "\n")


with ThreadPoolExecutor(int(__import__("os").environ.get("THREADS", "12"))) as pool:
    list(pool.map(run, batches))