빠른 시작
아래 흐름에서는 API 키를 사용하여 파일 하나를 업로드하고 번역 작업을 생성한 뒤 결과를 다운로드합니다.
-
자격 증명과 파일을 준비합니다
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)
얻는 결과
섹션 제목: “얻는 결과”스크립트는 먼저 job_id을 출력합니다. 작업이 성공하면 결과가 현재 디렉터리로 다운로드됩니다. 작업이 completed 또는 failed에 도달하면 폴링이 중지됩니다.
소요 시간은 파일 크기와 대기열에 따라 달라집니다. 프로덕션 환경에서는 무제한 폴링 대신 웹훅 또는 SSE 를 사용하십시오.
이 예제는 생성 요청을 자동으로 재시도하지 않습니다. 네트워크 시간 초과 후에는 작업 ID, 멱등 키 및 요청 본문을 유지하고 먼저 상태를 확인하십시오. 스크립트가 종료되더라도 이미 생성된 작업은 취소되지 않습니다.
무언가 실패했을 때
섹션 제목: “무언가 실패했을 때”401: 환경 변수가 설정되어 있고 키가 유효한지 확인하십시오.402또는 작업 중quota_exceeded: 채무 차감 후의 잔액이 시작 기준치를 충족하는지 확인하십시오.403: 키의 예산, 허용된 설정 및 리소스 소유자를 확인하십시오.429: 비즈니스 오류 코드를 읽어 레이트 리밋, 대기열 가득, 예산 소진을 구분합니다.- 직접 업로드 주소가 만료되었거나 업로드에 실패했습니다. 새 업로드 주소를 요청하십시오.
X-Request-Id와 요청 경로를 기록하되, 전체 키나 업로드 자격 증명은 절대 기록하지 않습니다. 모든 오류 및 재시도 방법은 오류 참조 에 있습니다.