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

    # 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,              # 청크당 항목 수 (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())