Python SDK

Lingo.devによるPythonでの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"]

    # テキストを翻訳
    text_result = await LingoDotDevEngine.quick_translate(
        "Hello world",
        api_key=api_key,
        source_locale="en",
        target_locale="es"
    )
    print(f"Text: {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: {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.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,              # チャンクごとのアイテム数 (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())

言語検出

テキスト文字列の言語を検出します。コンテンツを適切な翻訳パイプラインに自動的にルーティングしたり、ユーザー入力言語を検証したりするのに役立ちます。


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