> 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-fr/audio-et-voix/whisperx.md).

# WhisperX avec diarisation

Exécutez WhisperX pour une transcription vocale rapide avec horodatage au niveau du mot et diarisation des locuteurs sur les GPU Clore.ai.

WhisperX étend Whisper d'OpenAI avec trois améliorations essentielles : **horodatages au niveau du mot** via un alignement forcé des phonèmes, **diarisation des locuteurs** en utilisant pyannote.audio, et **jusqu'à 70× la vitesse en temps réel** grâce à l'inférence par lots avec faster-whisper. C'est l'outil de référence pour les pipelines de transcription de production qui ont besoin d'un minutage précis et d'une identification des locuteurs.

**GitHub :** [m-bain/whisperX](https://github.com/m-bain/whisperX) **PyPI :** [whisperx](https://pypi.org/project/whisperx/) **Licence :** BSD-4-Clause **Article :** [arxiv.org/abs/2303.00747](https://arxiv.org/abs/2303.00747)

## Caractéristiques clés

* **Horodatages au niveau du mot** — précision de ±50 ms via l'alignement forcé wav2vec2 (contre ±500 ms dans Whisper standard)
* **Diarisation des locuteurs** — identifiez qui a dit quoi via pyannote.audio 3.1
* **Inférence par lots** — jusqu'à 70× la vitesse temps réel sur RTX 4090
* **Préfiltrage VAD** — Silero VAD supprime le silence avant la transcription
* **Tous les modèles Whisper** — de tiny à large-v3-turbo
* **Plusieurs formats de sortie** — JSON, SRT, VTT, TXT, TSV
* **Détection automatique de la langue** — ou forcez une langue spécifique pour un traitement plus rapide

## Exigences

| Composant | Minimum             | Recommandé              |
| --------- | ------------------- | ----------------------- |
| GPU       | RTX 3060 12 GB      | RTX 4090 24 Go          |
| VRAM      | 4 Go (petit modèle) | 10 Go+ (large-v3-turbo) |
| RAM       | 8 Go                | 16 Go+                  |
| Disque    | 5 Go                | 20 Go (cache du modèle) |
| Python    | 3.9+                | 3.11                    |
| CUDA      | 12.8+               | 12.8+                   |

**Jeton HuggingFace requis** pour la diarisation des locuteurs — acceptez la licence sur [pyannote/speaker-diarization-3.1](https://huggingface.co/pyannote/speaker-diarization-3.1).

**Recommandation de Clore.ai :** RTX 3090 (0,07–0,21 $/h) pour le modèle large-v3-turbo avec une taille de lot de 16. RTX 4090 (0,14–0,42 $/h) pour un débit maximal avec une taille de lot de 32.

## Installation

```bash
# Installer WhisperX
pip install whisperx

# Vérifier le GPU
python -c "import torch; print(torch.cuda.get_device_name(0))"
```

Si vous rencontrez des conflits de version CUDA :

```bash
pip install torch==2.5.1+cu124 torchaudio==2.5.1+cu124 --index-url https://download.pytorch.org/whl/cu128
pip install whisperx
```

## Démarrage rapide

```python
import whisperx
import json

device = "cuda"
compute_type = "float16"  # "int8" pour une VRAM plus faible
batch_size = 16            # réduisez à 4-8 si la VRAM est limitée

# 1. Charger le modèle
model = whisperx.load_model("large-v3-turbo", device, compute_type=compute_type)

# 2. Charger et transcrire l'audio
audio = whisperx.load_audio("interview.mp3")
result = model.transcribe(audio, batch_size=batch_size)
print(f"Langue : {result['language']}")

# 3. Aligner pour des horodatages au niveau du mot
model_a, metadata = whisperx.load_align_model(
    language_code=result["language"], device=device
)
result = whisperx.align(
    result["segments"], model_a, metadata, audio, device,
    return_char_alignments=False,
)

# 4. Afficher les résultats
for seg in result["segments"]:
    print(f"[{seg['start']:.2f}s → {seg['end']:.2f}s] {seg['text']}")
    for w in seg.get("words", []):
        print(f"  '{w['word']}' à {w.get('start', 0):.2f}s")

# 5. Enregistrer
with open("transcript.json", "w") as f:
    json.dump(result, f, indent=2, ensure_ascii=False)
```

## Exemples d'utilisation

### Transcription avec diarisation des locuteurs

```python
import whisperx
import gc
import torch

device = "cuda"
HF_TOKEN = "hf_your_token_here"  # depuis huggingface.co/settings/tokens

# Étape 1 : Transcrire
model = whisperx.load_model("large-v3-turbo", device, compute_type="float16")
audio = whisperx.load_audio("meeting.mp3")
result = model.transcribe(audio, batch_size=16)

# Libérer la mémoire GPU avant de charger le modèle d'alignement
del model; gc.collect(); torch.cuda.empty_cache()

# Étape 2 : Aligner
model_a, metadata = whisperx.load_align_model(
    language_code=result["language"], device=device
)
result = whisperx.align(result["segments"], model_a, metadata, audio, device)
del model_a; gc.collect(); torch.cuda.empty_cache()

# Étape 3 : Faire la diarisation
diarize_model = whisperx.DiarizationPipeline(
    use_auth_token=HF_TOKEN, device=device
)
diarize_segments = diarize_model(audio, min_speakers=2, max_speakers=6)

# Étape 4 : Attribuer les locuteurs aux mots
result = whisperx.assign_word_speakers(diarize_segments, result)

for seg in result["segments"]:
    speaker = seg.get("speaker", "UNKNOWN")
    print(f"[{speaker}] [{seg['start']:.1f}s → {seg['end']:.1f}s] {seg['text']}")
```

### Utilisation en ligne de commande

```bash
# Transcription de base
whisperx audio.mp3 --model large-v3-turbo --device cuda

# Forcer la langue (plus rapide, saute la détection)
whisperx audio.mp3 --model large-v3-turbo --language en --device cuda

# Avec séparation des locuteurs
whisperx audio.mp3 --model large-v3-turbo --diarize --hf_token hf_your_token

# Sortie de sous-titres SRT
whisperx audio.mp3 --model large-v3-turbo --output_format srt --output_dir ./subs/

# Mode faible VRAM
whisperx audio.mp3 --model medium --compute_type int8 --batch_size 4 --device cuda

# Traitement par lot d'un répertoire
for f in /data/audio/*.mp3; do
  whisperx "$f" --model large-v3-turbo --output_dir /data/transcripts/
done
```

### Script de génération SRT

```python
import whisperx

def transcribe_to_srt(audio_path, output_path, model_name="large-v3-turbo"):
    device = "cuda"
    model = whisperx.load_model(model_name, device, compute_type="float16")
    audio = whisperx.load_audio(audio_path)
    result = model.transcribe(audio, batch_size=16)

    model_a, metadata = whisperx.load_align_model(
        language_code=result["language"], device=device
    )
    result = whisperx.align(result["segments"], model_a, metadata, audio, device)

    with open(output_path, "w") as f:
        for i, seg in enumerate(result["segments"], 1):
            start = format_ts(seg["start"])
            end = format_ts(seg["end"])
            f.write(f"{i}\n{start} --> {end}\n{seg['text'].strip()}\n\n")

    print(f"SRT enregistré dans {output_path}")

def format_ts(seconds):
    h = int(seconds // 3600)
    m = int((seconds % 3600) // 60)
    s = int(seconds % 60)
    ms = int((seconds % 1) * 1000)
    return f"{h:02d}:{m:02d}:{s:02d},{ms:03d}"

transcribe_to_srt("podcast.mp3", "podcast.srt")
```

## Benchmarks de performance

| Méthode          | Modèle             | Audio 1 h   | GPU          | Vitesse approx. |
| ---------------- | ------------------ | ----------- | ------------ | --------------- |
| Whisper standard | large-v3           | \~60 min    | RTX 3090     | 1×              |
| faster-whisper   | large-v3           | \~5 min     | RTX 3090     | \~12×           |
| **WhisperX**     | **large-v3-turbo** | **\~1 min** | **RTX 3090** | **\~60×**       |
| **WhisperX**     | **large-v3-turbo** | **\~50 s**  | **RTX 4090** | **\~70×**       |

| Taille de lot | Vitesse (RTX 4090)  | VRAM  |
| ------------- | ------------------- | ----- |
| 4             | \~30× en temps réel | 6 Go  |
| 8             | \~45× en temps réel | 8 Go  |
| 16            | \~60× en temps réel | 10 Go |
| 32            | \~70× en temps réel | 14 Go |

## Conseils pour les utilisateurs de Clore.ai

* **Libérer la VRAM entre les étapes** — supprimez les modèles et appelez `torch.cuda.empty_cache()` entre la transcription, l'alignement et la diarisation
* **Jeton HuggingFace** — vous devez accepter la licence du modèle pyannote avant que la diarisation fonctionne ; définissez `HF_TOKEN` comme variable d'environnement
* **Ajustement de la taille de lot** — commencez avec `batch_size=16`, réduisez à 4–8 sur les cartes de 12 Go, augmentez à 32 sur les cartes de 24 Go
* **`int8` calcul** — utiliser `compute_type="int8"` pour diviser par deux l'utilisation de la VRAM avec une perte de qualité minimale
* **Image Docker** — `pytorch/pytorch:2.11.0-cuda12.8-cudnn9-runtime`
* **Cache de modèle persistant** — montez `/root/.cache/huggingface` pour éviter de retélécharger les modèles à chaque redémarrage du conteneur

## Dépannage

| Problème                          | Solution                                                                                                                            |
| --------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- |
| `Mémoire CUDA insuffisante`       | Réduisez `batch_size`, utilisez `compute_type="int8"`, ou utilisez un modèle plus petit (medium, small)                             |
| La diarisation renvoie `UNKNOWN`  | Assurez-vous que le jeton HuggingFace est valide et que vous avez accepté la licence pyannote                                       |
| `Aucun module nommé 'whisperx'`   | `pip install whisperx` — assurez-vous qu'il n'y a pas de faute de frappe (c'est `whisperx`, et non `whisper-x`)                     |
| Horodatages des mots médiocres    | Vérifiez que `whisperx.align()` est appelé après `transcribe()` — la sortie brute de Whisper manque de précision au niveau des mots |
| Détection de la langue incorrecte | Forcez la langue avec `--language en` ou `language="en"` dans l'API Python                                                          |
| Traitement lent                   | Augmentez `batch_size`, utilisez `large-v3-turbo` au lieu de `large-v3`, assurez-vous que le GPU n'est pas partagé                  |


---

# 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-fr/audio-et-voix/whisperx.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.
