generate_codepoint_requirements.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. # Copyright 2024 Google LLC
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import json, argparse, codecs, re, os
  15. def generate_codepoint_requirements(path, encoding='utf-8', controlchars=False):
  16. latin_start = 0x20
  17. latin_end = 0x2AF
  18. lang = None
  19. codepoints = set()
  20. with codecs.open(path, encoding=encoding, mode='r') as fin:
  21. for line in fin:
  22. if lang is None:
  23. langstr = re.search(r"^\"Language: (\w*)", line)
  24. lang = langstr.group(1) if langstr else None
  25. continue
  26. msgstr = re.search("^msgstr \"(.*)\"$", line)
  27. if msgstr and len(msgstr.group(1)) > 0:
  28. for char in msgstr.group(1):
  29. codepoints.update(char)
  30. required_codepoints = [ord(c) for c in codepoints if ord(c) > latin_end or (ord(c) < latin_start and controlchars)]
  31. return {'language': lang, 'codepoints': required_codepoints}
  32. def main():
  33. parser = argparse.ArgumentParser(description="Given a PO file, generate a JSON file containing the codepoints required to display the translated strings")
  34. parser.add_argument('input', help="Path to PO file containing translated strings")
  35. parser.add_argument('--output', help="Path to output JSON file containing codepoints")
  36. parser.add_argument('--encoding', help="Set encoding of input file (default is utf-8)", default='utf-8')
  37. parser.add_argument('--controlchars', help="If set, control characters (U+0000 - U+001F) will not be excluded", action='store_true')
  38. args = parser.parse_args()
  39. if args.output is None:
  40. args.output = os.path.splitext(args.input)[0] + '.json'
  41. fout = open(args.output, mode='w')
  42. fout.write(json.dumps(generate_codepoint_requirements(args.input, args.encoding, args.controlchars), indent=2))
  43. if __name__ == "__main__":
  44. main()