快速入門
以下流程使用公共 API Key,上傳一份檔案,建立翻譯任務並下載產物。
-
準備憑證和文件
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 }; -
申請位址並直傳檔案
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,}); -
確認上傳,取得文件 ID
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; -
建立翻譯任務
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; -
等待完成並下載
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)
執行後你會得到什麼
Section titled “執行後你會得到什麼”腳本會先輸出 job_id。任務成功後,產物下載到目前目錄。輪詢在任務進入 completed 或 failed 時結束。
處理時長取決於檔案大小和排隊情況。範例設定了等待上限;在生產環境中,請改用 Webhook 或 SSE ,不要無限輪詢。
示例不會自動重試建立請求。遇到網路超時時,保留任務 ID、冪等金鑰和請求正文,先查詢狀態。已經建立的任務不會因為指令碼退出而自動取消。
401:檢查環境變量是否已設定、Key 是否有效。402,或任務中出現quota_exceeded:檢查積分餘額(扣除欠款後)是否足以達到開始門檻。403:檢查 Key 預算、配置權限和資源歸屬。429:讀取業務錯誤碼,區分是頻率限制、排隊還是預算用完。- 直傳位址過期或上傳失敗:請重新申請上傳位址。
請記錄 X-Request-Id 和請求路徑,但日誌裡不要出現完整密鑰或上傳憑證。完整的錯誤說明與重試方法見 錯誤碼參考 。