Auto-Translate API 參考文檔

Auto-Translate 專案完整 API 端點文檔

翻譯佇列系統 API 文檔

概述

本系統實現了完整的異步翻譯佇列系統,支援YouTube字幕和SRT檔案翻譯。系統採用依賴反轉設計,支援多種儲存後端和可配置的並發處理。

環境配置

必要環境變數

OPENAI_API_KEY=your_openai_api_key
THREADS=2  # 並發翻譯線程數(建議1-4)

可選環境變數

PORT=3000
SRT_DIR=./srts  # SRT檔案儲存目錄

API 端點說明

基本資訊

  • Base URL: http://localhost:3000 (本地) 或 http://18.141.225.228:3000 (生產環境)
  • Content-Type: application/json
  • 所有POST請求: 需要JSON格式的請求體

1. YouTube 字幕翻譯 (推薦)

端點

POST /api/youtube-to-srt-translate

請求格式

{
    "videoUrl": "https://www.youtube.com/watch?v=VIDEO_ID",
    "lang": "en",              // 源語言 (en, zh, ja, ko等)
    "targetLang": "zh-TW",     // 目標語言
    "translationModel": "gpt-4o", // 翻譯模型
    "priority": "normal"       // 可選: low, normal, high, urgent
}

響應格式

佇列版本 (異步)

{
    "success": true,
    "message": "翻譯任務已提交到佇列",
    "jobId": "job_1759060760034_abc123",
    "videoId": "VIDEO_ID",
    "status": "pending",
    "progress": 0,
    "downloadUrl": "/api/download/job_1759060760034_abc123",
    "statusUrl": "/api/queue/job/job_1759060760034_abc123/status"
}

同步版本 (直接返回)

直接返回翻譯完成的SRT內容作為檔案下載。

使用範例

# 基本使用
curl -X POST http://localhost:3000/api/youtube-to-srt-translate \
  -H "Content-Type: application/json" \
  -d '{
    "videoUrl": "https://www.youtube.com/watch?v=peUO_55ck4o",
    "lang": "en",
    "targetLang": "zh-TW",
    "translationModel": "gpt-4o"
  }'

# 高優先級任務
curl -X POST http://localhost:3000/api/youtube-to-srt-translate \
  -H "Content-Type: application/json" \
  -d '{
    "videoUrl": "https://www.youtube.com/watch?v=peUO_55ck4o",
    "lang": "en",
    "targetLang": "zh-TW",
    "translationModel": "gpt-4o",
    "priority": "high"
  }'

2. SRT 檔案翻譯

端點

POST /api/translate-srt

請求格式

需要使用 multipart/form-data 上傳檔案:

curl -X POST http://localhost:3000/api/translate-srt \
  -F "file=@path/to/your/file.srt" \
  -F "targetLang=zh-TW" \
  -F "translationModel=gpt-4o" \
  -F "priority=normal"

響應格式

{
    "success": true,
    "message": "翻譯任務已提交到佇列",
    "jobId": "job_1759060760035_def456",
    "status": "pending",
    "progress": 0,
    "downloadUrl": "/api/download/job_1759060760035_def456",
    "statusUrl": "/api/queue/job/job_1759060760035_def456/status"
}

3. 佇列管理 API

3.1 查看佇列狀態

GET /api/queue/status?jobId=OPTIONAL_JOB_ID

全體狀態

curl http://localhost:3000/api/queue/status

特定任務狀態

curl http://localhost:3000/api/queue/status?jobId=job_1759060760034_abc123

3.2 任務詳細狀態

GET /api/queue/job/{jobId}/status
curl http://localhost:3000/api/queue/job/job_1759060760034_abc123/status

3.3 下載完成的翻譯

GET /api/download/{jobId}
curl -O http://localhost:3000/api/download/job_1759060760034_abc123

3.4 取消任務

DELETE /api/queue/job/{jobId}
curl -X DELETE http://localhost:3000/api/queue/job/job_1759060760034_abc123

3.5 重試失敗任務

POST /api/queue/job/{jobId}/retry
curl -X POST http://localhost:3000/api/queue/job/job_1759060760034_abc123/retry

3.6 任務列表查詢

GET /api/queue/jobs

查詢參數

  • status: 任務狀態過濾 (pending, queued, processing, completed, failed, cancelled)
  • limit: 每頁數量 (預設: 20)
  • offset: 偏移量 (預設: 0)
  • sortBy: 排序欄位 (預設: createdAt)
  • sortOrder: 排序順序 desc/asc (預設: desc)

基本查詢

curl http://localhost:3000/api/queue/jobs

進階查詢

# 查看已完成的任務
curl "http://localhost:3000/api/queue/jobs?status=completed&limit=10"

# 按完成時間排序
curl "http://localhost:3000/api/queue/jobs?sortBy=completedAt&sortOrder=asc"

# 分頁查詢
curl "http://localhost:3000/api/queue/jobs?limit=5&offset=10"

響應格式

{
  "success": true,
  "jobs": [{
    "id": "job_1759140329164_ibq3y8awy",
    "status": "completed",
    "progress": 100,
    "priority": "normal",
    "videoId": "peUO_55ck4o",
    "videoUrl": "https://www.youtube.com/watch?v=peUO_55ck4o",
    "sourceLang": "en",
    "targetLang": "zh-TW",
    "translationModel": "gpt-4o",
    "createdAt": "2025-09-29T10:05:29.165Z",
    "startedAt": "2025-09-29T10:05:29.428Z",
    "completedAt": "2025-09-29T10:05:36.226Z",
    "processTime": 6799,
    "tokenUsage": {
      "totalTokens": 563,
      "estimatedCost": 0.006
    },
    "error": null,
    "workerId": "worker_1759140291405_d22bl"
  }],
  "pagination": {
    "total": 1,
    "limit": 20,
    "offset": 0,
    "hasMore": false
  },
  "filters": {
    "status": "completed",
    "sortBy": "createdAt",
    "sortOrder": "desc"
  }
}

4. 系統管理 API

4.1 調整線程數

PUT /api/queue/config/threads
curl -X PUT http://localhost:3000/api/queue/config/threads \
  -H "Content-Type: application/json" \
  -d '{"count": 4}'

4.2 工作線程統計

GET /api/queue/workers
curl http://localhost:3000/api/queue/workers

4.3 健康檢查

GET /api/queue/health
curl http://localhost:3000/api/queue/health

4.4 暫停/恢復工作線程

POST /api/queue/workers/{workerId}/pause
POST /api/queue/workers/{workerId}/resume

任務狀態說明

狀態值

  • pending: 任務已創建,等待處理
  • queued: 任務已加入佇列
  • processing: 正在翻譯中
  • completed: 翻譯完成
  • failed: 翻譯失敗
  • cancelled: 任務被取消

優先級

  • urgent: 緊急 (最高優先級)
  • high: 高優先級
  • normal: 普通優先級 (預設)
  • low: 低優先級

支援的語言代碼

常用語言

  • en: 英語
  • zh: 中文 (簡體)
  • zh-TW: 繁體中文
  • ja: 日語
  • ko: 韓語
  • es: 西班牙語
  • fr: 法語
  • de: 德語
  • it: 義大利語
  • pt: 葡萄牙語

支援的翻譯模型

OpenAI 模型

  • gpt-4o: GPT-4 Omni (推薦,平衡速度和品質)
  • gpt-4: GPT-4 (最高品質)
  • gpt-3.5-turbo: GPT-3.5 Turbo (最快速度)
  • gpt-4o-mini: GPT-4 Omni Mini (經濟選擇)

新增模型

  • gpt-4.1-mini: GPT-4.1 Mini
  • gpt-5-mini: GPT-5 Mini (實驗性)
  • gpt-5-nano: GPT-5 Nano (實驗性)
  • o1: O1 模型 (實驗性)

前端客戶端開發範例

JavaScript 範例

// 提交YouTube翻譯任務
async function translateYouTube(videoUrl, sourceLang, targetLang) {
    try {
        const response = await fetch('/api/youtube-to-srt-translate', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                videoUrl,
                lang: sourceLang,
                targetLang,
                translationModel: 'gpt-4o'
            })
        });

        const result = await response.json();

        if (result.success) {
            // 開始輪詢任務狀態
            pollJobStatus(result.jobId);
        } else {
            console.error('任務提交失敗:', result.error);
        }
    } catch (error) {
        console.error('請求失敗:', error);
    }
}

// 輪詢任務狀態
async function pollJobStatus(jobId) {
    const maxAttempts = 100; // 最多輪詢100次
    let attempts = 0;

    const poll = async () => {
        try {
            const response = await fetch(`/api/queue/job/${jobId}/status`);
            const status = await response.json();

            // 更新UI進度
            updateProgress(status.progress, status.status);

            if (status.status === 'completed') {
                // 下載完成的檔案
                window.location.href = `/api/download/${jobId}`;
            } else if (status.status === 'failed') {
                console.error('翻譯失敗:', status.error);
            } else if (status.status === 'processing' || status.status === 'queued') {
                // 如果還在處理中,繼續輪詢
                attempts++;
                if (attempts < maxAttempts) {
                    setTimeout(poll, 2000); // 每2秒檢查一次
                }
            }
        } catch (error) {
            console.error('狀態查詢失敗:', error);
        }
    };

    poll();
}

// 更新UI進度
function updateProgress(progress, status) {
    const progressBar = document.getElementById('progress');
    const statusText = document.getElementById('status');

    progressBar.style.width = progress + '%';
    statusText.textContent = `狀態: ${status} (${progress}%)`;
}

Python 範例

import requests
import time
import json

class TranslationClient:
    def __init__(self, base_url="http://localhost:3000"):
        self.base_url = base_url

    def translate_youtube(self, video_url, source_lang, target_lang, model="gpt-4o"):
        """提交YouTube翻譯任務"""
        response = requests.post(
            f"{self.base_url}/api/youtube-to-srt-translate",
            json={
                "videoUrl": video_url,
                "lang": source_lang,
                "targetLang": target_lang,
                "translationModel": model
            }
        )
        return response.json()

    def get_job_status(self, job_id):
        """查詢任務狀態"""
        response = requests.get(f"{self.base_url}/api/queue/job/{job_id}/status")
        return response.json()

    def wait_for_completion(self, job_id, check_interval=5):
        """等待任務完成"""
        while True:
            status = self.get_job_status(job_id)
            print(f"任務狀態: {status['status']}, 進度: {status['progress']}%")

            if status['status'] == 'completed':
                return status
            elif status['status'] == 'failed':
                raise Exception(f"翻譯失敗: {status.get('error', '未知錯誤')}")

            time.sleep(check_interval)

    def download_result(self, job_id, output_file):
        """下載翻譯結果"""
        response = requests.get(f"{self.base_url}/api/download/{job_id}")

        with open(output_file, 'wb') as f:
            f.write(response.content)

# 使用範例
client = TranslationClient()

# 提交翻譯任務
result = client.translate_youtube(
    "https://www.youtube.com/watch?v=peUO_55ck4o",
    "en",
    "zh-TW"
)

if result.get('success'):
    job_id = result['jobId']
    print(f"任務已提交: {job_id}")

    # 等待完成
    final_status = client.wait_for_completion(job_id)

    # 下載結果
    client.download_result(job_id, f"{job_id}.srt")
    print("翻譯完成並已下載!")

錯誤處理

常見錯誤碼

  • 400: 請求參數錯誤
  • 404: 任務或資源不存在
  • 429: 佇列已滿或請求過於頻繁
  • 500: 服務器內部錯誤

錯誤響應格式

{
    "error": "錯誤描述",
    "details": "詳細錯誤資訊",
    "code": "ERROR_CODE"
}

常見問題 FAQ

Q: 為什麼我的翻譯任務一直處於 pending 狀態?

A: 檢查以下幾點:

  1. 確認OPENAI_API_KEY是否正確設定
  2. 檢查工作線程是否正常運行 (GET /api/queue/workers)
  3. 查看應用程式日誌是否有錯誤訊息

Q: 如何提高翻譯速度?

A:

  1. 增加THREADS數量(建議不超過6)
  2. 使用更快的模型如 gpt-3.5-turbo
  3. 確保網路連接穩定

Q: 翻譯品質不滿意怎麼辦?

A:

  1. 使用更高品質的模型如 gpt-4
  2. 確認源語言設定正確
  3. 對於專業內容,可能需要人工後期編輯

Q: SSH環境需要cookies.txt檔案嗎?

A: 是的,SSH生產環境下載YouTube字幕需要cookies.txt檔案。本地開發環境不需要。


快速測試命令

測試YouTube翻譯 (推薦測試影片)

curl -X POST http://localhost:3000/api/youtube-to-srt-translate \
  -H "Content-Type: application/json" \
  -d '{
    "videoUrl": "https://www.youtube.com/watch?v=peUO_55ck4o",
    "lang": "en",
    "targetLang": "zh-TW",
    "translationModel": "gpt-4o"
  }'

檢查系統健康狀態

curl http://localhost:3000/api/queue/health

調整線程數 (注意:需要佇列版本)

curl -X PUT http://localhost:3000/api/queue/config/threads \
  -H "Content-Type: application/json" \
  -d '{"count": 3}'

注意事項

  1. 當前版本狀態:

    • 佇列系統已完成開發和測試
    • SSH環境可能仍使用同步版本
    • 本地環境已更新為佇列版本
  2. 環境差異:

    • 本地: 不需要cookies.txt檔案
    • SSH: 需要cookies.txt檔案進行YouTube認證
  3. 效能建議:

    • THREADS設定建議: 1-4 (根據CPU核心數調整)
    • 避免同時提交過多翻譯任務
    • 監控OpenAI API使用額度
  4. 最佳實踐:

    • 使用適當的翻譯模型平衡速度和品質
    • 實作前端進度顯示提升用戶體驗
    • 設置合理的錯誤處理和重試機制

更多技術細節請參考專案README或聯繫開發團隊。

使用 Hugo 建立
主題 StackJimmy 設計