مكتبة Python

الترجمة بالذكاء الاصطناعي باستخدام Python وLingo.dev

مقدمة

تقوم مكتبة Lingo.dev لبايثون بترجمة النصوص وكائنات JSON والمحادثات من خلال واجهة برمجة تطبيقات غير متزامنة. تتعامل مع البيانات الكبيرة عن طريق تقسيم المحتوى تلقائيًا إلى أحجام دفعات مثالية، وتتبع التقدم للترجمات طويلة المدى، وتدعم المعاجم للحفاظ على اتساق المصطلحات.

التثبيت

pip

pip install lingodotdev

uv

uv add lingodotdev

ترجمة سريعة

تخطى مدير السياق للترجمات الفردية. تتعامل هذه الطرق مع دورة حياة المحرك تلقائيًا وتستخدم الوضع السريع افتراضيًا، مما يجعلها مثالية لأدوات سطر الأوامر والنصوص البرمجية.


# /// 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 مفتاح API من Lingo.dev وتستخدم مديري سياق غير متزامنين.


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

ترجمة الكائنات

ترجمة القواميس المتداخلة مع الحفاظ على البنية. تقوم مجموعة أدوات التطوير بمعالجة جميع قيم السلاسل النصية بشكل متكرر بغض النظر عن العمق.


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

المعالجة التسلسلية مع تتبع التقدم

يتيح الوضع التسلسلي استدعاءات مفصلة لتتبع التقدم. تتلقى دالة الاستدعاء الجزء المصدري والجزء المترجم لكل دفعة تتم معالجتها، وهو مفيد لتصحيح أخطاء الترجمة أو عرض تقدم مفصل في واجهات المستخدم.


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

بيانات مرجعية

توفير مسارد أو ترجمات سابقة لضمان الاتساق. يتم إرسال البيانات المرجعية مع كل جزء إلى واجهة برمجة التطبيقات، لذا احتفظ بها بحجم معقول. استخدم هذا للمصطلحات التجارية، أو المفردات التقنية، أو الحفاظ على اتساق الترجمة عبر تحديثات المنتج.


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

الإعدادات

التحكم في سلوك المعالجة الدفعية ونقاط نهاية واجهة برمجة التطبيقات. تقوم مجموعة أدوات التطوير بتقسيم البيانات الكبيرة بناءً على قيود عدد المفاتيح وعدد الكلمات، مما يمنع انتهاء مهلة واجهة برمجة التطبيقات ويحسن موثوقية مهام الترجمة الكبيرة.


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

فحص مفتاح واجهة برمجة التطبيقات

التحقق من الحساب الذي يملك مفتاح واجهة برمجة التطبيقات. يُرجع 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())