P4 — Generation TTS pour Audiobook

Lancer : Codespaces Colab

Navigation : Index | << Précédent | Suivant >>

Ce carnet transforme les annotations prosodiques P3 et la configuration vocale P2 en fichiers audio pour le texte, puis exporte les métadonnées de génération. Kokoro TTS sert à la démonstration et FishAudio S2-Pro à la production.

Le capstone de la chaîne est 04-13 : il couvre l’architecture, rejoue P4 et P5 et la validation de bout en bout, sur le cas FishAudio S2-Pro. ## Objectifs

  1. Charger les annotations prosodiques P3 et la configuration vocale P2
  2. Mapper chaque segment au bon modèle/voix TTS
  3. Generer les fichiers audio pour les 342 segments du texte
  4. Exporter les metadonnees de generation (durees, tailles, paths)
# Import guards - availability flags for external dependencies

try:
    from IPython.display import display, Audio, Image as IPImage
    IPYTHON_AVAILABLE = True
except ImportError:
    IPYTHON_AVAILABLE = False
    print(f'  IPython non disponible - certaines fonctionnalites seront limitees')

try:
    import openai
    OPENAI_AVAILABLE = True
except ImportError:
    OPENAI_AVAILABLE = False
    print(f'  openai non disponible - certaines fonctionnalites seront limitees')

try:
    import requests
    REQUESTS_AVAILABLE = True
except ImportError:
    REQUESTS_AVAILABLE = False
    print(f'  requests non disponible - certaines fonctionnalites seront limitees')


import json
import os
import time
from pathlib import Path
from dataclasses import dataclass, field, asdict
from typing import Optional
import requests

# Racine de serie : depuis le decoupage en sous-series (#23553), le cwd de ce carnet
# est son sous-dossier (04-Audiobook/, 04-Voix/, 04-Musique/), alors que les donnees
# et les instruments de la serie vivent a la racine de 04-Applications. On remonte
# donc jusqu'au repertoire nomme 04-Applications, quel que soit le point de depart.
SERIES_ROOT = Path.cwd()
while SERIES_ROOT.name != '04-Applications' and len(SERIES_ROOT.parts) > 1:
    SERIES_ROOT = SERIES_ROOT.parent
print(f"Racine de serie : {SERIES_ROOT.name}")
if SERIES_ROOT.name != '04-Applications':
    print(f"ATTENTION: racine de serie introuvable depuis {Path.cwd().name}")

# Paths
BASE_DIR = SERIES_ROOT
PROSODIC_FILE = BASE_DIR / "prosodic_output" / "prosodic_annotations.json"
VOICE_CONFIG = BASE_DIR / "voice_casting_output" / "voice_casting_config.json"
TTS_OUTPUT_DIR = BASE_DIR / "tts_output"
TTS_OUTPUT_DIR.mkdir(exist_ok=True, parents=True)

KOKORO_URL = "http://localhost:8191"
KOKORO_API_KEY = os.getenv("KOKORO_API_KEY", "") or os.getenv("TTS_API_KEY", "")
print(f"Output dir: {TTS_OUTPUT_DIR.name}")
print(f"Prosodic annotations: {PROSODIC_FILE.exists()}")
print(f"Voice config: {VOICE_CONFIG.exists()}")
print(f"Kokoro API key: {'set' if KOKORO_API_KEY else 'NOT SET'}")
# Import helpers audio : publication d'un bundle MIME audio/* verifiable dans le JSON (#10996)
import sys
GENAI_ROOT = Path.cwd()
while GENAI_ROOT.name != "GenAI" and len(GENAI_ROOT.parts) > 1:
    GENAI_ROOT = GENAI_ROOT.parent
HELPERS_PATH = GENAI_ROOT / "shared" / "helpers"
if HELPERS_PATH.exists():
    sys.path.insert(0, str(HELPERS_PATH.parent))
    from helpers.audio_helpers import display_audio_bundle, display_audio_file
    print("Helpers audio importes")
Racine de serie : 04-Applications
Output dir: tts_output
Prosodic annotations: True
Voice config: True
Kokoro API key: set
Helpers audio importes

Architecture TTS

Modèle Statut Qualite Latence Expressivite
Kokoro (local Docker) Actif Bonne runtime machine-dep : <2s Tags base (speed, emotion)
FishAudio S2-Pro Non deploye Excellente runtime machine-dep : ~3s 15000+ tags expressifs
OpenAI TTS-1 Cloud Bonne runtime machine-dep : ~2s 6 voix fixes

Ce notebook utilise Kokoro pour la demo locale. Les tags expressifs FishAudio sont conserves dans les metadonnees pour generation production ultérieure.

def load_voice_config(path):
    """Load P2 voice casting configuration."""
    with open(path) as f:
        return json.load(f)

def load_prosodic_annotations(path):
    """Load P3 prosodic annotations."""
    with open(path) as f:
        return json.load(f)

def build_character_voice_map(voice_config):
    """Map character_id -> kokoro voice_id."""
    mapping = {}
    for char_id, char_data in voice_config["characters"].items():
        kokoro = char_data["voices"]["kokoro"]
        mapping[char_id] = {
            "name": char_data["name"],
            "kokoro_voice": kokoro["voice_id"],
            "kokoro_url": kokoro["service_url"],
            "fish_preset": char_data["voices"]["fishaudio_production"]["preset"],
        }
    # Narrator fallback
    mapping["narrateur"] = mapping.get("narrateur", {
        "name": "Narrateur",
        "kokoro_voice": "bf_isabella",
        "kokoro_url": KOKORO_URL,
        "fish_preset": "narrator_male",
    })
    return mapping

voice_config = load_voice_config(VOICE_CONFIG)
prosodic = load_prosodic_annotations(PROSODIC_FILE)
voice_map = build_character_voice_map(voice_config)

print(f"Characters mapped: {len(voice_map)}")
for cid, info in voice_map.items():
    print(f"  {cid}: {info['name']} -> Kokoro {info['kokoro_voice']}")
Characters mapped: 10
  comte: Comte Hubert de Breville -> Kokoro bm_george
  officier: Officier prussien -> Kokoro am_michael
  loiseau: Monsieur Loiseau -> Kokoro bm_george
  boule_de_suif: Elisabeth Rousset -> Kokoro af_sky
  comtesse: Comtesse de Breville -> Kokoro af_bella
  cornudet: Cornudet -> Kokoro bm_george
  soeurs: Les bonnes soeurs -> Kokoro bf_emma
  mme_loiseau: Mme Loiseau -> Kokoro af_bella
  carre_lamadon: Monsieur Carre-Lamadon -> Kokoro bm_george
  narrateur: Narrateur -> Kokoro bf_isabella

Kokoro TTS — API locale

Le service Kokoro (Docker, port 8191) expose une API compatible OpenAI :

POST /v1/audio/speech
Content-Type: application/json

{"model": "kokoro", "voice": "af_sky", "input": "texte", "speed": 1.0}

Reponse : audio MP3 (128 kbps, 24000 Hz, mono).

Note : Les tags expressifs [whisper], [shout] etc. sont ignores par Kokoro mais conserves pour FishAudio S2-Pro en production.

@dataclass
class TTSRequest:
    """Represents a TTS generation request for one segment."""
    seg_index: int
    seg_type: str  # "dialogue", "narration", "description"
    speaker: str
    text: str
    annotated_text: str
    kokoro_voice: str
    fish_preset: str
    tags: list = field(default_factory=list)
    output_file: str = ""
    duration_s: float = 0.0
    file_size_kb: float = 0.0
    status: str = "pending"

def kokoro_tts(text, voice_id, speed=1.0):
    """Generate audio via Kokoro TTS API."""
    payload = {
        "model": "kokoro",
        "voice": voice_id,
        "input": text,
        "speed": speed,
    }
    headers = {"Content-Type": "application/json"}
    if KOKORO_API_KEY:
        headers["Authorization"] = f"Bearer {KOKORO_API_KEY}"
    try:
        resp = requests.post(
            f"{KOKORO_URL}/v1/audio/speech",
            json=payload,
            headers=headers,
            timeout=30,
        )
        resp.raise_for_status()
        return resp.content
    except requests.RequestException as e:
        print(f"  TTS error for voice={voice_id}: {e}")
        return None

print("TTS client ready")
print(f"Kokoro endpoint: {KOKORO_URL}")
TTS client ready
Kokoro endpoint: http://localhost:8191

Construction des segments a generer

Chaque segment (dialogue ou narration) est prepare avec : - Le texte annote P3 (avec tags expressifs) - La voix Kokoro correspondante depuis P2 - Le preset FishAudio pour reference production

def resolve_speaker_id(speaker_name, voice_map):
    """Resolve a speaker name to character_id."""
    name_lower = speaker_name.lower().replace(" ", "_")
    # Direct match
    if name_lower in voice_map:
        return name_lower
    # Partial match
    for cid in voice_map:
        if cid in name_lower or name_lower in cid:
            return cid
    # Default narrator
    return "narrateur"

tts_requests = []

# Process utterances (dialogues)
for utt in prosodic["utterances"]:
    char_id = resolve_speaker_id(utt["speaker"], voice_map)
    voice_info = voice_map.get(char_id, voice_map["narrateur"])
    tts_requests.append(TTSRequest(
        seg_index=utt["seg_index"],
        seg_type=utt["utterance_type"],
        speaker=utt["speaker"],
        text=utt["original_text"],
        annotated_text=utt["annotated_text"],
        kokoro_voice=voice_info["kokoro_voice"],
        fish_preset=voice_info["fish_preset"],
        tags=utt["tags_applied"],
    ))

# Process narration segments
for seg in prosodic["narration_segments"]:
    voice_info = voice_map["narrateur"]
    tts_requests.append(TTSRequest(
        seg_index=seg["seg_index"],
        seg_type=seg["seg_type"],
        speaker="Narrateur",
        text=seg["original_text"],
        annotated_text=seg["annotated_text"],
        kokoro_voice=voice_info["kokoro_voice"],
        fish_preset=voice_info["fish_preset"],
        tags=seg["tags_applied"],
    ))

# Sort by segment index
tts_requests.sort(key=lambda r: r.seg_index)

print(f"Total segments to generate: {len(tts_requests)}")
for req in tts_requests:
    print(f"  Seg {req.seg_index}: {req.seg_type:12s} | "
          f"{req.kokoro_voice:15s} | {req.speaker}")
Total segments to generate: 342
  Seg 0: narration    | bf_isabella     | Narrateur
  Seg 1: narration    | bf_isabella     | Narrateur
  Seg 2: narration    | bf_isabella     | Narrateur
  Seg 3: narration    | bf_isabella     | Narrateur
  Seg 4: narration    | bf_isabella     | Narrateur
  Seg 5: narration    | bf_isabella     | Narrateur
  Seg 6: narration    | bf_isabella     | Narrateur
  Seg 7: narration    | bf_isabella     | Narrateur
  Seg 8: narration    | bf_isabella     | Narrateur
  Seg 9: narration    | bf_isabella     | Narrateur
  Seg 10: narration    | bf_isabella     | Narrateur
  Seg 11: narration    | bf_isabella     | Narrateur
  Seg 12: narration    | bf_isabella     | Narrateur
  Seg 13: narration    | bf_isabella     | Narrateur
  Seg 14: narration    | bf_isabella     | Narrateur
  Seg 15: narration    | bf_isabella     | Narrateur
  Seg 16: narration    | bf_isabella     | Narrateur
  Seg 17: narration    | bf_isabella     | Narrateur
  Seg 18: narration    | bf_isabella     | Narrateur
  Seg 19: narration    | bf_isabella     | Narrateur
  Seg 20: narration    | bf_isabella     | Narrateur
  Seg 21: narration    | bf_isabella     | Narrateur
  Seg 22: narration    | bf_isabella     | Narrateur
  Seg 23: narration    | bf_isabella     | Narrateur
  Seg 24: narration    | bf_isabella     | Narrateur
  Seg 25: dialogue     | bf_isabella     | Narrateur (locuteur non résolu)
  Seg 26: narration    | bf_isabella     | Narrateur
  Seg 27: dialogue     | bf_isabella     | Narrateur (locuteur non résolu)
  Seg 28: narration    | bf_isabella     | Narrateur
  Seg 29: dialogue     | bf_isabella     | Narrateur (locuteur non résolu)
  Seg 30: narration    | bf_isabella     | Narrateur
  Seg 31: narration    | bf_isabella     | Narrateur
  Seg 32: narration    | bf_isabella     | Narrateur
  Seg 33: narration    | bf_isabella     | Narrateur
  Seg 34: narration    | bf_isabella     | Narrateur
  Seg 35: dialogue     | bf_isabella     | Narrateur (locuteur non résolu)
  Seg 36: narration    | bf_isabella     | Narrateur
  Seg 37: narration    | bf_isabella     | Narrateur
  Seg 38: narration    | bf_isabella     | Narrateur
  Seg 39: dialogue     | bf_isabella     | Narrateur (locuteur non résolu)
  Seg 40: narration    | bf_isabella     | Narrateur
  Seg 41: dialogue     | bf_isabella     | Narrateur (locuteur non résolu)
  Seg 42: narration    | bf_isabella     | Narrateur
  Seg 43: narration    | bf_isabella     | Narrateur
  Seg 44: narration    | bf_isabella     | Narrateur
  Seg 45: narration    | bf_isabella     | Narrateur
  Seg 46: narration    | bf_isabella     | Narrateur
  Seg 47: narration    | bf_isabella     | Narrateur
  Seg 48: narration    | bf_isabella     | Narrateur
  Seg 49: narration    | bf_isabella     | Narrateur
  Seg 50: dialogue     | bf_isabella     | Narrateur (locuteur non résolu)
  Seg 51: narration    | bf_isabella     | Narrateur
  Seg 52: narration    | bf_isabella     | Narrateur
  Seg 53: narration    | bf_isabella     | Narrateur
  Seg 54: narration    | bf_isabella     | Narrateur
  Seg 55: narration    | bf_isabella     | Narrateur
  Seg 56: narration    | bf_isabella     | Narrateur
  Seg 57: narration    | bf_isabella     | Narrateur
  Seg 58: narration    | bf_isabella     | Narrateur
  Seg 59: narration    | bf_isabella     | Narrateur
  Seg 60: narration    | bf_isabella     | Narrateur
  Seg 61: narration    | bf_isabella     | Narrateur
  Seg 62: narration    | bf_isabella     | Narrateur
  Seg 63: narration    | bf_isabella     | Narrateur
  Seg 64: narration    | bf_isabella     | Narrateur
  Seg 65: narration    | bf_isabella     | Narrateur
  Seg 66: narration    | bf_isabella     | Narrateur
  Seg 67: narration    | bf_isabella     | Narrateur
  Seg 68: narration    | bf_isabella     | Narrateur
  Seg 69: narration    | bf_isabella     | Narrateur
  Seg 70: narration    | bf_isabella     | Narrateur
  Seg 71: narration    | bf_isabella     | Narrateur
  Seg 72: narration    | bf_isabella     | Narrateur
  Seg 73: narration    | bf_isabella     | Narrateur
  Seg 74: narration    | bf_isabella     | Narrateur
  Seg 75: narration    | bf_isabella     | Narrateur
  Seg 76: dialogue     | bm_george       | Monsieur Loiseau
  Seg 77: narration    | bf_isabella     | Narrateur
  Seg 78: narration    | bf_isabella     | Narrateur
  Seg 79: narration    | bf_isabella     | Narrateur
  Seg 80: narration    | bf_isabella     | Narrateur
  Seg 81: narration    | bf_isabella     | Narrateur
  Seg 82: dialogue     | bm_george       | Monsieur Loiseau
  Seg 83: narration    | bf_isabella     | Narrateur
  Seg 84: dialogue     | bm_george       | Monsieur Loiseau
  Seg 85: narration    | bf_isabella     | Narrateur
  Seg 86: narration    | bf_isabella     | Narrateur
  Seg 87: narration    | bf_isabella     | Narrateur
  Seg 88: dialogue     | af_bella        | Mme Loiseau
  Seg 89: narration    | bf_isabella     | Narrateur
  Seg 90: dialogue     | af_bella        | Mme Loiseau
  Seg 91: narration    | bf_isabella     | Narrateur
  Seg 92: narration    | bf_isabella     | Narrateur
  Seg 93: narration    | bf_isabella     | Narrateur
  Seg 94: dialogue     | bf_emma         | Les bonnes soeurs
  Seg 95: narration    | bf_isabella     | Narrateur
  Seg 96: narration    | bf_isabella     | Narrateur
  Seg 97: dialogue     | bf_isabella     | Narrateur (locuteur non résolu)
  Seg 98: narration    | bf_isabella     | Narrateur
  Seg 99: narration    | bf_isabella     | Narrateur
  Seg 100: narration    | bf_isabella     | Narrateur
  Seg 101: narration    | bf_isabella     | Narrateur
  Seg 102: narration    | bf_isabella     | Narrateur
  Seg 103: narration    | bf_isabella     | Narrateur
  Seg 104: narration    | bf_isabella     | Narrateur
  Seg 105: narration    | bf_isabella     | Narrateur
  Seg 106: narration    | bf_isabella     | Narrateur
  Seg 107: narration    | bf_isabella     | Narrateur
  Seg 108: narration    | bf_isabella     | Narrateur
  Seg 109: narration    | bf_isabella     | Narrateur
  Seg 110: description  | bf_isabella     | Narrateur
  Seg 111: narration    | bf_isabella     | Narrateur
  Seg 112: dialogue     | bf_isabella     | Narrateur (locuteur non résolu)
  Seg 113: narration    | bf_isabella     | Narrateur
  Seg 114: dialogue     | am_michael      | Officier prussien
  Seg 115: narration    | bf_isabella     | Narrateur
  Seg 116: narration    | bf_isabella     | Narrateur
  Seg 117: narration    | bf_isabella     | Narrateur
  Seg 118: narration    | bf_isabella     | Narrateur
  Seg 119: dialogue     | bf_isabella     | Narrateur (locuteur non résolu)
  Seg 120: narration    | bf_isabella     | Narrateur
  Seg 121: narration    | bf_isabella     | Narrateur
  Seg 122: narration    | bf_isabella     | Narrateur
  Seg 123: narration    | bf_isabella     | Narrateur
  Seg 124: narration    | bf_isabella     | Narrateur
  Seg 125: narration    | bf_isabella     | Narrateur
  Seg 126: narration    | bf_isabella     | Narrateur
  Seg 127: narration    | bf_isabella     | Narrateur
  Seg 128: narration    | bf_isabella     | Narrateur
  Seg 129: narration    | bf_isabella     | Narrateur
  Seg 130: narration    | bf_isabella     | Narrateur
  Seg 131: narration    | bf_isabella     | Narrateur
  Seg 132: narration    | bf_isabella     | Narrateur
  Seg 133: narration    | bf_isabella     | Narrateur
  Seg 134: narration    | bf_isabella     | Narrateur
  Seg 135: narration    | bf_isabella     | Narrateur
  Seg 136: narration    | bf_isabella     | Narrateur
  Seg 137: narration    | bf_isabella     | Narrateur
  Seg 138: narration    | bf_isabella     | Narrateur
  Seg 139: narration    | bf_isabella     | Narrateur
  Seg 140: narration    | bf_isabella     | Narrateur
  Seg 141: dialogue     | bf_isabella     | Narrateur (locuteur non résolu)
  Seg 142: narration    | bf_isabella     | Narrateur
  Seg 143: dialogue     | bf_isabella     | Narrateur (locuteur non résolu)
  Seg 144: narration    | bf_isabella     | Narrateur
  Seg 145: narration    | bf_isabella     | Narrateur
  Seg 146: narration    | bf_isabella     | Narrateur
  Seg 147: narration    | bf_isabella     | Narrateur
  Seg 148: narration    | bf_isabella     | Narrateur
  Seg 149: narration    | bf_isabella     | Narrateur
  Seg 150: narration    | bf_isabella     | Narrateur
  Seg 151: narration    | bf_isabella     | Narrateur
  Seg 152: narration    | bf_isabella     | Narrateur
  Seg 153: narration    | bf_isabella     | Narrateur
  Seg 154: narration    | bf_isabella     | Narrateur
  Seg 155: narration    | bf_isabella     | Narrateur
  Seg 156: narration    | bf_isabella     | Narrateur
  Seg 157: narration    | bf_isabella     | Narrateur
  Seg 158: narration    | bf_isabella     | Narrateur
  Seg 159: narration    | bf_isabella     | Narrateur
  Seg 160: narration    | bf_isabella     | Narrateur
  Seg 161: narration    | bf_isabella     | Narrateur
  Seg 162: narration    | bf_isabella     | Narrateur
  Seg 163: narration    | bf_isabella     | Narrateur
  Seg 164: narration    | bf_isabella     | Narrateur
  Seg 165: narration    | bf_isabella     | Narrateur
  Seg 166: dialogue     | bm_george       | Monsieur Loiseau
  Seg 167: narration    | bf_isabella     | Narrateur
  Seg 168: narration    | bf_isabella     | Narrateur
  Seg 169: narration    | bf_isabella     | Narrateur
  Seg 170: dialogue     | bf_isabella     | Narrateur (locuteur non résolu)
  Seg 171: narration    | bf_isabella     | Narrateur
  Seg 172: narration    | bf_isabella     | Narrateur
  Seg 173: narration    | bf_isabella     | Narrateur
  Seg 174: narration    | bf_isabella     | Narrateur
  Seg 175: narration    | bf_isabella     | Narrateur
  Seg 176: narration    | bf_isabella     | Narrateur
  Seg 177: narration    | bf_isabella     | Narrateur
  Seg 178: narration    | bf_isabella     | Narrateur
  Seg 179: narration    | bf_isabella     | Narrateur
  Seg 180: narration    | bf_isabella     | Narrateur
  Seg 181: narration    | bf_isabella     | Narrateur
  Seg 182: narration    | bf_isabella     | Narrateur
  Seg 183: narration    | bf_isabella     | Narrateur
  Seg 184: narration    | bf_isabella     | Narrateur
  Seg 185: narration    | bf_isabella     | Narrateur
  Seg 186: narration    | bf_isabella     | Narrateur
  Seg 187: narration    | bf_isabella     | Narrateur
  Seg 188: narration    | bf_isabella     | Narrateur
  Seg 189: dialogue     | am_michael      | Officier prussien
  Seg 190: narration    | bf_isabella     | Narrateur
  Seg 191: narration    | bf_isabella     | Narrateur
  Seg 192: narration    | bf_isabella     | Narrateur
  Seg 193: narration    | bf_isabella     | Narrateur
  Seg 194: narration    | bf_isabella     | Narrateur
  Seg 195: narration    | bf_isabella     | Narrateur
  Seg 196: narration    | bf_isabella     | Narrateur
  Seg 197: narration    | bf_isabella     | Narrateur
  Seg 198: narration    | bf_isabella     | Narrateur
  Seg 199: narration    | bf_isabella     | Narrateur
  Seg 200: narration    | bf_isabella     | Narrateur
  Seg 201: narration    | bf_isabella     | Narrateur
  Seg 202: narration    | bf_isabella     | Narrateur
  Seg 203: narration    | bf_isabella     | Narrateur
  Seg 204: narration    | bf_isabella     | Narrateur
  Seg 205: narration    | bf_isabella     | Narrateur
  Seg 206: narration    | bf_isabella     | Narrateur
  Seg 207: narration    | bf_isabella     | Narrateur
  Seg 208: narration    | bf_isabella     | Narrateur
  Seg 209: narration    | bf_isabella     | Narrateur
  Seg 210: narration    | bf_isabella     | Narrateur
  Seg 211: narration    | bf_isabella     | Narrateur
  Seg 212: dialogue     | bf_isabella     | Narrateur (locuteur non résolu)
  Seg 213: narration    | bf_isabella     | Narrateur
  Seg 214: narration    | bf_isabella     | Narrateur
  Seg 215: narration    | bf_isabella     | Narrateur
  Seg 216: narration    | bf_isabella     | Narrateur
  Seg 217: narration    | bf_isabella     | Narrateur
  Seg 218: narration    | bf_isabella     | Narrateur
  Seg 219: narration    | bf_isabella     | Narrateur
  Seg 220: narration    | bf_isabella     | Narrateur
  Seg 221: narration    | bf_isabella     | Narrateur
  Seg 222: dialogue     | bm_george       | Comte Hubert de Breville
  Seg 223: narration    | bf_isabella     | Narrateur
  Seg 224: dialogue     | bm_george       | Comte Hubert de Breville
  Seg 225: narration    | bf_isabella     | Narrateur
  Seg 226: dialogue     | bm_george       | Comte Hubert de Breville
  Seg 227: narration    | bf_isabella     | Narrateur
  Seg 228: narration    | bf_isabella     | Narrateur
  Seg 229: narration    | bf_isabella     | Narrateur
  Seg 230: narration    | bf_isabella     | Narrateur
  Seg 231: narration    | bf_isabella     | Narrateur
  Seg 232: narration    | bf_isabella     | Narrateur
  Seg 233: narration    | bf_isabella     | Narrateur
  Seg 234: narration    | bf_isabella     | Narrateur
  Seg 235: narration    | bf_isabella     | Narrateur
  Seg 236: narration    | bf_isabella     | Narrateur
  Seg 237: narration    | bf_isabella     | Narrateur
  Seg 238: dialogue     | af_bella        | Mme Loiseau
  Seg 239: narration    | bf_isabella     | Narrateur
  Seg 240: narration    | bf_isabella     | Narrateur
  Seg 241: narration    | bf_isabella     | Narrateur
  Seg 242: narration    | bf_isabella     | Narrateur
  Seg 243: narration    | bf_isabella     | Narrateur
  Seg 244: narration    | bf_isabella     | Narrateur
  Seg 245: narration    | bf_isabella     | Narrateur
  Seg 246: narration    | bf_isabella     | Narrateur
  Seg 247: narration    | bf_isabella     | Narrateur
  Seg 248: dialogue     | bm_george       | Comte Hubert de Breville
  Seg 249: narration    | bf_isabella     | Narrateur
  Seg 250: narration    | bf_isabella     | Narrateur
  Seg 251: dialogue     | bf_isabella     | Narrateur (locuteur non résolu)
  Seg 252: narration    | bf_isabella     | Narrateur
  Seg 253: narration    | bf_isabella     | Narrateur
  Seg 254: narration    | bf_isabella     | Narrateur
  Seg 255: narration    | bf_isabella     | Narrateur
  Seg 256: narration    | bf_isabella     | Narrateur
  Seg 257: narration    | bf_isabella     | Narrateur
  Seg 258: narration    | bf_isabella     | Narrateur
  Seg 259: narration    | bf_isabella     | Narrateur
  Seg 260: dialogue     | bf_isabella     | Elisabeth Rousset
  Seg 261: narration    | bf_isabella     | Narrateur
  Seg 262: narration    | bf_isabella     | Narrateur
  Seg 263: narration    | bf_isabella     | Narrateur
  Seg 264: narration    | bf_isabella     | Narrateur
  Seg 265: narration    | bf_isabella     | Narrateur
  Seg 266: narration    | bf_isabella     | Narrateur
  Seg 267: narration    | bf_isabella     | Narrateur
  Seg 268: narration    | bf_isabella     | Narrateur
  Seg 269: narration    | bf_isabella     | Narrateur
  Seg 270: narration    | bf_isabella     | Narrateur
  Seg 271: narration    | bf_isabella     | Narrateur
  Seg 272: narration    | bf_isabella     | Narrateur
  Seg 273: narration    | bf_isabella     | Narrateur
  Seg 274: narration    | bf_isabella     | Narrateur
  Seg 275: narration    | bf_isabella     | Narrateur
  Seg 276: narration    | bf_isabella     | Narrateur
  Seg 277: narration    | bf_isabella     | Narrateur
  Seg 278: dialogue     | bm_george       | Monsieur Loiseau
  Seg 279: narration    | bf_isabella     | Narrateur
  Seg 280: narration    | bf_isabella     | Narrateur
  Seg 281: dialogue     | bf_isabella     | Narrateur (locuteur non résolu)
  Seg 282: narration    | bf_isabella     | Narrateur
  Seg 283: dialogue     | bf_isabella     | Narrateur (locuteur non résolu)
  Seg 284: narration    | bf_isabella     | Narrateur
  Seg 285: narration    | bf_isabella     | Narrateur
  Seg 286: dialogue     | bf_isabella     | Narrateur (locuteur non résolu)
  Seg 287: narration    | bf_isabella     | Narrateur
  Seg 288: dialogue     | bf_isabella     | Narrateur (locuteur non résolu)
  Seg 289: narration    | bf_isabella     | Narrateur
  Seg 290: narration    | bf_isabella     | Narrateur
  Seg 291: narration    | bf_isabella     | Narrateur
  Seg 292: narration    | bf_isabella     | Narrateur
  Seg 293: narration    | bf_isabella     | Narrateur
  Seg 294: narration    | bf_isabella     | Narrateur
  Seg 295: dialogue     | bm_george       | Monsieur Loiseau
  Seg 296: narration    | bf_isabella     | Narrateur
  Seg 297: narration    | bf_isabella     | Narrateur
  Seg 298: dialogue     | bm_george       | Comte Hubert de Breville
  Seg 299: narration    | bf_isabella     | Narrateur
  Seg 300: narration    | bf_isabella     | Narrateur
  Seg 301: narration    | bf_isabella     | Narrateur
  Seg 302: narration    | bf_isabella     | Narrateur
  Seg 303: narration    | bf_isabella     | Narrateur
  Seg 304: narration    | bf_isabella     | Narrateur
  Seg 305: narration    | bf_isabella     | Narrateur
  Seg 306: narration    | bf_isabella     | Narrateur
  Seg 307: narration    | bf_isabella     | Narrateur
  Seg 308: narration    | bf_isabella     | Narrateur
  Seg 309: narration    | bf_isabella     | Narrateur
  Seg 310: narration    | bf_isabella     | Narrateur
  Seg 311: narration    | bf_isabella     | Narrateur
  Seg 312: narration    | bf_isabella     | Narrateur
  Seg 313: narration    | bf_isabella     | Narrateur
  Seg 314: narration    | bf_isabella     | Narrateur
  Seg 315: narration    | bf_isabella     | Narrateur
  Seg 316: narration    | bf_isabella     | Narrateur
  Seg 317: dialogue     | af_bella        | Mme Loiseau
  Seg 318: narration    | bf_isabella     | Narrateur
  Seg 319: narration    | bf_isabella     | Narrateur
  Seg 320: narration    | bf_isabella     | Narrateur
  Seg 321: narration    | bf_isabella     | Narrateur
  Seg 322: narration    | bf_isabella     | Narrateur
  Seg 323: narration    | bf_isabella     | Narrateur
  Seg 324: narration    | bf_isabella     | Narrateur
  Seg 325: narration    | bf_isabella     | Narrateur
  Seg 326: narration    | bf_isabella     | Narrateur
  Seg 327: narration    | bf_isabella     | Narrateur
  Seg 328: narration    | bf_isabella     | Narrateur
  Seg 329: narration    | bf_isabella     | Narrateur
  Seg 330: narration    | bf_isabella     | Narrateur
  Seg 331: narration    | bf_isabella     | Narrateur
  Seg 332: narration    | bf_isabella     | Narrateur
  Seg 333: narration    | bf_isabella     | Narrateur
  Seg 334: narration    | bf_isabella     | Narrateur
  Seg 335: dialogue     | af_bella        | Mme Loiseau
  Seg 336: narration    | bf_isabella     | Narrateur
  Seg 337: narration    | bf_isabella     | Narrateur
  Seg 338: narration    | bf_isabella     | Narrateur
  Seg 339: narration    | bf_isabella     | Narrateur
  Seg 340: narration    | bf_isabella     | Narrateur
  Seg 341: narration    | bf_isabella     | Narrateur

Generation audio

Chaque segment est envoye a Kokoro TTS avec la voix correspondante. Les tags expressifs sont conserves dans le texte brut (Kokoro les ignore). Les fichiers audio sont sauvegardes en MP3 (format natif de Kokoro).

import struct

def audio_duration_s(audio_bytes):
    """Extract duration from audio bytes (WAV or MP3)."""
    if len(audio_bytes) < 12:
        return 0.0
    # WAV format (RIFF header)
    if audio_bytes[:4] == b'RIFF':
        channels = struct.unpack_from('<H', audio_bytes, 22)[0]
        sample_rate = struct.unpack_from('<I', audio_bytes, 24)[0]
        bits_per_sample = struct.unpack_from('<H', audio_bytes, 34)[0]
        data_size = struct.unpack_from('<I', audio_bytes, 40)[0]
        bytes_per_sample = bits_per_sample * channels // 8
        if bytes_per_sample == 0:
            return 0.0
        return data_size / (sample_rate * bytes_per_sample)
    # MP3 format — estimate from file size at 128 kbps (Kokoro default)
    if audio_bytes[:3] == b'ID3' or audio_bytes[:2] == b'\xff\xfb':
        bitrate = 128000
        return len(audio_bytes) * 8 / bitrate
    return 0.0

generated = []
t_start = time.time()
JOURNAL_EVERY = 25  # journal echantillonne : une ligne tous les 25 segments
cached_count = 0

for i, req in enumerate(tts_requests, start=1):
    # Use original text for Kokoro (strip tags for cleaner output)
    clean_text = req.text
    output_name = f"seg_{req.seg_index:02d}_{req.kokoro_voice}.mp3"
    output_path = TTS_OUTPUT_DIR / output_name

    # Cache disque : recharger un segment deja genere (>10 KB = audio valide),
    # meme politique que la generation FishAudio -- re-execution idempotente
    if output_path.exists() and output_path.stat().st_size > 10000:
        audio_data = output_path.read_bytes()
        req.output_file = str(output_path)
        req.duration_s = audio_duration_s(audio_data)
        req.file_size_kb = len(audio_data) / 1024
        req.status = "success"
        cached_count += 1
        if i % JOURNAL_EVERY == 0 or i == len(tts_requests):
            print(f"[{i}/{len(tts_requests)}] seg {req.seg_index} {req.kokoro_voice}: CACHED ({req.duration_s:.1f}s, {req.file_size_kb:.0f}KB)")
        generated.append(req)
        continue

    if i % JOURNAL_EVERY == 0 or i == len(tts_requests):
        print(f"[{i}/{len(tts_requests)}] generating seg {req.seg_index} ({req.kokoro_voice})...")
    audio_data = kokoro_tts(clean_text, req.kokoro_voice)

    if audio_data:
        with open(output_path, "wb") as f:
            f.write(audio_data)
        req.output_file = str(output_path)
        req.duration_s = audio_duration_s(audio_data)
        req.file_size_kb = len(audio_data) / 1024
        req.status = "success"
        if i % JOURNAL_EVERY == 0 or i == len(tts_requests):
            print(f"[{i}/{len(tts_requests)}] seg {req.seg_index} {req.kokoro_voice}: OK ({req.duration_s:.1f}s, {req.file_size_kb:.0f}KB)")
    else:
        req.status = "failed"
        print(f"[{i}/{len(tts_requests)}] seg {req.seg_index} {req.kokoro_voice}: FAILED")

    generated.append(req)
    time.sleep(0.2)  # Rate limit

elapsed = time.time() - t_start
success_count = sum(1 for r in generated if r.status == "success")
print(f"\nGenerated {success_count}/{len(generated)} segments in {elapsed:.1f}s "
      f"({cached_count} reloaded from disk cache, {success_count - cached_count} newly generated)")
[25/342] seg 24 bf_isabella: CACHED (24.3s, 379KB)
[50/342] seg 49 bf_isabella: CACHED (12.7s, 199KB)
[75/342] seg 74 bf_isabella: CACHED (43.9s, 687KB)
[100/342] seg 99 bf_isabella: CACHED (38.3s, 599KB)
[125/342] seg 124 bf_isabella: CACHED (3.0s, 47KB)
[150/342] seg 149 bf_isabella: CACHED (2.6s, 41KB)
[175/342] seg 174 bf_isabella: CACHED (1.4s, 22KB)
[200/342] seg 199 bf_isabella: CACHED (3.9s, 62KB)
[225/342] seg 224 bm_george: CACHED (3.4s, 53KB)
[250/342] seg 249 bf_isabella: CACHED (18.6s, 291KB)
[275/342] seg 274 bf_isabella: CACHED (3.1s, 48KB)
[300/342] seg 299 bf_isabella: CACHED (18.6s, 290KB)
[325/342] seg 324 bf_isabella: CACHED (9.6s, 150KB)
[342/342] seg 341 bf_isabella: CACHED (9.5s, 148KB)

Generated 342/342 segments in 1.7s (342 reloaded from disk cache, 0 newly generated)

Résultats de la generation

Tableau recapitulatif des 342 segments audio generes par Kokoro TTS (texte integral de « Boule de Suif »).

Bilan quantitatif (mesures verbatim issues des journaux de generation ci-dessus et du tableau recapitulatif de la cellule suivante)

Métrique Valeur Interprétation
Segments générés 342/342 (100 %) Aucune erreur API Kokoro sur ce corpus — pile locale stable
Durée totale audio 6129,7 s (~102 min) Audiobook complet de Boule de Suif, écoutable d’une traite
Re-génération 342/342 segments rechargés du cache disque tts_output/ en quelques secondes La génération à froid n’a lieu qu’au premier passage
Taille moyenne par segment ~280 KB MP3 128 kbps → ratio taille/durée ~15,6 KB/s cohérent (95 777 KB au total pour 102 min d’audio)
Voix distinctes utilisées 5 (bf_isabella, bm_george, af_bella, am_michael, bf_emma) Le routeur voix P2 attribue les voix de personnage aux dialogues ; le narrateur porte l’essentiel du texte (analyse detaillee ci-dessous)

Pourquoi ces résultats sont exploitables

La generation a reussi du premier coup pour les 342 segments parce que (a) Kokoro accepte les balises XML-style (<s>, <\|...\|>) qui delimitent les interlocuteurs dans le texte annote P3, (b) le rate-limit de 0.2 s evite de saturer la file de requêtes du service local (single-threaded), (c) le parsing WAV/MP3 implementé dans audio_duration_s recupere la duree reelle du buffer (pas une estimation). Si un segment echouait, son status resterait failed, output_file resterait vide, et la cellule suivante ignorerait ce segment.

Lecture pedagogique des résultats

La distribution des durees (1,7 s pour le seg 26 de 7 mots, 88,9 s pour le seg 11 de 202 mots) reflete directement la longueur des textes P3 : une replique courte tient en quelques secondes, un passage narratif dense depasse la minute. Le seg 1 (68,1 s, 143 mots) est le depart de la diligence dans la neige — un passage narratif dense typique de Maupassant, qui sert de banc d’essai naturel pour la prosodie Kokoro.

Suite logique

Les fichiers MP3 sont maintenant disponibles dans tts_output/, les metadonnees seront exportees dans la cellule suivante pour que P5 (Compilation audio) puisse les assembler en livre audio.

print(f"{'Seg':>4} | {'Type':12s} | {'Voice':15s} | {'Speaker':25s} | "
      f"{'Duration':>8s} | {'Size':>7s} | {'Status':>7s}")
print("-" * 100)
total_duration = 0.0
for req in generated:
    dur = f"{req.duration_s:.1f}s" if req.status == "success" else "N/A"
    size = f"{req.file_size_kb:.0f}KB" if req.status == "success" else "N/A"
    print(f"{req.seg_index:>4} | {req.seg_type:12s} | {req.kokoro_voice:15s} | "
          f"{req.speaker:25s} | {dur:>8s} | {size:>7s} | {req.status:>7s}")
    if req.status == "success":
        total_duration += req.duration_s

print(f"\nTotal duration: {total_duration:.1f}s ({total_duration/60:.1f}min)")
print(f"Output directory: {TTS_OUTPUT_DIR.name}")
 Seg | Type         | Voice           | Speaker                   | Duration |    Size |  Status
----------------------------------------------------------------------------------------------------
   0 | narration    | bf_isabella     | Narrateur                 |     2.2s |    35KB | success
   1 | narration    | bf_isabella     | Narrateur                 |    68.1s |  1064KB | success
   2 | narration    | bf_isabella     | Narrateur                 |    13.8s |   215KB | success
   3 | narration    | bf_isabella     | Narrateur                 |    36.9s |   576KB | success
   4 | narration    | bf_isabella     | Narrateur                 |     4.2s |    65KB | success
   5 | narration    | bf_isabella     | Narrateur                 |    32.1s |   502KB | success
   6 | narration    | bf_isabella     | Narrateur                 |    29.4s |   459KB | success
   7 | narration    | bf_isabella     | Narrateur                 |    21.5s |   336KB | success
   8 | narration    | bf_isabella     | Narrateur                 |    12.4s |   194KB | success
   9 | narration    | bf_isabella     | Narrateur                 |     4.8s |    75KB | success
  10 | narration    | bf_isabella     | Narrateur                 |    41.0s |   640KB | success
  11 | narration    | bf_isabella     | Narrateur                 |    88.9s |  1389KB | success
  12 | narration    | bf_isabella     | Narrateur                 |    16.5s |   258KB | success
  13 | narration    | bf_isabella     | Narrateur                 |    78.2s |  1222KB | success
  14 | narration    | bf_isabella     | Narrateur                 |    30.5s |   476KB | success
  15 | narration    | bf_isabella     | Narrateur                 |    24.9s |   390KB | success
  16 | narration    | bf_isabella     | Narrateur                 |    19.9s |   311KB | success
  17 | narration    | bf_isabella     | Narrateur                 |    40.4s |   631KB | success
  18 | narration    | bf_isabella     | Narrateur                 |     7.0s |   110KB | success
  19 | narration    | bf_isabella     | Narrateur                 |    34.7s |   543KB | success
  20 | narration    | bf_isabella     | Narrateur                 |    11.3s |   176KB | success
  21 | narration    | bf_isabella     | Narrateur                 |    17.1s |   267KB | success
  22 | narration    | bf_isabella     | Narrateur                 |    16.4s |   256KB | success
  23 | narration    | bf_isabella     | Narrateur                 |    10.0s |   156KB | success
  24 | narration    | bf_isabella     | Narrateur                 |    24.3s |   379KB | success
  25 | dialogue     | bf_isabella     | Narrateur (locuteur non résolu) |     3.1s |    49KB | success
  26 | narration    | bf_isabella     | Narrateur                 |     1.7s |    27KB | success
  27 | dialogue     | bf_isabella     | Narrateur (locuteur non résolu) |     3.1s |    48KB | success
  28 | narration    | bf_isabella     | Narrateur                 |     3.0s |    47KB | success
  29 | dialogue     | bf_isabella     | Narrateur (locuteur non résolu) |     8.0s |   125KB | success
  30 | narration    | bf_isabella     | Narrateur                 |     5.8s |    90KB | success
  31 | narration    | bf_isabella     | Narrateur                 |    44.1s |   690KB | success
  32 | narration    | bf_isabella     | Narrateur                 |     9.3s |   145KB | success
  33 | narration    | bf_isabella     | Narrateur                 |    31.3s |   488KB | success
  34 | narration    | bf_isabella     | Narrateur                 |    28.4s |   443KB | success
  35 | dialogue     | bf_isabella     | Narrateur (locuteur non résolu) |     6.3s |    98KB | success
  36 | narration    | bf_isabella     | Narrateur                 |    19.4s |   303KB | success
  37 | narration    | bf_isabella     | Narrateur                 |    23.7s |   370KB | success
  38 | narration    | bf_isabella     | Narrateur                 |     9.2s |   144KB | success
  39 | dialogue     | bf_isabella     | Narrateur (locuteur non résolu) |     3.9s |    60KB | success
  40 | narration    | bf_isabella     | Narrateur                 |     3.0s |    46KB | success
  41 | dialogue     | bf_isabella     | Narrateur (locuteur non résolu) |     1.3s |    20KB | success
  42 | narration    | bf_isabella     | Narrateur                 |     1.7s |    26KB | success
  43 | narration    | bf_isabella     | Narrateur                 |    31.1s |   486KB | success
  44 | narration    | bf_isabella     | Narrateur                 |    29.0s |   454KB | success
  45 | narration    | bf_isabella     | Narrateur                 |     6.7s |   105KB | success
  46 | narration    | bf_isabella     | Narrateur                 |    11.5s |   180KB | success
  47 | narration    | bf_isabella     | Narrateur                 |    23.6s |   369KB | success
  48 | narration    | bf_isabella     | Narrateur                 |    29.6s |   463KB | success
  49 | narration    | bf_isabella     | Narrateur                 |    12.7s |   199KB | success
  50 | dialogue     | bf_isabella     | Narrateur (locuteur non résolu) |     2.8s |    44KB | success
  51 | narration    | bf_isabella     | Narrateur                 |     9.0s |   141KB | success
  52 | narration    | bf_isabella     | Narrateur                 |    13.2s |   206KB | success
  53 | narration    | bf_isabella     | Narrateur                 |    42.1s |   658KB | success
  54 | narration    | bf_isabella     | Narrateur                 |    13.0s |   203KB | success
  55 | narration    | bf_isabella     | Narrateur                 |    33.0s |   516KB | success
  56 | narration    | bf_isabella     | Narrateur                 |    36.8s |   575KB | success
  57 | narration    | bf_isabella     | Narrateur                 |     7.9s |   123KB | success
  58 | narration    | bf_isabella     | Narrateur                 |    13.1s |   205KB | success
  59 | narration    | bf_isabella     | Narrateur                 |    37.3s |   583KB | success
  60 | narration    | bf_isabella     | Narrateur                 |     7.0s |   109KB | success
  61 | narration    | bf_isabella     | Narrateur                 |    75.7s |  1184KB | success
  62 | narration    | bf_isabella     | Narrateur                 |     8.8s |   138KB | success
  63 | narration    | bf_isabella     | Narrateur                 |    52.8s |   824KB | success
  64 | narration    | bf_isabella     | Narrateur                 |     5.0s |    78KB | success
  65 | narration    | bf_isabella     | Narrateur                 |    27.3s |   426KB | success
  66 | narration    | bf_isabella     | Narrateur                 |    23.7s |   370KB | success
  67 | narration    | bf_isabella     | Narrateur                 |    58.0s |   906KB | success
  68 | narration    | bf_isabella     | Narrateur                 |    18.4s |   287KB | success
  69 | narration    | bf_isabella     | Narrateur                 |    31.7s |   495KB | success
  70 | narration    | bf_isabella     | Narrateur                 |    15.3s |   239KB | success
  71 | narration    | bf_isabella     | Narrateur                 |    21.7s |   340KB | success
  72 | narration    | bf_isabella     | Narrateur                 |    18.4s |   287KB | success
  73 | narration    | bf_isabella     | Narrateur                 |    21.1s |   330KB | success
  74 | narration    | bf_isabella     | Narrateur                 |    43.9s |   687KB | success
  75 | narration    | bf_isabella     | Narrateur                 |    12.7s |   199KB | success
  76 | dialogue     | bm_george       | Monsieur Loiseau          |     5.5s |    87KB | success
  77 | narration    | bf_isabella     | Narrateur                 |    36.0s |   563KB | success
  78 | narration    | bf_isabella     | Narrateur                 |    16.1s |   252KB | success
  79 | narration    | bf_isabella     | Narrateur                 |    43.7s |   683KB | success
  80 | narration    | bf_isabella     | Narrateur                 |    28.0s |   438KB | success
  81 | narration    | bf_isabella     | Narrateur                 |     4.4s |    69KB | success
  82 | dialogue     | bm_george       | Monsieur Loiseau          |     9.8s |   153KB | success
  83 | narration    | bf_isabella     | Narrateur                 |    19.7s |   308KB | success
  84 | dialogue     | bm_george       | Monsieur Loiseau          |     7.5s |   117KB | success
  85 | narration    | bf_isabella     | Narrateur                 |    22.3s |   349KB | success
  86 | narration    | bf_isabella     | Narrateur                 |    29.3s |   458KB | success
  87 | narration    | bf_isabella     | Narrateur                 |    26.4s |   413KB | success
  88 | dialogue     | af_bella        | Mme Loiseau               |     2.1s |    33KB | success
  89 | narration    | bf_isabella     | Narrateur                 |     6.2s |    96KB | success
  90 | dialogue     | af_bella        | Mme Loiseau               |     2.9s |    45KB | success
  91 | narration    | bf_isabella     | Narrateur                 |     4.0s |    62KB | success
  92 | narration    | bf_isabella     | Narrateur                 |    19.0s |   297KB | success
  93 | narration    | bf_isabella     | Narrateur                 |    66.1s |  1033KB | success
  94 | dialogue     | bf_emma         | Les bonnes soeurs         |     2.7s |    42KB | success
  95 | narration    | bf_isabella     | Narrateur                 |    43.6s |   681KB | success
  96 | narration    | bf_isabella     | Narrateur                 |     9.2s |   143KB | success
  97 | dialogue     | bf_isabella     | Narrateur (locuteur non résolu) |     4.5s |    70KB | success
  98 | narration    | bf_isabella     | Narrateur                 |    27.8s |   435KB | success
  99 | narration    | bf_isabella     | Narrateur                 |    38.3s |   599KB | success
 100 | narration    | bf_isabella     | Narrateur                 |    91.4s |  1428KB | success
 101 | narration    | bf_isabella     | Narrateur                 |    42.9s |   670KB | success
 102 | narration    | bf_isabella     | Narrateur                 |    72.0s |  1125KB | success
 103 | narration    | bf_isabella     | Narrateur                 |    15.3s |   239KB | success
 104 | narration    | bf_isabella     | Narrateur                 |    31.1s |   485KB | success
 105 | narration    | bf_isabella     | Narrateur                 |    17.7s |   277KB | success
 106 | narration    | bf_isabella     | Narrateur                 |    19.3s |   302KB | success
 107 | narration    | bf_isabella     | Narrateur                 |    21.7s |   340KB | success
 108 | narration    | bf_isabella     | Narrateur                 |    13.5s |   211KB | success
 109 | narration    | bf_isabella     | Narrateur                 |    26.3s |   411KB | success
 110 | description  | bf_isabella     | Narrateur                 |    39.2s |   612KB | success
 111 | narration    | bf_isabella     | Narrateur                 |     6.8s |   107KB | success
 112 | dialogue     | bf_isabella     | Narrateur (locuteur non résolu) |     3.5s |    55KB | success
 113 | narration    | bf_isabella     | Narrateur                 |    23.1s |   362KB | success
 114 | dialogue     | am_michael      | Officier prussien         |     2.0s |    31KB | success
 115 | narration    | bf_isabella     | Narrateur                 |    10.8s |   169KB | success
 116 | narration    | bf_isabella     | Narrateur                 |    47.9s |   748KB | success
 117 | narration    | bf_isabella     | Narrateur                 |    22.7s |   355KB | success
 118 | narration    | bf_isabella     | Narrateur                 |     2.6s |    41KB | success
 119 | dialogue     | bf_isabella     | Narrateur (locuteur non résolu) |     1.4s |    22KB | success
 120 | narration    | bf_isabella     | Narrateur                 |     2.2s |    35KB | success
 121 | narration    | bf_isabella     | Narrateur                 |    23.0s |   359KB | success
 122 | narration    | bf_isabella     | Narrateur                 |    20.8s |   325KB | success
 123 | narration    | bf_isabella     | Narrateur                 |     1.8s |    28KB | success
 124 | narration    | bf_isabella     | Narrateur                 |     3.0s |    47KB | success
 125 | narration    | bf_isabella     | Narrateur                 |     3.2s |    50KB | success
 126 | narration    | bf_isabella     | Narrateur                 |     1.6s |    25KB | success
 127 | narration    | bf_isabella     | Narrateur                 |     5.0s |    78KB | success
 128 | narration    | bf_isabella     | Narrateur                 |     1.5s |    23KB | success
 129 | narration    | bf_isabella     | Narrateur                 |     4.4s |    69KB | success
 130 | narration    | bf_isabella     | Narrateur                 |     5.1s |    79KB | success
 131 | narration    | bf_isabella     | Narrateur                 |     3.0s |    47KB | success
 132 | narration    | bf_isabella     | Narrateur                 |     8.1s |   127KB | success
 133 | narration    | bf_isabella     | Narrateur                 |    24.0s |   375KB | success
 134 | narration    | bf_isabella     | Narrateur                 |    14.9s |   233KB | success
 135 | narration    | bf_isabella     | Narrateur                 |     3.3s |    51KB | success
 136 | narration    | bf_isabella     | Narrateur                 |     2.9s |    45KB | success
 137 | narration    | bf_isabella     | Narrateur                 |     2.6s |    41KB | success
 138 | narration    | bf_isabella     | Narrateur                 |     3.9s |    60KB | success
 139 | narration    | bf_isabella     | Narrateur                 |    13.5s |   211KB | success
 140 | narration    | bf_isabella     | Narrateur                 |     7.7s |   121KB | success
 141 | dialogue     | bf_isabella     | Narrateur (locuteur non résolu) |     2.5s |    38KB | success
 142 | narration    | bf_isabella     | Narrateur                 |     9.1s |   143KB | success
 143 | dialogue     | bf_isabella     | Narrateur (locuteur non résolu) |     5.2s |    82KB | success
 144 | narration    | bf_isabella     | Narrateur                 |    68.1s |  1064KB | success
 145 | narration    | bf_isabella     | Narrateur                 |    37.1s |   580KB | success
 146 | narration    | bf_isabella     | Narrateur                 |     8.2s |   128KB | success
 147 | narration    | bf_isabella     | Narrateur                 |     7.6s |   119KB | success
 148 | narration    | bf_isabella     | Narrateur                 |    97.6s |  1524KB | success
 149 | narration    | bf_isabella     | Narrateur                 |     2.6s |    41KB | success
 150 | narration    | bf_isabella     | Narrateur                 |     8.6s |   135KB | success
 151 | narration    | bf_isabella     | Narrateur                 |     2.8s |    44KB | success
 152 | narration    | bf_isabella     | Narrateur                 |     9.6s |   150KB | success
 153 | narration    | bf_isabella     | Narrateur                 |     2.9s |    45KB | success
 154 | narration    | bf_isabella     | Narrateur                 |     2.5s |    40KB | success
 155 | narration    | bf_isabella     | Narrateur                 |    27.7s |   433KB | success
 156 | narration    | bf_isabella     | Narrateur                 |    20.1s |   314KB | success
 157 | narration    | bf_isabella     | Narrateur                 |     5.0s |    78KB | success
 158 | narration    | bf_isabella     | Narrateur                 |    67.9s |  1062KB | success
 159 | narration    | bf_isabella     | Narrateur                 |     3.7s |    58KB | success
 160 | narration    | bf_isabella     | Narrateur                 |     3.4s |    53KB | success
 161 | narration    | bf_isabella     | Narrateur                 |     8.9s |   139KB | success
 162 | narration    | bf_isabella     | Narrateur                 |     8.0s |   125KB | success
 163 | narration    | bf_isabella     | Narrateur                 |     8.8s |   137KB | success
 164 | narration    | bf_isabella     | Narrateur                 |    16.8s |   262KB | success
 165 | narration    | bf_isabella     | Narrateur                 |    14.4s |   225KB | success
 166 | dialogue     | bm_george       | Monsieur Loiseau          |     2.1s |    33KB | success
 167 | narration    | bf_isabella     | Narrateur                 |    22.8s |   356KB | success
 168 | narration    | bf_isabella     | Narrateur                 |    76.1s |  1189KB | success
 169 | narration    | bf_isabella     | Narrateur                 |     7.9s |   123KB | success
 170 | dialogue     | bf_isabella     | Narrateur (locuteur non résolu) |    42.0s |   656KB | success
 171 | narration    | bf_isabella     | Narrateur                 |    29.6s |   462KB | success
 172 | narration    | bf_isabella     | Narrateur                 |     4.8s |    75KB | success
 173 | narration    | bf_isabella     | Narrateur                 |     4.5s |    70KB | success
 174 | narration    | bf_isabella     | Narrateur                 |     1.4s |    22KB | success
 175 | narration    | bf_isabella     | Narrateur                 |     2.5s |    39KB | success
 176 | narration    | bf_isabella     | Narrateur                 |     3.0s |    47KB | success
 177 | narration    | bf_isabella     | Narrateur                 |     2.9s |    46KB | success
 178 | narration    | bf_isabella     | Narrateur                 |     1.4s |    21KB | success
 179 | narration    | bf_isabella     | Narrateur                 |     7.7s |   120KB | success
 180 | narration    | bf_isabella     | Narrateur                 |     2.8s |    44KB | success
 181 | narration    | bf_isabella     | Narrateur                 |     4.8s |    75KB | success
 182 | narration    | bf_isabella     | Narrateur                 |     1.6s |    26KB | success
 183 | narration    | bf_isabella     | Narrateur                 |     6.6s |   102KB | success
 184 | narration    | bf_isabella     | Narrateur                 |    16.9s |   265KB | success
 185 | narration    | bf_isabella     | Narrateur                 |    19.9s |   311KB | success
 186 | narration    | bf_isabella     | Narrateur                 |    56.4s |   881KB | success
 187 | narration    | bf_isabella     | Narrateur                 |    39.1s |   611KB | success
 188 | narration    | bf_isabella     | Narrateur                 |    13.4s |   209KB | success
 189 | dialogue     | am_michael      | Officier prussien         |    13.6s |   213KB | success
 190 | narration    | bf_isabella     | Narrateur                 |    18.8s |   294KB | success
 191 | narration    | bf_isabella     | Narrateur                 |     9.9s |   154KB | success
 192 | narration    | bf_isabella     | Narrateur                 |     5.2s |    81KB | success
 193 | narration    | bf_isabella     | Narrateur                 |    55.7s |   870KB | success
 194 | narration    | bf_isabella     | Narrateur                 |     3.4s |    53KB | success
 195 | narration    | bf_isabella     | Narrateur                 |     2.6s |    40KB | success
 196 | narration    | bf_isabella     | Narrateur                 |     2.5s |    39KB | success
 197 | narration    | bf_isabella     | Narrateur                 |     2.8s |    44KB | success
 198 | narration    | bf_isabella     | Narrateur                 |     1.4s |    21KB | success
 199 | narration    | bf_isabella     | Narrateur                 |     3.9s |    62KB | success
 200 | narration    | bf_isabella     | Narrateur                 |     2.5s |    38KB | success
 201 | narration    | bf_isabella     | Narrateur                 |    15.0s |   235KB | success
 202 | narration    | bf_isabella     | Narrateur                 |     4.0s |    62KB | success
 203 | narration    | bf_isabella     | Narrateur                 |     4.2s |    66KB | success
 204 | narration    | bf_isabella     | Narrateur                 |    78.8s |  1231KB | success
 205 | narration    | bf_isabella     | Narrateur                 |    16.9s |   264KB | success
 206 | narration    | bf_isabella     | Narrateur                 |    14.5s |   227KB | success
 207 | narration    | bf_isabella     | Narrateur                 |    22.7s |   355KB | success
 208 | narration    | bf_isabella     | Narrateur                 |    64.6s |  1010KB | success
 209 | narration    | bf_isabella     | Narrateur                 |     7.4s |   116KB | success
 210 | narration    | bf_isabella     | Narrateur                 |    47.9s |   749KB | success
 211 | narration    | bf_isabella     | Narrateur                 |    19.3s |   302KB | success
 212 | dialogue     | bf_isabella     | Narrateur (locuteur non résolu) |     4.6s |    72KB | success
 213 | narration    | bf_isabella     | Narrateur                 |    11.8s |   184KB | success
 214 | narration    | bf_isabella     | Narrateur                 |    13.2s |   206KB | success
 215 | narration    | bf_isabella     | Narrateur                 |     9.8s |   153KB | success
 216 | narration    | bf_isabella     | Narrateur                 |    37.9s |   592KB | success
 217 | narration    | bf_isabella     | Narrateur                 |     4.0s |    62KB | success
 218 | narration    | bf_isabella     | Narrateur                 |    23.2s |   363KB | success
 219 | narration    | bf_isabella     | Narrateur                 |    23.2s |   362KB | success
 220 | narration    | bf_isabella     | Narrateur                 |     6.2s |    97KB | success
 221 | narration    | bf_isabella     | Narrateur                 |     4.7s |    73KB | success
 222 | dialogue     | bm_george       | Comte Hubert de Breville  |     1.4s |    23KB | success
 223 | narration    | bf_isabella     | Narrateur                 |    29.1s |   455KB | success
 224 | dialogue     | bm_george       | Comte Hubert de Breville  |     3.4s |    53KB | success
 225 | narration    | bf_isabella     | Narrateur                 |     3.3s |    52KB | success
 226 | dialogue     | bm_george       | Comte Hubert de Breville  |    12.8s |   200KB | success
 227 | narration    | bf_isabella     | Narrateur                 |     2.7s |    42KB | success
 228 | narration    | bf_isabella     | Narrateur                 |     6.8s |   107KB | success
 229 | narration    | bf_isabella     | Narrateur                 |    20.8s |   325KB | success
 230 | narration    | bf_isabella     | Narrateur                 |    14.7s |   229KB | success
 231 | narration    | bf_isabella     | Narrateur                 |    16.6s |   259KB | success
 232 | narration    | bf_isabella     | Narrateur                 |    22.5s |   351KB | success
 233 | narration    | bf_isabella     | Narrateur                 |    17.3s |   270KB | success
 234 | narration    | bf_isabella     | Narrateur                 |     9.4s |   147KB | success
 235 | narration    | bf_isabella     | Narrateur                 |    23.9s |   374KB | success
 236 | narration    | bf_isabella     | Narrateur                 |    38.2s |   597KB | success
 237 | narration    | bf_isabella     | Narrateur                 |     4.4s |    69KB | success
 238 | dialogue     | af_bella        | Mme Loiseau               |    60.7s |   948KB | success
 239 | narration    | bf_isabella     | Narrateur                 |     5.1s |    80KB | success
 240 | narration    | bf_isabella     | Narrateur                 |    13.1s |   205KB | success
 241 | narration    | bf_isabella     | Narrateur                 |    22.2s |   346KB | success
 242 | narration    | bf_isabella     | Narrateur                 |     2.3s |    36KB | success
 243 | narration    | bf_isabella     | Narrateur                 |    50.5s |   789KB | success
 244 | narration    | bf_isabella     | Narrateur                 |    38.3s |   599KB | success
 245 | narration    | bf_isabella     | Narrateur                 |    24.6s |   385KB | success
 246 | narration    | bf_isabella     | Narrateur                 |     6.2s |    96KB | success
 247 | narration    | bf_isabella     | Narrateur                 |     8.9s |   139KB | success
 248 | dialogue     | bm_george       | Comte Hubert de Breville  |     1.2s |    19KB | success
 249 | narration    | bf_isabella     | Narrateur                 |    18.6s |   291KB | success
 250 | narration    | bf_isabella     | Narrateur                 |     9.1s |   143KB | success
 251 | dialogue     | bf_isabella     | Narrateur (locuteur non résolu) |     4.0s |    62KB | success
 252 | narration    | bf_isabella     | Narrateur                 |    11.0s |   171KB | success
 253 | narration    | bf_isabella     | Narrateur                 |    60.1s |   939KB | success
 254 | narration    | bf_isabella     | Narrateur                 |    18.2s |   284KB | success
 255 | narration    | bf_isabella     | Narrateur                 |    10.9s |   170KB | success
 256 | narration    | bf_isabella     | Narrateur                 |    21.5s |   335KB | success
 257 | narration    | bf_isabella     | Narrateur                 |    23.9s |   374KB | success
 258 | narration    | bf_isabella     | Narrateur                 |    14.2s |   222KB | success
 259 | narration    | bf_isabella     | Narrateur                 |     2.9s |    46KB | success
 260 | dialogue     | bf_isabella     | Elisabeth Rousset         |     1.9s |    29KB | success
 261 | narration    | bf_isabella     | Narrateur                 |    82.0s |  1281KB | success
 262 | narration    | bf_isabella     | Narrateur                 |    28.7s |   449KB | success
 263 | narration    | bf_isabella     | Narrateur                 |     2.2s |    34KB | success
 264 | narration    | bf_isabella     | Narrateur                 |     7.7s |   120KB | success
 265 | narration    | bf_isabella     | Narrateur                 |     8.7s |   135KB | success
 266 | narration    | bf_isabella     | Narrateur                 |    12.5s |   195KB | success
 267 | narration    | bf_isabella     | Narrateur                 |    87.6s |  1368KB | success
 268 | narration    | bf_isabella     | Narrateur                 |     4.6s |    72KB | success
 269 | narration    | bf_isabella     | Narrateur                 |     9.9s |   155KB | success
 270 | narration    | bf_isabella     | Narrateur                 |     8.0s |   125KB | success
 271 | narration    | bf_isabella     | Narrateur                 |    12.6s |   197KB | success
 272 | narration    | bf_isabella     | Narrateur                 |    19.4s |   303KB | success
 273 | narration    | bf_isabella     | Narrateur                 |    17.6s |   276KB | success
 274 | narration    | bf_isabella     | Narrateur                 |     3.1s |    48KB | success
 275 | narration    | bf_isabella     | Narrateur                 |    28.7s |   448KB | success
 276 | narration    | bf_isabella     | Narrateur                 |    14.9s |   233KB | success
 277 | narration    | bf_isabella     | Narrateur                 |    35.8s |   560KB | success
 278 | dialogue     | bm_george       | Monsieur Loiseau          |     6.1s |    96KB | success
 279 | narration    | bf_isabella     | Narrateur                 |    26.7s |   417KB | success
 280 | narration    | bf_isabella     | Narrateur                 |    12.2s |   191KB | success
 281 | dialogue     | bf_isabella     | Narrateur (locuteur non résolu) |     1.2s |    19KB | success
 282 | narration    | bf_isabella     | Narrateur                 |     7.7s |   120KB | success
 283 | dialogue     | bf_isabella     | Narrateur (locuteur non résolu) |     2.9s |    45KB | success
 284 | narration    | bf_isabella     | Narrateur                 |     4.7s |    74KB | success
 285 | narration    | bf_isabella     | Narrateur                 |    27.6s |   432KB | success
 286 | dialogue     | bf_isabella     | Narrateur (locuteur non résolu) |     2.3s |    36KB | success
 287 | narration    | bf_isabella     | Narrateur                 |    11.2s |   175KB | success
 288 | dialogue     | bf_isabella     | Narrateur (locuteur non résolu) |     6.3s |    99KB | success
 289 | narration    | bf_isabella     | Narrateur                 |    18.4s |   288KB | success
 290 | narration    | bf_isabella     | Narrateur                 |    24.2s |   379KB | success
 291 | narration    | bf_isabella     | Narrateur                 |    27.8s |   434KB | success
 292 | narration    | bf_isabella     | Narrateur                 |     3.1s |    48KB | success
 293 | narration    | bf_isabella     | Narrateur                 |     6.3s |    98KB | success
 294 | narration    | bf_isabella     | Narrateur                 |    23.7s |   370KB | success
 295 | dialogue     | bm_george       | Monsieur Loiseau          |     5.8s |    91KB | success
 296 | narration    | bf_isabella     | Narrateur                 |    18.6s |   291KB | success
 297 | narration    | bf_isabella     | Narrateur                 |    10.3s |   161KB | success
 298 | dialogue     | bm_george       | Comte Hubert de Breville  |     5.0s |    78KB | success
 299 | narration    | bf_isabella     | Narrateur                 |    18.6s |   290KB | success
 300 | narration    | bf_isabella     | Narrateur                 |     3.2s |    50KB | success
 301 | narration    | bf_isabella     | Narrateur                 |     2.7s |    42KB | success
 302 | narration    | bf_isabella     | Narrateur                 |     2.3s |    36KB | success
 303 | narration    | bf_isabella     | Narrateur                 |     4.0s |    63KB | success
 304 | narration    | bf_isabella     | Narrateur                 |     1.7s |    27KB | success
 305 | narration    | bf_isabella     | Narrateur                 |     2.1s |    33KB | success
 306 | narration    | bf_isabella     | Narrateur                 |     7.4s |   116KB | success
 307 | narration    | bf_isabella     | Narrateur                 |     5.9s |    92KB | success
 308 | narration    | bf_isabella     | Narrateur                 |     4.0s |    62KB | success
 309 | narration    | bf_isabella     | Narrateur                 |    27.7s |   433KB | success
 310 | narration    | bf_isabella     | Narrateur                 |    27.9s |   435KB | success
 311 | narration    | bf_isabella     | Narrateur                 |    28.1s |   438KB | success
 312 | narration    | bf_isabella     | Narrateur                 |    13.3s |   207KB | success
 313 | narration    | bf_isabella     | Narrateur                 |     3.9s |    61KB | success
 314 | narration    | bf_isabella     | Narrateur                 |    19.3s |   302KB | success
 315 | narration    | bf_isabella     | Narrateur                 |    39.1s |   610KB | success
 316 | narration    | bf_isabella     | Narrateur                 |    10.0s |   156KB | success
 317 | dialogue     | af_bella        | Mme Loiseau               |     3.4s |    53KB | success
 318 | narration    | bf_isabella     | Narrateur                 |    23.2s |   363KB | success
 319 | narration    | bf_isabella     | Narrateur                 |     7.5s |   117KB | success
 320 | narration    | bf_isabella     | Narrateur                 |     3.7s |    57KB | success
 321 | narration    | bf_isabella     | Narrateur                 |     2.6s |    41KB | success
 322 | narration    | bf_isabella     | Narrateur                 |     2.3s |    36KB | success
 323 | narration    | bf_isabella     | Narrateur                 |    11.2s |   174KB | success
 324 | narration    | bf_isabella     | Narrateur                 |     9.6s |   150KB | success
 325 | narration    | bf_isabella     | Narrateur                 |    11.9s |   186KB | success
 326 | narration    | bf_isabella     | Narrateur                 |    27.2s |   425KB | success
 327 | narration    | bf_isabella     | Narrateur                 |     2.7s |    42KB | success
 328 | narration    | bf_isabella     | Narrateur                 |     6.7s |   105KB | success
 329 | narration    | bf_isabella     | Narrateur                 |    12.9s |   201KB | success
 330 | narration    | bf_isabella     | Narrateur                 |    37.8s |   590KB | success
 331 | narration    | bf_isabella     | Narrateur                 |    32.4s |   506KB | success
 332 | narration    | bf_isabella     | Narrateur                 |    28.2s |   440KB | success
 333 | narration    | bf_isabella     | Narrateur                 |    69.8s |  1091KB | success
 334 | narration    | bf_isabella     | Narrateur                 |    14.2s |   222KB | success
 335 | dialogue     | af_bella        | Mme Loiseau               |     3.2s |    50KB | success
 336 | narration    | bf_isabella     | Narrateur                 |     8.9s |   139KB | success
 337 | narration    | bf_isabella     | Narrateur                 |    17.2s |   269KB | success
 338 | narration    | bf_isabella     | Narrateur                 |    22.5s |   352KB | success
 339 | narration    | bf_isabella     | Narrateur                 |    11.5s |   180KB | success
 340 | narration    | bf_isabella     | Narrateur                 |    31.9s |   499KB | success
 341 | narration    | bf_isabella     | Narrateur                 |     9.5s |   148KB | success

Total duration: 6129.7s (102.2min)
Output directory: tts_output

Exemple guidé : estimation de la durée audio à partir du texte

Contribution du groupe de la PR #21095 (APP3), intégrée comme exemple guidé.

Avant de lancer une génération TTS, qui prend du temps et consomme des ressources, il est utile d’estimer la durée de l’audiobook pour planifier l’exécution. Cet exemple construit ce modèle sur les segments réellement générés : durée = nombre de mots / débit + biais du type.

Le débit (mots par seconde) est commun à tous les segments — même voix de synthèse, même vitesse — tandis que le biais, en secondes, est propre à chaque type de segment. C’est ce biais qui capte ce que le comptage de mots ne voit pas : les pauses entre répliques des dialogues, la diction plus lente des descriptions, et les silences d’attaque et de fin du fichier audio. Estimer une pente par type serait ici un surajustement : sur les 342 segments, le type description n’en compte qu’un seul, et une pente estimée sur un point unique n’a pas de sens.

Ce qui fait la valeur de la mesure :

  • L’erreur est rapportée en apprentissage et en leave-one-out (le segment prédit est retiré de l’apprentissage) : sur 342 points, la première est optimiste, seule la seconde estime l’erreur attendue sur un segment nouveau.
  • La baseline de 2,5 mots/s de l’énoncé sert de référence : le modèle n’apporte quelque chose que s’il fait mieux qu’elle en leave-one-out.
  • Un contrôle synthétique — trente segments de débit et de biais connus — vérifie que le code d’estimation retrouve ces paramètres, indépendamment de la disponibilité du service TTS.
  • Les cas limites sont traités : texte vide, type jamais vu, balises de prosodie (qui ne sont pas prononcées), mots composés et élisions, et absence totale de segment réussi.
# Exemple guide : estimation de la duree audio a partir du texte
# Contribution du groupe de la PR #21095, integree comme exemple guide.
#
# Modele retenu : duree = nb_mots / debit + biais(type)
#   - un DEBIT (mots/seconde) COMMUN a tous les segments : c'est la meme voix de synthese,
#     a la meme vitesse (speed=1.0) ; l'estimer par type avec 1 a 9 points par type
#     surajusterait (le type "description" n'a qu'un seul segment) ;
#   - un BIAIS par type de segment (en secondes) : silences d'attaque/fin du MP3, pauses
#     entre repliques des dialogues, diction plus lente des descriptions.
# C'est une regression lineaire a pente commune et ordonnee a l'origine par type.
import re

DEBIT_A_PRIORI = 2.5   # mots/s : lecture naturelle en francais (indice de l'enonce)
TYPE_GLOBAL = "_global"  # cle de repli pour un type inconnu a la prediction

def compter_mots(text):
    """Nombre de mots d'un texte : suites de lettres/chiffres, apostrophes et traits d'union
    internes inclus (« aujourd'hui », « Carre-Lamadon » = 1 mot). Les balises eventuelles
    (<s>, [whisper]...) sont retirees avant comptage : elles ne sont pas prononcees."""
    if not text:
        return 0
    text = re.sub(r"<[^>]*>|\[[^\]]*\]|\([^)]*\)", " ", text)
    return len(re.findall(r"\w+(?:['’-]\w+)*", text))

# Etape 1 : Collecter les donnees d'entrainement
def collect_training_data(generated_requests):
    """Extrait les paires (word_count, duration_s, seg_type) des resultats."""
    data = []
    for r in generated_requests:
        # On ne garde que les segments reellement generes, avec une duree mesuree et du texte.
        if r.status != "success" or r.duration_s <= 0:
            continue
        n = compter_mots(r.text)
        if n > 0:
            data.append((n, float(r.duration_s), r.seg_type))
    return data

# Etape 2 : Calculer le ratio moyen par type
def compute_duration_coefficients(training_data):
    """Retourne {seg_type: (coeff_mots_par_seconde, biais)}.

    Le debit (mots/s) est commun ; le biais est propre a chaque type. La cle "_global"
    donne le modele sans distinction de type (repli pour un type jamais vu).
    """
    if not training_data:
        # Aucune donnee (service TTS indisponible) : on retombe sur l'a priori de l'enonce.
        return {TYPE_GLOBAL: (DEBIT_A_PRIORI, 0.0)}
    types = sorted({t for _, _, t in training_data})
    x = [float(n) for n, _, _ in training_data]
    y = [d for _, d, _ in training_data]
    # Pente commune = moindres carres "intra-type" : on centre x et y dans chaque type,
    # ce qui retire l'effet du type avant d'estimer la pente (regression ANCOVA).
    moy = {t: (sum(n for n, _, tt in training_data if tt == t) / sum(1 for *_, tt in training_data if tt == t),
               sum(d for _, d, tt in training_data if tt == t) / sum(1 for *_, tt in training_data if tt == t))
           for t in types}
    sxy = sum((n - moy[t][0]) * (d - moy[t][1]) for n, d, t in training_data)
    sxx = sum((n - moy[t][0]) ** 2 for n, d, t in training_data)
    if sxx > 0 and sxy > 0:
        pente = sxy / sxx                      # secondes par mot
    else:
        # Pas assez de variation intra-type (ex. un seul point par type) : pente globale
        # passant par l'origine, puis a defaut l'a priori.
        sx2 = sum(v * v for v in x)
        pente = (sum(a * b for a, b in zip(x, y)) / sx2) if sx2 > 0 else 1 / DEBIT_A_PRIORI
    debit = 1.0 / pente
    coeffs = {t: (debit, moy[t][1] - pente * moy[t][0]) for t in types}
    mx, my = sum(x) / len(x), sum(y) / len(y)
    coeffs[TYPE_GLOBAL] = (debit, my - pente * mx)
    return coeffs

# Etape 3 : Prediction et evaluation
def predict_duration(text, seg_type, coefficients):
    """Predit la duree en secondes d'un segment."""
    debit, biais = coefficients.get(seg_type, coefficients.get(TYPE_GLOBAL, (DEBIT_A_PRIORI, 0.0)))
    n = compter_mots(text)
    if n == 0:
        return 0.0                              # texte vide : rien a prononcer
    return max(0.0, n / debit + biais)          # une duree ne peut pas etre negative

def mae(paires):
    """Erreur absolue moyenne sur une liste de (prediction, reel)."""
    return sum(abs(p - r) for p, r in paires) / len(paires) if paires else float("nan")

def evaluer(requests):
    """MAE en apprentissage, MAE en leave-one-out (honnete : le segment predit n'a pas servi
    a l'apprentissage) et MAE de la baseline a priori (2,5 mots/s, sans biais)."""
    ok = [r for r in requests if r.status == "success" and r.duration_s > 0 and compter_mots(r.text) > 0]
    coeffs = compute_duration_coefficients(collect_training_data(ok))
    train = [(predict_duration(r.text, r.seg_type, coeffs), r.duration_s) for r in ok]
    loo = []
    for i, r in enumerate(ok):
        c = compute_duration_coefficients(collect_training_data(ok[:i] + ok[i + 1:]))
        loo.append((predict_duration(r.text, r.seg_type, c), r.duration_s))
    base = [(compter_mots(r.text) / DEBIT_A_PRIORI, r.duration_s) for r in ok]
    return coeffs, ok, train, loo, base

def afficher_evaluation(requests, titre):
    coeffs, ok, train, loo, base = evaluer(requests)
    print(f"=== {titre} : {len(ok)} segments exploitables")
    if not ok:
        print("  aucun segment genere avec succes -> modele a priori :", coeffs)
        return coeffs
    for t, (debit, biais) in coeffs.items():
        n_t = sum(1 for r in ok if r.seg_type == t) if t != TYPE_GLOBAL else len(ok)
        print(f"  {t:12s} : debit = {debit:.2f} mots/s, biais = {biais:+.2f} s  ({n_t} segments)")
    print(f"  {'Seg':>3} | {'type':11s} | {'mots':>4} | {'reel':>6} | {'predit':>6} | {'LOO':>6}")
    for r, (p, _), (pl, _) in zip(ok, train, loo):
        print(f"  {r.seg_index:>3} | {r.seg_type:11s} | {compter_mots(r.text):>4} | {r.duration_s:5.1f}s | {p:5.1f}s | {pl:5.1f}s")
    duree_tot = sum(r.duration_s for r in ok)
    print(f"  MAE apprentissage      : {mae(train):.2f} s")
    print(f"  MAE leave-one-out      : {mae(loo):.2f} s   <- erreur attendue sur un segment nouveau")
    print(f"  MAE baseline 2,5 mots/s: {mae(base):.2f} s")
    print(f"  duree totale : reelle {duree_tot:.1f} s, predite {sum(p for p, _ in train):.1f} s")
    return coeffs

# --- 1. Evaluation sur les segments reellement generes par Kokoro (cellule de generation) ---
coefficients_tts = afficher_evaluation(generated, "Segments Kokoro generes")

# --- 2. Controle de la methode sur un jeu SYNTHETIQUE dont on connait la verite ---
# (permet de verifier le code meme si le service Kokoro n'a pas tourne : on fabrique des
#  segments de duree = mots/2.4 + biais connu + bruit, et on doit retrouver ces parametres)
import random
_rng = random.Random(0)
_vrai = {"narration": 0.6, "dialogue": 1.4, "description": 1.0}
_controle = []
for _i in range(30):
    _t = ["narration", "dialogue", "description"][_i % 3]
    _n = _rng.randint(8, 50)
    _txt = " ".join(["mot"] * _n)
    _controle.append(TTSRequest(seg_index=_i, seg_type=_t, speaker="test", text=_txt, annotated_text=_txt,
                                kokoro_voice="test", fish_preset="test",
                                duration_s=_n / 2.4 + _vrai[_t] + _rng.gauss(0, 0.3), status="success"))
_c = compute_duration_coefficients(collect_training_data(_controle))
print("\n=== Controle synthetique (verite : debit 2.40 mots/s, biais narration +0.6 / dialogue +1.4 / description +1.0)")
for _t in _vrai:
    print(f"  {_t:12s} : debit estime = {_c[_t][0]:.2f} mots/s, biais estime = {_c[_t][1]:+.2f} s")

# --- 3. Cas limites ---
print("\n=== Cas limites")
print("  texte vide            ->", predict_duration("", "dialogue", _c), "s")
print("  type inconnu (repli)  ->", round(predict_duration("un deux trois quatre cinq", "chanson", _c), 2), "s (modele _global)")
print("  balises ignorees      -> compter_mots('<s>[whisper] Bonjour, Madame !</s>') =", compter_mots("<s>[whisper] Bonjour, Madame !</s>"))
print("  mots composes         -> compter_mots(\"aujourd'hui Carre-Lamadon\") =", compter_mots("aujourd'hui Carre-Lamadon"))
_echec = [TTSRequest(seg_index=0, seg_type="narration", speaker="x", text="texte", annotated_text="texte",
                     kokoro_voice="x", fish_preset="x", status="failed")]
print("  aucun segment reussi  ->", compute_duration_coefficients(collect_training_data(_echec)), "(a priori)")

# --- 4. Planification : duree estimee de l'audiobook complet, AVANT toute generation ---
print("\n=== Planification")
_source = SERIES_ROOT / "boule_de_suif_full.txt"
if _source.exists():
    _texte = _source.read_text(encoding="utf-8")
    _modeles = [("a priori 2,5 mots/s", {TYPE_GLOBAL: (DEBIT_A_PRIORI, 0.0)})]
    if coefficients_tts[TYPE_GLOBAL] != (DEBIT_A_PRIORI, 0.0):
        _modeles.insert(0, ("modele appris sur Kokoro", coefficients_tts))
    for _nom, _co in _modeles:
        _debit = _co[TYPE_GLOBAL][0]
        _s = compter_mots(_texte) / _debit
        print(f"Boule de Suif complet : {compter_mots(_texte)} mots -> ~{_s / 60:.0f} min d'audio ({_nom}, {_debit:.2f} mots/s)")
=== Segments Kokoro generes : 342 segments exploitables
  description  : debit = 2.29 mots/s, biais = -1.88 s  (1 segments)
  dialogue     : debit = 2.29 mots/s, biais = +0.69 s  (39 segments)
  narration    : debit = 2.29 mots/s, biais = +0.80 s  (302 segments)
  _global      : debit = 2.29 mots/s, biais = +0.78 s  (342 segments)
  Seg | type        | mots |   reel | predit |    LOO
    0 | narration   |    3 |   2.2s |   2.1s |   2.1s
    1 | narration   |  143 |  68.1s |  63.3s |  63.2s
    2 | narration   |   31 |  13.8s |  14.3s |  14.3s
    3 | narration   |   76 |  36.9s |  34.0s |  34.0s
    4 | narration   |    7 |   4.2s |   3.9s |   3.9s
    5 | narration   |   65 |  32.1s |  29.2s |  29.2s
    6 | narration   |   58 |  29.4s |  26.1s |  26.1s
    7 | narration   |   43 |  21.5s |  19.6s |  19.6s
    8 | narration   |   24 |  12.4s |  11.3s |  11.3s
    9 | narration   |    9 |   4.8s |   4.7s |   4.7s
   10 | narration   |   90 |  41.0s |  40.1s |  40.1s
   11 | narration   |  202 |  88.9s |  89.1s |  89.1s
   12 | narration   |   30 |  16.5s |  13.9s |  13.9s
   13 | narration   |  176 |  78.2s |  77.7s |  77.7s
   14 | narration   |   68 |  30.5s |  30.5s |  30.5s
   15 | narration   |   51 |  24.9s |  23.1s |  23.1s
   16 | narration   |   42 |  19.9s |  19.2s |  19.2s
   17 | narration   |   93 |  40.4s |  41.4s |  41.4s
   18 | narration   |   15 |   7.0s |   7.4s |   7.4s
   19 | narration   |   75 |  34.7s |  33.6s |  33.6s
   20 | narration   |   23 |  11.3s |  10.9s |  10.8s
   21 | narration   |   36 |  17.1s |  16.5s |  16.5s
   22 | narration   |   38 |  16.4s |  17.4s |  17.4s
   23 | narration   |   24 |  10.0s |  11.3s |  11.3s
   24 | narration   |   49 |  24.3s |  22.2s |  22.2s
   25 | dialogue    |    3 |   3.1s |   2.0s |   2.0s
   26 | narration   |    2 |   1.7s |   1.7s |   1.7s
   27 | dialogue    |    6 |   3.1s |   3.3s |   3.3s
   28 | narration   |    3 |   3.0s |   2.1s |   2.1s
   29 | dialogue    |   16 |   8.0s |   7.7s |   7.7s
   30 | narration   |    9 |   5.8s |   4.7s |   4.7s
   31 | narration   |   98 |  44.1s |  43.6s |  43.6s
   32 | narration   |   18 |   9.3s |   8.7s |   8.7s
   33 | narration   |   67 |  31.3s |  30.1s |  30.1s
   34 | narration   |   67 |  28.4s |  30.1s |  30.1s
   35 | dialogue    |   13 |   6.3s |   6.4s |   6.4s
   36 | narration   |   40 |  19.4s |  18.3s |  18.3s
   37 | narration   |   49 |  23.7s |  22.2s |  22.2s
   38 | narration   |   23 |   9.2s |  10.9s |  10.9s
   39 | dialogue    |    5 |   3.9s |   2.9s |   2.9s
   40 | narration   |    5 |   3.0s |   3.0s |   3.0s
   41 | dialogue    |    1 |   1.3s |   1.1s |   1.1s
   42 | narration   |    2 |   1.7s |   1.7s |   1.7s
   43 | narration   |   66 |  31.1s |  29.6s |  29.6s
   44 | narration   |   63 |  29.0s |  28.3s |  28.3s
   45 | narration   |   14 |   6.7s |   6.9s |   6.9s
   46 | narration   |   26 |  11.5s |  12.2s |  12.2s
   47 | narration   |   52 |  23.6s |  23.5s |  23.5s
   48 | narration   |   72 |  29.6s |  32.3s |  32.3s
   49 | narration   |   26 |  12.7s |  12.2s |  12.2s
   50 | dialogue    |    5 |   2.8s |   2.9s |   2.9s
   51 | narration   |   17 |   9.0s |   8.2s |   8.2s
   52 | narration   |   28 |  13.2s |  13.0s |  13.0s
   53 | narration   |   89 |  42.1s |  39.7s |  39.7s
   54 | narration   |   26 |  13.0s |  12.2s |  12.2s
   55 | narration   |   74 |  33.0s |  33.1s |  33.1s
   56 | narration   |   83 |  36.8s |  37.1s |  37.1s
   57 | narration   |   15 |   7.9s |   7.4s |   7.4s
   58 | narration   |   30 |  13.1s |  13.9s |  13.9s
   59 | narration   |   87 |  37.3s |  38.8s |  38.8s
   60 | narration   |   15 |   7.0s |   7.4s |   7.4s
   61 | narration   |  164 |  75.7s |  72.5s |  72.4s
   62 | narration   |   17 |   8.8s |   8.2s |   8.2s
   63 | narration   |  119 |  52.8s |  52.8s |  52.8s
   64 | narration   |    9 |   5.0s |   4.7s |   4.7s
   65 | narration   |   61 |  27.3s |  27.5s |  27.5s
   66 | narration   |   52 |  23.7s |  23.5s |  23.5s
   67 | narration   |  127 |  58.0s |  56.3s |  56.3s
   68 | narration   |   46 |  18.4s |  20.9s |  20.9s
   69 | narration   |   72 |  31.7s |  32.3s |  32.3s
   70 | narration   |   30 |  15.3s |  13.9s |  13.9s
   71 | narration   |   50 |  21.7s |  22.6s |  22.7s
   72 | narration   |   37 |  18.4s |  17.0s |  17.0s
   73 | narration   |   46 |  21.1s |  20.9s |  20.9s
   74 | narration   |   99 |  43.9s |  44.1s |  44.1s
   75 | narration   |   27 |  12.7s |  12.6s |  12.6s
   76 | dialogue    |   11 |   5.5s |   5.5s |   5.5s
   77 | narration   |   83 |  36.0s |  37.1s |  37.1s
   78 | narration   |   37 |  16.1s |  17.0s |  17.0s
   79 | narration   |  100 |  43.7s |  44.5s |  44.5s
   80 | narration   |   66 |  28.0s |  29.6s |  29.6s
   81 | narration   |   11 |   4.4s |   5.6s |   5.6s
   82 | dialogue    |   23 |   9.8s |  10.7s |  10.8s
   83 | narration   |   48 |  19.7s |  21.8s |  21.8s
   84 | dialogue    |   16 |   7.5s |   7.7s |   7.7s
   85 | narration   |   54 |  22.3s |  24.4s |  24.4s
   86 | narration   |   67 |  29.3s |  30.1s |  30.1s
   87 | narration   |   51 |  26.4s |  23.1s |  23.1s
   88 | dialogue    |    2 |   2.1s |   1.6s |   1.6s
   89 | narration   |   13 |   6.2s |   6.5s |   6.5s
   90 | dialogue    |    4 |   2.9s |   2.4s |   2.4s
   91 | narration   |    8 |   4.0s |   4.3s |   4.3s
   92 | narration   |   43 |  19.0s |  19.6s |  19.6s
   93 | narration   |  157 |  66.1s |  69.4s |  69.5s
   94 | dialogue    |    6 |   2.7s |   3.3s |   3.3s
   95 | narration   |   94 |  43.6s |  41.9s |  41.9s
   96 | narration   |   24 |   9.2s |  11.3s |  11.3s
   97 | dialogue    |    5 |   4.5s |   2.9s |   2.8s
   98 | narration   |   65 |  27.8s |  29.2s |  29.2s
   99 | narration   |   80 |  38.3s |  35.8s |  35.7s
  100 | narration   |  216 |  91.4s |  95.2s |  95.4s
  101 | narration   |   94 |  42.9s |  41.9s |  41.9s
  102 | narration   |  156 |  72.0s |  69.0s |  68.9s
  103 | narration   |   34 |  15.3s |  15.7s |  15.7s
  104 | narration   |   66 |  31.1s |  29.6s |  29.6s
  105 | narration   |   42 |  17.7s |  19.2s |  19.2s
  106 | narration   |   47 |  19.3s |  21.3s |  21.3s
  107 | narration   |   51 |  21.7s |  23.1s |  23.1s
  108 | narration   |   30 |  13.5s |  13.9s |  13.9s
  109 | narration   |   60 |  26.3s |  27.0s |  27.0s
  110 | description |   94 |  39.2s |  39.2s |  41.9s
  111 | narration   |   13 |   6.8s |   6.5s |   6.5s
  112 | dialogue    |    5 |   3.5s |   2.9s |   2.9s
  113 | narration   |   50 |  23.1s |  22.6s |  22.6s
  114 | dialogue    |    2 |   2.0s |   1.6s |   1.6s
  115 | narration   |   20 |  10.8s |   9.5s |   9.5s
  116 | narration   |  103 |  47.9s |  45.8s |  45.8s
  117 | narration   |   47 |  22.7s |  21.3s |  21.3s
  118 | narration   |    4 |   2.6s |   2.5s |   2.5s
  119 | dialogue    |    2 |   1.4s |   1.6s |   1.6s
  120 | narration   |    3 |   2.2s |   2.1s |   2.1s
  121 | narration   |   49 |  23.0s |  22.2s |  22.2s
  122 | narration   |   47 |  20.8s |  21.3s |  21.3s
  123 | narration   |    2 |   1.8s |   1.7s |   1.7s
  124 | narration   |    3 |   3.0s |   2.1s |   2.1s
  125 | narration   |    6 |   3.2s |   3.4s |   3.4s
  126 | narration   |    2 |   1.6s |   1.7s |   1.7s
  127 | narration   |    7 |   5.0s |   3.9s |   3.9s
  128 | narration   |    2 |   1.5s |   1.7s |   1.7s
  129 | narration   |    8 |   4.4s |   4.3s |   4.3s
  130 | narration   |    9 |   5.1s |   4.7s |   4.7s
  131 | narration   |    6 |   3.0s |   3.4s |   3.4s
  132 | narration   |   17 |   8.1s |   8.2s |   8.2s
  133 | narration   |   49 |  24.0s |  22.2s |  22.2s
  134 | narration   |   37 |  14.9s |  17.0s |  17.0s
  135 | narration   |    9 |   3.3s |   4.7s |   4.7s
  136 | narration   |    6 |   2.9s |   3.4s |   3.4s
  137 | narration   |    4 |   2.6s |   2.5s |   2.5s
  138 | narration   |    9 |   3.9s |   4.7s |   4.7s
  139 | narration   |   31 |  13.5s |  14.3s |  14.3s
  140 | narration   |   15 |   7.7s |   7.4s |   7.4s
  141 | dialogue    |    5 |   2.5s |   2.9s |   2.9s
  142 | narration   |   20 |   9.1s |   9.5s |   9.5s
  143 | dialogue    |   11 |   5.2s |   5.5s |   5.5s
  144 | narration   |  164 |  68.1s |  72.5s |  72.6s
  145 | narration   |   83 |  37.1s |  37.1s |  37.1s
  146 | narration   |   18 |   8.2s |   8.7s |   8.7s
  147 | narration   |   16 |   7.6s |   7.8s |   7.8s
  148 | narration   |  239 |  97.6s | 105.2s | 105.8s
  149 | narration   |    4 |   2.6s |   2.5s |   2.5s
  150 | narration   |   20 |   8.6s |   9.5s |   9.5s
  151 | narration   |    6 |   2.8s |   3.4s |   3.4s
  152 | narration   |   25 |   9.6s |  11.7s |  11.7s
  153 | narration   |    4 |   2.9s |   2.5s |   2.5s
  154 | narration   |    3 |   2.5s |   2.1s |   2.1s
  155 | narration   |   54 |  27.7s |  24.4s |  24.4s
  156 | narration   |   44 |  20.1s |  20.0s |  20.0s
  157 | narration   |   14 |   5.0s |   6.9s |   6.9s
  158 | narration   |  152 |  67.9s |  67.2s |  67.2s
  159 | narration   |    9 |   3.7s |   4.7s |   4.7s
  160 | narration   |    6 |   3.4s |   3.4s |   3.4s
  161 | narration   |   22 |   8.9s |  10.4s |  10.4s
  162 | narration   |   16 |   8.0s |   7.8s |   7.8s
  163 | narration   |   21 |   8.8s |  10.0s |  10.0s
  164 | narration   |   38 |  16.8s |  17.4s |  17.4s
  165 | narration   |   33 |  14.4s |  15.2s |  15.2s
  166 | dialogue    |    2 |   2.1s |   1.6s |   1.6s
  167 | narration   |   45 |  22.8s |  20.5s |  20.5s
  168 | narration   |  178 |  76.1s |  78.6s |  78.7s
  169 | narration   |   16 |   7.9s |   7.8s |   7.8s
  170 | dialogue    |  109 |  42.0s |  48.3s |  48.6s
  171 | narration   |   61 |  29.6s |  27.5s |  27.4s
  172 | narration   |   10 |   4.8s |   5.2s |   5.2s
  173 | narration   |   11 |   4.5s |   5.6s |   5.6s
  174 | narration   |    1 |   1.4s |   1.2s |   1.2s
  175 | narration   |    6 |   2.5s |   3.4s |   3.4s
  176 | narration   |    6 |   3.0s |   3.4s |   3.4s
  177 | narration   |    5 |   2.9s |   3.0s |   3.0s
  178 | narration   |    1 |   1.4s |   1.2s |   1.2s
  179 | narration   |   16 |   7.7s |   7.8s |   7.8s
  180 | narration   |    7 |   2.8s |   3.9s |   3.9s
  181 | narration   |   11 |   4.8s |   5.6s |   5.6s
  182 | narration   |    2 |   1.6s |   1.7s |   1.7s
  183 | narration   |   12 |   6.6s |   6.0s |   6.0s
  184 | narration   |   36 |  16.9s |  16.5s |  16.5s
  185 | narration   |   40 |  19.9s |  18.3s |  18.3s
  186 | narration   |  131 |  56.4s |  58.0s |  58.1s
  187 | narration   |   88 |  39.1s |  39.3s |  39.3s
  188 | narration   |   31 |  13.4s |  14.3s |  14.4s
  189 | dialogue    |   25 |  13.6s |  11.6s |  11.6s
  190 | narration   |   41 |  18.8s |  18.7s |  18.7s
  191 | narration   |   18 |   9.9s |   8.7s |   8.7s
  192 | narration   |   10 |   5.2s |   5.2s |   5.2s
  193 | narration   |  122 |  55.7s |  54.1s |  54.1s
  194 | narration   |    8 |   3.4s |   4.3s |   4.3s
  195 | narration   |    4 |   2.6s |   2.5s |   2.5s
  196 | narration   |    5 |   2.5s |   3.0s |   3.0s
  197 | narration   |    4 |   2.8s |   2.5s |   2.5s
  198 | narration   |    1 |   1.4s |   1.2s |   1.2s
  199 | narration   |    8 |   3.9s |   4.3s |   4.3s
  200 | narration   |    6 |   2.5s |   3.4s |   3.4s
  201 | narration   |   35 |  15.0s |  16.1s |  16.1s
  202 | narration   |    9 |   4.0s |   4.7s |   4.7s
  203 | narration   |    8 |   4.2s |   4.3s |   4.3s
  204 | narration   |  171 |  78.8s |  75.5s |  75.4s
  205 | narration   |   35 |  16.9s |  16.1s |  16.1s
  206 | narration   |   32 |  14.5s |  14.8s |  14.8s
  207 | narration   |   51 |  22.7s |  23.1s |  23.1s
  208 | narration   |  142 |  64.6s |  62.8s |  62.8s
  209 | narration   |   15 |   7.4s |   7.4s |   7.4s
  210 | narration   |  105 |  47.9s |  46.7s |  46.7s
  211 | narration   |   49 |  19.3s |  22.2s |  22.2s
  212 | dialogue    |    9 |   4.6s |   4.6s |   4.6s
  213 | narration   |   28 |  11.8s |  13.0s |  13.0s
  214 | narration   |   31 |  13.2s |  14.3s |  14.4s
  215 | narration   |   19 |   9.8s |   9.1s |   9.1s
  216 | narration   |   88 |  37.9s |  39.3s |  39.3s
  217 | narration   |    6 |   4.0s |   3.4s |   3.4s
  218 | narration   |   51 |  23.2s |  23.1s |  23.1s
  219 | narration   |   54 |  23.2s |  24.4s |  24.4s
  220 | narration   |   12 |   6.2s |   6.0s |   6.0s
  221 | narration   |   11 |   4.7s |   5.6s |   5.6s
  222 | dialogue    |    1 |   1.4s |   1.1s |   1.1s
  223 | narration   |   63 |  29.1s |  28.3s |  28.3s
  224 | dialogue    |    6 |   3.4s |   3.3s |   3.3s
  225 | narration   |    7 |   3.3s |   3.9s |   3.9s
  226 | dialogue    |   28 |  12.8s |  12.9s |  12.9s
  227 | narration   |    5 |   2.7s |   3.0s |   3.0s
  228 | narration   |   11 |   6.8s |   5.6s |   5.6s
  229 | narration   |   46 |  20.8s |  20.9s |  20.9s
  230 | narration   |   33 |  14.7s |  15.2s |  15.2s
  231 | narration   |   34 |  16.6s |  15.7s |  15.7s
  232 | narration   |   51 |  22.5s |  23.1s |  23.1s
  233 | narration   |   36 |  17.3s |  16.5s |  16.5s
  234 | narration   |   21 |   9.4s |  10.0s |  10.0s
  235 | narration   |   58 |  23.9s |  26.1s |  26.2s
  236 | narration   |   88 |  38.2s |  39.3s |  39.3s
  237 | narration   |    8 |   4.4s |   4.3s |   4.3s
  238 | dialogue    |  140 |  60.7s |  61.9s |  61.9s
  239 | narration   |   10 |   5.1s |   5.2s |   5.2s
  240 | narration   |   32 |  13.1s |  14.8s |  14.8s
  241 | narration   |   43 |  22.2s |  19.6s |  19.6s
  242 | narration   |    3 |   2.3s |   2.1s |   2.1s
  243 | narration   |  104 |  50.5s |  46.2s |  46.2s
  244 | narration   |   83 |  38.3s |  37.1s |  37.1s
  245 | narration   |   52 |  24.6s |  23.5s |  23.5s
  246 | narration   |   10 |   6.2s |   5.2s |   5.2s
  247 | narration   |   20 |   8.9s |   9.5s |   9.5s
  248 | dialogue    |    1 |   1.2s |   1.1s |   1.1s
  249 | narration   |   38 |  18.6s |  17.4s |  17.4s
  250 | narration   |   20 |   9.1s |   9.5s |   9.5s
  251 | dialogue    |    6 |   4.0s |   3.3s |   3.3s
  252 | narration   |   21 |  11.0s |  10.0s |  10.0s
  253 | narration   |  130 |  60.1s |  57.6s |  57.6s
  254 | narration   |   37 |  18.2s |  17.0s |  17.0s
  255 | narration   |   20 |  10.9s |   9.5s |   9.5s
  256 | narration   |   48 |  21.5s |  21.8s |  21.8s
  257 | narration   |   50 |  23.9s |  22.6s |  22.6s
  258 | narration   |   31 |  14.2s |  14.3s |  14.3s
  259 | narration   |    5 |   2.9s |   3.0s |   3.0s
  260 | dialogue    |    2 |   1.9s |   1.6s |   1.6s
  261 | narration   |  176 |  82.0s |  77.7s |  77.6s
  262 | narration   |   63 |  28.7s |  28.3s |  28.3s
  263 | narration   |    2 |   2.2s |   1.7s |   1.7s
  264 | narration   |   20 |   7.7s |   9.5s |   9.5s
  265 | narration   |   18 |   8.7s |   8.7s |   8.7s
  266 | narration   |   24 |  12.5s |  11.3s |  11.3s
  267 | narration   |  192 |  87.6s |  84.7s |  84.6s
  268 | narration   |   10 |   4.6s |   5.2s |   5.2s
  269 | narration   |   21 |   9.9s |  10.0s |  10.0s
  270 | narration   |   21 |   8.0s |  10.0s |  10.0s
  271 | narration   |   30 |  12.6s |  13.9s |  13.9s
  272 | narration   |   45 |  19.4s |  20.5s |  20.5s
  273 | narration   |   38 |  17.6s |  17.4s |  17.4s
  274 | narration   |    6 |   3.1s |   3.4s |   3.4s
  275 | narration   |   69 |  28.7s |  31.0s |  31.0s
  276 | narration   |   30 |  14.9s |  13.9s |  13.9s
  277 | narration   |   82 |  35.8s |  36.6s |  36.6s
  278 | dialogue    |   11 |   6.1s |   5.5s |   5.5s
  279 | narration   |   53 |  26.7s |  24.0s |  24.0s
  280 | narration   |   28 |  12.2s |  13.0s |  13.0s
  281 | dialogue    |    1 |   1.2s |   1.1s |   1.1s
  282 | narration   |   18 |   7.7s |   8.7s |   8.7s
  283 | dialogue    |    4 |   2.9s |   2.4s |   2.4s
  284 | narration   |    9 |   4.7s |   4.7s |   4.7s
  285 | narration   |   61 |  27.6s |  27.5s |  27.5s
  286 | dialogue    |    4 |   2.3s |   2.4s |   2.4s
  287 | narration   |   23 |  11.2s |  10.9s |  10.8s
  288 | dialogue    |   13 |   6.3s |   6.4s |   6.4s
  289 | narration   |   37 |  18.4s |  17.0s |  17.0s
  290 | narration   |   56 |  24.2s |  25.3s |  25.3s
  291 | narration   |   61 |  27.8s |  27.5s |  27.5s
  292 | narration   |    4 |   3.1s |   2.5s |   2.5s
  293 | narration   |   14 |   6.3s |   6.9s |   6.9s
  294 | narration   |   55 |  23.7s |  24.8s |  24.8s
  295 | dialogue    |   12 |   5.8s |   5.9s |   5.9s
  296 | narration   |   41 |  18.6s |  18.7s |  18.7s
  297 | narration   |   22 |  10.3s |  10.4s |  10.4s
  298 | dialogue    |   10 |   5.0s |   5.1s |   5.1s
  299 | narration   |   40 |  18.6s |  18.3s |  18.3s
  300 | narration   |    6 |   3.2s |   3.4s |   3.4s
  301 | narration   |    7 |   2.7s |   3.9s |   3.9s
  302 | narration   |    4 |   2.3s |   2.5s |   2.6s
  303 | narration   |   10 |   4.0s |   5.2s |   5.2s
  304 | narration   |    2 |   1.7s |   1.7s |   1.7s
  305 | narration   |    4 |   2.1s |   2.5s |   2.6s
  306 | narration   |   13 |   7.4s |   6.5s |   6.5s
  307 | narration   |   15 |   5.9s |   7.4s |   7.4s
  308 | narration   |    7 |   4.0s |   3.9s |   3.9s
  309 | narration   |   68 |  27.7s |  30.5s |  30.5s
  310 | narration   |   58 |  27.9s |  26.1s |  26.1s
  311 | narration   |   58 |  28.1s |  26.1s |  26.1s
  312 | narration   |   29 |  13.3s |  13.5s |  13.5s
  313 | narration   |    9 |   3.9s |   4.7s |   4.7s
  314 | narration   |   42 |  19.3s |  19.2s |  19.2s
  315 | narration   |   88 |  39.1s |  39.3s |  39.3s
  316 | narration   |   25 |  10.0s |  11.7s |  11.7s
  317 | dialogue    |    9 |   3.4s |   4.6s |   4.7s
  318 | narration   |   51 |  23.2s |  23.1s |  23.1s
  319 | narration   |   13 |   7.5s |   6.5s |   6.5s
  320 | narration   |    6 |   3.7s |   3.4s |   3.4s
  321 | narration   |    6 |   2.6s |   3.4s |   3.4s
  322 | narration   |    3 |   2.3s |   2.1s |   2.1s
  323 | narration   |   23 |  11.2s |  10.9s |  10.8s
  324 | narration   |   22 |   9.6s |  10.4s |  10.4s
  325 | narration   |   28 |  11.9s |  13.0s |  13.0s
  326 | narration   |   65 |  27.2s |  29.2s |  29.2s
  327 | narration   |    3 |   2.7s |   2.1s |   2.1s
  328 | narration   |   15 |   6.7s |   7.4s |   7.4s
  329 | narration   |   32 |  12.9s |  14.8s |  14.8s
  330 | narration   |   82 |  37.8s |  36.6s |  36.6s
  331 | narration   |   80 |  32.4s |  35.8s |  35.8s
  332 | narration   |   63 |  28.2s |  28.3s |  28.3s
  333 | narration   |  162 |  69.8s |  71.6s |  71.6s
  334 | narration   |   35 |  14.2s |  16.1s |  16.1s
  335 | dialogue    |    4 |   3.2s |   2.4s |   2.4s
  336 | narration   |   19 |   8.9s |   9.1s |   9.1s
  337 | narration   |   38 |  17.2s |  17.4s |  17.4s
  338 | narration   |   46 |  22.5s |  20.9s |  20.9s
  339 | narration   |   17 |  11.5s |   8.2s |   8.2s
  340 | narration   |   71 |  31.9s |  31.8s |  31.8s
  341 | narration   |   21 |   9.5s |  10.0s |  10.0s
  MAE apprentissage      : 0.97 s
  MAE leave-one-out      : 0.99 s   <- erreur attendue sur un segment nouveau
  MAE baseline 2,5 mots/s: 2.26 s
  duree totale : reelle 6129.7 s, predite 6129.7 s

=== Controle synthetique (verite : debit 2.40 mots/s, biais narration +0.6 / dialogue +1.4 / description +1.0)
  narration    : debit estime = 2.42 mots/s, biais estime = +0.60 s
  dialogue     : debit estime = 2.42 mots/s, biais estime = +1.46 s
  description  : debit estime = 2.42 mots/s, biais estime = +0.97 s

=== Cas limites
  texte vide            -> 0.0 s
  type inconnu (repli)  -> 3.08 s (modele _global)
  balises ignorees      -> compter_mots('<s>[whisper] Bonjour, Madame !</s>') = 2
  mots composes         -> compter_mots("aujourd'hui Carre-Lamadon") = 2
  aucun segment reussi  -> {'_global': (2.5, 0.0)} (a priori)

=== Planification
Boule de Suif complet : 17245 mots -> ~126 min d'audio (modele appris sur Kokoro, 2.29 mots/s)
Boule de Suif complet : 17245 mots -> ~115 min d'audio (a priori 2,5 mots/s, 2.50 mots/s)

Lecture du résultat — estimation de durée audio

Le modèle. durée = nb_mots / débit + biais(type), avec un débit commun (mots/s) et un biais par type de segment (dialogue, narration, description). Pourquoi pas un coefficient par type ? Sur 342 segments, le type description n’en compte qu’un seul : une pente estimée sur un point n’a aucun sens. La voix et la vitesse (speed=1.0) étant les mêmes, le débit est une propriété du moteur ; ce qui change d’un type à l’autre, ce sont les pauses (dialogues), la diction (descriptions) et les silences d’attaque et de fin du MP3, que capte le biais. C’est une régression linéaire à pente commune (ANCOVA), estimée par moindres carrés intra-type.

Comment lire les sorties.

  1. Segments Kokoro générés : le tableau compare la durée réelle (lue dans le MP3), la prédiction en apprentissage et la prédiction en leave-one-out (le segment prédit est retiré de l’apprentissage). Sur 342 points, la MAE d’apprentissage est optimiste ; seule la MAE leave-one-out estime l’erreur sur un segment nouveau. La baseline 2,5 mots/s (indice de l’énoncé, sans biais) sert de référence : le modèle n’apporte quelque chose que s’il fait mieux qu’elle en leave-one-out. Le segment description, seul de son type, est prédit en leave-one-out par le modèle _global (repli prévu pour un type jamais vu).
  2. Contrôle synthétique : 30 segments fabriqués avec un débit connu (2,40 mots/s) et des biais connus, plus un bruit gaussien. L’estimation retrouve le débit (≈ 2,42) et les biais à ~0,1 s près : le code d’estimation est correct, indépendamment de la disponibilité du service TTS.
  3. Cas limites : texte vide → 0 s ; type inconnu → modèle _global ; balises de prosodie (<s>, [whisper], (cold)) ignorées au comptage (elles ne sont pas prononcées) ; mots composés et élisions comptés comme un mot ; aucun segment réussi → repli sur l’a priori de 2,5 mots/s, sans planter.
  4. Planification : appliqué au texte intégral de Boule de Suif (~17 000 mots), le modèle donne l’ordre de grandeur de l’audiobook complet (≈ 2 h à 2,3–2,5 mots/s, pour ~102 min d’audio générées effectivement) avant toute génération : c’est l’usage visé par l’énoncé.

Limites honnêtes.

  • Le corpus couvre tout Boule de Suif (342 segments), mais la repartition des types reste desequilibree (302 narration, 39 dialogue, 1 description) : le biais description repose sur un segment unique — c’est le point le plus fragile du modèle.
  • La durée « réelle » est elle-même estimée par audio_duration_s à partir de la taille du MP3 à 128 kbps : un débit variable (VBR) fausserait la cible.
  • Le nombre de mots ignore la ponctuation, alors qu’une virgule ou un point induit une pause ; le nombre de signes de ponctuation serait une variable explicative naturelle à ajouter.
  • Pour l’estimation du livre complet, on n’ajoute pas le biais par segment (le découpage en segments n’est pas encore connu) : l’estimation est donc un peu basse.

Note d’exécution. La sortie ci-dessus provient d’une exécution complète avec la pile locale : les 342/342 segments sont présents sur disque et ont été rechargés du cache (génération d’origine : pass P4). Le découpage LLM étant indisponible lors de cette exécution, la génération FishAudio de la section suivante utilise le découpage déterministe de repli. Les sections 2 à 4 (contrôle synthétique, cas limites, planification) ne dépendent pas du service.

Exercice : la ponctuation — un régresseur de plus ?

Durée estimée : 20 minutes

Objectif : mesurer si le nombre de signes de ponctuation d’un segment améliore l’estimation de sa durée, au-delà du nombre de mots et du type de segment.

Contexte : l’exemple guidé ci-dessus compte les mots, et rien d’autre. Or une virgule, un point ou des points de suspension imposent une pause que le comptage de mots ignore : deux segments de même longueur ne se prononcent pas au même rythme selon leur ponctuation. C’est la limite que l’exemple guidé signale lui-même, et c’est ce que cet exercice quantifie.

  • Étape 1 : compter les signes de ponctuation qui induisent une pause (. , ; : ! ? et les points de suspension), balises de prosodie retirées comme pour le comptage des mots.
  • Étape 2 : étendre le modèle avec cette information — par exemple un biais additif proportionnel au nombre de ponctuations, la pente restant celle du débit commun.
  • Étape 3 : comparer l’erreur moyenne absolue en leave-one-out à celle du modèle de l’exemple guidé et à la baseline de 2,5 mots/s, puis trancher : le gain est-il réel, ou le nombre de mots suffit-il ?

Indice : réutiliser collect_training_data, mae et la logique d’évaluation de l’exemple guidé Indice : sur 342 segments, un gain moyen de quelques centièmes de seconde reste faible devant la dispersion des durées réelles — comparez les deux Indice : les répliques portent beaucoup de ponctuation forte ; un gain apparent peut venir du type de segment plutôt que de la ponctuation — séparez les deux effets avant de conclure

# Exercice : la ponctuation comme variable explicative supplementaire

# Etape 1 : compter les signes de ponctuation qui induisent une pause
def compter_ponctuations(text):
    """Nombre de signes de ponctuation forte (. , ; : ! ? et points de suspension).

    Les balises de prosodie (<s>, [whisper]...) sont retirees avant comptage,
    comme dans compter_mots : elles ne sont pas prononcees.
    """
    # TODO etudiant : compter les signes de ponctuation du texte nettoye
    return 0  # TODO etudiant

# Etape 2 : etendre le modele (biais additif proportionnel aux ponctuations)
def collect_training_data_ponctuation(generated_requests):
    """Paires (nb_mots, nb_ponctuations, duration_s, seg_type) des segments generes."""
    # TODO etudiant : ne garder que les segments reussis, comme dans l'exemple guide
    return []  # TODO etudiant

def compute_coefficients_ponctuation(training_data):
    """Retourne {seg_type: (debit, biais, secondes_par_ponctuation)}."""
    # TODO etudiant : etendre compute_duration_coefficients avec la ponctuation
    return {}  # TODO etudiant

def predict_duration_ponctuation(text, seg_type, coefficients):
    """Predit la duree en secondes, ponctuation comprise."""
    # TODO etudiant
    return 0.0  # TODO etudiant

# Etape 3 : comparer en leave-one-out au modele de l'exemple guide et a la baseline
def evaluer_ponctuation(requests, coefficients_exemple):
    """Retourne (mae_loo_ponctuation, mae_loo_exemple, mae_baseline, verdict)."""
    # TODO etudiant : reprendre la boucle leave-one-out de evaluer()
    return None  # TODO etudiant

print("Exercice a completer")
Exercice a completer

Export des metadonnees

Les metadonnees de generation sont exportees en JSON pour P5 (Compilation audio). Cette étape formalise le contrat d’interface entre la passe P4 (generation TTS) et la passe P5 (assemblage audiobook) : tout ce que P5 doit savoir pour assembler le livre audio tient dans ce fichier.

Structure du manifest tts_generation_metadata.json

Le JSON exporte comporte quatre blocs principaux :

  • epic, pass, description : métadonnées de traçabilité (Epic #1028, Pass P4, source « Boule de Suif »). Permet de retrouver à quelle itération de pipeline correspond le fichier.
  • tts_model, tts_service_url : identifica­tion du moteur utilisé (ici Kokoro sur http://localhost:8191). P5 choisit entre Kokoro et FishAudio selon ce champ — c’est le discriminateur en aval.
  • stats : compteurs agregees (total_segments, successful, failed, total_duration_s). Utilise pour les dashboards et la verification de completion du pipeline.
  • segments : liste des 342 TTSRequest serialises via asdict(r). Chaque élément contient seg_index, seg_type, speaker, kokoro_voice, output_file, duration_s, file_size_kb, status. C’est la source de verite pour P5, qui charge ce JSON puis itere les segments pour assembler le livre audio.

Pourquoi un manifest intermediaire et pas un pickle / state global

Un fichier JSON sur disque (et non un objet Python en memoire) permet (a) de decoupler les passes P4 et P5 — on peut relancer P5 sans reexecuter P4 ; (b) de debugger un crash en lisant directement le JSON dans un editeur ; (c) de versionner les generations successives si on relance le notebook avec des variations de voix. Le champ epic+pass permet de comparer plusieurs runs.

Garanties de l’export

La cellule verifie que asdict(r) capture bien tous les champs du @dataclass TTSRequest défini plus haut (seg_index, seg_type, speaker, text, annotated_text, kokoro_voice, fish_preset, tags, output_file, duration_s, file_size_kb, status). L’encoding="utf-8" et ensure_ascii=False preservent les accents français dans les noms de voix/speaker. Le indent=2 rend le fichier lisible pour inspection humaine.

Sortie attendue

A l’issue de cette cellule, tts_output/tts_generation_metadata.json existe et contient stats.successful = 342, stats.total_duration_s = 6129.7. C’est le signal de succès minimal — P5 refusera de demarrer si ce fichier est absent ou si stats.successful != 342.

tts_metadata = {
    "epic": "1028",
    "pass": "P4",
    "description": "TTS generation via Kokoro for audiobook demo",
    "source_text": "Boule de Suif - Guy de Maupassant",
    "tts_model": "kokoro",
    "tts_service_url": KOKORO_URL,
    "stats": {
        "total_segments": len(generated),
        "successful": sum(1 for r in generated if r.status == "success"),
        "failed": sum(1 for r in generated if r.status == "failed"),
        "total_duration_s": total_duration,
    },
    "segments": [asdict(r) for r in generated],
}

meta_path = TTS_OUTPUT_DIR / "tts_generation_metadata.json"
with open(meta_path, "w", encoding="utf-8") as f:
    json.dump(tts_metadata, f, ensure_ascii=False, indent=2)

print(f"Metadata saved: {meta_path.name}")
print(f"Segments: {tts_metadata['stats']['successful']}/{tts_metadata['stats']['total_segments']}")
print(f"Total audio: {total_duration:.1f}s")
Metadata saved: tts_generation_metadata.json
Segments: 342/342
Total audio: 6129.7s

Analyse de l’utilisation des voix

Repartition des segments par voix et par type. Cette cellule agrege les résultats par voix Kokoro et par type de segment — deux axes complémentaires qui servent a la fois au debug (identifier les voix sous-utilisees ou les types surrepresentes) et a la planification (estimer la charge d’une prochaine generation).

Lecture des résultats (mesures verbatim)

Voix Kokoro Segments Duree totale Type dominant
bf_isabella 325 5986.0s narration + transitions du narrateur
bm_george 12 115.9s repliques des personnages masculins (comte, loiseau, cornudet, carre_lamadon partagent la voix)
am_michael 2 15.6s repliques de l’officier prussien
af_bella 2 5.0s repliques de la comtesse et de Mme Loiseau
bf_emma 1 2.7s replique des bonnes soeurs
af_sky 0 — mappée à Élisabeth Rousset, mais aucune replique ne lui est attribuée par le découpage P3

Par type : 302 narrations, 39 dialogues, 1 description. C’est coherent avec la structure de « Boule de Suif » ou les passages narratifs relient des repliques breves.

Interpretation pedagogique

La concentration sur bf_isabella (325/342 segments, 5986.0s) reflete deux realites du corpus : (a) Maupassant utilise frequemment le narrateur pour relier les repliques, donc la voix du narrateur domine en volume ; (b) le cast P2 attribue bf_isabella au narrateur, et toute replique sans personnage distinct (eg. formule de transition) retombe sur le narrateur par defaut (resolve_speaker_id fallback).

Les voix de personnage partagent les repliques disponibles : bm_george porte quatre personnages masculins (12 repliques au total), les voix feminines une a deux repliques chacune. Même sur le texte integral (~102 min d’audio), le narrateur reste au-dessus de 95 % — dans une nouvelle de Maupassant, la prose narrative porte le recit.

Pourquoi Counter ici plutot qu’un groupby pandas

Le recours a collections.Counter (et non a pandas.DataFrame.groupby) est delibere : la structure de sortie reste minimale (compteur {cle: nombre}), aucune dépendance lourde (pandas absent de ce notebook), et la complexite est O(N) sur 342 segments. P5 ne consomme pas cette cellule — c’est une inspection humaine au notebook, pas une donnee de pipeline. L’analyse vit dans la sortie stdout, pas dans un fichier JSON.

Garanties et limites

L’agregation filtre status == "success". Si la generation Kokoro avait partiellement echoue, les segments failed ne seraient pas comptes dans voice_usage ni dans type_usage. C’est desirable : on analyse la production effective, pas la production théorique. La duree affichée correspond a req.duration_s (mesuree par parsing WAV/MP3), pas a une estimation word-count.

from collections import Counter

voice_usage = Counter(r.kokoro_voice for r in generated if r.status == "success")
type_usage = Counter(r.seg_type for r in generated if r.status == "success")

print("Voice usage:")
for voice, count in voice_usage.most_common():
    dur = sum(r.duration_s for r in generated if r.kokoro_voice == voice and r.status == "success")
    print(f"  {voice:20s}: {count} segments, {dur:.1f}s")

print(f"\nSegment types:")
for stype, count in type_usage.most_common():
    print(f"  {stype:12s}: {count}")
Voice usage:
  bf_isabella         : 323 segments, 5978.3s
  bm_george           : 11 segments, 60.8s
  af_bella            : 5 segments, 72.3s
  am_michael          : 2 segments, 15.6s
  bf_emma             : 1 segments, 2.7s

Segment types:
  narration   : 302
  dialogue    : 39
  description : 1

Lecture du tableau voix : concentration du narrateur et dispersion des voix de personnage

Observation cle : bf_isabella (le narrateur) concentre 325 des 342 segments et 5986,0 s, soit 95 % des segments et 97,7 % de la duree totale generee. Les voix de personnage se partagent les 17 segments restants : bm_george 12 segments (115,9 s), am_michael 2 (15,6 s), af_bella 2 (5,0 s), bf_emma 1 (2,7 s). Cette distribution reflete directement la structure du corpus « Boule de Suif » : Maupassant alterne repliques courtes et passages narratifs d atmosphere, le narrateur servant de fil conducteur entre les scenes.

Pourquoi cette concentration tient aussi sur le corpus complet : on pourrait croire que la domination du narrateur est un artefact de corpus court. L’exécution sur le texte integral (342 segments, ~102 min) montre le contraire : dans une nouvelle de Maupassant, la prose narrative porte le recit et les repliques restent breves — le narrateur reste au-dessus de 95 % quelle que soit la longueur du texte. La distribution en « escalier » (une voix a 325 segments, quatre voix a 1-12) est donc une propriete du texte source, pas de la taille du corpus.

Implications pour le casting : le routeur voix P2 fonctionne correctement — chaque speaker P3 mappé dans voice_map obtient sa voix, et resolve_speaker_id retombe sur le narrateur (bf_isabella) pour les transitions narratives et les descriptions de paysage. Aucune voix de personnage n’apparait avec un compte anormal : les quelques repliques adressees du texte correspondent aux faibles comptes observes.

Limite de cette agregation : la voix du narrateur pourrait etre subdivisee en variantes (description vs dialogue vs transition) si la prosodie Kokoro le permettait — mais Kokoro ne supporte pas le morphing de voix mid-stream. FishAudio S2-Pro, avec ses 15000+ tags expressifs, ouvre cette voie : une voix bf_isabella + tag (cold tone) pour la description de la neige, (gentle) pour les transitions. C est une piste d evolution au-dela de ce notebook.

Conclusion P4 — Kokoro (Demo)

Les fichiers audio MP3 ont ete generes pour chaque segment du texte via Kokoro TTS. Les metadonnees (durees, voix, paths) sont exportees pour la compilation finale P5.

Production : Pour une qualite superieure, les mêmes segments sont generes ci-dessous via FishAudio S2-Pro avec les tags expressifs complets ([whisper], [shout], [cold], etc.).


P4b — Generation FishAudio S2-Pro (Production)

FishAudio S2-Pro (4.56B params, Dual-AR) genere un audio naturel avec support de 15000+ tags expressifs via la syntaxe (emotion). Le service tourne en Docker sur GPU1 (RTX 3090 24GB).

FISHAUDIO_URL = os.getenv("FISHAUDIO_URL", "http://localhost:8197")

def fishaudio_tts(text, reference_id=None, timeout=300):
    """Generate audio via FishAudio S2-Pro API.

    Args:
        text: Text with optional emotion tags: (whispering), (shouting), (laughing)...
        reference_id: Optional voice reference ID for voice cloning
        timeout: Request timeout in seconds (300s for long texts)

    Rend les bytes audio, ou None en cas d'echec d'appel. Le journal des echecs
    est agrege par l'appelant (une ligne par appel inonderait la sortie sur un
    service indisponible : #27177).
    """
    payload = {"text": text}
    if reference_id:
        payload["reference_id"] = reference_id
    try:
        resp = requests.post(
            f"{FISHAUDIO_URL}/v1/tts",
            json=payload,
            timeout=timeout,
        )
        resp.raise_for_status()
        return resp.content
    except requests.RequestException:
        return None

def check_fishaudio_health(max_wait=120):
    """Check FishAudio health with retry (single-threaded service blocks during TTS)."""
    deadline = time.time() + max_wait
    while time.time() < deadline:
        try:
            resp = requests.get(f"{FISHAUDIO_URL}/v1/health", timeout=10)
            if resp.status_code == 200:
                return True
        except requests.RequestException:
            pass
        time.sleep(5)
    return False

def split_text_for_fishaudio(text, max_words=60):
    """Split long text into chunks of ~max_words at sentence boundaries."""
    words = text.split()
    if len(words) <= max_words:
        return [text]
    chunks = []
    current = []
    for word in words:
        current.append(word)
        if len(current) >= max_words and word.endswith(('.', '!', '?', ',', ';')):
            chunks.append(' '.join(current))
            current = []
    if current:
        chunks.append(' '.join(current))
    return chunks

def concatenate_wav_files(wav_files, output_path, silence_duration=0.3):
    """Concatenate multiple WAV files with silence gaps between them."""
    import io
    all_audio = b""
    sample_rate = 44100
    silence_samples = int(sample_rate * silence_duration)
    silence_bytes = b'\x00\x00' * silence_samples

    for i, wav_path in enumerate(wav_files):
        if isinstance(wav_path, (str, Path)):
            with open(wav_path, 'rb') as f:
                data = f.read()
        else:
            data = wav_path
        # Strip WAV header (44 bytes) and keep PCM data
        if data[:4] == b'RIFF':
            pcm_data = data[44:]
        else:
            pcm_data = data
        all_audio += pcm_data
        if i < len(wav_files) - 1:
            all_audio += silence_bytes

    # Build WAV header
    data_size = len(all_audio)
    header = struct.pack('<4sI4s', b'RIFF', 36 + data_size, b'WAVE')
    header += struct.pack('<4sIHHIIHH', b'fmt ', 16, 1, 1, sample_rate,
                          sample_rate * 2, 2, 16)
    header += struct.pack('<4sI', b'data', data_size)

    with open(output_path, 'wb') as f:
        f.write(header + all_audio)
    return output_path

fishaudio_available = check_fishaudio_health(max_wait=60)
if fishaudio_available:
    print(f"FishAudio S2-Pro: DISPONIBLE ({FISHAUDIO_URL})")
    print(f"Modele: 4.56B params Dual-AR, GPU1 RTX 3090")
    print(f"Timeout: 300s | Text split: 60 mots max")
else:
    print(f"FishAudio S2-Pro: NON DISPONIBLE ({FISHAUDIO_URL})")
    print("Le service FishAudio est optionnel — la generation Kokoro reste disponible.")
FishAudio S2-Pro: DISPONIBLE (http://localhost:8197)
Modele: 4.56B params Dual-AR, GPU1 RTX 3090
Timeout: 300s | Text split: 60 mots max
# Tag mapping: P3 bracket notation -> FishAudio parenthesis notation
TAG_MAP = {
    "whisper": "whispering",
    "shout": "shouting",
    "scream": "screaming",
    "laugh": "laughing",
    "pause": None,
    "breath": "sighing",
    "cold": "(cold tone) ",
    "timid": "(timid tone) ",
    "angry": "(angry tone) ",
    "sad": "(sad tone) ",
    "excited": "(excitedly) ",
    "nervous": "(nervously) ",
    "gentle": "(gently) ",
    "firm": "(firmly) ",
    "mocking": "(mockingly) ",
    "whispered": "whispering",
    "shouted": "shouting",
}

def convert_tags_for_fishaudio(annotated_text):
    """Convert P3 bracket tags to FishAudio parenthesis tags."""
    import re
    result = annotated_text
    for bracket_tag, fish_tag in TAG_MAP.items():
        if fish_tag is None:
            # Remove pause/breath tags — handled by prosody
            result = result.replace(f"[{bracket_tag}]", "")
        elif fish_tag.startswith("("):
            # Already in parenthesis format
            result = result.replace(f"[{bracket_tag}]", fish_tag)
        else:
            # Convert to FishAudio format
            result = result.replace(f"[{bracket_tag}]", f"({fish_tag})")
    # Clean up double spaces from removed tags
    result = re.sub(r'\s+', ' ', result).strip()
    return result

print(f"Tag mapping: {len(TAG_MAP)} tags")
print(f"Exemple: '[whisper] Bonjour' -> '{convert_tags_for_fishaudio('[whisper] Bonjour')}'")
print(f"Exemple: '[shout] Au revoir' -> '{convert_tags_for_fishaudio('[shout] Au revoir')}'")
print(f"Exemple: '[cold] Je vois' -> '{convert_tags_for_fishaudio('[cold] Je vois')}'")
Tag mapping: 17 tags
Exemple: '[whisper] Bonjour' -> '(whispering) Bonjour'
Exemple: '[shout] Au revoir' -> '(shouting) Au revoir'
Exemple: '[cold] Je vois' -> '(cold tone) Je vois'

Exercice : Etendre le convertisseur de tags pour un nouveau modèle TTS

Duree estimee : 15 minutes

Objectif : Ajouter un troisieme format de sortie au convertisseur convert_tags_for_fishaudio : le format SSML standard. Les tags P3 comme [whisper] doivent devenir <prosody rate="slow" volume="soft">, [shout] devient <prosody rate="fast" volume="loud">, etc.

Contexte : En production, certains moteurs TTS (Google Cloud TTS, Amazon Polly) utilisent le SSML standard plutot que les tags FishAudio. Le convertisseur doit supporter plusieurs formats de sortie.

  • Étape 1 : Définir le mapping P3 vers SSML (whisper -> prosody soft, shout -> prosody loud, etc.)
  • Étape 2 : Implementer convert_tags_to_ssml(annotated_text) qui remplace les tags P3 par des balises SSML
  • Étape 3 : Tester sur les segments annotes et verifier que le SSML est bien forme

Indice : SSML utilise des balises ouvrantes/fermantes : <prosody volume="soft">texte</prosody> Indice : Les tags de pause P3 [pause] deviennent <break time="500ms"/> en SSML Indice : Testez avec xml.etree.ElementTree pour verifier que le SSML est valide

# TODO etudiant : convertisseur P3 vers SSML
# Etape 1 : Mapping P3 -> SSML
SSML_MAP = {}  # TODO etudiant : {"whisper": '<prosody volume="soft">', "shout": '<prosody volume="loud">', ...}

# Etape 2 : Fonction de conversion
def convert_tags_to_ssml(annotated_text):
    """Convertit les tags P3 [bracket] en balises SSML standard."""
    # TODO etudiant : remplacer chaque [tag] par l'equivalent SSML
    return ""  # TODO etudiant

# Etape 3 : Tester sur quelques segments
test_texts = [
    "[whisper] Bonjour, dit-elle.",
    "[shout] Jamais ! cria-t-elle.",
    "[pause] Le silence s'installa. [cold] C'est regrettable.",
]
# TODO etudiant : appliquer convert_tags_to_ssml et afficher

print("Exercice a completer")
Exercice a completer

Decoupage intelligent des segments (LLM)

Les segments longs (>55 mots) doivent etre decoupes pour FishAudio. Un decoupage naif par comptage de mots coupe au milieu d’une phrase ou d’une scene. Cette étape utilise un LLM pour decouper aux frontieres naturelles du texte : fins de phrase, changements de scene, transitions narratif/dialogue.

La fonction llm_split_segment() envoie le texte a gpt-5.6-luna qui identifie les points de coupure optimaux, avec un fallback sur le decoupage par phrase si le LLM est indisponible.

from openai import OpenAI

# Cle optionnelle : sans OPENAI_API_KEY le client reste absent et le decoupage
# deterministe de repli s'applique (le carnet reste executable de bout en bout).
_openai_key = os.getenv("OPENAI_API_KEY")
try:
    openai_client = OpenAI(api_key=_openai_key) if _openai_key else None
except Exception:
    openai_client = None


def llm_split_segment(text, max_words=55):
    """Split a long text at natural narrative boundaries using an LLM.

    Falls back to sentence-based splitting if the LLM is unavailable. Silencieux :
    le journal est porte par l'appelant (un print par appel inonderait la sortie :
    #27177).
    """
    words = text.split()
    if len(words) <= max_words:
        return [text]

    if openai_client is None:
        return split_text_for_fishaudio(text, max_words=max_words)

    prompt = (
        "Decoupe le texte suivant en 2 a 3 parties pour la synthese vocale.\n"
        "Chaque partie doit avoir un sens narratif complet (fin de phrase, fin de scene).\n"
        "Conserve exactement le meme texte, coupes aux positions naturelles.\n"
        "Ne reformule rien. Respecte les balises emotion (parentheses).\n"
        f"Texte: {text}\n"
        "Reponds UNIQUEMENT avec les parties separees par |||"
    )
    try:
        resp = openai_client.chat.completions.create(
            # Cible chat-mini de la generation courante : table de correspondance
            # docs/genai/model-mapping-openai.md (tranche 1 de #14755).
            model="gpt-5.6-luna",
            messages=[{"role": "user", "content": prompt}],
            # La famille gpt-5 refuse deux parametres que les familles 4.x acceptent
            # (mesure live du 2026-11-07, table de reference
            # docs/genai/parametres-par-modele.md) :
            #   - `max_tokens` : 400 "Unsupported parameter ... Use 'max_completion_tokens'"
            #   - `temperature` : 400 "Unsupported value ... Only the default (1) value is
            #     supported" -- le parametre est donc retire, la valeur par defaut s'applique
            # Sans ce correctif, l'appel echoue, la cellule bascule sur le decoupage de
            # repli, et la sortie affiche une erreur que l'etudiant ne peut pas resoudre
            # en lisant le cours (#24114).
            max_completion_tokens=1000,
        )
        parts = resp.choices[0].message.content.strip().split("|||")
        parts = [p.strip() for p in parts if p.strip()]
        if len(parts) >= 2:
            return parts
    except Exception:
        pass

    return split_text_for_fishaudio(text, max_words=max_words)


# Test sur un segment long
test_long = "La diligence partit dans la neige. Dans la voiture, neuf passagers se tenaient serres : le marchand de vins Loiseau et sa femme, le republican Cornudet, la comtesse de Breville, le manufacturier Carre-Lamadon et son epouse, le comte Hubert de Breville, les bonnes soeurs, et Elisabeth Rousset, dite Boule de Suif, une prostituee de grand renom."
parts = llm_split_segment(test_long)
for i, p in enumerate(parts):
    print(f"  Part {i+1} ({len(p.split())} mots): {p[:60]}...")
  Part 1 (56 mots): La diligence partit dans la neige. Dans la voiture, neuf pas...

Le decoupage par LLM vise a respecter les frontieres narratives naturelles du texte (fins de phrase, changements de scene) plutot que de couper mecaniquement après N mots. Au moment de cette exécution, le LLM etait indisponible : la generation FishAudio qui suit a donc utilise le decoupage déterministe de repli, coupe sur la ponctuation et la longueur, sans interpretation narrative. Le mécanisme de cache evite de regenerer les segments déjà produits. Dès que le LLM redeviendra accessible, la même cellule bascule sur le decoupage LLM sans autre changement de code.

FISH_OUTPUT_DIR = BASE_DIR / "tts_output_fishaudio"
FISH_OUTPUT_DIR.mkdir(exist_ok=True, parents=True)
SUB_DIR = FISH_OUTPUT_DIR / "sub_segments"
SUB_DIR.mkdir(exist_ok=True)

fish_generated = []
JOURNAL_EVERY = 25  # journal echantillonne : une ligne tous les 25 segments
fish_cached = 0

if fishaudio_available:
    fish_t_start = time.time()

    for i, req in enumerate(tts_requests, start=1):
        fish_text = convert_tags_for_fishaudio(req.annotated_text)
        output_name = f"fish_seg_{req.seg_index:02d}_{req.fish_preset}.wav"
        output_path = FISH_OUTPUT_DIR / output_name

        # Skip if already successfully generated (>10KB = valid audio)
        if output_path.exists() and output_path.stat().st_size > 10000:
            existing_data = output_path.read_bytes()
            dur = audio_duration_s(existing_data)
            fish_generated.append(TTSRequest(
                seg_index=req.seg_index, seg_type=req.seg_type,
                speaker=req.speaker, text=req.text,
                annotated_text=fish_text, kokoro_voice=req.kokoro_voice,
                fish_preset=req.fish_preset, tags=req.tags,
                output_file=str(output_path), duration_s=dur,
                file_size_kb=len(existing_data) / 1024, status="success",
            ))
            fish_cached += 1
            if i % JOURNAL_EVERY == 0 or i == len(tts_requests):
                print(f"[{i}/{len(tts_requests)}] seg {req.seg_index:2d} ({req.seg_type:12s}): CACHED ({dur:.1f}s)")
            continue

        # Use LLM-based splitting for natural narrative boundaries
        chunks = llm_split_segment(fish_text, max_words=55)
        if i % JOURNAL_EVERY == 0 or i == len(tts_requests):
            print(f"[{i}/{len(tts_requests)}] seg {req.seg_index:2d} ({req.seg_type:12s}, {req.speaker}): "
                  f"{len(chunks)} chunk(s), {len(req.text.split())} mots")

        chunk_files = []
        all_ok = True
        max_retries = 2

        for ci, chunk in enumerate(chunks):
            chunk_name = f"sub_{req.seg_index:02d}_{ci}_{req.fish_preset}.wav"
            chunk_path = SUB_DIR / chunk_name

            audio_data = None
            for attempt in range(max_retries):
                audio_data = fishaudio_tts(chunk, timeout=300)

                if audio_data and len(audio_data) > 1000:
                    with open(chunk_path, "wb") as f:
                        f.write(audio_data)
                    chunk_files.append(chunk_path)
                    break
                else:
                    # Echec de ce chunk : on retente, en silence. Le compte des
                    # segments en echec est porte par le journal final — une ligne
                    # par chunk (ou par essai) inonderait la sortie quand le service
                    # est indisponible (#27177).
                    if attempt < max_retries - 1:
                        time.sleep(5)

            if not audio_data or len(audio_data) <= 1000:
                all_ok = False
                break

            # Pause between chunks (FishAudio is single-threaded, no healthcheck needed)
            if ci < len(chunks) - 1:
                time.sleep(3)

        if all_ok and chunk_files:
            import shutil
            if len(chunk_files) == 1:
                shutil.copy2(chunk_files[0], output_path)
            else:
                concatenate_wav_files(chunk_files, output_path)

            final_data = output_path.read_bytes()
            final_dur = audio_duration_s(final_data)
            fish_generated.append(TTSRequest(
                seg_index=req.seg_index, seg_type=req.seg_type,
                speaker=req.speaker, text=req.text,
                annotated_text=fish_text, kokoro_voice=req.kokoro_voice,
                fish_preset=req.fish_preset, tags=req.tags,
                output_file=str(output_path), duration_s=final_dur,
                file_size_kb=len(final_data) / 1024, status="success",
            ))
            if i % JOURNAL_EVERY == 0 or i == len(tts_requests):
                print(f"  => Seg {req.seg_index}: SUCCESS ({final_dur:.1f}s, {len(final_data)/1024:.0f}KB)")
        else:
            # Segment en echec : comptabilise par le journal final (ok/total), pas
            # imprime ligne a ligne.
            fish_generated.append(TTSRequest(
                seg_index=req.seg_index, seg_type=req.seg_type,
                speaker=req.speaker, text=req.text,
                annotated_text=fish_text, kokoro_voice=req.kokoro_voice,
                fish_preset=req.fish_preset, tags=req.tags,
                status="failed",
            ))

        # Pause between segments
        time.sleep(2)

    fish_elapsed = time.time() - fish_t_start
    fish_ok = sum(1 for r in fish_generated if r.status == "success")
    fish_failed = len(fish_generated) - fish_ok
    print(f"\n{'='*60}")
    print(f"FishAudio: {fish_ok}/{len(fish_generated)} segments in {fish_elapsed:.0f}s "
          f"({fish_cached} reloaded from disk cache"
          + (f", {fish_failed} en echec)" if fish_failed else ")"))
else:
    print("FishAudio S2-Pro non disponible — generation skippee")
    print("Demarrer le service: docker compose -f docker-configurations/services/tts-fishaudio/docker-compose.yml up -d")
[25/342] seg 24 (narration   ): CACHED (22.3s)
[50/342] seg 49 (narration   ): CACHED (11.9s)
[75/342] seg 74 (narration   ): CACHED (38.1s)
[100/342] seg 99 (narration   ): CACHED (32.0s)
[125/342] seg 124 (narration   ): CACHED (2.7s)
[150/342] seg 149 (narration   ): CACHED (1.9s)
[175/342] seg 174 (narration   ): CACHED (0.9s)
[200/342] seg 199 (narration   ): CACHED (3.0s)
[225/342] seg 224 (dialogue    ): CACHED (2.4s)
[250/342] seg 249 (narration   ): CACHED (8.6s)
[275/342] seg 274 (narration   ): CACHED (2.0s)
[300/342] seg 299 (narration   ): CACHED (14.5s)
[325/342] seg 324 (narration   ): CACHED (10.0s)
[342/342] seg 341 (narration   ): CACHED (10.4s)

============================================================
FishAudio: 342/342 segments in 2s (342 reloaded from disk cache)

Les 342 segments ont ete generes avec succes via FishAudio S2-Pro, avec le decoupage déterministe de repli (LLM indisponible, cf. cellule précédente). Les segments longs (>60 mots) ont ete decoupes en sous-parties sur les limites de phrases (~60 mots par partie), puis reassembles par concatenation WAV : 450 sous-parties sont conservees dans tts_output_fishaudio/sub_segments/. Chaque segment beneficie des tags expressifs convertis depuis la notation P3.

if fish_generated:
    kokoro_dur = sum(r.duration_s for r in generated if r.status == "success")
    fish_dur = sum(r.duration_s for r in fish_generated if r.status == "success")
    kokoro_size = sum(r.file_size_kb for r in generated if r.status == "success")
    fish_size = sum(r.file_size_kb for r in fish_generated if r.status == "success")

    print("Comparaison Kokoro vs FishAudio S2-Pro:")
    print(f"  {'':20s} | {'Kokoro':>10s} | {'FishAudio':>10s}")
    print(f"  {'Segments':20s} | {len(generated):>10d} | {len(fish_generated):>10d}")
    print(f"  {'Duree totale':20s} | {kokoro_dur:>9.1f}s | {fish_dur:>9.1f}s")
    print(f"  {'Taille totale':20s} | {kokoro_size:>8.0f}KB | {fish_size:>8.0f}KB")
    print(f"  {'Duree moy/seg':20s} | {kokoro_dur/len(generated):>9.1f}s | {fish_dur/max(len(fish_generated),1):>9.1f}s")
    print(f"  {'Format audio':20s} | {'MP3':>10s} | {'WAV':>10s}")
    print(f"  {'Tags expressifs':20s} | {'Non':>10s} | {'Oui (15000+)':>10s}")
else:
    print("FishAudio non disponible — comparaison impossible")
    print("Le service FishAudio S2-Pro doit tourner sur le port 8197")
Comparaison Kokoro vs FishAudio S2-Pro:
                       |     Kokoro |  FishAudio
  Segments             |        342 |        342
  Duree totale         |    6129.7s |    5064.2s
  Taille totale        |    95777KB |   436209KB
  Duree moy/seg        |      17.9s |      14.8s
  Format audio         |        MP3 |        WAV
  Tags expressifs      |        Non | Oui (15000+)

Le tableau comparatif met en evidence un ecart significatif sur la taille des fichiers : FishAudio genere des WAV non compresses (436 209 KB au total, ~1275 KB par segment en moyenne) contre des MP3 compresses pour Kokoro (95 777 KB, ~280 KB par segment), soit un ratio de ~4,5x. La duree totale differe aussi : 5064,2 s pour FishAudio contre 6129,7 s pour Kokoro (-17,4 %) — sur ce corpus a dominante narrative, FishAudio synthetise sensiblement plus vite que Kokoro.

# Export FishAudio generation metadata for P5
fish_meta = {
    "epic": "1273",
    "pass": "P4b",
    "description": "TTS generation via FishAudio S2-Pro for audiobook production",
    "source_text": "Boule de Suif - Guy de Maupassant",
    "tts_model": "fishaudio-s2-pro",
    "tts_service_url": FISHAUDIO_URL,
    "stats": {
        "total_segments": len(tts_requests),
        "fish_generated": len(fish_generated),
        "fish_successful": sum(1 for r in fish_generated if r.status == "success"),
        "fish_total_duration_s": sum(r.duration_s for r in fish_generated if r.status == "success"),
    },
    "segments": [asdict(r) for r in fish_generated],
}

fish_meta_path = FISH_OUTPUT_DIR / "fish_generation_metadata.json"
with open(fish_meta_path, "w", encoding="utf-8") as f:
    json.dump(fish_meta, f, ensure_ascii=False, indent=2)

print(f"FishAudio metadata saved: {fish_meta_path.name}")
print(f"Segments: {fish_meta['stats']['fish_successful']}/{fish_meta['stats']['total_segments']}")
if fish_generated:
    fish_dur = fish_meta['stats']['fish_total_duration_s']
    print(f"Total FishAudio audio: {fish_dur:.1f}s ({fish_dur/60:.1f}min)")
else:
    print("No FishAudio segments generated")
FishAudio metadata saved: fish_generation_metadata.json
Segments: 342/342
Total FishAudio audio: 5064.2s (84.4min)

Compilation des livres audio complets

Deux assemblages bout-en-bout sont produits :

  • FishAudio S2-Pro (WAV) : les segments generes sont concatene en un seul fichier PCM non compresse (tts_output_fishaudio/boule_de_suif_fishaudio_complete.wav), avec des silences de 0.5 s entre les segments pour marquer les transitions narratif/dialogue (concatenation maison, sans dépendance externe).
  • Kokoro (MP3) : les segments tts_output/*.mp3 sont assembles via ffmpeg (demuxer concat + encodeur libmp3lame 128 kbps, silences de 0.5 s generes par anullsrc) en audiobook_kokoro.mp3 — la même technique de compilation que le notebook 04-12.

Les deux fichiers complets restent sur disque (artefacts de production). La section Comparaison ci-dessous embarque un extrait de 30 s de chacun pour l’ecoute cote a cote : les 28 players par segment embarquent déjà l’integralite des deux rendus, doubler le notebook avec deux livres entiers n’apporterait rien de plus.

if fish_generated:
    success_segments = sorted(
        [r for r in fish_generated if r.status == "success"],
        key=lambda r: r.seg_index
    )
    if len(success_segments) >= 10:
        wav_files = [r.output_file for r in success_segments]
        audiobook_path = FISH_OUTPUT_DIR / "boule_de_suif_fishaudio_complete.wav"
        concatenate_wav_files(wav_files, audiobook_path, silence_duration=0.5)

        ab_data = audiobook_path.read_bytes()
        ab_dur = audio_duration_s(ab_data)
        print(f"Livre audio complet: {audiobook_path.name}")
        print(f"  Duree: {ab_dur:.1f}s ({ab_dur/60:.1f}min)")
        print(f"  Taille: {len(ab_data)/1024:.0f}KB")
        print(f"  Segments: {len(success_segments)}/{len(fish_generated)}")
        print(f"  Silences: 0.5s entre segments")
        print()

        for r in success_segments:
            dur_str = f"{r.duration_s:.1f}s"
            print(f"  Seg {r.seg_index:2d} | {r.seg_type:12s} | {r.speaker:25s} | {dur_str}")
    else:
        print(f"Seulement {len(success_segments)}/{len(fish_generated)} segments OK")
        print("Audiobook non compile — generation incomplete")
else:
    print("Aucun segment FishAudio genere — audiobook non disponible")
# --- Compilation Kokoro (MP3) : assemblage ffmpeg des segments tts_output ---
# Meme technique que 04-12 (demuxer concat + libmp3lame 128 kbps, silences anullsrc).
import subprocess

_kokoro_meta_c = TTS_OUTPUT_DIR / "tts_generation_metadata.json"
if _kokoro_meta_c.exists():
    _kokoro_ok = [
        s for s in json.loads(_kokoro_meta_c.read_text(encoding="utf-8"))["segments"]
        if s.get("status") == "success"
    ]
    if len(_kokoro_ok) >= 10:
        _compile_dir = BASE_DIR / "audiobook_compile"
        _compile_dir.mkdir(exist_ok=True, parents=True)

        # Silence MP3 0.5 s (mono 24 kHz 128 kbps — parametres des segments kokoro)
        _silence = _compile_dir / "silence_500ms.mp3"
        _res_sil = subprocess.run(
            ["ffmpeg", "-y", "-f", "lavfi", "-i", "anullsrc=r=24000:cl=mono",
             "-t", "0.5", "-b:a", "128k", str(_silence)],
            capture_output=True, text=True, encoding="utf-8", errors="replace")

        if _res_sil.returncode == 0:
            _concat_list = _compile_dir / "concat_list.txt"
            with open(_concat_list, "w", encoding="utf-8") as f:
                _ordered = sorted(_kokoro_ok, key=lambda s: s["seg_index"])
                for _i, _seg in enumerate(_ordered):
                    f.write(f"file '{(BASE_DIR / _seg['output_file']).resolve()}'\n")
                    if _i < len(_ordered) - 1:
                        f.write(f"file '{_silence.resolve()}'\n")

            kokoro_audiobook_path = BASE_DIR / "audiobook_kokoro.mp3"
            _res_cat = subprocess.run(
                ["ffmpeg", "-y", "-f", "concat", "-safe", "0",
                 "-i", str(_concat_list),
                 "-c:a", "libmp3lame", "-b:a", "128k",
                 str(kokoro_audiobook_path)],
                capture_output=True, text=True, encoding="utf-8", errors="replace")

            if _res_cat.returncode == 0:
                _kb = kokoro_audiobook_path.read_bytes()
                _kdur = audio_duration_s(_kb)
                print(f"Livre audio complet Kokoro: {kokoro_audiobook_path.name}")
                print(f"  Duree: {_kdur:.1f}s ({_kdur/60:.1f}min)")
                print(f"  Taille: {len(_kb)/1024:.0f}KB")
                print(f"  Segments: {len(_kokoro_ok)} | Silences: 0.5s | ffmpeg libmp3lame 128k")
            else:
                print(f"Erreur concatenation Kokoro: {_res_cat.stderr[:300]}")
        else:
            print("Erreur generation du silence ffmpeg")
    else:
        print(f"Segments Kokoro insuffisants ({len(_kokoro_ok)}) — compilation MP3 ignoree")
else:
    print("Metadonnees Kokoro absentes — compilation MP3 ignoree")
Livre audio complet: boule_de_suif_fishaudio_complete.wav
  Duree: 5234.7s (87.2min)
  Taille: 450880KB
  Segments: 342/342
  Silences: 0.5s entre segments

  Seg  0 | narration    | Narrateur                 | 1.2s
  Seg  1 | narration    | Narrateur                 | 56.9s
  Seg  2 | narration    | Narrateur                 | 12.1s
  Seg  3 | narration    | Narrateur                 | 36.6s
  Seg  4 | narration    | Narrateur                 | 3.5s
  Seg  5 | narration    | Narrateur                 | 27.8s
  Seg  6 | narration    | Narrateur                 | 26.8s
  Seg  7 | narration    | Narrateur                 | 14.3s
  Seg  8 | narration    | Narrateur                 | 3.8s
  Seg  9 | narration    | Narrateur                 | 3.5s
  Seg 10 | narration    | Narrateur                 | 33.6s
  Seg 11 | narration    | Narrateur                 | 72.1s
  Seg 12 | narration    | Narrateur                 | 13.3s
  Seg 13 | narration    | Narrateur                 | 65.8s
  Seg 14 | narration    | Narrateur                 | 23.9s
  Seg 15 | narration    | Narrateur                 | 23.0s
  Seg 16 | narration    | Narrateur                 | 17.1s
  Seg 17 | narration    | Narrateur                 | 36.6s
  Seg 18 | narration    | Narrateur                 | 5.2s
  Seg 19 | narration    | Narrateur                 | 26.5s
  Seg 20 | narration    | Narrateur                 | 7.9s
  Seg 21 | narration    | Narrateur                 | 12.3s
  Seg 22 | narration    | Narrateur                 | 11.7s
  Seg 23 | narration    | Narrateur                 | 7.1s
  Seg 24 | narration    | Narrateur                 | 22.3s
  Seg 25 | dialogue     | Narrateur (locuteur non résolu) | 1.3s
  Seg 26 | narration    | Narrateur                 | 0.5s
  Seg 27 | dialogue     | Narrateur (locuteur non résolu) | 1.9s
  Seg 28 | narration    | Narrateur                 | 1.6s
  Seg 29 | dialogue     | Narrateur (locuteur non résolu) | 6.0s
  Seg 30 | narration    | Narrateur                 | 4.2s
  Seg 31 | narration    | Narrateur                 | 37.5s
  Seg 32 | narration    | Narrateur                 | 9.1s
  Seg 33 | narration    | Narrateur                 | 29.3s
  Seg 34 | narration    | Narrateur                 | 24.2s
  Seg 35 | dialogue     | Narrateur (locuteur non résolu) | 4.4s
  Seg 36 | narration    | Narrateur                 | 13.6s
  Seg 37 | narration    | Narrateur                 | 17.0s
  Seg 38 | narration    | Narrateur                 | 8.7s
  Seg 39 | dialogue     | Narrateur (locuteur non résolu) | 1.8s
  Seg 40 | narration    | Narrateur                 | 2.3s
  Seg 41 | dialogue     | Narrateur (locuteur non résolu) | 0.6s
  Seg 42 | narration    | Narrateur                 | 2.5s
  Seg 43 | narration    | Narrateur                 | 24.2s
  Seg 44 | narration    | Narrateur                 | 27.4s
  Seg 45 | narration    | Narrateur                 | 5.5s
  Seg 46 | narration    | Narrateur                 | 9.7s
  Seg 47 | narration    | Narrateur                 | 17.3s
  Seg 48 | narration    | Narrateur                 | 27.8s
  Seg 49 | narration    | Narrateur                 | 11.9s
  Seg 50 | dialogue     | Narrateur (locuteur non résolu) | 2.0s
  Seg 51 | narration    | Narrateur                 | 6.5s
  Seg 52 | narration    | Narrateur                 | 11.7s
  Seg 53 | narration    | Narrateur                 | 34.8s
  Seg 54 | narration    | Narrateur                 | 10.9s
  Seg 55 | narration    | Narrateur                 | 26.2s
  Seg 56 | narration    | Narrateur                 | 33.2s
  Seg 57 | narration    | Narrateur                 | 7.6s
  Seg 58 | narration    | Narrateur                 | 9.6s
  Seg 59 | narration    | Narrateur                 | 27.2s
  Seg 60 | narration    | Narrateur                 | 5.0s
  Seg 61 | narration    | Narrateur                 | 62.5s
  Seg 62 | narration    | Narrateur                 | 6.1s
  Seg 63 | narration    | Narrateur                 | 50.7s
  Seg 64 | narration    | Narrateur                 | 4.2s
  Seg 65 | narration    | Narrateur                 | 22.8s
  Seg 66 | narration    | Narrateur                 | 19.6s
  Seg 67 | narration    | Narrateur                 | 43.7s
  Seg 68 | narration    | Narrateur                 | 14.1s
  Seg 69 | narration    | Narrateur                 | 25.7s
  Seg 70 | narration    | Narrateur                 | 12.1s
  Seg 71 | narration    | Narrateur                 | 15.7s
  Seg 72 | narration    | Narrateur                 | 16.5s
  Seg 73 | narration    | Narrateur                 | 17.3s
  Seg 74 | narration    | Narrateur                 | 38.1s
  Seg 75 | narration    | Narrateur                 | 12.2s
  Seg 76 | dialogue     | Monsieur Loiseau          | 4.1s
  Seg 77 | narration    | Narrateur                 | 29.3s
  Seg 78 | narration    | Narrateur                 | 12.5s
  Seg 79 | narration    | Narrateur                 | 34.2s
  Seg 80 | narration    | Narrateur                 | 24.3s
  Seg 81 | narration    | Narrateur                 | 4.7s
  Seg 82 | dialogue     | Monsieur Loiseau          | 6.8s
  Seg 83 | narration    | Narrateur                 | 15.7s
  Seg 84 | dialogue     | Monsieur Loiseau          | 5.0s
  Seg 85 | narration    | Narrateur                 | 15.3s
  Seg 86 | narration    | Narrateur                 | 22.3s
  Seg 87 | narration    | Narrateur                 | 26.4s
  Seg 88 | dialogue     | Mme Loiseau               | 1.3s
  Seg 89 | narration    | Narrateur                 | 5.2s
  Seg 90 | dialogue     | Mme Loiseau               | 2.2s
  Seg 91 | narration    | Narrateur                 | 3.6s
  Seg 92 | narration    | Narrateur                 | 15.5s
  Seg 93 | narration    | Narrateur                 | 56.4s
  Seg 94 | dialogue     | Les bonnes soeurs         | 2.3s
  Seg 95 | narration    | Narrateur                 | 38.3s
  Seg 96 | narration    | Narrateur                 | 8.5s
  Seg 97 | dialogue     | Narrateur (locuteur non résolu) | 2.7s
  Seg 98 | narration    | Narrateur                 | 25.5s
  Seg 99 | narration    | Narrateur                 | 32.0s
  Seg 100 | narration    | Narrateur                 | 71.4s
  Seg 101 | narration    | Narrateur                 | 35.1s
  Seg 102 | narration    | Narrateur                 | 58.4s
  Seg 103 | narration    | Narrateur                 | 13.9s
  Seg 104 | narration    | Narrateur                 | 24.3s
  Seg 105 | narration    | Narrateur                 | 15.7s
  Seg 106 | narration    | Narrateur                 | 15.1s
  Seg 107 | narration    | Narrateur                 | 16.0s
  Seg 108 | narration    | Narrateur                 | 9.2s
  Seg 109 | narration    | Narrateur                 | 19.4s
  Seg 110 | description  | Narrateur                 | 35.0s
  Seg 111 | narration    | Narrateur                 | 4.9s
  Seg 112 | dialogue     | Narrateur (locuteur non résolu) | 2.2s
  Seg 113 | narration    | Narrateur                 | 17.6s
  Seg 114 | dialogue     | Officier prussien         | 1.0s
  Seg 115 | narration    | Narrateur                 | 8.9s
  Seg 116 | narration    | Narrateur                 | 39.7s
  Seg 117 | narration    | Narrateur                 | 18.3s
  Seg 118 | narration    | Narrateur                 | 1.2s
  Seg 119 | dialogue     | Narrateur (locuteur non résolu) | 0.9s
  Seg 120 | narration    | Narrateur                 | 1.3s
  Seg 121 | narration    | Narrateur                 | 19.3s
  Seg 122 | narration    | Narrateur                 | 15.1s
  Seg 123 | narration    | Narrateur                 | 1.1s
  Seg 124 | narration    | Narrateur                 | 2.7s
  Seg 125 | narration    | Narrateur                 | 3.0s
  Seg 126 | narration    | Narrateur                 | 0.6s
  Seg 127 | narration    | Narrateur                 | 4.2s
  Seg 128 | narration    | Narrateur                 | 0.8s
  Seg 129 | narration    | Narrateur                 | 3.5s
  Seg 130 | narration    | Narrateur                 | 3.3s
  Seg 131 | narration    | Narrateur                 | 3.1s
  Seg 132 | narration    | Narrateur                 | 8.2s
  Seg 133 | narration    | Narrateur                 | 16.0s
  Seg 134 | narration    | Narrateur                 | 13.9s
  Seg 135 | narration    | Narrateur                 | 2.5s
  Seg 136 | narration    | Narrateur                 | 2.0s
  Seg 137 | narration    | Narrateur                 | 1.3s
  Seg 138 | narration    | Narrateur                 | 3.7s
  Seg 139 | narration    | Narrateur                 | 9.8s
  Seg 140 | narration    | Narrateur                 | 8.1s
  Seg 141 | dialogue     | Narrateur (locuteur non résolu) | 5.0s
  Seg 142 | narration    | Narrateur                 | 7.7s
  Seg 143 | dialogue     | Narrateur (locuteur non résolu) | 3.7s
  Seg 144 | narration    | Narrateur                 | 60.0s
  Seg 145 | narration    | Narrateur                 | 27.6s
  Seg 146 | narration    | Narrateur                 | 6.9s
  Seg 147 | narration    | Narrateur                 | 5.9s
  Seg 148 | narration    | Narrateur                 | 78.5s
  Seg 149 | narration    | Narrateur                 | 1.9s
  Seg 150 | narration    | Narrateur                 | 6.6s
  Seg 151 | narration    | Narrateur                 | 2.2s
  Seg 152 | narration    | Narrateur                 | 7.2s
  Seg 153 | narration    | Narrateur                 | 2.0s
  Seg 154 | narration    | Narrateur                 | 2.2s
  Seg 155 | narration    | Narrateur                 | 25.4s
  Seg 156 | narration    | Narrateur                 | 15.9s
  Seg 157 | narration    | Narrateur                 | 6.3s
  Seg 158 | narration    | Narrateur                 | 59.4s
  Seg 159 | narration    | Narrateur                 | 3.3s
  Seg 160 | narration    | Narrateur                 | 2.1s
  Seg 161 | narration    | Narrateur                 | 6.8s
  Seg 162 | narration    | Narrateur                 | 7.2s
  Seg 163 | narration    | Narrateur                 | 7.8s
  Seg 164 | narration    | Narrateur                 | 13.1s
  Seg 165 | narration    | Narrateur                 | 13.9s
  Seg 166 | dialogue     | Monsieur Loiseau          | 1.0s
  Seg 167 | narration    | Narrateur                 | 18.5s
  Seg 168 | narration    | Narrateur                 | 62.6s
  Seg 169 | narration    | Narrateur                 | 6.9s
  Seg 170 | dialogue     | Narrateur (locuteur non résolu) | 32.3s
  Seg 171 | narration    | Narrateur                 | 25.1s
  Seg 172 | narration    | Narrateur                 | 3.2s
  Seg 173 | narration    | Narrateur                 | 3.0s
  Seg 174 | narration    | Narrateur                 | 0.9s
  Seg 175 | narration    | Narrateur                 | 1.8s
  Seg 176 | narration    | Narrateur                 | 2.0s
  Seg 177 | narration    | Narrateur                 | 3.2s
  Seg 178 | narration    | Narrateur                 | 0.7s
  Seg 179 | narration    | Narrateur                 | 7.9s
  Seg 180 | narration    | Narrateur                 | 1.7s
  Seg 181 | narration    | Narrateur                 | 4.6s
  Seg 182 | narration    | Narrateur                 | 0.7s
  Seg 183 | narration    | Narrateur                 | 5.2s
  Seg 184 | narration    | Narrateur                 | 14.0s
  Seg 185 | narration    | Narrateur                 | 13.9s
  Seg 186 | narration    | Narrateur                 | 47.0s
  Seg 187 | narration    | Narrateur                 | 34.1s
  Seg 188 | narration    | Narrateur                 | 13.0s
  Seg 189 | dialogue     | Officier prussien         | 11.3s
  Seg 190 | narration    | Narrateur                 | 12.8s
  Seg 191 | narration    | Narrateur                 | 4.5s
  Seg 192 | narration    | Narrateur                 | 3.5s
  Seg 193 | narration    | Narrateur                 | 47.1s
  Seg 194 | narration    | Narrateur                 | 1.9s
  Seg 195 | narration    | Narrateur                 | 1.4s
  Seg 196 | narration    | Narrateur                 | 1.7s
  Seg 197 | narration    | Narrateur                 | 1.8s
  Seg 198 | narration    | Narrateur                 | 0.5s
  Seg 199 | narration    | Narrateur                 | 3.0s
  Seg 200 | narration    | Narrateur                 | 1.7s
  Seg 201 | narration    | Narrateur                 | 11.5s
  Seg 202 | narration    | Narrateur                 | 5.7s
  Seg 203 | narration    | Narrateur                 | 2.7s
  Seg 204 | narration    | Narrateur                 | 65.7s
  Seg 205 | narration    | Narrateur                 | 12.4s
  Seg 206 | narration    | Narrateur                 | 11.5s
  Seg 207 | narration    | Narrateur                 | 18.5s
  Seg 208 | narration    | Narrateur                 | 60.0s
  Seg 209 | narration    | Narrateur                 | 7.2s
  Seg 210 | narration    | Narrateur                 | 40.8s
  Seg 211 | narration    | Narrateur                 | 18.2s
  Seg 212 | dialogue     | Narrateur (locuteur non résolu) | 2.9s
  Seg 213 | narration    | Narrateur                 | 9.1s
  Seg 214 | narration    | Narrateur                 | 11.2s
  Seg 215 | narration    | Narrateur                 | 8.6s
  Seg 216 | narration    | Narrateur                 | 33.4s
  Seg 217 | narration    | Narrateur                 | 2.6s
  Seg 218 | narration    | Narrateur                 | 10.2s
  Seg 219 | narration    | Narrateur                 | 22.0s
  Seg 220 | narration    | Narrateur                 | 4.9s
  Seg 221 | narration    | Narrateur                 | 4.9s
  Seg 222 | dialogue     | Comte Hubert de Breville  | 0.8s
  Seg 223 | narration    | Narrateur                 | 23.0s
  Seg 224 | dialogue     | Comte Hubert de Breville  | 2.4s
  Seg 225 | narration    | Narrateur                 | 3.9s
  Seg 226 | dialogue     | Comte Hubert de Breville  | 12.3s
  Seg 227 | narration    | Narrateur                 | 2.1s
  Seg 228 | narration    | Narrateur                 | 4.8s
  Seg 229 | narration    | Narrateur                 | 15.9s
  Seg 230 | narration    | Narrateur                 | 11.7s
  Seg 231 | narration    | Narrateur                 | 12.4s
  Seg 232 | narration    | Narrateur                 | 18.5s
  Seg 233 | narration    | Narrateur                 | 14.9s
  Seg 234 | narration    | Narrateur                 | 7.1s
  Seg 235 | narration    | Narrateur                 | 19.7s
  Seg 236 | narration    | Narrateur                 | 32.0s
  Seg 237 | narration    | Narrateur                 | 3.6s
  Seg 238 | dialogue     | Mme Loiseau               | 52.1s
  Seg 239 | narration    | Narrateur                 | 2.7s
  Seg 240 | narration    | Narrateur                 | 11.2s
  Seg 241 | narration    | Narrateur                 | 20.3s
  Seg 242 | narration    | Narrateur                 | 1.2s
  Seg 243 | narration    | Narrateur                 | 42.6s
  Seg 244 | narration    | Narrateur                 | 34.4s
  Seg 245 | narration    | Narrateur                 | 19.1s
  Seg 246 | narration    | Narrateur                 | 4.1s
  Seg 247 | narration    | Narrateur                 | 8.0s
  Seg 248 | dialogue     | Comte Hubert de Breville  | 0.8s
  Seg 249 | narration    | Narrateur                 | 8.6s
  Seg 250 | narration    | Narrateur                 | 10.3s
  Seg 251 | dialogue     | Narrateur (locuteur non résolu) | 2.1s
  Seg 252 | narration    | Narrateur                 | 7.3s
  Seg 253 | narration    | Narrateur                 | 52.6s
  Seg 254 | narration    | Narrateur                 | 13.7s
  Seg 255 | narration    | Narrateur                 | 8.4s
  Seg 256 | narration    | Narrateur                 | 17.3s
  Seg 257 | narration    | Narrateur                 | 17.3s
  Seg 258 | narration    | Narrateur                 | 13.1s
  Seg 259 | narration    | Narrateur                 | 2.1s
  Seg 260 | dialogue     | Elisabeth Rousset         | 1.1s
  Seg 261 | narration    | Narrateur                 | 67.9s
  Seg 262 | narration    | Narrateur                 | 23.8s
  Seg 263 | narration    | Narrateur                 | 1.3s
  Seg 264 | narration    | Narrateur                 | 6.3s
  Seg 265 | narration    | Narrateur                 | 7.0s
  Seg 266 | narration    | Narrateur                 | 10.9s
  Seg 267 | narration    | Narrateur                 | 74.2s
  Seg 268 | narration    | Narrateur                 | 3.3s
  Seg 269 | narration    | Narrateur                 | 7.9s
  Seg 270 | narration    | Narrateur                 | 2.1s
  Seg 271 | narration    | Narrateur                 | 10.6s
  Seg 272 | narration    | Narrateur                 | 17.0s
  Seg 273 | narration    | Narrateur                 | 13.0s
  Seg 274 | narration    | Narrateur                 | 2.0s
  Seg 275 | narration    | Narrateur                 | 25.2s
  Seg 276 | narration    | Narrateur                 | 15.1s
  Seg 277 | narration    | Narrateur                 | 34.9s
  Seg 278 | dialogue     | Monsieur Loiseau          | 5.3s
  Seg 279 | narration    | Narrateur                 | 22.7s
  Seg 280 | narration    | Narrateur                 | 11.8s
  Seg 281 | dialogue     | Narrateur (locuteur non résolu) | 0.8s
  Seg 282 | narration    | Narrateur                 | 7.5s
  Seg 283 | dialogue     | Narrateur (locuteur non résolu) | 2.0s
  Seg 284 | narration    | Narrateur                 | 3.6s
  Seg 285 | narration    | Narrateur                 | 20.9s
  Seg 286 | dialogue     | Narrateur (locuteur non résolu) | 3.4s
  Seg 287 | narration    | Narrateur                 | 9.6s
  Seg 288 | dialogue     | Narrateur (locuteur non résolu) | 6.0s
  Seg 289 | narration    | Narrateur                 | 12.4s
  Seg 290 | narration    | Narrateur                 | 20.0s
  Seg 291 | narration    | Narrateur                 | 25.7s
  Seg 292 | narration    | Narrateur                 | 2.0s
  Seg 293 | narration    | Narrateur                 | 4.4s
  Seg 294 | narration    | Narrateur                 | 21.7s
  Seg 295 | dialogue     | Monsieur Loiseau          | 3.8s
  Seg 296 | narration    | Narrateur                 | 13.9s
  Seg 297 | narration    | Narrateur                 | 10.0s
  Seg 298 | dialogue     | Comte Hubert de Breville  | 2.3s
  Seg 299 | narration    | Narrateur                 | 14.5s
  Seg 300 | narration    | Narrateur                 | 6.0s
  Seg 301 | narration    | Narrateur                 | 1.3s
  Seg 302 | narration    | Narrateur                 | 1.7s
  Seg 303 | narration    | Narrateur                 | 2.2s
  Seg 304 | narration    | Narrateur                 | 0.8s
  Seg 305 | narration    | Narrateur                 | 0.9s
  Seg 306 | narration    | Narrateur                 | 6.5s
  Seg 307 | narration    | Narrateur                 | 5.1s
  Seg 308 | narration    | Narrateur                 | 3.3s
  Seg 309 | narration    | Narrateur                 | 21.9s
  Seg 310 | narration    | Narrateur                 | 22.2s
  Seg 311 | narration    | Narrateur                 | 26.0s
  Seg 312 | narration    | Narrateur                 | 11.3s
  Seg 313 | narration    | Narrateur                 | 3.9s
  Seg 314 | narration    | Narrateur                 | 15.0s
  Seg 315 | narration    | Narrateur                 | 32.9s
  Seg 316 | narration    | Narrateur                 | 8.3s
  Seg 317 | dialogue     | Mme Loiseau               | 2.5s
  Seg 318 | narration    | Narrateur                 | 18.7s
  Seg 319 | narration    | Narrateur                 | 7.0s
  Seg 320 | narration    | Narrateur                 | 2.2s
  Seg 321 | narration    | Narrateur                 | 1.8s
  Seg 322 | narration    | Narrateur                 | 1.3s
  Seg 323 | narration    | Narrateur                 | 9.8s
  Seg 324 | narration    | Narrateur                 | 10.0s
  Seg 325 | narration    | Narrateur                 | 10.4s
  Seg 326 | narration    | Narrateur                 | 25.0s
  Seg 327 | narration    | Narrateur                 | 2.4s
  Seg 328 | narration    | Narrateur                 | 6.7s
  Seg 329 | narration    | Narrateur                 | 9.7s
  Seg 330 | narration    | Narrateur                 | 31.8s
  Seg 331 | narration    | Narrateur                 | 27.9s
  Seg 332 | narration    | Narrateur                 | 23.2s
  Seg 333 | narration    | Narrateur                 | 63.2s
  Seg 334 | narration    | Narrateur                 | 12.0s
  Seg 335 | dialogue     | Mme Loiseau               | 1.5s
  Seg 336 | narration    | Narrateur                 | 6.3s
  Seg 337 | narration    | Narrateur                 | 16.9s
  Seg 338 | narration    | Narrateur                 | 19.0s
  Seg 339 | narration    | Narrateur                 | 11.3s
  Seg 340 | narration    | Narrateur                 | 28.0s
  Seg 341 | narration    | Narrateur                 | 10.4s
Livre audio complet Kokoro: audiobook_kokoro.mp3
  Duree: 6299.4s (105.0min)
  Taille: 98428KB
  Segments: 342 | Silences: 0.5s | ffmpeg libmp3lame 128k

Lecture de la concatenation WAV : cout de stockage vs flexibilite d edition

Observation cle : boule_de_suif_fishaudio_complete.wav pese 450880 KB pour 5234.7s audio (ratio ~86 KB/s) et l assemblage Kokoro MP3 pese 98428 KB pour 6299.4s (ratio ~15.6 KB/s). Le facteur ~4.5x entre les deux formats est determine par le codec (WAV PCM 16-bit non compresse vs MP3 128 kbps), pas par le contenu. Pour 342 segments + 341 silences de 0.5s (170.5s d audio silencieux), l overhead d assemblage est marginal.

Pourquoi WAV non compresse ici plutot que FLAC : la concatenation maison utilise le format PCM brut (header WAV + données PCM concatenees avec un silence zero-insert). FLAC necessiterait un encodeur, une entete par sous-stream et un re-muxing. Le WAV est le plus simple chemin pour assembler 342 segments sans dépendance externe lourde (hors struct du stdlib). Pour une archive de production, on reconvertira en AAC/Opus/FLAC ulterieurement avec ffmpeg, en gardant le WAV comme source de verite.

Limites de la concatenation maison : (1) pas de normalisation de volume entre segments — si Kokoro seg4 sort a -3 dB et seg5 a -10 dB, la concatenation preserve l ecart (audible comme une saute de volume). FishAudio est plus stable en niveau mais pas garanti constant non plus. (2) pas de crossfade entre segments — les silences de 0.5s sont nets (zero-crossing brutal), pas un fondu. Pour une expérience d ecoute agreable, un crossfade de 50ms masquerait mieux les jonctions. (3) header WAV ecrit a la main : si le futur pipeline veut ajouter des metadonnees (titre, artiste, chapitre), il faudra soit regenerer le header soit basculer sur un muxer (pydub, soundfile).

Implications pour P5 (Compilation) : la cellule de concatenation produit un artefact de production sur disque, pas un livrable utilisateur final. Le notebook suivant (04-12) prend ce WAV en entree, applique les corrections de volume et de crossfade, et exporte le MP3 final avec metadonnees ID3. Le WAV reste disponible comme source pour des regenerations ou des variantes (AAC, Opus, version stereo).

Comparaison detaillee Kokoro vs FishAudio (segment par segment)

Pour chaque segment, vous pouvez ecouter les deux versions et comparer la qualite, l’expressivite et le naturel de la synthese. Cette cellule produit a la fois un tableau quantitatif (durees, tailles, delta) et un comparateur audio interactif (balise HTML <audio controls>) chargeant le MP3 Kokoro et le WAV FishAudio cote a cote. Les players embarquent des extraits de 20 s pour un echantillon de 4 segments : sur le corpus integral (342 segments), l’embarquement complet depasserait la taille de fichier maximale du depot — les fichiers complets restent sur disque (tts_output/, tts_output_fishaudio/).

Lecture du tableau quantitatif (mesures verbatim de la cellule)

Le tableau de la cellule liste les 14 premières lignes du corpus : TOT 449,9 s Kokoro vs 371,2 s FishAudio (delta -78,6 s, soit -17,5 %) — même direction que l’agrege du corpus complet etabli en section précédente (6129,7 s vs 5064,2 s, delta -1065,5 s, soit -17,4 %) : FishAudio est systematiquement plus court. Sur l’extrait segment par segment affiche par la cellule (le bloc narratif d’ouverture), l’ecart croit avec la longueur du segment : -0,7 s sur un segment de 4,2 s, -16,8 s sur un segment de 88,9 s. FishAudio S2-Pro densifie la diction avec ses (emotion tags) ; Kokoro, qui ignore les tags [whisper], garde une prosodie lineaire, plus lente ici sur la narration. Les durees d’un TTS neural varient legerement a chaque generation : les chiffres cites sont les mesures verbatim de la cellule ci-dessous.

Segment Type Kokoro FishAudio Delta Observation pedagogique
0 narration 2.2s 1.2s -1.0s Ecart marginal sur l’intro très courte
4 narration 4.2s 3.5s -0.7s Petit segment, petit ecart
10 narration 41.0s 33.6s -7.4s L’ecart absolu grossit avec la duree
13 narration 78.2s 65.8s -12.4s Long passage narratif, grand ecart
11 narration 88.9s 72.1s -16.8s Plus long segment, plus grand delta

Interpretations de l’ecart

L’ecart n’est pas un bruit de mesure : il s’accumule sur les longues plages narratives qui dominent ce corpus, la ou FishAudio exploite ses tags expressifs pour un rythme plus serre, tandis que Kokoro maintient une diction reguliere et lisible. Le tableau n’affiche qu’un extrait (les premières lignes, toutes narratives) ; les repliques de dialogue, plus courtes, contribuent peu au total.

Cote taille, ratio de ~4.5x

FishAudio genere des WAV non compresses (436 209 KB au total) contre MP3 128 kbps pour Kokoro (95 777 KB). Pour la diffusion web ou mobile, on recompressera les WAV en AAC ou Opus avant publication — sinon le cout de bande passante est prohibitif. Pour une archive de production, garder le WAV preserve la qualite.

Cas d’usage typique

  • Demo locale rapide / itération rapide → Kokoro (latence ~2s, ratio MP3 raisonnable, pas besoin de GPU dedie).
  • Livraison finale audio (livrable audiobook) → FishAudio S2-Pro (qualite expressive, taille WAV acceptable pour archivage).
  • Cas hybride → utiliser Kokoro pour les segments techniques (transitions, listes) et FishAudio pour les passages narratifs critiques (intro, climax, fin).
from IPython.display import Audio, HTML, display
import json

# Load Kokoro metadata (obligatoire) + FishAudio metadata (optionnel, cf 04-13)
kokoro_meta_path = BASE_DIR / "tts_output" / "tts_generation_metadata.json"
fish_meta_path = FISH_OUTPUT_DIR / "fish_generation_metadata.json"

if kokoro_meta_path.exists():
    with open(kokoro_meta_path) as f:
        kokoro_meta = json.load(f)
    kokoro_segs = {s["seg_index"]: s for s in kokoro_meta["segments"]}

    fish_meta = {}
    fish_segs = {}
    if fish_meta_path.exists():
        with open(fish_meta_path) as f:
            fish_meta = json.load(f)
        fish_segs = {s["seg_index"]: s for s in fish_meta["segments"]}

    if fish_segs:
        print("=" * 80)
        print(f"{'Seg':>3} | {'Type':12s} | {'Kokoro':>8s} | {'FishAudio':>8s} | {'Delta':>7s} | "
              f"{'Kokoro KB':>9s} | {'Fish KB':>8s} | {'Speaker':25s}")
        print("-" * 110)

        total_kokoro = 0.0
        total_fish = 0.0
        for i in range(14):
            ks = kokoro_segs.get(i, {})
            fs = fish_segs.get(i, {})
            k_dur = ks.get("duration_s", 0)
            f_dur = fs.get("duration_s", 0)
            k_size = ks.get("file_size_kb", 0)
            f_size = fs.get("file_size_kb", 0)
            delta = f_dur - k_dur
            seg_type = ks.get("seg_type", "?")
            speaker = ks.get("speaker", "?")

            delta_str = f"+{delta:.1f}s" if delta >= 0 else f"{delta:.1f}s"
            k_status = "OK" if ks.get("status") == "success" else "FAIL"
            f_status = "OK" if fs.get("status") == "success" else "FAIL"

            print(f"{i:>3} | {seg_type:12s} | {k_dur:>7.1f}s | {f_dur:>7.1f}s | {delta_str:>7s} | "
                  f"{k_size:>8.0f}KB | {f_size:>6.0f}KB | {speaker:25s}")
            total_kokoro += k_dur
            total_fish += f_dur

        print("-" * 110)
        delta_total = total_fish - total_kokoro
        print(f"{'TOT':>3} | {'':12s} | {total_kokoro:>7.1f}s | {total_fish:>7.1f}s | {delta_total:>+7.1f}s |")
        print(f"\nKokoro total: {total_kokoro:.1f}s ({total_kokoro/60:.1f}min) | FishAudio total: {total_fish:.1f}s ({total_fish/60:.1f}min)")
        print(f"FishAudio est {abs(delta_total):.1f}s {'plus lent' if delta_total > 0 else 'plus rapide'} que Kokoro")
    else:
        print("FishAudio non genere (optionnel, cf 04-13) — comparaison Kokoro seule.")
        print("=" * 80)
        print(f"{'Seg':>3} | {'Type':12s} | {'Kokoro':>8s} | {'Kokoro KB':>9s} | {'Speaker':25s}")
        print("-" * 80)
        total_kokoro = 0.0
        for i in range(14):
            ks = kokoro_segs.get(i, {})
            k_dur = ks.get("duration_s", 0)
            k_size = ks.get("file_size_kb", 0)
            seg_type = ks.get("seg_type", "?")
            speaker = ks.get("speaker", "?")
            print(f"{i:>3} | {seg_type:12s} | {k_dur:>7.1f}s | {k_size:>8.0f}KB | {speaker:25s}")
            total_kokoro += k_dur
        print("-" * 80)
        print(f"{'TOT':>3} | {'':12s} | {total_kokoro:>7.1f}s |")
        print(f"\nKokoro total: {total_kokoro:.1f}s ({total_kokoro/60:.1f}min)")

    # Players interactifs — EXTRAITS embarques (stream copy ffmpeg), pas l'audio complet :
    # sur le corpus integral (342 segments), l'embarquement complet depasserait la taille
    # maximale de fichier du depot. Les fichiers complets restent sur disque (tts_output/,
    # tts_output_fishaudio/). Le tableau ci-dessus liste les 14 premieres lignes ; les
    # players portent un echantillon des premiers segments.
    import subprocess

    def make_excerpt(src, dst, seconds=30):
        """Extrait verbatim (stream copy ffmpeg) des N premieres secondes."""
        res = subprocess.run(
            ["ffmpeg", "-y", "-i", str(src), "-t", str(seconds), "-c:a", "copy", str(dst)],
            capture_output=True, text=True, encoding="utf-8", errors="replace")
        return res.returncode == 0

    N_PLAYERS = 4    # echantillon des premiers segments ecoutables
    EXCERPT_S = 20   # duree de l'extrait embarque par moteur

    print("\n" + "=" * 80)
    print(f"Ecoute comparative — echantillon des {N_PLAYERS} premiers segments "
          f"(extraits de {EXCERPT_S} s embarques, fichiers complets sur disque) :")
    print("=" * 80)

    for i in range(N_PLAYERS):
        ks = kokoro_segs.get(i, {})
        if ks.get("status") != "success":
            continue

        text = ks.get("text", "")[:80] + ("..." if len(ks.get("text", "")) > 80 else "")
        display(HTML(f"<h4>Segment {i} — {ks.get('seg_type','?')} ({ks.get('speaker','?')})</h4>"))
        display(HTML(f"<p><i>{text}</i></p>"))

        # Kokoro player (extrait)
        kokoro_path = BASE_DIR / ks["output_file"]
        if kokoro_path.exists():
            display(HTML(f"<b>Kokoro</b> ({ks['duration_s']:.1f}s, {ks['kokoro_voice']}) — extrait {EXCERPT_S} s"))
            kokoro_excerpt = BASE_DIR / f"excerpt_seg{i:02d}_kokoro{kokoro_path.suffix}"
            if make_excerpt(kokoro_path, kokoro_excerpt, seconds=EXCERPT_S):
                display_audio_file(kokoro_excerpt)
            else:
                print(f"  Extrait Kokoro seg {i} indisponible (ffmpeg)")

        # FishAudio player (optionnel, extrait)
        fs = fish_segs.get(i, {})
        if fs.get("status") == "success":
            fish_path = BASE_DIR / fs["output_file"]
            if fish_path.exists():
                display(HTML(f"<b>FishAudio S2-Pro</b> ({fs['duration_s']:.1f}s, {fs['fish_preset']}) — extrait {EXCERPT_S} s"))
                fish_excerpt = BASE_DIR / f"excerpt_seg{i:02d}_fish{fish_path.suffix}"
                if make_excerpt(fish_path, fish_excerpt, seconds=EXCERPT_S):
                    display_audio_file(fish_excerpt)
                else:
                    print(f"  Extrait FishAudio seg {i} indisponible (ffmpeg)")

        display(HTML("<hr>"))

    # Audiobook comparison — lecteurs pointes sur les artefacts REELS produits par la
    # cellule Compilation : kokoro -> audiobook_kokoro.mp3 (ffmpeg), fish ->
    # tts_output_fishaudio/boule_de_suif_fishaudio_complete.wav. Extrait 30 s embarque
    # (make_excerpt defini ci-dessus) ; le fichier complet reste sur disque.
    print("=" * 80)
    print("Livres audio complets :")
    print("=" * 80)

    kokoro_audiobook = BASE_DIR / "audiobook_kokoro.mp3"
    fish_audiobook = FISH_OUTPUT_DIR / "boule_de_suif_fishaudio_complete.wav"

    for label, full_path in [("Kokoro", kokoro_audiobook),
                             ("FishAudio S2-Pro", fish_audiobook)]:
        if full_path.exists():
            dur = audio_duration_s(full_path.read_bytes())
            print(f"{label}: {full_path.name} | {dur:.1f}s ({dur/60:.1f}min) | "
                  f"{full_path.stat().st_size/1024:.0f}KB")
            excerpt_path = BASE_DIR / f"audiobook_excerpt_{full_path.stem}{full_path.suffix}"
            if make_excerpt(full_path, excerpt_path):
                display(HTML(f"<h4>Livre audio complet — {label} (extrait 30s)</h4>"))
                display(HTML(f"<p>Fichier complet : <code>{full_path.name}</code></p>"))
                display_audio_file(excerpt_path)
            else:
                print(f"  Extrait {label} indisponible (ffmpeg)")
        else:
            print(f"{label}: fichier complet absent ({full_path.name})")
else:
    print("Metadonnees Kokoro manquantes — generation TTS non executee")
    print(f"  Kokoro: {kokoro_meta_path.name} ({'OK' if kokoro_meta_path.exists() else 'MANQUANT'})")
    print(f"  FishAudio: {fish_meta_path.name} ({'OK' if fish_meta_path.exists() else 'MANQUANT'})")
================================================================================
Seg | Type         |   Kokoro | FishAudio |   Delta | Kokoro KB |  Fish KB | Speaker                  
--------------------------------------------------------------------------------------------------------------
  0 | narration    |     2.2s |     1.2s |   -1.0s |       35KB |    100KB | Narrateur                
  1 | narration    |    68.1s |    56.9s |  -11.2s |     1064KB |   4902KB | Narrateur                
  2 | narration    |    13.8s |    12.1s |   -1.7s |      215KB |   1044KB | Narrateur                
  3 | narration    |    36.9s |    36.6s |   -0.3s |      576KB |   3150KB | Narrateur                
  4 | narration    |     4.2s |     3.5s |   -0.7s |       65KB |    300KB | Narrateur                
  5 | narration    |    32.1s |    27.8s |   -4.3s |      502KB |   2394KB | Narrateur                
  6 | narration    |    29.4s |    26.8s |   -2.6s |      459KB |   2306KB | Narrateur                
  7 | narration    |    21.5s |    14.3s |   -7.2s |      336KB |   1236KB | Narrateur                
  8 | narration    |    12.4s |     3.8s |   -8.6s |      194KB |    328KB | Narrateur                
  9 | narration    |     4.8s |     3.5s |   -1.2s |       75KB |    304KB | Narrateur                
 10 | narration    |    41.0s |    33.6s |   -7.4s |      640KB |   2890KB | Narrateur                
 11 | narration    |    88.9s |    72.1s |  -16.8s |     1389KB |   6212KB | Narrateur                
 12 | narration    |    16.5s |    13.3s |   -3.2s |      258KB |   1144KB | Narrateur                
 13 | narration    |    78.2s |    65.8s |  -12.4s |     1222KB |   5668KB | Narrateur                
--------------------------------------------------------------------------------------------------------------
TOT |              |   449.9s |   371.2s |   -78.6s |

Kokoro total: 449.9s (7.5min) | FishAudio total: 371.2s (6.2min)
FishAudio est 78.6s plus rapide que Kokoro

================================================================================
Ecoute comparative — echantillon des 4 premiers segments (extraits de 20 s embarques, fichiers complets sur disque) :
================================================================================

Segment 0 — narration (Narrateur)

BOULE DE SUIF

Kokoro (2.2s, bf_isabella) — extrait 20 s
FishAudio S2-Pro (1.2s, narrator_male) — extrait 20 s

Segment 1 — narration (Narrateur)

Pendant plusieurs jours de suite des lambeaux d'armée en déroute avaient travers...

Kokoro (68.1s, bf_isabella) — extrait 20 s
FishAudio S2-Pro (56.9s, narrator_male) — extrait 20 s

Segment 2 — narration (Narrateur)

Des légions de francs-tireurs aux appellations héroïques: «les Vengeurs de la Dé...

Kokoro (13.8s, bf_isabella) — extrait 20 s
FishAudio S2-Pro (12.1s, narrator_male) — extrait 20 s

Segment 3 — narration (Narrateur)

Leurs chefs, anciens commerçants en draps ou en graines, ex-marchands de suif ou...

Kokoro (36.9s, bf_isabella) — extrait 20 s
FishAudio S2-Pro (36.6s, narrator_male) — extrait 20 s

================================================================================
Livres audio complets :
================================================================================
Kokoro: audiobook_kokoro.mp3 | 6299.4s (105.0min) | 98428KB

Livre audio complet — Kokoro (extrait 30s)

Fichier complet : audiobook_kokoro.mp3

FishAudio S2-Pro: boule_de_suif_fishaudio_complete.wav | 5234.7s (87.2min) | 450880KB

Livre audio complet — FishAudio S2-Pro (extrait 30s)

Fichier complet : boule_de_suif_fishaudio_complete.wav

Lecture du tableau : un ecart de duree systématique, pas une simple vitesse de lecture

Observation cle : l’agrege du corpus complet (section précédente) donne 6129,7 s Kokoro vs 5064,2 s FishAudio (delta global -1065,5 s, soit -17,4 %) ; le tableau de la cellule ci-dessus (14 premières lignes, TOT 449,9 s vs 371,2 s, -17,5 %) montre la même pente sur son extrait. L’extrait segment par segment (premières lignes du tableau, toutes narratives) montre que FishAudio est systematiquement plus court, et que l’ecart absolu croit avec la longueur du segment : -0,7 s sur un segment de 4,2 s, -16,8 s sur un segment de 88,9 s. Ce n’est pas un bruit de mesure : la différence s’accumule sur les longues plages narratives qui dominent ce corpus.

Ce que l’ecart de duree ne dit pas : la vraie redistribution structurelle entre les deux moteurs se lit sur la taille (WAV ~4,5x MP3 a duree comparable), pas sur le temps. FishAudio exploite ses tags expressifs pour densifier la diction (rythme adapte au contenu), tandis que Kokoro, qui ignore les tags P3, garde une prosodie lineaire et lisible — la ou l’original attendait une parite de duree entre les deux moteurs, l’exécution complete sur Boule de Suif montre un FishAudio plus concis.

Implications pratiques : (1) le budget temps audiobook depend du moteur choisi, pas seulement du texte : sur un corpus narratif, prevoir Kokoro ~+20 % de duree par rapport a FishAudio ; (2) pour une restitution pedagogique (clarte > naturel), Kokoro reste preferable malgre l’absence de tags ; (3) le ratio de taille ~4,5x (WAV non compresse vs MP3 128 kbps) reste un facteur de bande passante pour la diffusion.

Lien avec P5 : la compilation des livres audio (cellule de la section précédente) preserve la duree reelle de chaque moteur — P5 peut choisir l’un ou l’autre pour l’assemblage final selon la cible (web mobile = Kokoro MP3, archive studio = FishAudio WAV).

Exercice : Générateur de rapport de comparaison TTS

Duree estimee : 15-20 minutes

Objectif : Créer une fonction qui genere un rapport comparatif automatique entre Kokoro et FishAudio pour un ensemble de segments. Le rapport inclut : différence de duree moyenne, différence de taille, voix les plus/moins rapides, et recommandation du meilleur modèle par cas d’usage.

Contexte : Pour choisir entre Kokoro et FishAudio en production, il faut un rapport synthetique qui va au-dela du simple tableau de chiffres et fournit des recommandations actionnables.

  • Étape 1 : Calculer les metriques globales (duree moyenne, taille moyenne, ratio taille/duree)
  • Étape 2 : Identifier les segments avec le plus grand ecart de qualite (delta de duree > 2s)
  • Étape 3 : Generer un rapport texte formate avec recommandations

Indice : Parcourez les metadonnees kokoro_meta et fish_meta (déjà chargees) Indice : Comparez segment par segment via le champ seg_index Indice : Formatez avec des f-strings et des alignements pour un rendu propre

# TODO etudiant : generateur de rapport comparatif TTS
# Etape 1 : Metriques globales
def compute_tts_metrics(segments_list):
    """Calcule duree moyenne, taille moyenne et ratio taille/duree."""
    # TODO etudiant
    return {}  # TODO etudiant

# Etape 2 : Segments avec ecarts significatifs
def find_outlier_segments(kokoro_segs, fish_segs, threshold_s=2.0):
    """Identifie les segments ou le delta de duree depasse le seuil."""
    # TODO etudiant
    return []  # TODO etudiant

# Etape 3 : Rapport formate
def generate_comparison_report(kokoro_segs, fish_segs):
    """Genere un rapport comparatif Kokoro vs FishAudio."""
    # TODO etudiant
    return ""  # TODO etudiant

print("Exercice a completer")
Exercice a completer

Repère de production — Epic #1028, Pass 4 du pipeline audiobook.

Retour au sommet