File: sample_text_translation_translate.py

package info (click to toggle)
python-azure 20250603%2Bgit-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 851,724 kB
  • sloc: python: 7,362,925; ansic: 804; javascript: 287; makefile: 195; sh: 145; xml: 109
file content (375 lines) | stat: -rw-r--r-- 15,452 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------

"""
FILE: sample_text_translation_translate.py

DESCRIPTION:
    This file contains sample snippets for the Text Translation service.

USAGE:
    python sample_text_translation_translate.py

    Set the text translation endpoint environment variables with your own value before running the samples:
        
        1) AZURE_TEXT_TRANSLATION_ENDPOINT - the endpoint to your Text Translation resource.
        Note: the endpoint must be formatted to use the custom domain name for your resource:
        https:\\<NAME-OF-YOUR-RESOURCE>.cognitiveservices.azure.com\
                    
    The create_text_translation_client_with_credential call requires additional variables:
        2) AZURE_TEXT_TRANSLATION_APIKEY - the API key to your Text Translation resource.
        3) AZURE_TEXT_TRANSLATION_REGION - the Azure Region of your Text Translation resource.
"""

from azure.core.exceptions import HttpResponseError
from azure.ai.translation.text.models import TextType, ProfanityAction, ProfanityMarker

# -------------------------------------------------------------------------
# Text translation client
# -------------------------------------------------------------------------
import sample_text_translation_client

text_translator = sample_text_translation_client.create_text_translation_client_with_credential()


# -------------------------------------------------------------------------
# Get text translation
# -------------------------------------------------------------------------
def get_text_translation():
    # [START get_text_translation]
    try:
        from_language = "en"
        to_language = ["cs"]
        input_text_elements = ["This is a test"]

        response = text_translator.translate(
            body=input_text_elements, to_language=to_language, from_language=from_language
        )
        translation = response[0] if response else None

        if translation:
            for translated_text in translation.translations:
                print(f"Text was translated to: '{translated_text.to}' and the result is: '{translated_text.text}'.")

    except HttpResponseError as exception:
        if exception.error is not None:
            print(f"Error Code: {exception.error.code}")
            print(f"Message: {exception.error.message}")
        raise
    # [END get_text_translation]


def get_text_translation_auto():
    # [START get_text_translation_auto]
    try:
        to_language = ["cs"]
        input_text_elements = ["This is a test"]

        response = text_translator.translate(body=input_text_elements, to_language=to_language)
        translation = response[0] if response else None

        if translation:
            detected_language = translation.detected_language
            if detected_language:
                print(
                    f"Detected languages of the input text: {detected_language.language} with score: {detected_language.score}."
                )
            for translated_text in translation.translations:
                print(f"Text was translated to: '{translated_text.to}' and the result is: '{translated_text.text}'.")

    except HttpResponseError as exception:
        if exception.error is not None:
            print(f"Error Code: {exception.error.code}")
            print(f"Message: {exception.error.message}")
        raise
    # [END get_text_translation_auto]


def get_text_translation_with_transliteration():
    # [START get_text_translation_with_transliteration]
    try:
        from_script = "Latn"
        from_language = "ar"
        to_script = "Latn"
        to_language = ["zh-Hans"]
        input_text_elements = ["hudha akhtabar."]

        response = text_translator.translate(
            body=input_text_elements,
            to_language=to_language,
            from_script=from_script,
            from_language=from_language,
            to_script=to_script,
        )
        translation = response[0] if response else None

        if translation:
            if translation.source_text:
                print(f"Source Text: {translation.source_text.text}")
            first_translation = translation.translations[0]
            if first_translation:
                print(f"Translation: '{first_translation.text}'.")
                transliteration = first_translation.transliteration
                if transliteration:
                    print(f"Transliterated text ({transliteration.script}): {transliteration.text}")

    except HttpResponseError as exception:
        if exception.error is not None:
            print(f"Error Code: {exception.error.code}")
            print(f"Message: {exception.error.message}")
        raise
    # [END get_text_translation_with_transliteration]


def get_text_translation_multiple_inputs():
    # [START get_text_translation_multiple_inputs]
    try:
        to_language = ["cs"]
        input_text_elements = [
            "This is a test.",
            "Esto es una prueba.",
            "Dies ist ein Test.",
        ]

        translations = text_translator.translate(body=input_text_elements, to_language=to_language)

        for translation in translations:
            print(
                f"Detected languages of the input text: {translation.detected_language.language if translation.detected_language else None} with score: {translation.detected_language.score if translation.detected_language else None}."
            )
            print(
                f"Text was translated to: '{translation.translations[0].to if translation.translations else None}' and the result is: '{translation.translations[0].text if translation.translations else None}'."
            )

    except HttpResponseError as exception:
        if exception.error is not None:
            print(f"Error Code: {exception.error.code}")
            print(f"Message: {exception.error.message}")
    # [END get_text_translation_multiple_inputs]


def get_text_translation_multiple_languages():
    # [START get_text_translation_multiple_languages]
    try:
        to_language = ["cs", "es", "de"]
        input_text_elements = ["This is a test"]

        response = text_translator.translate(body=input_text_elements, to_language=to_language)
        translation = response[0] if response else None

        if translation:
            detected_language = translation.detected_language
            if detected_language:
                print(
                    f"Detected languages of the input text: {detected_language.language} with score: {detected_language.score}."
                )
            for translated_text in translation.translations:
                print(f"Text was translated to: '{translated_text.to}' and the result is: '{translated_text.text}'.")

    except HttpResponseError as exception:
        if exception.error is not None:
            print(f"Error Code: {exception.error.code}")
            print(f"Message: {exception.error.message}")
    # [END get_text_translation_multiple_languages]


def get_text_translation_type():
    # [START get_text_translation_type]
    try:
        text_type = TextType.HTML
        to_language = ["cs"]
        input_text_elements = ["<html><body>This <b>is</b> a test.</body></html>"]

        response = text_translator.translate(body=input_text_elements, to_language=to_language, text_type=text_type)
        translation = response[0] if response else None

        if translation:
            detected_language = translation.detected_language
            if detected_language:
                print(
                    f"Detected languages of the input text: {detected_language.language} with score: {detected_language.score}."
                )
            for translated_text in translation.translations:
                print(f"Text was translated to: '{translated_text.to}' and the result is: '{translated_text.text}'.")

    except HttpResponseError as exception:
        if exception.error is not None:
            print(f"Error Code: {exception.error.code}")
            print(f"Message: {exception.error.message}")
    # [END get_text_translation_type]


def get_text_translation_exclude():
    # [START get_text_translation_exclude]
    try:
        text_type = TextType.HTML
        from_language = "en"
        to_language = ["cs"]
        input_text_elements = [
            '<div class="notranslate">This will not be translated.</div><div>This will be translated. </div>'
        ]

        response = text_translator.translate(
            body=input_text_elements,
            to_language=to_language,
            from_language=from_language,
            text_type=text_type,
        )
        translation = response[0] if response else None

        if translation:
            for translated_text in translation.translations:
                print(f"Text was translated to: '{translated_text.to}' and the result is: '{translated_text.text}'.")

    except HttpResponseError as exception:
        if exception.error is not None:
            print(f"Error Code: {exception.error.code}")
            print(f"Message: {exception.error.message}")
    # [END get_text_translation_exclude]


def get_text_translation_entity():
    # [START get_text_translation_entity]
    try:
        from_language = "en"
        to_language = ["cs"]
        input_text_elements = [
            'The word <mstrans:dictionary translation="wordomatic">wordomatic</mstrans:dictionary> is a dictionary entry.'
        ]

        response = text_translator.translate(
            body=input_text_elements, to_language=to_language, from_language=from_language
        )
        translation = response[0] if response else None

        if translation:
            for translated_text in translation.translations:
                print(f"Text was translated to: '{translated_text.to}' and the result is: '{translated_text.text}'.")

    except HttpResponseError as exception:
        if exception.error is not None:
            print(f"Error Code: {exception.error.code}")
            print(f"Message: {exception.error.message}")
    # [END get_text_translation_entity]


def get_text_translation_profanity():
    # [START get_text_translation_profanity]
    try:
        profanity_action = ProfanityAction.MARKED
        profanity_maker = ProfanityMarker.ASTERISK
        to_language = ["cs"]
        input_text_elements = ["This is ***."]

        response = text_translator.translate(
            body=input_text_elements,
            to_language=to_language,
            profanity_action=profanity_action,
            profanity_marker=profanity_maker,
        )
        translation = response[0] if response else None

        if translation:
            detected_language = translation.detected_language
            if detected_language:
                print(
                    f"Detected languages of the input text: {detected_language.language} with score: {detected_language.score}."
                )
            for translated_text in translation.translations:
                print(f"Text was translated to: '{translated_text.to}' and the result is: '{translated_text.text}'.")

    except HttpResponseError as exception:
        if exception.error is not None:
            print(f"Error Code: {exception.error.code}")
            print(f"Message: {exception.error.message}")
    # [END get_text_translation_profanity]


def get_text_translation_alignment():
    # [START get_text_translation_alignment]
    try:
        include_alignment = True
        to_language = ["cs"]
        input_text_elements = ["The answer lies in machine translation."]

        response = text_translator.translate(
            body=input_text_elements, to_language=to_language, include_alignment=include_alignment
        )
        translation = response[0] if response else None

        if translation:
            detected_language = translation.detected_language
            if detected_language:
                print(
                    f"Detected languages of the input text: {detected_language.language} with score: {detected_language.score}."
                )
            for translated_text in translation.translations:
                print(f"Text was translated to: '{translated_text.to}' and the result is: '{translated_text.text}'.")
                if translated_text.alignment:
                    print(f"Alignments: {translated_text.alignment.proj}")

    except HttpResponseError as exception:
        if exception.error is not None:
            print(f"Error Code: {exception.error.code}")
            print(f"Message: {exception.error.message}")
    # [END get_text_translation_alignment]


def get_text_translation_sentence_length():
    # [START get_text_translation_sentence_length]
    try:
        include_sentence_length = True
        to_language = ["cs"]
        input_text_elements = ["The answer lies in machine translation. This is a test."]

        response = text_translator.translate(
            body=input_text_elements, to_language=to_language, include_sentence_length=include_sentence_length
        )
        translation = response[0] if response else None

        if translation:
            detected_language = translation.detected_language
            if detected_language:
                print(
                    f"Detected languages of the input text: {detected_language.language} with score: {detected_language.score}."
                )
            for translated_text in translation.translations:
                print(f"Text was translated to: '{translated_text.to}' and the result is: '{translated_text.text}'.")
                if translated_text.sent_len:
                    print(f"Source Sentence length: {translated_text.sent_len.src_sent_len}")
                    print(f"Translated Sentence length: {translated_text.sent_len.trans_sent_len}")

    except HttpResponseError as exception:
        if exception.error is not None:
            print(f"Error Code: {exception.error.code}")
            print(f"Message: {exception.error.message}")
    # [END get_text_translation_sentence_length]


def get_text_translation_custom():
    # [START get_text_translation_custom]
    try:
        category = "<<Category ID>>"
        to_language = ["cs"]
        input_text_elements = ["This is a test"]

        response = text_translator.translate(body=input_text_elements, to_language=to_language, category=category)
        translation = response[0] if response else None

        if translation:
            detected_language = translation.detected_language
            if detected_language:
                print(
                    f"Detected languages of the input text: {detected_language.language} with score: {detected_language.score}."
                )
            for translated_text in translation.translations:
                print(f"Text was translated to: '{translated_text.to}' and the result is: '{translated_text.text}'.")

    except HttpResponseError as exception:
        if exception.error is not None:
            print(f"Error Code: {exception.error.code}")
            print(f"Message: {exception.error.message}")
    # [END get_text_translation_custom]