Spaces:
Running on Zero

File size: 14,041 Bytes
3087104
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
"""Audit des quartiers numérotés (lot Q1) : lesquels existent dans nos données, lesquels manquent.



À Dakar, beaucoup de quartiers portent un numéro, toujours dit en français

(Sacré-Cœur 3, Liberté 6, HLM 5, Unité 15…). Ce script cherche chaque numéro

dans nos lieux et nos arrêts, sans réseau, et écrit

data/audit/quartiers_numerotes_manquants.csv. Il ne modifie aucune donnée.



Sources, de la plus sûre à la moins sûre :

1. les arrêts du réseau tel que le moteur le charge (itinéraires Tata et

   Dem Dikk, corrections comprises) : position « mesurée » si sa confiance est

   « bonne », sinon « estimée » ;

2. data/arrets_geo.csv : le nom de l'arrêt, ou la colonne « quartier » (le

   quartier où se trouve un arrêt) ;

3. data/sources/osm_bus_dakar/arrets_osm.csv : arrêts OpenStreetMap, position

   « mesurée » (coordonnées OSM) ;

4. data/corrections/corrections_geo_ddd_proposees.csv : l'adresse Nominatim

   d'un arrêt Dem Dikk (colonne detail, « estimée ») ;

   data/reference/lignes_reference.csv : la liste officielle des arrêts de

   chaque ligne (nom seul : position « absente ») ;

5. data/lieux_geo.csv : point de quartier précalculé, toujours « estimée »

   (ce n'est pas un arrêt mesuré) ;

6. data/corrections/lieux_quartiers_numerotes.csv (lot Q2) : quartiers

   confirmés par deux sources, position « mesurée ».



Usage (PowerShell) :

    $env:PYTHONIOENCODING='utf-8'

    .\\.venv\\Scripts\\python.exe scripts\\audit_quartiers_numerotes.py

"""

from __future__ import annotations

import contextlib
import csv
import io
import re
import sys
import unicodedata
from collections import defaultdict
from pathlib import Path

RACINE = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(RACINE / "src"))
SORTIE = RACINE / "data" / "audit" / "quartiers_numerotes_manquants.csv"

ROMAINS = {"i": 1, "ii": 2, "iii": 3, "iv": 4, "v": 5, "vi": 6, "vii": 7, "viii": 8, "ix": 9, "x": 10}
MOTS = {"un": 1, "deux": 2, "trois": 3, "quatre": 4, "cinq": 5, "six": 6}

# (famille, motif du nom normalisé, numéros attendus, gabarit du nom attendu)
FAMILLES = [
    ("Sacré-Cœur", r"\bsacre coeur", range(1, 4), "Sacré-Cœur {}"),
    ("Liberté", r"\b(?:sicap )?liberte", range(1, 7), "Liberté {}"),
    ("HLM", r"\bhlm", range(1, 7), "HLM {}"),
    # « Unité 15 », « Unités 09 10 15 », « U23 », « U.25 » (OSM, page Dem Dikk).
    ("Parcelles Assainies (unités)", r"\b(?:unites?|u(?= ?\d))", range(1, 27), "Unité {}"),
    ("Dieuppeul", r"\bdieuppeul", range(1, 5), "Dieuppeul {}"),
    ("Cambérène", r"\bcamberene", range(1, 3), "Cambérène {}"),
    ("Sicap Amitié", r"\b(?:sicap )?amitie", range(1, 4), "Amitié {}"),
    ("Hamo (Guédiawaye)", r"\bhamo", range(1, 7), "Hamo {}"),
    ("Gorom", r"\bgorom", range(1, 3), "Gorom {}"),
    ("Jaxaay", r"\bjaxaay", range(1, 3), "Jaxaay {}"),
]
# Quartiers sans numéro cités par Cheikh : simple contrôle de présence.
SANS_NUMERO = [
    ("HLM", r"\bhlm grand yoff\b", "HLM Grand Yoff"),
    ("HLM", r"\bhlm grand medine\b", "HLM Grand Médine"),
    ("Grand Yoff", r"\bgrand yoff\b", "Grand Yoff"),
    ("Castors", r"\bcastors?\b", "Castors"),
    ("Sicap", r"\bbaobabs?\b", "Sicap Baobabs"),
    ("Sicap", r"\bmermoz\b", "Sicap Mermoz"),
    ("Cité Keur Gorgui", r"\bkeur gorgui\b", "Cité Keur Gorgui"),
    ("Grand Dakar", r"\bgrand dakar\b", "Grand Dakar"),
    ("Sicap", r"\bsicap karack\b", "Sicap Karack"),
    ("Patte d'Oie", r"\bpatte d ?oie\b", "Patte d'Oie"),
]
RANG_POSITION = {"mesurée": 0, "estimée": 1, "absente": 2}
# Pour la priorité : les arrêts du quartier, numérotés ou non (« Marché HLM »,
# « Derklé », « Parcelles Assainies »), disent combien de lignes le desservent.
QUARTIER_DE_LA_FAMILLE = {
    "Parcelles Assainies (unités)": r"\bparcelles\b|\bunites?\b",
    "Dieuppeul": r"\bdieuppeul\b|\bderkle\b",
}


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


def numeros_apres(nom_norm: str, motif: str) -> set[int]:
    """Les numéros qui suivent le nom de famille : « unites 09 10 15 », « hamo v/vi »."""
    trouves: set[int] = set()
    for depart in re.finditer(motif, nom_norm):
        suite = nom_norm[depart.end():].replace("/", " ").split()
        for mot in suite:
            mot = mot.strip()
            if mot in ("et", "a"):
                continue
            if mot.isdigit():
                trouves.add(int(mot))
            elif mot in ROMAINS:
                trouves.add(ROMAINS[mot])
            elif mot in MOTS:
                trouves.add(MOTS[mot])
            else:
                break
    return trouves


def charger_sources() -> list[dict]:
    """Toutes les mentions (nom, fichier, position) de nos données."""
    from routing import adapter as moteur

    tests = RACINE / "tests"
    sys.path.insert(0, str(tests))
    import test_trajets  # noqa: E402  (le matcher hors ligne des tests, sans réseau)

    with contextlib.redirect_stdout(io.StringIO()):
        matcher = test_trajets._matcher_hors_ligne()
        moteur.chercher_v2(matcher, "Ouakam", "Palais")
    reseau = moteur._NETWORK

    tata_ddd = {r["arret"] for r in csv.DictReader(open(RACINE / "data" / "itineraires_dakar.csv", encoding="utf-8"))}
    officiel = {
        r["arret"]
        for r in csv.DictReader(open(RACINE / "data" / "corrections" / "corrections_geo_ddd_proposees.csv", encoding="utf-8"))
    }
    lignes_par_arret: dict[str, set] = defaultdict(set)
    for cle, ligne in reseau.lines.items():
        for arret in ligne.stops:
            lignes_par_arret[arret].add(cle)

    sources: list[dict] = []
    for arret in reseau.stop_names:
        if reseau.stop_confidence.get(arret) == "bonne":
            position = "mesurée"
        else:
            position = "estimée" if reseau.coords(arret) else "absente"
        fichier = (
            "data/itineraires_dakar.csv" if arret in tata_ddd
            else "data/corrections/corrections_geo_ddd_proposees.csv" if arret in officiel
            else "data/corrections (itinéraires revus)"
        )
        sources.append({"nom": arret, "fichier": fichier, "position": position,
                        "lignes": lignes_par_arret.get(arret, set())})
    for r in csv.DictReader(open(RACINE / "data" / "arrets_geo.csv", encoding="utf-8")):
        position = "mesurée" if r["confiance"] == "bonne" else "estimée"
        sources.append({"nom": r["arret"], "fichier": "data/arrets_geo.csv", "position": position,
                        "lignes": lignes_par_arret.get(r["arret"], set())})
        if r.get("quartier"):
            sources.append({"nom": r["quartier"], "fichier": "data/arrets_geo.csv (colonne quartier)",
                            "position": position, "via": r["arret"],
                            "lignes": lignes_par_arret.get(r["arret"], set())})
    for r in csv.DictReader(open(RACINE / "data" / "sources" / "osm_bus_dakar" / "arrets_osm.csv", encoding="utf-8")):
        if (r.get("name") or "").strip():
            sources.append({"nom": r["name"], "fichier": "data/sources/osm_bus_dakar/arrets_osm.csv",
                            "position": "mesurée" if r.get("lat") else "absente", "lignes": set()})
    chemin_ddd = RACINE / "data" / "corrections" / "corrections_geo_ddd_proposees.csv"
    for r in csv.DictReader(open(chemin_ddd, encoding="utf-8")):
        if (r.get("source") or "") == "nominatim" and r.get("detail"):
            # « Marché HLM 5, Rue HLM-173, HLM 5, Commune de HLM… » : le quartier de l'arrêt.
            for morceau in r["detail"].split(","):
                sources.append({"nom": morceau.strip(), "fichier": f"{chemin_ddd.relative_to(RACINE).as_posix()} (adresse Nominatim)",
                                "position": "estimée", "via": r["arret"], "lignes": set()})
    # Listes officielles (« Terminus Cambérène ; Cambérène 2 ; Cambérène 1 ; … ;
    # U.25 ; U.26 ») : le nom existe, sans position.
    chemin_ref = RACINE / "data" / "reference" / "lignes_reference.csv"
    if chemin_ref.exists():
        for r in csv.DictReader(open(chemin_ref, encoding="utf-8-sig")):
            for morceau in (r.get("arrets_principaux") or "").split(";"):
                if morceau.strip():
                    sources.append({"nom": morceau.strip(),
                                    "fichier": "data/reference/lignes_reference.csv (liste officielle, nom seul)",
                                    "position": "absente", "lignes": set()})
    chemin_q2 = RACINE / "data" / "corrections" / "lieux_quartiers_numerotes.csv"
    if chemin_q2.exists():
        for r in csv.DictReader(open(chemin_q2, encoding="utf-8-sig")):
            mesuree = (r.get("position") or "").startswith("mesurée") and r.get("lat")
            sources.append({"nom": r["lieu"], "fichier": "data/corrections/lieux_quartiers_numerotes.csv",
                            "position": "mesurée" if mesuree else "estimée", "lignes": set()})
    for r in csv.DictReader(open(RACINE / "data" / "lieux_geo.csv", encoding="utf-8")):
        sources.append({"nom": r["lieu"], "fichier": "data/lieux_geo.csv",
                        "position": "estimée" if r.get("lat") else "absente", "lignes": set()})
    for source in sources:
        source["norm"] = normaliser(source["nom"])
    return sources


def mentions_collecte() -> list[str]:
    """Les transcriptions des vocaux collectés (lecture seule), pour la priorité."""
    chemin = RACINE / "data" / "collecte" / "metadata.csv"
    if not chemin.exists():
        return []
    return [
        normaliser(" ".join([r.get("transcription_propre") or "", r.get("transcription") or ""]))
        for r in csv.DictReader(open(chemin, encoding="utf-8"))
    ]


def ligne_csv(famille, numero, attendu, trouves) -> dict:
    if not trouves:
        return {"famille": famille, "numero": numero, "nom_attendu": attendu, "present": "non",
                "nom_dans_nos_donnees": "", "fichier": "", "position": "absente"}
    trouves = sorted(trouves, key=lambda s: (RANG_POSITION[s["position"]], "quartier" in s["fichier"], s["nom"]))
    meilleur = trouves[0]
    noms = []
    for s in trouves:
        nom = f"{s['nom']} (quartier de l'arrêt {s['via']})" if s.get("via") else s["nom"]
        if nom not in noms:
            noms.append(nom)
    return {"famille": famille, "numero": numero, "nom_attendu": attendu, "present": "oui",
            "nom_dans_nos_donnees": " ; ".join(noms[:4]), "fichier": meilleur["fichier"],
            "position": meilleur["position"]}


def main() -> None:
    sources = charger_sources()
    collecte = mentions_collecte()
    rangees, manquants = [], []
    for famille, motif, numeros, gabarit in FAMILLES:
        par_numero: dict[int, list] = defaultdict(list)
        quartier = QUARTIER_DE_LA_FAMILLE.get(famille, motif)
        lignes_famille: set = set()
        for s in sources:
            for n in numeros_apres(s["norm"], motif):
                par_numero[n].append(s)
            if re.search(quartier, s["norm"]):
                lignes_famille |= s["lignes"]
        for n in numeros:
            attendu = gabarit.format(n)
            rangee = ligne_csv(famille, n, attendu, par_numero.get(n, []))
            rangees.append(rangee)
            # À ajouter : absent, ou présent par son nom seul (aucune position).
            if rangee["present"] == "non" or rangee["position"] == "absente":
                dit = sum(bool(re.search(motif + rf"\s*0?{n}\b", t)) for t in collecte)
                etat = "absent" if rangee["present"] == "non" else "nom seul, sans position"
                manquants.append((famille, attendu, dit, len(lignes_famille), etat))
    for famille, motif, attendu in SANS_NUMERO:
        trouves = [s for s in sources if re.search(motif, s["norm"])]
        rangee = ligne_csv(famille, "-", attendu, trouves)
        rangees.append(rangee)
        if rangee["present"] == "non":
            dit = sum(bool(re.search(motif, t)) for t in collecte)
            manquants.append((famille, attendu, dit, 0, "absent"))

    SORTIE.parent.mkdir(parents=True, exist_ok=True)
    colonnes = ["famille", "numero", "nom_attendu", "present", "nom_dans_nos_donnees", "fichier", "position"]
    with open(SORTIE, "w", encoding="utf-8", newline="") as fichier:
        ecrivain = csv.DictWriter(fichier, fieldnames=colonnes)
        ecrivain.writeheader()
        ecrivain.writerows(rangees)

    print(f"Écrit : {SORTIE.relative_to(RACINE)} ({len(rangees)} lignes)\n")
    print("Par famille : présents / attendus (dont position mesurée)")
    familles = list(dict.fromkeys(r["famille"] for r in rangees))
    for famille in familles:
        lignes = [r for r in rangees if r["famille"] == famille]
        presents = [r for r in lignes if r["present"] == "oui"]
        mesures = [r for r in presents if r["position"] == "mesurée"]
        absents = [str(r["numero"]) for r in lignes if r["present"] == "non"]
        print(f"  {famille:32} {len(presents):2}/{len(lignes):2} (mesurée {len(mesures)})"
              + (f"  manquent : {', '.join(absents)}" if absents else ""))
    print(f"\nÀ ajouter : {len(manquants)} (absents, ou nom seul sans position)")
    print("Priorité : mentions dans les vocaux collectés, puis lignes qui desservent le quartier")
    for famille, attendu, dit, lignes, etat in sorted(manquants, key=lambda m: (-m[2], -m[3], m[1]))[:15]:
        print(f"  {attendu:24} vocaux : {dit:2}  lignes du quartier : {lignes:3}  ({etat})")


if __name__ == "__main__":
    main()