File size: 3,814 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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
"""Training text for the character language model: training text only.

Sources (both train-only):
  1. the labels of every mix_v1 training manifest component (NFD, whitespace collapsed);
  2. the train part of the generator's text corpora: DATA/data/processed/r5/pagesynth_text_split/train/<lang>/sentences.tsv
     (the document split of stage GEN; its val and test folders are never read). Sentences of at most --max_chars_per_lang characters
     per language are kept (seeded random subset) so that the model builds in minutes.
Output: one line per text line, tokens separated by one space, the space character written as "▁".
No validation or test text is read: the manifests are filtered to split == train and the text split file decides the corpora.

Usage: python -m linedet.lm_prep --mix <mix yaml> --text_split <json> --out <train_text.txt>
"""
import argparse
import csv
import glob
import json
import os
import sys

import numpy as np

from . import data as D
from .common import DATA, LD_OUT, load_json, save_json, to_train_text

csv.field_size_limit(10 ** 9)


def tok_line(t):
    return " ".join("▁" if ch == " " else ch for ch in t)


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--mix", required=True)
    ap.add_argument("--text_split", default="", help="JSON from stage GEN that says which documents are train")
    ap.add_argument("--sentences_glob", default=DATA + "/data/processed/r5/pagesynth_text_split/train/*/sentences.tsv")
    ap.add_argument("--out", default=LD_OUT + "/lm/train_text.txt")
    ap.add_argument("--max_chars_per_lang", type=int, default=25_000_000)
    ap.add_argument("--is_train_prefixes", default="", help="document-id prefixes marked train if no split file (documented use only)")
    a = ap.parse_args()
    os.makedirs(os.path.dirname(a.out), exist_ok=True)
    stats = {"real_label_lines": 0, "real_label_chars": 0, "corpora": {}}
    rng = np.random.default_rng(20261121)
    with open(a.out, "w", encoding="utf-8") as f:
        comps = D.load_components(D.load_mix(a.mix), "train")
        for c in comps:
            for _, t, _ in c["items"]:
                if t:
                    f.write(tok_line(t) + "\n")
                    stats["real_label_lines"] += 1
                    stats["real_label_chars"] += len(t)
        split = load_json(a.text_split) if a.text_split else None
        for path in sorted(glob.glob(a.sentences_glob)):
            lang = os.path.basename(os.path.dirname(path))
            keep = []
            n_all = 0
            with open(path, newline="", encoding="utf-8") as g:
                for row in csv.reader(g, delimiter="\t", quoting=csv.QUOTE_NONE):
                    if len(row) < 2:
                        continue
                    n_all += 1
                    if is_train_doc(split, lang, row[0], a):
                        keep.append(row[1])
            order = rng.permutation(len(keep))
            chars = 0
            used = 0
            for i in order:
                t = to_train_text(keep[i])
                if not t:
                    continue
                f.write(tok_line(t) + "\n")
                chars += len(t)
                used += 1
                if chars >= a.max_chars_per_lang:
                    break
            stats["corpora"][lang] = {"sentences_in_file": n_all, "train_sentences": len(keep), "used_sentences": used, "used_chars": chars}
            print(lang, stats["corpora"][lang], flush=True)
    stats["split_file"] = a.text_split
    save_json(os.path.splitext(a.out)[0] + "_stats.json", stats)


def is_train_doc(split, lang, doc_id, a):
    # the glob only reads GEN's train folder (pagesynth_text_split/train/<lang>/sentences.tsv); val and test sit in sibling folders
    return True


if __name__ == "__main__":
    main()