Bắt đầu nhanh
Luồng dưới đây sử dụng khóa API để tải lên một tệp, tạo công việc dịch và tải xuống kết quả.
-
Chuẩn bị thông tin xác thực và tệp
Terminal window export OMNIDOC_API_KEY="sk_your_key"BASE="https://omnidoc.top/api/v1"FILE="report.docx"SIZE=$(wc -c < "$FILE" | tr -d ' ')import uuidfrom pathlib import Pathimport requestsAPI_KEY = "sk_your_key"BASE = "https://omnidoc.top/api/v1"FILE = Path("report.docx")H = {"X-API-Key": API_KEY}import axios from 'axios';import fs from 'node:fs';import path from 'node:path';const API_KEY = 'sk_your_key';const BASE = 'https://omnidoc.top/api/v1';const filePath = 'report.docx';const apiHeaders = { 'X-API-Key': API_KEY }; -
Yêu cầu một địa chỉ và tải tệp lên
Terminal window PRESIGN=$(curl --fail-with-body -sS "$BASE/upload/presign" \-H "X-API-Key: $OMNIDOC_API_KEY" \-H "Content-Type: application/json" \-d "$(jq -n --arg filename "$(basename "$FILE")" --argjson size "$SIZE" \'{filename:$filename,file_size:$size}')")UPLOAD_URL=$(printf '%s' "$PRESIGN" | jq -r '.upload_url')UPLOAD_TYPE=$(printf '%s' "$PRESIGN" | jq -r '.upload_headers["Content-Type"]')FINALIZE_TOKEN=$(printf '%s' "$PRESIGN" | jq -r '.finalize_token')curl --fail-with-body -sS -X PUT "$UPLOAD_URL" \-H "Content-Type: $UPLOAD_TYPE" \-H "If-None-Match: *" \--upload-file "$FILE"presign = requests.post(f"{BASE}/upload/presign",headers=H,json={"filename": FILE.name,"file_size": FILE.stat().st_size,},timeout=20,)presign.raise_for_status()ticket = presign.json()with FILE.open("rb") as stream:put_headers = {**ticket["upload_headers"],"Content-Length": str(FILE.stat().st_size),}uploaded = requests.put(ticket["upload_url"], headers=put_headers, data=stream, timeout=300)uploaded.raise_for_status()const stat = fs.statSync(filePath);const { data: ticket } = await axios.post(`${BASE}/upload/presign`,{filename: path.basename(filePath),file_size: stat.size,},{ headers: apiHeaders });await axios.put(ticket.upload_url, fs.createReadStream(filePath), {headers: { ...ticket.upload_headers, 'Content-Length': stat.size },maxBodyLength: Infinity,}); -
Xác nhận tải lên và lấy ID tài liệu
Terminal window DOCUMENT=$(curl --fail-with-body -sS "$BASE/upload/finalize" \-H "X-API-Key: $OMNIDOC_API_KEY" \-H "Content-Type: application/json" \-d "$(jq -n --arg token "$FINALIZE_TOKEN" '{finalize_token:$token}')")DOCUMENT_ID=$(printf '%s' "$DOCUMENT" | jq -r '.document.id')finalized = requests.post(f"{BASE}/upload/finalize",headers=H,json={"finalize_token": ticket["finalize_token"]},timeout=30,)finalized.raise_for_status()document_id = finalized.json()["document"]["id"]const { data: finalized } = await axios.post(`${BASE}/upload/finalize`,{ finalize_token: ticket.finalize_token },{ headers: apiHeaders });const documentId = finalized.document.id; -
Tạo tác vụ dịch thuật
Terminal window JOB=$(curl --fail-with-body -sS "$BASE/jobs" \-H "X-API-Key: $OMNIDOC_API_KEY" \-H "Content-Type: application/json" \-H "Idempotency-Key: $(uuidgen)" \-d "$(jq -n --arg document_id "$DOCUMENT_ID" \'{document_id:$document_id,target_lang:"en"}')")JOB_ID=$(printf '%s' "$JOB" | jq -r '.id')job_response = requests.post(f"{BASE}/jobs",headers={**H, "Idempotency-Key": str(uuid.uuid4())},json={"document_id": document_id, "target_lang": "en"},timeout=30,)job_response.raise_for_status()job_id = job_response.json()["id"]const { data: job } = await axios.post(`${BASE}/jobs`,{ document_id: documentId, target_lang: 'en' },{ headers: { ...apiHeaders, 'Idempotency-Key': crypto.randomUUID() } });const jobId = job.id; -
Chờ hoàn tất và tải xuống
import reimport timefrom urllib.parse import unquotewhile True:response = requests.get(f"{BASE}/jobs/{job_id}", headers=H, timeout=20)response.raise_for_status()job = response.json()if job["status"] in {"completed", "failed"}:breaktime.sleep(3)if job["status"] == "failed":raise RuntimeError(job.get("error_msg") or "translation failed")artifacts = requests.get(f"{BASE}/artifacts", headers=H, params={"job_id": job_id}, timeout=20)artifacts.raise_for_status()for artifact in artifacts.json():download = requests.get(f"{BASE}/artifacts/{artifact['id']}/download",headers=H,timeout=300,)download.raise_for_status()fallback = f"{artifact['id']}.{artifact['format']}"disposition = download.headers.get("Content-Disposition", "")utf8 = re.search(r"filename\*=UTF-8''([^;]+)", disposition, re.I)plain = re.search(r'filename="([^"]+)"', disposition, re.I)if utf8:name = unquote(utf8.group(1))elif plain:name = plain.group(1)else:name = fallbacksafe_name = Path(name).name or fallbackPath(safe_name).write_bytes(download.content)
Những gì bạn nhận được
Phần tiêu đề “Những gì bạn nhận được”Script trước tiên in ra job_id. Khi công việc thành công, kết quả sẽ được tải xuống thư mục hiện tại. Quá trình kiểm tra sẽ dừng khi công việc đạt đến completed hoặc failed.
Thời gian xử lý phụ thuộc vào kích thước tệp và thứ tự trong hàng đợi. Trong môi trường sản xuất, hãy sử dụng webhook hoặc SSE thay vì kiểm tra liên tục mà không giới hạn.
Ví dụ này không tự động thực hiện lại các yêu cầu tạo. Sau khi xảy ra thời gian chờ mạng, hãy giữ nguyên ID công việc, khóa tính idempotence và thân yêu cầu, đồng thời kiểm tra trạng thái trước. Một công việc đã được tạo sẽ không bị hủy khi tập lệnh kết thúc.
Khi có sự cố xảy ra
Phần tiêu đề “Khi có sự cố xảy ra”401: kiểm tra xem biến môi trường đã được thiết lập và khóa là hợp lệ.402, hoặcquota_exceededkhi thực hiện công việc: kiểm tra xem số dư tín dụng (sau khi trừ nợ) có đủ vượt qua ngưỡng bắt đầu hay không.403: kiểm tra ngân sách của khóa, các cài đặt được phép và chủ sở hữu tài nguyên.429: đọc mã lỗi nghiệp vụ để phân biệt giữa giới hạn tốc độ, hàng đợi đầy và ngân sách đã hết.- Địa chỉ tải lên trực tiếp đã hết hạn hoặc quá trình tải lên thất bại: vui lòng yêu cầu một địa chỉ tải lên mới.
Ghi lại X-Request-Id và đường dẫn yêu cầu, nhưng không bao giờ ghi lại khóa đầy đủ hoặc thông tin xác thực tải lên. Tất cả các lỗi và phương thức thử lại đều có trong tham chiếu lỗi . .