File size: 1,878 Bytes
898977e
217f640
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a7afeef
217f640
 
 
 
 
 
a7afeef
 
217f640
 
 
 
 
 
 
 
 
a7afeef
 
217f640
a7afeef
217f640
 
 
 
eb048c0
217f640
 
 
 
 
 
 
 
 
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
# (c) 2022 Jordi Mas i Hernàndez. Licensed under GPL 3.0.
import polib
import re
 
def _remove_accelerators(result):
    CHARS = (
        '_', '&', '~'  # Accelerators.
    )
    for c in CHARS:
        result = result.replace(c, '')

    return result.strip()

def _remove_tags(text):
    clean = re.sub("<[^>]*>", "", text)
    return clean

def _is_non_localized_string(src, trg):
    words_src_len = len(src.split())
    words_trg_len = len(trg.split())
    if words_src_len > 2 and words_trg_len > 2:
        return src == trg

    return False

def _is_invalid(src, trg):
    if len(src) < 2 or len(trg) < 2:
        return True

    if '\n' in src or '\n' in trg:
        return True

    if '@@image' in src or '@@image' in trg:
        return True

    if _is_non_localized_string(src, trg):
        return True

    return False


def generate_tsv(po_filename, output_filename):

    SEPARATOR = '\t'

    input_po = polib.pofile(po_filename)
    entries = 0
    words = 0
    srcs = set()

    with open(po_filename, "r") as source,\
        open(output_filename, "w") as output:

        for entry in input_po:

            src = _remove_accelerators(entry.msgid.strip())
            trg = _remove_accelerators(entry.msgstr.strip())
            src = _remove_tags(src)
            trg = _remove_tags(trg)

            if _is_invalid(src, trg):
                continue

            if SEPARATOR in src or SEPARATOR in trg:
                continue

            if src in srcs:
                continue

            srcs.add(src)
            output.write(f"{src}{SEPARATOR}{trg}\n")
            words += len(src.split())
            entries += 1

    print(f"Generated {entries} entries with {words} words")


def main():

    print("Generate TSV from a PO file")
    generate_tsv("tots-tm.po", "MemoriesProjectesLliures.tsv")

if __name__ == "__main__":
    main()