memoQTM.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. from suds.client import Client
  2. from base64 import b64decode, b64encode
  3. import os
  4. import json
  5. class TM(object):
  6. """Wrapper for TM."""
  7. def __init__(self, info=None):
  8. self.info = info
  9. def __repr__(self):
  10. if self.info != None:
  11. return "{} - {}\n{} - {}".format(
  12. self.info.Name, self.info.Guid,
  13. self.info.SourceLanguageCode, self.info.TargetLanguageCode)
  14. else:
  15. return "No TM!"
  16. def get_guid(self):
  17. """Returns guid of active TM."""
  18. return self.info.Guid
  19. class MemoQTM(object):
  20. """Client for memoQ Translation memory API."""
  21. def __init__(self):
  22. with open("config.json") as json_file:
  23. self.config = json.load(json_file)
  24. if self.config["api_base_url"] != "":
  25. api_url = self.config["api_base_url"] + "/memoqservices/tm?wsdl"
  26. self.client = Client(api_url)
  27. self.tm = TM()
  28. def __repr__(self):
  29. return "{}".format(self.tm)
  30. def get_tm_details(self, guid):
  31. """Returns TM Info for TM of given guid or none if no TM or connection problems."""
  32. try:
  33. info = self.client.service.GetTMInfo(guid)
  34. return info
  35. except:
  36. return None
  37. def set_active_tm(self, guid):
  38. """Sets TM of given guid as active."""
  39. tm_info = self.get_tm_details(guid)
  40. if tm_info != None:
  41. self.tm = TM(tm_info)
  42. def get_all_tms(self):
  43. """Returns list of all TMs on server."""
  44. return [TM(x) for x in self.client.service.ListTMs()[0]]
  45. def download_tmx(self, path, guid=None):
  46. """Downloads TMX export of active or given TM to given path.
  47. Returns path to TMX file or none on any failure."""
  48. if guid != None:
  49. self.set_active_tm(guid)
  50. if self.tm.info == None:
  51. return None
  52. session_id = None
  53. try:
  54. session_id = self.client.service.BeginChunkedTMXExport(
  55. self.tm.get_guid())
  56. except Exception as e:
  57. print(e)
  58. return None
  59. output_filename = os.path.join(path, (self.tm.info.Name + ".tmx"))
  60. output = open(output_filename, 'wb')
  61. while True:
  62. try:
  63. chunk = self.client.service.GetNextTMXChunk(session_id)
  64. if chunk is not None:
  65. output.write(b64decode(chunk))
  66. else:
  67. break
  68. except:
  69. self.client.service.EndChunkedTMXExport(session_id)
  70. output.close()
  71. return None
  72. output.close()
  73. self.client.service.EndChunkedTMXExport(session_id)
  74. return output_filename