Cotton code
78 lines · 2.9 KB · PythonRaw
#!/usr/bin/env python3"""UJIpenchars2 into the ink corpus: `corpus-ujipenchars2.py <ujipenchars2.txt> <out dir>`.UJIpenchars2 (Prat, Castro, Llorens, Marzal and Vilar, 2008; UCI dataset 177,CC BY 4.0) is 60 writers each writing every character twice with a stylus ona tablet PC. Only a–z, A–Z and 0–9 are taken. Its points carry no time, so t issynthesised (`ink_corpus.POINT_MS` a point, `GAP_MS` between strokes).The file (Latin-1) is UNIPEN-like:    WORD a trn_UJI_W01-01      NUMSTROKES 1      POINTS 44 # 557 844 550 803 ...the writer is the sample id less its repetition (`trn_UJI_W01`). A samplewhose stroke count or point count disagrees with its header is a broken fileand stops the conversion."""import osimport reimport syssys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))import ink_corpus  # noqa: E402DATASET = "ujipenchars2"SYMBOL = re.compile(r"[A-Za-z0-9]")def samples(text):    """(character, sample id, strokes) for every sample in the file."""    lines = [l.strip() for l in text.splitlines()]    lines = [l for l in lines if l and not l.startswith("//")]    i = 0    while i < len(lines):        head = lines[i].split()        if len(head) != 3 or head[0] != "WORD":            raise ValueError(f"expected 'WORD <char> <id>', got {lines[i]!r}")        char, sample = head[1], head[2]        count = lines[i + 1].split()        if len(count) != 2 or count[0] != "NUMSTROKES":            raise ValueError(f"{sample}: expected NUMSTROKES, got {lines[i + 1]!r}")        strokes = []        for k in range(int(count[1])):            fields = lines[i + 2 + k].split()            if fields[0] != "POINTS" or fields[2] != "#":                raise ValueError(f"{sample}: expected POINTS n #, got {lines[i + 2 + k]!r}")            numbers = [int(v) for v in fields[3:]]            if len(numbers) != 2 * int(fields[1]):                raise ValueError(f"{sample}: POINTS {fields[1]} but {len(numbers)} numbers")            strokes.append([[numbers[j], numbers[j + 1], None] for j in range(0, len(numbers), 2)])        yield char, sample, strokes        i += 2 + int(count[1])def main(argv):    if len(argv) != 3:        sys.exit("usage: corpus-ujipenchars2.py <ujipenchars2.txt> <out dir>")    with open(argv[1], encoding="latin-1") as f:        text = f.read()    rows, skipped = [], 0    for char, sample, strokes in samples(text):        if not SYMBOL.fullmatch(char):            continue        writer = sample.rsplit("-", 1)[0]        row = ink_corpus.line(strokes, char, writer, DATASET, "stylus")        if row is None:            skipped += 1        else:            rows.append(row)    timing = f"synthesised: {ink_corpus.POINT_MS} ms a point, {ink_corpus.GAP_MS} ms between strokes"    stats = ink_corpus.write(rows, skipped, argv[2], DATASET, timing)    print(f"{DATASET}: {stats['lines']} symbols, {stats['writers']} writers, {skipped} skipped")if __name__ == "__main__":    main(sys.argv)