MCPcopy Index your code
hub / github.com/InstaPy/InstaPy / translate_text

Function translate_text

instapy/text_analytics.py:366–413  ·  view source on GitHub ↗

Translate the text to the specified language :param translation_direction: "en-ru" [from english to russian] "en" [to english, auto-detect source lang] :return: String with the translated text or None

(translation_direction, text_to_translate)

Source from the content-addressed store, hash-verified

364
365
366def translate_text(translation_direction, text_to_translate):
367 """
368 Translate the text to the specified language
369
370 :param translation_direction:
371 "en-ru" [from english to russian]
372 "en" [to english, auto-detect source lang]
373
374 :return:
375 String with the translated text or None
376 """
377
378 # if the text doesn't have an end mark, add a dot to get a better
379 # translation
380 if not text_to_translate.endswith((".", "?", "!", ";")):
381 text_to_translate += "."
382
383 POST = "/api/{}/tr.json/translate?key={}&text={}&lang={}".format(
384 YANDEX_API_VERSION,
385 YANDEX_CONFIG["API_key"],
386 text_to_translate,
387 translation_direction,
388 )
389 logger = Settings.logger
390
391 try:
392 req = requests.get(YANDEX_HOST + POST)
393 except SSLError as exc:
394 print("")
395 logger.exception(
396 "{}\t~there was a connection error :<"
397 "\n{}\n".format(YANDEX_FAILURE_MSG, str(exc).encode("utf-8"))
398 )
399 return None
400
401 data = json.loads(req.text)
402 # check if there are any errors in the request
403 request_state = lift_yandex_request(data)
404 if request_state is not True:
405 return None
406
407 # get the result
408 if "text" in data.keys() and data["text"]:
409 translated_text = data["text"][0]
410 return translated_text
411
412 else:
413 return None
414
415
416def lift_yandex_request(request):

Callers 1

text_analysisFunction · 0.85

Calls 1

lift_yandex_requestFunction · 0.85

Tested by

no test coverage detected