Spaces:
Running on Zero
Running on Zero
File size: 4,679 Bytes
9633dbc | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 | """Vérifie que chaque phrase de EXEMPLES traverse le pipeline complet.
phrase en wolof -> extract_intent() (LLM) -> StopsMatcher.find_line() (CSV)
La liste est importée depuis app.py : toute modification de EXEMPLES est donc
contrôlée par ce script. À lancer après chaque changement de EXEMPLES, et avant
une démo, pour ne pas découvrir devant le jury qu'une phrase ne matche aucune ligne.
Usage:
python -X utf8 -u src/app/check_examples.py
Code de sortie : 0 si toutes les phrases donnent found=True, 1 sinon.
"""
from __future__ import annotations
import sys
import time
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from app.app import EXEMPLES
from intent.extract_intent import extract_intent, get_client
from matching.stops_matcher import StopsMatcher
SEPARATEUR = "=" * 68
# L'API NVIDIA limite le débit : enchaîner les phrases sans pause déclenche des
# 429 qui font échouer la vérification pour une raison étrangère aux phrases.
PAUSE_ENTRE_PHRASES = 4
def verifier_phrase(phrase: str, matcher: StopsMatcher, client) -> dict:
"""Enchaîne extraction puis correspondance sur une phrase."""
rapport: dict = {"phrase": phrase, "ok": False, "etape": None, "detail": None}
intent = extract_intent(phrase, client=client)
rapport["intent"] = intent
if intent.get("erreur"):
rapport["etape"] = "extraction"
rapport["detail"] = intent["erreur"]
return rapport
depart, arrivee = intent["depart"], intent["arrivee"]
rapport["depart"], rapport["arrivee"] = depart, arrivee
if not depart or not arrivee:
rapport["etape"] = "extraction"
rapport["detail"] = f"champ vide (depart={depart!r}, arrivee={arrivee!r})"
return rapport
resultat = matcher.find_line(depart, arrivee)
rapport["resultat"] = resultat
rapport["etape"] = "correspondance"
if not resultat["found"]:
rapport["detail"] = _raison_echec(resultat)
return rapport
rapport["ok"] = True
rapport["detail"] = ", ".join(
f"{match['compagnie']} {match['ligne']} ({match['sens']})"
for match in resultat["lignes"]
)
return rapport
def _raison_echec(resultat: dict) -> str:
if not resultat["depart_valide"] or not resultat["arrivee_valide"]:
details = []
if not resultat["depart_valide"]:
details.append(
f"départ hors réseau (proche : {resultat['depart_matched']} "
f"{resultat['depart_score']})"
)
if not resultat["arrivee_valide"]:
details.append(
f"arrivée hors réseau (proche : {resultat['arrivee_matched']} "
f"{resultat['arrivee_score']})"
)
return " ; ".join(details)
return (
f"aucune ligne ne relie {resultat['depart_matched']} à "
f"{resultat['arrivee_matched']} dans le CSV"
)
def main() -> int:
print(SEPARATEUR)
print("Vérification EXEMPLES — pipeline complet (extraction LLM + matcher)")
print(SEPARATEUR)
matcher = StopsMatcher()
client = get_client()
rapports = []
for index, phrase in enumerate(EXEMPLES):
if index:
time.sleep(PAUSE_ENTRE_PHRASES)
print(f"\n[{index + 1}/{len(EXEMPLES)}] analyse en cours…")
rapports.append(verifier_phrase(phrase, matcher, client))
echecs = 0
for index, rapport in enumerate(rapports, start=1):
marque = "OK " if rapport["ok"] else "ECHEC"
print(f"\n[{index}/{len(rapports)}] {marque} {rapport['phrase']}")
if rapport["etape"] == "extraction" and "intent" in rapport:
print(f" extraction : depart={rapport['intent']['depart']!r} "
f"arrivee={rapport['intent']['arrivee']!r}")
elif "depart" in rapport:
print(f" extraction : depart={rapport['depart']!r} "
f"arrivee={rapport['arrivee']!r}")
print(f" {rapport['etape']:<13}: {rapport['detail']}")
if not rapport["ok"]:
echecs += 1
print("\n" + SEPARATEUR)
if echecs:
print(f"{echecs}/{len(rapports)} phrase(s) en échec :")
for rapport in rapports:
if not rapport["ok"]:
print(f" - {rapport['phrase']} ({rapport['etape']} : {rapport['detail']})")
print("Corriger EXEMPLES dans src/app/app.py avec un trajet présent dans le CSV.")
else:
print(f"{len(rapports)}/{len(rapports)} phrase(s) valides : le pipeline de démo tient.")
print(SEPARATEUR)
return 1 if echecs else 0
if __name__ == "__main__":
sys.exit(main())
|