Python SDK

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

简介

Lingo.dev Python SDK 通过异步 API 翻译文本、JSON 对象和聊天对话。它通过自动将内容分块为最佳批量大小来处理大负载,跟踪长时间运行的翻译进度,并支持术语表以确保术语一致性。

安装

pip

pip install lingodotdev

uv

uv add lingodotdev

快速翻译

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


# /// 脚本

# 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"]

    # 翻译文本
    text_result = await LingoDotDevEngine.quick_translate(
        "Hello world",
        api_key=api_key,
        source_locale="en",
        target_locale="es"
    )
    print(f"文本: {text_result}")

    # 翻译对象
    object_result = await LingoDotDevEngine.quick_translate(
        {"greeting": "Hello", "farewell": "Goodbye"},
        api_key=api_key,
        source_locale="en",
        target_locale="fr"
    )
    print(f"对象: {object_result}")

asyncio.run(main())

基本用法

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


# /// 脚本

# 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"进度: {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}")

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:
        # 将文本翻译为多种语言
        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())

带进度的顺序处理

顺序模式支持详细的进度回调。回调会接收每个处理批次的源块和翻译块,这对于调试翻译问题或在用户界面中显示详细进度非常有用。


# /// 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 超时并提高大型翻译任务的可靠性。


# /// 脚本

# 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,              # 每个批次的项目数量 (1-250)
        "ideal_batch_item_size": 250,  # 每个批次的单词数量 (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())

语言检测

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


# /// 脚本

# 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"检测到的语言: {locale}")

asyncio.run(main())

API 密钥检查

检查哪个账户拥有某个 API 密钥。如果身份验证失败,则返回 None。可用于调试身份验证问题或在管理工具中显示账户信息。


# /// 脚本

# 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),以便实施适当的重试逻辑。


# /// 脚本

# 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"无效的参数或错误的请求: {e}")
    except RuntimeError as e:
        print(f"服务器或网络错误: {e}")

asyncio.run(main())