Spaces:
Running on Zero

guindima-ai / scripts /audit_quartiers_numerotes.py
PythonMindset's picture
Deploiement GuindiMa AI (interface Gradio) (part 2)
3087104 verified
Raw History Blame Contribute Delete
14 kB
"""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()