> For the complete documentation index, see [llms.txt](https://docs.clore.ai/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.clore.ai/guides/guides_v2-zh/yin-pin-yu-yu-yin/whisper-transcription.md).

# Whisper Transcription

在 Clore.ai GPU 上使用 OpenAI Whisper 转录音频和视频

在 CLORE.AI GPU 上使用 OpenAI 的 Whisper 转录音频和视频文件。

{% hint style="success" %}
所有示例都可以在通过以下方式租用的 GPU 服务器上运行 [CLORE.AI 市场](https://clore.ai/marketplace).
{% endhint %}

## 服务器要求

| 参数   | 最低       | 推荐              |
| ---- | -------- | --------------- |
| 内存   | 8GB      | 16GB+           |
| 显存   | 4GB（小型）  | 10GB+（large-v3） |
| 网络   | 200Mbps  | 500Mbps+        |
| 启动时间 | 约 1-2 分钟 | -               |

## Whisper 是什么？

OpenAI Whisper 是一个语音识别模型，可以：

* 转录 99 种语言的音频
* 翻译成英语
* 生成时间戳
* 处理嘈杂音频

## 模型大小

| 模型                 | 显存      | 速度                | 质量     | 备注                        |
| ------------------ | ------- | ----------------- | ------ | ------------------------- |
| tiny               | 1GB     | \~32x realtime    | 基础     | 最快，准确率最低                  |
| base               | 1GB     | \~16x realtime    | 好      | 适合快速任务的良好平衡               |
| small              | 2GB     | \~6x realtime     | 更好     | 推荐用于大多数场景                 |
| medium             | 5GB     | \~2x realtime     | 很高     | 高准确率，中等速度                 |
| large-v3           | 10GB    | \~1x realtime     | 最佳     | 最高准确率                     |
| **large-v3-turbo** | **6GB** | **\~8x realtime** | **最佳** | **比 large-v3 快 8 倍，质量相近** |

> **💡 推荐：** 使用 `large-v3-turbo` 以获得最佳速度/质量平衡。其准确率与 `large-v3` 相当，速度快 8 倍，且显存需求更低。

### 使用 large-v3-turbo

```python
import whisper

# 加载 large-v3-turbo（比 large-v3 快 8 倍，质量相近）
model = whisper.load_model("large-v3-turbo", device="cuda")

result = model.transcribe("audio.mp3")
print(result["text"])
```

使用 Faster-Whisper：

```python
from faster_whisper import WhisperModel

# 通过 faster-whisper 使用 large-v3-turbo
model = WhisperModel("deepdml/faster-whisper-large-v3-turbo-ct2", device="cuda", compute_type="float16")
segments, info = model.transcribe("audio.mp3")

for segment in segments:
    print(f"[{segment.start:.2f}s -> {segment.end:.2f}s] {segment.text}")
```

***

## WhisperX：增强替代方案

用于 **词级时间戳**, **说话人分离**，以及 **最高快 70 倍** 处理，请考虑使用 [WhisperX](/guides/guides_v2-zh/yin-pin-yu-yu-yin/whisperx.md):

```bash
pip install whisperx
```

```python
import whisperx

model = whisperx.load_model("large-v3-turbo", device="cuda", compute_type="float16")
audio = whisperx.load_audio("audio.mp3")
result = model.transcribe(audio, batch_size=16)

# 词级对齐
model_a, metadata = whisperx.load_align_model(language_code=result["language"], device="cuda")
result = whisperx.align(result["segments"], model_a, metadata, audio, device="cuda")

# result["word_segments"] 包含词级时间戳
```

➡️ 查看完整 [WhisperX 指南](/guides/guides_v2-zh/yin-pin-yu-yu-yin/whisperx.md) 以了解说话人分离和高级功能。

## 快速部署（推荐）

使用预构建的 Faster-Whisper 服务器即可立即部署：

**Docker 镜像：**

```
fedirz/faster-whisper-server:latest-cuda
```

**端口：**

```
22/tcp
8000/http
```

**无需命令** - 服务器会自动启动。

### 验证是否正常工作

部署后，找到你的 `http_pub` URL 在 **我的订单** 并测试：

```bash
curl https://your-http-pub.clorecloud.net/

# 预期：服务器信息 JSON 响应
```

{% hint style="warning" %}
如果收到 HTTP 502，请等待 1-2 分钟——服务仍在启动中。
{% endhint %}

### 通过 API 转录

```bash
# 转录音频文件
curl -X POST https://your-http-pub.clorecloud.net/v1/audio/transcriptions \
  -F "file=@audio.mp3" \
  -F "model=Systran/faster-whisper-large-v3" \
  -F "response_format=json"

# 带时间戳
curl -X POST https://your-http-pub.clorecloud.net/v1/audio/transcriptions \
  -F "file=@audio.mp3" \
  -F "model=Systran/faster-whisper-large-v3" \
  -F "response_format=verbose_json" \
  -F "timestamp_granularities[]=word"
```

## 完整 API 参考（Faster-Whisper-Server）

### 端点

| 端点                         | 方法   | 描述              |
| -------------------------- | ---- | --------------- |
| `/v1/audio/transcriptions` | POST | 转录音频（兼容 OpenAI） |
| `/v1/audio/translations`   | POST | 将音频翻译成英语        |
| `/v1/models`               | GET  | 列出所有可用模型        |
| `/v1/models/{model_name}`  | GET  | 获取特定模型信息        |
| `/api/ps`                  | GET  | 列出当前已加载的模型      |
| `/api/ps/{model_name}`     | GET  | 检查特定模型是否已加载     |
| `/api/pull/{model_name}`   | POST | 下载并加载模型         |
| `/health`                  | GET  | 健康检查端点          |
| `/docs`                    | GET  | Swagger UI 文档   |
| `/openapi.json`            | GET  | OpenAPI 规范      |

#### 列出可用模型

```bash
curl https://your-http-pub.clorecloud.net/v1/models
```

响应：

```json
{
  "data": [
    {"id": "Systran/faster-whisper-large-v3", "object": "model"},
    {"id": "Systran/faster-whisper-medium", "object": "model"}
  ]
}
```

#### Swagger 文档

在浏览器中打开以进行交互式 API 测试：

```
https://your-http-pub.clorecloud.net/docs
```

### 转录选项

| 参数                          | 类型  | 描述                                            |
| --------------------------- | --- | --------------------------------------------- |
| `file`                      | 文件  | 要转录的音频文件                                      |
| `model`                     | 字符串 | 要使用的模型（默认： `Systran/faster-whisper-large-v3`) |
| `language`                  | 字符串 | 强制指定语言（例如， `en`, `ja`, `ru`)                  |
| `response_format`           | 字符串 | `json`, `text`, `srt`, `vtt`, `verbose_json`  |
| `temperature`               | 浮点数 | 采样温度（0.0-1.0）                                 |
| `timestamp_granularities[]` | 数组  | `word` 或 `segment` 用于时间戳                      |

#### 响应格式

**JSON（默认）：**

```json
{"text": "转录文本在此..."}
```

**详细 JSON：**

```json
{
  "text": "完整转录...",
  "segments": [
    {"start": 0.0, "end": 2.5, "text": "第一段"},
    {"start": 2.5, "end": 5.0, "text": "第二段"}
  ],
  "language": "en"
}
```

**SRT：**

```
1
00:00:00,000 --> 00:00:02,500
第一段

2
00:00:02,500 --> 00:00:05,000
第二段
```

## 替代方案：手动安装

如果你需要更多控制，可使用手动安装部署：

**Docker 镜像：**

```
pytorch/pytorch:2.11.0-cuda12.8-cudnn9-runtime
```

**端口：**

```
22/tcp
```

**命令：**

```bash
pip install openai-whisper faster-whisper
```

{% hint style="info" %}
手动安装需要 3-5 分钟。上面的预构建镜像更适合更快启动。
{% endhint %}

## 基本用法（SSH）

```bash
ssh -p <port> root@<proxy>

# 转录音频文件
whisper audio.mp3 --model large-v3 --device cuda

# 输出为特定格式
whisper audio.mp3 --model large-v3 --output_format txt

# 指定语言
whisper audio.mp3 --model large-v3 --language 日语
```

### 带时间戳转录

```bash
whisper audio.mp3 --model large-v3 --word_timestamps True
```

## 上传音频文件

```bash
# 上传单个文件
scp -P <port> interview.mp3 root@<proxy>:/workspace/

# 上传文件夹
scp -P <port> -r ./audio_files/ root@<proxy>:/workspace/
```

## Python API

```python
import whisper

# 加载模型（首次使用时会下载）
model = whisper.load_model("large-v3", device="cuda")

# 转录
result = model.transcribe("audio.mp3")

# 打印文本
print(result["text"])

# 打印时间戳
for segment in result["segments"]:
    print(f"[{segment['start']:.2f}s -> {segment['end']:.2f}s] {segment['text']}")
```

## Faster-Whisper（推荐）

Faster-Whisper 速度快 4 倍，显存占用更低：

```bash
pip install faster-whisper
```

```python
from faster_whisper import WhisperModel

# 以优化方式加载模型
model = WhisperModel("large-v3", device="cuda", compute_type="float16")

# 转录
segments, info = model.transcribe("audio.mp3")

print(f"检测到的语言：{info.language}")
for segment in segments:
    print(f"[{segment.start:.2f}s -> {segment.end:.2f}s] {segment.text}")
```

## 语言选项

```python
from faster_whisper import WhisperModel

model = WhisperModel("large-v3", device="cuda")

# 自动检测语言
segments, info = model.transcribe("audio.mp3")
print(f"语言：{info.language}（{info.language_probability:.0%}）")

# 强制指定语言
segments, _ = model.transcribe("audio.mp3", language="ja")
```

## 翻译成英语

```python
from faster_whisper import WhisperModel

model = WhisperModel("large-v3", device="cuda")
segments, _ = model.transcribe("japanese.mp3", task="translate")

for segment in segments:
    print(segment.text)
```

命令行：

```bash
whisper japanese.mp3 --model large-v3 --task translate
```

## 字幕生成

### SRT 格式

```python
from faster_whisper import WhisperModel

def format_timestamp(seconds):
    hours = int(seconds // 3600)
    minutes = int((seconds % 3600) // 60)
    secs = int(seconds % 60)
    millis = int((seconds - int(seconds)) * 1000)
    return f"{hours:02d}:{minutes:02d}:{secs:02d},{millis:03d}"

model = WhisperModel("large-v3", device="cuda")
segments, _ = model.transcribe("video.mp4")

with open("subtitles.srt", "w") as f:
    for i, segment in enumerate(segments, 1):
        f.write(f"{i}\n")
        f.write(f"{format_timestamp(segment.start)} --> {format_timestamp(segment.end)}\n")
        f.write(f"{segment.text.strip()}\n\n")
```

### VTT 格式

```bash
whisper video.mp4 --model large-v3 --output_format vtt
```

## 词级时间戳

```python
from faster_whisper import WhisperModel

model = WhisperModel("large-v3", device="cuda")

segments, _ = model.transcribe("audio.mp3", word_timestamps=True)

for segment in segments:
    for word in segment.words:
        print(f"[{word.start:.2f}s] {word.word}")
```

## 说话人分离

谁说了什么（需要 pyannote）：

```bash
pip install pyannote.audio
```

```python
from faster_whisper import WhisperModel
from pyannote.audio import Pipeline

# 说话人分离
diarization = Pipeline.from_pretrained(
    "pyannote/speaker-diarization-3.1",
    use_auth_token="YOUR_HF_TOKEN"
)
diarization_result = diarization("audio.mp3")

# 转录
whisper = WhisperModel("large-v3", device="cuda")
segments, _ = whisper.transcribe("audio.mp3")

# 合并
for segment in segments:
    # 在片段时间查找说话人
    speaker = None
    for turn, _, spk in diarization_result.itertracks(yield_label=True):
        if turn.start <= segment.start <= turn.end:
            speaker = spk
            break
    print(f"[{speaker}] {segment.text}")
```

## REST API 服务器

创建一个转录 API：

```python
from fastapi import FastAPI, UploadFile
from faster_whisper import WhisperModel
import tempfile

app = FastAPI()
model = WhisperModel("large-v3", device="cuda", compute_type="float16")

@app.post("/transcribe")
async def transcribe(file: UploadFile):
    with tempfile.NamedTemporaryFile(delete=False) as tmp:
        tmp.write(await file.read())
        tmp_path = tmp.name

    segments, info = model.transcribe(tmp_path)

    return {
        "language": info.language,
        "text": " ".join([s.text for s in segments]),
        "segments": [
            {"start": s.start, "end": s.end, "text": s.text}
            for s in segments
        ]
    }

# 运行：uvicorn server:app --host 0.0.0.0 --port 8000
```

## 性能基准

| 模型       | GPU      | 1 小时音频 |
| -------- | -------- | ------ |
| large-v3 | RTX 3090 | \~5 分钟 |
| large-v3 | RTX 4090 | \~3 分钟 |
| large-v3 | A100     | \~2 分钟 |
| medium   | RTX 3090 | \~2 分钟 |

## 内存高效处理

对于非常长的音频：

```python
from faster_whisper import WhisperModel

model = WhisperModel("large-v3", device="cuda", compute_type="int8")

# 分块处理
segments, _ = model.transcribe(
    "long_audio.mp3",
    vad_filter=True,  # 跳过静音
    vad_parameters=dict(min_silence_duration_ms=500)
)
```

## 下载结果

```bash
# 下载转录文本
scp -P <port> -r root@<proxy>:/workspace/transcripts/ ./

# 下载字幕
scp -P <port> root@<proxy>:/workspace/subtitles.srt ./
```

## 故障排查

{% hint style="danger" %}
**CUDA 内存不足**
{% endhint %}

* 使用更小的模型（medium 而不是 large）
* 使用 `compute_type="int8"` 用于 faster-whisper
* 处理更短的音频片段

### http\_pub URL 上出现 HTTP 502

服务仍在启动中。等待 1-2 分钟后重试：

```bash
curl https://your-http-pub.clorecloud.net/
```

### 准确率差

* 使用更大的模型
* 指定语言： `--language English`
* 为 faster-whisper 增大 beam\_size

### 处理缓慢

* 确保使用 GPU： `nvidia-smi`
* 使用 faster-whisper 而不是原版
* 启用 VAD 以跳过静音

## 成本估算

CLORE.AI 市场的典型费率：

| GPU      | 显存   | 每日价格       | 适合用于        |
| -------- | ---- | ---------- | ----------- |
| RTX 3060 | 12GB | $0.15–0.30 | 小型/中型模型     |
| RTX 3090 | 24GB | $0.30–1.00 | large-v3    |
| RTX 4090 | 24GB | $0.50–2.00 | large-v3，快速 |
| A100     | 40GB | $1.50–3.00 | 批处理         |

*价格以美元/天计。费率因提供商而异——请查看* [*CLORE.AI 市场*](https://clore.ai/marketplace) *以获取当前费率。*


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.clore.ai/guides/guides_v2-zh/yin-pin-yu-yu-yin/whisper-transcription.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
