Cheikh Niang commited on
Commit
5c385ae
·
verified ·
1 Parent(s): 716b3ec

Deploiement GuindiMa AI (interface Gradio)

Browse files
Files changed (3) hide show
  1. app.py +31 -5
  2. data/sources/geolocaliser_arrets.py +491 -491
  3. src/matching/geo.py +394 -275
app.py CHANGED
@@ -49,6 +49,7 @@ from intent.extract_intent import ( # noqa: E402
49
  extract_local,
50
  )
51
  from matching.compagnie import message_autre_compagnie # noqa: E402
 
52
  from matching.lieux import AVANT_NUMERO, FAUX_AMIS, joli, sans_accents # noqa: E402
53
  from matching.stops_matcher import StopsMatcher # noqa: E402
54
  from tts.speak import ( # noqa: E402
@@ -427,25 +428,38 @@ def _quartiers_arrets() -> dict[str, str]:
427
 
428
  Lecture seule de `data/arrets_geo.csv` : on indexe chaque arrêt sous son nom
429
  brut et sous sa forme affichée, pour retrouver le quartier depuis les arrêts
430
- déjà mis en forme du trajet. Les arrêts « douteuse » ou « introuvable » sont
431
- ignorés.
 
432
  """
433
  chemin = ARRETS_GEO
434
  if not chemin.exists():
435
  return {}
 
436
  table: dict[str, str] = {}
437
  with open(chemin, newline="", encoding="utf-8") as f:
438
  for rangee in csv.DictReader(f):
439
  if rangee.get("confiance", "").strip().lower() not in CONFIANCES_QUARTIER:
440
  continue
441
- quartier = _quartier_court(rangee.get("quartier") or rangee.get("commune") or "")
442
  arret = (rangee.get("arret") or "").strip()
443
- if quartier and arret:
 
 
 
444
  table.setdefault(arret, quartier)
445
  table.setdefault(joli(arret), quartier)
446
  return table
447
 
448
 
 
 
 
 
 
 
 
 
 
449
  def _source_trajet(match: dict) -> str:
450
  """L'origine de l'itinéraire, sous la liste des arrêts.
451
 
@@ -518,18 +532,30 @@ def _chiffres_du_nom(nom: str) -> str:
518
  # garde à part, à rappeler en petit dans le bloc des arrêts.
519
  _NOTE_RETOUR = re.compile(r"\s*\(\s*(?:au\s+)?retour(?:\s+par)?\s+rue\s+(\d+)\s*\)", re.I)
520
 
 
 
 
 
 
 
 
 
 
 
 
521
 
522
  def _nom_arret(nom: str) -> tuple[str, str]:
523
  """Le nom d'arrêt affiché et, s'il y a lieu, la note « au retour ».
524
 
525
  « Rue 25 (Retour Par Rue 37) » → (« Rue 25 », « au retour : par la rue 37 »).
 
526
  """
527
  propre, note = nom, ""
528
  trouve = _NOTE_RETOUR.search(nom)
529
  if trouve:
530
  note = f"au retour : par la rue {trouve.group(1)}"
531
  propre = f"{nom[:trouve.start()]} {nom[trouve.end():]}".strip()
532
- return _chiffres_du_nom(propre), note
533
 
534
 
535
  def _nom_astuce(arret: str) -> str:
 
49
  extract_local,
50
  )
51
  from matching.compagnie import message_autre_compagnie # noqa: E402
52
+ from matching.geo import arrets_non_fiables # noqa: E402
53
  from matching.lieux import AVANT_NUMERO, FAUX_AMIS, joli, sans_accents # noqa: E402
54
  from matching.stops_matcher import StopsMatcher # noqa: E402
55
  from tts.speak import ( # noqa: E402
 
428
 
429
  Lecture seule de `data/arrets_geo.csv` : on indexe chaque arrêt sous son nom
430
  brut et sous sa forme affichée, pour retrouver le quartier depuis les arrêts
431
+ déjà mis en forme du trajet. Les arrêts « douteuse » ou « introuvable », les
432
+ rues numérotées et les homonymes isolés sur leur ligne (mêmes jugements que
433
+ la recherche de ligne) sont ignorés : pas de quartier trompeur affiché.
434
  """
435
  chemin = ARRETS_GEO
436
  if not chemin.exists():
437
  return {}
438
+ ignores = _arrets_sans_quartier()
439
  table: dict[str, str] = {}
440
  with open(chemin, newline="", encoding="utf-8") as f:
441
  for rangee in csv.DictReader(f):
442
  if rangee.get("confiance", "").strip().lower() not in CONFIANCES_QUARTIER:
443
  continue
 
444
  arret = (rangee.get("arret") or "").strip()
445
+ if not arret or arret in ignores:
446
+ continue
447
+ quartier = _quartier_court(rangee.get("quartier") or rangee.get("commune") or "")
448
+ if quartier:
449
  table.setdefault(arret, quartier)
450
  table.setdefault(joli(arret), quartier)
451
  return table
452
 
453
 
454
+ @lru_cache(maxsize=1)
455
+ def _arrets_sans_quartier() -> frozenset[str]:
456
+ """Les arrêts à position non fiable, jugés comme dans la recherche de ligne."""
457
+ try:
458
+ return frozenset(arrets_non_fiables(ARRETS_GEO))
459
+ except Exception:
460
+ return frozenset()
461
+
462
+
463
  def _source_trajet(match: dict) -> str:
464
  """L'origine de l'itinéraire, sous la liste des arrêts.
465
 
 
532
  # garde à part, à rappeler en petit dans le bloc des arrêts.
533
  _NOTE_RETOUR = re.compile(r"\s*\(\s*(?:au\s+)?retour(?:\s+par)?\s+rue\s+(\d+)\s*\)", re.I)
534
 
535
+ # Parenthèses qui font partie du NOM (« Rue Abebebikila (Rue 11 Prolongée) ») :
536
+ # rendues avec un tiret, pour ne pas ressembler au quartier affiché entre
537
+ # parenthèses juste après.
538
+ _PARENTHESES_NOM = re.compile(r"\s*\(([^)]*)\)\s*")
539
+
540
+
541
+ def _sans_parentheses_quartier(nom: str) -> str:
542
+ """« Rue Abebebikila (Rue 11 Prolongée) » → « Rue Abebebikila – Rue 11 Prolongée »."""
543
+ transforme = _PARENTHESES_NOM.sub(r" – \1 ", nom)
544
+ return re.sub(r"\s+", " ", transforme).strip()
545
+
546
 
547
  def _nom_arret(nom: str) -> tuple[str, str]:
548
  """Le nom d'arrêt affiché et, s'il y a lieu, la note « au retour ».
549
 
550
  « Rue 25 (Retour Par Rue 37) » → (« Rue 25 », « au retour : par la rue 37 »).
551
+ Les parenthèses qui restent font partie du nom et sont rendues avec un tiret.
552
  """
553
  propre, note = nom, ""
554
  trouve = _NOTE_RETOUR.search(nom)
555
  if trouve:
556
  note = f"au retour : par la rue {trouve.group(1)}"
557
  propre = f"{nom[:trouve.start()]} {nom[trouve.end():]}".strip()
558
+ return _sans_parentheses_quartier(_chiffres_du_nom(propre)), note
559
 
560
 
561
  def _nom_astuce(arret: str) -> str:
data/sources/geolocaliser_arrets.py CHANGED
@@ -1,491 +1,491 @@
1
- """Géolocalise les arrêts du réseau avec Nominatim (OpenStreetMap).
2
-
3
- Pour chaque arrêt unique de data/itineraires_dakar.csv, on interroge Nominatim,
4
- on garde latitude, longitude, quartier et commune, puis on écrit
5
- data/arrets_geo.csv. Aucun CSV existant ni la recherche de ligne n'est modifié.
6
-
7
- Robustesse de la recherche :
8
- - plusieurs requêtes avant d'abandonner un arrêt : nom nettoyé des préfixes
9
- (« Giratoire de Liberté VI » -> « Liberté 6 »), chiffres romains convertis,
10
- puis commune de voisinage (« Pikine », « Guédiawaye », « Rufisque ») quand
11
- les arrêts voisins de la ligne y sont ;
12
- - les arrêts toujours introuvables reçoivent une position estimée (milieu de
13
- leurs deux voisins connus sur la même ligne, si ces voisins sont à moins de
14
- 3 km), confiance « estimee » ; sinon l'arrêt reste « introuvable » ;
15
- - un arrêt n'est « douteuse » que s'il fait un détour anormal entre ses deux
16
- voisins : d(précédent, arrêt) + d(arrêt, suivant) > 2·d(précédent, suivant) + 2 km ;
17
- - un géocodage inverse (reverse, zoom 14) donne un quartier/commune homogène
18
- pour chaque position finale.
19
-
20
- Politique d'usage Nominatim : au plus une requête par seconde, User-Agent
21
- explicite, et cache local (data/sources/cache_nominatim.json) : une requête déjà
22
- faite n'est jamais refaite.
23
-
24
- Usage :
25
- python data/sources/geolocaliser_arrets.py # collecte + rapport
26
- python data/sources/geolocaliser_arrets.py --limite 10 # essai sur 10 arrêts
27
- """
28
-
29
- from __future__ import annotations
30
-
31
- import argparse
32
- import csv
33
- import json
34
- import math
35
- import re
36
- import sys
37
- import time
38
- import unicodedata
39
- from pathlib import Path
40
-
41
- import requests
42
-
43
- RACINE = Path(__file__).resolve().parents[2]
44
- DATA = RACINE / "data"
45
- ITINERAIRES = DATA / "itineraires_dakar.csv"
46
- SORTIE = DATA / "arrets_geo.csv"
47
- CACHE = Path(__file__).resolve().parent / "cache_nominatim.json"
48
-
49
- GEOCODE = "https://nominatim.openstreetmap.org/search"
50
- REVERSE = "https://nominatim.openstreetmap.org/reverse"
51
- USER_AGENT = "GuindiMa-AI/1.0 (cheikhniang159@gmail.com)"
52
- DELAI_SECONDES = 1.0
53
- TIMEOUT = 30
54
- ZOOM_REVERSE = 14
55
- RAYON_DETOUR = 2000.0 # marge du contrôle « détour anormal », en mètres
56
- DISTANCE_VOISINS_MAX = 3000.0 # écart max entre les deux voisins connus, pour estimer
57
-
58
- CHAMPS_QUARTIER = ("neighbourhood", "quarter", "suburb")
59
- CHAMPS_COMMUNE = ("city_district", "city", "municipality")
60
-
61
- # Communes de la banlieue : si un voisin de la ligne y est, on retente avec cette
62
- # commune au lieu de « Dakar ».
63
- COMMUNES_BANLIEUE = {"pikine": "Pikine", "guediawaye": "Guédiawaye", "rufisque": "Rufisque"}
64
-
65
- # Préfixes d'arrêt sans valeur pour Nominatim.
66
- PREFIXES = re.compile(
67
- r"^\s*(?:terminus|arr[êe]t|giratoire(?:\s+de)?|rond[-\s]?point(?:\s+de)?|"
68
- r"croisement(?:\s+de)?|station|gare(?:\s+(?:de|routi[èe]re))?)\s+",
69
- re.I,
70
- )
71
-
72
- ROMAINS = {
73
- "i": 1, "ii": 2, "iii": 3, "iv": 4, "v": 5, "vi": 6,
74
- "vii": 7, "viii": 8, "ix": 9, "x": 10, "xi": 11, "xii": 12,
75
- }
76
-
77
-
78
- # --------------------------------------------------------------------------- #
79
- # Nettoyage des noms
80
- # --------------------------------------------------------------------------- #
81
-
82
-
83
- def sans_accents(texte: str) -> str:
84
- normalise = unicodedata.normalize("NFD", str(texte).lower().replace("œ", "oe"))
85
- return "".join(c for c in normalise if unicodedata.category(c) != "Mn")
86
-
87
-
88
- def nettoyer_prefixes(nom: str) -> str:
89
- """Retire les préfixes d'arrêt (« Terminus Gare de X » -> « X »)."""
90
- precedent = None
91
- while precedent != nom:
92
- precedent = nom
93
- nom = PREFIXES.sub("", nom).strip()
94
- return nom
95
-
96
-
97
- def remplacer_romains(nom: str) -> str:
98
- """« Hamo VI » -> « Hamo 6 ». Ne touche qu'aux nombres romains entiers."""
99
- return re.sub(
100
- r"\b[IVXLCDMivxlcdm]{1,4}\b",
101
- lambda m: str(ROMAINS[m.group(0).lower()]) if m.group(0).lower() in ROMAINS else m.group(0),
102
- nom,
103
- )
104
-
105
-
106
- def formes(arret: str) -> list[str]:
107
- """Requêtes possibles pour un arrêt, de la plus fidèle à la plus nettoyée."""
108
- resultat: list[str] = []
109
-
110
- def ajouter(nom: str) -> None:
111
- nom = nom.strip()
112
- if nom and nom not in resultat:
113
- resultat.append(nom)
114
-
115
- ajouter(arret)
116
- ajouter(nettoyer_prefixes(arret))
117
- ajouter(remplacer_romains(arret))
118
- ajouter(remplacer_romains(nettoyer_prefixes(arret)))
119
- return resultat
120
-
121
-
122
- # --------------------------------------------------------------------------- #
123
- # Nominatim
124
- # --------------------------------------------------------------------------- #
125
-
126
-
127
- def _champs(objet: dict) -> dict:
128
- """Latitude, longitude, quartier, commune d'un objet Nominatim."""
129
- adresse = objet.get("address") or {}
130
- quartier = next((adresse[c] for c in CHAMPS_QUARTIER if adresse.get(c)), "")
131
- commune = next((adresse[c] for c in CHAMPS_COMMUNE if adresse.get(c)), "")
132
- return {
133
- "lat": float(objet["lat"]),
134
- "lon": float(objet["lon"]),
135
- "quartier": quartier,
136
- "commune": commune,
137
- "pays": str(adresse.get("country_code") or "").lower(),
138
- "display_name": objet.get("display_name", ""),
139
- }
140
-
141
-
142
- def _resultat_geocode(brut) -> dict:
143
- return {"trouve": True, **_champs(brut[0])} if brut else {"trouve": False}
144
-
145
-
146
- def _resultat_reverse(brut) -> dict:
147
- if not brut or brut.get("error"):
148
- return {"trouve": False}
149
- return {"trouve": True, **_champs(brut)}
150
-
151
-
152
- class Nominatim:
153
- """Client poli : cache d'abord, puis au plus une requête réseau par seconde."""
154
-
155
- def __init__(self) -> None:
156
- self.cache = charger_cache()
157
- self.session = requests.Session()
158
- self.derniere = 0.0
159
- self.requetes = 0
160
-
161
- def _sauver(self) -> None:
162
- CACHE.write_text(json.dumps(self.cache, ensure_ascii=False, indent=1, sort_keys=True), encoding="utf-8")
163
-
164
- def _attendre(self) -> None:
165
- attente = DELAI_SECONDES - (time.monotonic() - self.derniere)
166
- if attente > 0:
167
- time.sleep(attente)
168
-
169
- def _appeler(self, url: str, params: dict, cle: str, convertir):
170
- """Cache d'abord, puis une requête (1/s). None si échec réseau (non mis en cache)."""
171
- if cle in self.cache:
172
- return self.cache[cle]
173
- self._attendre()
174
- try:
175
- reponse = self.session.get(url, params=params, headers={"User-Agent": USER_AGENT}, timeout=TIMEOUT)
176
- reponse.raise_for_status()
177
- donnees = reponse.json()
178
- except Exception as exc:
179
- self.derniere = time.monotonic()
180
- print(f" [échec réseau] {cle} : {type(exc).__name__} : {exc}", flush=True)
181
- return None
182
- self.derniere = time.monotonic()
183
- self.requetes += 1
184
- self.cache[cle] = convertir(donnees)
185
- self._sauver()
186
- return self.cache[cle]
187
-
188
- def geocode(self, requete: str) -> dict | None:
189
- params = {"q": requete, "format": "jsonv2", "addressdetails": "1", "limit": "1"}
190
- return self._appeler(GEOCODE, params, f"fwd|{requete}", _resultat_geocode)
191
-
192
- def reverse(self, lat: float, lon: float) -> dict | None:
193
- params = {"lat": f"{lat}", "lon": f"{lon}", "format": "jsonv2", "zoom": str(ZOOM_REVERSE), "addressdetails": "1"}
194
- return self._appeler(REVERSE, params, f"rev|{lat:.5f},{lon:.5f}", _resultat_reverse)
195
-
196
-
197
- def distance_metres(a: tuple[float, float], b: tuple[float, float]) -> float:
198
- rayon = 6_371_000.0
199
- p1, p2 = math.radians(a[0]), math.radians(b[0])
200
- dp = math.radians(b[0] - a[0])
201
- dl = math.radians(b[1] - a[1])
202
- h = math.sin(dp / 2) ** 2 + math.cos(p1) * math.cos(p2) * math.sin(dl / 2) ** 2
203
- return 2 * rayon * math.asin(math.sqrt(h))
204
-
205
-
206
- # --------------------------------------------------------------------------- #
207
- # Données
208
- # --------------------------------------------------------------------------- #
209
-
210
-
211
- def lire_itineraires() -> list[dict]:
212
- with open(ITINERAIRES, newline="", encoding="utf-8") as f:
213
- return list(csv.DictReader(f))
214
-
215
-
216
- def arrets_uniques(rangees: list[dict]) -> list[str]:
217
- vus: dict[str, None] = {}
218
- for rangee in rangees:
219
- vus.setdefault(rangee["arret"], None)
220
- return list(vus)
221
-
222
-
223
- def lignes_ordonnees(rangees: list[dict]) -> dict[tuple[str, str], list[str]]:
224
- par_ligne: dict[tuple[str, str], list[str]] = {}
225
- for rangee in rangees:
226
- par_ligne.setdefault((rangee["compagnie"], rangee["ligne"]), []).append(rangee["arret"])
227
- return par_ligne
228
-
229
-
230
- def charger_cache() -> dict:
231
- """Charge le cache ; convertit l'ancien format (clé = arrêt) au nouveau."""
232
- if not CACHE.exists():
233
- return {}
234
- donnees = json.loads(CACHE.read_text(encoding="utf-8"))
235
- migre = {}
236
- for cle, valeur in donnees.items():
237
- if cle.startswith(("fwd|", "rev|")):
238
- migre[cle] = valeur
239
- else: # la requête de base était « <arrêt>, Dakar, Sénégal »
240
- migre[f"fwd|{cle}, Dakar, Sénégal"] = valeur
241
- return migre
242
-
243
-
244
- # --------------------------------------------------------------------------- #
245
- # Collecte
246
- # --------------------------------------------------------------------------- #
247
-
248
-
249
- def geocoder_arret(arret: str, client: Nominatim, variantes: list[str]) -> dict | None:
250
- """Première requête qui trouve l'arrêt ; None si échec réseau ou aucune trouvaille."""
251
- for requete in variantes:
252
- info = client.geocode(requete)
253
- if info is None: # échec réseau : on n'abandonne pas définitivement, on retente plus tard
254
- return None
255
- if info.get("trouve"):
256
- return {**info, "_requete": requete}
257
- return None
258
-
259
-
260
- def communes_voisines(arret: str, par_ligne: dict, trouves: dict[str, dict]) -> list[str]:
261
- """Communes de banlieue où se trouvent les arrêts voisins de la ligne."""
262
- cibles: list[str] = []
263
- for arrets in par_ligne.values():
264
- if arret not in arrets:
265
- continue
266
- index = arrets.index(arret)
267
- for voisin in (index - 1, index + 1):
268
- if not 0 <= voisin < len(arrets):
269
- continue
270
- info = trouves.get(arrets[voisin])
271
- if not info:
272
- continue
273
- texte = sans_accents(f"{info.get('display_name', '')} {info.get('commune', '')}")
274
- for cle, nom in COMMUNES_BANLIEUE.items():
275
- if re.search(rf"\b{cle}\b", texte) and nom not in cibles:
276
- cibles.append(nom)
277
- return cibles
278
-
279
-
280
- def interpoler(
281
- par_ligne: dict[tuple[str, str], list[str]], positions: dict[str, tuple[float, float]]
282
- ) -> dict[str, list[tuple[float, float]]]:
283
- """Estimations : milieu des deux voisins connus, s'ils sont à moins de 3 km.
284
-
285
- On ne devine une position qu'entre deux arrêts géocodés proches : au-delà de
286
- DISTANCE_VOISINS_MAX, le milieu n'a plus de sens (il tomberait au hasard
287
- entre deux points éloignés) et l'arrêt reste « introuvable ».
288
- """
289
- estimations: dict[str, list[tuple[float, float]]] = {}
290
- for arrets in par_ligne.values():
291
- connus = [i for i, a in enumerate(arrets) if a in positions]
292
- for i, arret in enumerate(arrets):
293
- if arret in positions:
294
- continue
295
- avant = max((j for j in connus if j < i), default=None)
296
- apres = min((j for j in connus if j > i), default=None)
297
- if avant is None or apres is None:
298
- continue
299
- pa, pb = positions[arrets[avant]], positions[arrets[apres]]
300
- if distance_metres(pa, pb) > DISTANCE_VOISINS_MAX:
301
- continue
302
- estimations.setdefault(arret, []).append(((pa[0] + pb[0]) / 2, (pa[1] + pb[1]) / 2))
303
- return estimations
304
-
305
-
306
- def detours_anormaux(
307
- par_ligne: dict[tuple[str, str], list[str]], positions: dict[str, tuple[float, float]]
308
- ) -> dict[str, str]:
309
- """Arrêts dont d(précédent, arrêt) + d(arrêt, suivant) > 2·d(précédent, suivant) + 2 km."""
310
- douteux: dict[str, str] = {}
311
- for (compagnie, ligne), arrets in par_ligne.items():
312
- for i in range(1, len(arrets) - 1):
313
- avant, arret, apres = arrets[i - 1], arrets[i], arrets[i + 1]
314
- if not all(a in positions for a in (avant, arret, apres)):
315
- continue
316
- d1 = distance_metres(positions[avant], positions[arret])
317
- d2 = distance_metres(positions[arret], positions[apres])
318
- d0 = distance_metres(positions[avant], positions[apres])
319
- if d1 + d2 > 2 * d0 + RAYON_DETOUR:
320
- douteux.setdefault(
321
- arret,
322
- f"{compagnie} {ligne} : {d1 / 1000:.1f} + {d2 / 1000:.1f} km "
323
- f"au lieu de {d0 / 1000:.1f} km",
324
- )
325
- return douteux
326
-
327
-
328
- # --------------------------------------------------------------------------- #
329
- # Sortie et rapport
330
- # --------------------------------------------------------------------------- #
331
-
332
-
333
- def ecrire_csv(lignes: list[dict]) -> None:
334
- colonnes = ["arret", "lat", "lon", "quartier", "commune", "confiance"]
335
- with open(SORTIE, "w", newline="", encoding="utf-8") as f:
336
- ecrivain = csv.DictWriter(f, fieldnames=colonnes)
337
- ecrivain.writeheader()
338
- ecrivain.writerows({c: ligne[c] for c in colonnes} for ligne in lignes)
339
-
340
-
341
- def arrets_de_ligne(rangees: list[dict], compagnie: str, ligne: str) -> list[str]:
342
- """Arrêts d'une ligne, dans l'ordre, dédoublonnés."""
343
- retenues = sorted(
344
- (r for r in rangees if r["compagnie"] == compagnie and r["ligne"] == ligne),
345
- key=lambda r: float(r["ordre"]),
346
- )
347
- vus: dict[str, None] = {}
348
- for rangee in retenues:
349
- vus.setdefault(rangee["arret"], None)
350
- return list(vus)
351
-
352
-
353
- def afficher_ligne(titre: str, arrets: list[str], lignes: list[dict]) -> None:
354
- par_arret = {ligne["arret"]: ligne for ligne in lignes}
355
- print(f"\n--- {titre} ({len(arrets)} arrêts) ---")
356
- for arret in arrets:
357
- ligne = par_arret.get(arret, {})
358
- lieu = ligne.get("quartier") or ligne.get("commune") or ""
359
- coords = f"{ligne.get('lat', '')},{ligne.get('lon', '')}" if ligne.get("lat") else "—"
360
- print(f" {arret:<38} {lieu:<20} {coords:<23} [{ligne.get('confiance', '')}]")
361
-
362
-
363
- def main() -> None:
364
- if hasattr(sys.stdout, "reconfigure"):
365
- sys.stdout.reconfigure(encoding="utf-8", errors="replace")
366
-
367
- parser = argparse.ArgumentParser(description="Géolocalise les arrêts du réseau avec Nominatim.")
368
- parser.add_argument("--limite", type=int, default=None, help="ne traiter que les N premiers arrêts")
369
- args = parser.parse_args()
370
-
371
- rangees = lire_itineraires()
372
- arrets = arrets_uniques(rangees)
373
- if args.limite:
374
- arrets = arrets[: args.limite]
375
- par_ligne = lignes_ordonnees(rangees)
376
-
377
- client = Nominatim()
378
- positions: dict[str, tuple[float, float]] = {}
379
- trouves: dict[str, dict] = {}
380
-
381
- # 1) Requêtes de base et nettoyées, sur Dakar.
382
- print(f"=== 1) Géocodage de {len(arrets)} arrêts ===")
383
- for i, arret in enumerate(arrets, start=1):
384
- variantes = [f"{forme}, Dakar, Sénégal" for forme in formes(arret)]
385
- info = geocoder_arret(arret, client, variantes)
386
- if info:
387
- positions[arret] = (info["lat"], info["lon"])
388
- trouves[arret] = info
389
- if i % 50 == 0 or i == len(arrets):
390
- print(f" {i:3d}/{len(arrets)} trouvés {len(positions)} requêtes {client.requetes}", flush=True)
391
-
392
- # 2) Restants : on retente avec la commune des voisins (si banlieue).
393
- restants = [a for a in arrets if a not in positions]
394
- deja_trouves = len(positions)
395
- print(f"\n=== 2) {len(restants)} arrêts à retenter par commune de voisinage ===")
396
- for i, arret in enumerate(restants, start=1):
397
- communes = communes_voisines(arret, par_ligne, trouves)
398
- variantes = [f"{forme}, {commune}, Sénégal" for commune in communes for forme in formes(arret)]
399
- info = geocoder_arret(arret, client, variantes)
400
- if info:
401
- positions[arret] = (info["lat"], info["lon"])
402
- trouves[arret] = info
403
- if i % 50 == 0 or i == len(restants):
404
- print(f" {i:3d}/{len(restants)} trouvés en plus {len(positions) - deja_trouves} requêtes {client.requetes}", flush=True)
405
-
406
- # 3) Interpolation des arrêts toujours introuvables.
407
- estimes: dict[str, tuple[float, float]] = {}
408
- for arret, liste in interpoler(par_ligne, positions).items():
409
- lat = sum(p[0] for p in liste) / len(liste)
410
- lon = sum(p[1] for p in liste) / len(liste)
411
- positions[arret] = estimes[arret] = (lat, lon)
412
-
413
- # 4) Détours anormaux.
414
- douteux = detours_anormaux(par_ligne, positions)
415
-
416
- # 5) Géocodage inverse : quartier/commune homogène pour chaque position.
417
- print(f"\n=== 3) Géocodage inverse de {len(positions)} positions ===")
418
- infos: dict[str, dict] = {}
419
- for i, (arret, (lat, lon)) in enumerate(positions.items(), start=1):
420
- infos[arret] = client.reverse(lat, lon) or {"trouve": False}
421
- if i % 100 == 0 or i == len(positions):
422
- print(f" {i:3d}/{len(positions)} requêtes {client.requetes}", flush=True)
423
-
424
- # 6) Fichier et bilan.
425
- lignes = []
426
- for arret in arrets:
427
- info = infos.get(arret) or {"trouve": False}
428
- if arret not in positions:
429
- confiance = "introuvable"
430
- elif arret in douteux:
431
- confiance = "douteuse"
432
- elif arret in estimes:
433
- confiance = "estimee"
434
- else:
435
- confiance = "bonne"
436
- lignes.append(
437
- {
438
- "arret": arret,
439
- "lat": f"{positions[arret][0]:.6f}" if arret in positions else "",
440
- "lon": f"{positions[arret][1]:.6f}" if arret in positions else "",
441
- "quartier": info.get("quartier", "") if info.get("trouve") else "",
442
- "commune": info.get("commune", "") if info.get("trouve") else "",
443
- "confiance": confiance,
444
- }
445
- )
446
- ecrire_csv(lignes)
447
-
448
- comptes = {"bonne": 0, "estimee": 0, "douteuse": 0, "introuvable": 0}
449
- for ligne in lignes:
450
- comptes[ligne["confiance"]] += 1
451
-
452
- print("\n=== Bilan ===")
453
- print(f"{len(lignes)} arrêts -> {SORTIE.relative_to(RACINE)}")
454
- for nom in ("bonne", "estimee", "douteuse", "introuvable"):
455
- print(f" {nom:11s}: {comptes[nom]}")
456
-
457
- if douteux:
458
- print(f"\n--- Détours anormaux ({len(douteux)}) ---")
459
- for arret in douteux:
460
- print(f" {arret} : {douteux[arret]}")
461
- if lignes and sum(1 for l in lignes if l["confiance"] == "introuvable"):
462
- print(f"\n--- Introuvables ({sum(1 for l in lignes if l['confiance'] == 'introuvable')}) ---")
463
- for arret in (l["arret"] for l in lignes if l["confiance"] == "introuvable"):
464
- print(f" {arret}")
465
-
466
- # Deux lignes de référence : Médina doit apparaître sur « Avenue Blaise Diagne »
467
- # et Liberté 6 sur « Giratoire [de] Liberté VI ».
468
- for compagnie, ligne in (("Tata AFTU", "Ligne 1"), ("Dakar Dem Dikk", "Ligne 4")):
469
- afficher_ligne(f"{compagnie} {ligne}", arrets_de_ligne(rangees, compagnie, ligne), lignes)
470
-
471
- # Arrêts proches du Marché Sandaga (le marché est géocodé d'abord).
472
- marche = client.geocode("Marché Sandaga, Dakar, Sénégal")
473
- if marche and marche.get("trouve"):
474
- centre = (marche["lat"], marche["lon"])
475
- par_arret = {ligne["arret"]: ligne for ligne in lignes}
476
- proches = sorted((distance_metres(centre, p), a) for a, p in positions.items() if distance_metres(centre, p) <= 500)
477
- print(f"\n--- Arrêts à moins de 500 m du Marché Sandaga ({marche.get('display_name', '')}) ---")
478
- for distance, arret in proches:
479
- ligne = par_arret.get(arret, {})
480
- lieu = ligne.get("quartier") or ligne.get("commune") or ""
481
- print(f" {arret:<38} {distance:4.0f} m {lieu}")
482
- if not proches:
483
- print(" (aucun)")
484
- else:
485
- print("\n[Marché Sandaga] introuvable via Nominatim")
486
-
487
- print(f"\n{client.requetes} requêtes Nominatim cette exécution — {len(client.cache)} entrées en cache")
488
-
489
-
490
- if __name__ == "__main__":
491
- main()
 
1
+ """Géolocalise les arrêts du réseau avec Nominatim (OpenStreetMap).
2
+
3
+ Pour chaque arrêt unique de data/itineraires_dakar.csv, on interroge Nominatim,
4
+ on garde latitude, longitude, quartier et commune, puis on écrit
5
+ data/arrets_geo.csv. Aucun CSV existant ni la recherche de ligne n'est modifié.
6
+
7
+ Robustesse de la recherche :
8
+ - plusieurs requêtes avant d'abandonner un arrêt : nom nettoyé des préfixes
9
+ (« Giratoire de Liberté VI » -> « Liberté 6 »), chiffres romains convertis,
10
+ puis commune de voisinage (« Pikine », « Guédiawaye », « Rufisque ») quand
11
+ les arrêts voisins de la ligne y sont ;
12
+ - les arrêts toujours introuvables reçoivent une position estimée (milieu de
13
+ leurs deux voisins connus sur la même ligne, si ces voisins sont à moins de
14
+ 3 km), confiance « estimee » ; sinon l'arrêt reste « introuvable » ;
15
+ - un arrêt n'est « douteuse » que s'il fait un détour anormal entre ses deux
16
+ voisins : d(précédent, arrêt) + d(arrêt, suivant) > 2·d(précédent, suivant) + 2 km ;
17
+ - un géocodage inverse (reverse, zoom 14) donne un quartier/commune homogène
18
+ pour chaque position finale.
19
+
20
+ Politique d'usage Nominatim : au plus une requête par seconde, User-Agent
21
+ explicite, et cache local (data/sources/cache_nominatim.json) : une requête déjà
22
+ faite n'est jamais refaite.
23
+
24
+ Usage :
25
+ python data/sources/geolocaliser_arrets.py # collecte + rapport
26
+ python data/sources/geolocaliser_arrets.py --limite 10 # essai sur 10 arrêts
27
+ """
28
+
29
+ from __future__ import annotations
30
+
31
+ import argparse
32
+ import csv
33
+ import json
34
+ import math
35
+ import re
36
+ import sys
37
+ import time
38
+ import unicodedata
39
+ from pathlib import Path
40
+
41
+ import requests
42
+
43
+ RACINE = Path(__file__).resolve().parents[2]
44
+ DATA = RACINE / "data"
45
+ ITINERAIRES = DATA / "itineraires_dakar.csv"
46
+ SORTIE = DATA / "arrets_geo.csv"
47
+ CACHE = Path(__file__).resolve().parent / "cache_nominatim.json"
48
+
49
+ GEOCODE = "https://nominatim.openstreetmap.org/search"
50
+ REVERSE = "https://nominatim.openstreetmap.org/reverse"
51
+ USER_AGENT = "GuindiMa-AI/1.0 (cheikhniang159@gmail.com)"
52
+ DELAI_SECONDES = 1.0
53
+ TIMEOUT = 30
54
+ ZOOM_REVERSE = 14
55
+ RAYON_DETOUR = 2000.0 # marge du contrôle « détour anormal », en mètres
56
+ DISTANCE_VOISINS_MAX = 3000.0 # écart max entre les deux voisins connus, pour estimer
57
+
58
+ CHAMPS_QUARTIER = ("neighbourhood", "quarter", "suburb")
59
+ CHAMPS_COMMUNE = ("city_district", "city", "municipality")
60
+
61
+ # Communes de la banlieue : si un voisin de la ligne y est, on retente avec cette
62
+ # commune au lieu de « Dakar ».
63
+ COMMUNES_BANLIEUE = {"pikine": "Pikine", "guediawaye": "Guédiawaye", "rufisque": "Rufisque"}
64
+
65
+ # Préfixes d'arrêt sans valeur pour Nominatim.
66
+ PREFIXES = re.compile(
67
+ r"^\s*(?:terminus|arr[êe]t|giratoire(?:\s+de)?|rond[-\s]?point(?:\s+de)?|"
68
+ r"croisement(?:\s+de)?|station|gare(?:\s+(?:de|routi[èe]re))?)\s+",
69
+ re.I,
70
+ )
71
+
72
+ ROMAINS = {
73
+ "i": 1, "ii": 2, "iii": 3, "iv": 4, "v": 5, "vi": 6,
74
+ "vii": 7, "viii": 8, "ix": 9, "x": 10, "xi": 11, "xii": 12,
75
+ }
76
+
77
+
78
+ # --------------------------------------------------------------------------- #
79
+ # Nettoyage des noms
80
+ # --------------------------------------------------------------------------- #
81
+
82
+
83
+ def sans_accents(texte: str) -> str:
84
+ normalise = unicodedata.normalize("NFD", str(texte).lower().replace("œ", "oe"))
85
+ return "".join(c for c in normalise if unicodedata.category(c) != "Mn")
86
+
87
+
88
+ def nettoyer_prefixes(nom: str) -> str:
89
+ """Retire les préfixes d'arrêt (« Terminus Gare de X » -> « X »)."""
90
+ precedent = None
91
+ while precedent != nom:
92
+ precedent = nom
93
+ nom = PREFIXES.sub("", nom).strip()
94
+ return nom
95
+
96
+
97
+ def remplacer_romains(nom: str) -> str:
98
+ """« Hamo VI » -> « Hamo 6 ». Ne touche qu'aux nombres romains entiers."""
99
+ return re.sub(
100
+ r"\b[IVXLCDMivxlcdm]{1,4}\b",
101
+ lambda m: str(ROMAINS[m.group(0).lower()]) if m.group(0).lower() in ROMAINS else m.group(0),
102
+ nom,
103
+ )
104
+
105
+
106
+ def formes(arret: str) -> list[str]:
107
+ """Requêtes possibles pour un arrêt, de la plus fidèle à la plus nettoyée."""
108
+ resultat: list[str] = []
109
+
110
+ def ajouter(nom: str) -> None:
111
+ nom = nom.strip()
112
+ if nom and nom not in resultat:
113
+ resultat.append(nom)
114
+
115
+ ajouter(arret)
116
+ ajouter(nettoyer_prefixes(arret))
117
+ ajouter(remplacer_romains(arret))
118
+ ajouter(remplacer_romains(nettoyer_prefixes(arret)))
119
+ return resultat
120
+
121
+
122
+ # --------------------------------------------------------------------------- #
123
+ # Nominatim
124
+ # --------------------------------------------------------------------------- #
125
+
126
+
127
+ def _champs(objet: dict) -> dict:
128
+ """Latitude, longitude, quartier, commune d'un objet Nominatim."""
129
+ adresse = objet.get("address") or {}
130
+ quartier = next((adresse[c] for c in CHAMPS_QUARTIER if adresse.get(c)), "")
131
+ commune = next((adresse[c] for c in CHAMPS_COMMUNE if adresse.get(c)), "")
132
+ return {
133
+ "lat": float(objet["lat"]),
134
+ "lon": float(objet["lon"]),
135
+ "quartier": quartier,
136
+ "commune": commune,
137
+ "pays": str(adresse.get("country_code") or "").lower(),
138
+ "display_name": objet.get("display_name", ""),
139
+ }
140
+
141
+
142
+ def _resultat_geocode(brut) -> dict:
143
+ return {"trouve": True, **_champs(brut[0])} if brut else {"trouve": False}
144
+
145
+
146
+ def _resultat_reverse(brut) -> dict:
147
+ if not brut or brut.get("error"):
148
+ return {"trouve": False}
149
+ return {"trouve": True, **_champs(brut)}
150
+
151
+
152
+ class Nominatim:
153
+ """Client poli : cache d'abord, puis au plus une requête réseau par seconde."""
154
+
155
+ def __init__(self) -> None:
156
+ self.cache = charger_cache()
157
+ self.session = requests.Session()
158
+ self.derniere = 0.0
159
+ self.requetes = 0
160
+
161
+ def _sauver(self) -> None:
162
+ CACHE.write_text(json.dumps(self.cache, ensure_ascii=False, indent=1, sort_keys=True), encoding="utf-8")
163
+
164
+ def _attendre(self) -> None:
165
+ attente = DELAI_SECONDES - (time.monotonic() - self.derniere)
166
+ if attente > 0:
167
+ time.sleep(attente)
168
+
169
+ def _appeler(self, url: str, params: dict, cle: str, convertir):
170
+ """Cache d'abord, puis une requête (1/s). None si échec réseau (non mis en cache)."""
171
+ if cle in self.cache:
172
+ return self.cache[cle]
173
+ self._attendre()
174
+ try:
175
+ reponse = self.session.get(url, params=params, headers={"User-Agent": USER_AGENT}, timeout=TIMEOUT)
176
+ reponse.raise_for_status()
177
+ donnees = reponse.json()
178
+ except Exception as exc:
179
+ self.derniere = time.monotonic()
180
+ print(f" [échec réseau] {cle} : {type(exc).__name__} : {exc}", flush=True)
181
+ return None
182
+ self.derniere = time.monotonic()
183
+ self.requetes += 1
184
+ self.cache[cle] = convertir(donnees)
185
+ self._sauver()
186
+ return self.cache[cle]
187
+
188
+ def geocode(self, requete: str) -> dict | None:
189
+ params = {"q": requete, "format": "jsonv2", "addressdetails": "1", "limit": "1"}
190
+ return self._appeler(GEOCODE, params, f"fwd|{requete}", _resultat_geocode)
191
+
192
+ def reverse(self, lat: float, lon: float) -> dict | None:
193
+ params = {"lat": f"{lat}", "lon": f"{lon}", "format": "jsonv2", "zoom": str(ZOOM_REVERSE), "addressdetails": "1"}
194
+ return self._appeler(REVERSE, params, f"rev|{lat:.5f},{lon:.5f}", _resultat_reverse)
195
+
196
+
197
+ def distance_metres(a: tuple[float, float], b: tuple[float, float]) -> float:
198
+ rayon = 6_371_000.0
199
+ p1, p2 = math.radians(a[0]), math.radians(b[0])
200
+ dp = math.radians(b[0] - a[0])
201
+ dl = math.radians(b[1] - a[1])
202
+ h = math.sin(dp / 2) ** 2 + math.cos(p1) * math.cos(p2) * math.sin(dl / 2) ** 2
203
+ return 2 * rayon * math.asin(math.sqrt(h))
204
+
205
+
206
+ # --------------------------------------------------------------------------- #
207
+ # Données
208
+ # --------------------------------------------------------------------------- #
209
+
210
+
211
+ def lire_itineraires() -> list[dict]:
212
+ with open(ITINERAIRES, newline="", encoding="utf-8") as f:
213
+ return list(csv.DictReader(f))
214
+
215
+
216
+ def arrets_uniques(rangees: list[dict]) -> list[str]:
217
+ vus: dict[str, None] = {}
218
+ for rangee in rangees:
219
+ vus.setdefault(rangee["arret"], None)
220
+ return list(vus)
221
+
222
+
223
+ def lignes_ordonnees(rangees: list[dict]) -> dict[tuple[str, str], list[str]]:
224
+ par_ligne: dict[tuple[str, str], list[str]] = {}
225
+ for rangee in rangees:
226
+ par_ligne.setdefault((rangee["compagnie"], rangee["ligne"]), []).append(rangee["arret"])
227
+ return par_ligne
228
+
229
+
230
+ def charger_cache() -> dict:
231
+ """Charge le cache ; convertit l'ancien format (clé = arrêt) au nouveau."""
232
+ if not CACHE.exists():
233
+ return {}
234
+ donnees = json.loads(CACHE.read_text(encoding="utf-8"))
235
+ migre = {}
236
+ for cle, valeur in donnees.items():
237
+ if cle.startswith(("fwd|", "rev|")):
238
+ migre[cle] = valeur
239
+ else: # la requête de base était « <arrêt>, Dakar, Sénégal »
240
+ migre[f"fwd|{cle}, Dakar, Sénégal"] = valeur
241
+ return migre
242
+
243
+
244
+ # --------------------------------------------------------------------------- #
245
+ # Collecte
246
+ # --------------------------------------------------------------------------- #
247
+
248
+
249
+ def geocoder_arret(arret: str, client: Nominatim, variantes: list[str]) -> dict | None:
250
+ """Première requête qui trouve l'arrêt ; None si échec réseau ou aucune trouvaille."""
251
+ for requete in variantes:
252
+ info = client.geocode(requete)
253
+ if info is None: # échec réseau : on n'abandonne pas définitivement, on retente plus tard
254
+ return None
255
+ if info.get("trouve"):
256
+ return {**info, "_requete": requete}
257
+ return None
258
+
259
+
260
+ def communes_voisines(arret: str, par_ligne: dict, trouves: dict[str, dict]) -> list[str]:
261
+ """Communes de banlieue où se trouvent les arrêts voisins de la ligne."""
262
+ cibles: list[str] = []
263
+ for arrets in par_ligne.values():
264
+ if arret not in arrets:
265
+ continue
266
+ index = arrets.index(arret)
267
+ for voisin in (index - 1, index + 1):
268
+ if not 0 <= voisin < len(arrets):
269
+ continue
270
+ info = trouves.get(arrets[voisin])
271
+ if not info:
272
+ continue
273
+ texte = sans_accents(f"{info.get('display_name', '')} {info.get('commune', '')}")
274
+ for cle, nom in COMMUNES_BANLIEUE.items():
275
+ if re.search(rf"\b{cle}\b", texte) and nom not in cibles:
276
+ cibles.append(nom)
277
+ return cibles
278
+
279
+
280
+ def interpoler(
281
+ par_ligne: dict[tuple[str, str], list[str]], positions: dict[str, tuple[float, float]]
282
+ ) -> dict[str, list[tuple[float, float]]]:
283
+ """Estimations : milieu des deux voisins connus, s'ils sont à moins de 3 km.
284
+
285
+ On ne devine une position qu'entre deux arrêts géocodés proches : au-delà de
286
+ DISTANCE_VOISINS_MAX, le milieu n'a plus de sens (il tomberait au hasard
287
+ entre deux points éloignés) et l'arrêt reste « introuvable ».
288
+ """
289
+ estimations: dict[str, list[tuple[float, float]]] = {}
290
+ for arrets in par_ligne.values():
291
+ connus = [i for i, a in enumerate(arrets) if a in positions]
292
+ for i, arret in enumerate(arrets):
293
+ if arret in positions:
294
+ continue
295
+ avant = max((j for j in connus if j < i), default=None)
296
+ apres = min((j for j in connus if j > i), default=None)
297
+ if avant is None or apres is None:
298
+ continue
299
+ pa, pb = positions[arrets[avant]], positions[arrets[apres]]
300
+ if distance_metres(pa, pb) > DISTANCE_VOISINS_MAX:
301
+ continue
302
+ estimations.setdefault(arret, []).append(((pa[0] + pb[0]) / 2, (pa[1] + pb[1]) / 2))
303
+ return estimations
304
+
305
+
306
+ def detours_anormaux(
307
+ par_ligne: dict[tuple[str, str], list[str]], positions: dict[str, tuple[float, float]]
308
+ ) -> dict[str, str]:
309
+ """Arrêts dont d(précédent, arrêt) + d(arrêt, suivant) > 2·d(précédent, suivant) + 2 km."""
310
+ douteux: dict[str, str] = {}
311
+ for (compagnie, ligne), arrets in par_ligne.items():
312
+ for i in range(1, len(arrets) - 1):
313
+ avant, arret, apres = arrets[i - 1], arrets[i], arrets[i + 1]
314
+ if not all(a in positions for a in (avant, arret, apres)):
315
+ continue
316
+ d1 = distance_metres(positions[avant], positions[arret])
317
+ d2 = distance_metres(positions[arret], positions[apres])
318
+ d0 = distance_metres(positions[avant], positions[apres])
319
+ if d1 + d2 > 2 * d0 + RAYON_DETOUR:
320
+ douteux.setdefault(
321
+ arret,
322
+ f"{compagnie} {ligne} : {d1 / 1000:.1f} + {d2 / 1000:.1f} km "
323
+ f"au lieu de {d0 / 1000:.1f} km",
324
+ )
325
+ return douteux
326
+
327
+
328
+ # --------------------------------------------------------------------------- #
329
+ # Sortie et rapport
330
+ # --------------------------------------------------------------------------- #
331
+
332
+
333
+ def ecrire_csv(lignes: list[dict]) -> None:
334
+ colonnes = ["arret", "lat", "lon", "quartier", "commune", "confiance"]
335
+ with open(SORTIE, "w", newline="", encoding="utf-8") as f:
336
+ ecrivain = csv.DictWriter(f, fieldnames=colonnes)
337
+ ecrivain.writeheader()
338
+ ecrivain.writerows({c: ligne[c] for c in colonnes} for ligne in lignes)
339
+
340
+
341
+ def arrets_de_ligne(rangees: list[dict], compagnie: str, ligne: str) -> list[str]:
342
+ """Arrêts d'une ligne, dans l'ordre, dédoublonnés."""
343
+ retenues = sorted(
344
+ (r for r in rangees if r["compagnie"] == compagnie and r["ligne"] == ligne),
345
+ key=lambda r: float(r["ordre"]),
346
+ )
347
+ vus: dict[str, None] = {}
348
+ for rangee in retenues:
349
+ vus.setdefault(rangee["arret"], None)
350
+ return list(vus)
351
+
352
+
353
+ def afficher_ligne(titre: str, arrets: list[str], lignes: list[dict]) -> None:
354
+ par_arret = {ligne["arret"]: ligne for ligne in lignes}
355
+ print(f"\n--- {titre} ({len(arrets)} arrêts) ---")
356
+ for arret in arrets:
357
+ ligne = par_arret.get(arret, {})
358
+ lieu = ligne.get("quartier") or ligne.get("commune") or ""
359
+ coords = f"{ligne.get('lat', '')},{ligne.get('lon', '')}" if ligne.get("lat") else "—"
360
+ print(f" {arret:<38} {lieu:<20} {coords:<23} [{ligne.get('confiance', '')}]")
361
+
362
+
363
+ def main() -> None:
364
+ if hasattr(sys.stdout, "reconfigure"):
365
+ sys.stdout.reconfigure(encoding="utf-8", errors="replace")
366
+
367
+ parser = argparse.ArgumentParser(description="Géolocalise les arrêts du réseau avec Nominatim.")
368
+ parser.add_argument("--limite", type=int, default=None, help="ne traiter que les N premiers arrêts")
369
+ args = parser.parse_args()
370
+
371
+ rangees = lire_itineraires()
372
+ arrets = arrets_uniques(rangees)
373
+ if args.limite:
374
+ arrets = arrets[: args.limite]
375
+ par_ligne = lignes_ordonnees(rangees)
376
+
377
+ client = Nominatim()
378
+ positions: dict[str, tuple[float, float]] = {}
379
+ trouves: dict[str, dict] = {}
380
+
381
+ # 1) Requêtes de base et nettoyées, sur Dakar.
382
+ print(f"=== 1) Géocodage de {len(arrets)} arrêts ===")
383
+ for i, arret in enumerate(arrets, start=1):
384
+ variantes = [f"{forme}, Dakar, Sénégal" for forme in formes(arret)]
385
+ info = geocoder_arret(arret, client, variantes)
386
+ if info:
387
+ positions[arret] = (info["lat"], info["lon"])
388
+ trouves[arret] = info
389
+ if i % 50 == 0 or i == len(arrets):
390
+ print(f" {i:3d}/{len(arrets)} trouvés {len(positions)} requêtes {client.requetes}", flush=True)
391
+
392
+ # 2) Restants : on retente avec la commune des voisins (si banlieue).
393
+ restants = [a for a in arrets if a not in positions]
394
+ deja_trouves = len(positions)
395
+ print(f"\n=== 2) {len(restants)} arrêts à retenter par commune de voisinage ===")
396
+ for i, arret in enumerate(restants, start=1):
397
+ communes = communes_voisines(arret, par_ligne, trouves)
398
+ variantes = [f"{forme}, {commune}, Sénégal" for commune in communes for forme in formes(arret)]
399
+ info = geocoder_arret(arret, client, variantes)
400
+ if info:
401
+ positions[arret] = (info["lat"], info["lon"])
402
+ trouves[arret] = info
403
+ if i % 50 == 0 or i == len(restants):
404
+ print(f" {i:3d}/{len(restants)} trouvés en plus {len(positions) - deja_trouves} requêtes {client.requetes}", flush=True)
405
+
406
+ # 3) Interpolation des arrêts toujours introuvables.
407
+ estimes: dict[str, tuple[float, float]] = {}
408
+ for arret, liste in interpoler(par_ligne, positions).items():
409
+ lat = sum(p[0] for p in liste) / len(liste)
410
+ lon = sum(p[1] for p in liste) / len(liste)
411
+ positions[arret] = estimes[arret] = (lat, lon)
412
+
413
+ # 4) Détours anormaux.
414
+ douteux = detours_anormaux(par_ligne, positions)
415
+
416
+ # 5) Géocodage inverse : quartier/commune homogène pour chaque position.
417
+ print(f"\n=== 3) Géocodage inverse de {len(positions)} positions ===")
418
+ infos: dict[str, dict] = {}
419
+ for i, (arret, (lat, lon)) in enumerate(positions.items(), start=1):
420
+ infos[arret] = client.reverse(lat, lon) or {"trouve": False}
421
+ if i % 100 == 0 or i == len(positions):
422
+ print(f" {i:3d}/{len(positions)} requêtes {client.requetes}", flush=True)
423
+
424
+ # 6) Fichier et bilan.
425
+ lignes = []
426
+ for arret in arrets:
427
+ info = infos.get(arret) or {"trouve": False}
428
+ if arret not in positions:
429
+ confiance = "introuvable"
430
+ elif arret in douteux:
431
+ confiance = "douteuse"
432
+ elif arret in estimes:
433
+ confiance = "estimee"
434
+ else:
435
+ confiance = "bonne"
436
+ lignes.append(
437
+ {
438
+ "arret": arret,
439
+ "lat": f"{positions[arret][0]:.6f}" if arret in positions else "",
440
+ "lon": f"{positions[arret][1]:.6f}" if arret in positions else "",
441
+ "quartier": info.get("quartier", "") if info.get("trouve") else "",
442
+ "commune": info.get("commune", "") if info.get("trouve") else "",
443
+ "confiance": confiance,
444
+ }
445
+ )
446
+ ecrire_csv(lignes)
447
+
448
+ comptes = {"bonne": 0, "estimee": 0, "douteuse": 0, "introuvable": 0}
449
+ for ligne in lignes:
450
+ comptes[ligne["confiance"]] += 1
451
+
452
+ print("\n=== Bilan ===")
453
+ print(f"{len(lignes)} arrêts -> {SORTIE.relative_to(RACINE)}")
454
+ for nom in ("bonne", "estimee", "douteuse", "introuvable"):
455
+ print(f" {nom:11s}: {comptes[nom]}")
456
+
457
+ if douteux:
458
+ print(f"\n--- Détours anormaux ({len(douteux)}) ---")
459
+ for arret in douteux:
460
+ print(f" {arret} : {douteux[arret]}")
461
+ if lignes and sum(1 for l in lignes if l["confiance"] == "introuvable"):
462
+ print(f"\n--- Introuvables ({sum(1 for l in lignes if l['confiance'] == 'introuvable')}) ---")
463
+ for arret in (l["arret"] for l in lignes if l["confiance"] == "introuvable"):
464
+ print(f" {arret}")
465
+
466
+ # Deux lignes de référence : Médina doit apparaître sur « Avenue Blaise Diagne »
467
+ # et Liberté 6 sur « Giratoire [de] Liberté VI ».
468
+ for compagnie, ligne in (("Tata AFTU", "Ligne 1"), ("Dakar Dem Dikk", "Ligne 4")):
469
+ afficher_ligne(f"{compagnie} {ligne}", arrets_de_ligne(rangees, compagnie, ligne), lignes)
470
+
471
+ # Arrêts proches du Marché Sandaga (le marché est géocodé d'abord).
472
+ marche = client.geocode("Marché Sandaga, Dakar, Sénégal")
473
+ if marche and marche.get("trouve"):
474
+ centre = (marche["lat"], marche["lon"])
475
+ par_arret = {ligne["arret"]: ligne for ligne in lignes}
476
+ proches = sorted((distance_metres(centre, p), a) for a, p in positions.items() if distance_metres(centre, p) <= 500)
477
+ print(f"\n--- Arrêts à moins de 500 m du Marché Sandaga ({marche.get('display_name', '')}) ---")
478
+ for distance, arret in proches:
479
+ ligne = par_arret.get(arret, {})
480
+ lieu = ligne.get("quartier") or ligne.get("commune") or ""
481
+ print(f" {arret:<38} {distance:4.0f} m {lieu}")
482
+ if not proches:
483
+ print(" (aucun)")
484
+ else:
485
+ print("\n[Marché Sandaga] introuvable via Nominatim")
486
+
487
+ print(f"\n{client.requetes} requêtes Nominatim cette exécution — {len(client.cache)} entrées en cache")
488
+
489
+
490
+ if __name__ == "__main__":
491
+ main()
src/matching/geo.py CHANGED
@@ -1,275 +1,394 @@
1
- """Positions des lieux dits : quartiers des arrêts et points géocodés.
2
-
3
- Sert à la recherche de ligne quand un lieu dit par l'utilisateur (Médina,
4
- Sandaga, Plateau…) ne se retrouve pas dans le nom des arrêts. Deux sources :
5
-
6
- * ``data/arrets_geo.csv`` (produit par data/sources/geolocaliser_arrets.py) :
7
- pour chaque arrêt, sa position, son quartier et sa commune. Les arrêts
8
- « douteuse » sont ignorés (position non fiable).
9
- * ``data/lieux_geo.csv`` (produit par data/sources/geolocaliser_lieux.py) : la
10
- position d'un lieu, précalculée pour éviter toute requête réseau sur un lieu
11
- connu de l'extraction. Un lieu absent y est géocodé une seule fois en direct
12
- (cache disque, au plus une requête par seconde, même User-Agent).
13
-
14
- Candidats pour un lieu : les arrêts dont le quartier ou la commune correspond,
15
- plus ceux à moins de 800 m du point du lieu. La note d'un arrêt proche décroît
16
- avec la distance, si bien que l'arrêt conseillé est le candidat le plus proche.
17
- """
18
-
19
- from __future__ import annotations
20
-
21
- import csv
22
- import json
23
- import math
24
- import re
25
- import time
26
- from pathlib import Path
27
-
28
- try: # import à plat (app.py) ou en paquet
29
- from matching.lieux import FAUX_AMIS, sans_accents
30
- except ImportError: # pragma: no cover
31
- from .lieux import FAUX_AMIS, sans_accents
32
-
33
- DATA = Path(__file__).resolve().parents[2] / "data"
34
- ARRETS_GEO = DATA / "arrets_geo.csv"
35
- LIEUX_GEO = DATA / "lieux_geo.csv"
36
- CACHE_LIEUX = DATA / "sources" / "cache_lieux_nominatim.json"
37
-
38
- GEOCODE = "https://nominatim.openstreetmap.org/search"
39
- USER_AGENT = "GuindiMa-AI/1.0 (cheikhniang159@gmail.com)"
40
- DELAI_SECONDES = 1.0
41
- TIMEOUT = 15
42
- RAYON_METRES = 800.0
43
- # Le nom passe avant la position : une note géographique reste sous 0.75, donc
44
- # toujours sous un arrêt trouvé par son nom (score 1.0, ou ≥ 0.85 après marge).
45
- SCORE_QUARTIER = 0.7
46
- SCORE_PROCHE_MIN = 0.6
47
- SCORE_GEO_MAX = 0.75
48
- CONFIANCE_IGNOREE = {"douteuse"}
49
- # Seule une position de confiance « bonne » sert à la proximité : une position
50
- # « estimee » peut tomber dans le mauvais quartier.
51
- CONFIANCE_PROXIMITE = {"bonne"}
52
-
53
- # Mots de structure, retirés avant de comparer un lieu à un quartier/commune.
54
- GENERIQUES = {
55
- "commune", "communes", "arrondissement", "arrondissements", "departement",
56
- "departements", "quartier", "quartiers", "region", "de", "du", "des", "d",
57
- "la", "le", "les", "l",
58
- }
59
-
60
- # Niveaux administratifs trop larges : « Département de Guédiawaye » ne dit pas
61
- # que l'arrêt est dans la ville de Guédiawaye (il peut être à Pikine).
62
- NIVEAUX_LARGES = ("arrondissement", "departement")
63
-
64
-
65
- def normaliser(texte: str) -> str:
66
- """Minuscules, sans accents ni ponctuation : « Dakar-Plateau » -> « dakar plateau »."""
67
- return " ".join(re.sub(r"[^a-z0-9]+", " ", sans_accents(str(texte))).split())
68
-
69
-
70
- def _mots(texte: str) -> list[str]:
71
- return [mot for mot in normaliser(texte).split() if mot not in GENERIQUES]
72
-
73
-
74
- def _niveau_precis(valeur: str) -> bool:
75
- """Un quartier ou une commune, jamais « Département de » ni « Arrondissement de »."""
76
- return bool(valeur) and not normaliser(valeur).startswith(NIVEAUX_LARGES)
77
-
78
-
79
- def distance_metres(a: tuple[float, float], b: tuple[float, float]) -> float:
80
- """Distance à vol d'oiseau entre deux points (latitude, longitude)."""
81
- rayon = 6_371_000.0
82
- p1, p2 = math.radians(a[0]), math.radians(b[0])
83
- dp, dl = math.radians(b[0] - a[0]), math.radians(b[1] - a[1])
84
- h = math.sin(dp / 2) ** 2 + math.cos(p1) * math.cos(p2) * math.sin(dl / 2) ** 2
85
- return 2 * rayon * math.asin(math.sqrt(h))
86
-
87
-
88
- class _Nominatim:
89
- """Géocodage direct, poli : cache disque d'abord, puis au plus 1 requête/s."""
90
-
91
- def __init__(self, cache: Path = CACHE_LIEUX) -> None:
92
- self.cache_path = cache
93
- self.cache: dict[str, list[float] | None] = {}
94
- if cache.exists():
95
- try:
96
- self.cache = json.loads(cache.read_text(encoding="utf-8"))
97
- except (OSError, json.JSONDecodeError):
98
- self.cache = {}
99
- self.session = None
100
- self.derniere = 0.0
101
-
102
- def _sauver(self) -> None:
103
- try:
104
- self.cache_path.write_text(
105
- json.dumps(self.cache, ensure_ascii=False), encoding="utf-8"
106
- )
107
- except OSError: # disque en lecture seule (Space) : le cache reste en mémoire
108
- pass
109
-
110
- def _attendre(self) -> None:
111
- attente = DELAI_SECONDES - (time.monotonic() - self.derniere)
112
- if attente > 0:
113
- time.sleep(attente)
114
-
115
- def geocode(self, requete: str) -> tuple[float, float] | None:
116
- if requete in self.cache:
117
- valeur = self.cache[requete]
118
- return tuple(valeur) if valeur else None
119
- try:
120
- import requests
121
- except ImportError: # sans requests, pas de géocodage direct : on continue sans
122
- return None
123
- if self.session is None:
124
- self.session = requests.Session()
125
- self._attendre()
126
- point = None
127
- try:
128
- reponse = self.session.get(
129
- GEOCODE,
130
- params={"q": requete, "format": "jsonv2", "limit": "1"},
131
- headers={"User-Agent": USER_AGENT},
132
- timeout=TIMEOUT,
133
- )
134
- reponse.raise_for_status()
135
- resultats = reponse.json()
136
- if resultats:
137
- point = (float(resultats[0]["lat"]), float(resultats[0]["lon"]))
138
- except Exception: # réseau, HTTP, JSON : on n'insiste pas, une autre fois
139
- self.derniere = time.monotonic()
140
- return None
141
- self.derniere = time.monotonic()
142
- self.cache[requete] = [point[0], point[1]] if point else None
143
- self._sauver()
144
- return point
145
-
146
-
147
- class LieuxGeo:
148
- """Positions et quartiers des arrêts, et points des lieux dits."""
149
-
150
- def __init__(
151
- self,
152
- arrets_geo: Path = ARRETS_GEO,
153
- lieux_geo: Path = LIEUX_GEO,
154
- cache: Path = CACHE_LIEUX,
155
- ) -> None:
156
- self._arrets: dict[str, dict] = {}
157
- self._cible_mots: dict[str, set[str]] = {}
158
- self._lire_arrets(arrets_geo)
159
-
160
- self._lieux: dict[str, tuple[float, float]] = {}
161
- self._absents: set[str] = set()
162
- self._lire_lieux(lieux_geo)
163
-
164
- self._client = _Nominatim(cache)
165
-
166
- # -- chargement ------------------------------------------------------- #
167
-
168
- def _lire_arrets(self, chemin: Path) -> None:
169
- if not Path(chemin).exists():
170
- return
171
- with open(chemin, newline="", encoding="utf-8") as f:
172
- for rangee in csv.DictReader(f):
173
- point = None
174
- if rangee.get("lat") and rangee.get("lon"):
175
- try:
176
- point = (float(rangee["lat"]), float(rangee["lon"]))
177
- except ValueError:
178
- point = None
179
- arret = rangee["arret"]
180
- quartier = rangee.get("quartier", "")
181
- commune = rangee.get("commune", "")
182
- cible: set[str] = set()
183
- if _niveau_precis(quartier):
184
- cible |= set(_mots(quartier))
185
- if _niveau_precis(commune):
186
- cible |= set(_mots(commune))
187
- self._arrets[arret] = {
188
- "point": point,
189
- "quartier": quartier,
190
- "commune": commune,
191
- "confiance": rangee.get("confiance", ""),
192
- }
193
- self._cible_mots[arret] = cible
194
-
195
- def _lire_lieux(self, chemin: Path) -> None:
196
- if not chemin.exists():
197
- return
198
- with open(chemin, newline="", encoding="utf-8") as f:
199
- for rangee in csv.DictReader(f):
200
- try:
201
- self._lieux[normaliser(rangee["lieu"])] = (float(rangee["lat"]), float(rangee["lon"]))
202
- except (KeyError, ValueError):
203
- continue
204
-
205
- # ------------------------------------------------------------------ #
206
-
207
- def point(self, lieu: str) -> tuple[float, float] | None:
208
- """Point du lieu dit : lieux_geo.csv, sinon Nominatim (une seule fois)."""
209
- if not lieu:
210
- return None
211
- cle = normaliser(lieu)
212
- if not cle:
213
- return None
214
- if cle in self._lieux:
215
- return self._lieux[cle]
216
- if cle in self._absents:
217
- return None
218
- trouve = self._client.geocode(f"{lieu}, Dakar, Sénégal")
219
- if trouve is not None:
220
- self._lieux[cle] = trouve
221
- return trouve
222
- self._absents.add(cle)
223
- return None
224
-
225
- def point_arret(self, arret: str) -> tuple[float, float] | None:
226
- info = self._arrets.get(arret)
227
- return info["point"] if info else None
228
-
229
- def scores_lieu(self, lieu: str, proximite: bool = True) -> dict[str, float]:
230
- """Arrêt -> note, pour les arrêts qui se trouvent au lieu dit.
231
-
232
- Un arrêt dont le quartier ou la commune correspond au lieu vaut
233
- SCORE_QUARTIER ; un arrêt à moins de 800 m vaut d'autant plus que le
234
- point est proche (au plus SCORE_GEO_MAX). La correspondance de quartier,
235
- comme la proximité, ne retient que la confiance « bonne » : un arrêt
236
- « estimee » peut tomber dans un quartier voisin. Les arrêts « douteuse »
237
- et les faux amis sont écartés. `proximite=False` n'utilise que le quartier
238
- ou la commune : quand le lieu est déjà reconnu par son nom, on ne veut pas
239
- y ajouter les arrêts simplement proches.
240
- """
241
- if not lieu:
242
- return {}
243
- point = self.point(lieu) if proximite else None
244
- cible = set(_mots(lieu))
245
- scores: dict[str, float] = {}
246
- for arret, info in self._arrets.items():
247
- if info["confiance"] in CONFIANCE_IGNOREE:
248
- continue
249
- # Un faux ami (« Sortie Pikine », « Garage Guédiawaye ») n'est jamais
250
- # un candidat géographique : son nom dit un quartier où il n'est pas.
251
- if normaliser(arret) in FAUX_AMIS:
252
- continue
253
- note = 0.0
254
- if (
255
- cible
256
- and info["confiance"] in CONFIANCE_PROXIMITE
257
- and cible <= self._cible_mots.get(arret, set())
258
- ):
259
- note = SCORE_QUARTIER
260
- if (
261
- proximite
262
- and info["confiance"] in CONFIANCE_PROXIMITE
263
- and point is not None
264
- and info["point"] is not None
265
- ):
266
- distance = distance_metres(point, info["point"])
267
- if distance <= RAYON_METRES:
268
- note = max(
269
- note,
270
- SCORE_PROCHE_MIN
271
- + (SCORE_GEO_MAX - SCORE_PROCHE_MIN) * (1 - distance / RAYON_METRES),
272
- )
273
- if note > 0:
274
- scores[arret] = note
275
- return scores
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Positions des lieux dits : quartiers des arrêts et points géocodés.
2
+
3
+ Sert à la recherche de ligne quand un lieu dit par l'utilisateur (Médina,
4
+ Sandaga, Plateau…) ne se retrouve pas dans le nom des arrêts. Deux sources :
5
+
6
+ * ``data/arrets_geo.csv`` (produit par data/sources/geolocaliser_arrets.py) :
7
+ pour chaque arrêt, sa position, son quartier et sa commune. Les arrêts
8
+ « douteuse » sont ignorés (position non fiable).
9
+ * ``data/lieux_geo.csv`` (produit par data/sources/geolocaliser_lieux.py) : la
10
+ position d'un lieu, précalculée pour éviter toute requête réseau sur un lieu
11
+ connu de l'extraction. Un lieu absent y est géocodé une seule fois en direct
12
+ (cache disque, au plus une requête par seconde, même User-Agent).
13
+
14
+ Candidats pour un lieu : les arrêts dont le quartier ou la commune correspond,
15
+ plus ceux à moins de 800 m du point du lieu. La note d'un arrêt proche décroît
16
+ avec la distance, si bien que l'arrêt conseillé est le candidat le plus proche.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import csv
22
+ import json
23
+ import math
24
+ import re
25
+ import time
26
+ from pathlib import Path
27
+
28
+ try: # import à plat (app.py) ou en paquet
29
+ from matching.lieux import FAUX_AMIS, sans_accents
30
+ except ImportError: # pragma: no cover
31
+ from .lieux import FAUX_AMIS, sans_accents
32
+
33
+ DATA = Path(__file__).resolve().parents[2] / "data"
34
+ ARRETS_GEO = DATA / "arrets_geo.csv"
35
+ LIEUX_GEO = DATA / "lieux_geo.csv"
36
+ ITINERAIRES_CSV = DATA / "itineraires_dakar.csv"
37
+ CACHE_LIEUX = DATA / "sources" / "cache_lieux_nominatim.json"
38
+
39
+ GEOCODE = "https://nominatim.openstreetmap.org/search"
40
+ USER_AGENT = "GuindiMa-AI/1.0 (cheikhniang159@gmail.com)"
41
+ DELAI_SECONDES = 1.0
42
+ TIMEOUT = 15
43
+ RAYON_METRES = 800.0
44
+ # Le nom passe avant la position : une note géographique reste sous 0.75, donc
45
+ # toujours sous un arrêt trouvé par son nom (score 1.0, ou ≥ 0.85 après marge).
46
+ SCORE_QUARTIER = 0.7
47
+ SCORE_PROCHE_MIN = 0.6
48
+ SCORE_GEO_MAX = 0.75
49
+ CONFIANCE_IGNOREE = {"douteuse"}
50
+ # Seule une position de confiance « bonne » sert à la proximité : une position
51
+ # « estimee » peut tomber dans le mauvais quartier.
52
+ CONFIANCE_PROXIMITE = {"bonne"}
53
+
54
+ # Un arrêt isolé de tout son voisinage sur une ligne AFTU a une position fausse
55
+ # (nom d'arrêt retrouvé ailleurs par homonymie). Les lignes Dem Dikk, tracées sur
56
+ # OpenStreetMap, ne sont pas concernées.
57
+ SEUIL_VOISIN_METRES = 3000.0
58
+ COMPAGNIE_VOISINS = "Tata AFTU"
59
+ # « Rue 9 », « Rue 9bis », « Rue 34 » : le nom seul ne dit pas de quel quartier
60
+ # il s'agit, la position géocodée n'est donc jamais fiable. Une rue numérotée qui
61
+ # porte en plus une localité (« Rue 10 Pikine Ouest ») reste situable.
62
+ _RUE_NUMEROTEE = re.compile(r"^rue\s+\d+\s*(?:bis|ter)?$", re.IGNORECASE)
63
+
64
+
65
+ def nom_rue_numerotee(arret: str) -> bool:
66
+ """Vrai si le nom d'arrêt est une rue numérotée seule (« Rue 9 », « Rue 9bis »)."""
67
+ sans_annotation = re.sub(r"\([^)]*\)", " ", str(arret))
68
+ return bool(_RUE_NUMEROTEE.match(normaliser(sans_annotation)))
69
+
70
+
71
+ def _hors_voisinage(
72
+ positions: dict[str, tuple[float, float]],
73
+ bonnes: set[str],
74
+ itineraires_csv: Path,
75
+ ) -> set[str]:
76
+ """Arrêts « bonne » loin de TOUS leurs voisins connus sur une ligne Tata AFTU.
77
+
78
+ Le précédent et le suivant qui ont une position servent de repères : un arrêt
79
+ « bonne » à plus de 3 km de chacun est un homonyme géocodé ailleurs. Un arrêt
80
+ sans voisin connu n'est pas jugé (isolé dans les données, pas forcément faux).
81
+ """
82
+ chemin = Path(itineraires_csv)
83
+ if not chemin.exists():
84
+ return set()
85
+ lignes: dict[tuple[str, str], list[str]] = {}
86
+ with open(chemin, newline="", encoding="utf-8") as f:
87
+ rangees = [
88
+ rangee
89
+ for rangee in csv.DictReader(f)
90
+ if rangee.get("compagnie") == COMPAGNIE_VOISINS
91
+ ]
92
+ for rangee in sorted(rangees, key=lambda r: int(r.get("ordre") or 0)):
93
+ lignes.setdefault((rangee["compagnie"], rangee["ligne"]), []).append(rangee["arret"])
94
+ ecartes: set[str] = set()
95
+ for arrets in lignes.values():
96
+ for i, arret in enumerate(arrets):
97
+ # Un terminus n'a qu'un côté : il peut être loin du dernier arrêt connu
98
+ # (tronçon de ligne long), ce n'est pas un indice d'homonymie.
99
+ if not 0 < i < len(arrets) - 1:
100
+ continue
101
+ if arret not in bonnes:
102
+ continue
103
+ ici = positions.get(arret)
104
+ if ici is None:
105
+ continue
106
+ voisins = [
107
+ positions[arrets[j]]
108
+ for j in (i - 1, i + 1)
109
+ if arrets[j] in positions
110
+ ]
111
+ if voisins and all(
112
+ distance_metres(ici, voisin) > SEUIL_VOISIN_METRES for voisin in voisins
113
+ ):
114
+ ecartes.add(arret)
115
+ return ecartes
116
+
117
+
118
+ def _non_fiables(arrets: dict[str, dict], itineraires_csv: Path) -> set[str]:
119
+ """Arrêts à position non fiable : rues numérotées et isolés sur une ligne AFTU."""
120
+ rues = {arret for arret in arrets if nom_rue_numerotee(arret)}
121
+ positions = {
122
+ arret: info["point"]
123
+ for arret, info in arrets.items()
124
+ if info.get("point") is not None
125
+ }
126
+ bonnes = {
127
+ arret
128
+ for arret, info in arrets.items()
129
+ if info.get("confiance") == "bonne"
130
+ }
131
+ return rues | _hors_voisinage(positions, bonnes, itineraires_csv)
132
+
133
+
134
+ def arrets_non_fiables(
135
+ arrets_geo: Path = ARRETS_GEO,
136
+ itineraires_csv: Path = ITINERAIRES_CSV,
137
+ ) -> set[str]:
138
+ """Noms d'arrêts dont la position ne vaut ni pour le quartier ni pour la proximité.
139
+
140
+ Partagé avec l'affichage (app.py) : les mêmes arrêts ne montrent pas de
141
+ quartier entre parenthèses.
142
+ """
143
+ arrets: dict[str, dict] = {}
144
+ chemin = Path(arrets_geo)
145
+ if chemin.exists():
146
+ with open(chemin, newline="", encoding="utf-8") as f:
147
+ for rangee in csv.DictReader(f):
148
+ point = None
149
+ if rangee.get("lat") and rangee.get("lon"):
150
+ try:
151
+ point = (float(rangee["lat"]), float(rangee["lon"]))
152
+ except ValueError:
153
+ point = None
154
+ arrets[rangee["arret"]] = {
155
+ "point": point,
156
+ "confiance": rangee.get("confiance", ""),
157
+ }
158
+ return _non_fiables(arrets, itineraires_csv)
159
+
160
+
161
+ # Mots de structure, retirés avant de comparer un lieu à un quartier/commune.
162
+ GENERIQUES = {
163
+ "commune", "communes", "arrondissement", "arrondissements", "departement",
164
+ "departements", "quartier", "quartiers", "region", "de", "du", "des", "d",
165
+ "la", "le", "les", "l",
166
+ }
167
+
168
+ # Niveaux administratifs trop larges : « Département de Guédiawaye » ne dit pas
169
+ # que l'arrêt est dans la ville de Guédiawaye (il peut être à Pikine).
170
+ NIVEAUX_LARGES = ("arrondissement", "departement")
171
+
172
+
173
+ def normaliser(texte: str) -> str:
174
+ """Minuscules, sans accents ni ponctuation : « Dakar-Plateau » -> « dakar plateau »."""
175
+ return " ".join(re.sub(r"[^a-z0-9]+", " ", sans_accents(str(texte))).split())
176
+
177
+
178
+ def _mots(texte: str) -> list[str]:
179
+ return [mot for mot in normaliser(texte).split() if mot not in GENERIQUES]
180
+
181
+
182
+ def _niveau_precis(valeur: str) -> bool:
183
+ """Un quartier ou une commune, jamais « Département de » ni « Arrondissement de »."""
184
+ return bool(valeur) and not normaliser(valeur).startswith(NIVEAUX_LARGES)
185
+
186
+
187
+ def distance_metres(a: tuple[float, float], b: tuple[float, float]) -> float:
188
+ """Distance à vol d'oiseau entre deux points (latitude, longitude)."""
189
+ rayon = 6_371_000.0
190
+ p1, p2 = math.radians(a[0]), math.radians(b[0])
191
+ dp, dl = math.radians(b[0] - a[0]), math.radians(b[1] - a[1])
192
+ h = math.sin(dp / 2) ** 2 + math.cos(p1) * math.cos(p2) * math.sin(dl / 2) ** 2
193
+ return 2 * rayon * math.asin(math.sqrt(h))
194
+
195
+
196
+ class _Nominatim:
197
+ """Géocodage direct, poli : cache disque d'abord, puis au plus 1 requête/s."""
198
+
199
+ def __init__(self, cache: Path = CACHE_LIEUX) -> None:
200
+ self.cache_path = cache
201
+ self.cache: dict[str, list[float] | None] = {}
202
+ if cache.exists():
203
+ try:
204
+ self.cache = json.loads(cache.read_text(encoding="utf-8"))
205
+ except (OSError, json.JSONDecodeError):
206
+ self.cache = {}
207
+ self.session = None
208
+ self.derniere = 0.0
209
+
210
+ def _sauver(self) -> None:
211
+ try:
212
+ self.cache_path.write_text(
213
+ json.dumps(self.cache, ensure_ascii=False), encoding="utf-8"
214
+ )
215
+ except OSError: # disque en lecture seule (Space) : le cache reste en mémoire
216
+ pass
217
+
218
+ def _attendre(self) -> None:
219
+ attente = DELAI_SECONDES - (time.monotonic() - self.derniere)
220
+ if attente > 0:
221
+ time.sleep(attente)
222
+
223
+ def geocode(self, requete: str) -> tuple[float, float] | None:
224
+ if requete in self.cache:
225
+ valeur = self.cache[requete]
226
+ return tuple(valeur) if valeur else None
227
+ try:
228
+ import requests
229
+ except ImportError: # sans requests, pas de géocodage direct : on continue sans
230
+ return None
231
+ if self.session is None:
232
+ self.session = requests.Session()
233
+ self._attendre()
234
+ point = None
235
+ try:
236
+ reponse = self.session.get(
237
+ GEOCODE,
238
+ params={"q": requete, "format": "jsonv2", "limit": "1"},
239
+ headers={"User-Agent": USER_AGENT},
240
+ timeout=TIMEOUT,
241
+ )
242
+ reponse.raise_for_status()
243
+ resultats = reponse.json()
244
+ if resultats:
245
+ point = (float(resultats[0]["lat"]), float(resultats[0]["lon"]))
246
+ except Exception: # réseau, HTTP, JSON : on n'insiste pas, une autre fois
247
+ self.derniere = time.monotonic()
248
+ return None
249
+ self.derniere = time.monotonic()
250
+ self.cache[requete] = [point[0], point[1]] if point else None
251
+ self._sauver()
252
+ return point
253
+
254
+
255
+ class LieuxGeo:
256
+ """Positions et quartiers des arrêts, et points des lieux dits."""
257
+
258
+ def __init__(
259
+ self,
260
+ arrets_geo: Path = ARRETS_GEO,
261
+ lieux_geo: Path = LIEUX_GEO,
262
+ cache: Path = CACHE_LIEUX,
263
+ itineraires_csv: Path = ITINERAIRES_CSV,
264
+ ) -> None:
265
+ self._arrets: dict[str, dict] = {}
266
+ self._cible_mots: dict[str, set[str]] = {}
267
+ self._lire_arrets(arrets_geo)
268
+ # Les positions trompeuses (rues numérotées, homonymes isolés sur une
269
+ # ligne AFTU) sont écartées en mémoire, sans toucher aux CSV.
270
+ self._ecarter_non_fiables(itineraires_csv)
271
+
272
+ self._lieux: dict[str, tuple[float, float]] = {}
273
+ self._absents: set[str] = set()
274
+ self._lire_lieux(lieux_geo)
275
+
276
+ self._client = _Nominatim(cache)
277
+
278
+ # -- chargement ------------------------------------------------------- #
279
+
280
+ def _lire_arrets(self, chemin: Path) -> None:
281
+ if not Path(chemin).exists():
282
+ return
283
+ with open(chemin, newline="", encoding="utf-8") as f:
284
+ for rangee in csv.DictReader(f):
285
+ point = None
286
+ if rangee.get("lat") and rangee.get("lon"):
287
+ try:
288
+ point = (float(rangee["lat"]), float(rangee["lon"]))
289
+ except ValueError:
290
+ point = None
291
+ arret = rangee["arret"]
292
+ quartier = rangee.get("quartier", "")
293
+ commune = rangee.get("commune", "")
294
+ cible: set[str] = set()
295
+ if _niveau_precis(quartier):
296
+ cible |= set(_mots(quartier))
297
+ if _niveau_precis(commune):
298
+ cible |= set(_mots(commune))
299
+ self._arrets[arret] = {
300
+ "point": point,
301
+ "quartier": quartier,
302
+ "commune": commune,
303
+ "confiance": rangee.get("confiance", ""),
304
+ }
305
+ self._cible_mots[arret] = cible
306
+
307
+ def _ecarter_non_fiables(self, itineraires_csv: Path) -> None:
308
+ """Neutralise les positions trompeuses, sans modifier les CSV."""
309
+ for arret in _non_fiables(self._arrets, itineraires_csv):
310
+ if arret in self._arrets:
311
+ self._arrets[arret]["confiance"] = "douteuse"
312
+ self._cible_mots[arret] = set()
313
+
314
+ def _lire_lieux(self, chemin: Path) -> None:
315
+ if not chemin.exists():
316
+ return
317
+ with open(chemin, newline="", encoding="utf-8") as f:
318
+ for rangee in csv.DictReader(f):
319
+ try:
320
+ self._lieux[normaliser(rangee["lieu"])] = (float(rangee["lat"]), float(rangee["lon"]))
321
+ except (KeyError, ValueError):
322
+ continue
323
+
324
+ # ------------------------------------------------------------------ #
325
+
326
+ def point(self, lieu: str) -> tuple[float, float] | None:
327
+ """Point du lieu dit : lieux_geo.csv, sinon Nominatim (une seule fois)."""
328
+ if not lieu:
329
+ return None
330
+ cle = normaliser(lieu)
331
+ if not cle:
332
+ return None
333
+ if cle in self._lieux:
334
+ return self._lieux[cle]
335
+ if cle in self._absents:
336
+ return None
337
+ trouve = self._client.geocode(f"{lieu}, Dakar, Sénégal")
338
+ if trouve is not None:
339
+ self._lieux[cle] = trouve
340
+ return trouve
341
+ self._absents.add(cle)
342
+ return None
343
+
344
+ def point_arret(self, arret: str) -> tuple[float, float] | None:
345
+ info = self._arrets.get(arret)
346
+ return info["point"] if info else None
347
+
348
+ def scores_lieu(self, lieu: str, proximite: bool = True) -> dict[str, float]:
349
+ """Arrêt -> note, pour les arrêts qui se trouvent au lieu dit.
350
+
351
+ Un arrêt dont le quartier ou la commune correspond au lieu vaut
352
+ SCORE_QUARTIER ; un arrêt à moins de 800 m vaut d'autant plus que le
353
+ point est proche (au plus SCORE_GEO_MAX). La correspondance de quartier,
354
+ comme la proximité, ne retient que la confiance « bonne » : un arrêt
355
+ « estimee » peut tomber dans un quartier voisin. Les arrêts « douteuse »
356
+ et les faux amis sont écartés. `proximite=False` n'utilise que le quartier
357
+ ou la commune : quand le lieu est déjà reconnu par son nom, on ne veut pas
358
+ y ajouter les arrêts simplement proches.
359
+ """
360
+ if not lieu:
361
+ return {}
362
+ point = self.point(lieu) if proximite else None
363
+ cible = set(_mots(lieu))
364
+ scores: dict[str, float] = {}
365
+ for arret, info in self._arrets.items():
366
+ if info["confiance"] in CONFIANCE_IGNOREE:
367
+ continue
368
+ # Un faux ami (« Sortie Pikine », « Garage Guédiawaye ») n'est jamais
369
+ # un candidat géographique : son nom dit un quartier où il n'est pas.
370
+ if normaliser(arret) in FAUX_AMIS:
371
+ continue
372
+ note = 0.0
373
+ if (
374
+ cible
375
+ and info["confiance"] in CONFIANCE_PROXIMITE
376
+ and cible <= self._cible_mots.get(arret, set())
377
+ ):
378
+ note = SCORE_QUARTIER
379
+ if (
380
+ proximite
381
+ and info["confiance"] in CONFIANCE_PROXIMITE
382
+ and point is not None
383
+ and info["point"] is not None
384
+ ):
385
+ distance = distance_metres(point, info["point"])
386
+ if distance <= RAYON_METRES:
387
+ note = max(
388
+ note,
389
+ SCORE_PROCHE_MIN
390
+ + (SCORE_GEO_MAX - SCORE_PROCHE_MIN) * (1 - distance / RAYON_METRES),
391
+ )
392
+ if note > 0:
393
+ scores[arret] = note
394
+ return scores