Permet d'obtenir la transcription des vidéos de l'assemblée/sénat en fournissant un lien vidéo m3u8 en entrée
  • TypeScript 99.7%
  • Dockerfile 0.2%
  • JavaScript 0.1%
Find a file
Repository files (latest commit first)
Filename Latest commit message Latest commit date
2026-11-13 16:49:38 +01:00
.forgejo/workflows fix(docker): use glibc base so the sherpa-onnx voiceprint loads 2026-10-28 14:54:46 +01:00
eval chore(eval): cache LLM labels for evaluation runs 2026-11-13 16:49:38 +01:00
specs fix(eval): adapte la base voix au schéma v2 (identityId) 2026-11-04 16:43:37 +01:00
src fix(youtube): robuste bot-check datacenter (deno, clients mweb, cookies, PO token) 2026-11-13 11:05:25 +01:00
tests fix(ci): skip transcribeOne startSec tests without ffprobe 2026-11-13 11:11:32 +01:00
.dockerignore Add a dockerfile for deployment, and update readme about the dockerfile and the new output json format 2025-08-19 19:35:43 +02:00
.env.example fix(youtube): robuste bot-check datacenter (deno, clients mweb, cookies, PO token) 2026-11-13 11:05:25 +01:00
.gitignore feat(eval): --out writes the text report, default path in eval/output/ 2026-10-27 15:08:07 +01:00
.prettierrc add prettierRc to prevent unwanted diff 2025-10-17 11:21:04 +02:00
Dockerfile fix(youtube): robuste bot-check datacenter (deno, clients mweb, cookies, PO token) 2026-11-13 11:05:25 +01:00
eslint.config.js feat(stream): pre-flight probe, fail-fast session errors, Stream naming 2026-09-14 12:48:54 +02:00
LICENSE.md chore: update authors & copyright 2026-01-25 22:43:56 +01:00
package-lock.json revert: reste en 1.9.18 (le skip ffprobe est un fix, pas une release) 2026-11-13 11:12:12 +01:00
package.json revert: reste en 1.9.18 (le skip ffprobe est un fix, pas une release) 2026-11-13 11:12:12 +01:00
README.md fix(youtube): robuste bot-check datacenter (deno, clients mweb, cookies, PO token) 2026-11-13 11:05:25 +01:00
tsconfig.build.json fix(pack): publier dist avec declarations et exports en sous-chemins 2026-09-15 23:19:09 +02:00
tsconfig.json feat(stream): pre-flight probe, fail-fast session errors, Stream naming 2026-09-14 12:48:54 +02:00
vitest.config.ts vitest config in root 2026-01-19 18:48:33 +01:00

tricoteuses-transcription-videos

Node.js/TypeScript pipeline to transcribe French Parliament videos (with speaker diarization), from either a .m3u8 URL or a WAV file extracted via ffmpeg.

  • Output: a JSON array in the Compte-Rendu format of Assemblée's Data:

    [
      {
        "code_grammaire": "PAROLE_GENERIQUE",
        "ordre_absolu_seance": "4",
        "orateurs": {
          "orateur": {
            "nom": "speaker A",
            "id": "",
            "qualite": ""
          }
        },
        "texte": {
          "_": "Merci monsieur le rapporteur général."
        }
      },
      {
        "code_grammaire": "PAROLE_GENERIQUE",
        "ordre_absolu_seance": "5",
        "orateurs": {
          "orateur": {
            "nom": "speaker D",
            "id": "",
            "qualite": ""
          }
        },
        "texte": {
          "_": "Merci monsieur le président, mesdames et messieurs, ..."
        }
      }
    ]
    

    Timestamps are milliseconds. speaker is a letter (A, B, C…).

  • Plug-and-play architecture via providers: currently AssemblyAI and Deepgram. You can plug additional models later without changing application code.


Table of Contents


Prerequisites

  • Node.js ≥ 20
  • npm
  • ffmpeg + ffprobe available in your PATH (audio extraction + input inspection):
    ffmpeg -version && ffprobe -version
    
  • yt-dlp available in your PATH (only needed for watch-page URLs: YouTube, Vimeo, … — direct media URLs and local files don't need it). YouTube also needs a JS runtime for its EJS challenges (deno ≥ 2.3.0 recommended, enabled by default; node ≥ 22 works with --js-runtimes node, which the worker passes automatically) plus the EJS scripts (pip install "yt-dlp[default]"). From datacenter IPs YouTube answers "Sign in to confirm you're not a bot": same yt-dlp, plus cookies of a logged-in session (YOUTUBE_COOKIES_FILE=/path/to/cookies.txt, Netscape format) and, as a manual override, a static PO token (YOUTUBE_PO_TOKEN=mweb.gvs+XXX — per-video tokens are auto-provided by the bgutil-ytdlp-pot-provider plugin in the Docker image):
    yt-dlp --version
    deno --version
    
  • Assemblée dataset prepared :
    • Must contain: Agenda__nettoye/ for the target legislature.

Installation

npm install
cp .env.example .env   # add your models key

Usage (single video, useful for model testing)

1) Select your provider in .env

Set TRANSCRIPTION_PROVIDER to one of: deepgram or assemblyai

2) From a .m3u8 URL (audio extraction + transcription)

# create the output folders if needed
mkdir -p ./out ./audios

npm run transcribe --   --m3u8 "https://videos-an.vodalys.com/.../master.m3u8"   --out ./audios/reunion.wav   --startSec 0   --t 800   --save ./out/transcript-{model_name}.json

CLI Options

  • --startSec : start offset (seconds)
  • --t : duration (seconds)
  • --out: WAV path; if omitted, we default to os.tmpdir()
  • --save: output JSON path (default: ./transcript.json)
  • --lang fr to force language (otherwise uses .env default)
  • --diarize false to disable diarization (enabled by default)

3) From an existing audio file WAV

npm run transcribe --   --file C:/path/to/reunion.wav   --save ./out/transcript-{model_name}.json

Usage (batch by reunion UIDs, useful in prod)

Process only specific Assemblée reunion UIDs using the dataset loaders. For each UID:

  1. read reunion.urlVideo,
  2. extract audio to ./audios/<uid>.wav (skip ffmpeg if the WAV already exists),
  3. transcribe + diarize the full video with the current provider,
  4. write segments to $ASSEMBLEE_DATA_DIR/Videos_<ROMAN_LEGISLATURE>_nettoye/<uid>/transcript.json (+ info.json with basic metadata).

audioStartSec (skip leading silence)

Each output carries audioStartSec: the first transcribed speech on the absolute video timeline (whole seconds, minus a 2s margin), so a player can deep-link past leading silence (?t=<audioStartSec>):

  • transcript.json → metadata.audioStartSec,
  • compte-rendu.json → metadonnees.audioStartSec,
  • info-<uid>.json → audioStartSec (+ effectiveStartSec, the applied -ss offset).

It is null when no usable speech segment exists — fall back to reunion.timecodeDebutVideo in that case.

CLI Options

  • --dataDir: Absolute path to Assemblée dataset (or as 1st positional). Required.
  • -l, --legislature: Legislature number (e.g., 16 or 17).
  • -s, --fromSession: Session number to start from (Senat only)
  • --uids: Comma-separated UIDs (e.g., uid1,uid2).
  • --uid: Repeatable UID flag (can be used multiple times).
  • --lang: Language code (e.g., fr).
  • --diarize: Enable diarization (default: true).
  • --no-diarize: Disable diarization.
  • --keepWav: Keep extracted WAV files (default: true).
  • --no-keepWav: Delete WAV after successful transcription.
  • --audioDir: Directory for WAV files (default: ./audios).
  • --overwrite: Re-extract audio even if the output already exists (default: false).
  • --startSec: Start offset (seconds).
  • --t: Duration (seconds).
  • -p, --provider: Transcription provider (assemblyai | deepgram).

Examples

Transcribe all Reunions from 17th legislature (max 50):

npm run transcribe:reunions ../assemblee-data -- --legislature 17 --provider assemblyai --max 50

Force re-extraction + startTimecode to optimize wav:

npm run transcribe:reunions -- --dataDir /abs/path/assemblee-data -l 17 --uid RUANR5...   --overwrite --startSec 796

# Transcribe one AN
npm run transcribe:reunions ../assemblee-data -- --legislature 17 --transcriptsDir ../assemblee-data/transcripts --audioDir ../assemblee-data/audios --provider deepgram --chambre AN --uid RUANR5L17S2025IDC453375
# Transcribe one SN
npm run transcribe:reunions ../senat-data -- --fromSession 2025 --transcriptsDir ../senat-data/transcripts --audioDir ../senat-data/audios --provider deepgram --chambre SN --uid RUSN20251016IDODDF-900

Usage - Transcription Live

Live transcription continuously transcribes an HLS .m3u8 stream, with automatic retries and a clean stop when the stream ends.
It is designed for one job per live (e.g. one Kubernetes pod per debate).

Basic CLI usage

npm run transcribe:live --   --url "https://videos-an.vodalys.com/live/.../index.m3u8"   --out ./live-transcripts/live-$(date +%s).ndjson

Live CLI options

  • --url (required unless --uid): live stream URL (HLS .m3u8, YouTube live watch URL)
  • --uid: DebatDirect UID (enables API push)
  • --out: NDJSON output file (default: ./live-transcripts/live-<timestamp>.ndjson)
  • --lang: language code (default from .env)
  • --diarize / --no-diarize: enable/disable diarization (default: enabled)
  • --provider: transcription provider (deepgram, assemblyai, …)
  • --model: provider-specific model (optional)
  • --startSec: skip this many seconds at the start
  • --statusPollSec: poll DebatDirect status every N seconds (default: 20)
  • --identifySpeakers: enable live speaker identification (LLM backend, voiceprint first when configured)

Live identification policy:

  • Roster strict : seuls les ids de la liste NVS/agenda sont acceptés ; aucun nom libre.
  • Les claims fenêtrés (clé de diarization couvrant plusieurs personnes) sont conservés entre les runs.
  • Une clé n'est publiée en mapping global (seule forme stockée par l'API direct) que si ses fenêtres strong sont unanimes, stables sur au moins 2 runs et couvrent ≥ 80 % de sa parole. Les clés hétérogènes restent anonymes (pas de faux positif). En rolling live, des claims weak convergents (même identité, 3 justifications distinctes) sont promus strong et publiés.
  • Le backend voiceprint passe avant le LLM quand une base est configurée (--voiceprint ou VOICEPRINT_BASES) ; un claim voiceprint strong est prioritaire. --no-voiceprint force le LLM seul. Voir Voice identification.
  • Voiceprint : l'audio live est capté par un tee PCM, accumulé par clé, puis embeddé localement (ONNX TITANet). Une clé dont les deux moitiés divergent (voix mélangées) s'abstient. La base d'empreintes est lue depuis un chemin local, une URL HTTPS ou un S3 compatible (SigV4, base-meta.json fournit sha256 et modelVersion). Le modèle est embarqué dans l'image.
  • --replay: transcribe a past session instead of a live stream (finite VOD read from the start). With --uid, creates a replay record through the API; without --uid, local mode requires --url, --livePlayerUrl and --dataNvsUrl.
  • --livePlayerUrl / --dataNvsUrl: NVS URLs, required only in local replay mode (--replay without --uid).

Replay a past session

--replay reads a finite VOD from the start (not the live edge). With --uid, the API creates a dedicated replay record from the source direct and paragraphs are pushed to it:

# API mode: create a replay record from a past direct and transcribe it
npm run transcribe:live -- --replay --uid TRDAN5... --startSec 0

# Local mode: no API push
npm run transcribe:live -- --replay \
  --url "https://.../index.m3u8" \
  --livePlayerUrl "https://.../player.nvs" \
  --dataNvsUrl "https://.../data.nvs"

Output format (NDJSON)

The output file is append-only, one JSON object per line. Two timestamps coexist on utterance lines, by design:

  • start/end (ms): provider-measured, relative to the current attempt's read position (the raw measurement — recomputable after a calibration fix).
  • startAbsMs/endAbsMs: absolute epoch (ms) on the real stream timeline, derived as pdtAnchorMs + start from the HLS playlist #EXT-X-PROGRAM-DATE-TIME. Present only when the anchor is available (HLS input with PDT; absent for non-HLS inputs or unparsable playlists).
  • startVideoMs/endVideoMs: seek position in the video (ms from the broadcast/video start) = startAbsMs - broadcastStartMs. Present when both the PDT anchor and broadcastStartMs are known — use it to deep-link the player (YouTube ?t=<sec>, NVS video timecode).
  • at (ISO 8601): wall clock at reception — measures pipeline latency, never a speech time.
  • timecodeOffsetMs (parliament push path): converts relative times to the DebatDirect video timeline before API push.

broadcastStartMs (meta lines) comes from the native NVS starttime epoch, or from the watch page metadata (yt-dlp -J → timestamp, YouTube liveBroadcastDetails.startTimestamp) when there is no native epoch.

{"type":"meta","msg":"live transcription start","url":"...","broadcastStartMs":1759150543000}
{"type":"meta","msg":"session start","attempt":1,"pdtAnchorMs":1789403090054,"timecodeOffsetMs":52354,"timecodeSource":"pdt"}
{"type":"utterance","at":"2026-09-14T17:05:12.345Z","start":12034,"end":15002,"startAbsMs":1789403102088,"endAbsMs":1789403105056,"startVideoMs":30252597088,"endVideoMs":30252600056,"speaker":"1","text":"Bonjour à tous"}
{"type":"meta","msg":"session ended","durSec":6400}

Deep-link example: ?t=${Math.round(startVideoMs / 1000)}.

This format allows streaming ingestion, retries without duplicates, and easy replay.

Error handling & retries

  • On stream errors or disconnects, the script retries automatically with a short backoff.
  • If a session ends too quickly, it is retried until the minimum valid duration is reached.

Production integration

Typical flow:

  1. API detects a new DebatDirect
  2. A job/pod is started for this live
  3. transcribe:live runs for this single stream
  4. Segments are pushed incrementally to the API
  5. When the live ends, the job exits and the debate is marked TERMINE

Rule: 1 live = 1 process.

Voice identification (voiceprints)

Speakers can be recognized by voice in every entry point (transcribe:media, transcribe:stream, transcribe:reunions, transcribe:live), for any video — not only the Assemblée. Spec: specs/empreintes-vocales-generiques-spec.md.

  1. Model (once, ~101 MB, pinned checksum): npm run vp:model.

  2. Label voices — a CSV (or NDJSON of LabeledSpan) of speech ranges:

    identity_id,name,namespace,media_uri,start,end
    elise-durand,Élise Durand,podcast,https://www.youtube.com/watch?v=REdl9nuI6uE,1:01,1:45
    

    Identities are opaque ids within a namespace (podcast:elise-durand, an:PA793378). Assemblée labels come from the CR/NVS pipeline (vp:clips, which writes <UID>.spans.ndjson).

  3. Enroll (cut, purity check, embed): npm run vp:enroll -- --spans labels.csv --out podcast.entries.ndjson.

  4. Build and publish a base (namespaces must be declared with a legal basis and retention — voiceprints are biometric data):

    echo '{"podcast":{"legalBasis":"consentement","retentionDays":365}}' > namespaces.json
    npm run vp:build -- --entries podcast.entries.ndjson --namespaces namespaces.json \
      --out ./bases/podcast/build/base.jsonl --publish --to ./bases/podcast
    
  5. Evaluate and calibrate (session held out, open-world false accepts): npm run vp:eval -- --base ./bases/podcast --out eval.json, then rebuild with --thresholds eval.json to store calibrated thresholds in base-meta.json.

  6. Use it: npm run transcribe:media -- --input <url> --voiceprint ./bases/podcast (several bases: comma-separated, or VOICEPRINT_BASES; --voiceprintNamespaces restricts candidates). A roster entry may carry "identityId" to bind a voice to a roster id.

Other commands: vp:publish, vp:forget (erasure registry applied by vp:build --forget), and vp:migrate, the only reader of the pre-v2 format (AN bases and agent outputs manifest + embeddings): see the runbook.

Voice abstains rather than guesses: distance threshold, margin to the first other identity, purity of the key (two halves must match). In batch/media, voice is also queried per contiguous speech range, so a diarization key mixing two people gets windowed claims instead of nothing.

Tests

Provider benchmark on fixtures

An opt-in integration test compares deepgram, assemblyai and mistral on fixture videos and prints a ranking based on:

  • average WER (word error rate, lower is better)
  • average transcription latency in milliseconds (tie-breaker)

Run it with:

RUN_PROVIDER_BENCHMARK_TEST=true \
PROVIDER_BENCHMARK_MAX_FIXTURES=2 \
npm run test -- tests/integration/providers.fixtures.benchmark.test.ts

Required API keys:

  • DEEPGRAM_API_KEY
  • ASSEMBLYAI_API_KEY
  • MISTRAL_API_KEY

The test is skipped by default unless RUN_PROVIDER_BENCHMARK_TEST=true.

Code Architecture

src/
├─ config/
│  └─ env.ts                   # .env loading & validation
├─ types/
│  └─ transcription.ts         # common types (segments in ms, speakers, metadata)
├─ providers/
│  ├─ TranscriptionProvider.ts # generic interface
│  ├─ assemblyai.ts            # AssemblyAI implementation
│  ├─ deepgram.ts              # Deepgram implementation
│  ├─ mistral.ts               # Mistral implementation
│  └─ index.ts                 # provider factory based on .env
├─ utils/
│  └─ ffmpeg.ts                # .m3u8 → WAV mono 16k extraction
│  └─ transcribe.ts            # single function used by scripts/services
├─ scripts/
│  └─ transcribe_reunions.ts
└─ └─ transcribe_live.ts

Swap providers later

Application code always calls:

const result = await transcribeVideo({
  filePath: '/tmp/reunion.wav',
  language: 'fr',
  diarize: true,
});

To add another provider:

  1. Create src/providers/myProvider.ts implementing TranscriptionProvider.
  2. Add a case in src/providers/index.ts and a .env value (TRANSCRIPTION_PROVIDER=myProvider).
  3. Map the new API’s response to the same types (segments in ms, letter speakers).

Docker :

Build the image

docker build -t transcriber:dev .

Run (change the ABSOLUTE_PATH_TO_ASSEMBLEE_DATA)

docker run \
  --env-file .env \
  -e LEGISLATURE=17 \
  -v "/ABSOLUTE_PATH_TO_ASSEMBLEE_DATA:/app/assemblee-data" \
  transcriber:dev

License

AGPL-3.0-or-later