MCPcopy Create free account
hub / github.com/DeepL/deepl-python / translate_mustache

Function translate_mustache

examples/mustache/mustache.py:78–130  ·  view source on GitHub ↗

Translates given Mustache template text using DeepL Translator, by converting the template to XML. Most of the arguments of the translate_text function are supported, source_lang, target_lang, glossary_id, formality, etc. The tag_handling argument is *not* supported, because th

(
    template: str,
    target_lang: str,
    translator: deepl.Translator,
    delimiters: Optional[List[Tuple[str, str]]] = None,
    placeholder_tag: str = "m",
    **kwargs,
)

Source from the content-addressed store, hash-verified

76
77
78def translate_mustache(
79 template: str,
80 target_lang: str,
81 translator: deepl.Translator,
82 delimiters: Optional[List[Tuple[str, str]]] = None,
83 placeholder_tag: str = "m",
84 **kwargs,
85) -> str:
86 """
87 Translates given Mustache template text using DeepL Translator, by
88 converting the template to XML.
89
90 Most of the arguments of the translate_text function are supported,
91 source_lang, target_lang, glossary_id, formality, etc.
92 The tag_handling argument is *not* supported, because the Mustache tags
93 are replaced by XML before translation.
94
95 :param template: Mustache template to be translated.
96 :param target_lang: language code to translate template into, for example
97 "DE", "EN-US", "FR".
98 :param translator: deepl.Translator to use for translation.
99 :param delimiters: Optional. Tuples of left- and right-delimiters
100 identifying Mustache tags. Delimiter tuples must be specified in
101 order-of-precedence, for example {{{ must be before {{.
102 :param placeholder_tag: Optional. Dummy XML-tag to replace Mustache tags,
103 defaults to "m".
104 :return: Translated Mustache template.
105 """
106 if not delimiters:
107 delimiters = [("{{{", "}}}"), ("{{", "}}")]
108
109 logger = logging.getLogger("deepl")
110 # Replace Mustache tags with placeholder XML tags
111 placeholder_xml, replaced_tags = convert_mustache_to_xml(
112 template, placeholder_tag, delimiters
113 )
114 logger.info("XML with placeholder tags: %s", placeholder_xml)
115 logger.debug("Placeholder tokens: %s", replaced_tags)
116
117 # Translate XML with placeholder tags
118 result = translator.translate_text(
119 placeholder_xml, target_lang=target_lang, tag_handling="xml", **kwargs
120 )
121 assert isinstance(result, TextResult)
122 logger.info("Translated XML: %s", result.text)
123
124 # Reinsert the extracted Mustache tags in the translated XML
125 xml_parser = TagReplacerHTMLParser(replaced_tags)
126 xml_parser.feed(result.text)
127 xml_parser.close()
128 translated_template = xml_parser.parsed()
129
130 return translated_template

Callers 1

mainFunction · 0.90

Calls 5

convert_mustache_to_xmlFunction · 0.85
translate_textMethod · 0.80
parsedMethod · 0.80
closeMethod · 0.45

Tested by

no test coverage detected