Download contact_resolver.py from finanfa-tech/fon-nlu: direct link, hf CLI and curl.
- Browser
- Download file 8.7 kB
-
https://huggingface.co/finanfa-tech/fon-nlu/resolve/main/contact_resolver.py
- Command line
-
hf download hf://finanfa-tech/fon-nlu/contact_resolver.py
-
curl -L -o contact_resolver.py https://huggingface.co/finanfa-tech/fon-nlu/resolve/main/contact_resolver.py
8.7 kB
| import re | |
| import unicodedata | |
| from difflib import SequenceMatcher | |
| def normalize_text(text: str) -> str: | |
| """Normalise un texte (minuscules, sans accents, sans ponctuations superflues).""" | |
| text = unicodedata.normalize('NFKD', text) | |
| text = ''.join(c for c in text if not unicodedata.combining(c)) | |
| text = text.replace('ɔ', 'o').replace('ɛ', 'e').replace('ɖ', 'd') | |
| return re.sub(r'[^a-zA-Z0-9\s]', ' ', text).lower().strip() | |
| # Dictionnaire des équivalences de parenté / surnoms en Fongbé et Français | |
| # Permet de mapper par exemple "nɔ ce" (ma mère en fon) vers le contact enregistré sous "Maman" | |
| RELATIONSHIP_ALIASES = { | |
| # Mère / Maman | |
| "maman": ["maman", "mama", "mere", "no ce", "noxó", "no"], | |
| "no ce": ["maman", "mama", "mere", "no ce"], | |
| "mama": ["maman", "mama", "mere", "no ce"], | |
| "mere": ["maman", "mama", "mere"], | |
| # Père / Papa | |
| "papa": ["papa", "pere", "to ce", "dada", "to"], | |
| "to ce": ["papa", "pere", "to ce"], | |
| "pere": ["papa", "pere", "to ce"], | |
| # Frères et Sœurs | |
| "fofo": ["fofo", "grand frere", "frere", "novi ce"], | |
| "fofo ce": ["fofo", "grand frere", "frere"], | |
| "grand frere": ["fofo", "grand frere", "frere"], | |
| "mon grand frere": ["fofo", "grand frere", "frere"], | |
| "dada": ["dada", "grande soeur", "soeur", "novi ce"], | |
| "dada ce": ["dada", "grande soeur", "soeur"], | |
| "grande soeur": ["dada", "grande soeur", "soeur"], | |
| "novi ce": ["frere", "soeur", "fofo", "dada", "novi"], | |
| "mon frere": ["frere", "fofo", "novi ce"], | |
| "ma soeur": ["soeur", "dada", "novi ce"], | |
| # Conjoints | |
| "asi ce": ["femme", "epouse", "cherie", "madame", "asi"], | |
| "ma femme": ["femme", "epouse", "cherie", "asi ce"], | |
| "asu ce": ["mari", "epoux", "cheri", "asu"], | |
| "mon mari": ["mari", "epoux", "cheri", "asu ce"], | |
| } | |
| class ContactResolver: | |
| """ | |
| Résout un nom oral (en Fongbé ou Français) vers un contact du carnet d'adresses, | |
| en gérant les liens de parenté (Maman, Papa, nɔ ce, tɔ́ ce...), le fuzzy matching | |
| et les homonymes. | |
| """ | |
| def __init__(self, contacts: list[dict]): | |
| self.contacts = contacts | |
| def resolve(self, spoken_name: str, threshold: float = 0.65) -> dict: | |
| norm_spoken = normalize_text(spoken_name) | |
| if not norm_spoken: | |
| return {"status": "NOT_FOUND", "match": None, "candidates": []} | |
| # 1. Recherche d'alias (ex: l'usager dit 'nɔ ce', on cherche 'maman', 'mère', etc.) | |
| target_search_terms = [norm_spoken] | |
| for key, aliases in RELATIONSHIP_ALIASES.items(): | |
| if norm_spoken == key or norm_spoken in aliases: | |
| target_search_terms.extend(aliases) | |
| target_search_terms.append(key) | |
| target_search_terms = list(dict.fromkeys(target_search_terms)) | |
| exact_matches = [] | |
| fuzzy_matches = [] | |
| for c in self.contacts: | |
| norm_name = normalize_text(c["name"]) | |
| # Vérification directe ou via alias | |
| matched = False | |
| for term in target_search_terms: | |
| if term == norm_name: | |
| exact_matches.append((1.0, c)) | |
| matched = True | |
| break | |
| elif term in norm_name.split() or norm_name in term.split(): | |
| exact_matches.append((0.92, c)) | |
| matched = True | |
| break | |
| if not matched: | |
| # Calcul de similarité phonétique / fuzzy Levenshtein | |
| best_sim = max(SequenceMatcher(None, term, norm_name).ratio() for term in target_search_terms) | |
| if best_sim >= threshold: | |
| fuzzy_matches.append((best_sim, c)) | |
| all_matches = sorted(exact_matches + fuzzy_matches, key=lambda x: x[0], reverse=True) | |
| # Déduplication par id de contact | |
| seen_ids = set() | |
| dedup_matches = [] | |
| for score, contact in all_matches: | |
| if contact["id"] not in seen_ids: | |
| seen_ids.add(contact["id"]) | |
| dedup_matches.append((score, contact)) | |
| if not dedup_matches: | |
| return { | |
| "status": "NOT_FOUND", | |
| "spoken_name": spoken_name, | |
| "message_fon": f"Un mɔ « {spoken_name} » ɖò xóxlá towe mɛ ǎ. Nambá tɔn tɛ́ wɛ?", | |
| "message_fr": f"Je n'ai pas trouvé « {spoken_name} » dans tes contacts. Quel est son numéro ?" | |
| } | |
| top_score, top_contact = dedup_matches[0] | |
| close_candidates = [c for score, c in dedup_matches if score >= 0.85] | |
| if len(close_candidates) == 1: | |
| return { | |
| "status": "MATCH_UNIQUE", | |
| "match": top_contact, | |
| "confidence": top_score, | |
| "confirmation_fon": f"A jló na sɛ́ akwɛ ɔ dó {top_contact['name']} ({top_contact['phone']}) à?", | |
| "confirmation_fr": f"Veux-tu envoyer l'argent à {top_contact['name']} ({top_contact['phone']}) ?" | |
| } | |
| return { | |
| "status": "MULTIPLE_MATCHES", | |
| "candidates": close_candidates, | |
| "spoken_name": spoken_name, | |
| "disambiguation_fon": f"Mɛ wè wɛ ɖó nyǐkɔ « {spoken_name} » : " + " kpo ".join(c['name'] for c in close_candidates) + ". Mɛ̌ɖé jló na sɛ́ dó?", | |
| "disambiguation_fr": f"Tu as plusieurs contacts sous « {spoken_name} » : " + ", ".join(c['name'] for c in close_candidates) + ". Lequel choisis-tu ?" | |
| } | |
| # CONTACTS DE DÉMONSTRATION UNIQUEMENT (numéros factices). Ne jamais utiliser en production : passez toujours la vraie liste de contacts de l'utilisateur. | |
| DEFAULT_CONTACTS = [ | |
| {"id": "1", "name": "Maman", "phone": "+229 00 00 00 01"}, | |
| {"id": "2", "name": "Papa", "phone": "+229 00 00 00 02"}, | |
| {"id": "3", "name": "Fofó", "phone": "+229 00 00 00 03"}, | |
| {"id": "4", "name": "Femme", "phone": "+229 00 00 00 04"}, | |
| {"id": "5", "name": "Koffi", "phone": "+229 00 00 00 05"}, | |
| {"id": "6", "name": "Rachid", "phone": "+229 00 00 00 06"}, | |
| {"id": "7", "name": "Mariam", "phone": "+229 00 00 00 07"}, | |
| {"id": "8", "name": "Bio", "phone": "+229 00 00 00 08"}, | |
| {"id": "9", "name": "Sèna", "phone": "+229 00 00 00 09"}, | |
| {"id": "10", "name": "Femi", "phone": "+229 00 00 00 10"}, | |
| {"id": "11", "name": "Ablawa", "phone": "+229 00 00 00 11"}, | |
| {"id": "12", "name": "Sègla", "phone": "+229 00 00 00 12"}, | |
| {"id": "13", "name": "Modeste", "phone": "+229 00 00 00 13"}, | |
| {"id": "14", "name": "Gisèle", "phone": "+229 00 00 00 14"}, | |
| {"id": "15", "name": "Tonton", "phone": "+229 00 00 00 15"}, | |
| {"id": "16", "name": "Tantie", "phone": "+229 00 00 00 16"} | |
| ] | |
| _default_resolver = None | |
| def resolve_contact(query: str, contacts: list[dict] = None) -> dict | None: | |
| """ | |
| Fonction utilitaire pour résoudre un nom de contact ou lien de parenté. | |
| Retourne {'nom': str, 'phone': str, 'match_info': dict} ou None. | |
| """ | |
| global _default_resolver | |
| if contacts is not None: | |
| resolver = ContactResolver(contacts) | |
| else: | |
| if _default_resolver is None: | |
| _default_resolver = ContactResolver(DEFAULT_CONTACTS) | |
| resolver = _default_resolver | |
| res = resolver.resolve(query) | |
| if res["status"] == "MATCH_UNIQUE": | |
| return { | |
| "nom": res["match"]["name"], | |
| "phone": res["match"]["phone"], | |
| "match_info": res | |
| } | |
| elif res["status"] == "MULTIPLE_MATCHES" and res.get("candidates"): | |
| return { | |
| "nom": res["candidates"][0]["name"], | |
| "phone": res["candidates"][0]["phone"], | |
| "match_info": res | |
| } | |
| return None | |
| if __name__ == "__main__": | |
| contacts = [ | |
| {"id": "1", "name": "Maman", "phone": "+229 00 00 00 17"}, | |
| {"id": "2", "name": "Papa", "phone": "+229 00 00 00 18"}, | |
| {"id": "3", "name": "Fofó Mensah", "phone": "+229 00 00 00 19"}, | |
| {"id": "4", "name": "Chérie / Femme", "phone": "+229 00 00 00 20"}, | |
| {"id": "5", "name": "Kofi", "phone": "+229 00 00 00 21"}, | |
| {"id": "6", "name": "Kofi Plombier", "phone": "+229 00 00 00 22"} | |
| ] | |
| resolver = ContactResolver(contacts) | |
| print("1. 'nɔ ce' (ma mère en fon) ->", resolver.resolve("nɔ ce")['match']['name']) | |
| print("2. 'tɔ́ ce' (mon père en fon) ->", resolver.resolve("tɔ́ ce")['match']['name']) | |
| print("3. 'maman' (en français) ->", resolver.resolve("maman")['match']['name']) | |
| print("4. 'asì ce' (mon épouse) ->", resolver.resolve("asì ce")['match']['name']) | |
| print("5. 'fofó' (grand frère) ->", resolver.resolve("fofó")['match']['name']) | |