| 1 | from collections import Counter |
| 2 | from google.protobuf import text_format |
| 3 | from gflanguages import languages_public_pb2 |
| 4 | |
| 5 | ATTRIBUTES = "base auxiliary marks punctuation index".split(" ") |
| 6 | |
| 7 | |
| 8 | def main(args=None): |
| 9 | for path in args: |
| 10 | with open(path, encoding="utf-8") as fp: |
| 11 | language = text_format.Parse( |
| 12 | fp.read(), languages_public_pb2.LanguageProto() |
| 13 | ) |
| 14 | changed = False |
| 15 | exemplar_values = {} |
| 16 | if not hasattr(language, "exemplar_chars"): |
| 17 | exit() |
| 18 | for attr in ATTRIBUTES: |
| 19 | if hasattr(language.exemplar_chars, attr): |
| 20 | values = getattr(language.exemplar_chars, attr).split(" ") |
| 21 | value_set = set() |
| 22 | clean_values = [] |
| 23 | for value in values: |
| 24 | if value in value_set: |
| 25 | continue |
| 26 | else: |
| 27 | value_set.add(value) |
| 28 | clean_values.append(value) |
| 29 | |
| 30 | if clean_values != values: |
| 31 | if {len(set(values))} != {len(set(clean_values))}: |
| 32 | print("before: "+ " ".join(values)) |
| 33 | print("after: "+ " ".join(clean_values)) |
| 34 | sys.exit("Failed fixing exemplar.") |
| 35 | setattr(language.exemplar_chars, attr, " ".join(clean_values)) |
| 36 | changed = True |
| 37 | exemplar_values[attr] = { |
| 38 | "before": values, |
| 39 | "after": clean_values |
| 40 | } |
| 41 | |
| 42 | if changed: |
| 43 | for exemplar, values in exemplar_values.items(): |
| 44 | before = values["before"] |
| 45 | after = values["after"] |
| 46 | counter = Counter(before) |
| 47 | duplicates = [(g, c - 1) for g, c in counter.most_common() if c > 1] |
| 48 | print( |
| 49 | f"Changed {path} {exemplar} exemplar:\n" |
| 50 | f"- from {len(before)} ({len(set(before))} as set) " |
| 51 | f"to {len(after)} elements\n" |
| 52 | f"- removing {len(before) - len(after)} duplicate(s):\n" |
| 53 | f" {duplicates}\n" |
| 54 | ) |
| 55 | with open(path, "w", encoding="utf-8") as fp: |
| 56 | fp.write(text_format.MessageToString(language, as_utf8=True)) |
| 57 | fp.close() |
| 58 | |
| 59 | |
| 60 | if __name__ == "__main__": |
| 61 | import sys |
| 62 | |
| 63 | main(args=sys.argv[1:]) |