File size: 3,137 Bytes
24aaa76
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""R5: split the generator's sentence lists into train / val / test BY SOURCE DOCUMENT.

Rule (written to OUT/text_split.json): document id = the source field before the TAB of sentences.tsv
(wiki:<article id>, fw2:<web document uuid>, ailab:<newspaper>:<file>:<row group>:<row>). bucket = first 8 hex digits of
sha256(document id) read as an integer, modulo 1000. bucket < 900 -> train, 900-949 -> val, 950-999 -> test.
All sentences of one document land in the same split, so no test sentence comes from a training document.
The label vocabulary (words for figure, table and map labels) is rebuilt from the TRAIN sentences only and copied to val and test,
so that a val or test label word was seen in train documents but no val/test sentence leaks into train. geo_labels.json is copied.

usage: python r5_text_split.py --lang kk --src DIR --out DIR
"""
import argparse
import hashlib
import json
import os
import shutil
import sys

sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
from pagesynth import vocab as V  # noqa: E402

ap = argparse.ArgumentParser()
ap.add_argument("--lang", required=True)
ap.add_argument("--src", required=True)
ap.add_argument("--out", required=True)
a = ap.parse_args()


def split_of(doc):
    b = int(hashlib.sha256(doc.encode("utf-8")).hexdigest()[:8], 16) % 1000
    return "train" if b < 900 else ("val" if b < 950 else "test")


files = {}
for sp in ("train", "val", "test"):
    d = os.path.join(a.out, sp, a.lang)
    os.makedirs(d, exist_ok=True)
    files[sp] = open(os.path.join(d, "sentences.tsv"), "w", encoding="utf-8")
cnt = {sp: 0 for sp in files}
docs = {sp: set() for sp in files}
train_sents = []
n = 0
with open(os.path.join(a.src, a.lang, "sentences.tsv"), encoding="utf-8") as f:
    for line in f:
        line = line.rstrip("\n")
        if not line:
            continue
        src, _, txt = line.partition("\t")
        sp = split_of(src)
        files[sp].write(src + "\t" + txt + "\n")
        cnt[sp] += 1
        docs[sp].add(src)
        if sp == "train":
            train_sents.append(txt)
        n += 1
for f in files.values():
    f.close()
low, cap = V.count_words(train_sents, a.lang, 20, 0.02)
chosen, stats = V.select_words(low, cap, a.lang, 20, 0.02)
vocab = dict(lang=a.lang, source="sentences.tsv of the TRAIN split", sentences=len(train_sents), min_lower_count=20, max_capitalised_ratio=0.02,
             words=[w for w, _ in chosen], counts=[c for _, c in chosen], words_with_letter=stats)
for sp in files:
    d = os.path.join(a.out, sp, a.lang)
    with open(os.path.join(d, "label_words.json"), "w", encoding="utf-8") as f:
        json.dump(vocab, f, ensure_ascii=False)
    g = os.path.join(a.src, a.lang, "geo_labels.json")
    if os.path.exists(g):
        shutil.copy(g, os.path.join(d, "geo_labels.json"))
res = dict(lang=a.lang, sentences_total=n, sentences={sp: cnt[sp] for sp in cnt}, documents={sp: len(docs[sp]) for sp in docs}, label_words=len(vocab["words"]))
with open(os.path.join(a.out, "split_stats_%s.json" % a.lang), "w", encoding="utf-8") as f:
    json.dump(res, f, indent=1)
print(json.dumps(res))