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

如何在无AutoML模型下用Glossary ID结合Google Cloud Translation API翻译文档

使用Google Cloud Translation API结合术语表ID翻译文档(无需AutoML)

你可以直接使用Google Cloud Translation API的translate_document方法,并在请求中指定术语表ID,无需依赖AutoML模型。以下是完整的Python代码示例:

前提条件

  • 已安装Google Cloud Translation客户端库:pip install google-cloud-translate
  • 已创建术语表并获取其完整资源ID(格式为projects/[PROJECT_ID]/locations/[LOCATION]/glossaries/[GLOSSARY_ID])
  • 已配置Google Cloud认证(例如设置GOOGLE_APPLICATION_CREDENTIALS环境变量)

代码示例

from google.cloud import translate_v3 as translate

def translate_document_with_glossary(
    project_id: str,
    location: str,
    input_file_path: str,
    output_file_path: str,
    source_lang: str,
    target_lang: str,
    glossary_id: str,
):
    client = translate.TranslationServiceClient()

    # 构造术语表资源路径
    glossary_path = client.glossary_path(project_id, location, glossary_id)

    # 设置术语表配置
    glossary_config = translate.TranslateTextGlossaryConfig(glossary=glossary_path)

    # 读取输入文档
    with open(input_file_path, "rb") as f:
        input_content = f.read()

    # 构造文档翻译请求
    parent = f"projects/{project_id}/locations/{location}"
    document_input = translate.DocumentInputConfig(
        content=input_content,
        mime_type="application/pdf"  # 根据你的文档类型调整,支持docx、pdf、txt等
    )

    request = translate.TranslateDocumentRequest(
        parent=parent,
        source_language_code=source_lang,
        target_language_code=target_lang,
        document_input_config=document_input,
        glossary_config=glossary_config,
    )

    # 发送请求并获取结果
    response = client.translate_document(request=request)

    # 将翻译后的内容写入输出文件
    with open(output_file_path, "wb") as f:
        f.write(response.document_translation.byte_stream_outputs[0])

    print(f"翻译完成,结果已保存至 {output_file_path}")

# 调用示例
if __name__ == "__main__":
    translate_document_with_glossary(
        project_id="your-project-id",
        location="us-central1",  # 术语表所在的区域
        input_file_path="input.pdf",
        output_file_path="output_translated.pdf",
        source_lang="zh-CN",
        target_lang="en-US",
        glossary_id="your-glossary-id",
    )

关键说明

  • 确保术语表的区域与API请求的location参数一致
  • 支持的文档类型包括:application/pdf、application/vnd.openxmlformats-officedocument.wordprocessingml.document(docx)、text/plain等
  • 如果需要翻译纯文本而非文档,可以使用translate_text方法并传入glossary_config参数,逻辑类似

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 11:00:19