SkilVaultSign inStart free

Catalogue / azure-doc-translation-py

azure-doc-translation-py

Older skill: source not recordedSignedBuilds Python workflows for Azure AI Document Translation with the `azure-ai-translation-document` package: batch jobs across blob containers, single-file translation, glossaries, multiple target languages, status monitoring, cancellation, and async concurrency — with format-preserving output and pa…
---
name: azure-doc-translation-py
description: >-
  Builds Python workflows for Azure AI Document Translation with the
  `azure-ai-translation-document` package: batch jobs across blob containers,
  single-file translation, glossaries, multiple target languages, status
  monitoring, cancellation, and async concurrency — with format-preserving
  output and partial-failure reporting. Use when the user says "translate
  these documents to Spanish", "batch translate a folder of PDFs and DOCX",
  "use a glossary with document translation", or "check my translation job
  status". Not for plain-text string translation, for uploading documents the
  user has not approved sending to Azure, or for promising verified layout
  fidelity without checking the output.
---

Azure Document Translation (Python)

Batch translate documents between Azure Blob containers while keeping an auditable job identity, surfacing per-document failures, and protecting keys and SAS URLs. Package: azure-ai-translation-document. Check the installed version's signatures first — batch and single-file surfaces differ between releases. Ask before installing or upgrading anything.

Scope before submitting

  • Confirm which documents or source container may go to Azure, the destination container per language, glossary use, and that charges may apply.
  • A new container, extra language, credential change, cancellation, or local output write outside that scope needs fresh approval.
  • Even read-only discovery calls (formats, languages, statuses) hit the service — keep them inside the approved scope too.
  • Never print an API key or a SAS-bearing URL; deliver error details through a reviewed private channel.

Setup and authentication

pip install azure-ai-translation-document
AZURE_DOCUMENT_TRANSLATION_ENDPOINT=https://<resource>.cognitiveservices.azure.com
AZURE_DOCUMENT_TRANSLATION_KEY=<key — only if using key auth>
AZURE_SOURCE_CONTAINER_URL=https://<storage>.blob.core.windows.net/<container>?<sas>
AZURE_TARGET_CONTAINER_URL=https://<storage>.blob.core.windows.net/<container>?<sas>
import os
from azure.ai.translation.document import DocumentTranslationClient

# Preferred: Entra ID — no key needed
from azure.identity import DefaultAzureCredential
client = DocumentTranslationClient(
    endpoint=os.environ["AZURE_DOCUMENT_TRANSLATION_ENDPOINT"],
    credential=DefaultAzureCredential(),
)

# Alternative: API key
from azure.core.credentials import AzureKeyCredential
client = DocumentTranslationClient(endpoint, AzureKeyCredential(os.environ["AZURE_DOCUMENT_TRANSLATION_KEY"]))

Correct imports, all from the base module unless noted:

| Import | From | | --- | --- | | DocumentTranslationClient (sync) | azure.ai.translation.document | | DocumentTranslationClient (async) | azure.ai.translation.document.aio | | SingleDocumentTranslationClient | azure.ai.translation.document | | DocumentTranslationInput, TranslationTarget, TranslationGlossary, FilePurpose | azure.ai.translation.document | | AzureKeyCredential | azure.core.credentials | | DefaultAzureCredential | azure.identity (.aio for async) |

Wrong: from azure.ai.translation import DocumentTranslationInput; a nonexistent TranslationDocument; mixing the sync client with async with. Always close clients with with client: / async with client: or close().

Storage rules

  • Batch source and target are Azure Blob Storage containers; give each target language its own destination container and never overwrite an existing translation set.
  • SAS permissions baseline: source read + list, target write + list.
az storage container generate-sas --account-name myaccount --name source --permissions rl --expiry 2026-03-31
az storage container generate-sas --account-name myaccount --name target --permissions wl --expiry 2026-03-31

A ? in the URL does not prove the SAS is valid, unexpired, or sufficient — have the owner verify access without exposing the token. Managed-identity storage access is configured differently; a missing SAS is not automatically an error.

Batch translation

from azure.ai.translation.document import DocumentTranslationInput, TranslationTarget

poller = client.begin_translation(
    inputs=[
        DocumentTranslationInput(
            source_url=os.environ["AZURE_SOURCE_CONTAINER_URL"],
            targets=[
                TranslationTarget(
                    target_url=os.environ["AZURE_TARGET_CONTAINER_URL"],
                    language="es",
                )
            ],
        )
    ],
)
result = poller.result()   # the parameter is inputs=, never documents=
print(poller.status(), poller.details.documents_succeeded_count,
      poller.details.documents_failed_count)
  • Multiple target languages: add more TranslationTarget entries (es, fr, de…) to the same input — each with its own container URL.
  • Glossary: attach TranslationGlossary(glossary_url=..., file_format="csv") to the relevant target; check the supported glossary formats and language pairing for the pair.
  • Save poller.id to the job record immediately — a timeout can leave the job running, and you recover by ID instead of resubmitting a duplicate.
  • A terminal job status does not mean every document succeeded; inspect documents individually.

Reusable batch adapter

Offline-testable core: the caller supplies the SDK client and model classes, so nothing runs until approved=True. Redacted status records keep SAS queries and raw error text out of logs.

from urllib.parse import urlsplit, urlunsplit

def safe_location(value):
    parts = urlsplit(str(value))
    return urlunsplit((parts.scheme, parts.netloc, parts.path, '', ''))

def build_inputs(specs, Input, Target, Glossary):
    result = []
    for spec in specs:
        if not spec.get('source_url') or not spec.get('targets'):
            raise ValueError('Each source needs at least one target')
        targets, languages, destinations = [], set(), set()
        for item in spec['targets']:
            language, destination = item['language'], item['target_url']
            if not language or not destination:
                raise ValueError('Target language and destination are required')
            if language in languages or safe_location(destination) in destinations:
                raise ValueError('Use distinct languages and destinations per source')
            languages.add(language); destinations.add(safe_location(destination))
            options = dict(target_url=destination, language=language)
            if item.get('glossaries'):
                options['glossaries'] = [Glossary(glossary_url=g['url'], file_format=g['format'])
                                         for g in item['glossaries']]
            targets.append(Target(**options))
        result.append(Input(source_url=spec['source_url'], targets=targets))
    if not result:
        raise ValueError('No sources supplied')
    return result

def status_record(value):
    error = getattr(value, 'error', None)
    return {'id': getattr(value, 'id', None),
            'status': str(getattr(value, 'status', 'Unknown')),
            'source': safe_location(getattr(value, 'source_document_url', '')),
            'language': getattr(value, 'translated_to', None),
            'error_code': getattr(error, 'code', None)}

def submit_batch(client, inputs, *, approved=False):
    if not approved:
        raise PermissionError('Document submission is not authorized')
    poller = client.begin_translation(inputs=inputs)
    return poller, poller.id          # retain the ID before waiting

def finish_batch(client, poller):
    documents = list(poller.result())
    return {'operation_id': poller.id, 'status': str(poller.status()),
            'succeeded': poller.details.documents_succeeded_count,
            'failed': poller.details.documents_failed_count,
            'documents': [status_record(d) for d in documents]}

def cancel_batch(client, operation_id, *, approved=False):
    if not approved:
        raise PermissionError('Cancellation is not authorized')
    return client.cancel_translation(operation_id)

Monitoring and cancellation

for op in client.list_translation_statuses():
    print(op.id, op.status, op.created_on, op.documents_total_count,
          op.documents_succeeded_count, op.documents_failed_count)

for doc in client.list_document_statuses(operation_id):
    print(doc.source_document_url, doc.status, doc.translated_to,
          doc.error.message if doc.error else "ok")
  • Compare statuses against the installed SDK's values — guessed strings like "completed" are unreliable.
  • Cancellation targets one exact operation ID; confirm afterwards via its status and document outcomes. Already-translated outputs and charges may remain — never delete outputs as part of cancelling.

Single-file translation

Use the separate SingleDocumentTranslationClient — the batch client has no translate() method. Content type must match the actual bytes:

| File | Content type | | --- | --- | | DOCX | application/vnd.openxmlformats-officedocument.wordprocessingml.document | | XLSX | application/vnd.openxmlformats-officedocument.spreadsheetml.sheet | | PPTX | application/vnd.openxmlformats-officedocument.presentationml.presentation | | PDF | application/pdf | | HTML | text/html | | TXT | text/plain |

def translate_file(client, source, destination, language, content_type,
                   *, glossary_url=None, approved=False):
    if not approved:
        raise PermissionError('Upload and output creation are not authorized')
    from pathlib import Path
    source, destination = Path(source), Path(destination)
    if not source.is_file() or destination.exists():
        raise ValueError('Source must exist and destination must be new')
    options = dict(body=source.read_bytes(), target_language=language,
                   content_type=content_type)
    if glossary_url is not None:
        options['glossary_url'] = glossary_url
    translated = client.translate(**options)
    if not isinstance(translated, (bytes, bytearray)):
        raise TypeError('Inspect this SDK version: expected translated bytes')
    with destination.open('xb') as out:
        out.write(translated)
    return destination

Afterwards, open the output in a real reader and check content and layout. If the write fails midway, report the partial file for an approved cleanup.

Async

import asyncio
from azure.ai.translation.document.aio import DocumentTranslationClient
from azure.identity.aio import DefaultAzureCredential

async def run_batches(endpoint, credential, batches, concurrency, *, approved=False):
    if not approved:
        raise PermissionError('Batch submissions are not authorized')
    if concurrency < 1:
        raise ValueError('Concurrency must be positive')
    limit = asyncio.Semaphore(concurrency)
    async with DocumentTranslationClient(endpoint=endpoint, credential=credential) as client:
        async def one(inputs):
            async with limit:
                poller = await client.begin_translation(inputs=inputs)
                operation_id = poller.id        # persist privately before awaiting
                docs = [status_record(d) for d in await poller.result()]
                return {'operation_id': operation_id, 'documents': docs}
        return await asyncio.gather(*(one(b) for b in batches), return_exceptions=True)
  • Import the client from .aio — the sync client rejects async with; every call needs await.
  • Close both the credential and the client. An async single-document client is version-dependent: inspect the .aio exports before using one; if only sync exists, use the sync path or a bounded thread wrapper.

Preview shortened. The full SKILL.md is in the pack.