# Audio and Video Transcription

> 使用 faster-whisper（基于 CTranslate2 的 Whisper）对音频和视频流进行自动语音识别。

Source: https://docs.sommatic.ai/zh/nodes/ai.transcribe/

- 标识: `ai.transcribe`
- 类别: AI
- 版本: 1.0.0
- 状态: 可用
- 执行方式: async

使用 faster-whisper（基于 CTranslate2 的 Whisper）对音频和视频流进行自动语音识别。

在 CPU 上单轮解码，可配置模型大小、束宽和语言提示。适合对会议、语音留言和短视频做实用级转写。如需说话人分离、100 多种语言区域或自定义词表，请使用 `connectors.microsoft.azure.speech`。

**功能特性：**
- **模型选择：** `tiny`、`base`（默认）或 `small`。模型越大越准确，但延迟和内存占用也越高。
- **束搜索：** 可配置束宽；beam > 1 可提升嘈杂输入的转写质量，代价呈线性增长。
- **语言：** ISO 639-1 提示（`es`、`en`、`pt` 等），或根据音频前 30 秒自动检测。
- **词级时间戳：** 可选的逐片段时间戳，用于生成字幕、划分章节或定位证据。
- **输入格式：** mp3、wav、m4a、ogg、flac、mp4、mov、webm。容器解复用以及重采样为 16 kHz PCM 均通过 ffmpeg 在内部完成。
- **静音输入处理：** 语音活动检测（VAD）在流中未发现语音时，触发 `empty` 端口。

## 配置

- `model_size` (string, 可选): 适合 CPU 的模型大小。越大所需内存和时间越多。 默认值: `base`. 可选值: `tiny`, `base`, `small`.
- `language` (string, 可选): 语言提示（例如 es、en、pt）。留空则自动检测。
- `word_timestamps` (boolean, 可选): 在输出中给出逐片段时间戳。 默认值: `false`.
- `beam_size` (number, 可选): 值越高质量越好，但速度越慢。 默认值: `1`.

配置中会显示通用执行设置，但该节点目前不执行重试（`retryOnFail`、`maxTries`）。所有节点均未实现 `continueOnFail`。

## 输出端口

- `extracted` (默认): Transcribed
- `empty`: No Speech
- `error`: Error

## 输入契约

- `content_base64` (string, 可选): 以 base64 编码的音频/视频内容。
- `file_path` (string, 可选): 替代方式：本地文件路径。

## 输出契约

- `text` (string, 可选): 完整的转写文本。
- `chars` (number, 可选)
- `empty` (boolean, 可选)
- `method` (string, 可选)
- `metadata` (object, 可选)
- `segments` (array, 可选)

## 在表达式中

后续节点可通过 `$("Audio and Video Transcription").item.json.<路径>` 读取此节点输出中的内容（请把 `Audio and Video Transcription` 换成你的节点标签）。**Editor** 标记工作流编辑器在 Previous Nodes 中提示的路径（输出契约）；**Worker** 标记 worker 实际通过 `extracted` 返回的路径，依据“端口”一节所示的输出。

- `$("Audio and Video Transcription").item.json.text` (string) = `"Hello, this is a reminder about tomorrow’s d…"`: 完整的转写文本。
- `$("Audio and Video Transcription").item.json.chars` (number) = `59`
- `$("Audio and Video Transcription").item.json.empty` (boolean) = `false`
- `$("Audio and Video Transcription").item.json.method` (string) = `"faster-whisper-base"`
- `$("Audio and Video Transcription").item.json.metadata` (object) = `{…}`
- `$("Audio and Video Transcription").item.json.segments` (array) = `[…] (1)`
- `$("Audio and Video Transcription").item.json.metadata.language` (string) = `"en"` (编辑器不提示)
- `$("Audio and Video Transcription").item.json.metadata.language_probability` (number) = `0.98` (编辑器不提示)
- `$("Audio and Video Transcription").item.json.metadata.duration_seconds` (number) = `4.2` (编辑器不提示)
- `$("Audio and Video Transcription").item.json.metadata.segments_count` (number) = `1` (编辑器不提示)


## 工作原理

使用 faster-whisper（int8）在 CPU 上转写音频或视频，返回完整文本、检测到的语言，并在开启 `word_timestamps` 时返回带时间戳的片段。

1. 解析节点配置：配置键中的表达式会基于本次运行求值；传入条目按原样使用。
2. 先从配置、再从传入条目读取 `content_base64` 或 `file_path`。两者都没有时返回 `error`。
3. 在 Python 中，存在的 `file_path` 会被直接使用；否则将 base64 字节写入临时文件。
4. 加载 Whisper 模型 `model_size`（默认 `base`），并使用 `language`（为空则自动检测）、`beam_size`（默认 1）和 `word_timestamps` 进行转写。
5. 用空格将各片段文本拼接为 `text`。仅当 `word_timestamps` 为 `true` 时才填充 `segments`。
6. Python 失败返回 `error`；转写结果为空返回 `empty`；其余返回 `extracted`。

## 在工作流中

### 节点

```json
{
  "node_id": "node-transcribe",
  "label": "Transcribe voicemail",
  "operator_slug": "ai.transcribe",
  "operator_version": "1.0.0",
  "config": {
    "model_size": "base",
    "language": "en",
    "word_timestamps": true,
    "beam_size": 1,
    "execution": {
      "timeout_ms": 900000
    }
  }
}
```

### Envelope

```json
{
  "ok": true,
  "port": "extracted",
  "data": {
    "text": "Hello, this is a reminder about tomorrow’s delivery window.",
    "chars": 59,
    "empty": false,
    "method": "faster-whisper-base",
    "metadata": {
      "language": "en",
      "language_probability": 0.98,
      "duration_seconds": 4.2,
      "segments_count": 1
    },
    "segments": [
      {
        "start": 0,
        "end": 4.1,
        "text": "Hello, this is a reminder about tomorrow’s delivery window."
      }
    ]
  }
}
```

## 输出端口 (代码中的行为)

### `extracted`

转写结果包含文本。

```json
{
  "text": "Hello, this is a reminder about tomorrow’s delivery window.",
  "chars": 59,
  "empty": false,
  "method": "faster-whisper-base",
  "metadata": {
    "language": "en",
    "language_probability": 0.98,
    "duration_seconds": 4.2,
    "segments_count": 1
  },
  "segments": [
    {
      "start": 0,
      "end": 4.1,
      "text": "Hello, this is a reminder about tomorrow’s delivery window."
    }
  ]
}
```

### `empty`

模型未返回任何文本（静音或无语音）。结构相同，`text: ""`。

```json
{
  "text": "",
  "chars": 0,
  "empty": true,
  "method": "faster-whisper-base",
  "metadata": {
    "language": "en",
    "language_probability": 0.41,
    "duration_seconds": 12,
    "segments_count": 0
  },
  "segments": []
}
```

### `error`

缺少输入或脚本失败。`data` 为 `{ error }` 或 `{ error, stderr }`。

```json
{
  "error": "Python timed out after 900000ms",
  "stderr": ""
}
```

## 代码中的行为

- `word_timestamps`: 为 `true` 时，`segments` 按片段列出 `{ start, end, text }`（单位：秒），不返回逐词时间。为 `false` 时 `segments` 为 `[]`。
- `language`: ISO 639-1 语言提示。留空则自动检测；检测到的代码位于 `metadata.language`。
- `execution.timeout_ms`: Python 运行的超时时间。未设置时代码使用 900000 毫秒（15 分钟）；schema 显示为 300000。
- `content_base64 / file_path`: 它们未在配置 schema 中声明，但会先于传入条目从配置读取。可用表达式指向文件，例如 `{{ $json.attachment.content_base64 }}`。

## 错误

| 消息 | 端口 | 原因与处理 |
| --- | --- | --- |
| `Either content_base64 or file_path is required.` | `error` | 配置和传入条目中都没有 `content_base64` 或 `file_path`。请从上一个节点映射文件。 |
| `Either content_base64 or file_path is required` | `error` | 当 `file_path` 在编排器主机上不存在时由 Python 脚本抛出。数据中还包含 `stderr`。 |
| `<faster-whisper or decoder error>` | `error` | 文件无法解码为音频或视频，或主机上无法加载模型。 |
| `Python timed out after <timeout_ms>ms` | `error` | 脚本超过了 `execution.timeout_ms`。请调大该值或减少处理的页数。 |
| `Python runtime not available (ENOENT)` | `error` | 编排器主机上没有可用的 Python 解释器。 |

## 说明与限制

- 每次运行都是新的 Python 进程，因此每次都会加载模型；更大的 `model_size` 会增加内存占用和启动时间。
- 未配置语音活动检测过滤：`empty` 表示模型没有产生文本，而不是 VAD 步骤检测到静音。
- 不支持说话人分离，也不支持自定义词表。
- `file_path` 是编排器主机上的路径。两者同时存在时以 `content_base64` 为准。
- 提取在 Python 子进程中运行。首次使用时，编排器会创建虚拟环境并安装固定版本的依赖，可能需要数分钟；之后的运行会复用该环境。
- Python 结果的输出上限为 50 MB；超过后节点从 `error` 端口输出。
- 引擎不会对此节点应用 `execution.retryOnFail`、`maxTries`、`waitBetweenTries` 或 `continueOnFail`。请通过连接 `error` 端口处理失败。


## 契约（JSON Schema）

### All (`*.definition.js`)

```json
{
  "slug": "ai.transcribe",
  "name": "Audio and Video Transcription",
  "category": "ai",
  "version": "1.0.0",
  "description": "Automatic Speech Recognition over audio and video streams using faster-whisper (CTranslate2-backed Whisper).\n\n  Single-pass decoding on CPU with configurable model size, beam width, and language hint. Suitable for utility-grade transcription of meetings, voicemails, and short-form media. For speaker diarization, 100+ locales, or custom vocabulary, use `connectors.microsoft.azure.speech`.\n\n  **Features:**\n  - **Model selection:** `tiny`, `base` (default), or `small`. Larger models increase accuracy at the cost of latency and memory.\n  - **Beam search:** Configurable beam size; beam > 1 improves transcription quality on noisy input at a linear cost.\n  - **Language:** ISO 639-1 hint (`es`, `en`, `pt`, ...) or auto-detection from the first 30 seconds of audio.\n  - **Word timestamps:** Optional per-segment timestamps for subtitle generation, chaptering, or evidence anchoring.\n  - **Input formats:** mp3, wav, m4a, ogg, flac, mp4, mov, webm. Container demuxing and PCM resampling to 16 kHz handled internally via ffmpeg.\n  - **Silent input handling:** Emits port `empty` when Voice Activity Detection finds no speech in the stream.",
  "capabilities": [
    "asr",
    "speech-to-text",
    "audio",
    "video",
    "transcription"
  ],
  "config_schema": {
    "type": "object",
    "properties": {
      "model_size": {
        "type": "string",
        "title": "Whisper Model Size",
        "enum": [
          "tiny",
          "base",
          "small"
        ],
        "default": "base",
        "description": "CPU-friendly model sizes. Larger requires more memory and time."
      },
      "language": {
        "type": "string",
        "title": "Language (ISO 639-1)",
        "description": "Language hint (e.g., es, en, pt). Leave empty to auto-detect."
      },
      "word_timestamps": {
        "type": "boolean",
        "title": "Word Timestamps",
        "default": false,
        "description": "Emit per-segment timestamps in the output."
      },
      "beam_size": {
        "type": "number",
        "title": "Beam Size",
        "default": 1,
        "description": "Higher values improve quality at the cost of speed."
      },
      "execution": {
        "type": "object",
        "title": "Execution Settings",
        "properties": {
          "alwaysOutputData": {
            "type": "boolean",
            "title": "Always Output Data",
            "description": "Always output data, even on error (if configured).",
            "default": false
          },
          "retryOnFail": {
            "type": "boolean",
            "title": "Retry On Fail",
            "description": "Retry the execution if it fails.",
            "default": false
          },
          "maxTries": {
            "type": "integer",
            "title": "Max Retries",
            "description": "Number of retries.",
            "default": 3,
            "displayOptions": {
              "show": {
                "retryOnFail": [
                  true
                ]
              }
            }
          },
          "waitBetweenTries": {
            "type": "integer",
            "title": "Wait Between Retries (ms)",
            "default": 1000,
            "displayOptions": {
              "show": {
                "retryOnFail": [
                  true
                ]
              }
            }
          },
          "continueOnFail": {
            "type": "boolean",
            "title": "Continue On Fail",
            "description": "Do not crash workflow on error.",
            "default": false
          },
          "timeout_ms": {
            "type": "integer",
            "title": "Timeout (ms)",
            "description": "Max execution time for this node before it is killed, in milliseconds. Honored by long-running operators (e.g. OCR/extraction, inline code). Default 300000 (5 min).",
            "default": 300000
          }
        }
      }
    }
  },
  "input_contract_schema": {
    "type": "object",
    "properties": {
      "content_base64": {
        "type": "string",
        "description": "Audio/video content base64-encoded."
      },
      "file_path": {
        "type": "string",
        "description": "Alternative: local file path."
      }
    }
  },
  "output_contract_schema": {
    "type": "object",
    "properties": {
      "text": {
        "type": "string",
        "description": "Full transcribed text."
      },
      "chars": {
        "type": "number"
      },
      "empty": {
        "type": "boolean"
      },
      "method": {
        "type": "string"
      },
      "metadata": {
        "type": "object"
      },
      "segments": {
        "type": "array"
      }
    }
  },
  "ports": [
    {
      "port_id": "extracted",
      "label": "Transcribed",
      "is_default": true,
      "supports_condition": true
    },
    {
      "port_id": "empty",
      "label": "No Speech",
      "is_default": false,
      "supports_condition": true
    },
    {
      "port_id": "error",
      "label": "Error",
      "is_default": false,
      "supports_condition": false
    }
  ],
  "execution_mode": "async",
  "tags": [
    "ai",
    "asr",
    "audio",
    "video",
    "whisper",
    "transcription"
  ],
  "is_stateful": false,
  "publisher": {
    "identity": "org_sommatic_ai",
    "profile": {
      "name": "Sommatic AI",
      "verified": true,
      "url": "https://me.veripass.com/sommatic",
      "logo_url": null
    }
  }
}
```

### config_schema

```json
{
  "type": "object",
  "properties": {
    "model_size": {
      "type": "string",
      "title": "Whisper Model Size",
      "enum": [
        "tiny",
        "base",
        "small"
      ],
      "default": "base",
      "description": "CPU-friendly model sizes. Larger requires more memory and time."
    },
    "language": {
      "type": "string",
      "title": "Language (ISO 639-1)",
      "description": "Language hint (e.g., es, en, pt). Leave empty to auto-detect."
    },
    "word_timestamps": {
      "type": "boolean",
      "title": "Word Timestamps",
      "default": false,
      "description": "Emit per-segment timestamps in the output."
    },
    "beam_size": {
      "type": "number",
      "title": "Beam Size",
      "default": 1,
      "description": "Higher values improve quality at the cost of speed."
    },
    "execution": {
      "type": "object",
      "title": "Execution Settings",
      "properties": {
        "alwaysOutputData": {
          "type": "boolean",
          "title": "Always Output Data",
          "description": "Always output data, even on error (if configured).",
          "default": false
        },
        "retryOnFail": {
          "type": "boolean",
          "title": "Retry On Fail",
          "description": "Retry the execution if it fails.",
          "default": false
        },
        "maxTries": {
          "type": "integer",
          "title": "Max Retries",
          "description": "Number of retries.",
          "default": 3,
          "displayOptions": {
            "show": {
              "retryOnFail": [
                true
              ]
            }
          }
        },
        "waitBetweenTries": {
          "type": "integer",
          "title": "Wait Between Retries (ms)",
          "default": 1000,
          "displayOptions": {
            "show": {
              "retryOnFail": [
                true
              ]
            }
          }
        },
        "continueOnFail": {
          "type": "boolean",
          "title": "Continue On Fail",
          "description": "Do not crash workflow on error.",
          "default": false
        },
        "timeout_ms": {
          "type": "integer",
          "title": "Timeout (ms)",
          "description": "Max execution time for this node before it is killed, in milliseconds. Honored by long-running operators (e.g. OCR/extraction, inline code). Default 300000 (5 min).",
          "default": 300000
        }
      }
    }
  }
}
```

### input_contract_schema

```json
{
  "type": "object",
  "properties": {
    "content_base64": {
      "type": "string",
      "description": "Audio/video content base64-encoded."
    },
    "file_path": {
      "type": "string",
      "description": "Alternative: local file path."
    }
  }
}
```

### output_contract_schema

```json
{
  "type": "object",
  "properties": {
    "text": {
      "type": "string",
      "description": "Full transcribed text."
    },
    "chars": {
      "type": "number"
    },
    "empty": {
      "type": "boolean"
    },
    "method": {
      "type": "string"
    },
    "metadata": {
      "type": "object"
    },
    "segments": {
      "type": "array"
    }
  }
}
```

### ports

```json
[
  {
    "port_id": "extracted",
    "label": "Transcribed",
    "is_default": true,
    "supports_condition": true
  },
  {
    "port_id": "empty",
    "label": "No Speech",
    "is_default": false,
    "supports_condition": true
  },
  {
    "port_id": "error",
    "label": "Error",
    "is_default": false,
    "supports_condition": false
  }
]
```
