PythonMindset commited on
Commit
cc9ddc5
·
verified ·
1 Parent(s): 1e64afd

Deploiement GuindiMa AI (interface Gradio) (part 2)

Browse files
scripts/brev.py CHANGED
@@ -310,6 +310,117 @@ print(
310
  """
311
 
312
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
313
  def _source(cellule: dict) -> str:
314
  return "".join(cellule["source"])
315
 
@@ -527,6 +638,25 @@ def adapter_conversation(nb: dict) -> dict:
527
  return nb
528
 
529
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
530
  def _ecrire(nb: dict, cible: Path) -> None:
531
  cible.parent.mkdir(parents=True, exist_ok=True)
532
  cible.write_text(json.dumps(nb, ensure_ascii=False, indent=1) + "\n", encoding="utf-8")
@@ -550,6 +680,11 @@ def main(argv: list[str] | None = None) -> int:
550
  _ecrire(conversation, dossier / "voix_ajouts_conversation_brev.ipynb")
551
  print(f"{dossier / 'voix_ajouts_conversation_brev.ipynb'} : écrit")
552
 
 
 
 
 
 
553
  test = adapter_test(json.loads(TEST_COLAB.read_text(encoding="utf-8")))
554
  _ecrire(test, dossier / "voix_test_prononciation_brev.ipynb")
555
  print(f"{dossier / 'voix_test_prononciation_brev.ipynb'} : écrit")
 
310
  """
311
 
312
 
313
+ INTRO_LISTE = """\
314
+ # GuindiMa — régénérer une liste d'audios, voix Oolel native (sur Brev)
315
+
316
+ Notebook générique : il régénère **n'importe quelle liste** d'audios, sans toucher
317
+ au reste du cache. Exemple : `data/audit/voix_gare.csv` (« Gare » se dit « Gaar »).
318
+
319
+ **Avant de lancer :** dépose à côté du notebook un fichier **`liste_regen.csv`**
320
+ (colonnes `fichier`, `phrase` ; la phrase est le texte que la voix doit dire,
321
+ lexique déjà appliqué). Un autre nom ? Variable d'environnement `LISTE_REGEN`.
322
+
323
+ Mêmes réglages que les autres séries : voix `8_1_c.wav` du Space
324
+ soynade-research/Oolel-Voices-Demo, graine 1234, 3 essais par audio, Whisper
325
+ wolof garde le meilleur.
326
+
327
+ **Machine :** GPU NVIDIA (T4 ou L4) chez Brev — pas de Google Drive : tout est
328
+ écrit dans `sortie_voix/`, à côté du notebook. Voir `notebooks/BREV_LIRE_MOI.md`.
329
+
330
+ **Jeton 🔑 :** la cellule Whisper lit le jeton dans la **variable
331
+ d'environnement `HF_TOKEN`** de la machine — pas de saisie cachée : sans
332
+ interface, il n'y a pas de clavier au premier plan. Jeton absent → Whisper
333
+ wolof public de contrôle directement.
334
+
335
+ **Lancer :** la première cellule installe pip (ensurepip) et les paquets, puis
336
+ **Kernel -> Restart Kernel** et Run All. Sans interface :
337
+
338
+ jupyter nbconvert --to notebook --execute --ExecutePreprocessor.timeout=-1 voix_regen_liste_brev.ipynb
339
+
340
+ La reprise saute les audios déjà faits **avec la même phrase** dans
341
+ `sortie_voix/audios_regen/` ; un audio fait avec une autre phrase est refait.
342
+
343
+ À la fin, télécharge `sortie_voix/regen.zip`, puis sur ton PC (même CSV) :
344
+
345
+ python scripts/installer_voix_oolel.py --liste sortie_voix/regen.zip liste_regen.csv
346
+ """
347
+
348
+ DOSSIER_LISTE = """\
349
+ # Tout atterrit ici, à côté du notebook : audios, rapport, voix de référence.
350
+ import os, glob, shutil
351
+
352
+ BASE = './sortie_voix'
353
+ SORTIE = f'{BASE}/audios_regen'
354
+ RAPPORT = f'{BASE}/rapport_regen.csv'
355
+ REF = f'{BASE}/8_1_c.wav'
356
+ os.makedirs(SORTIE, exist_ok=True)
357
+ if not os.path.exists(REF):
358
+ from huggingface_hub import hf_hub_download
359
+ telecharge = hf_hub_download(
360
+ repo_id='soynade-research/Oolel-Voices-Demo',
361
+ repo_type='space',
362
+ filename='8_1_c.wav',
363
+ )
364
+ shutil.copy(telecharge, REF)
365
+ print('voix de référence :', REF)
366
+ """
367
+
368
+ PLAN_LISTE = """\
369
+ # La liste à régénérer : liste_regen.csv à côté du notebook (fichier, phrase).
370
+ import csv
371
+
372
+ LISTE = os.environ.get('LISTE_REGEN', './liste_regen.csv')
373
+ assert os.path.exists(LISTE), f'{LISTE} introuvable : dépose la liste (colonnes fichier, phrase) à côté du notebook.'
374
+ with open(LISTE, encoding='utf-8-sig', newline='') as f:
375
+ lues = list(csv.DictReader(f))
376
+ assert lues and {'fichier', 'phrase'} <= set(lues[0]), 'colonnes attendues : fichier, phrase'
377
+ PHRASES = [{'fichier': l['fichier'].strip(), 'phrase': l['phrase'].strip()} for l in lues if l['fichier'].strip()]
378
+ noms = [p['fichier'] for p in PHRASES]
379
+ assert len(noms) == len(set(noms)), 'un fichier apparaît deux fois dans la liste'
380
+ assert all(n.endswith('.wav') and '/' not in n and '\\\\' not in n for n in noms), 'noms de fichiers .wav simples attendus'
381
+ PLAN = {'modele': MODELE, 'voix_reference': '8_1_c.wav (Space soynade-research/Oolel-Voices-Demo)', 'graine': GRAINE_PLAN, 'phrases': PHRASES}
382
+ GRAINE = PLAN['graine']
383
+
384
+ # Reprise honnête : un audio déjà fait avec une AUTRE phrase (« Gare » avant
385
+ # « Gaar ») est oublié, pour être refait avec la bonne.
386
+ if os.path.exists(RAPPORT):
387
+ with open(RAPPORT, encoding='utf-8-sig') as f:
388
+ anciens = list(csv.DictReader(f))
389
+ voulues = {p['fichier']: p['phrase'] for p in PHRASES}
390
+ gardes = []
391
+ for l in anciens:
392
+ if l['fichier'] in voulues and l['phrase'] != voulues[l['fichier']]:
393
+ chemin = f"{SORTIE}/{l['fichier']}"
394
+ if os.path.exists(chemin):
395
+ os.remove(chemin)
396
+ else:
397
+ gardes.append(l)
398
+ if len(gardes) != len(anciens):
399
+ with open(RAPPORT, 'w', encoding='utf-8-sig', newline='') as f:
400
+ w = csv.DictWriter(f, fieldnames=list(anciens[0]))
401
+ w.writeheader()
402
+ w.writerows(gardes)
403
+ print(len(anciens) - len(gardes), 'audio(s) à refaire : la phrase a changé')
404
+ print(len(PHRASES), 'phrases ; déjà faits :', len([n for n in noms if os.path.exists(f'{SORTIE}/{n}')]))
405
+ """
406
+
407
+ FIN_LISTE = """\
408
+ # Vérifier le dossier et préparer sortie_voix/regen.zip pour installer_voix_oolel.py --liste
409
+ import zipfile
410
+
411
+ manquants = [p['fichier'] for p in PHRASES if not os.path.exists(f"{SORTIE}/{p['fichier']}")]
412
+ assert not manquants, f"{len(manquants)} audios manquants (ex. {manquants[:5]}) : relance la cellule de génération."
413
+ # Seulement les audios de la liste (et le rapport) : un audio d'une liste
414
+ # précédente, resté dans le dossier, ne part pas dans le zip.
415
+ archive = f'{BASE}/regen.zip'
416
+ with zipfile.ZipFile(archive, 'w', zipfile.ZIP_DEFLATED) as boite:
417
+ for p in PHRASES:
418
+ boite.write(f"{SORTIE}/{p['fichier']}", arcname=p['fichier'])
419
+ boite.write(RAPPORT, arcname='rapport_regen.csv')
420
+ print(len(PHRASES), 'audios OK — sur ton PC : python scripts/installer_voix_oolel.py --liste sortie_voix/regen.zip liste_regen.csv')
421
+ """
422
+
423
+
424
  def _source(cellule: dict) -> str:
425
  return "".join(cellule["source"])
426
 
 
638
  return nb
639
 
640
 
641
+ def adapter_liste(nb: dict) -> dict:
642
+ """Le notebook générique : régénère la liste d'un CSV posé à côté de lui.
643
+
644
+ Même base que le complet (pip, Whisper, génération avec 3 essais, reprise) ;
645
+ seuls le plan (lu dans liste_regen.csv au lancement), le dossier de sortie
646
+ et le zip final changent. Modèle et graine restent ceux du plan des 637.
647
+ """
648
+ nb = _adapter(nb, INTRO_LISTE, DOSSIER_LISTE, FIN_LISTE)
649
+ cells = nb["cells"]
650
+ i_plan = _cel(cells, "PLAN = ", "plan")
651
+ plan_637 = json.loads((RACINE / "scripts" / "phrases_voix.json").read_text(encoding="utf-8"))
652
+ cells[i_plan]["source"] = (
653
+ f"MODELE = {plan_637['modele']!r}\n"
654
+ f"GRAINE_PLAN = {plan_637['graine']!r}\n"
655
+ + PLAN_LISTE
656
+ ).splitlines(keepends=True)
657
+ return nb
658
+
659
+
660
  def _ecrire(nb: dict, cible: Path) -> None:
661
  cible.parent.mkdir(parents=True, exist_ok=True)
662
  cible.write_text(json.dumps(nb, ensure_ascii=False, indent=1) + "\n", encoding="utf-8")
 
680
  _ecrire(conversation, dossier / "voix_ajouts_conversation_brev.ipynb")
681
  print(f"{dossier / 'voix_ajouts_conversation_brev.ipynb'} : écrit")
682
 
683
+ # Le notebook générique : n'importe quelle liste (fichier, phrase).
684
+ liste = adapter_liste(preparer.construire())
685
+ _ecrire(liste, dossier / "voix_regen_liste_brev.ipynb")
686
+ print(f"{dossier / 'voix_regen_liste_brev.ipynb'} : écrit")
687
+
688
  test = adapter_test(json.loads(TEST_COLAB.read_text(encoding="utf-8")))
689
  _ecrire(test, dossier / "voix_test_prononciation_brev.ipynb")
690
  print(f"{dossier / 'voix_test_prononciation_brev.ipynb'} : écrit")
scripts/installer_voix_oolel.py CHANGED
@@ -28,6 +28,11 @@ Il ne lance rien tout seul : c'est un outil qu'on exécute à la main.
28
  python scripts/installer_voix_oolel.py --zip sortie_voix/tts_cache_oolel.zip
29
  python scripts/installer_voix_oolel.py --conversation sortie_voix/ajouts_conversation.zip
30
  python scripts/installer_voix_oolel.py --tata tata_tattaa.zip
 
 
 
 
 
31
  """
32
 
33
  from __future__ import annotations
@@ -143,6 +148,55 @@ def installer_tata(archive: Path, attendus: list[str], cache: Path = CACHE) -> i
143
  return 0
144
 
145
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
146
  def main() -> int:
147
  parseur = argparse.ArgumentParser(
148
  description="Installe la voix native d'Oolel (8_1_c.wav) dans data/tts_cache_oolel/."
@@ -171,8 +225,29 @@ def main() -> int:
171
  default=None,
172
  help="zip des 72 lignes Tata régénérées avec « Tattaa » (--tata tata_tattaa.zip)",
173
  )
 
 
 
 
 
 
 
 
174
  args = parseur.parse_args()
175
 
 
 
 
 
 
 
 
 
 
 
 
 
 
176
  if args.tata:
177
  archive = Path(args.tata)
178
  if not archive.is_file():
 
28
  python scripts/installer_voix_oolel.py --zip sortie_voix/tts_cache_oolel.zip
29
  python scripts/installer_voix_oolel.py --conversation sortie_voix/ajouts_conversation.zip
30
  python scripts/installer_voix_oolel.py --tata tata_tattaa.zip
31
+ python scripts/installer_voix_oolel.py --liste sortie_voix/regen.zip data/audit/voix_gare.csv
32
+
33
+ Avec --liste, on remplace exactement les audios d'une liste (CSV : colonne
34
+ `fichier`), produits par notebooks/voix_regen_liste_brev.ipynb. Tout ou rien :
35
+ s'il en manque un seul dans le zip, rien n'est touché.
36
  """
37
 
38
  from __future__ import annotations
 
148
  return 0
149
 
150
 
151
+ def lire_liste(chemin_csv: Path) -> list[str]:
152
+ """Les noms de la colonne « fichier » d'une liste à régénérer, sans doublon."""
153
+ with chemin_csv.open(encoding="utf-8-sig", newline="") as fichier:
154
+ lecteur = csv.DictReader(fichier)
155
+ if "fichier" not in (lecteur.fieldnames or []):
156
+ raise ValueError(f"{chemin_csv} : colonne « fichier » absente")
157
+ noms = [rangee["fichier"].strip() for rangee in lecteur if rangee["fichier"].strip()]
158
+ return list(dict.fromkeys(noms))
159
+
160
+
161
+ def installer_liste(
162
+ archive: Path,
163
+ noms: list[str],
164
+ cache: Path = CACHE,
165
+ connus: list[str] | None = None,
166
+ ) -> int:
167
+ """Remplace exactement les audios de la liste ; 0 si tout va bien, 1 sinon.
168
+
169
+ Tout ou rien : un nom absent du zip, un nom inconnu de voix_complete.csv
170
+ (faute de frappe qui créerait un fichier jamais joué) ou un nom qui n'est
171
+ pas un simple .wav, et rien n'est copié. Le reste du zip (rapport,
172
+ audios d'une autre liste) est ignoré.
173
+ """
174
+ if not noms:
175
+ print("liste vide : rien à installer", file=sys.stderr)
176
+ return 1
177
+ mauvais = [nom for nom in noms if not nom.endswith(".wav") or Path(nom).name != nom]
178
+ if mauvais:
179
+ print(f"noms refusés (simple fichier .wav attendu) : {mauvais[:5]}", file=sys.stderr)
180
+ return 1
181
+ connus = fichiers_attendus() if connus is None else connus
182
+ inconnus = [nom for nom in noms if nom not in set(connus)]
183
+ if inconnus:
184
+ print(f"{len(inconnus)} nom(s) absent(s) de voix_complete.csv, ex. : {inconnus[:5]}", file=sys.stderr)
185
+ return 1
186
+ with zipfile.ZipFile(archive) as boite:
187
+ par_nom = {Path(nom).name: nom for nom in boite.namelist() if nom.lower().endswith(".wav")}
188
+ manquants = [nom for nom in noms if nom not in par_nom]
189
+ if manquants:
190
+ print(f"{len(manquants)} fichier(s) manquant(s) dans l'archive, ex. : {manquants[:5]}", file=sys.stderr)
191
+ return 1
192
+ cache.mkdir(parents=True, exist_ok=True)
193
+ for nom in noms:
194
+ with boite.open(par_nom[nom]) as source, open(cache / nom, "wb") as cible:
195
+ shutil.copyfileobj(source, cible)
196
+ print(f"{len(noms)} audios remplacés dans {cache} (liste)")
197
+ return 0
198
+
199
+
200
  def main() -> int:
201
  parseur = argparse.ArgumentParser(
202
  description="Installe la voix native d'Oolel (8_1_c.wav) dans data/tts_cache_oolel/."
 
225
  default=None,
226
  help="zip des 72 lignes Tata régénérées avec « Tattaa » (--tata tata_tattaa.zip)",
227
  )
228
+ parseur.add_argument(
229
+ "--liste",
230
+ dest="liste",
231
+ nargs=2,
232
+ metavar=("ZIP", "CSV"),
233
+ default=None,
234
+ help="zip du notebook voix_regen_liste_brev + la liste (colonne fichier) à remplacer",
235
+ )
236
  args = parseur.parse_args()
237
 
238
+ if args.liste:
239
+ archive, liste = Path(args.liste[0]), Path(args.liste[1])
240
+ for chemin in (archive, liste):
241
+ if not chemin.is_file():
242
+ print(f"introuvable : {chemin}", file=sys.stderr)
243
+ return 1
244
+ try:
245
+ noms = lire_liste(liste)
246
+ except ValueError as exc:
247
+ print(exc, file=sys.stderr)
248
+ return 1
249
+ return installer_liste(archive, noms)
250
+
251
  if args.tata:
252
  archive = Path(args.tata)
253
  if not archive.is_file():
src/app/cartes.py CHANGED
@@ -7,3 +7,15 @@ def titre_autre_possibilite(numero: int) -> str:
7
  "<div style='color:#0B6B37;font-size:16px;font-weight:700;"
8
  f"margin:14px 0 4px 0;'>Autre possibilité {escape(str(numero))}</div>"
9
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
7
  "<div style='color:#0B6B37;font-size:16px;font-weight:700;"
8
  f"margin:14px 0 4px 0;'>Autre possibilité {escape(str(numero))}</div>"
9
  )
10
+
11
+
12
+ def titre_section(texte: str) -> str:
13
+ """Titre de section en HTML, jamais en Markdown « ### ».
14
+
15
+ Collé à la carte précédente (« </div>### Pas de bus direct »), le Markdown
16
+ restait dans le bloc HTML et l'usager voyait les « ### » tels quels.
17
+ """
18
+ return (
19
+ "<div style='color:#11301C;font-size:20px;font-weight:800;"
20
+ f"margin:18px 0 6px 0;'>{escape(str(texte))}</div>"
21
+ )
src/routing/adapter.py CHANGED
@@ -20,6 +20,7 @@ from .places import PlaceIndex, normalize_name, terminus_forms
20
  from .router import (
21
  Leg,
22
  NoRouteFoundError,
 
23
  PLACE_STOP_RADIUS_M,
24
  PlaceNotFoundError,
25
  ResolvedPlace,
@@ -297,15 +298,67 @@ def _resoudre(matcher, lieu: str) -> dict:
297
  # lui (message vague sinon). Un lieu nommé exactement prend la position de
298
  # l'arrêt sur le réseau ; un quartier prend son point de lieux_geo.csv. Jamais
299
  # d'appel réseau ici : pas de position vaut mieux qu'une position devinée.
300
- point_sur = None
301
- if meilleur and note >= 1.0:
302
- for nom in _vers_reseau([meilleur]):
303
- coords = _NETWORK.coords(nom)
304
- if coords is not None:
305
- point_sur = coords
306
- break
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
307
  if point_sur is None:
308
- point_sur = matcher.geo.point_connu(lieu)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
309
 
310
  def place(seuil: float) -> ResolvedPlace:
311
  # Pas de restriction ici : un arrêt loin du lieu dit garde sa ligne. La
@@ -429,6 +482,89 @@ def _vague(lieu: dict, arret: str) -> bool:
429
  return haversine_m(point, coords) > PLACE_STOP_RADIUS_M
430
 
431
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
432
  def _resultat_vide(depart: str, arrivee: str, dep: dict, arr: dict) -> dict:
433
  return {
434
  "found": False,
@@ -513,6 +649,7 @@ def chercher_v2(
513
  for trip in trips
514
  if all(leg.operator in compagnies for leg in trip.legs)
515
  ]
 
516
  if not trips:
517
  return resultat
518
 
 
20
  from .router import (
21
  Leg,
22
  NoRouteFoundError,
23
+ ACCESS_WALK_RADIUS_M,
24
  PLACE_STOP_RADIUS_M,
25
  PlaceNotFoundError,
26
  ResolvedPlace,
 
298
  # lui (message vague sinon). Un lieu nommé exactement prend la position de
299
  # l'arrêt sur le réseau ; un quartier prend son point de lieux_geo.csv. Jamais
300
  # d'appel réseau ici : pas de position vaut mieux qu'une position devinée.
301
+ # Un lieu qui porte exactement le nom d'un arrêt se définit par ces arrêts.
302
+ # - point fiable : un de ces arrêts en position « bonne » ; sinon le point
303
+ # de lieux_geo.csv, s'il tombe à moins de 1 km de l'un d'eux (« Yoff » y
304
+ # est posé sur l'arrêt Grand Yoff, 2,8 km plus au sud) ; sinon la position
305
+ # estimée de l'arrêt. « Rond point Sandaga », estimé à 1,9 km du marché,
306
+ # ne sert donc jamais de point à lui seul.
307
+ exacts = (
308
+ [a for a in tries if _note_du_nom(lieu, a) >= 1.0]
309
+ if meilleur and note >= 1.0
310
+ else []
311
+ )
312
+ positions_exactes = [
313
+ (nom, _NETWORK.coords(nom))
314
+ for nom in _vers_reseau(exacts)
315
+ if _NETWORK.coords(nom) is not None
316
+ ]
317
+ point_sur = next(
318
+ (
319
+ coords
320
+ for nom, coords in positions_exactes
321
+ if _NETWORK.stop_confidence.get(nom) == "bonne"
322
+ ),
323
+ None,
324
+ )
325
  if point_sur is None:
326
+ point_csv = matcher.geo.point_connu(lieu)
327
+ if point_csv is not None and (
328
+ not positions_exactes
329
+ or any(
330
+ haversine_m(point_csv, coords) <= ACCORD_POINT_LIEU_M
331
+ for _, coords in positions_exactes
332
+ )
333
+ ):
334
+ point_sur = point_csv
335
+ elif positions_exactes:
336
+ point_sur = positions_exactes[0][1]
337
+
338
+ # Un lieu exact ne prend un arrêt par la géographie seule (commune,
339
+ # quartier) que s'il est à distance de marche de l'un de ses arrêts : la
340
+ # commune de Yoff couvre la Foire et les HLM Grand Yoff, et la Tata 2, qui
341
+ # ne passe jamais à Yoff (trace AFTU à 2,2 km), était proposée depuis
342
+ # « Route HLM Grand Médine ».
343
+ reperes = [coords for _, coords in positions_exactes]
344
+ if point_sur is not None:
345
+ reperes.append(point_sur)
346
+ if note >= 1.0 and reperes:
347
+ for arret in tries:
348
+ if _note_du_nom(lieu, arret) >= MIN_SCORE or notes_v1[arret] <= 0:
349
+ continue
350
+ positions = [
351
+ _NETWORK.coords(nom)
352
+ for nom in _arrets_du_reseau(arret)
353
+ if _NETWORK.coords(nom) is not None
354
+ ]
355
+ if not positions or min(
356
+ haversine_m(repere, position)
357
+ for repere in reperes
358
+ for position in positions
359
+ ) > ACCESS_WALK_RADIUS_M:
360
+ notes_v1[arret] = 0.0
361
+ tries = sorted(notes_v1, key=lambda arret: -notes_v1[arret])
362
 
363
  def place(seuil: float) -> ResolvedPlace:
364
  # Pas de restriction ici : un arrêt loin du lieu dit garde sa ligne. La
 
482
  return haversine_m(point, coords) > PLACE_STOP_RADIUS_M
483
 
484
 
485
+ # Le point d'un lieu (lieux_geo.csv) n'est cru que s'il est à 1 km au plus
486
+ # d'un arrêt du même nom.
487
+ ACCORD_POINT_LIEU_M = 1_000.0
488
+
489
+ # Un changement ne recule jamais vers le départ de plus de 1 km : Maristes ->
490
+ # Rufisque montait vers Liberté 6 (plus à l'ouest) pour reprendre la 213
491
+ # dans l'autre sens.
492
+ RECUL_MAX_M = 1_000.0
493
+
494
+
495
+ def _position_sure(leg: Leg, arret: str) -> tuple[float, float] | None:
496
+ """La position de cet arrêt sur la ligne du tronçon, si elle est mesurée."""
497
+
498
+ ligne = _NETWORK.lines.get((leg.operator, leg.line))
499
+ if ligne is None or arret not in ligne.stops:
500
+ return None
501
+ index = ligne.stops.index(arret)
502
+ if not _NETWORK.position_sure(ligne, index):
503
+ return None
504
+ return _NETWORK.position_on_line(ligne, index)
505
+
506
+
507
+ def _position_connue(leg: Leg, arret: str) -> tuple[float, float] | None:
508
+ """La position de cet arrêt sur la ligne du tronçon, même devinée."""
509
+
510
+ ligne = _NETWORK.lines.get((leg.operator, leg.line))
511
+ if ligne is None or arret not in ligne.stops:
512
+ return None
513
+ return _NETWORK.position_on_line(ligne, ligne.stops.index(arret))
514
+
515
+
516
+ def _dans_le_lieu(lieu: dict, leg: Leg, arret: str) -> bool:
517
+ """Vrai si cet arrêt fait partie du lieu dit (nom, ou position sûre à 600 m)."""
518
+
519
+ if arret in lieu.get("nom_exact", ()) or arret in lieu.get("par_son_nom", ()):
520
+ return True
521
+ point, position = lieu.get("point_sur"), _position_sure(leg, arret)
522
+ return (
523
+ point is not None
524
+ and position is not None
525
+ and haversine_m(point, position) <= PLACE_STOP_RADIUS_M
526
+ )
527
+
528
+
529
+ def _changements_coherents(trip: Trip, dep: dict, arr: dict) -> bool:
530
+ """Un trajet avec changement qui avance vraiment.
531
+
532
+ - jamais un bus de plus une fois arrivé : « Marché Colobane Rufisque » est
533
+ déjà Rufisque, le 3e bus vers la Gare de Rufisque était de trop ;
534
+ - jamais un premier bus pour rien : changer dans le lieu de départ veut dire
535
+ que le 2e bus passait déjà là ;
536
+ - jamais de recul : chaque changement (aux positions sûres) reste à peu près
537
+ aussi près de l'arrivée que le précédent.
538
+ """
539
+
540
+ if len(trip.legs) < 2:
541
+ return True
542
+ for leg in trip.legs[:-1]:
543
+ if _dans_le_lieu(arr, leg, leg.alight_stop):
544
+ return False
545
+ for leg in trip.legs[1:]:
546
+ if _dans_le_lieu(dep, leg, leg.board_stop):
547
+ return False
548
+
549
+ cible = arr.get("point_sur") or _position_sure(trip.legs[-1], trip.legs[-1].alight_stop)
550
+ if cible is None:
551
+ return True
552
+ precedent = dep.get("point_sur") or _position_sure(trip.legs[0], trip.legs[0].board_stop)
553
+ for leg in trip.legs[1:]:
554
+ # Le sens se juge avec la position connue, même approximative : la
555
+ # marge de 1 km absorbe l'imprécision (« Rond Point Liberté 6 » de la
556
+ # 213 n'est placé que par Nominatim, mais il est bien à l'ouest).
557
+ position = _position_connue(leg, leg.board_stop)
558
+ if position is None:
559
+ continue
560
+ if precedent is not None and (
561
+ haversine_m(position, cible) > haversine_m(precedent, cible) + RECUL_MAX_M
562
+ ):
563
+ return False
564
+ precedent = position
565
+ return True
566
+
567
+
568
  def _resultat_vide(depart: str, arrivee: str, dep: dict, arr: dict) -> dict:
569
  return {
570
  "found": False,
 
649
  for trip in trips
650
  if all(leg.operator in compagnies for leg in trip.legs)
651
  ]
652
+ trips = [trip for trip in trips if _changements_coherents(trip, dep, arr)]
653
  if not trips:
654
  return resultat
655
 
src/routing/network.py CHANGED
@@ -1,720 +1,794 @@
1
- """The Dakar bus graph.
2
-
3
- A node is a stop **as seen by one line in one direction**. Keeping the
4
- direction in the node is what lets the router produce a proper leg with a
5
- terminus ("towards Palais 2") instead of just a pair of stop names.
6
-
7
- Each line is usable in both directions. Ride edges follow the ordered
8
- itinerary; transfer edges connect different lines at the same normalized
9
- stop name, or at two stops within 500 m.
10
- """
11
-
12
- from __future__ import annotations
13
-
14
- import heapq
15
- import math
16
- from collections import Counter, defaultdict
17
- from dataclasses import dataclass
18
- from typing import Iterable, NamedTuple
19
-
20
- from .places import _GENERIC_TOKENS, normalize_name, terminus_forms
21
- from .traces import distances_sur_trace
22
-
23
- # Modeling constants. They are deliberately simple and easy to tune.
24
- # Vitesse commerciale, sur de vraies longueurs de route. Sur le terrain, les bus
25
- # Dem Dikk roulent nettement plus vite que les Tata, qui s'arrêtent partout.
26
- SPEED_BY_COMPANY_M_PER_MIN = {
27
- "Dakar Dem Dikk": 333.0, # 20 km/h
28
- "Tata AFTU": 250.0, # 15 km/h
29
- }
30
- # La plus rapide : la recherche guidée s'en sert pour ne jamais surestimer le
31
- # temps restant. Une compagnie inconnue roule à cette vitesse aussi.
32
- BUS_SPEED_M_PER_MIN = max(SPEED_BY_COMPANY_M_PER_MIN.values())
33
- FIXED_MINUTES_PER_SEGMENT = 3.0 # fallback when a stop has no coordinates
34
- # Une ligne réduite à ses deux terminus, dont l'un sans position, n'a aucun
35
- # arrêt pour borner la distance : Dem Dikk 11 (Keur Massar -> Lat Dior) coûtait
36
- # 3 min et devenait une téléportation à travers toute la ville.
37
- UNKNOWN_TWO_STOP_RIDE_MINUTES = 35.0
38
- TRANSFER_PENALTY_MIN = 6.0 # waiting / walking to the next line
39
- WALK_SPEED_M_PER_MIN = 80.0
40
- MAX_TRANSFER_WALK_M = 500.0
41
- # Correspondances à pied gardées pour deux lignes données : les plus courtes. Toutes
42
- # les garder faisait 126 000 arêtes et jusqu'à 44 s par requête, sans bus direct.
43
- MAX_WALK_TRANSFERS_PER_LINE_PAIR = 2
44
- # Un ancien nom absent des listes officielles (« Cambérène 2 ») vaut l'arrêt officiel
45
- # le plus proche : portant le même nom de quartier, ou tout près s'il n'y en a pas.
46
- LEGACY_SAME_NAME_RADIUS_M = 2_000.0
47
- LEGACY_ANY_NAME_RADIUS_M = 500.0
48
- POSITION_AGREEMENT_M = 500.0
49
- SAME_NAME_MAX_APART_M = 1_000.0
50
-
51
- LineKey = tuple[str, str] # (operator, line name)
52
-
53
-
54
- class Node(NamedTuple):
55
- line: LineKey
56
- direction: int # 0 = itinerary order, 1 = reversed
57
- index: int
58
-
59
-
60
- @dataclass(frozen=True)
61
- class Line:
62
- company: str
63
- name: str
64
- stops: tuple[str, ...]
65
- terminus_a: str | None = None
66
- terminus_b: str | None = None
67
-
68
- @property
69
- def key(self) -> LineKey:
70
- return (self.company, self.name)
71
-
72
- def stops_for(self, direction: int) -> tuple[str, ...]:
73
- return self.stops if direction == 0 else tuple(reversed(self.stops))
74
-
75
- def terminus_for(self, direction: int) -> str:
76
- return self.stops_for(direction)[-1]
77
-
78
-
79
- @dataclass(frozen=True)
80
- class Edge:
81
- target: Node
82
- kind: str # "ride" or "transfer"
83
- minutes: float
84
- distance_m: float | None = None
85
- walk_minutes: float = 0.0
86
- walk_distance_m: float | None = None
87
- transfer_penalty: float = 0.0
88
- estimated: bool = False # durée forfaitaire, pas de distance connue
89
-
90
-
91
- def _number(value: object) -> float | None:
92
- """Convert a CSV value to a coordinate, or None when it is missing."""
93
-
94
- try:
95
- number = float(value)
96
- except (TypeError, ValueError):
97
- return None
98
- return None if math.isnan(number) else number
99
-
100
-
101
- def haversine_m(
102
- a: tuple[float, float],
103
- b: tuple[float, float],
104
- ) -> float:
105
- """Great-circle distance in metres."""
106
-
107
- lat1, lon1 = map(math.radians, a)
108
- lat2, lon2 = map(math.radians, b)
109
- dlat = lat2 - lat1
110
- dlon = lon2 - lon1
111
- h = (
112
- math.sin(dlat / 2) ** 2
113
- + math.cos(lat1) * math.cos(lat2) * math.sin(dlon / 2) ** 2
114
- )
115
- return 2 * 6_371_000 * math.asin(math.sqrt(h))
116
-
117
-
118
- def interpolate_missing_coordinates(
119
- lines: Iterable[Line],
120
- stop_coords: dict[str, tuple[float, float]],
121
- stop_confidence: dict[str, str] | None = None,
122
- passes: int = 3,
123
- ) -> tuple[dict[str, tuple[float, float]], dict[str, str]]:
124
- """Place unlocated stops between the located stops around them.
125
-
126
- L'arrêt prend la position linéaire entre l'arrêt géolocalisé qui le
127
- précède et celui qui le suit sur la ligne. Si plusieurs lignes le
128
- desservent, on moyenne leurs propositions. Les trois passes permettent
129
- à un arrêt interpolé sur une ligne de servir d'ancre sur une autre.
130
- """
131
-
132
- coords = dict(stop_coords)
133
- confidence = dict(stop_confidence or {})
134
-
135
- for _ in range(max(1, passes)):
136
- proposals: dict[str, list[tuple[float, float]]] = defaultdict(list)
137
- for line in lines:
138
- stops = line.stops
139
- for index, stop in enumerate(stops):
140
- if stop in coords:
141
- continue
142
-
143
- previous = None
144
- for before in range(index - 1, -1, -1):
145
- if stops[before] in coords:
146
- previous = before
147
- break
148
- following = None
149
- for after in range(index + 1, len(stops)):
150
- if stops[after] in coords:
151
- following = after
152
- break
153
- if previous is None or following is None:
154
- continue
155
-
156
- ratio = (index - previous) / (following - previous)
157
- start = coords[stops[previous]]
158
- end = coords[stops[following]]
159
- proposals[stop].append(
160
- (
161
- start[0] + (end[0] - start[0]) * ratio,
162
- start[1] + (end[1] - start[1]) * ratio,
163
- )
164
- )
165
-
166
- if not proposals:
167
- break
168
- for stop, points in proposals.items():
169
- if stop in coords:
170
- continue
171
- coords[stop] = (
172
- sum(point[0] for point in points) / len(points),
173
- sum(point[1] for point in points) / len(points),
174
- )
175
- confidence[stop] = "interpolee"
176
-
177
- return coords, confidence
178
-
179
-
180
- def _name_tokens(name: str) -> set[str]:
181
- return {
182
- token
183
- for token in normalize_name(name).split()
184
- if token not in _GENERIC_TOKENS and not token.isdigit()
185
- }
186
-
187
-
188
- def _legacy_stops(
189
- data,
190
- lines: list[Line],
191
- stop_coords: dict[str, tuple[float, float]],
192
- stop_confidence: dict[str, str],
193
- ) -> dict[str, str]:
194
- """Ancien nom bien situé -> arrêt officiel le plus proche de la même zone.
195
-
196
- Une position interpolée ne désigne jamais de zone, ni un ancien nom douteux :
197
- mieux vaut ne pas répondre que répondre à côté.
198
- """
199
-
200
- current = {stop for line in lines for stop in line.stops}
201
- norms = {normalize_name(stop) for stop in current}
202
- located = [
203
- (stop, stop_coords[stop], _name_tokens(stop))
204
- for stop in current
205
- if stop in stop_coords and stop_confidence.get(stop) in {"bonne", "estimee"}
206
- ]
207
-
208
- legacy: dict[str, str] = {}
209
- for row in data.arrets.itertuples(index=False):
210
- name = str(row.arret)
211
- if (
212
- normalize_name(name) in norms
213
- or getattr(row, "confiance", None) != "bonne"
214
- ):
215
- continue
216
- lat, lon = _number(row.lat), _number(row.lon)
217
- if lat is None or lon is None:
218
- continue
219
- tokens = _name_tokens(name)
220
- best: tuple[bool, float, str] | None = None
221
- for stop, coords, stop_tokens in located:
222
- distance = haversine_m((lat, lon), coords)
223
- same_area = bool(tokens & stop_tokens)
224
- limit = (
225
- LEGACY_SAME_NAME_RADIUS_M if same_area else LEGACY_ANY_NAME_RADIUS_M
226
- )
227
- if distance > limit:
228
- continue
229
- candidate = (not same_area, distance, stop)
230
- if best is None or candidate < best:
231
- best = candidate
232
- if best is not None:
233
- legacy[name] = best[2]
234
- return legacy
235
-
236
-
237
- class Network:
238
- def __init__(
239
- self,
240
- lines: Iterable[Line],
241
- stop_coords: dict[str, tuple[float, float]],
242
- stop_confidence: dict[str, str] | None = None,
243
- line_positions: dict[LineKey, tuple] | None = None,
244
- line_distances: dict[LineKey, tuple] | None = None,
245
- legacy_stops: dict[str, str] | None = None,
246
- ) -> None:
247
- self.lines = {line.key: line for line in lines}
248
- self.stop_coords = dict(stop_coords)
249
- self.stop_confidence = dict(stop_confidence or {})
250
- # Position de chaque arrêt sur sa ligne, et longueur mesurée sur la trace.
251
- self.line_positions = dict(line_positions or {})
252
- self.line_distances = dict(line_distances or {})
253
- self.stop_names = sorted(
254
- {stop for line in self.lines.values() for stop in line.stops}
255
- )
256
-
257
- self._nodes_at_stop: dict[str, list[Node]] = defaultdict(list)
258
- self._nodes_at_norm: dict[str, list[Node]] = defaultdict(list)
259
- self._stops_by_norm: dict[str, list[str]] = defaultdict(list)
260
- self._all_nodes: list[Node] = []
261
-
262
- for line in self.lines.values():
263
- for direction in (0, 1):
264
- sequence = line.stops_for(direction)
265
- for index, stop in enumerate(sequence):
266
- node = Node(line.key, direction, index)
267
- self._all_nodes.append(node)
268
- self._nodes_at_stop[stop].append(node)
269
- self._nodes_at_norm[normalize_name(stop)].append(node)
270
-
271
- for stop in self.stop_names:
272
- self._stops_by_norm[normalize_name(stop)].append(stop)
273
-
274
- # « Dieuppeul » et « Liberté 5 » mènent aussi à « Terminus liberté 5
275
- # (Dieuppeul) », sans en faire le même arrêt pour les correspondances.
276
- for stop in self.stop_names:
277
- for form in terminus_forms(stop):
278
- names = self._stops_by_norm[normalize_name(form)]
279
- if stop not in names:
280
- names.append(stop)
281
- for old_name, stop in (legacy_stops or {}).items():
282
- normalized = normalize_name(old_name)
283
- if not self._stops_by_norm.get(normalized):
284
- self._stops_by_norm[normalized] = [stop]
285
-
286
- self._adjacency: dict[Node, list[Edge]] | None = None
287
-
288
- # ------------------------------------------------------------------
289
- # Small accessors used by the router and the CLI.
290
- # ------------------------------------------------------------------
291
- @property
292
- def all_nodes(self) -> list[Node]:
293
- return self._all_nodes
294
-
295
- def line_for(self, node: Node) -> Line:
296
- return self.lines[node.line]
297
-
298
- def stop_for(self, node: Node) -> str:
299
- return self.line_for(node).stops_for(node.direction)[node.index]
300
-
301
- def terminus_for(self, node: Node) -> str:
302
- return self.line_for(node).terminus_for(node.direction)
303
-
304
- def nodes_at_stop(self, stop: str) -> list[Node]:
305
- return self._nodes_at_stop.get(stop, [])
306
-
307
- def nodes_at_normalized(self, normalized: str) -> list[Node]:
308
- return self._nodes_at_norm.get(normalized, [])
309
-
310
- def stops_for_normalized(self, normalized: str) -> list[str]:
311
- return list(self._stops_by_norm.get(normalized, ()))
312
-
313
- def coords(self, stop: str) -> tuple[float, float] | None:
314
- return self.stop_coords.get(stop)
315
-
316
- @property
317
- def downtown_centre(self) -> tuple[float, float] | None:
318
- """Approximate the city centre with the Palais stops."""
319
-
320
- points = [
321
- self.stop_coords[name]
322
- for name in ("Palais 1", "Palais 2", "Palais")
323
- if name in self.stop_coords
324
- ]
325
- if not points:
326
- return None
327
- return (
328
- sum(point[0] for point in points) / len(points),
329
- sum(point[1] for point in points) / len(points),
330
- )
331
-
332
- # ------------------------------------------------------------------
333
- # Graph construction.
334
- # ------------------------------------------------------------------
335
- @property
336
- def adjacency(self) -> dict[Node, list[Edge]]:
337
- if self._adjacency is None:
338
- self._adjacency = self._build_adjacency()
339
- return self._adjacency
340
-
341
- def position_on_line(self, line: Line, index: int) -> tuple[float, float] | None:
342
- """La position de cet arrêt sur cette ligne (sa position générale par défaut)."""
343
-
344
- positions = self.line_positions.get(line.key)
345
- if positions is not None:
346
- return positions[index]
347
- return self.coords(line.stops[index])
348
-
349
- def _segment_distances(self, line: Line) -> tuple[float | None, ...]:
350
- """Longueur de chaque segment, dans l'ordre de la ligne.
351
-
352
- La trace d'abord, sinon les distances entre arrêts consécutifs. Un arrêt
353
- sans position est sauté : la distance entre ses deux voisins est partagée.
354
- """
355
-
356
- mesurees = self.line_distances.get(line.key)
357
- if mesurees is not None:
358
- return mesurees
359
-
360
- positions = [
361
- self.position_on_line(line, index) for index in range(len(line.stops))
362
- ]
363
- connus = [i for i, position in enumerate(positions) if position is not None]
364
- segments: list[float | None] = [None] * (len(positions) - 1)
365
- for gauche, droite in zip(connus, connus[1:]):
366
- part = haversine_m(positions[gauche], positions[droite]) / (droite - gauche)
367
- for index in range(gauche, droite):
368
- segments[index] = part
369
- return tuple(segments)
370
-
371
- @staticmethod
372
- def _ride_estimate(
373
- distance: float | None,
374
- stops_on_line: int,
375
- company: str = "",
376
- ) -> float:
377
- if distance is None:
378
- if stops_on_line == 2:
379
- return UNKNOWN_TWO_STOP_RIDE_MINUTES
380
- return FIXED_MINUTES_PER_SEGMENT
381
- speed = SPEED_BY_COMPANY_M_PER_MIN.get(company, BUS_SPEED_M_PER_MIN)
382
- return max(0.5, distance / speed)
383
-
384
- def _build_adjacency(self) -> dict[Node, list[Edge]]:
385
- adjacency: dict[Node, list[Edge]] = {
386
- node: [] for node in self._all_nodes
387
- }
388
-
389
- # Ride along the ordered stops, in both directions.
390
- for line in self.lines.values():
391
- forward = self._segment_distances(line)
392
- for direction in (0, 1):
393
- sequence = line.stops_for(direction)
394
- distances = forward if direction == 0 else forward[::-1]
395
- for index in range(len(sequence) - 1):
396
- source = Node(line.key, direction, index)
397
- target = Node(line.key, direction, index + 1)
398
- distance = distances[index]
399
- minutes = self._ride_estimate(
400
- distance, len(sequence), line.company
401
- )
402
- adjacency[source].append(
403
- Edge(
404
- target=target,
405
- kind="ride",
406
- minutes=minutes,
407
- distance_m=distance,
408
- estimated=distance is None and len(sequence) == 2,
409
- )
410
- )
411
-
412
- # Transfers at the same normalized stop name. This also joins
413
- # spellings such as "Sahm" and "SAHM".
414
- # Deux lignes peuvent donner le même nom à deux endroits éloignés : « VDN » est
415
- # une avenue de 15 km, et Tata 37 y passe loin de TAF TAF. Sans ce contrôle,
416
- # on changeait de bus à « VDN » en se téléportant vers Malika.
417
- def node_position(node: Node) -> tuple[float, float] | None:
418
- line = self.lines[node.line]
419
- index = (
420
- node.index
421
- if node.direction == 0
422
- else len(line.stops) - 1 - node.index
423
- )
424
- return self.position_on_line(line, index)
425
-
426
- for nodes in self._nodes_at_norm.values():
427
- positions = {node: node_position(node) for node in nodes}
428
- for source in nodes:
429
- for target in nodes:
430
- if source == target or source.line == target.line:
431
- continue
432
- here, there = positions[source], positions[target]
433
- if (
434
- here is not None
435
- and there is not None
436
- and haversine_m(here, there) > SAME_NAME_MAX_APART_M
437
- ):
438
- continue
439
- adjacency[source].append(
440
- Edge(
441
- target=target,
442
- kind="transfer",
443
- minutes=TRANSFER_PENALTY_MIN,
444
- walk_minutes=0.0,
445
- walk_distance_m=0.0,
446
- transfer_penalty=TRANSFER_PENALTY_MIN,
447
- )
448
- )
449
-
450
- # Short walking transfers between different stop names: only the closest
451
- # stop pairs of each pair of lines.
452
- lines_at_stop: dict[str, set[LineKey]] = defaultdict(set)
453
- nodes_on_line: dict[tuple[LineKey, str], list[Node]] = defaultdict(list)
454
- for stop, nodes in self._nodes_at_stop.items():
455
- for node in nodes:
456
- lines_at_stop[stop].add(node.line)
457
- nodes_on_line[(node.line, stop)].append(node)
458
-
459
- def position_for(line: LineKey, stop: str) -> tuple[float, float] | None:
460
- first = min(
461
- (node for node in nodes_on_line[(line, stop)] if node.direction == 0),
462
- key=lambda node: node.index,
463
- )
464
- return self.position_on_line(self.lines[line], first.index)
465
-
466
- by_line_pair: dict[
467
- tuple[LineKey, LineKey], list[tuple[float, str, str]]
468
- ] = defaultdict(list)
469
- stops_with_coords = [
470
- stop for stop in self.stop_names if stop in self.stop_coords
471
- ]
472
- for left_index, left_stop in enumerate(stops_with_coords):
473
- left_norm = normalize_name(left_stop)
474
- for right_stop in stops_with_coords[left_index + 1 :]:
475
- if normalize_name(right_stop) == left_norm:
476
- continue
477
- distance = haversine_m(
478
- self.stop_coords[left_stop], self.stop_coords[right_stop]
479
- )
480
- if distance > MAX_TRANSFER_WALK_M:
481
- continue
482
- for left_line in lines_at_stop[left_stop]:
483
- for right_line in lines_at_stop[right_stop]:
484
- # Là où chaque ligne passe vraiment : une position générale
485
- # fausse mettait Pikine Texaco (Tata 80) à côté de Ngor.
486
- left_here = position_for(left_line, left_stop)
487
- right_here = position_for(right_line, right_stop)
488
- if (
489
- left_here is None
490
- or right_here is None
491
- or haversine_m(left_here, right_here) > MAX_TRANSFER_WALK_M
492
- ):
493
- continue
494
- if left_line < right_line:
495
- by_line_pair[(left_line, right_line)].append(
496
- (distance, left_stop, right_stop)
497
- )
498
- elif right_line < left_line:
499
- by_line_pair[(right_line, left_line)].append(
500
- (distance, right_stop, left_stop)
501
- )
502
-
503
- for (first_line, second_line), candidates in by_line_pair.items():
504
- closest = heapq.nsmallest(MAX_WALK_TRANSFERS_PER_LINE_PAIR, candidates)
505
- for distance, first_stop, second_stop in closest:
506
- walk_minutes = distance / WALK_SPEED_M_PER_MIN
507
- cost = TRANSFER_PENALTY_MIN + walk_minutes
508
- for source in nodes_on_line[(first_line, first_stop)]:
509
- for target in nodes_on_line[(second_line, second_stop)]:
510
- for start, end in ((source, target), (target, source)):
511
- adjacency[start].append(
512
- Edge(
513
- target=end,
514
- kind="transfer",
515
- minutes=cost,
516
- walk_minutes=walk_minutes,
517
- walk_distance_m=distance,
518
- transfer_penalty=TRANSFER_PENALTY_MIN,
519
- )
520
- )
521
-
522
- # If the same (source, target) node pair was reached twice, keep
523
- # the cheapest way to make that change.
524
- for source, edges in adjacency.items():
525
- cheapest: dict[Node, Edge] = {}
526
- for edge in edges:
527
- current = cheapest.get(edge.target)
528
- if current is None or (edge.minutes, edge.walk_minutes) < (
529
- current.minutes,
530
- current.walk_minutes,
531
- ):
532
- cheapest[edge.target] = edge
533
- adjacency[source] = list(cheapest.values())
534
-
535
- return adjacency
536
-
537
- # ------------------------------------------------------------------
538
- # Loading the real data.
539
- # ------------------------------------------------------------------
540
- @classmethod
541
- def from_data(cls, data, corrections_path=None) -> "Network":
542
- termini: dict[LineKey, tuple[str | None, str | None]] = {}
543
- for row in data.lignes.itertuples(index=False):
544
- key = (str(row.compagnie), str(row.ligne))
545
- if key not in termini:
546
- termini[key] = (str(row.terminus_a), str(row.terminus_b))
547
-
548
- lines: list[Line] = []
549
- line_orders: dict[LineKey, list[int]] = {}
550
- grouped = data.itineraires.groupby(["compagnie", "ligne"], sort=False)
551
- for (company, name), group in grouped:
552
- ordered = group.sort_values("ordre")
553
- stops = tuple(str(stop) for stop in ordered["arret"])
554
- if len(stops) < 2:
555
- continue
556
- line_orders[(str(company), str(name))] = [
557
- int(ordre) for ordre in ordered["ordre"]
558
- ]
559
- terminus_a, terminus_b = termini.get(
560
- (str(company), str(name)), (None, None)
561
- )
562
- lines.append(
563
- Line(
564
- company=str(company),
565
- name=str(name),
566
- stops=stops,
567
- terminus_a=terminus_a,
568
- terminus_b=terminus_b,
569
- )
570
- )
571
-
572
- # Field corrections are layered on top of the downloaded itinerary
573
- # before coordinates and graph nodes are built.
574
- from .corrections import apply_corrections, load_corrections
575
-
576
- known_stops = {
577
- str(row.arret) for row in data.arrets.itertuples(index=False)
578
- }
579
- known_stops.update(
580
- stop for line in lines for stop in line.stops
581
- )
582
- corrected = apply_corrections(
583
- lines,
584
- load_corrections(corrections_path),
585
- known_stops,
586
- )
587
- lines = corrected.lines
588
-
589
- stop_coords: dict[str, tuple[float, float]] = {}
590
- stop_confidence: dict[str, str] = {}
591
- for row in data.arrets.itertuples(index=False):
592
- stop = str(row.arret)
593
- if stop not in stop_coords:
594
- lat = _number(row.lat)
595
- lon = _number(row.lon)
596
- if lat is not None and lon is not None:
597
- stop_coords[stop] = (lat, lon)
598
- confidence = getattr(row, "confiance", None)
599
- if isinstance(confidence, str) and stop not in stop_confidence:
600
- stop_confidence[stop] = confidence
601
-
602
- # Some stops in itineraires have no coordinate row of their own.
603
- # If a place with the same normalized name exists in lieux_geo,
604
- # borrow its position. This is still only a best effort.
605
- place_coords: dict[str, tuple[float, float]] = {}
606
- for row in data.lieux.itertuples(index=False):
607
- lat = _number(row.lat)
608
- lon = _number(row.lon)
609
- if lat is None or lon is None:
610
- continue
611
- normalized = normalize_name(row.lieu)
612
- place_coords.setdefault(normalized, (lat, lon))
613
-
614
- for stop in {stop for line in lines for stop in line.stops}:
615
- if stop in stop_coords:
616
- continue
617
- borrowed = place_coords.get(normalize_name(stop))
618
- if borrowed is not None:
619
- stop_coords[stop] = borrowed
620
- stop_confidence.setdefault(stop, "estimee")
621
-
622
- # Une position fiable sur une ligne situe aussi un arrêt qui n'en avait pas
623
- # de bonne (« Sandaga », « Point E », nouveaux noms officiels de Dem Dikk).
624
- by_order = getattr(data, "positions_ligne", {})
625
- sure_by_order = getattr(data, "positions_sures", {})
626
- raw_positions: dict[LineKey, list] = {}
627
- proposals: dict[str, list[tuple[tuple[float, float], bool]]] = defaultdict(list)
628
- for line in lines:
629
- orders = line_orders.get(line.key)
630
- per_line = by_order.get(line.key)
631
- if not per_line or orders is None or len(orders) != len(line.stops):
632
- continue
633
- raw_positions[line.key] = [per_line.get(ordre, ...) for ordre in orders]
634
- for stop, ordre in zip(line.stops, orders):
635
- position = per_line.get(ordre)
636
- if position is not None:
637
- proposals[stop].append(
638
- (position, sure_by_order.get(line.key, {}).get(ordre, False))
639
- )
640
-
641
- # Une ligne seule ne déplace pas un arrêt pour tout le réseau : sa position
642
- # peut être fausse (Tata 35 met Pikine Texaco près de Ngor, ce qui créait une
643
- # correspondance à pied entre les deux). Il faut deux lignes d'accord, ou
644
- # que l'arrêt n'ait encore aucune position. Si toutes les lignes qui le
645
- # desservent s'accordent, elles priment même sur une position « bonne » :
646
- # AIBD, seulement sur TAF TAF, restait à Grand Yoff dans arrets_geo.csv.
647
- served = Counter(stop for line in lines for stop in line.stops)
648
- for stop, proposed in proposals.items():
649
- position, sure, supporters = max(
650
- (
651
- (
652
- candidate,
653
- is_sure,
654
- sum(
655
- haversine_m(candidate, other) <= POSITION_AGREEMENT_M
656
- for other, _ in proposed
657
- ),
658
- )
659
- for candidate, is_sure in proposed
660
- ),
661
- key=lambda item: (item[2], item[1]),
662
- )
663
- if stop not in stop_coords:
664
- stop_coords[stop] = position
665
- stop_confidence[stop] = (
666
- "bonne" if sure and supporters >= 2 else "estimee"
667
- )
668
- elif (
669
- supporters == len(proposed) == served[stop]
670
- and haversine_m(position, stop_coords[stop]) > POSITION_AGREEMENT_M
671
- ):
672
- stop_coords[stop] = position
673
- stop_confidence[stop] = "bonne" if sure else "estimee"
674
- elif (
675
- sure
676
- and supporters >= 2
677
- and stop_confidence.get(stop) != "bonne"
678
- ):
679
- stop_coords[stop] = position
680
- stop_confidence[stop] = "bonne"
681
-
682
- # Les arrêts restants sont placés à vol d'oiseau le long de leur
683
- # ligne, uniquement en mémoire : les CSV ne sont jamais modifiés.
684
- stop_coords, stop_confidence = interpolate_missing_coordinates(
685
- lines, stop_coords, stop_confidence
686
- )
687
-
688
- # Sur chaque ligne : sa propre position si elle en a une, None si elle est
689
- # connue pour être inconnue, sinon la position générale de l'arrêt.
690
- line_positions = {
691
- key: tuple(
692
- stop_coords.get(stop) if position is ... else position
693
- for stop, position in zip(by_key[key].stops, positions)
694
- )
695
- for by_key in [{line.key: line for line in lines}]
696
- for key, positions in raw_positions.items()
697
- }
698
-
699
- # La vraie longueur de route pour les lignes Tata qui ont une trace.
700
- line_distances: dict[LineKey, tuple] = {}
701
- traces = getattr(data, "traces", {})
702
- for line in lines:
703
- trace = traces.get(line.name) if line.company == "Tata AFTU" else None
704
- if not trace:
705
- continue
706
- positions = line_positions.get(line.key) or tuple(
707
- stop_coords.get(stop) for stop in line.stops
708
- )
709
- measured = distances_sur_trace(trace, positions)
710
- if measured is not None:
711
- line_distances[line.key] = measured
712
-
713
- return cls(
714
- lines,
715
- stop_coords,
716
- stop_confidence,
717
- line_positions,
718
- line_distances,
719
- _legacy_stops(data, lines, stop_coords, stop_confidence),
720
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The Dakar bus graph.
2
+
3
+ A node is a stop **as seen by one line in one direction**. Keeping the
4
+ direction in the node is what lets the router produce a proper leg with a
5
+ terminus ("towards Palais 2") instead of just a pair of stop names.
6
+
7
+ Each line is usable in both directions. Ride edges follow the ordered
8
+ itinerary; transfer edges connect different lines at the same normalized
9
+ stop name, or at two stops within 500 m.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import heapq
15
+ import math
16
+ from collections import Counter, defaultdict
17
+ from dataclasses import dataclass
18
+ from typing import Iterable, NamedTuple
19
+
20
+ from .places import _GENERIC_TOKENS, normalize_name, terminus_forms
21
+ from .traces import distances_sur_trace
22
+
23
+ # Modeling constants. They are deliberately simple and easy to tune.
24
+ # Vitesse commerciale, sur de vraies longueurs de route. Sur le terrain, les bus
25
+ # Dem Dikk roulent nettement plus vite que les Tata, qui s'arrêtent partout.
26
+ SPEED_BY_COMPANY_M_PER_MIN = {
27
+ "Dakar Dem Dikk": 333.0, # 20 km/h
28
+ "Tata AFTU": 250.0, # 15 km/h
29
+ }
30
+ # La plus rapide : la recherche guidée s'en sert pour ne jamais surestimer le
31
+ # temps restant. Une compagnie inconnue roule à cette vitesse aussi.
32
+ BUS_SPEED_M_PER_MIN = max(SPEED_BY_COMPANY_M_PER_MIN.values())
33
+ FIXED_MINUTES_PER_SEGMENT = 3.0 # fallback when a stop has no coordinates
34
+ # Une ligne réduite à ses deux terminus, dont l'un sans position, n'a aucun
35
+ # arrêt pour borner la distance : Dem Dikk 11 (Keur Massar -> Lat Dior) coûtait
36
+ # 3 min et devenait une téléportation à travers toute la ville.
37
+ UNKNOWN_TWO_STOP_RIDE_MINUTES = 35.0
38
+ TRANSFER_PENALTY_MIN = 6.0 # waiting / walking to the next line
39
+ WALK_SPEED_M_PER_MIN = 80.0
40
+ # Une correspondance à pied ne dépasse pas 400 m (5 min) : au-delà, l'usager
41
+ # ne retrouve plus l'arrêt du bus suivant sans aide.
42
+ MAX_TRANSFER_WALK_M = 400.0
43
+ # Correspondances à pied gardées pour deux lignes données : les plus courtes. Toutes
44
+ # les garder faisait 126 000 arêtes et jusqu'à 44 s par requête, sans bus direct.
45
+ MAX_WALK_TRANSFERS_PER_LINE_PAIR = 2
46
+ # Un ancien nom absent des listes officielles (« Cambérène 2 ») vaut l'arrêt officiel
47
+ # le plus proche : portant le même nom de quartier, ou tout près s'il n'y en a pas.
48
+ LEGACY_SAME_NAME_RADIUS_M = 2_000.0
49
+ LEGACY_ANY_NAME_RADIUS_M = 500.0
50
+ POSITION_AGREEMENT_M = 500.0
51
+ SAME_NAME_MAX_APART_M = 1_000.0
52
+
53
+ LineKey = tuple[str, str] # (operator, line name)
54
+
55
+
56
+ class Node(NamedTuple):
57
+ line: LineKey
58
+ direction: int # 0 = itinerary order, 1 = reversed
59
+ index: int
60
+
61
+
62
+ @dataclass(frozen=True)
63
+ class Line:
64
+ company: str
65
+ name: str
66
+ stops: tuple[str, ...]
67
+ terminus_a: str | None = None
68
+ terminus_b: str | None = None
69
+
70
+ @property
71
+ def key(self) -> LineKey:
72
+ return (self.company, self.name)
73
+
74
+ def stops_for(self, direction: int) -> tuple[str, ...]:
75
+ return self.stops if direction == 0 else tuple(reversed(self.stops))
76
+
77
+ def terminus_for(self, direction: int) -> str:
78
+ return self.stops_for(direction)[-1]
79
+
80
+
81
+ @dataclass(frozen=True)
82
+ class Edge:
83
+ target: Node
84
+ kind: str # "ride" or "transfer"
85
+ minutes: float
86
+ distance_m: float | None = None
87
+ walk_minutes: float = 0.0
88
+ walk_distance_m: float | None = None
89
+ transfer_penalty: float = 0.0
90
+ estimated: bool = False # durée forfaitaire, pas de distance connue
91
+
92
+
93
+ def _number(value: object) -> float | None:
94
+ """Convert a CSV value to a coordinate, or None when it is missing."""
95
+
96
+ try:
97
+ number = float(value)
98
+ except (TypeError, ValueError):
99
+ return None
100
+ return None if math.isnan(number) else number
101
+
102
+
103
+ def haversine_m(
104
+ a: tuple[float, float],
105
+ b: tuple[float, float],
106
+ ) -> float:
107
+ """Great-circle distance in metres."""
108
+
109
+ lat1, lon1 = map(math.radians, a)
110
+ lat2, lon2 = map(math.radians, b)
111
+ dlat = lat2 - lat1
112
+ dlon = lon2 - lon1
113
+ h = (
114
+ math.sin(dlat / 2) ** 2
115
+ + math.cos(lat1) * math.cos(lat2) * math.sin(dlon / 2) ** 2
116
+ )
117
+ return 2 * 6_371_000 * math.asin(math.sqrt(h))
118
+
119
+
120
+ def interpolate_missing_coordinates(
121
+ lines: Iterable[Line],
122
+ stop_coords: dict[str, tuple[float, float]],
123
+ stop_confidence: dict[str, str] | None = None,
124
+ passes: int = 3,
125
+ ) -> tuple[dict[str, tuple[float, float]], dict[str, str]]:
126
+ """Place unlocated stops between the located stops around them.
127
+
128
+ L'arrêt prend la position linéaire entre l'arrêt géolocalisé qui le
129
+ précède et celui qui le suit sur la ligne. Si plusieurs lignes le
130
+ desservent, on moyenne leurs propositions. Les trois passes permettent
131
+ à un arrêt interpolé sur une ligne de servir d'ancre sur une autre.
132
+ """
133
+
134
+ coords = dict(stop_coords)
135
+ confidence = dict(stop_confidence or {})
136
+
137
+ for _ in range(max(1, passes)):
138
+ proposals: dict[str, list[tuple[float, float]]] = defaultdict(list)
139
+ for line in lines:
140
+ stops = line.stops
141
+ for index, stop in enumerate(stops):
142
+ if stop in coords:
143
+ continue
144
+
145
+ previous = None
146
+ for before in range(index - 1, -1, -1):
147
+ if stops[before] in coords:
148
+ previous = before
149
+ break
150
+ following = None
151
+ for after in range(index + 1, len(stops)):
152
+ if stops[after] in coords:
153
+ following = after
154
+ break
155
+ if previous is None or following is None:
156
+ continue
157
+
158
+ ratio = (index - previous) / (following - previous)
159
+ start = coords[stops[previous]]
160
+ end = coords[stops[following]]
161
+ proposals[stop].append(
162
+ (
163
+ start[0] + (end[0] - start[0]) * ratio,
164
+ start[1] + (end[1] - start[1]) * ratio,
165
+ )
166
+ )
167
+
168
+ if not proposals:
169
+ break
170
+ for stop, points in proposals.items():
171
+ if stop in coords:
172
+ continue
173
+ coords[stop] = (
174
+ sum(point[0] for point in points) / len(points),
175
+ sum(point[1] for point in points) / len(points),
176
+ )
177
+ confidence[stop] = "interpolee"
178
+
179
+ return coords, confidence
180
+
181
+
182
+ def _name_tokens(name: str) -> set[str]:
183
+ return {
184
+ token
185
+ for token in normalize_name(name).split()
186
+ if token not in _GENERIC_TOKENS and not token.isdigit()
187
+ }
188
+
189
+
190
+ def _legacy_stops(
191
+ data,
192
+ lines: list[Line],
193
+ stop_coords: dict[str, tuple[float, float]],
194
+ stop_confidence: dict[str, str],
195
+ ) -> dict[str, str]:
196
+ """Ancien nom bien situé -> arrêt officiel le plus proche de la même zone.
197
+
198
+ Une position interpolée ne désigne jamais de zone, ni un ancien nom douteux :
199
+ mieux vaut ne pas répondre que répondre à côté.
200
+ """
201
+
202
+ current = {stop for line in lines for stop in line.stops}
203
+ norms = {normalize_name(stop) for stop in current}
204
+ located = [
205
+ (stop, stop_coords[stop], _name_tokens(stop))
206
+ for stop in current
207
+ if stop in stop_coords and stop_confidence.get(stop) in {"bonne", "estimee"}
208
+ ]
209
+
210
+ legacy: dict[str, str] = {}
211
+ for row in data.arrets.itertuples(index=False):
212
+ name = str(row.arret)
213
+ if (
214
+ normalize_name(name) in norms
215
+ or getattr(row, "confiance", None) != "bonne"
216
+ ):
217
+ continue
218
+ lat, lon = _number(row.lat), _number(row.lon)
219
+ if lat is None or lon is None:
220
+ continue
221
+ tokens = _name_tokens(name)
222
+ best: tuple[bool, float, str] | None = None
223
+ for stop, coords, stop_tokens in located:
224
+ distance = haversine_m((lat, lon), coords)
225
+ same_area = bool(tokens & stop_tokens)
226
+ limit = (
227
+ LEGACY_SAME_NAME_RADIUS_M if same_area else LEGACY_ANY_NAME_RADIUS_M
228
+ )
229
+ if distance > limit:
230
+ continue
231
+ candidate = (not same_area, distance, stop)
232
+ if best is None or candidate < best:
233
+ best = candidate
234
+ if best is not None:
235
+ legacy[name] = best[2]
236
+ return legacy
237
+
238
+
239
+ class Network:
240
+ def __init__(
241
+ self,
242
+ lines: Iterable[Line],
243
+ stop_coords: dict[str, tuple[float, float]],
244
+ stop_confidence: dict[str, str] | None = None,
245
+ line_positions: dict[LineKey, tuple] | None = None,
246
+ line_distances: dict[LineKey, tuple] | None = None,
247
+ legacy_stops: dict[str, str] | None = None,
248
+ line_sure: dict[LineKey, tuple] | None = None,
249
+ ) -> None:
250
+ self.lines = {line.key: line for line in lines}
251
+ self.stop_coords = dict(stop_coords)
252
+ self.stop_confidence = dict(stop_confidence or {})
253
+ # Position de chaque arrêt sur sa ligne, et longueur mesurée sur la trace.
254
+ self.line_positions = dict(line_positions or {})
255
+ self.line_distances = dict(line_distances or {})
256
+ # Position mesurée (arrêt OSM, terminus officiel…) ou devinée
257
+ # (interpolation le long de la ligne) : seule la première peut porter
258
+ # une correspondance à pied ou borner une durée.
259
+ self.line_sure = dict(line_sure or {})
260
+ self.stop_names = sorted(
261
+ {stop for line in self.lines.values() for stop in line.stops}
262
+ )
263
+
264
+ self._nodes_at_stop: dict[str, list[Node]] = defaultdict(list)
265
+ self._nodes_at_norm: dict[str, list[Node]] = defaultdict(list)
266
+ self._stops_by_norm: dict[str, list[str]] = defaultdict(list)
267
+ self._all_nodes: list[Node] = []
268
+
269
+ for line in self.lines.values():
270
+ for direction in (0, 1):
271
+ sequence = line.stops_for(direction)
272
+ for index, stop in enumerate(sequence):
273
+ node = Node(line.key, direction, index)
274
+ self._all_nodes.append(node)
275
+ self._nodes_at_stop[stop].append(node)
276
+ self._nodes_at_norm[normalize_name(stop)].append(node)
277
+
278
+ for stop in self.stop_names:
279
+ self._stops_by_norm[normalize_name(stop)].append(stop)
280
+
281
+ # « Dieuppeul » et « Liberté 5 » mènent aussi à « Terminus liberté 5
282
+ # (Dieuppeul) », sans en faire le même arrêt pour les correspondances.
283
+ for stop in self.stop_names:
284
+ for form in terminus_forms(stop):
285
+ names = self._stops_by_norm[normalize_name(form)]
286
+ if stop not in names:
287
+ names.append(stop)
288
+ for old_name, stop in (legacy_stops or {}).items():
289
+ normalized = normalize_name(old_name)
290
+ if not self._stops_by_norm.get(normalized):
291
+ self._stops_by_norm[normalized] = [stop]
292
+
293
+ self._adjacency: dict[Node, list[Edge]] | None = None
294
+
295
+ # ------------------------------------------------------------------
296
+ # Small accessors used by the router and the CLI.
297
+ # ------------------------------------------------------------------
298
+ @property
299
+ def all_nodes(self) -> list[Node]:
300
+ return self._all_nodes
301
+
302
+ def line_for(self, node: Node) -> Line:
303
+ return self.lines[node.line]
304
+
305
+ def stop_for(self, node: Node) -> str:
306
+ return self.line_for(node).stops_for(node.direction)[node.index]
307
+
308
+ def terminus_for(self, node: Node) -> str:
309
+ return self.line_for(node).terminus_for(node.direction)
310
+
311
+ def nodes_at_stop(self, stop: str) -> list[Node]:
312
+ return self._nodes_at_stop.get(stop, [])
313
+
314
+ def nodes_at_normalized(self, normalized: str) -> list[Node]:
315
+ return self._nodes_at_norm.get(normalized, [])
316
+
317
+ def stops_for_normalized(self, normalized: str) -> list[str]:
318
+ return list(self._stops_by_norm.get(normalized, ()))
319
+
320
+ def coords(self, stop: str) -> tuple[float, float] | None:
321
+ return self.stop_coords.get(stop)
322
+
323
+ @property
324
+ def downtown_centre(self) -> tuple[float, float] | None:
325
+ """Approximate the city centre with the Palais stops."""
326
+
327
+ points = [
328
+ self.stop_coords[name]
329
+ for name in ("Palais 1", "Palais 2", "Palais")
330
+ if name in self.stop_coords
331
+ ]
332
+ if not points:
333
+ return None
334
+ return (
335
+ sum(point[0] for point in points) / len(points),
336
+ sum(point[1] for point in points) / len(points),
337
+ )
338
+
339
+ # ------------------------------------------------------------------
340
+ # Graph construction.
341
+ # ------------------------------------------------------------------
342
+ @property
343
+ def adjacency(self) -> dict[Node, list[Edge]]:
344
+ if self._adjacency is None:
345
+ self._adjacency = self._build_adjacency()
346
+ return self._adjacency
347
+
348
+ def position_on_line(self, line: Line, index: int) -> tuple[float, float] | None:
349
+ """La position de cet arrêt sur cette ligne (sa position générale par défaut)."""
350
+
351
+ positions = self.line_positions.get(line.key)
352
+ if positions is not None:
353
+ return positions[index]
354
+ return self.coords(line.stops[index])
355
+
356
+ def position_sure(self, line: Line, index: int) -> bool:
357
+ """Vrai si la position de cet arrêt sur cette ligne est mesurée, pas devinée.
358
+
359
+ « Marché Colobane Rufisque » (Tata 57), placé par interpolation sur
360
+ ZAC Mbao, faisait changer de bus « à 1 min à pied » de ZAC Mbao.
361
+ """
362
+
363
+ drapeaux = self.line_sure.get(line.key)
364
+ if drapeaux is not None:
365
+ return bool(drapeaux[index])
366
+ return self.stop_confidence.get(line.stops[index]) == "bonne"
367
+
368
+ def _plancher_vol_oiseau(
369
+ self, line: Line, segments: tuple[float | None, ...]
370
+ ) -> tuple[float | None, ...]:
371
+ """Une route n'est jamais plus courte que la ligne droite.
372
+
373
+ Entre deux arrêts aux positions sûres, la somme des segments est au
374
+ moins la distance à vol d'oiseau ; sinon les segments sont allongés
375
+ d'autant. Une trace projetée sur des arrêts mal placés donnait
376
+ « Route Nationale N°1 -> Marché Colobane Rufisque » en 7 min.
377
+ """
378
+
379
+ surs = [
380
+ index
381
+ for index in range(len(line.stops))
382
+ if self.position_sure(line, index)
383
+ and self.position_on_line(line, index) is not None
384
+ ]
385
+ resultat = list(segments)
386
+ for gauche, droite in zip(surs, surs[1:]):
387
+ morceau = resultat[gauche:droite]
388
+ if any(valeur is None for valeur in morceau):
389
+ continue
390
+ longueur = sum(morceau)
391
+ droite_m = haversine_m(
392
+ self.position_on_line(line, gauche),
393
+ self.position_on_line(line, droite),
394
+ )
395
+ if longueur <= 0 or longueur >= droite_m:
396
+ continue
397
+ facteur = droite_m / longueur
398
+ for index in range(gauche, droite):
399
+ resultat[index] = resultat[index] * facteur
400
+ return tuple(resultat)
401
+
402
+ def _segment_distances(self, line: Line) -> tuple[float | None, ...]:
403
+ """Longueur de chaque segment, dans l'ordre de la ligne.
404
+
405
+ La trace d'abord, sinon les distances entre arrêts consécutifs. Un arrêt
406
+ sans position est sauté : la distance entre ses deux voisins est partagée.
407
+ """
408
+
409
+ mesurees = self.line_distances.get(line.key)
410
+ if mesurees is not None:
411
+ return self._plancher_vol_oiseau(line, mesurees)
412
+
413
+ positions = [
414
+ self.position_on_line(line, index) for index in range(len(line.stops))
415
+ ]
416
+ connus = [i for i, position in enumerate(positions) if position is not None]
417
+ segments: list[float | None] = [None] * (len(positions) - 1)
418
+ for gauche, droite in zip(connus, connus[1:]):
419
+ part = haversine_m(positions[gauche], positions[droite]) / (droite - gauche)
420
+ for index in range(gauche, droite):
421
+ segments[index] = part
422
+ return self._plancher_vol_oiseau(line, tuple(segments))
423
+
424
+ @staticmethod
425
+ def _ride_estimate(
426
+ distance: float | None,
427
+ stops_on_line: int,
428
+ company: str = "",
429
+ ) -> float:
430
+ if distance is None:
431
+ if stops_on_line == 2:
432
+ return UNKNOWN_TWO_STOP_RIDE_MINUTES
433
+ return FIXED_MINUTES_PER_SEGMENT
434
+ speed = SPEED_BY_COMPANY_M_PER_MIN.get(company, BUS_SPEED_M_PER_MIN)
435
+ return max(0.5, distance / speed)
436
+
437
+ def _build_adjacency(self) -> dict[Node, list[Edge]]:
438
+ adjacency: dict[Node, list[Edge]] = {
439
+ node: [] for node in self._all_nodes
440
+ }
441
+
442
+ # Ride along the ordered stops, in both directions.
443
+ for line in self.lines.values():
444
+ forward = self._segment_distances(line)
445
+ for direction in (0, 1):
446
+ sequence = line.stops_for(direction)
447
+ distances = forward if direction == 0 else forward[::-1]
448
+ for index in range(len(sequence) - 1):
449
+ source = Node(line.key, direction, index)
450
+ target = Node(line.key, direction, index + 1)
451
+ distance = distances[index]
452
+ minutes = self._ride_estimate(
453
+ distance, len(sequence), line.company
454
+ )
455
+ adjacency[source].append(
456
+ Edge(
457
+ target=target,
458
+ kind="ride",
459
+ minutes=minutes,
460
+ distance_m=distance,
461
+ estimated=distance is None and len(sequence) == 2,
462
+ )
463
+ )
464
+
465
+ # Transfers at the same normalized stop name. This also joins
466
+ # spellings such as "Sahm" and "SAHM".
467
+ # Deux lignes peuvent donner le même nom à deux endroits éloignés : « VDN » est
468
+ # une avenue de 15 km, et Tata 37 y passe loin de TAF TAF. Sans ce contrôle,
469
+ # on changeait de bus à « VDN » en se téléportant vers Malika.
470
+ def node_position(node: Node) -> tuple[float, float] | None:
471
+ line = self.lines[node.line]
472
+ index = (
473
+ node.index
474
+ if node.direction == 0
475
+ else len(line.stops) - 1 - node.index
476
+ )
477
+ return self.position_on_line(line, index)
478
+
479
+ for nodes in self._nodes_at_norm.values():
480
+ positions = {node: node_position(node) for node in nodes}
481
+ for source in nodes:
482
+ for target in nodes:
483
+ if source == target or source.line == target.line:
484
+ continue
485
+ here, there = positions[source], positions[target]
486
+ if (
487
+ here is not None
488
+ and there is not None
489
+ and haversine_m(here, there) > SAME_NAME_MAX_APART_M
490
+ ):
491
+ continue
492
+ adjacency[source].append(
493
+ Edge(
494
+ target=target,
495
+ kind="transfer",
496
+ minutes=TRANSFER_PENALTY_MIN,
497
+ walk_minutes=0.0,
498
+ walk_distance_m=0.0,
499
+ transfer_penalty=TRANSFER_PENALTY_MIN,
500
+ )
501
+ )
502
+
503
+ # Short walking transfers between different stop names: only the closest
504
+ # stop pairs of each pair of lines.
505
+ lines_at_stop: dict[str, set[LineKey]] = defaultdict(set)
506
+ nodes_on_line: dict[tuple[LineKey, str], list[Node]] = defaultdict(list)
507
+ for stop, nodes in self._nodes_at_stop.items():
508
+ for node in nodes:
509
+ lines_at_stop[stop].add(node.line)
510
+ nodes_on_line[(node.line, stop)].append(node)
511
+
512
+ def position_for(line: LineKey, stop: str) -> tuple[float, float] | None:
513
+ first = min(
514
+ (node for node in nodes_on_line[(line, stop)] if node.direction == 0),
515
+ key=lambda node: node.index,
516
+ )
517
+ # Une position devinée ne fait jamais marcher l'usager : « péage »
518
+ # (Dem Dikk 213), interpolé entre Poste Thiaroye et Patte d'Oie,
519
+ # tombait « à 1 min » de Bountou Pikine.
520
+ if not self.position_sure(self.lines[line], first.index):
521
+ return None
522
+ return self.position_on_line(self.lines[line], first.index)
523
+
524
+ by_line_pair: dict[
525
+ tuple[LineKey, LineKey], list[tuple[float, str, str]]
526
+ ] = defaultdict(list)
527
+ stops_with_coords = [
528
+ stop for stop in self.stop_names if stop in self.stop_coords
529
+ ]
530
+ for left_index, left_stop in enumerate(stops_with_coords):
531
+ left_norm = normalize_name(left_stop)
532
+ for right_stop in stops_with_coords[left_index + 1 :]:
533
+ if normalize_name(right_stop) == left_norm:
534
+ continue
535
+ distance = haversine_m(
536
+ self.stop_coords[left_stop], self.stop_coords[right_stop]
537
+ )
538
+ if distance > MAX_TRANSFER_WALK_M:
539
+ continue
540
+ for left_line in lines_at_stop[left_stop]:
541
+ for right_line in lines_at_stop[right_stop]:
542
+ # Là où chaque ligne passe vraiment : une position générale
543
+ # fausse mettait Pikine Texaco (Tata 80) à côté de Ngor.
544
+ left_here = position_for(left_line, left_stop)
545
+ right_here = position_for(right_line, right_stop)
546
+ if (
547
+ left_here is None
548
+ or right_here is None
549
+ or haversine_m(left_here, right_here) > MAX_TRANSFER_WALK_M
550
+ ):
551
+ continue
552
+ if left_line < right_line:
553
+ by_line_pair[(left_line, right_line)].append(
554
+ (distance, left_stop, right_stop)
555
+ )
556
+ elif right_line < left_line:
557
+ by_line_pair[(right_line, left_line)].append(
558
+ (distance, right_stop, left_stop)
559
+ )
560
+
561
+ for (first_line, second_line), candidates in by_line_pair.items():
562
+ closest = heapq.nsmallest(MAX_WALK_TRANSFERS_PER_LINE_PAIR, candidates)
563
+ for distance, first_stop, second_stop in closest:
564
+ walk_minutes = distance / WALK_SPEED_M_PER_MIN
565
+ cost = TRANSFER_PENALTY_MIN + walk_minutes
566
+ for source in nodes_on_line[(first_line, first_stop)]:
567
+ for target in nodes_on_line[(second_line, second_stop)]:
568
+ for start, end in ((source, target), (target, source)):
569
+ adjacency[start].append(
570
+ Edge(
571
+ target=end,
572
+ kind="transfer",
573
+ minutes=cost,
574
+ walk_minutes=walk_minutes,
575
+ walk_distance_m=distance,
576
+ transfer_penalty=TRANSFER_PENALTY_MIN,
577
+ )
578
+ )
579
+
580
+ # If the same (source, target) node pair was reached twice, keep
581
+ # the cheapest way to make that change.
582
+ for source, edges in adjacency.items():
583
+ cheapest: dict[Node, Edge] = {}
584
+ for edge in edges:
585
+ current = cheapest.get(edge.target)
586
+ if current is None or (edge.minutes, edge.walk_minutes) < (
587
+ current.minutes,
588
+ current.walk_minutes,
589
+ ):
590
+ cheapest[edge.target] = edge
591
+ adjacency[source] = list(cheapest.values())
592
+
593
+ return adjacency
594
+
595
+ # ------------------------------------------------------------------
596
+ # Loading the real data.
597
+ # ------------------------------------------------------------------
598
+ @classmethod
599
+ def from_data(cls, data, corrections_path=None) -> "Network":
600
+ termini: dict[LineKey, tuple[str | None, str | None]] = {}
601
+ for row in data.lignes.itertuples(index=False):
602
+ key = (str(row.compagnie), str(row.ligne))
603
+ if key not in termini:
604
+ termini[key] = (str(row.terminus_a), str(row.terminus_b))
605
+
606
+ lines: list[Line] = []
607
+ line_orders: dict[LineKey, list[int]] = {}
608
+ grouped = data.itineraires.groupby(["compagnie", "ligne"], sort=False)
609
+ for (company, name), group in grouped:
610
+ ordered = group.sort_values("ordre")
611
+ stops = tuple(str(stop) for stop in ordered["arret"])
612
+ if len(stops) < 2:
613
+ continue
614
+ line_orders[(str(company), str(name))] = [
615
+ int(ordre) for ordre in ordered["ordre"]
616
+ ]
617
+ terminus_a, terminus_b = termini.get(
618
+ (str(company), str(name)), (None, None)
619
+ )
620
+ lines.append(
621
+ Line(
622
+ company=str(company),
623
+ name=str(name),
624
+ stops=stops,
625
+ terminus_a=terminus_a,
626
+ terminus_b=terminus_b,
627
+ )
628
+ )
629
+
630
+ # Field corrections are layered on top of the downloaded itinerary
631
+ # before coordinates and graph nodes are built.
632
+ from .corrections import apply_corrections, load_corrections
633
+
634
+ known_stops = {
635
+ str(row.arret) for row in data.arrets.itertuples(index=False)
636
+ }
637
+ known_stops.update(
638
+ stop for line in lines for stop in line.stops
639
+ )
640
+ corrected = apply_corrections(
641
+ lines,
642
+ load_corrections(corrections_path),
643
+ known_stops,
644
+ )
645
+ lines = corrected.lines
646
+
647
+ stop_coords: dict[str, tuple[float, float]] = {}
648
+ stop_confidence: dict[str, str] = {}
649
+ for row in data.arrets.itertuples(index=False):
650
+ stop = str(row.arret)
651
+ if stop not in stop_coords:
652
+ lat = _number(row.lat)
653
+ lon = _number(row.lon)
654
+ if lat is not None and lon is not None:
655
+ stop_coords[stop] = (lat, lon)
656
+ confidence = getattr(row, "confiance", None)
657
+ if isinstance(confidence, str) and stop not in stop_confidence:
658
+ stop_confidence[stop] = confidence
659
+
660
+ # Some stops in itineraires have no coordinate row of their own.
661
+ # If a place with the same normalized name exists in lieux_geo,
662
+ # borrow its position. This is still only a best effort.
663
+ place_coords: dict[str, tuple[float, float]] = {}
664
+ for row in data.lieux.itertuples(index=False):
665
+ lat = _number(row.lat)
666
+ lon = _number(row.lon)
667
+ if lat is None or lon is None:
668
+ continue
669
+ normalized = normalize_name(row.lieu)
670
+ place_coords.setdefault(normalized, (lat, lon))
671
+
672
+ for stop in {stop for line in lines for stop in line.stops}:
673
+ if stop in stop_coords:
674
+ continue
675
+ borrowed = place_coords.get(normalize_name(stop))
676
+ if borrowed is not None:
677
+ stop_coords[stop] = borrowed
678
+ stop_confidence.setdefault(stop, "estimee")
679
+
680
+ # Une position fiable sur une ligne situe aussi un arrêt qui n'en avait pas
681
+ # de bonne (« Sandaga », « Point E », nouveaux noms officiels de Dem Dikk).
682
+ by_order = getattr(data, "positions_ligne", {})
683
+ sure_by_order = getattr(data, "positions_sures", {})
684
+ raw_positions: dict[LineKey, list] = {}
685
+ raw_sure: dict[LineKey, list] = {}
686
+ proposals: dict[str, list[tuple[tuple[float, float], bool]]] = defaultdict(list)
687
+ for line in lines:
688
+ orders = line_orders.get(line.key)
689
+ per_line = by_order.get(line.key)
690
+ if not per_line or orders is None or len(orders) != len(line.stops):
691
+ continue
692
+ raw_positions[line.key] = [per_line.get(ordre, ...) for ordre in orders]
693
+ raw_sure[line.key] = [
694
+ sure_by_order.get(line.key, {}).get(ordre, ...) for ordre in orders
695
+ ]
696
+ for stop, ordre in zip(line.stops, orders):
697
+ position = per_line.get(ordre)
698
+ if position is not None:
699
+ proposals[stop].append(
700
+ (position, sure_by_order.get(line.key, {}).get(ordre, False))
701
+ )
702
+
703
+ # Une ligne seule ne déplace pas un arrêt pour tout le réseau : sa position
704
+ # peut être fausse (Tata 35 met Pikine Texaco près de Ngor, ce qui créait une
705
+ # correspondance à pied entre les deux). Il faut deux lignes d'accord, ou
706
+ # que l'arrêt n'ait encore aucune position. Si toutes les lignes qui le
707
+ # desservent s'accordent, elles priment même sur une position « bonne » :
708
+ # AIBD, seulement sur TAF TAF, restait à Grand Yoff dans arrets_geo.csv.
709
+ served = Counter(stop for line in lines for stop in line.stops)
710
+ for stop, proposed in proposals.items():
711
+ position, sure, supporters = max(
712
+ (
713
+ (
714
+ candidate,
715
+ is_sure,
716
+ sum(
717
+ haversine_m(candidate, other) <= POSITION_AGREEMENT_M
718
+ for other, _ in proposed
719
+ ),
720
+ )
721
+ for candidate, is_sure in proposed
722
+ ),
723
+ key=lambda item: (item[2], item[1]),
724
+ )
725
+ if stop not in stop_coords:
726
+ stop_coords[stop] = position
727
+ stop_confidence[stop] = (
728
+ "bonne" if sure and supporters >= 2 else "estimee"
729
+ )
730
+ elif (
731
+ supporters == len(proposed) == served[stop]
732
+ and haversine_m(position, stop_coords[stop]) > POSITION_AGREEMENT_M
733
+ ):
734
+ stop_coords[stop] = position
735
+ stop_confidence[stop] = "bonne" if sure else "estimee"
736
+ elif (
737
+ sure
738
+ and supporters >= 2
739
+ and stop_confidence.get(stop) != "bonne"
740
+ ):
741
+ stop_coords[stop] = position
742
+ stop_confidence[stop] = "bonne"
743
+
744
+ # Les arrêts restants sont placés à vol d'oiseau le long de leur
745
+ # ligne, uniquement en mémoire : les CSV ne sont jamais modifiés.
746
+ stop_coords, stop_confidence = interpolate_missing_coordinates(
747
+ lines, stop_coords, stop_confidence
748
+ )
749
+
750
+ # Sur chaque ligne : sa propre position si elle en a une, None si elle est
751
+ # connue pour être inconnue, sinon la position générale de l'arrêt.
752
+ line_positions = {
753
+ key: tuple(
754
+ stop_coords.get(stop) if position is ... else position
755
+ for stop, position in zip(by_key[key].stops, positions)
756
+ )
757
+ for by_key in [{line.key: line for line in lines}]
758
+ for key, positions in raw_positions.items()
759
+ }
760
+
761
+ # Sûreté de chaque position sur sa ligne : celle du fichier de la ligne,
762
+ # sinon celle de la position générale (« bonne » seulement).
763
+ line_sure = {
764
+ key: tuple(
765
+ stop_confidence.get(stop) == "bonne" if sure is ... else bool(sure)
766
+ for stop, sure in zip(by_key[key].stops, flags)
767
+ )
768
+ for by_key in [{line.key: line for line in lines}]
769
+ for key, flags in raw_sure.items()
770
+ }
771
+
772
+ # La vraie longueur de route pour les lignes Tata qui ont une trace.
773
+ line_distances: dict[LineKey, tuple] = {}
774
+ traces = getattr(data, "traces", {})
775
+ for line in lines:
776
+ trace = traces.get(line.name) if line.company == "Tata AFTU" else None
777
+ if not trace:
778
+ continue
779
+ positions = line_positions.get(line.key) or tuple(
780
+ stop_coords.get(stop) for stop in line.stops
781
+ )
782
+ measured = distances_sur_trace(trace, positions)
783
+ if measured is not None:
784
+ line_distances[line.key] = measured
785
+
786
+ return cls(
787
+ lines,
788
+ stop_coords,
789
+ stop_confidence,
790
+ line_positions,
791
+ line_distances,
792
+ _legacy_stops(data, lines, stop_coords, stop_confidence),
793
+ line_sure,
794
+ )
src/tts/lexique_prononciation.py CHANGED
@@ -36,6 +36,9 @@ LEXIQUE: dict[str, str] = {
36
  "Acapes": "Akaapes",
37
  "Albert Sarraut": "Alber Saroo",
38
  "ASECNA": "Aseknaa",
 
 
 
39
  }
40
 
41
 
 
36
  "Acapes": "Akaapes",
37
  "Albert Sarraut": "Alber Saroo",
38
  "ASECNA": "Aseknaa",
39
+ # « Gare de Rufisque » sortait comme « heure de Rufisque » : le locuteur
40
+ # natif fait dire « Gaar » (mot entier ; « Garage » n'est pas touché).
41
+ "Gare": "Gaar",
42
  }
43
 
44