Python SDK
الترجمة بالذكاء الاصطناعي باستخدام Python وLingo.dev
مقدمة
يترجم Lingo.dev Python SDK النصوص وكائنات 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())
ترجمة الكائنات
ترجمة القواميس المتداخلة مع الحفاظ على البنية. يعالج 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())
المعالجة المتسلسلة مع التقدم
يتيح الوضع المتسلسل استدعاءات تقدم مفصلة. يتلقى الاستدعاء الجزء المصدر والجزء المترجم لكل دفعة تتم معالجتها، وهو مفيد لتصحيح مشكلات الترجمة أو عرض التقدم التفصيلي في واجهات المستخدم.
# /// 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())
التكوين
التحكم في سلوك التجميع ونقاط نهاية واجهة برمجة التطبيقات. يقسم SDK الحمولات الكبيرة بناءً على قيود عدد المفاتيح وعدد الكلمات، مما يمنع انتهاء مهلة واجهة برمجة التطبيقات ويحسن الموثوقية لمهام الترجمة الكبيرة.
# /// 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())