Python SDK (polylingo)

Khách hàng Python chính thức cho PolyLingo REST API. Nó sử dụng httpx và cung cấp cả khách hàng đồng bộbất đồng bộ với cùng tên phương thức.

Để biết chi tiết HTTP thô, xem API reference.


Cài đặt

pip install polylingo

Python: >= 3.9


Khách hàng đồng bộ

import os
import polylingo

client = polylingo.PolyLingo(
    api_key=os.environ["POLYLINGO_API_KEY"],
    base_url="https://api.usepolylingo.com/v1",  # tùy chọn; mặc định được hiển thị
    timeout=120.0,  # tùy chọn; giây cho mỗi yêu cầu (mặc định 120)
)

result = client.translate(content="# Hello", targets=["es", "fr"], format="markdown")
print(result["translations"]["es"])

client.close()

Trình quản lý ngữ cảnh:

with polylingo.PolyLingo(api_key="...") as client:
    print(client.languages())
Đối sốBắt buộcMô tả
api_keyKhóa API (Authorization: Bearer …).
base_urlKhôngTiền tố API bao gồm /v1. Mặc định https://api.usepolylingo.com/v1.
timeoutKhôngThời gian chờ httpx tính bằng giây. Mặc định 120.0.

Khách hàng bất đồng bộ

import polylingo

async with polylingo.AsyncPolyLingo(api_key="...") as client:
    r = await client.translate(content="Hi", targets=["de"])

Sử dụng await client.aclose() nếu không dùng async with.

Tên phương thức giống với khách hàng đồng bộ; tất cả phương thức mạng đều là async def.


Các phương thức (đồng bộ và bất đồng bộ)

health() / await health()

GET /health

h = client.health()
# async: h = await client.health()

languages() / await languages()

GET /languages

data = client.languages()
langs = data["languages"]

translate(...)

POST /translate

r = client.translate(
    content="# Hello",
    targets=["es", "fr"],
    format="markdown",  # tùy chọn
    source="en",        # tùy chọn
    model="standard",   # tùy chọn: "standard" | "advanced"
)
r["translations"]["es"]
r["usage"]["total_tokens"]

batch(...)

POST /translate/batch

b = client.batch(
    items=[
        {"id": "a", "content": "Hello"},
        {"id": "b", "content": "## Title", "format": "markdown"},
    ],
    targets=["de"],
)
b["results"][0]["translations"]["de"]

usage() / await usage()

GET /usage

u = client.usage()

Công việc (client.jobs)

create / await create

POST /jobs. Trả về thân 202 (job_id, status, …).

job = client.jobs.create(content=long_md, targets=["de", "fr"], format="markdown")
# cũng chấp nhận kwargs: client.jobs.create(**{"content": ..., "targets": [...]})

get(job_id) / await get(job_id)

GET /jobs/:id. Khi status == "completed", phản hồi bao gồm translationsusage ở cấp trên cùng.

translate(...) (tiện lợi)

Kiểm tra liên tục cho đến khi completed hoặc failed, hoặc hết thời gian.

done = client.jobs.translate(
    content=long_md,
    targets=["de", "fr", "es"],
    format="markdown",
    poll_interval=10.0,   # giây giữa các lần kiểm tra; mặc định 5.0
    timeout=600.0,        # tổng số giây; mặc định 1200 (20 phút)
    on_progress=lambda pos: print(f"Queue: {pos}"),
)
done["translations"]["de"]

Bất đồng bộ:

done = await client.jobs.translate(
    content=long_md,
    targets=["de"],
    poll_interval=2.0,
    timeout=300.0,
)

Trạng thái API: pending, processing, completed, failed.


Ngoại lệ

LớpKhi nào
polylingo.PolyLingoErrorCơ sở. status, error, thông điệp args[0].
polylingo.AuthErrorHTTP 401.
polylingo.RateLimitErrorHTTP 429. Có thể có retry_after (giây).
polylingo.JobFailedErrorCông việc thất bại, payload hoàn thành sai hoặc hết thời gian kiểm tra. Bao gồm job_id.
import polylingo

try:
    client.translate(content="x", targets=["es"])
except polylingo.AuthError as e:
    print(e.status, e.error)
except polylingo.RateLimitError as e:
    print(e.retry_after)
except polylingo.JobFailedError as e:
    print(e.job_id)
except polylingo.PolyLingoError as e:
    print(e.status, e.error)

Mẫu công việc bất đồng bộ (tóm tắt)

  1. Thủ công: jobs.create → vòng lặp jobs.get đến trạng thái cuối.
  2. Trợ giúp: jobs.translate với poll_interval, timeout và tùy chọn on_progress.

Ưu tiên dùng công việc cho nội dung rất lớn, nơi translate đồng bộ có thể gặp giới hạn thời gian của máy khách hoặc máy chủ.


Kiểu dữ liệu

Gói đi kèm py.typed. Đối tượng phản hồi là các giá trị dict đơn giản phù hợp với API; nếu muốn, hãy dùng chú thích kiểu TypedDict trong mã của bạn.


Nhật ký thay đổi

0.1.2

  • Bảo trì: URL cơ sở API mặc định là https://api.usepolylingo.com/v1.

0.1.0

  • Phát hành ban đầu: đồng bộ PolyLingo, bất đồng bộ AsyncPolyLingo, bao phủ đầy đủ các điểm cuối bao gồm trợ giúp kiểm tra jobs.translate.
Python SDK | Tài liệu PolyLingo | PolyLingo