# Audio and Video Transcription

> Reconocimiento automático de voz sobre flujos de audio y video con faster-whisper (Whisper sobre CTranslate2).

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

- Slug: `ai.transcribe`
- Familia: IA
- Versión: 1.0.0
- Estado: Disponible
- Ejecución: async

Reconocimiento automático de voz sobre flujos de audio y video con faster-whisper (Whisper sobre CTranslate2).

Decodificación en una sola pasada en CPU, con tamaño de modelo, ancho de beam y pista de idioma configurables. Adecuado para transcripciones de uso general de reuniones, mensajes de voz y contenido multimedia breve. Para diarización de hablantes, más de 100 configuraciones regionales o vocabulario personalizado, usa `connectors.microsoft.azure.speech`.

**Características:**
- **Selección del modelo:** `tiny`, `base` (predeterminado) o `small`. Los modelos más grandes aumentan la precisión a costa de la latencia y la memoria.
- **Beam search:** Tamaño de beam configurable; un beam > 1 mejora la calidad de la transcripción con entradas ruidosas, con un costo lineal.
- **Idioma:** Pista ISO 639-1 (`es`, `en`, `pt`, ...) o detección automática a partir de los primeros 30 segundos de audio.
- **Marcas de tiempo:** Marcas de tiempo opcionales por segmento para generar subtítulos, capítulos o anclar evidencias.
- **Formatos de entrada:** mp3, wav, m4a, ogg, flac, mp4, mov, webm. El demultiplexado del contenedor y el remuestreo PCM a 16 kHz se hacen internamente con ffmpeg.
- **Entrada sin voz:** Emite el puerto `empty` cuando la detección de actividad de voz no encuentra habla en el flujo.

## Configuración

- `model_size` (string, opcional): Tamaños de modelo aptos para CPU. Los más grandes requieren más memoria y tiempo. Por defecto: `base`. Valores permitidos: `tiny`, `base`, `small`.
- `language` (string, opcional): Pista de idioma (p. ej., es, en, pt). Déjala vacía para la detección automática.
- `word_timestamps` (boolean, opcional): Incluye marcas de tiempo por segmento en la salida. Por defecto: `false`.
- `beam_size` (number, opcional): Los valores más altos mejoran la calidad a costa de la velocidad. Por defecto: `1`.

Su configuración muestra los ajustes de ejecución compartidos, pero este nodo aún no aplica reintentos (`retryOnFail`, `maxTries`). Ningún nodo aplica `continueOnFail`.

## Puertos de salida

- `extracted` (por defecto): Transcribed
- `empty`: No Speech
- `error`: Error

## Contrato de entrada

- `content_base64` (string, opcional): Contenido de audio o video codificado en base64.
- `file_path` (string, opcional): Alternativa: ruta de archivo local.

## Contrato de salida

- `text` (string, opcional): Texto transcrito completo.
- `chars` (number, opcional)
- `empty` (boolean, opcional)
- `method` (string, opcional)
- `metadata` (object, opcional)
- `segments` (array, opcional)

## En expresiones

Lo que un nodo posterior puede leer de la salida de este nodo con `$("Audio and Video Transcription").item.json.<ruta>` (escribe la etiqueta de tu nodo en lugar de `Audio and Video Transcription`). **Editor** marca las rutas que sugiere el editor de workflows en Previous Nodes (el contrato de salida); **Worker** marca las rutas que el worker devuelve de verdad por `extracted`, según la salida que muestra Puertos.

- `$("Audio and Video Transcription").item.json.text` (string) = `"Hello, this is a reminder about tomorrow’s d…"`: Texto transcrito completo.
- `$("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"` (El editor no la sugiere)
- `$("Audio and Video Transcription").item.json.metadata.language_probability` (number) = `0.98` (El editor no la sugiere)
- `$("Audio and Video Transcription").item.json.metadata.duration_seconds` (number) = `4.2` (El editor no la sugiere)
- `$("Audio and Video Transcription").item.json.metadata.segments_count` (number) = `1` (El editor no la sugiere)


## Cómo funciona

Transcribe audio o video en CPU con faster-whisper (int8) y devuelve el texto completo, el idioma detectado y, si `word_timestamps` está activo, los segmentos con tiempos.

1. Resuelve la configuración del nodo: las expresiones de las claves de configuración se evalúan contra la ejecución; el ítem entrante se usa tal cual.
2. Lee `content_base64` o `file_path` primero de la configuración y luego del ítem entrante. Si no hay ninguno, devuelve `error`.
3. En Python, un `file_path` existente se usa directamente; si no, los bytes base64 se escriben en un archivo temporal.
4. Carga el modelo Whisper `model_size` (predeterminado `base`) y transcribe con `language` (vacío = detección automática), `beam_size` (predeterminado 1) y `word_timestamps`.
5. Une los textos de los segmentos con espacios en `text`. `segments` solo se llena cuando `word_timestamps` es `true`.
6. Los fallos de Python devuelven `error`; una transcripción vacía devuelve `empty`; lo demás, `extracted`.

## En un workflow

### Nodo

```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."
      }
    ]
  }
}
```

## Puertos de salida (comportamiento en el código)

### `extracted`

La transcripción tiene texto.

```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`

El modelo no devolvió texto (silencio o sin voz). Misma forma con `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`

Falta la entrada o el script falla. `data` es `{ error }` o `{ error, stderr }`.

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

## Comportamiento en el código

- `word_timestamps`: Con `true`, `segments` lista `{ start, end, text }` por segmento, en segundos. No se devuelven tiempos por palabra. Con `false`, `segments` es `[]`.
- `language`: Indicación ISO 639-1. Déjalo vacío para la detección automática; el código detectado está en `metadata.language`.
- `execution.timeout_ms`: Tiempo límite de la ejecución de Python. Si no se define, el código usa 900000 ms (15 min); el esquema muestra 300000.
- `content_base64 / file_path`: No están declaradas en el esquema de configuración, pero se leen de la configuración antes que del ítem entrante. Úsalas para apuntar a un archivo con una expresión, p. ej. `{{ $json.attachment.content_base64 }}`.

## Errores

| Mensaje | Puerto | Causa y solución |
| --- | --- | --- |
| `Either content_base64 or file_path is required.` | `error` | Ni la configuración ni el ítem entrante tienen `content_base64` o `file_path`. Mapea el archivo desde el nodo anterior. |
| `Either content_base64 or file_path is required` | `error` | Lo lanza el script de Python cuando `file_path` no existe en el host del orquestador. Los datos incluyen también `stderr`. |
| `<faster-whisper or decoder error>` | `error` | El archivo no se puede decodificar como audio o video, o el modelo no se pudo cargar en el host. |
| `Python timed out after <timeout_ms>ms` | `error` | El script superó `execution.timeout_ms`. Auméntalo o procesa menos páginas. |
| `Python runtime not available (ENOENT)` | `error` | No hay un intérprete de Python disponible en el host del orquestador. |

## Notas y límites

- Cada ejecución es un proceso de Python nuevo, así que el modelo se carga en cada ejecución; los valores mayores de `model_size` suman memoria y tiempo de arranque.
- No hay un filtro de actividad de voz configurado: `empty` significa que el modelo no produjo texto, no que un paso de VAD encontrara silencio.
- Sin diarización de hablantes ni vocabulario personalizado.
- `file_path` es una ruta en el host del orquestador. `content_base64` tiene prioridad cuando llegan ambos.
- La extracción se ejecuta en un subproceso de Python. En el primer uso, el orquestador crea un entorno virtual e instala las dependencias fijadas, lo que puede tardar minutos; las ejecuciones siguientes lo reutilizan.
- El resultado de Python está limitado a 50 MB de salida; si lo supera, el nodo sale por `error`.
- El motor no aplica `execution.retryOnFail`, `maxTries`, `waitBetweenTries` ni `continueOnFail` a este nodo. Gestiona los fallos conectando el puerto `error`.


## Contratos (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
  }
]
```
