You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

105 lines
3.2 KiB

import requests
from requests_toolbelt.multipart.encoder import MultipartEncoder
import json
import argparse
import os
import constants
def main():
# Impl
print("[INFO][PREFLIGHT] Initializing translator...", end="")
availableLanguages = list()
params = {
"auth_key": constants.API_ACCESS_KEY,
"type": "target"
}
availableLanguagesRequest = requests.get(constants.LANGUAGES_API_ENDPOINT_URL, data=params)
responseInJSON = json.loads(str(availableLanguagesRequest.text))
for arrayMember in responseInJSON:
availableLanguages.append(arrayMember["language"])
print("done")
argumentParser = argparse.ArgumentParser(description="Translate text using Deepl service")
argumentParser.add_argument(
"--file",
help="File, that contains text to translate",
type=str
)
argumentParser.add_argument(
"--output",
help="File, that translation will be written to(specify /dev/stdout for output into console)",
type=str
)
argumentParser.add_argument(
"--target_lang",
help="Language to translate text to",
type=str
)
arguments = argumentParser.parse_args()
languageIsAvailable = bool(False)
for language in availableLanguages:
if not arguments.target_lang == language:
continue
elif arguments.target_lang == language:
languageIsAvailable = True
break
if not languageIsAvailable:
print("[ERROR][PREFLIGHT] Language {0} is not supported!".format(arguments.target_lang))
print("[INFO][TERMINATION] Supported languages are:", end=" ")
for language in availableLanguages:
print("{0}".format(language), end=" ")
print("\n")
exit(1)
if not os.path.exists(arguments.file):
print("[ERROR][PREFLIGHT] File {0} not found!".format(arguments.file))
exit(1)
elif os.path.exists(arguments.file):
readOnlyFileDescriptor = open(arguments.file, "r")
fileContent = readOnlyFileDescriptor.read()
params = {
"auth_key": constants.API_ACCESS_KEY
}
print("[INFO][PREFLIGHT] Performing subscription check...", end="")
usageMonitoringRequest = requests.get(constants.USAGE_API_ENDPOINT_URL, data=params)
responseInJSON = json.loads(str(usageMonitoringRequest.text))
availableCharacters = int(responseInJSON["character_limit"])
if len(fileContent) > availableCharacters:
print("[ERROR][PREFLIGHT] Amount of characters in the text file exceeds available!")
readOnlyFileDescriptor.close()
exit(1)
elif len(fileContent) <= availableCharacters:
print("done")
params = {
"auth_key": constants.API_ACCESS_KEY,
"text": fileContent,
"target_lang": arguments.target_lang
}
translationRequest = requests.get(constants.TRANSLATE_API_ENDPOINT_URL, data=params)
responseInJSON = json.loads(str(translationRequest.text))
translation = responseInJSON["translations"][0]["text"]
readWriteFileDescriptor = open(arguments.output, "w")
readWriteFileDescriptor.write(translation)
readOnlyFileDescriptor.close()
readWriteFileDescriptor.close()
main()