memoQTM.py 2.3 KB

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