lionbridge_import.py 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  1. # Copyright (c) 2019 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. import argparse #To get the source directory from command line arguments.
  4. import io # To fix encoding issues in Windows
  5. import os #To find files from the source.
  6. import os.path #To find files from the source and the destination path.
  7. cura_files = {"cura", "fdmprinter.def.json", "fdmextruder.def.json"}
  8. uranium_files = {"uranium"}
  9. def lionbridge_import(source: str) -> None:
  10. """Imports translation files from Lionbridge.
  11. Lionbridge has a bit of a weird export feature. It exports it to the same
  12. file type as what we imported, so that's a .pot file. However this .pot file
  13. only contains the translations, so the header is completely empty. We need
  14. to merge those translations into our existing files so that the header is
  15. preserved.
  16. """
  17. print("Importing from:", source)
  18. print("Importing to Cura:", destination_cura())
  19. print("Importing to Uranium:", destination_uranium())
  20. for language in (directory for directory in os.listdir(source) if os.path.isdir(os.path.join(source, directory))):
  21. print("================ Processing language:", language, "================")
  22. directory = os.path.join(source, language)
  23. for file_pot in (file for file in os.listdir(directory) if file.endswith(".pot")):
  24. source_file = file_pot[:-4] #Strip extension.
  25. if source_file in cura_files:
  26. destination_file = os.path.join(destination_cura(), language.replace("-", "_"), source_file + ".po")
  27. print("Merging", source_file, "(Cura) into", destination_file)
  28. elif source_file in uranium_files:
  29. destination_file = os.path.join(destination_uranium(), language.replace("-", "_"), source_file + ".po")
  30. print("Merging", source_file, "(Uranium) into", destination_file)
  31. else:
  32. raise Exception("Unknown file: " + source_file + "... Is this Cura or Uranium?")
  33. with io.open(os.path.join(directory, file_pot), encoding = "utf8") as f:
  34. source_str = f.read()
  35. with io.open(destination_file, encoding = "utf8") as f:
  36. destination_str = f.read()
  37. result = merge(source_str, destination_str)
  38. with io.open(destination_file, "w", encoding = "utf8") as f:
  39. f.write(result)
  40. def destination_cura() -> str:
  41. """Gets the destination path to copy the translations for Cura to.
  42. :return: Destination path for Cura.
  43. """
  44. return os.path.abspath(os.path.join(__file__, "..", "..", "resources", "i18n"))
  45. def destination_uranium() -> str:
  46. """Gets the destination path to copy the translations for Uranium to.
  47. :return: Destination path for Uranium.
  48. """
  49. try:
  50. import UM
  51. except ImportError:
  52. relative_path = os.path.join(__file__, "..", "..", "..", "Uranium", "resources", "i18n", "uranium.pot")
  53. absolute_path = os.path.abspath(relative_path)
  54. if os.path.exists(absolute_path):
  55. absolute_path = os.path.abspath(os.path.join(absolute_path, ".."))
  56. print("Uranium is at:", absolute_path)
  57. return absolute_path
  58. else:
  59. raise Exception("Can't find Uranium. Please put UM on the PYTHONPATH or put the Uranium folder next to the Cura folder. Looked for: " + absolute_path)
  60. return os.path.abspath(os.path.join(UM.__file__, "..", "..", "resources", "i18n"))
  61. def merge(source: str, destination: str) -> str:
  62. """Merges translations from the source file into the destination file if they
  63. were missing in the destination file.
  64. :param source: The contents of the source .po file.
  65. :param destination: The contents of the destination .po file.
  66. """
  67. result_lines = []
  68. last_destination = {
  69. "msgctxt": "\"\"\n",
  70. "msgid": "\"\"\n",
  71. "msgstr": "\"\"\n",
  72. "msgid_plural": "\"\"\n"
  73. }
  74. current_state = "none"
  75. for line in destination.split("\n"):
  76. if line.startswith("msgctxt \""):
  77. current_state = "msgctxt"
  78. line = line[8:]
  79. last_destination[current_state] = ""
  80. elif line.startswith("msgid \""):
  81. current_state = "msgid"
  82. line = line[6:]
  83. last_destination[current_state] = ""
  84. elif line.startswith("msgstr \""):
  85. current_state = "msgstr"
  86. line = line[7:]
  87. last_destination[current_state] = ""
  88. elif line.startswith("msgid_plural \""):
  89. current_state = "msgid_plural"
  90. line = line[13:]
  91. last_destination[current_state] = ""
  92. if line.startswith("\"") and line.endswith("\""):
  93. last_destination[current_state] += line + "\n"
  94. else: #White lines or comment lines trigger us to search for the translation in the source file.
  95. if last_destination["msgstr"] == "\"\"\n" and last_destination["msgid"] != "\"\"\n": #No translation for this yet!
  96. last_destination["msgstr"] = find_translation(source, last_destination["msgctxt"], last_destination["msgid"]) #Actually place the translation in.
  97. if last_destination["msgctxt"] != "\"\"\n" or last_destination["msgid"] != "\"\"\n" or last_destination["msgid_plural"] != "\"\"\n" or last_destination["msgstr"] != "\"\"\n":
  98. if last_destination["msgctxt"] != "\"\"\n":
  99. result_lines.append("msgctxt {msgctxt}".format(msgctxt = last_destination["msgctxt"][:-1])) #The [:-1] to strip the last newline.
  100. result_lines.append("msgid {msgid}".format(msgid = last_destination["msgid"][:-1]))
  101. if last_destination["msgid_plural"] != "\"\"\n":
  102. result_lines.append("msgid_plural {msgid_plural}".format(msgid_plural = last_destination["msgid_plural"][:-1]))
  103. else:
  104. result_lines.append("msgstr {msgstr}".format(msgstr = last_destination["msgstr"][:-1]))
  105. last_destination = {
  106. "msgctxt": "\"\"\n",
  107. "msgid": "\"\"\n",
  108. "msgstr": "\"\"\n",
  109. "msgid_plural": "\"\"\n"
  110. }
  111. result_lines.append(line) #This line itself.
  112. return "\n".join(result_lines)
  113. def find_translation(source: str, msgctxt: str, msgid: str) -> str:
  114. """Finds a translation in the source file.
  115. :param source: The contents of the source .po file.
  116. :param msgctxt: The ctxt of the translation to find.
  117. :param msgid: The id of the translation to find.
  118. """
  119. last_source = {
  120. "msgctxt": "\"\"\n",
  121. "msgid": "\"\"\n",
  122. "msgstr": "\"\"\n",
  123. "msgid_plural": "\"\"\n"
  124. }
  125. current_state = "none"
  126. for line in source.split("\n"):
  127. if line.startswith("msgctxt \""):
  128. current_state = "msgctxt"
  129. line = line[8:]
  130. last_source[current_state] = ""
  131. elif line.startswith("msgid \""):
  132. current_state = "msgid"
  133. line = line[6:]
  134. last_source[current_state] = ""
  135. elif line.startswith("msgstr \""):
  136. current_state = "msgstr"
  137. line = line[7:]
  138. last_source[current_state] = ""
  139. elif line.startswith("msgid_plural \""):
  140. current_state = "msgid_plural"
  141. line = line[13:]
  142. last_source[current_state] = ""
  143. if line.startswith("\"") and line.endswith("\""):
  144. last_source[current_state] += line + "\n"
  145. else: #White lines trigger us to process this translation. Is it the correct one?
  146. #Process the source and destination keys for comparison independent of newline technique.
  147. source_ctxt = "".join((line.strip()[1:-1] for line in last_source["msgctxt"].split("\n")))
  148. source_id = "".join((line.strip()[1:-1] for line in last_source["msgid"].split("\n")))
  149. dest_ctxt = "".join((line.strip()[1:-1] for line in msgctxt.split("\n")))
  150. dest_id = "".join((line.strip()[1:-1] for line in msgid.split("\n")))
  151. if source_ctxt == dest_ctxt and source_id == dest_id:
  152. if last_source["msgstr"] == "\"\"\n" and last_source["msgid_plural"] == "\"\"\n":
  153. print("!!! Empty translation for {" + dest_ctxt + "}", dest_id, "!!!")
  154. return last_source["msgstr"]
  155. last_source = {
  156. "msgctxt": "\"\"\n",
  157. "msgid": "\"\"\n",
  158. "msgstr": "\"\"\n",
  159. "msgid_plural": "\"\"\n"
  160. }
  161. #Still here? Then the entire msgctxt+msgid combination was not found at all.
  162. print("!!! Missing translation for {" + msgctxt.strip() + "}", msgid.strip(), "!!!")
  163. return "\"\"\n"
  164. if __name__ == "__main__":
  165. argparser = argparse.ArgumentParser(description = "Import translation files from Lionbridge.")
  166. argparser.add_argument("source")
  167. args = argparser.parse_args()
  168. lionbridge_import(args.source)