SSE을 사용한 실시간 진행 상황
SSE(Server-Sent Events)를 통해 파일 번역 작업(/jobs)의 진행 상황을 실시간으로 수신합니다. SSE를 사용할 수 없는 경우 연결은 404을 반환하므로 대신 작업 상태를 폴링하십시오.
연결 흐름
섹션 제목: “연결 흐름”브라우저의 EventSource은 사용자 지정 헤더를 보낼 수 없으므로 자격 증명은 두 단계로 처리됩니다:
- 귀하의 서버는 API 키를 티켓으로 교환합니다(유효 기간 30초, 사용 가능 횟수 1회).
- 티켓을 사용하여 SSE에 연결합니다(이는 브라우저에서 발생할 수 있으며, 티켓은 장기간 유효한 자격 증명이 아닙니다).
POST /api/v1/sse/ticket/{job_id} → {"ticket": "..."}GET /api/v1/sse/jobs/{job_id}?ticket=...JavaScript 예시
섹션 제목: “JavaScript 예시”API 키를 서버에 저장합니다: 서버는 티켓을 받아 브라우저에 전달합니다.
// Server (Node.js 18+): exchange the key for a ticketasync function createSseTicket(jobId) { const response = await fetch( `https://omnidoc.top/api/v1/sse/ticket/${jobId}`, { method: 'POST', headers: { 'X-API-Key': process.env.OMNIDOC_API_KEY } } ); if (!response.ok) throw new Error(`ticket failed: ${response.status}`); return (await response.json()).ticket;}// Browser: connect to SSE with the ticket from your serverconst source = new EventSource( `https://omnidoc.top/api/v1/sse/jobs/${jobId}?ticket=${encodeURIComponent(ticket)}`);
// The events are named, so use addEventListener (onmessage does not receive them)source.addEventListener('job_update', (event) => { const data = JSON.parse(event.data); console.log(`status: ${data.status}, stage: ${data.stage}, progress: ${data.stage_progress}%`);});
source.addEventListener('job_done', (event) => { const data = JSON.parse(event.data); console.log(`finished: ${data.status}`); source.close();});이벤트 유형
섹션 제목: “이벤트 유형”| 이벤트 | 설명 |
|---|---|
job_update | 상태 또는 단계가 변경됨(연결 직후 현재 상태의 스냅샷이 전송됩니다) |
job_done | 작업이 종료되었습니다(completed 또는 failed); 연결을 닫을 수 있습니다. |
timeout | 스트림이 최대 지속 시간에 도달했습니다. 재연결하세요. |
error | 서버 측 문제 발생; 새 티켓을 발급받아 나중에 다시 연결해 주세요. |
이벤트 데이터
섹션 제목: “이벤트 데이터”서버의 stage_message는 중국어로 되어 있습니다:
event: job_updatedata: {"status":"processing","stage":"translating","stage_progress":45,"stage_message":"正在翻译..."}
event: job_donedata: {"status":"completed","stage":"completed","stage_progress":100,"stage_message":""}작업이 완료되면 GET /api/v1/artifacts?job_id=...을 사용하여 결과 목록을 가져옵니다.
Python 예시
섹션 제목: “Python 예시”pip install requests sseclient-pyimport json
import requestsimport sseclient # sseclient-py
BASE = "https://omnidoc.top/api/v1"HEADERS = {"X-API-Key": "sk_your_key"}job_id = "q3f8s6c2a9m1k4tx"
ticket_response = requests.post( f"{BASE}/sse/ticket/{job_id}", headers=HEADERS, timeout=20)ticket_response.raise_for_status()ticket = ticket_response.json()["ticket"]
# Read timeout longer than the 15-second heartbeat; no API key while connectedresponse = requests.get( f"{BASE}/sse/jobs/{job_id}", params={"ticket": ticket}, stream=True, timeout=(10, 60),)response.raise_for_status()client = sseclient.SSEClient(response)
for event in client.events(): data = json.loads(event.data) print(f"[{event.event}] {data.get('stage')} {data.get('stage_progress', 0)}%") if event.event in {"job_done", "timeout", "error"}: break # timeout / error: get a new ticket and reconnect, or poll instead참고 사항
섹션 제목: “참고 사항”- 티켓은 한 번만 사용할 수 있습니다. 재연결하기 전에 새 티켓을 발급받으세요.
- 각 계정은 한 번에 최대 6개의 SSE 연결을 유지할 수 있으며, 분당 최대 30장의 티켓을 교환할 수 있습니다. 이를 초과하면 응답이
429으로 반환되므로, 대신Retry-After을 기다리거나 폴링을 사용하십시오. - 오랜 시간 동안 작업 이벤트가 없으면 서버는
timeout이벤트를 보내며, 새 티켓을 받아 재연결합니다. - 연결이 유휴 상태일 때 서버는 하트비트 주석을 보냅니다. 클라이언트는 해당 주석 행을 무시해야 합니다.
- 연결이 끊어지면 폴링
GET /jobs/{id}이 대체 수단으로 작동합니다.