File: sample_single_document_translation.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 (55 lines) | stat: -rw-r--r-- 2,013 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
# ------------------------------------
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
# ------------------------------------

"""
FILE: synchronous_document_translation.py

DESCRIPTION:
    This sample demonstrates how to invoke synchronous document translation operations.

USAGE:
    python synchronous_document_translation.py

    Set the environment variables with your own values before running the sample:
    1) AZURE_DOCUMENT_TRANSLATION_ENDPOINT - the endpoint to your Document Translation resource.
    2) AZURE_DOCUMENT_TRANSLATION_KEY - your Document Translation API key.
"""

import os
from azure.core.credentials import AzureKeyCredential
from azure.ai.translation.document import SingleDocumentTranslationClient
from azure.ai.translation.document.models import DocumentTranslateContent


TEST_INPUT_FILE_NAME = os.path.abspath(
    os.path.join(os.path.abspath(__file__), "..", "../tests/TestData/test-input.txt")
)


def sample_single_document_translation():
    # [START synchronous_document_translation]
    endpoint = os.environ["AZURE_DOCUMENT_TRANSLATION_ENDPOINT"]
    key = os.environ["AZURE_DOCUMENT_TRANSLATION_KEY"]

    client = SingleDocumentTranslationClient(endpoint, AzureKeyCredential(key))
    target_languages = "hi"
    file_name = os.path.basename(TEST_INPUT_FILE_NAME)
    print(f"File for translation: {file_name}")
    file_type = "text/html"
    with open(TEST_INPUT_FILE_NAME, "r") as file:
        file_contents = file.read()

    document_content = (file_name, file_contents, file_type)
    document_translate_content = DocumentTranslateContent(document=document_content)

    response_stream = client.translate(body=document_translate_content, target_language=target_languages)
    translated_response = response_stream.decode("utf-8-sig")  # type: ignore[attr-defined]
    print(f"Translated response: {translated_response}")

    # [END synchronous_document_translation]


if __name__ == "__main__":
    sample_single_document_translation()