fon-nlu 1.0.0 : intentions + extraction de montants (fon, français, mélange)
Browse files- README.md +144 -0
- contact_resolver.py +192 -0
- fon_amount_parser.py +167 -0
- intent_classifier.joblib +3 -0
- nlu_engine.py +78 -0
- nlu_metadata.json +79 -0
- requirements.txt +3 -0
- slot_extractor.py +140 -0
README.md
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
language:
|
| 3 |
+
- fon
|
| 4 |
+
- fr
|
| 5 |
+
license: cc-by-nc-4.0
|
| 6 |
+
library_name: scikit-learn
|
| 7 |
+
pipeline_tag: text-classification
|
| 8 |
+
tags:
|
| 9 |
+
- fon
|
| 10 |
+
- fongbe
|
| 11 |
+
- benin
|
| 12 |
+
- low-resource
|
| 13 |
+
- nlu
|
| 14 |
+
- intent-classification
|
| 15 |
+
- slot-filling
|
| 16 |
+
- mobile-money
|
| 17 |
+
- voice-assistant
|
| 18 |
+
- code-switching
|
| 19 |
+
- finanfa-tech
|
| 20 |
+
---
|
| 21 |
+
|
| 22 |
+
# fon-nlu — compréhension de commandes Mobile Money en fon, français et mélange fon-français
|
| 23 |
+
|
| 24 |
+
**Petit modèle de compréhension (NLU) pour un assistant vocal de paiement mobile** : à partir d'une phrase (la transcription de ce que dit l'utilisateur) en **fon, en français ou en mélange des deux**, il trouve **ce que veut faire l'utilisateur** (l'intention) et en extrait **les informations utiles** (montant, destinataire, numéro de compteur ou de police).
|
| 25 |
+
|
| 26 |
+
**Auteur : AWADEME Ronaldo — [Finanfa Tech](https://huggingface.co/finanfa-tech)**
|
| 27 |
+
|
| 28 |
+
> 🇬🇧 *English summary:* A lightweight intent classifier + rule-based slot extractor for Mobile Money voice commands in Fon (Fongbe), French and Fon–French code-switching (Benin). 8 intents (money transfer, SBEE electricity and SONEB water bill payment, balance check, airtime purchase, meter/policy number, yes, no). Fon amount expressions (e.g. "caki wè" = 2,000 FCFA, "kpowun ko atɔ́ɔ́n" = 625 FCFA) were validated by a native speaker. **Honest accuracy on unseen phrase forms is 87 % (macro-F1 79 %), not the 100 % a standard cross-validation shows.** Research-grade; never execute a payment without reading back the amount and recipient and asking for confirmation. Non-commercial license (CC-BY-NC-4.0).
|
| 29 |
+
|
| 30 |
+
## ⚠️ À lire avant d'utiliser
|
| 31 |
+
|
| 32 |
+
- **Ne déclenchez jamais un paiement sans relire à voix haute le montant et le destinataire, et sans confirmation explicite de l'utilisateur.** Le modèle se trompe, et une erreur sur un montant est une erreur financière.
|
| 33 |
+
- **Précision réelle : 87 %** sur des formes de phrase que le modèle n'a pas vues (macro-F1 79 %). La validation croisée classique donne 100 %, mais ce chiffre est **trompeur** : les 991 exemples ne sont que **113 formes de phrase différentes** (avec des montants, noms et numéros variés), donc les mêmes formes se retrouvent en entraînement et en test.
|
| 34 |
+
- **Il n'existe pas de classe « inconnu »** : toute phrase reçoit l'une des 8 intentions, même hors sujet. Utilisez le score de confiance et **rejetez en dessous de 0,6** (exemple : « Il fait beau aujourd'hui » reçoit 0,31).
|
| 35 |
+
- **Le paiement SONEB (eau) est mal reconnu** : seulement 35 % des phrases SONEB sont retrouvées sur des formes inédites ; elles sont souvent prises pour une facture SBEE (électricité) ou une demande de numéro de compteur. Vérifiez toujours le type de facture avec l'utilisateur.
|
| 36 |
+
- **Texte uniquement** : le modèle reçoit du texte. Il n'a pas été testé sur des transcriptions automatiques de parole, qui contiennent des erreurs.
|
| 37 |
+
- **Les contacts fournis dans `contact_resolver.py` sont fictifs** (numéros factices). En production, passez toujours la vraie liste de contacts de l'utilisateur.
|
| 38 |
+
- **Usage non commercial uniquement** (CC-BY-NC-4.0). Fichier `.joblib` : ne le chargez que depuis une source de confiance (format pickle).
|
| 39 |
+
|
| 40 |
+
## Ce que fait le modèle
|
| 41 |
+
|
| 42 |
+
**8 intentions** : `transfert_argent`, `paiement_sbee` (électricité), `paiement_soneb` (eau), `consulter_solde`, `achat_credit` (crédit de communication), `fournir_compteur` (donner un compteur ou une police en réponse), `confirmation_oui`, `annulation_non`.
|
| 43 |
+
|
| 44 |
+
**Informations extraites** (par des règles, pas par le modèle) : `montant` (en FCFA), `destinataire_nom` (avec résolution des liens de parenté : « nɔ ce » = Maman, « tɔ́ ce » = Papa…), `destinataire_numero`, `numero_compteur` (11 chiffres), `numero_police` (8 chiffres), `compteur_nom` (« compteur maison »…).
|
| 45 |
+
|
| 46 |
+
### Les montants en fon (validés par le locuteur)
|
| 47 |
+
Les expressions suivantes ont été relues et validées par AWADEME Ronaldo, locuteur natif du fon. Une même valeur peut s'écrire de plusieurs façons (fon, français, chiffres).
|
| 48 |
+
|
| 49 |
+
| Expression | Valeur | Exemples dans les données |
|
| 50 |
+
|---|---|---|
|
| 51 |
+
| kpowun ko | 500 FCFA | 30 |
|
| 52 |
+
| kpowun ko nukun ɛnɛ | 600 FCFA | 62 |
|
| 53 |
+
| kpowun ko atɔ́ɔ́n | 625 FCFA | 13 |
|
| 54 |
+
| caki ɖokpó | 1 000 FCFA | 25 |
|
| 55 |
+
| mille francs | 1 000 FCFA | 20 |
|
| 56 |
+
| caki wè | 2 000 FCFA | 27 |
|
| 57 |
+
| deux mille | 2 000 FCFA | 4 |
|
| 58 |
+
| deux mille francs | 2 000 FCFA | 2 |
|
| 59 |
+
| caki atɔn | 3 000 FCFA | 23 |
|
| 60 |
+
| trois mille francs | 3 000 FCFA | 31 |
|
| 61 |
+
| caki ɛnɛ | 4 000 FCFA | 13 |
|
| 62 |
+
| caki atɔ́ɔ́n | 5 000 FCFA | 25 |
|
| 63 |
+
| cinq mille francs | 5 000 FCFA | 11 |
|
| 64 |
+
| franc caki atɔ́ɔ́n | 5 000 FCFA | 25 |
|
| 65 |
+
| caki ayizɛ́n | 6 000 FCFA | 26 |
|
| 66 |
+
| caki tantɔn | 8 000 FCFA | 12 |
|
| 67 |
+
| caki wǒ | 10 000 FCFA | 19 |
|
| 68 |
+
| dix mille | 10 000 FCFA | 15 |
|
| 69 |
+
| caki afɔtɔ́n | 15 000 FCFA | 23 |
|
| 70 |
+
| quinze mille francs | 15 000 FCFA | 20 |
|
| 71 |
+
| caki ko | 20 000 FCFA | 17 |
|
| 72 |
+
| vingt mille francs | 20 000 FCFA | 23 |
|
| 73 |
+
| caki kande-wǒ | 50 000 FCFA | 21 |
|
| 74 |
+
| cinquante mille francs | 50 000 FCFA | 10 |
|
| 75 |
+
| caki kanweko | 100 000 FCFA | 3 |
|
| 76 |
+
| cent mille francs | 100 000 FCFA | 27 |
|
| 77 |
+
| deux cent mille | 200 000 FCFA | 21 |
|
| 78 |
+
|
| 79 |
+
Les chiffres (« 5000 », « 50 000 ») et le français (« cinq mille francs », « quatre vingt mille ») sont aussi compris.
|
| 80 |
+
|
| 81 |
+
## Utilisation
|
| 82 |
+
|
| 83 |
+
```bash
|
| 84 |
+
pip install -r requirements.txt # scikit-learn 1.9.1, numpy, joblib
|
| 85 |
+
hf download finanfa-tech/fon-nlu --local-dir fon-nlu
|
| 86 |
+
cd fon-nlu
|
| 87 |
+
```
|
| 88 |
+
|
| 89 |
+
```python
|
| 90 |
+
from nlu_engine import VoiceMoMoNLU
|
| 91 |
+
|
| 92 |
+
nlu = VoiceMoMoNLU()
|
| 93 |
+
r = nlu.parse("Un jló na sɛ́ cinq mille francs dó Femi")
|
| 94 |
+
print(r["intent"], r["confidence"], r["slots"])
|
| 95 |
+
# transfert_argent 0.98 {'montant': {'raw': 'cinq mille francs', 'normalized': 5000}, 'destinataire_nom': {...}}
|
| 96 |
+
|
| 97 |
+
if r["confidence"] < 0.6:
|
| 98 |
+
pass # phrase non comprise : redemander à l'utilisateur
|
| 99 |
+
# sinon : relire « {montant} FCFA à {destinataire} » à voix haute et demander une confirmation avant tout paiement
|
| 100 |
+
```
|
| 101 |
+
|
| 102 |
+
Les scripts doivent rester dans le même dossier (le modèle utilise la fonction `normalize` de `fon_amount_parser.py`).
|
| 103 |
+
|
| 104 |
+
## Architecture
|
| 105 |
+
- **Intentions** : caractéristiques TF-IDF sur les mots (1 à 3) et sur les caractères (2 à 5), après suppression des accents et des signes du fon, puis SVM linéaire à probabilités calibrées (scikit-learn).
|
| 106 |
+
- **Informations** : règles et expressions régulières, un analyseur de montants (fon, français, chiffres), un résolveur de contacts (liens de parenté, correspondance approchée).
|
| 107 |
+
- Taille : 340 Ko pour le modèle ; environ 4 ms par phrase sur un processeur (mesuré sur un Mac, Python 3.13).
|
| 108 |
+
|
| 109 |
+
## Données d'entraînement
|
| 110 |
+
991 exemples (384 en français, 337 en fon, 270 en mélange). Les phrases viennent de **gabarits écrits pour le projet** (113 formes de phrase), variés par script (montants, noms, numéros), puis **relus et corrigés par AWADEME Ronaldo, locuteur natif** : au moins 117 exemples modifiés par lui lors de la dernière relecture, et audit des 29 expressions de montants validé par lui. Les noms et numéros sont des valeurs de test. Le jeu de données n'est pas public. Voir la carte du jeu : `finanfa-tech/fon-nlu-data` (privé).
|
| 111 |
+
|
| 112 |
+
## Évaluation
|
| 113 |
+
Validation croisée en 5 plis où les phrases de même forme restent ensemble (aucune fuite entre entraînement et test) :
|
| 114 |
+
|
| 115 |
+
| Intention | Précision | Rappel | F1 | Exemples |
|
| 116 |
+
|---|---|---|---|---|
|
| 117 |
+
| achat_credit | 1.00 | 0.56 | 0.72 | 48 |
|
| 118 |
+
| annulation_non | 1.00 | 0.81 | 0.90 | 42 |
|
| 119 |
+
| confirmation_oui | 1.00 | 0.62 | 0.77 | 42 |
|
| 120 |
+
| consulter_solde | 1.00 | 0.96 | 0.98 | 83 |
|
| 121 |
+
| fournir_compteur | 0.58 | 1.00 | 0.73 | 69 |
|
| 122 |
+
| paiement_sbee | 0.75 | 0.82 | 0.78 | 152 |
|
| 123 |
+
| paiement_soneb | 0.85 | 0.35 | 0.49 | 81 |
|
| 124 |
+
| transfert_argent | 0.94 | 1.00 | 0.97 | 474 |
|
| 125 |
+
|
| 126 |
+
**Toutes intentions : précision 87.1 %, F1 macro 79.2 %.**
|
| 127 |
+
|
| 128 |
+
Extraction du montant : 709 sur 709 exacts sur le jeu de développement. Ce chiffre n'est **pas indépendant** (les règles ont été écrites en regardant ces exemples) ; il ne prouve pas que tout montant dit autrement sera bien lu.
|
| 129 |
+
|
| 130 |
+
## Limites connues
|
| 131 |
+
- Seulement 113 formes de phrase : une manière de parler différente peut être mal comprise. Plus de phrases réelles, dites naturellement, améliorera surtout le modèle.
|
| 132 |
+
- Rappel faible sur `paiement_soneb` (0,35), `achat_credit` (0,56) et `confirmation_oui` (0,62) sur des formes inédites.
|
| 133 |
+
- Orthographe et tons du fon variables : le modèle ignore les tons, ce qui fusionne des mots différents.
|
| 134 |
+
- Les intentions `fournir_destinataire` et `demande_aide_faq`, prévues dans le schéma du projet, ne sont pas dans ce modèle.
|
| 135 |
+
- Un seul relecteur ; système de comptage traditionnel (kpowun, caki, kantaan) validé sur les 29 expressions listées seulement.
|
| 136 |
+
|
| 137 |
+
## Versions
|
| 138 |
+
- **1.0.0 (2026-11-15)** : première version publique. Entraînée sur 991 exemples corrigés ; bug corrigé dans l'analyse des montants (le « un » du fon était compté comme un chiffre : « Un jló na sɛ́ cinq mille » donnait 6 000 au lieu de 5 000) ; « kpowun ko atɔ́ɔ́n » = 625 FCFA ajouté.
|
| 139 |
+
|
| 140 |
+
## Licence
|
| 141 |
+
CC-BY-NC-4.0 (usage non commercial, attribution).
|
| 142 |
+
|
| 143 |
+
## Citation
|
| 144 |
+
AWADEME Ronaldo, Finanfa Tech. *fon-nlu : compréhension de commandes Mobile Money en fon, français et mélange*, 2026. https://huggingface.co/finanfa-tech/fon-nlu
|
contact_resolver.py
ADDED
|
@@ -0,0 +1,192 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import re
|
| 2 |
+
import unicodedata
|
| 3 |
+
from difflib import SequenceMatcher
|
| 4 |
+
|
| 5 |
+
def normalize_text(text: str) -> str:
|
| 6 |
+
"""Normalise un texte (minuscules, sans accents, sans ponctuations superflues)."""
|
| 7 |
+
text = unicodedata.normalize('NFKD', text)
|
| 8 |
+
text = ''.join(c for c in text if not unicodedata.combining(c))
|
| 9 |
+
text = text.replace('ɔ', 'o').replace('ɛ', 'e').replace('ɖ', 'd')
|
| 10 |
+
return re.sub(r'[^a-zA-Z0-9\s]', ' ', text).lower().strip()
|
| 11 |
+
|
| 12 |
+
# Dictionnaire des équivalences de parenté / surnoms en Fongbé et Français
|
| 13 |
+
# Permet de mapper par exemple "nɔ ce" (ma mère en fon) vers le contact enregistré sous "Maman"
|
| 14 |
+
RELATIONSHIP_ALIASES = {
|
| 15 |
+
# Mère / Maman
|
| 16 |
+
"maman": ["maman", "mama", "mere", "no ce", "noxó", "no"],
|
| 17 |
+
"no ce": ["maman", "mama", "mere", "no ce"],
|
| 18 |
+
"mama": ["maman", "mama", "mere", "no ce"],
|
| 19 |
+
"mere": ["maman", "mama", "mere"],
|
| 20 |
+
|
| 21 |
+
# Père / Papa
|
| 22 |
+
"papa": ["papa", "pere", "to ce", "dada", "to"],
|
| 23 |
+
"to ce": ["papa", "pere", "to ce"],
|
| 24 |
+
"pere": ["papa", "pere", "to ce"],
|
| 25 |
+
|
| 26 |
+
# Frères et Sœurs
|
| 27 |
+
"fofo": ["fofo", "grand frere", "frere", "novi ce"],
|
| 28 |
+
"fofo ce": ["fofo", "grand frere", "frere"],
|
| 29 |
+
"grand frere": ["fofo", "grand frere", "frere"],
|
| 30 |
+
"mon grand frere": ["fofo", "grand frere", "frere"],
|
| 31 |
+
"dada": ["dada", "grande soeur", "soeur", "novi ce"],
|
| 32 |
+
"dada ce": ["dada", "grande soeur", "soeur"],
|
| 33 |
+
"grande soeur": ["dada", "grande soeur", "soeur"],
|
| 34 |
+
"novi ce": ["frere", "soeur", "fofo", "dada", "novi"],
|
| 35 |
+
"mon frere": ["frere", "fofo", "novi ce"],
|
| 36 |
+
"ma soeur": ["soeur", "dada", "novi ce"],
|
| 37 |
+
|
| 38 |
+
# Conjoints
|
| 39 |
+
"asi ce": ["femme", "epouse", "cherie", "madame", "asi"],
|
| 40 |
+
"ma femme": ["femme", "epouse", "cherie", "asi ce"],
|
| 41 |
+
"asu ce": ["mari", "epoux", "cheri", "asu"],
|
| 42 |
+
"mon mari": ["mari", "epoux", "cheri", "asu ce"],
|
| 43 |
+
}
|
| 44 |
+
|
| 45 |
+
class ContactResolver:
|
| 46 |
+
"""
|
| 47 |
+
Résout un nom oral (en Fongbé ou Français) vers un contact du carnet d'adresses,
|
| 48 |
+
en gérant les liens de parenté (Maman, Papa, nɔ ce, tɔ́ ce...), le fuzzy matching
|
| 49 |
+
et les homonymes.
|
| 50 |
+
"""
|
| 51 |
+
def __init__(self, contacts: list[dict]):
|
| 52 |
+
self.contacts = contacts
|
| 53 |
+
|
| 54 |
+
def resolve(self, spoken_name: str, threshold: float = 0.65) -> dict:
|
| 55 |
+
norm_spoken = normalize_text(spoken_name)
|
| 56 |
+
if not norm_spoken:
|
| 57 |
+
return {"status": "NOT_FOUND", "match": None, "candidates": []}
|
| 58 |
+
|
| 59 |
+
# 1. Recherche d'alias (ex: l'usager dit 'nɔ ce', on cherche 'maman', 'mère', etc.)
|
| 60 |
+
target_search_terms = [norm_spoken]
|
| 61 |
+
for key, aliases in RELATIONSHIP_ALIASES.items():
|
| 62 |
+
if norm_spoken == key or norm_spoken in aliases:
|
| 63 |
+
target_search_terms.extend(aliases)
|
| 64 |
+
target_search_terms.append(key)
|
| 65 |
+
target_search_terms = list(dict.fromkeys(target_search_terms))
|
| 66 |
+
|
| 67 |
+
exact_matches = []
|
| 68 |
+
fuzzy_matches = []
|
| 69 |
+
|
| 70 |
+
for c in self.contacts:
|
| 71 |
+
norm_name = normalize_text(c["name"])
|
| 72 |
+
|
| 73 |
+
# Vérification directe ou via alias
|
| 74 |
+
matched = False
|
| 75 |
+
for term in target_search_terms:
|
| 76 |
+
if term == norm_name:
|
| 77 |
+
exact_matches.append((1.0, c))
|
| 78 |
+
matched = True
|
| 79 |
+
break
|
| 80 |
+
elif term in norm_name.split() or norm_name in term.split():
|
| 81 |
+
exact_matches.append((0.92, c))
|
| 82 |
+
matched = True
|
| 83 |
+
break
|
| 84 |
+
|
| 85 |
+
if not matched:
|
| 86 |
+
# Calcul de similarité phonétique / fuzzy Levenshtein
|
| 87 |
+
best_sim = max(SequenceMatcher(None, term, norm_name).ratio() for term in target_search_terms)
|
| 88 |
+
if best_sim >= threshold:
|
| 89 |
+
fuzzy_matches.append((best_sim, c))
|
| 90 |
+
|
| 91 |
+
all_matches = sorted(exact_matches + fuzzy_matches, key=lambda x: x[0], reverse=True)
|
| 92 |
+
# Déduplication par id de contact
|
| 93 |
+
seen_ids = set()
|
| 94 |
+
dedup_matches = []
|
| 95 |
+
for score, contact in all_matches:
|
| 96 |
+
if contact["id"] not in seen_ids:
|
| 97 |
+
seen_ids.add(contact["id"])
|
| 98 |
+
dedup_matches.append((score, contact))
|
| 99 |
+
|
| 100 |
+
if not dedup_matches:
|
| 101 |
+
return {
|
| 102 |
+
"status": "NOT_FOUND",
|
| 103 |
+
"spoken_name": spoken_name,
|
| 104 |
+
"message_fon": f"Un mɔ « {spoken_name} » ɖò xóxlá towe mɛ ǎ. Nambá tɔn tɛ́ wɛ?",
|
| 105 |
+
"message_fr": f"Je n'ai pas trouvé « {spoken_name} » dans tes contacts. Quel est son numéro ?"
|
| 106 |
+
}
|
| 107 |
+
|
| 108 |
+
top_score, top_contact = dedup_matches[0]
|
| 109 |
+
close_candidates = [c for score, c in dedup_matches if score >= 0.85]
|
| 110 |
+
|
| 111 |
+
if len(close_candidates) == 1:
|
| 112 |
+
return {
|
| 113 |
+
"status": "MATCH_UNIQUE",
|
| 114 |
+
"match": top_contact,
|
| 115 |
+
"confidence": top_score,
|
| 116 |
+
"confirmation_fon": f"A jló na sɛ́ akwɛ ɔ dó {top_contact['name']} ({top_contact['phone']}) à?",
|
| 117 |
+
"confirmation_fr": f"Veux-tu envoyer l'argent à {top_contact['name']} ({top_contact['phone']}) ?"
|
| 118 |
+
}
|
| 119 |
+
|
| 120 |
+
return {
|
| 121 |
+
"status": "MULTIPLE_MATCHES",
|
| 122 |
+
"candidates": close_candidates,
|
| 123 |
+
"spoken_name": spoken_name,
|
| 124 |
+
"disambiguation_fon": f"Mɛ wè wɛ ɖó nyǐkɔ « {spoken_name} » : " + " kpo ".join(c['name'] for c in close_candidates) + ". Mɛ̌ɖé jló na sɛ́ dó?",
|
| 125 |
+
"disambiguation_fr": f"Tu as plusieurs contacts sous « {spoken_name} » : " + ", ".join(c['name'] for c in close_candidates) + ". Lequel choisis-tu ?"
|
| 126 |
+
}
|
| 127 |
+
|
| 128 |
+
# CONTACTS DE DÉMONSTRATION UNIQUEMENT (numéros factices). Ne jamais utiliser en production : passez toujours la vraie liste de contacts de l'utilisateur.
|
| 129 |
+
DEFAULT_CONTACTS = [
|
| 130 |
+
{"id": "1", "name": "Maman", "phone": "+229 00 00 00 01"},
|
| 131 |
+
{"id": "2", "name": "Papa", "phone": "+229 00 00 00 02"},
|
| 132 |
+
{"id": "3", "name": "Fofó", "phone": "+229 00 00 00 03"},
|
| 133 |
+
{"id": "4", "name": "Femme", "phone": "+229 00 00 00 04"},
|
| 134 |
+
{"id": "5", "name": "Koffi", "phone": "+229 00 00 00 05"},
|
| 135 |
+
{"id": "6", "name": "Rachid", "phone": "+229 00 00 00 06"},
|
| 136 |
+
{"id": "7", "name": "Mariam", "phone": "+229 00 00 00 07"},
|
| 137 |
+
{"id": "8", "name": "Bio", "phone": "+229 00 00 00 08"},
|
| 138 |
+
{"id": "9", "name": "Sèna", "phone": "+229 00 00 00 09"},
|
| 139 |
+
{"id": "10", "name": "Femi", "phone": "+229 00 00 00 10"},
|
| 140 |
+
{"id": "11", "name": "Ablawa", "phone": "+229 00 00 00 11"},
|
| 141 |
+
{"id": "12", "name": "Sègla", "phone": "+229 00 00 00 12"},
|
| 142 |
+
{"id": "13", "name": "Modeste", "phone": "+229 00 00 00 13"},
|
| 143 |
+
{"id": "14", "name": "Gisèle", "phone": "+229 00 00 00 14"},
|
| 144 |
+
{"id": "15", "name": "Tonton", "phone": "+229 00 00 00 15"},
|
| 145 |
+
{"id": "16", "name": "Tantie", "phone": "+229 00 00 00 16"}
|
| 146 |
+
]
|
| 147 |
+
|
| 148 |
+
_default_resolver = None
|
| 149 |
+
|
| 150 |
+
def resolve_contact(query: str, contacts: list[dict] = None) -> dict | None:
|
| 151 |
+
"""
|
| 152 |
+
Fonction utilitaire pour résoudre un nom de contact ou lien de parenté.
|
| 153 |
+
Retourne {'nom': str, 'phone': str, 'match_info': dict} ou None.
|
| 154 |
+
"""
|
| 155 |
+
global _default_resolver
|
| 156 |
+
if contacts is not None:
|
| 157 |
+
resolver = ContactResolver(contacts)
|
| 158 |
+
else:
|
| 159 |
+
if _default_resolver is None:
|
| 160 |
+
_default_resolver = ContactResolver(DEFAULT_CONTACTS)
|
| 161 |
+
resolver = _default_resolver
|
| 162 |
+
|
| 163 |
+
res = resolver.resolve(query)
|
| 164 |
+
if res["status"] == "MATCH_UNIQUE":
|
| 165 |
+
return {
|
| 166 |
+
"nom": res["match"]["name"],
|
| 167 |
+
"phone": res["match"]["phone"],
|
| 168 |
+
"match_info": res
|
| 169 |
+
}
|
| 170 |
+
elif res["status"] == "MULTIPLE_MATCHES" and res.get("candidates"):
|
| 171 |
+
return {
|
| 172 |
+
"nom": res["candidates"][0]["name"],
|
| 173 |
+
"phone": res["candidates"][0]["phone"],
|
| 174 |
+
"match_info": res
|
| 175 |
+
}
|
| 176 |
+
return None
|
| 177 |
+
|
| 178 |
+
if __name__ == "__main__":
|
| 179 |
+
contacts = [
|
| 180 |
+
{"id": "1", "name": "Maman", "phone": "+229 00 00 00 17"},
|
| 181 |
+
{"id": "2", "name": "Papa", "phone": "+229 00 00 00 18"},
|
| 182 |
+
{"id": "3", "name": "Fofó Mensah", "phone": "+229 00 00 00 19"},
|
| 183 |
+
{"id": "4", "name": "Chérie / Femme", "phone": "+229 00 00 00 20"},
|
| 184 |
+
{"id": "5", "name": "Kofi", "phone": "+229 00 00 00 21"},
|
| 185 |
+
{"id": "6", "name": "Kofi Plombier", "phone": "+229 00 00 00 22"}
|
| 186 |
+
]
|
| 187 |
+
resolver = ContactResolver(contacts)
|
| 188 |
+
print("1. 'nɔ ce' (ma mère en fon) ->", resolver.resolve("nɔ ce")['match']['name'])
|
| 189 |
+
print("2. 'tɔ́ ce' (mon père en fon) ->", resolver.resolve("tɔ́ ce")['match']['name'])
|
| 190 |
+
print("3. 'maman' (en français) ->", resolver.resolve("maman")['match']['name'])
|
| 191 |
+
print("4. 'asì ce' (mon épouse) ->", resolver.resolve("asì ce")['match']['name'])
|
| 192 |
+
print("5. 'fofó' (grand frère) ->", resolver.resolve("fofó")['match']['name'])
|
fon_amount_parser.py
ADDED
|
@@ -0,0 +1,167 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import re
|
| 2 |
+
import unicodedata
|
| 3 |
+
|
| 4 |
+
def normalize(text: str) -> str:
|
| 5 |
+
text = unicodedata.normalize('NFKD', text)
|
| 6 |
+
text = ''.join(c for c in text if not unicodedata.combining(c))
|
| 7 |
+
text = text.replace('ɔ', 'o').replace('ɛ', 'e').replace('ɖ', 'd')
|
| 8 |
+
return text.lower().strip()
|
| 9 |
+
|
| 10 |
+
# Multiplicateurs Fongbé
|
| 11 |
+
FON_MULT = {
|
| 12 |
+
"dokpo": 1, "de": 1,
|
| 13 |
+
"we": 2, "aton": 3, "ene": 4, "atoon": 5,
|
| 14 |
+
"ayizen": 6, "tenwe": 7, "tanton": 8, "tenne": 9,
|
| 15 |
+
"wo": 10,
|
| 16 |
+
"afoton": 15, # afɔtɔ́n = 15 en Fongbé
|
| 17 |
+
"afaton": 15, # tolérance orthographique
|
| 18 |
+
"ko": 20,
|
| 19 |
+
"gban": 30,
|
| 20 |
+
"kande": 40,
|
| 21 |
+
"kandewo": 50,
|
| 22 |
+
"kanweko": 100,
|
| 23 |
+
"afode": 200
|
| 24 |
+
}
|
| 25 |
+
|
| 26 |
+
# Unités et dizaines en Français
|
| 27 |
+
FRENCH_UNITS = {
|
| 28 |
+
"un": 1, "une": 1, "deux": 2, "trois": 3, "quatre": 4, "cinq": 5,
|
| 29 |
+
"six": 6, "sept": 7, "huit": 8, "neuf": 9, "dix": 10,
|
| 30 |
+
"onze": 11, "douze": 12, "treize": 13, "quatorze": 14, "quinze": 15,
|
| 31 |
+
"seize": 16, "dix-sept": 17, "dix-huit": 18, "dix-neuf": 19,
|
| 32 |
+
"vingt": 20, "trente": 30, "quarante": 40, "cinquante": 50,
|
| 33 |
+
"soixante": 60, "soixante-dix": 70, "quatre-vingt": 80, "quatre-vingts": 80,
|
| 34 |
+
"quatre-vingt-dix": 90
|
| 35 |
+
}
|
| 36 |
+
|
| 37 |
+
FRENCH_NUMBER_WORDS = {w for k in FRENCH_UNITS for w in k.split('-')} | {"cent", "cents", "vingts", "et"}
|
| 38 |
+
|
| 39 |
+
def parse_french_mille(clean: str) -> int:
|
| 40 |
+
"""Analyse le nombre qui précède 'mille' (cinquante mille, deux cent mille, quatre vingt mille...).
|
| 41 |
+
Seuls les mots-nombres CONSÉCUTIFS juste avant « mille » comptent : dans « un jlo na se cinq mille », le « un » du fon
|
| 42 |
+
(= « je ») ne doit pas s'ajouter au cinq (bug corrigé : 5000 était lu 6000)."""
|
| 43 |
+
m = re.search(r'([a-z\s\-]+?)\s+mille\b', clean)
|
| 44 |
+
if not m:
|
| 45 |
+
return 1000
|
| 46 |
+
tokens = [w for w in re.split(r'[\s\-]+', m.group(0).rsplit('mille', 1)[0].strip()) if w]
|
| 47 |
+
words = []
|
| 48 |
+
for w in reversed(tokens):
|
| 49 |
+
if w in FRENCH_NUMBER_WORDS:
|
| 50 |
+
words.append(w)
|
| 51 |
+
else:
|
| 52 |
+
break
|
| 53 |
+
words.reverse()
|
| 54 |
+
current, i = 0, 0
|
| 55 |
+
while i < len(words):
|
| 56 |
+
w = words[i]
|
| 57 |
+
if w == "quatre" and i + 1 < len(words) and words[i + 1] in ("vingt", "vingts"):
|
| 58 |
+
current += 80; i += 2; continue
|
| 59 |
+
if w in ("cent", "cents"):
|
| 60 |
+
current = 100 if current == 0 else current * 100
|
| 61 |
+
elif w in FRENCH_UNITS:
|
| 62 |
+
current += FRENCH_UNITS[w]
|
| 63 |
+
i += 1
|
| 64 |
+
return (current * 1000) if current > 0 else 1000
|
| 65 |
+
|
| 66 |
+
def parse_fon_amount(text: str) -> int | None:
|
| 67 |
+
"""
|
| 68 |
+
Extrait un montant en FCFA depuis une chaîne en Fongbé, en Français ou en chiffres.
|
| 69 |
+
Supporte les montants courants et les montants colossaux (jusqu'à plusieurs millions FCFA) :
|
| 70 |
+
- Fongbé : 'caki wè' (2000), 'caki ko' (20000), 'caki kande-wǒ' (50000), 'caki kanweko' (100000)
|
| 71 |
+
- Français : 'quinze mille' (15000), 'cinquante mille' (50000), 'deux cent mille' (200000)
|
| 72 |
+
- Chiffres : '50000', '15000', '20 000', '100.000'
|
| 73 |
+
"""
|
| 74 |
+
# 0. Normalisation des séparateurs de milliers (ex: 50 000 ou 50.000 -> 50000)
|
| 75 |
+
text_clean_num = re.sub(r'(\d+)[ .](\d{3})\b', r'\1\2', text)
|
| 76 |
+
clean = normalize(text_clean_num)
|
| 77 |
+
|
| 78 |
+
# 1. Base Millions
|
| 79 |
+
if "million" in clean:
|
| 80 |
+
if "deux" in clean: return 2000000
|
| 81 |
+
if "trois" in clean: return 3000000
|
| 82 |
+
if "cinq" in clean: return 5000000
|
| 83 |
+
return 1000000
|
| 84 |
+
|
| 85 |
+
# 2. Base Caki / Kotokun / Franc Afɔtɔ́n (1 000 FCFA)
|
| 86 |
+
if "caki" in clean or "kotokun" in clean or "afoton" in clean or "afaton" in clean:
|
| 87 |
+
# Cas où afɔtɔ́n (15) est le multiplicateur de caki (ex: caki afɔtɔ́n = 15 000 FCFA)
|
| 88 |
+
if "caki" in clean and ("afoton" in clean or "afaton" in clean):
|
| 89 |
+
return 15000
|
| 90 |
+
|
| 91 |
+
parts = clean.replace("franc", "").replace("akwe", "").replace("-", "").split()
|
| 92 |
+
base_idx = -1
|
| 93 |
+
for i, p in enumerate(parts):
|
| 94 |
+
if p in ["caki", "kotokun", "afoton", "afaton"]:
|
| 95 |
+
base_idx = i
|
| 96 |
+
break
|
| 97 |
+
if base_idx != -1:
|
| 98 |
+
sub = parts[base_idx + 1:base_idx + 4]
|
| 99 |
+
sub_str = ''.join(sub)
|
| 100 |
+
if "kandewo" in sub_str or ("kande" in sub and "wo" in sub):
|
| 101 |
+
return 50 * 1000
|
| 102 |
+
if "konukunatoon" in sub_str or ("ko" in sub and "atoon" in sub):
|
| 103 |
+
return 25 * 1000
|
| 104 |
+
if "wonukunatoon" in sub_str or ("wo" in sub and "atoon" in sub):
|
| 105 |
+
return 15 * 1000
|
| 106 |
+
for p in sub:
|
| 107 |
+
if p in FON_MULT and p != "de":
|
| 108 |
+
return FON_MULT[p] * 1000
|
| 109 |
+
# Si chiffres arabes après caki (ex: caki 50)
|
| 110 |
+
for p in sub:
|
| 111 |
+
if p.isdigit():
|
| 112 |
+
return int(p) * 1000
|
| 113 |
+
return 1000
|
| 114 |
+
|
| 115 |
+
# 3. Base Kpowun (25 FCFA) - Système traditionnel de comptage
|
| 116 |
+
if "kpowun" in clean:
|
| 117 |
+
if "ko nukun ene" in clean: return 24 * 25 # 600 FCFA
|
| 118 |
+
if "ko nukun atoon" in clean: return 25 * 25 # 625 FCFA
|
| 119 |
+
if "ko atoon" in clean: return 25 * 25 # 625 FCFA (forme validée par le locuteur : kpowun ko atɔ́ɔ́n)
|
| 120 |
+
if "ko" in clean: return 20 * 25 # 500 FCFA
|
| 121 |
+
parts = clean.replace("franc", "").split()
|
| 122 |
+
for p in parts:
|
| 123 |
+
if p in FON_MULT and p != "kpowun":
|
| 124 |
+
return FON_MULT[p] * 25
|
| 125 |
+
return 25
|
| 126 |
+
|
| 127 |
+
# 4. Base Kantaan (200 FCFA)
|
| 128 |
+
if "kantaan" in clean:
|
| 129 |
+
parts = clean.replace("franc", "").split()
|
| 130 |
+
for p in parts:
|
| 131 |
+
if p in FON_MULT and p != "kantaan":
|
| 132 |
+
return FON_MULT[p] * 200
|
| 133 |
+
return 200
|
| 134 |
+
|
| 135 |
+
# 5. Expressions françaises avec 'mille'
|
| 136 |
+
if "mille" in clean:
|
| 137 |
+
return parse_french_mille(clean)
|
| 138 |
+
|
| 139 |
+
# 6. Chiffres arabes directs (ex: 50000, 15000, 20000, 100000)
|
| 140 |
+
# On ignore les numéros de téléphone (8 chiffres) et compteurs (11 chiffres)
|
| 141 |
+
for m in re.finditer(r'\b(\d+)\b', text_clean_num):
|
| 142 |
+
num_str = m.group(1)
|
| 143 |
+
val = int(num_str)
|
| 144 |
+
# Montants valides : de 100 FCFA à 5 000 000 FCFA (et pas 8 ou 11 chiffres)
|
| 145 |
+
if 100 <= val <= 5000000 and len(num_str) not in [8, 11]:
|
| 146 |
+
return val
|
| 147 |
+
|
| 148 |
+
return None
|
| 149 |
+
|
| 150 |
+
if __name__ == "__main__":
|
| 151 |
+
tests = [
|
| 152 |
+
("Xɔ crédit sbee 50000 dó 14253647589 jí", 50000),
|
| 153 |
+
("Recharge mon compteur de cinquante mille francs", 50000),
|
| 154 |
+
("Xɔ crédit sbee caki ko dó 14253647589 jí", 20000),
|
| 155 |
+
("Payer quinze mille pour le courant", 15000),
|
| 156 |
+
("Sú facture SONEB cent mille", 100000),
|
| 157 |
+
("Sɛ́ deux cent mille à Papa", 200000),
|
| 158 |
+
("Acheter crédit SBEE de 15000 sur le 14253647589", 15000),
|
| 159 |
+
("Xɔ crédit sbee caki kande-wǒ dó 14253647589 jí", 50000),
|
| 160 |
+
("Xɔ crédit sbee caki kanweko dó 14253647589 jí", 100000),
|
| 161 |
+
("Paiement facture d'eau 20 000", 20000)
|
| 162 |
+
]
|
| 163 |
+
for text, expected in tests:
|
| 164 |
+
res = parse_fon_amount(text)
|
| 165 |
+
print(f"« {text} » -> {res} FCFA (Attendu: {expected})")
|
| 166 |
+
assert res == expected, f"ERREUR: {res} != {expected}"
|
| 167 |
+
print("\nTOUS LES TESTS DE MONTANTS COLOSSAUX ET COURANTS ONT RÉUSSI !")
|
intent_classifier.joblib
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:e6d3447e6b21ecea1df7a2c8e747303467a6c0e5eda64e6c7ab969b8b0b8b952
|
| 3 |
+
size 339925
|
nlu_engine.py
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Moteur d'inférence NLU en temps réel pour Voice-MoMo (Option A).
|
| 3 |
+
Combine la classification d'intention probabiliste et l'extraction de slots culturelle.
|
| 4 |
+
Latence : < 5ms. Zéro hallucination financière.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
import json
|
| 8 |
+
import joblib
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
from typing import Dict, Any, Optional
|
| 11 |
+
|
| 12 |
+
from slot_extractor import extract_slots
|
| 13 |
+
|
| 14 |
+
HERE = Path(__file__).resolve().parent
|
| 15 |
+
MODEL_PATH = HERE / "intent_classifier.joblib"
|
| 16 |
+
METADATA_PATH = HERE / "nlu_metadata.json"
|
| 17 |
+
|
| 18 |
+
class VoiceMoMoNLU:
|
| 19 |
+
def __init__(self, model_path: Optional[Path] = None):
|
| 20 |
+
self.model_path = model_path or MODEL_PATH
|
| 21 |
+
self.model = None
|
| 22 |
+
self.classes = []
|
| 23 |
+
self._load_model()
|
| 24 |
+
|
| 25 |
+
def _load_model(self):
|
| 26 |
+
if not self.model_path.exists():
|
| 27 |
+
raise FileNotFoundError(f"Modèle NLU introuvable à : {self.model_path}. Lancez l'entraînement d'abord.")
|
| 28 |
+
self.model = joblib.load(self.model_path)
|
| 29 |
+
self.classes = list(self.model.classes_)
|
| 30 |
+
|
| 31 |
+
def parse(self, text: str) -> Dict[str, Any]:
|
| 32 |
+
"""
|
| 33 |
+
Analyse une phrase utilisateur en Fongbé, Français ou Code-Switching.
|
| 34 |
+
Retourne l'intention, l'indice de confiance et les slots extraits.
|
| 35 |
+
"""
|
| 36 |
+
if not text or not text.strip():
|
| 37 |
+
return {
|
| 38 |
+
"text": text,
|
| 39 |
+
"intent": "inconnu",
|
| 40 |
+
"confidence": 0.0,
|
| 41 |
+
"slots": {}
|
| 42 |
+
}
|
| 43 |
+
|
| 44 |
+
text = text.strip()
|
| 45 |
+
|
| 46 |
+
# 1. Prédiction de l'intention avec probabilités calibrées
|
| 47 |
+
probas = self.model.predict_proba([text])[0]
|
| 48 |
+
best_idx = probas.argmax()
|
| 49 |
+
intent = self.classes[best_idx]
|
| 50 |
+
confidence = float(probas[best_idx])
|
| 51 |
+
|
| 52 |
+
# 2. Extraction des entités (slots)
|
| 53 |
+
slots = extract_slots(text, intent=intent)
|
| 54 |
+
|
| 55 |
+
return {
|
| 56 |
+
"text": text,
|
| 57 |
+
"intent": intent,
|
| 58 |
+
"confidence": round(confidence, 4),
|
| 59 |
+
"slots": slots
|
| 60 |
+
}
|
| 61 |
+
|
| 62 |
+
if __name__ == "__main__":
|
| 63 |
+
nlu = VoiceMoMoNLU()
|
| 64 |
+
examples = [
|
| 65 |
+
"Xɔ crédit sbee caki wè dó 14253647589 jí",
|
| 66 |
+
"Sɛ́ caki atɔn dó nɔ ce",
|
| 67 |
+
"Envoie cinq mille francs à Papa",
|
| 68 |
+
"Sú akwɛ sìn tɔn caki atɔn dó police 78965412 jí",
|
| 69 |
+
"Xɔ credit kpowun ko nukun ɛnɛ nú mì",
|
| 70 |
+
"Akwɛ nabí wɛ kpò ɖò comtù ce mɛ?",
|
| 71 |
+
"Ɛɛn, é sɔgbe, sɛ́dó",
|
| 72 |
+
"Eo, e sɔ́ gbɛ́ a, gbéjé"
|
| 73 |
+
]
|
| 74 |
+
for ex in examples:
|
| 75 |
+
res = nlu.parse(ex)
|
| 76 |
+
print(f"\nPhrase : {ex}")
|
| 77 |
+
print(f"Intent : {res['intent']} (confiance: {res['confidence'] * 100:.1f}%)")
|
| 78 |
+
print(f"Slots : {res['slots']}")
|
nlu_metadata.json
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"name": "fon-nlu",
|
| 3 |
+
"version": "1.0.0",
|
| 4 |
+
"date": "2026-11-15",
|
| 5 |
+
"classes": [
|
| 6 |
+
"achat_credit",
|
| 7 |
+
"annulation_non",
|
| 8 |
+
"confirmation_oui",
|
| 9 |
+
"consulter_solde",
|
| 10 |
+
"fournir_compteur",
|
| 11 |
+
"paiement_sbee",
|
| 12 |
+
"paiement_soneb",
|
| 13 |
+
"transfert_argent"
|
| 14 |
+
],
|
| 15 |
+
"n_examples": 991,
|
| 16 |
+
"n_phrase_forms": 113,
|
| 17 |
+
"eval_leaky_cv_accuracy": 1.0,
|
| 18 |
+
"eval_grouped_cv": {
|
| 19 |
+
"folds": 5,
|
| 20 |
+
"accuracy": 0.8708,
|
| 21 |
+
"f1_macro": 0.7923,
|
| 22 |
+
"per_class": {
|
| 23 |
+
"achat_credit": {
|
| 24 |
+
"precision": 1.0,
|
| 25 |
+
"recall": 0.562,
|
| 26 |
+
"f1-score": 0.72,
|
| 27 |
+
"support": 48.0
|
| 28 |
+
},
|
| 29 |
+
"annulation_non": {
|
| 30 |
+
"precision": 1.0,
|
| 31 |
+
"recall": 0.81,
|
| 32 |
+
"f1-score": 0.895,
|
| 33 |
+
"support": 42.0
|
| 34 |
+
},
|
| 35 |
+
"confirmation_oui": {
|
| 36 |
+
"precision": 1.0,
|
| 37 |
+
"recall": 0.619,
|
| 38 |
+
"f1-score": 0.765,
|
| 39 |
+
"support": 42.0
|
| 40 |
+
},
|
| 41 |
+
"consulter_solde": {
|
| 42 |
+
"precision": 1.0,
|
| 43 |
+
"recall": 0.964,
|
| 44 |
+
"f1-score": 0.982,
|
| 45 |
+
"support": 83.0
|
| 46 |
+
},
|
| 47 |
+
"fournir_compteur": {
|
| 48 |
+
"precision": 0.58,
|
| 49 |
+
"recall": 1.0,
|
| 50 |
+
"f1-score": 0.734,
|
| 51 |
+
"support": 69.0
|
| 52 |
+
},
|
| 53 |
+
"paiement_sbee": {
|
| 54 |
+
"precision": 0.749,
|
| 55 |
+
"recall": 0.822,
|
| 56 |
+
"f1-score": 0.784,
|
| 57 |
+
"support": 152.0
|
| 58 |
+
},
|
| 59 |
+
"paiement_soneb": {
|
| 60 |
+
"precision": 0.848,
|
| 61 |
+
"recall": 0.346,
|
| 62 |
+
"f1-score": 0.491,
|
| 63 |
+
"support": 81.0
|
| 64 |
+
},
|
| 65 |
+
"transfert_argent": {
|
| 66 |
+
"precision": 0.939,
|
| 67 |
+
"recall": 1.0,
|
| 68 |
+
"f1-score": 0.968,
|
| 69 |
+
"support": 474.0
|
| 70 |
+
}
|
| 71 |
+
}
|
| 72 |
+
},
|
| 73 |
+
"amount_extraction_dev_set": {
|
| 74 |
+
"exact": 709,
|
| 75 |
+
"total": 709,
|
| 76 |
+
"note": "jeu de développement : non indépendant"
|
| 77 |
+
},
|
| 78 |
+
"sklearn_version": "1.9.1"
|
| 79 |
+
}
|
requirements.txt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
scikit-learn==1.9.1
|
| 2 |
+
numpy
|
| 3 |
+
joblib
|
slot_extractor.py
ADDED
|
@@ -0,0 +1,140 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Extracteur d'entités hybride et culturel pour Voice-MoMo NLU.
|
| 3 |
+
Extrait les montants (Fongbé / Français / Chiffres), destinataires (contacts / parenté / numéros),
|
| 4 |
+
et compteurs (SBEE / SONEB) avec zéro hallucination financière.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
import re
|
| 8 |
+
import unicodedata
|
| 9 |
+
from typing import Dict, Any, Optional
|
| 10 |
+
from fon_amount_parser import parse_fon_amount, normalize
|
| 11 |
+
from contact_resolver import resolve_contact
|
| 12 |
+
|
| 13 |
+
# Noms de compteurs connus
|
| 14 |
+
KNOWN_METERS = {
|
| 15 |
+
"compteur maison": "compteur maison",
|
| 16 |
+
"kɔmpitɛɛ xwegbe ton": "compteur maison",
|
| 17 |
+
"kompitee xwegbe ton": "compteur maison",
|
| 18 |
+
"kɔmtɛɛ xwegbe ton": "compteur maison",
|
| 19 |
+
"komtee xwegbe ton": "compteur maison",
|
| 20 |
+
"compteur boutique": "compteur boutique",
|
| 21 |
+
"compteur salon": "compteur salon",
|
| 22 |
+
"compteur atelier": "compteur atelier",
|
| 23 |
+
"compteur maman": "compteur maman"
|
| 24 |
+
}
|
| 25 |
+
|
| 26 |
+
def extract_slots(text: str, intent: Optional[str] = None) -> Dict[str, Any]:
|
| 27 |
+
"""
|
| 28 |
+
Extrait l'ensemble des slots disponibles dans la phrase utilisateur.
|
| 29 |
+
Retourne un dictionnaire des entités normalisées et leurs formes brutes.
|
| 30 |
+
"""
|
| 31 |
+
slots = {}
|
| 32 |
+
clean = normalize(text)
|
| 33 |
+
|
| 34 |
+
# 1. Extraction du Montant (FCFA)
|
| 35 |
+
montant_val = parse_fon_amount(text)
|
| 36 |
+
if montant_val is not None:
|
| 37 |
+
# Trouver la portion de texte brute correspondante
|
| 38 |
+
raw_montant = None
|
| 39 |
+
# Recherche par motifs connus
|
| 40 |
+
fon_amount_patterns = [
|
| 41 |
+
r'caki\s+[^\s,]+(?:\s+[^\s,]+)?(?:\s+[^\s,]+)?',
|
| 42 |
+
r'franc\s+caki\s+[^\s,]+',
|
| 43 |
+
r'kpowun\s+ko(?:\s+nukun\s+[^\s,]+|\s+atɔ́ɔ́n)?',
|
| 44 |
+
r'franc\s+afatɔ́n\s+[^\s,]+',
|
| 45 |
+
r'kotokun\s+[^\s,]+',
|
| 46 |
+
r'kantaan\s+[^\s,]+',
|
| 47 |
+
r'franc\s+kantaan\s+[^\s,]+',
|
| 48 |
+
r'\b\d{1,3}(?:[ .]\d{3})+\b', # 50 000 ou 100.000
|
| 49 |
+
r'\b\d{3,7}\b', # 100 à 5000000
|
| 50 |
+
r'(?:[a-zA-Z\-]+?\s+)?(?:cent\s+)?(?:un|deux|trois|quatre|cinq|six|sept|huit|neuf|dix|quinze|seize|vingt|trente|quarante|cinquante|soixante|cent)\s+mille(?:\s+francs)?',
|
| 51 |
+
r'mille\s+francs',
|
| 52 |
+
r'(?:un|deux|trois|cinq)\s+millions?'
|
| 53 |
+
]
|
| 54 |
+
for pat in fon_amount_patterns:
|
| 55 |
+
m = re.search(pat, text, re.IGNORECASE)
|
| 56 |
+
if m:
|
| 57 |
+
raw_montant = m.group(0)
|
| 58 |
+
break
|
| 59 |
+
|
| 60 |
+
slots["montant"] = {
|
| 61 |
+
"raw": raw_montant or str(montant_val),
|
| 62 |
+
"normalized": montant_val
|
| 63 |
+
}
|
| 64 |
+
|
| 65 |
+
# 2. Extraction du Numéro de Compteur SBEE (11 chiffres) ou Compteur Nom
|
| 66 |
+
# Compteur à 11 chiffres
|
| 67 |
+
m_cpt = re.search(r'\b(14\d{9}|\d{11})\b', text)
|
| 68 |
+
if m_cpt:
|
| 69 |
+
slots["numero_compteur"] = {
|
| 70 |
+
"raw": m_cpt.group(1),
|
| 71 |
+
"normalized": m_cpt.group(1)
|
| 72 |
+
}
|
| 73 |
+
else:
|
| 74 |
+
# Compteur nommé (ex: compteur maison, kɔ́mpitɛ́ɛ́ xwégbe tɔn)
|
| 75 |
+
for alias, norm_name in KNOWN_METERS.items():
|
| 76 |
+
if alias in clean:
|
| 77 |
+
slots["compteur_nom"] = {
|
| 78 |
+
"raw": alias,
|
| 79 |
+
"normalized": norm_name
|
| 80 |
+
}
|
| 81 |
+
break
|
| 82 |
+
|
| 83 |
+
# 3. Extraction de la Police SONEB (8 chiffres)
|
| 84 |
+
m_police = re.search(r'(?:police\s+)?\b(78\d{6}|\d{8})\b', text, re.IGNORECASE)
|
| 85 |
+
# S'il ne s'agit pas d'un numéro de téléphone destinataire
|
| 86 |
+
if m_police:
|
| 87 |
+
num = m_police.group(1)
|
| 88 |
+
if intent == "paiement_soneb" or "soneb" in clean or "sin" in clean or "police" in clean.lower():
|
| 89 |
+
slots["numero_police"] = {
|
| 90 |
+
"raw": num,
|
| 91 |
+
"normalized": num
|
| 92 |
+
}
|
| 93 |
+
|
| 94 |
+
# 4. Extraction du Destinataire (Nom, Parenté, Numéro Bénin 8 chiffres)
|
| 95 |
+
if intent in [None, "transfert_argent", "achat_credit"]:
|
| 96 |
+
# Numéro direct (8 chiffres commençant par 4, 5, 6, 9)
|
| 97 |
+
m_phone = re.search(r'\b([4569]\d{7})\b', text)
|
| 98 |
+
if m_phone and "numero_police" not in slots:
|
| 99 |
+
slots["destinataire_numero"] = {
|
| 100 |
+
"raw": m_phone.group(1),
|
| 101 |
+
"normalized": m_phone.group(1)
|
| 102 |
+
}
|
| 103 |
+
else:
|
| 104 |
+
# Chercher dans les expressions de parenté ou prénoms
|
| 105 |
+
# "dó Maman", "dó nɔ ce", "à Papa", "pour mon grand frère", etc.
|
| 106 |
+
recipient_patterns = [
|
| 107 |
+
r'(?:sur\s+le\s+numéro|sur\s+le)\s+([^0-9\n\r,;?!]+?)(?:\s+jí|\s*$)',
|
| 108 |
+
r'(?:dó|nú|dó\s+mɛ|à|pour|vers)\s+([^0-9\n\r,;?!]+?)(?:\s+jí|\s*$)',
|
| 109 |
+
r'(?:yì\s+nú)\s+([^0-9\n\r,;?!]+?)(?:\s+jí|\s*$)'
|
| 110 |
+
]
|
| 111 |
+
for pat in recipient_patterns:
|
| 112 |
+
m_rec = re.search(pat, text, re.IGNORECASE)
|
| 113 |
+
if m_rec:
|
| 114 |
+
raw_dest = m_rec.group(1).strip()
|
| 115 |
+
if raw_dest.lower() in ["mɛ", "mi", "mì", "moi", "compteur maison", "compteur boutique"]:
|
| 116 |
+
continue
|
| 117 |
+
resolved = resolve_contact(raw_dest)
|
| 118 |
+
norm_name = resolved["nom"] if resolved else raw_dest.title()
|
| 119 |
+
slots["destinataire_nom"] = {
|
| 120 |
+
"raw": raw_dest,
|
| 121 |
+
"normalized": norm_name,
|
| 122 |
+
"contact_info": resolved
|
| 123 |
+
}
|
| 124 |
+
break
|
| 125 |
+
|
| 126 |
+
return slots
|
| 127 |
+
|
| 128 |
+
if __name__ == "__main__":
|
| 129 |
+
test_cases = [
|
| 130 |
+
("Xɔ crédit sbee caki wè dó 14253647589 jí", "paiement_sbee"),
|
| 131 |
+
("Sɛ́ akwɛ caki atɔ́ɔ́n dó tɔ́ ce", "transfert_argent"),
|
| 132 |
+
("Sú facture SONEB ce caki atɔ́ɔ́n dó police 78965412 jí", "paiement_soneb"),
|
| 133 |
+
("Envoie 5000 sur le 97123456", "transfert_argent"),
|
| 134 |
+
("Xɔ credit kpowun ko nukun ɛnɛ nú mì", "achat_credit"),
|
| 135 |
+
("Xɔ crédit caki atɔ́ɔ́n nú dó compteur maison ji", "paiement_sbee")
|
| 136 |
+
]
|
| 137 |
+
for text, intent in test_cases:
|
| 138 |
+
res = extract_slots(text, intent)
|
| 139 |
+
print(f"\n[Phrase]: {text}")
|
| 140 |
+
print(f" Slots extraits: {res}")
|