You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

大体积PDF文档翻译并存储至Azure Blob的代码实现需求

大体积PDF翻译+Azure Blob存储实现方案

核心依赖安装

先安装所需Python包:

pip install azure-translation-document azure-storage-blob pdfplumber

方案说明

针对14MB这类大体积PDF,普通文本翻译API易因内存或请求限制失败,推荐用Azure文档翻译服务(专门支持大文件批量翻译,原生兼容PDF格式),翻译完成后直接将结果存储至Azure Blob。

完整代码实现

1. 配置Azure服务参数

# Azure文档翻译服务配置
TRANSLATOR_KEY = "你的文档翻译服务密钥"
TRANSLATOR_REGION = "你的服务区域(如eastus)"
# 可选:若源PDF已在Blob,填容器SAS URL;用本地文件则跳过
SOURCE_BLOB_SAS_URL = ""
# 翻译结果要存入的Blob容器SAS URL
TARGET_BLOB_SAS_URL = "目标容器SAS URL"

# Azure Blob存储配置(手动上传时用)
BLOB_CONNECTION_STRING = "你的Blob存储连接字符串"
TARGET_CONTAINER_NAME = "目标容器名称"

2. 大PDF翻译(Azure文档翻译服务原生支持)

该服务自动处理大文件分片、翻译,无需手动拆分文本:

from azure.core.credentials import AzureKeyCredential
from azure.ai.translation.document import DocumentTranslationClient

def translate_large_pdf(source_path, target_lang="zh-Hans"):
    client = DocumentTranslationClient(
        endpoint=f"https://{TRANSLATOR_REGION}.cognitiveservices.azure.com/",
        credential=AzureKeyCredential(TRANSLATOR_KEY)
    )

    # 提交翻译任务(支持本地文件或Blob SAS URL)
    poller = client.begin_translation(
        source_url=source_path,
        target_url=TARGET_BLOB_SAS_URL,
        target_language=target_lang
    )
    result = poller.result()

    # 输出结果状态
    for doc in result:
        if doc.status == "Succeeded":
            print(f"翻译完成,结果Blob路径:{doc.translated_document_url}")
            return doc.translated_document_url
        else:
            print(f"翻译失败:{doc.error.message}")
            return None

3. 手动上传翻译结果至Blob(本地文件场景)

如果翻译结果生成在本地,可手动上传至Blob:

from azure.storage.blob import BlobServiceClient

def upload_to_blob(local_file_path, blob_file_name):
    blob_service_client = BlobServiceClient.from_connection_string(BLOB_CONNECTION_STRING)
    blob_client = blob_service_client.get_blob_client(container=TARGET_CONTAINER_NAME, blob=blob_file_name)

    with open(local_file_path, "rb") as data:
        blob_client.upload_blob(data, overwrite=True)
    print(f"文件 {blob_file_name} 已上传至Blob存储")

4. 主函数调用

if __name__ == "__main__":
    # 本地大PDF路径(若用Blob源,替换为SOURCE_BLOB_SAS_URL)
    local_pdf = "large_document.pdf"
    # 执行翻译
    translate_large_pdf(local_pdf)
    # 若需手动上传本地翻译文件,取消注释
    # upload_to_blob("translated_result.pdf", "translated_large_pdf.pdf")

关键注意事项

  • 确保Azure文档翻译服务已启用,密钥、区域配置准确
  • 超大型PDF(>100MB)建议先上传至Blob,用SAS URL提交翻译,避免本地传输限制
  • 翻译为异步任务,poller.result()会等待完成,可添加超时设置或异步回调
  • Blob容器SAS URL需包含读写权限,确保服务能写入结果

内容的提问来源于stack exchange,提问作者sathish chandra

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 00:25:11