File size: 2,949 Bytes
28f510f
 
 
 
 
 
 
 
 
 
 
 
f89d38d
28f510f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f89d38d
 
 
 
28f510f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Moteur d'inférence NLU en temps réel pour Voice-MoMo (Option A).
Combine la classification d'intention probabiliste et l'extraction de slots culturelle.
Latence : < 5ms. Zéro hallucination financière.
"""

import json
import joblib
from pathlib import Path
from typing import Dict, Any, Optional

from slot_extractor import extract_slots
from fon_amount_parser import mentions_electricity

HERE = Path(__file__).resolve().parent
MODEL_PATH = HERE / "intent_classifier.joblib"
METADATA_PATH = HERE / "nlu_metadata.json"

class VoiceMoMoNLU:
    def __init__(self, model_path: Optional[Path] = None):
        self.model_path = model_path or MODEL_PATH
        self.model = None
        self.classes = []
        self._load_model()

    def _load_model(self):
        if not self.model_path.exists():
            raise FileNotFoundError(f"Modèle NLU introuvable à : {self.model_path}. Lancez l'entraînement d'abord.")
        self.model = joblib.load(self.model_path)
        self.classes = list(self.model.classes_)

    def parse(self, text: str) -> Dict[str, Any]:
        """
        Analyse une phrase utilisateur en Fongbé, Français ou Code-Switching.
        Retourne l'intention, l'indice de confiance et les slots extraits.
        """
        if not text or not text.strip():
            return {
                "text": text,
                "intent": "inconnu",
                "confidence": 0.0,
                "slots": {}
            }

        text = text.strip()

        # 1. Prédiction de l'intention avec probabilités calibrées
        probas = self.model.predict_proba([text])[0]
        best_idx = probas.argmax()
        intent = self.classes[best_idx]
        confidence = float(probas[best_idx])

        # Règle métier : « crédit » = électricité seulement si SBEE / compteur / courant est dit, sinon crédit de communication
        if intent in ("achat_credit", "paiement_sbee"):
            intent = "paiement_sbee" if mentions_electricity(text) else "achat_credit"

        # 2. Extraction des entités (slots)
        slots = extract_slots(text, intent=intent)

        return {
            "text": text,
            "intent": intent,
            "confidence": round(confidence, 4),
            "slots": slots
        }

if __name__ == "__main__":
    nlu = VoiceMoMoNLU()
    examples = [
        "Xɔ crédit sbee caki wè dó 14253647589 jí",
        "Sɛ́ caki atɔn dó nɔ ce",
        "Envoie cinq mille francs à Papa",
        "Sú akwɛ sìn tɔn caki atɔn dó police 78965412 jí",
        "Xɔ credit kpowun ko nukun ɛnɛ nú mì",
        "Akwɛ nabí wɛ kpò ɖò comtù ce mɛ?",
        "Ɛɛn, é sɔgbe, sɛ́dó",
        "Eo, e sɔ́ gbɛ́ a, gbéjé"
    ]
    for ex in examples:
        res = nlu.parse(ex)
        print(f"\nPhrase : {ex}")
        print(f"Intent : {res['intent']} (confiance: {res['confidence'] * 100:.1f}%)")
        print(f"Slots  : {res['slots']}")