Translates given JSON input using DeepL Translator. Most of the arguments of the translate_text function are supported, source_lang, target_lang, glossary_id, formality, etc. :param json_input: JSON input to be translated. :param target_lang: language code to translate templat
(
json_input: str,
target_lang: str,
translator: deepl.Translator,
**kwargs,
)
| 61 | |
| 62 | |
| 63 | def translate_json( |
| 64 | json_input: str, |
| 65 | target_lang: str, |
| 66 | translator: deepl.Translator, |
| 67 | **kwargs, |
| 68 | ) -> str: |
| 69 | """ |
| 70 | Translates given JSON input using DeepL Translator. |
| 71 | |
| 72 | Most of the arguments of the translate_text function are supported, |
| 73 | source_lang, target_lang, glossary_id, formality, etc. |
| 74 | |
| 75 | :param json_input: JSON input to be translated. |
| 76 | :param target_lang: language code to translate template into, for example |
| 77 | "DE", "EN-US", "FR". |
| 78 | :param translator: deepl.Translator to use for translation. |
| 79 | :return: Translated JSON. |
| 80 | """ |
| 81 | |
| 82 | logger = logging.getLogger("deepl") |
| 83 | obj = json.loads(json_input) |
| 84 | # Wrap the JSON object in an array, in case the input is a string |
| 85 | obj = [obj] |
| 86 | |
| 87 | # Find all text in the JSON that is to be translated |
| 88 | translation_candidates: List[ |
| 89 | Tuple[str, Callable[[deepl.TextResult], None]] |
| 90 | ] = [] |
| 91 | parse_json_for_translation(obj, translation_candidates) |
| 92 | logger.info( |
| 93 | f"Found {len(translation_candidates)} strings to be translated" |
| 94 | ) |
| 95 | |
| 96 | # Translate all texts |
| 97 | batch_translate(translation_candidates, target_lang, translator, **kwargs) |
| 98 | logger.info("Translation complete") |
| 99 | |
| 100 | # Unwrap the dummy array and convert to JSON |
| 101 | return json.dumps(obj[0]) |
no test coverage detected