Translate Function
This Python snippet can be used to translate an array of texts (texts
) from a source language code (src
) to a target language code (tgt
) using a specific engine
ID and an apiKey
.
def relay(texts, src, tgt, engine, apiKey):
url = 'https://prod.pangeamt.com:8443/NexRelay/v1/translate'
data = {
"src": src,
"tgt": tgt,
"apikey": apiKey,
"engine": engine,
"text": texts
}
headers = {'Content-type': 'application/json'}
print(data)
r = requests.post(url, data=json.dumps(data), headers=headers)
ans = r.text
try:
translationresponse = json.loads(ans, strict=False)
except:
print(translationresponse)
return translationresponse
Batch Translation of Documents
The following example script can be used to request the translation of all supported document types in a folder or directory structure.
import requests
import os
import json
from glob import glob
import time
from shutil import copyfile
username = 'your-username'
apikey = 'your-apikey'
engine = 0
srcLang = "es"
tgtLang = "en"
srcdir = "C:\\Users\\Usuario\\PycharmProjects\\sendfile\\srcfiles"
tgtdir = "C:\\Users\\Usuario\\PycharmProjects\\sendfile\\tgtfiles"
faildir = "C:\\Users\\Usuario\\PycharmProjects\\sendfile\\failedfiles"
sent = {}
status = {}
failed = []
finished = {}
url_base = 'https://prod.pangeamt.com:8443/PGFile/v1'
def dosend(path, engine, src, tgt, apikey, username):
url = url_base + '/sendfile'
files = {'file': open(path, 'rb')}
filename = os.path.basename(path)
values = {
'title': filename,
'engine': engine,
'src': src,
'tgt': tgt,
'apikey': apikey,
'processname': 'translate',
'username': username,
'notiflink': 'testlink',
'processoption': '1'
}
r = requests.post(url, files=files, data=values)
rc = None
ret = json.loads(r.text)
if 'error' in ret:
print("error found processing", path, ret['error_message'])
else:
rc = ret['fileId']
return rc
def doget(username, apikey):
url = url_base + '/checkfile?apikey=' + apikey + '&username=' + username
r = requests.get(url)
return json.loads(r.text)
def dodownload(fileid, apikey, newpath):
url = url_base + '/download?apikey=' + str(apikey) + '&fileid=' + str(fileid)
r = requests.get(url)
totalbits = 0
if r.status_code == 200:
with open(newpath, 'wb') as f:
for chunk in r.iter_content(chunk_size=1024):
if chunk:
totalbits += 1024
f.write(chunk)
return (r.status_code, totalbits)
# Scan source directory
tosend = []
srcpaths = glob(srcdir + '\\**\\*.*', recursive=True)
nfound = 0
nvalid = 0
for path in srcpaths:
nfound += 1
file = os.path.basename(path)
fName, ext = os.path.splitext(file)
if ext in ['.txt', '.docx', '.pdf', '.xlsx', '.pptx', '.PDF', '.DOCX']:
nvalid += 1
tosend.append(path)
print("SRC found", nfound, ", files to send", nvalid)
initTime = time.time()
# Create target directory
try:
os.makedirs(tgtdir)
except OSError:
pass
# Send files
for path in tosend:
fileId = dosend(path, engine, srcLang, tgtLang, apikey, username)
if fileId is not None:
sent[fileId] = path
else:
failed.append(path)
print("All files sent")
# Check and download
dochek = True
while dochek:
time.sleep(5)
rcstatus = doget(username, apikey)
for st in rcstatus:
status[st['fileId']] = st
if st['status'] == -10:
try:
if sent[st['fileId']] not in failed:
failed.append(sent[st['fileId']])
srcPath = sent[st['fileId']]
srcDir = os.path.dirname(srcPath)
srcName = os.path.basename(srcPath)
relPath = srcDir[len(srcdir):]
tgtDir = faildir + relPath
print(relPath + '\\' + srcName, "FAILED")
try:
os.makedirs(tgtDir)
except OSError:
pass
copyfile(srcPath, tgtDir + '\\' + srcName)
except:
pass
if st['status'] == 100:
try:
srcPath = sent[st['fileId']]
srcDir = os.path.dirname(srcPath)
relPath = srcDir[len(srcdir):]
tgtDir = tgtdir + relPath
print(relPath + '\\' + st['translatedName'], "can be downloaded")
try:
os.makedirs(tgtDir)
except OSError:
pass
translatedPath = tgtDir + '\\' + st['translatedName']
rc, bits = dodownload(st['fileId'], apikey, translatedPath)
print("Download of", translatedPath, "rc:", rc, "bits:", bits)
if rc == 200 and bits > 0:
finished[st['fileId']] = translatedPath
except Exception as ee:
print(ee)
print("Sent", len(sent))
print("Finished", len(finished))
print("Failed", len(failed))
if len(finished) + len(failed) == len(sent):
dochek = False
print("Job finished!")
endTime = time.time()
print("Started at", initTime, "ended at", endTime, "delay:", endTime - initTime)
else:
print("In Process", len(sent) - len(finished) - len(failed))
print("=" * 60)
Was this article helpful?
That’s Great!
Thank you for your feedback
Sorry! We couldn't be helpful
Thank you for your feedback
Feedback sent
We appreciate your effort and will try to fix the article