-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexport_smartcat.py
175 lines (161 loc) · 6.5 KB
/
export_smartcat.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
#!/usr/bin/python
# Export and download translation file from smartCAT.
# Please make sure before use script you're created
# configuation file for script. See example below.
#
# Example (smartcat.ini):
# [config_name]
# accountId =
# authKey =
# documentId =
# languageId =
import sys
import time
import configparser
from smartcat import *
class smartCatConfig:
@staticmethod
def __ReadConfigKey(config, key_name):
if not key_name in config:
raise Exception(f"Missing key '{key_name}' in smartCAT config")
key_value = config[key_name].strip()
if len(key_value) == 0:
raise Exception(f"Empty key '{key_name}' value in smartCAT config")
return key_value
@staticmethod
def __ReadConfigKeyPair(config, key_name):
key_value = smartCatConfig.__ReadConfigKey(config, key_name)
return [x.strip() for x in key_value.split(",", 1)]
def __init__(self, config):
self.accountId = smartCatConfig.__ReadConfigKey(config, "accountId")
self.authKey = smartCatConfig.__ReadConfigKey(config, "authKey")
self.documentIds = []
documentIndex = 1
while f"documentId_{documentIndex}" in config:
self.documentIds.append(
smartCatConfig.__ReadConfigKeyPair(
config, f"documentId_{documentIndex}"
)
)
documentIndex = documentIndex + 1
self.languageId = smartCatConfig.__ReadConfigKey(config, "languageId")
def printDocumentIds(self):
print("Available export files ids:")
documentIndex = 1
for documentPair in self.documentIds:
print(f"{documentIndex} - {documentPair[1]}")
documentIndex = documentIndex + 1
def readDocumentIds(self, mode):
if len(self.documentIds) > 1:
self.printDocumentIds()
if mode != "pullfs":
ids = set(
map(
int,
filter(None, input("Enter export ids (optional): ").split(" ")),
)
)
else:
ids = ""
if len(ids) == 0:
return set(range(1, len(self.documentIds) + 1))
return [id for id in ids if id > 0 and id <= len(self.documentIds)]
return set(range(1, len(self.documentIds) + 1))
def export_target(document_resource, document_id, output_file_name,type="target"):
print(f"Export document: {output_file_name}")
extname = {'target':'.xlsx','xliff':'.xliff','multilang_Csv':'', 'DocumentWithMetadata':'.xliff'}
with document_resource.request_export(
document_ids=document_id, target_type=type
) as export_result:
if export_result.status_code != 200:
print("Error: Failed request status code - ", export_result.status_code)
return 1
print("Export started")
export_json = json.loads(export_result.text)
export_task_id = export_json["id"]
wait_download_ready = False
try:
while True:
with document_resource.download_export_result(
export_task_id
) as download_result:
if download_result.status_code == 200:
if wait_download_ready:
print("")
wait_download_ready = False
print("Download started")
with open(output_file_name + extname[type], "wb") as out_file:
for chunk in download_result.iter_content(chunk_size=8192):
out_file.write(chunk)
print("Download completed")
break
elif download_result.status_code == 204:
if wait_download_ready:
print(".", end="")
else:
print("Wait download ready", end="")
wait_download_ready = True
time.sleep(1)
else:
if wait_download_ready:
print("")
print(
"Error: export status code - ", download_result.status_code
)
return 1
except:
if wait_download_ready:
print("")
raise
print("Export completed")
return 0
def main(args):
result = 1
config_name = ""
if len(args) > 1:
config_name = args[1]
try:
config = configparser.ConfigParser()
if not config.read("smartcat.ini"):
print("Error: Missing config file - smartcat.ini")
return 1
if len(config.sections()) == 0:
print("Error: No sections in smartCAT config")
return 1
print(
"Available smartCAT config - ", ", ".join(str(e) for e in config.sections())
)
if len(config_name) == 0:
config_name = input("Enter smartCAT config name: ").strip()
while not config.has_section(config_name):
if len(config_name) > 0:
print("Unknown smartCAT config name - ", config_name)
config_name = input("Enter smartCAT config name: ").strip()
elif not config.has_section(config_name):
print("Unknown smartCAT config name - ", config_name)
return 1
print("Use smartCAT config name - ", config_name)
smartCAT_config = smartCatConfig(config[config_name])
exportDocumentIds = smartCAT_config.readDocumentIds(args[0])
api = SmartCAT(
smartCAT_config.accountId, smartCAT_config.authKey, SmartCAT.SERVER_EUROPE
)
for id in exportDocumentIds:
documentInfo = smartCAT_config.documentIds[id - 1]
document_id = documentInfo[0] + "_" + smartCAT_config.languageId
if len(args) > 2:
result = export_target(api.document, document_id, documentInfo[1],args[2])
else:
result = export_target(api.document, document_id, documentInfo[1])
except Exception as err:
print("Error: Failed export: {0}".format(err))
except KeyboardInterrupt as err:
print("Interrupted")
if result == 0:
print("Done")
if args[0] == "pullfs":
return smartCAT_config.documentIds
else:
return result
if __name__ == "__main__":
sys.exit(main(sys.argv))