Python SDK

使用 Python 和 Lingo.dev 进行 AI 翻译

简介

Lingo.dev Python SDK 通过异步 API 支持文本、JSON 对象和聊天会话的翻译。它能够自动将大体积内容分块为最佳批次,适配大规模翻译任务,跟踪长时间运行的翻译进度,并支持术语表以确保术语一致性。

安装

pip

pip install lingodotdev

uv

uv add lingodotdev

快速翻译

对于一次性翻译,可跳过上下文管理器。这些方法会自动处理引擎生命周期,并默认启用快速模式,非常适合 CLI 工具和脚本。

# /// script
# requires-python = ">=3.11"
# dependencies = [
#     "lingodotdev==1.3.0",
# ]
# ///

import asyncio
import os
from lingodotdev.engine import LingoDotDevEngine

async def main():
    api_key = os.environ["LINGODOTDEV_API_KEY"]

    # Translate text
    text_result = await LingoDotDevEngine.quick_translate(
        "Hello world",
        api_key=api_key,
        source_locale="en",
        target_locale="es"
    )
    print(f"Text: {text_result}")

    # Translate object
    object_result = await LingoDotDevEngine.quick_translate(
        {"greeting": "Hello", "farewell": "Goodbye"},
        api_key=api_key,
        source_locale="en",
        target_locale="fr"
    )
    print(f"Object: {object_result}")

asyncio.run(main())

基本用法

SDK 需要从 Lingo.dev 获取 API 密钥,并使用异步上下文管理器。

# /// script
# requires-python = ">=3.11"
# dependencies = [
#     "lingodotdev==1.3.0",
# ]
# ///

import asyncio
import os
from lingodotdev import LingoDotDevEngine

async def main():
    api_key = os.environ["LINGODOTDEV_API_KEY"]
    async with LingoDotDevEngine({"api_key": api_key}) as engine:
        result = await engine.localize_text(
            "Welcome! We missed you.",
            {"source_locale": "en", "target_locale": "es"}
        )
        print(result)

asyncio.run(main())

带进度的文本翻译

通过回调函数跟踪翻译进度。即使是单条文本也会经过分块处理,从而为长文本提供进度报告,并在所有内容类型中保持一致的行为。

# /// script
# requires-python = ">=3.11"
# dependencies = [
#     "lingodotdev==1.3.0",
# ]
# ///

import asyncio
import os
from lingodotdev import LingoDotDevEngine

def on_progress(percent: int):
    print(f"Progress: {percent}%")

async def main():
    api_key = os.environ["LINGODOTDEV_API_KEY"]
    async with LingoDotDevEngine({"api_key": api_key}) as engine:
        result = await engine.localize_text(
            "We sent a confirmation email.",
            {"source_locale": "en", "target_locale": "es"},
            progress_callback=on_progress
        )
        print(f"Result: {result}")

asyncio.run(main())

对象翻译

在保留结构的同时翻译嵌套字典。SDK 会递归处理所有层级的字符串值。

# /// script
# requires-python = ">=3.11"
# dependencies = [
#     "lingodotdev==1.3.0",
# ]
# ///

import asyncio
import os
from lingodotdev import LingoDotDevEngine

async def main():
    content = {
        "title": "Welcome",
        "cta": "Start your free trial",
        "footer": {
            "legal": "All rights reserved.",
            "help": "Need help?"
        }
    }

    api_key = os.environ["LINGODOTDEV_API_KEY"]
    async with LingoDotDevEngine({"api_key": api_key}) as engine:
        result = await engine.localize_object(
            content,
            {"source_locale": "en", "target_locale": "es"}
        )
        print(result)

asyncio.run(main())

批量翻译为多种语言

一次调用即可将内容翻译为多个目标语言。返回的列表与请求顺序一致,每个目标语言对应一个结果。

# /// script
# requires-python = ">=3.11"
# dependencies = [
#     "lingodotdev==1.3.0",
# ]
# ///

import asyncio
import os
from lingodotdev import LingoDotDevEngine

async def main():
    api_key = os.environ["LINGODOTDEV_API_KEY"]
    async with LingoDotDevEngine({"api_key": api_key}) as engine:
        # Translate text to multiple languages
        text_results = await engine.batch_localize_text(
            "Welcome to our application",
            {
                "source_locale": "en",
                "target_locales": ["es", "fr", "de"],
                "fast": True
            }
        )
        print(f"Text results: {text_results}")

asyncio.run(main())

批量对象翻译

快速批处理方法可同时处理文本和对象。

# /// script
# requires-python = ">=3.11"
# dependencies = [
#     "lingodotdev==1.3.0",
# ]
# ///

import asyncio
import os
from lingodotdev.engine import LingoDotDevEngine

async def main():
    api_key = os.environ["LINGODOTDEV_API_KEY"]
    results = await LingoDotDevEngine.quick_batch_translate(
        {"greeting": "Hello", "bye": "Goodbye"},
        api_key=api_key,
        target_locales=["es", "fr", "de"],
        source_locale="en",
        fast=True,
    )
    for locale, result in zip(["es", "fr", "de"], results):
        print(f"{locale}: {result}")

asyncio.run(main())

聊天翻译

在翻译聊天消息时保留发言人姓名。每条消息必须包含 "name" 和 "text" 字段。适用于本地化支持对话、聊天记录或对话系统,同时保持对话结构不变。

# /// script
# requires-python = ">=3.11"
# dependencies = [
#     "lingodotdev==1.3.0",
# ]
# ///

import asyncio
import os
from lingodotdev import LingoDotDevEngine

async def main():
    chat = [
        {"name": "Alice", "text": "Hello everyone!"},
        {"name": "Bob", "text": "How are you doing?"},
        {"name": "Alice", "text": "Great, thanks for asking!"},
    ]

    api_key = os.environ["LINGODOTDEV_API_KEY"]
    async with LingoDotDevEngine({"api_key": api_key}) as engine:
        result = await engine.localize_chat(
            chat,
            {"source_locale": "en", "target_locale": "es"}
        )
        for message in result:
            print(f"{message['name']}: {message['text']}")

asyncio.run(main())

顺序处理与进度反馈

顺序模式支持详细的进度回调。回调会为每个已处理批次提供源片段和翻译片段,便于调试翻译问题或在 UI 中显示详细进度。

# /// script
# requires-python = ">=3.11"
# dependencies = [
#     "lingodotdev==1.3.0",
# ]
# ///

import asyncio
import os
from lingodotdev import LingoDotDevEngine

def progress(percent: int, src_chunk: dict, out_chunk: dict):
    print(f"{percent}% complete - processed {len(src_chunk)} keys")

async def main():
    content = {
        "welcome": "Hello",
        "goodbye": "Farewell",
        "help": "Need assistance?"
    }

    api_key = os.environ["LINGODOTDEV_API_KEY"]
    async with LingoDotDevEngine({"api_key": api_key}) as engine:
        result = await engine.localize_object(
            content,
            {"source_locale": "en", "target_locale": "es"},
            progress_callback=progress
        )
        print(result)

asyncio.run(main())

并发处理

并行处理片段以加快翻译速度。此模式牺牲了进度跟踪以提升速度,适用于对吞吐量要求高于用户反馈的生产环境。

# /// script
# requires-python = ">=3.11"
# dependencies = [
#     "lingodotdev==1.3.0",
# ]
# ///

import asyncio
import os
from lingodotdev import LingoDotDevEngine

async def main():
    content = {
        "header": {"title": "Welcome", "subtitle": "Get started"},
        "body": {"intro": "Learn more", "details": "Full description"},
        "footer": {"copyright": "2024", "contact": "Email us"}
    }

    api_key = os.environ["LINGODOTDEV_API_KEY"]
    async with LingoDotDevEngine({"api_key": api_key}) as engine:
        result = await engine.localize_object(
            content,
            {"source_locale": "en", "target_locale": "es"},
            concurrent=True
        )
        print(result)

asyncio.run(main())

参考数据

可提供术语表或历史翻译以确保一致性。参考数据会随每个片段一同发送到 API,因此请保持其合理大小。适用于品牌术语、技术词汇或在产品更新中保持翻译一致性。

# /// script
# requires-python = ">=3.11"
# dependencies = [
#     "lingodotdev==1.3.0",
# ]
# ///

import asyncio
import os
from lingodotdev import LingoDotDevEngine

async def main():
    content = {"cta": "Start your free trial", "title": "Welcome"}

    reference = {
        "es": {"cta": "Comienza tu prueba gratuita"},
        "fr": {"cta": "Commencez votre essai gratuit"},
    }

    api_key = os.environ["LINGODOTDEV_API_KEY"]
    async with LingoDotDevEngine({"api_key": api_key}) as engine:
        result = await engine.localize_object(
            content,
            {
                "source_locale": "en",
                "target_locale": "es",
                "reference": reference,
            },
            concurrent=True
        )
        print(result)

asyncio.run(main())

配置

可控制批处理行为和 API 端点。SDK 会根据键数量和词数限制拆分大型负载,防止 API 超时并提升大规模翻译任务的可靠性。

# /// script
# requires-python = ">=3.11"
# dependencies = [
#     "lingodotdev==1.3.0",
# ]
# ///

import asyncio
import os
from lingodotdev import LingoDotDevEngine

async def main():
    config = {
        "api_key": os.environ["LINGODOTDEV_API_KEY"],
        "api_url": "https://engine.lingo.dev",
        "batch_size": 25,              # Items per chunk (1-250)
        "ideal_batch_item_size": 250,  # Words per chunk (1-2500)
    }

    async with LingoDotDevEngine(config) as engine:
        result = await engine.localize_text(
            "Reset your password",
            {"source_locale": "en", "target_locale": "es", "fast": True}
        )
        print(result)

asyncio.run(main())

语言检测

检测文本字符串的语言。适用于自动将内容路由到正确的翻译流程或验证用户输入的语言。

# /// script
# requires-python = ">=3.11"
# dependencies = [
#     "lingodotdev==1.3.0",
# ]
# ///

import asyncio
import os
from lingodotdev import LingoDotDevEngine

async def main():
    api_key = os.environ["LINGODOTDEV_API_KEY"]
    async with LingoDotDevEngine({"api_key": api_key}) as engine:
        locale = await engine.recognize_locale("Guten Morgen")
        print(f"Detected language: {locale}")

asyncio.run(main())

API 密钥自检

检查 API 密钥归属于哪个账户。如果认证失败则返回 None。适用于调试认证问题或在管理工具中显示账户信息。

# /// script
# requires-python = ">=3.11"
# dependencies = [
#     "lingodotdev==1.3.0",
# ]
# ///

import asyncio
import os
from lingodotdev import LingoDotDevEngine

async def main():
    api_key = os.environ["LINGODOTDEV_API_KEY"]
    async with LingoDotDevEngine({"api_key": api_key}) as engine:
        user = await engine.whoami()
        if user:
            print(f"Authenticated as: {user}")
        else:
            print("Authentication failed")

asyncio.run(main())

错误处理

SDK 会因参数问题抛出 ValueError,对于网络或服务器错误则抛出 RuntimeError。请区分用户错误(ValueError)与基础设施问题(RuntimeError),以便实现合适的重试逻辑。

# /// script
# requires-python = ">=3.11"
# dependencies = [
#     "lingodotdev==1.3.0",
# ]
# ///

import asyncio
import os
from lingodotdev import LingoDotDevEngine

async def main():
    try:
        api_key = os.environ["LINGODOTDEV_API_KEY"]
        async with LingoDotDevEngine({"api_key": api_key}) as engine:
            result = await engine.localize_text(
                "Hello",
                {"target_locale": "es"}
            )
            print(result)
    except ValueError as e:
        print(f"Invalid parameters or bad request: {e}")
    except RuntimeError as e:
        print(f"Server or network error: {e}")

asyncio.run(main())