# Moteur retenu (v2) : attribution, détection avec sources, sélection, insertion, texte S2
MOTEUR_RETENU = "v2"
MAX_TAGS = 3
RANG_SOURCE = {"incise": 0, "lexique": 1, "ponctuation": 2, "role": 3, "defaut": 4}
PRIORITE_CATEGORIES = {
"dialogue": ["intensity", "emotions", "tone", "breath", "rhythm"],
"narration": ["rhythm", "tone"], # le narrateur ne porte pas les émotions des personnages
}
CONFLITS = [{"whisper", "shout"}, {"warm", "cold"}, {"tender", "cold"}]
TON_PAR_ROLE = {"antagoniste": "cold", "protagoniste": "warm"} # règle d'origine, priorité la plus basse
ORDRE_TAGS_MOTEUR = [tag for categorie in FISHAUDIO_TAGS.values() for tag in categorie]
CATEGORIE = {tag: cat for cat, tags in FISHAUDIO_TAGS.items() for tag in tags}
# « enfin » est retiré de `hesitate` : ses 14 occurrences dans le conte sont temporelles ou
# discursives (« attelée enfin », « Enfin, vers minuit »), aucune n'est une hésitation.
MOTS_CLES_RETIRES = {"hesitate": {"enfin"}}
MOTIFS_MOTEUR = {
tag: [p for p in (_compiler_mot_cle(k) for k in mots + MOTS_CLES_AJOUTES.get(tag, [])
if k not in MOTS_CLES_RETIRES.get(tag, set())) if p]
for categorie in FISHAUDIO_TAGS.values() for tag, mots in categorie.items()}
def lexique(texte):
forme = normaliser_fr(texte)
return [tag for tag in ORDRE_TAGS_MOTEUR if any(p.search(forme) for p in MOTIFS_MOTEUR.get(tag, []))]
# --- 1. Attribution des voix -------------------------------------------------------------
ALIAS_PERSONNAGES = {
"boule_de_suif": ["boule de suif", "elisabeth rousset", "elisabeth"],
"loiseau": ["loiseau", "monsieur loiseau", "m. loiseau"],
"mme_loiseau": ["mme loiseau", "madame loiseau"],
"comte": ["le comte", "comte hubert"],
"comtesse": ["la comtesse", "comtesse"],
"cornudet": ["cornudet"],
"carre_lamadon": ["carre-lamadon", "m. carre-lamadon"],
"soeurs": ["la religieuse", "les religieuses", "bonne soeur", "bonnes soeurs", "la vieille religieuse"],
"officier": ["l'officier", "officier"],
# personnages réels du conte, absents du casting P2 : reconnus pour ne pas être confondus
"mme_carre_lamadon": ["mme carre-lamadon", "madame carre-lamadon"],
"follenvie": ["follenvie", "mme follenvie", "madame follenvie"],
}
assert set(ALIAS_PERSONNAGES) - {"mme_carre_lamadon", "follenvie"} <= IDS_P2, "alias vers un identifiant absent de P2"
DESTINATAIRE = re.compile(r"(?:^|\W)(?:a|au|aux|vers|envers|contre)\s+(?:l'|la |le |les )?$")
GENRE = {c["id"]: c["gender"] for c in characters}
GENRE.update({"mme_carre_lamadon": "F", "follenvie": "M"})
PRONOM_SUJET = re.compile(r"(?<!\w)(il|elle)(?!\w)")
def locuteur_de_l_intro(intro):
"""Personnage nommé comme locuteur dans la phrase d'introduction (dernière mention qui
n'est pas un destinataire), ou None. Les alias les plus longs sont cherchés d'abord."""
forme = normaliser_fr(intro)
alias = sorted(((cid, a) for cid, liste in ALIAS_PERSONNAGES.items() for a in liste), key=lambda x: -len(x[1]))
mentions = []
for cid, a in alias:
for m in re.finditer(r"(?<!\w)" + re.escape(a) + r"(?!\w)", forme):
if any(m.start() < fin and debut < m.end() for debut, fin, _ in mentions):
continue
if DESTINATAIRE.search(forme[:m.start()]):
continue
mentions.append((m.start(), m.end(), cid))
if not mentions:
return None
debut, fin, cid = max(mentions)
# « comme le comte insistait, elle répondit » : un pronom sujet qui suit la mention et ne
# s'accorde pas avec elle désigne quelqu'un d'autre -> locuteur non résolu.
pronoms = PRONOM_SUJET.findall(forme[fin:])
if pronoms and {"il": "M", "elle": "F"}[pronoms[-1]] != GENRE.get(cid):
return None
return cid
def nom_affiche(char_id, defaut):
if char_id == NARRATEUR_ID:
return "Narrateur"
return voice_config["characters"].get(char_id, {}).get("name", defaut)
def resoudre_attribution(u):
profil = get_speaker_profile(u["speaker"], characters, voice_config)
intro = incise_precedente(int(u["seg_index"]))
cite = locuteur_de_l_intro(intro) if intro else None
char_id, attribution = profil["char_id"], None
if cite and cite != profil["char_id"]:
if cite in IDS_P2:
char_id, attribution = cite, "corrigée par l'incise"
else:
char_id, attribution = None, f"non résolue (locuteur non casté : {cite})"
elif cite:
attribution = "confirmée par l'incise"
elif profil["resolution"] == "narrateur":
attribution = "non résolue (P1 : Narrateur)"
elif profil["resolution"] == "inconnu":
attribution = "non résolue (nom absent de P1)"
else:
attribution = "P1, non vérifiée"
if attribution.startswith("non résolue"):
char_id = None # pas d'identifiant inventé : la voix du narrateur est un repli signalé
voix = get_speaker_profile(nom_affiche(char_id, u["speaker"]), characters, voice_config) if char_id else None
if char_id in IDS_P2:
fish_preset, role = voice_config["characters"][char_id]["voices"]["fishaudio_production"]["preset"], voix["role"]
else: # non résolue : voix du narrateur, explicitement signalée
fish_preset, role = PRESET_NARRATEUR, "narrateur"
return dict(char_id=char_id, attribution=attribution, fish_preset=fish_preset, role=role,
speaker=nom_affiche(char_id, u["speaker"]) if char_id else "Narrateur (locuteur non résolu)",
intro=intro, cite=cite)
# --- 2. Détection avec sources, sélection, insertion ---------------------------------------
def _noter(sources, tag, source):
if tag not in sources or RANG_SOURCE[source] < RANG_SOURCE[sources[tag]]:
sources[tag] = source
def _apres_suspension(texte):
"""Position juste après les premiers points de suspension (début du mot suivant)."""
fin = RE_SUSPENSION.search(texte).end()
while fin < len(texte) and texte[fin] in " \n":
fin += 1
return fin
def detecter_replique(texte, intro):
sources = {}
for tag in lexique(intro):
_noter(sources, tag, "incise")
for tag in lexique(texte):
_noter(sources, tag, "lexique")
if detect_caps_shouting(texte) or texte.count("!") >= 2:
_noter(sources, "shout", "ponctuation")
if detect_hesitation(texte):
_noter(sources, "hesitate", "ponctuation")
positions = {}
if compter_suspensions(texte)[0]:
_noter(sources, "pause", "ponctuation")
positions["pause"] = [_apres_suspension(texte)]
return sources, positions
def detecter_narration(seg):
texte = seg["text"]
forme = normaliser_fr(texte)
sources, positions = {}, {}
for tag in lexique(texte):
_noter(sources, tag, "lexique")
for motifs, tags_regle in REGLES_ORIGINE:
if any(p.search(forme) for p in motifs):
for tag in tags_regle:
_noter(sources, tag, "lexique")
for tag, motifs in RYTHME.items():
for motif in motifs:
for m in motif.finditer(forme):
_noter(sources, tag, "lexique")
positions.setdefault(tag, []).append(_debut_de_phrase(forme, m.start()))
if compter_suspensions(texte)[0]:
_noter(sources, "pause", "ponctuation")
if sources["pause"] == "ponctuation":
positions["pause"] = [_apres_suspension(texte)]
return sources, positions
def selectionner(sources, type_seg, role=None):
"""Retourne (retenus, ecartes) : tri par source, puis catégorie, puis ordre de la taxonomie."""
categories = PRIORITE_CATEGORIES[type_seg]
ecartes = {t: "catégorie non portée par le narrateur" for t in sources if CATEGORIE.get(t) not in categories}
if type_seg == "dialogue":
# « Elle pleure sa honte » : un son non verbal NOMMÉ dans les paroles décrit, il ne
# s'exécute pas. Rires, sanglots, soupirs ne viennent que de la phrase d'introduction.
for t in sources:
if sources[t] == "lexique" and CATEGORIE.get(t) in ("emotions", "breath"):
ecartes[t] = "son non verbal cité dans les paroles"
candidats = sorted((t for t in sources if CATEGORIE.get(t) in categories and t not in ecartes),
key=lambda t: (RANG_SOURCE[sources[t]], categories.index(CATEGORIE[t]), ORDRE_TAGS_MOTEUR.index(t)))
retenus = []
for t in candidats:
conflit = next((r for r in retenus if any({t, r} <= c for c in CONFLITS)), None)
if conflit:
ecartes[t] = f"conflit avec {conflit}"
elif len(retenus) >= MAX_TAGS:
ecartes[t] = f"plafond de {MAX_TAGS} tags"
else:
retenus.append(t)
ton_par_defaut = TON_PAR_ROLE.get(role)
if (type_seg == "dialogue" and ton_par_defaut and len(retenus) < MAX_TAGS
and not any(CATEGORIE.get(t) == "tone" for t in retenus)
and not any({ton_par_defaut, r} <= c for c in CONFLITS for r in retenus)):
sources[ton_par_defaut] = "role"
retenus.append(ton_par_defaut)
return retenus, ecartes
def inserer_tags(texte, retenus, positions):
"""Insère CHAQUE tag retenu une fois : en tête, ou au début de la phrase du changement
de rythme (première occurrence). Retourne (texte_annote, [(position, tag), ...])."""
en_tete, au_fil = [], []
for tag in retenus:
pos = min(positions.get(tag, [0]))
(au_fil if pos > 0 else en_tete).append((pos, tag))
annote = texte
for pos, tag in sorted(au_fil, reverse=True):
annote = (annote[:pos] + f"[{tag}] " + annote[pos:]) if pos < len(annote) else (annote.rstrip() + f" [{tag}]")
annote = "".join(f"[{tag}] " for _, tag in en_tete) + annote
return annote, [(0, tag) for _, tag in en_tete] + sorted(au_fil)
TAG_INSERE = re.compile(r"\[([a-z_]+)\]")
def tags_dans_le_texte(texte_annote):
"""Relit les tags réellement présents dans un texte annoté (source de vérité des statistiques)."""
return TAG_INSERE.findall(texte_annote)
# --- 3. Texte pour FishAudio S2-Pro ---------------------------------------------------------
# Tags officiels S2-Pro (v4/schemas.py, d'après https://fish.audio/fr/blog/how-to-use-inline-tags-in-fish-audio-s2/)
TAGS_S2_OFFICIELS = {
"clears throat", "inhale", "inhalation", "exhale", "sigh", "panting", "breathing", "gasp",
"groan", "moaning", "sobbing", "crying", "laughing", "chuckling", "giggle",
"pause", "short pause", "long pause",
"whispering", "whispering voice", "soft voice", "low voice", "loud voice", "shouting",
"excited", "angry", "sad", "emphasis", "rustling sound"}
# Correspondances : celles de v4/p4_annotation.py (TAG_TO_FISHAUDIO) quand elles existent,
# complétées pour les tags de cette taxonomie ; None = aucun équivalent officiel, non transmis.
VERS_S2 = {
"whisper": "whispering", "shout": "shouting", "laugh": "laughing", "sob": "sobbing",
"sigh": "sigh", "gasp": "gasp", "pause": "pause", "slow": "pause", # v4
"cold": "low voice", "warm": "soft voice", "onctuous": "soft voice", # v4
"indignant": "angry", "timid": "whispering", # v4
"groan": "groan", "inhale": "inhale", "exhale": "exhale", "mutter": "low voice",
"tender": "soft voice", "sarcastic": "emphasis", "hesitate": "short pause",
"quick": None, "choke": None, # pas de tag officiel de débit ni d'étranglement
}
assert {v for v in VERS_S2.values() if v} <= TAGS_S2_OFFICIELS
def texte_fishaudio(texte_annote):
"""Remplace chaque tag interne par son tag S2 officiel (ou le retire), fusionne les doublons."""
non_transmis = []
def remplacer(m):
cible = VERS_S2.get(m.group(1))
if cible is None:
non_transmis.append(m.group(1))
return ""
return f"[{cible}]"
texte = TAG_INSERE.sub(remplacer, texte_annote)
texte = re.sub(r"(\[[^\]]+\])(\s*\1)+", r"\1", texte) # tag S2 répété à la suite
texte = re.sub(r"[ \t]+", " ", texte).strip()
assert set(re.findall(r"\[([^\]]+)\]", texte)) <= TAGS_S2_OFFICIELS
return texte, non_transmis
# --- 4. Annotation et régénération -------------------------------------------------------
@dataclass
class AnnotationRetenue:
seg_index: int
seg_type: str
utterance_type: str
speaker: str
speaker_p1: str
character_id: Optional[str]
attribution: str
fish_preset: str
original_text: str
annotated_text: str
fishaudio_text: str
tags_detectes: dict
tags_retenus: list
tags_ecartes: dict
tags_inseres: list
tags_applied: list
tags_non_transmis: list
tag_par_defaut: bool
emotion_profile: str
def _finaliser(seg_index, seg_type, utt_type, speaker, speaker_p1, char_id, attribution, preset, texte,
sources, retenus, ecartes, positions, par_defaut):
assert "[" not in texte, "le texte source contient déjà un crochet"
annote, inseres = inserer_tags(texte, retenus, positions)
relus = tags_dans_le_texte(annote)
assert sorted(relus) == sorted(retenus), (seg_index, relus, retenus) # retenus = insérés, 1 pour 1
fish, non_transmis = texte_fishaudio(annote)
return AnnotationRetenue(
seg_index=seg_index, seg_type=seg_type, utterance_type=utt_type, speaker=speaker,
speaker_p1=speaker_p1, character_id=char_id, attribution=attribution, fish_preset=preset,
original_text=texte, annotated_text=annote, fishaudio_text=fish,
tags_detectes=dict(sorted(sources.items(), key=lambda kv: ORDRE_TAGS_MOTEUR.index(kv[0]))),
tags_retenus=retenus, tags_ecartes=ecartes, tags_inseres=[[p, t] for p, t in inseres],
tags_applied=relus, tags_non_transmis=non_transmis, tag_par_defaut=par_defaut,
emotion_profile="+".join(relus) or "neutral")
def annoter_replique(u):
att = resoudre_attribution(u)
sources, positions = detecter_replique(u["text"], att["intro"])
retenus, ecartes = selectionner(sources, "dialogue", att["role"])
return _finaliser(int(u["seg_index"]), "dialogue", u.get("utterance_type", "dialogue"), att["speaker"],
u["speaker"], att["char_id"], att["attribution"], att["fish_preset"], u["text"],
sources, retenus, ecartes, positions, False)
def annoter_narration(seg):
sources, positions = detecter_narration(seg)
retenus, ecartes = selectionner(sources, "narration")
par_defaut = not retenus
if par_defaut:
defaut = "slow" if seg["seg_type"] == "description" else "pause"
sources[defaut] = "defaut"
retenus = [defaut]
return _finaliser(int(seg["index"]), seg["seg_type"], seg["seg_type"], "Narrateur", "Narrateur",
NARRATEUR_ID, "narration", PRESET_NARRATEUR, seg["text"],
sources, retenus, ecartes, positions, par_defaut)
# Les annotations v1 restent disponibles pour comparaison ; les variables exportées par les
# sections 7 à 9 (annotations, segment_annotations) contiennent désormais le moteur retenu.
annotations_v1, segment_annotations_v1 = annotations, segment_annotations
annotations = [annoter_replique(u) for u in utterances]
segment_annotations = [asdict(annoter_narration(s)) for s in segments
if int(s["index"]) not in dialogue_seg_indices]
toutes_retenues = list(annotations) + [AnnotationRetenue(**s) for s in segment_annotations]
# --- Rapport ---------------------------------------------------------------------------------
print(f"Moteur retenu : {MOTEUR_RETENU} | {len(annotations)} répliques, {len(segment_annotations)} segments narratifs")
print("Vérification : pour chacune des", len(toutes_retenues), "annotations, tags retenus = tags insérés (relus dans le texte)")
print("\nAttribution des répliques :")
for statut, n in Counter(a.attribution for a in annotations).most_common():
print(f" {statut:45} {n:2d}")
print("\nCorrections et confirmations par la phrase d'introduction :")
for a in annotations:
if "incise" in a.attribution:
print(f" seg {a.seg_index:3d} : {a.speaker_p1:24} -> {a.speaker:24} ({a.attribution})")
if a.attribution.startswith("corrigée"): # pièces à relire pour valider la correction
print(f" introduction : « {incise_precedente(a.seg_index)[-110:]} »")
print(f" réplique : « {' '.join(a.original_text.split())[:80]} »")
def balises_s2(texte):
return re.findall(r"\[([^\]]+)\]", texte)
etapes = Counter()
for a in toutes_retenues:
etapes["détectés"] += len(a.tags_detectes)
etapes["retenus"] += len(a.tags_retenus)
etapes["insérés (tags internes)"] += len(a.tags_applied)
etapes["supprimés à la conversion S2"] += len(a.tags_non_transmis)
etapes["conservés avant fusion"] += len(a.tags_applied) - len(a.tags_non_transmis)
etapes["balises préparées pour FishAudio (après fusion)"] += len(balises_s2(a.fishaudio_text))
etapes["fusionnés (même balise S2 adjacente)"] = etapes["conservés avant fusion"] - etapes["balises préparées pour FishAudio (après fusion)"]
print("\nTags par étape :")
for etape in ["détectés", "retenus", "insérés (tags internes)", "supprimés à la conversion S2", "conservés avant fusion",
"fusionnés (même balise S2 adjacente)", "balises préparées pour FishAudio (après fusion)"]:
print(f" {etape:48} {etapes[etape]:4d}")
fusions = Counter(tuple(t for t in a.tags_applied if t not in a.tags_non_transmis) for a in toutes_retenues
if len(a.tags_applied) - len(a.tags_non_transmis) > len(balises_s2(a.fishaudio_text)))
print(" origine des fusions :", {"+".join(k): v for k, v in fusions.items()})
print(" (aucune synthèse n'est exécutée ici : ces balises sont PRÉPARÉES, pas transmises)")
print("Raisons d'écart :", dict(Counter(r.split(" avec ")[0] for a in toutes_retenues for r in a.tags_ecartes.values())))
print("Tags supprimés à la conversion S2 (sans équivalent officiel) :",
dict(Counter(t for a in toutes_retenues for t in a.tags_non_transmis)))
print(f"\nRépliques taguées : v1 {sum(bool(a.tags_applied) for a in annotations_v1)}/{len(annotations_v1)}"
f" -> moteur retenu {sum(bool(a.tags_applied) for a in annotations)}/{len(annotations)}")
print("\nExemples (réplique : détectés -> retenus -> texte annoté -> texte FishAudio) :")
for a in annotations:
if a.tags_applied and ("incise" in a.attribution or a.tags_ecartes):
print(f" seg {a.seg_index} [{a.speaker}] {a.tags_detectes} -> {a.tags_retenus}"
+ (f" | écartés {a.tags_ecartes}" if a.tags_ecartes else ""))
print(f" {a.annotated_text[:90]}\n {a.fishaudio_text[:90]}")