Python SDK

PythonとLingo.devによるAI翻訳

はじめに

Lingo.dev Python SDKは、非同期APIを通じてテキスト、JSONオブジェクト、チャット会話を翻訳します。コンテンツを最適なバッチサイズに自動的にチャンク化することで大きなペイロードを処理し、長時間実行される翻訳の進行状況を追跡し、一貫した用語のためのグロッサリーをサポートします。

インストール

pip

pip install lingodotdev

uv

uv add lingodotdev

クイック翻訳

1回限りの翻訳にはコンテキストマネージャーをスキップします。これらのメソッドはエンジンのライフサイクルを自動的に処理し、デフォルトで高速モードを使用するため、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())

複数言語へのバッチ翻訳

1回の呼び出しで複数のターゲット言語にコンテンツを翻訳します。リクエストされた順序と同じ順序で、ターゲットロケールごとに1つの結果を含むリストを返します。

# /// 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 import LingoDotDevEngine

async def main():
    objects = [
        {"title": "Getting Started", "description": "Learn the basics"},
        {"title": "Advanced Usage", "description": "Deep dive into features"},
        {"title": "API Reference", "description": "Complete method listing"},
    ]

    api_key = os.environ["LINGODOTDEV_API_KEY"]
    async with LingoDotDevEngine({"api_key": api_key}) as engine:
        results = await engine.batch_localize_objects(
            objects,
            {"source_locale": "en", "target_locale": "es"}
        )
        for result in results:
            print(result)

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())

APIリファレンス

コンストラクター

パラメーターデフォルト説明
api_keystrrequiredLingo.devのAPIキー
api_urlstr"https://engine.lingo.dev"APIエンドポイントのURL
batch_sizeint25チャンクごとのアイテム数(1~250)
ideal_batch_item_sizeint250チャンクごとの単語数(1~2500)

インスタンスメソッド

メソッドパラメーター戻り値説明
localize_text(text, params, progress_callback?)text: str, params: dictstr1つのテキスト文字列を翻訳
localize_object(obj, params, progress_callback?, concurrent?)obj: dict, params: dictdictディクショナリの構造を保持しつつ翻訳
localize_chat(chat, params, progress_callback?)chat: list[dict], params: dictlist[dict]チャットメッセージを話者名を保持して翻訳
batch_localize_text(text, params)text: str, params: dict with target_localeslist[str]複数のターゲットロケールに同時翻訳
batch_localize_objects(objects, params)objects: list[dict], params: dictlist[dict]複数オブジェクトを同時に翻訳
recognize_locale(text)text: strstrテキスト文字列の言語を検出
whoami()dict | None現在のAPIキーのアカウント情報を取得

クラスメソッド

メソッドパラメーター戻り値説明
quick_translate(content, api_key, target_locale, source_locale?, api_url?, fast?)content: str | dictstr | dictコンテキストマネージャーを使わない一度きりの翻訳
quick_batch_translate(content, api_key, target_locales, source_locale?, api_url?, fast?)content: str | dictlist複数のロケールへの一括翻訳

ローカライズ用パラメーター

キー必須説明
source_localestrいいえソース言語コード(省略時は自動検出)
target_localestrはい対象言語コード
target_localeslist[str]バッチ用対象言語コードのリスト
fastboolいいえ高速モードを有効にして迅速な翻訳にする
referencedictいいえ用語集やリファレンス翻訳で一貫性を保つ