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 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_keystr필수Lingo.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: dictstr단일 문자열 번역
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컨텍스트 매니저 없이 1회 번역 수행
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아니오일관된 번역을 위한 용어집 또는 참고 번역