Spaces:
Running on Zero

File size: 5,605 Bytes
5322cb1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Le numéro de ligne que l'usager nomme : « dama bëgg jël bus bu cinquante et un ».



Lot D1 : à Dakar, on dit surtout le numéro en français (« la cinquante et

un », « bus bu trente-trois »), parfois en wolof (« juróom fukk ak benn »), et

l'ASR l'écrit à sa façon (« sinkant », « trant »). On reconnaît les trois

formes, et les chiffres, seulement juste après un mot qui annonce une ligne

(« bus bu », « ligne », « numéro », « la ») : ailleurs, un nombre reste un

nombre (« Liberté 6 », « Unité 15 »).



Les tables viennent des mêmes fonctions que la voix (tts.speak) : un seul

endroit fixe la façon d'écrire un nombre. La voix, elle, ne change pas.

"""

from __future__ import annotations

import re
import unicodedata
from functools import lru_cache

# Formes de l'ASR (Kiriku, Whisper) pour les mots des nombres, dites en
# français ou en wolof. Seulement après un mot qui annonce une ligne.
FORMES_ASR = {
    # français
    "sinkant": "cinquante", "sinkante": "cinquante", "sinquante": "cinquante", "cinkant": "cinquante",
    "trant": "trente", "trante": "trente", "tront": "trente",
    "karant": "quarante", "karante": "quarante", "carante": "quarante",
    "swasant": "soixante", "swasante": "soixante", "soisante": "soixante", "soixant": "soixante",
    "van": "vingt", "vin": "vingt", "vint": "vingt", "ven": "vingt",
    "sank": "cinq", "senk": "cinq", "sink": "cinq", "sinq": "cinq",
    "katr": "quatre", "katre": "quatre", "kat": "quatre",
    "set": "sept", "sette": "sept", "wit": "huit", "uit": "huit", "nef": "neuf",
    "dis": "dix", "diz": "dix", "onz": "onze", "douz": "douze", "treiz": "treize",
    "katorz": "quatorze", "kenz": "quinze", "seiz": "seize",
    "deu": "deux", "deuz": "deux", "troi": "trois", "trwa": "trois", "sis": "six", "siis": "six",
    "e": "et", "ey": "et", "san": "cent", "sant": "cent", "cents": "cent",
    # wolof
    "jurom": "juroom", "juuroom": "juroom", "fuk": "fukk", "fouk": "fukk", "nar": "naar",
    "nyaar": "naar", "net": "nett", "nyett": "nett", "nent": "neent", "nyeent": "neent",
    "temeer": "teemeer", "teemer": "teemeer", "temer": "teemeer", "fanwer": "fanweer",
    "fanweeer": "fanweer", "ben": "benn",
}
# Mots qui annoncent une ligne. « la » seul est ambigu en wolof : il n'annonce
# une ligne qu'avec un numéro d'au moins 10 (« la cinquante et un »).
ANNONCES = {"ligne", "lignes", "numero", "num"}
ANNONCES_BU = {"bus", "biis", "bis", "car", "kaar"}
MOTS_MAX = 8
NUMERO_MAX = 999


def _normaliser(texte: str) -> str:
    sans = "".join(
        c for c in unicodedata.normalize("NFD", str(texte).lower()) if unicodedata.category(c) != "Mn"
    )
    return re.sub(r"\s+", " ", re.sub(r"[^a-z0-9]+", " ", sans)).strip()


@lru_cache(maxsize=1)
def _tables() -> dict[str, int]:
    """Texte normalisé (« cinquante et un », « juroom fukk ak benn ») -> nombre."""
    try:
        from tts.speak import nombre_en_francais, nombre_en_wolof
    except ImportError:  # pragma: no cover
        from ..tts.speak import nombre_en_francais, nombre_en_wolof

    tables: dict[str, int] = {}
    for n in range(1, NUMERO_MAX + 1):
        francais = _normaliser(nombre_en_francais(n))
        tables.setdefault(francais, n)
        # « cinquante un », « quatre vingt », « deux cent » : sans « et » ni « s ».
        tables.setdefault(francais.replace(" et ", " "), n)
        tables.setdefault(re.sub(r"\b(vingts|cents)\b", lambda m: m.group(1)[:-1], francais), n)
        tables.setdefault(_normaliser(nombre_en_wolof(n)), n)
    return tables


def _numero(mots: list[str]) -> int | None:
    """Le nombre le plus long au début de `mots`, en chiffres ou en lettres."""
    if not mots:
        return None
    chiffres = re.fullmatch(r"(\d{1,3})[a-z]?", mots[0])
    if chiffres:
        n = int(chiffres.group(1))
        return n if 1 <= n <= NUMERO_MAX else None
    corriges = [FORMES_ASR.get(mot, mot) for mot in mots[:MOTS_MAX]]
    tables = _tables()
    for taille in range(len(corriges), 0, -1):
        n = tables.get(" ".join(corriges[:taille]))
        if n is not None:
            return n
    return None


def ligne_nommee(phrase: str | None) -> int | None:
    """Le numéro de ligne nommé dans la phrase, ou None.



    « dama bëgg jël bus bu cinquante et un » -> 51 ; « ligne 7 » -> 7 ;

    « bus bu juróom fukk ak benn » -> 51 ; « bus bu dem Pikine » -> None.

    """
    mots = _normaliser(phrase or "").split()
    for i, mot in enumerate(mots):
        if mot in ANNONCES:
            n = _numero(mots[i + 1:])
        elif mot in ANNONCES_BU and i + 1 < len(mots) and mots[i + 1] == "bu":
            suite = mots[i + 2:]
            # « bus bu Tata numero 5 » : la compagnie peut s'intercaler.
            if suite[:1] and suite[0] in {"tata", "ddd", "aftu"}:
                suite = suite[1:]
            if suite[:1] and suite[0] in ANNONCES:
                suite = suite[1:]
            n = _numero(suite)
        elif mot == "la":
            n = _numero(mots[i + 1:])
            n = n if n is not None and n >= 10 else None
        else:
            continue
        if n is not None:
            return n
    return None


def numeros_du_bus(ligne: object) -> int | None:
    """« Ligne 51 » -> 51, « Ligne 16A » -> 16, « TAF TAF » -> None."""
    trouve = re.fullmatch(r"(?:ligne\s*)?(\d{1,3})\s*[a-z]?", str(ligne or "").strip(), re.IGNORECASE)
    return int(trouve.group(1)) if trouve else None