Spaces:
Paused
Paused
Deploy from GitHub Actions — 82fe9383394b9c62e886abe2b198e1cd12b52c82
Browse files- README.md +158 -8
- backend/Dockerfile +0 -0
- backend/README.md +92 -0
- backend/build_db.py +57 -0
- backend/main.py +273 -0
- backend/requirements.txt +0 -0
- docker-compose.yml +69 -0
- frontend/Dockerfile +0 -0
- frontend/README.md +0 -0
- frontend/requirements.txt +0 -0
README.md
CHANGED
|
@@ -1,11 +1,161 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
---
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
---
|
| 10 |
|
| 11 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SNCF GTFS — Tableau de Bord Horaires
|
| 2 |
+
|
| 3 |
+
Application web de consultation des horaires de trains SNCF à partir des données GTFS officielles.
|
| 4 |
+
|
| 5 |
+
---
|
| 6 |
+
|
| 7 |
+
## Architecture
|
| 8 |
+
|
| 9 |
+
```
|
| 10 |
+
sncf_gtfs/
|
| 11 |
+
│
|
| 12 |
+
├── backend/ ← API REST FastAPI (port 8013)
|
| 13 |
+
│ ├── main.py — Tous les endpoints JSON
|
| 14 |
+
│ ├── requirements.txt
|
| 15 |
+
│ ├── README.md
|
| 16 |
+
│ └── Dockerfile
|
| 17 |
+
│
|
| 18 |
+
├── frontend/ ← Interface web FastAPI + Jinja2 (port 8011)
|
| 19 |
+
│ ├── main.py — Routage pages + proxy API
|
| 20 |
+
│ ├── requirements.txt
|
| 21 |
+
│ ├── Dockerfile
|
| 22 |
+
│ ├── templates/
|
| 23 |
+
│ │ ├── base.html — Layout commun (navbar, ticker, horloge)
|
| 24 |
+
│ │ ├── index.html — Accueil + recherche rapide
|
| 25 |
+
│ │ ├── departures.html — Tableau des prochains trains
|
| 26 |
+
│ │ ├── journey.html — Itinéraire direct A → B
|
| 27 |
+
│ │ └── map.html — Carte interactive Leaflet
|
| 28 |
+
│ └── static/
|
| 29 |
+
│ ├── css/app.css — Thème dark "tableau ferroviaire"
|
| 30 |
+
│ └── js/app.js — Autocomplete, horloge, interactions
|
| 31 |
+
│
|
| 32 |
+
├── datas/
|
| 33 |
+
│ ├──DBS
|
| 34 |
+
│ │ └── gtfs_sncf.db ← Base SQLite (volume partagé Docker)
|
| 35 |
+
│ └── build_db.py — Script de reconstruction de la DB
|
| 36 |
+
│
|
| 37 |
+
├── docker-compose.yml ← Orchestration des 2 services
|
| 38 |
+
└── README.md
|
| 39 |
+
```
|
| 40 |
+
|
| 41 |
+
### Séparation des responsabilités
|
| 42 |
+
|
| 43 |
+
| Couche | Service | Rôle |
|
| 44 |
+
|--------|---------|------|
|
| 45 |
+
| **Données** | Volume Docker `./datas/DBS/` | Fichier SQLite partagé en lecture seule |
|
| 46 |
+
| **Backend** | `backend` (port 8013) | API REST pure — uniquement du JSON, aucun HTML |
|
| 47 |
+
| **Frontend** | `frontend` (port 8011) | Rendu HTML Jinja2 + proxy vers le backend |
|
| 48 |
+
|
| 49 |
+
---
|
| 50 |
+
|
| 51 |
+
## Démarrage rapide
|
| 52 |
+
|
| 53 |
+
### Prérequis
|
| 54 |
+
- Docker et Docker Compose installés
|
| 55 |
+
- Fichier `gtfs_sncf.db` dans `./data/` (déjà inclus)
|
| 56 |
+
|
| 57 |
+
### 1. Lancer le projet
|
| 58 |
+
```bash
|
| 59 |
+
cd sncf_gtfs
|
| 60 |
+
docker compose up --build
|
| 61 |
+
```
|
| 62 |
+
|
| 63 |
+
### 2. Accéder aux services
|
| 64 |
+
| Service | URL |
|
| 65 |
+
|---------|-----|
|
| 66 |
+
| **Interface web** | http://localhost:8011 |
|
| 67 |
+
| **API REST + Swagger** | http://localhost:8013/docs |
|
| 68 |
+
| **API ReDoc** | http://localhost:8013/redoc |
|
| 69 |
+
|
| 70 |
---
|
| 71 |
+
|
| 72 |
+
## Reconstruire la base SQLite
|
| 73 |
+
|
| 74 |
+
Si tu as de nouveaux fichiers GTFS SNCF :
|
| 75 |
+
|
| 76 |
+
```bash
|
| 77 |
+
# Copier les fichiers GTFS dans ./gtfs_raw/
|
| 78 |
+
python data/build_db.py --src ./gtfs_raw --out ./data/gtfs_sncf.db
|
| 79 |
+
|
| 80 |
+
# Puis redémarrer les conteneurs
|
| 81 |
+
docker compose restart
|
| 82 |
+
```
|
| 83 |
+
|
| 84 |
+
Fichiers GTFS attendus dans `./gtfs_raw/` :
|
| 85 |
+
```
|
| 86 |
+
agency.txt
|
| 87 |
+
routes.csv
|
| 88 |
+
stops.csv
|
| 89 |
+
trips.txt
|
| 90 |
+
stop_times2.csv ← séparateur point-virgule
|
| 91 |
+
calendar_dates.txt
|
| 92 |
+
transfers.txt
|
| 93 |
+
feed_info.txt
|
| 94 |
+
```
|
| 95 |
+
|
| 96 |
---
|
| 97 |
|
| 98 |
+
## Endpoints API
|
| 99 |
+
|
| 100 |
+
### Arrêts
|
| 101 |
+
| Méthode | Endpoint | Description |
|
| 102 |
+
|---------|----------|-------------|
|
| 103 |
+
| GET | `/stops/search?q=Paris&limit=20` | Recherche par nom |
|
| 104 |
+
| GET | `/stops/{stop_id}` | Détails d'un arrêt |
|
| 105 |
+
| GET | `/stops/{stop_id}/children` | Quais d'une gare |
|
| 106 |
+
|
| 107 |
+
### Horaires
|
| 108 |
+
| Méthode | Endpoint | Description |
|
| 109 |
+
|---------|----------|-------------|
|
| 110 |
+
| GET | `/next-trains?stop_id=...&date=20260218&time=10:00:00` | Prochains trains |
|
| 111 |
+
| GET | `/trains?from_stop_id=...&to_stop_id=...&date=...` | Trains directs A→B |
|
| 112 |
+
|
| 113 |
+
### Lignes
|
| 114 |
+
| Méthode | Endpoint | Description |
|
| 115 |
+
|---------|----------|-------------|
|
| 116 |
+
| GET | `/routes?q=TGV&route_type=2` | Rechercher une ligne |
|
| 117 |
+
| GET | `/routes/{route_id}/stops` | Arrêts d'une ligne |
|
| 118 |
+
|
| 119 |
+
### Carte
|
| 120 |
+
| Méthode | Endpoint | Description |
|
| 121 |
+
|---------|----------|-------------|
|
| 122 |
+
| GET | `/map/stops?lat=46.8&lon=2.4&radius_km=80` | Gares dans un rayon |
|
| 123 |
+
|
| 124 |
+
---
|
| 125 |
+
|
| 126 |
+
## Notes GTFS SNCF
|
| 127 |
+
|
| 128 |
+
- **stop_id** : Un même arrêt physique a plusieurs identifiants selon le type de train
|
| 129 |
+
- `StopArea:OCE...` → Zone (gare entière, location_type=1)
|
| 130 |
+
- `StopPoint:OCETGV INOUI-...` → Quai TGV INOUI
|
| 131 |
+
- `StopPoint:OCETrain TER-...` → Quai TER
|
| 132 |
+
- `StopPoint:OCEOUIGO-...` → Quai OUIGO
|
| 133 |
+
- **departure_time** : Peut dépasser `24:00:00` pour les trains de nuit (GTFS standard)
|
| 134 |
+
- **calendar_dates** : Uniquement des exceptions — exception_type=1 (actif), 2 (supprimé)
|
| 135 |
+
|
| 136 |
+
---
|
| 137 |
+
|
| 138 |
+
## Technologies
|
| 139 |
+
|
| 140 |
+
- **Python 3.12**
|
| 141 |
+
- **FastAPI** — backend API + frontend web
|
| 142 |
+
- **Jinja2** — moteur de templates HTML
|
| 143 |
+
- **httpx** — appels HTTP async frontend→backend
|
| 144 |
+
- **SQLite** — base de données légère, pas de serveur requis
|
| 145 |
+
- **Leaflet.js** — carte interactive
|
| 146 |
+
- **Docker Compose** — orchestration
|
| 147 |
+
|
| 148 |
+
---
|
| 149 |
+
|
| 150 |
+
## Données
|
| 151 |
+
|
| 152 |
+
Source : **SNCF Open Data** — flux GTFS national
|
| 153 |
+
Validité : 2026-02-14 → 2026-07-31
|
| 154 |
+
Couverture : TGV INOUI · OUIGO · TER · Intercités · Lyria · ICE · Cars TER
|
| 155 |
+
|
| 156 |
+
La spécification GTFS (General Transit Feed Specification) est une norme ouverte utilisée pour diffuser aux usagers des informations pertinentes sur les réseaux de transport en commun.
|
| 157 |
+
Le GTFS se décline en deux formats : GTFS Schedule et GTFS Realtime.
|
| 158 |
+
Elle permet aux agences de transport public de publier leurs données dans un format compatible avec une grande variété d'applications logicielles.
|
| 159 |
+
Aujourd'hui, le format de données GTFS est utilisé par des milliers de prestataires de transport public.
|
| 160 |
+
|
| 161 |
+
|
backend/Dockerfile
ADDED
|
File without changes
|
backend/README.md
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# API Horaires SNCF — GTFS
|
| 2 |
+
|
| 3 |
+
API REST FastAPI pour consulter les horaires des prochains trains depuis les données GTFS SNCF.
|
| 4 |
+
|
| 5 |
+
## Installation
|
| 6 |
+
|
| 7 |
+
```bash
|
| 8 |
+
pip install fastapi uvicorn pandas
|
| 9 |
+
```
|
| 10 |
+
|
| 11 |
+
## Démarrage rapide
|
| 12 |
+
|
| 13 |
+
### 1. Construire la base SQLite
|
| 14 |
+
```bash
|
| 15 |
+
# Placer les fichiers GTFS dans ./uploads/
|
| 16 |
+
python build_db.py --uploads-dir ./uploads --db gtfs_sncf.db
|
| 17 |
+
```
|
| 18 |
+
|
| 19 |
+
### 2. Lancer l'API
|
| 20 |
+
```bash
|
| 21 |
+
uvicorn main:app --reload
|
| 22 |
+
# → http://localhost:8013
|
| 23 |
+
# → http://localhost:8013/docs (Swagger UI interactif)
|
| 24 |
+
```
|
| 25 |
+
|
| 26 |
+
### Variable d'environnement
|
| 27 |
+
```bash
|
| 28 |
+
export DB_PATH=/chemin/vers/gtfs_sncf.db
|
| 29 |
+
uvicorn main:app --reload
|
| 30 |
+
```
|
| 31 |
+
|
| 32 |
+
---
|
| 33 |
+
|
| 34 |
+
## Endpoints
|
| 35 |
+
|
| 36 |
+
| Méthode | URL | Description |
|
| 37 |
+
|---------|-----|-------------|
|
| 38 |
+
| GET | `/` | Index des endpoints |
|
| 39 |
+
| GET | `/health` | Statut + stats tables |
|
| 40 |
+
| GET | `/stops/search?q=Paris` | Chercher une gare |
|
| 41 |
+
| GET | `/stops/{stop_id}` | Détails d'un arrêt |
|
| 42 |
+
| GET | `/next-trains?stop_id=...` | Prochains trains depuis une gare |
|
| 43 |
+
| GET | `/trains?from_stop_id=...&to_stop_id=...` | Trains directs entre 2 gares |
|
| 44 |
+
| GET | `/routes?q=TGV` | Rechercher une ligne |
|
| 45 |
+
| GET | `/routes/{route_id}/stops` | Arrêts d'une ligne |
|
| 46 |
+
|
| 47 |
+
---
|
| 48 |
+
|
| 49 |
+
## Exemple d'utilisation
|
| 50 |
+
|
| 51 |
+
```bash
|
| 52 |
+
# 1. Trouver l'identifiant de Lyon Part Dieu
|
| 53 |
+
curl "http://localhost:8013/stops/search?q=Lyon+Part+Dieu"
|
| 54 |
+
# → stop_id: "StopPoint:OCETrain TER-87723197"
|
| 55 |
+
|
| 56 |
+
# 2. Prochains trains aujourd'hui à partir de maintenant
|
| 57 |
+
curl "http://localhost:8013/next-trains?stop_id=StopPoint:OCETrain%20TER-87723197"
|
| 58 |
+
|
| 59 |
+
# 3. Trains directs Lyon → Paris demain matin
|
| 60 |
+
curl "http://localhost:8013/trains?from_stop_id=StopPoint:OCETGV%20INOUI-87723197&to_stop_id=StopPoint:OCETGV%20INOUI-87113001&date=20260219&time=07:00:00"
|
| 61 |
+
```
|
| 62 |
+
|
| 63 |
+
---
|
| 64 |
+
|
| 65 |
+
## Structure des fichiers GTFS attendus
|
| 66 |
+
|
| 67 |
+
```
|
| 68 |
+
uploads/
|
| 69 |
+
├── agency.txt — Opérateurs (SNCF Voyageurs…)
|
| 70 |
+
├── routes.csv — Lignes
|
| 71 |
+
├── trips.txt — Trajets / courses
|
| 72 |
+
├── stop_times2.csv — Horaires arrêt par arrêt (sep=;)
|
| 73 |
+
├── stops.csv — Points d'arrêt
|
| 74 |
+
├── calendar_dates.txt — Dates de circulation
|
| 75 |
+
├── transfers.txt — Correspondances
|
| 76 |
+
└── feed_info.txt — Métadonnées du flux
|
| 77 |
+
```
|
| 78 |
+
|
| 79 |
+
---
|
| 80 |
+
|
| 81 |
+
## Notes techniques
|
| 82 |
+
|
| 83 |
+
- Les `stop_id` SNCF contiennent le type de train : `StopPoint:OCETrain TER-87723197`, `StopPoint:OCETGV INOUI-87723197`, etc. Un même arrêt physique peut avoir plusieurs `stop_id` selon le type de train.
|
| 84 |
+
- Le champ `departure_time` peut dépasser `24:00:00` (ex : `25:30:00`) pour les trains de nuit — c'est du GTFS standard.
|
| 85 |
+
- La table `calendar_dates` gère uniquement les exceptions (exception_type=1 = service actif, 2 = supprimé).
|
| 86 |
+
|
| 87 |
+
## Requirements
|
| 88 |
+
```
|
| 89 |
+
fastapi>=0.110
|
| 90 |
+
uvicorn>=0.29
|
| 91 |
+
pandas>=2.0
|
| 92 |
+
```
|
backend/build_db.py
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
build_db.py — Construit la base SQLite depuis les fichiers GTFS SNCF
|
| 3 |
+
Usage : python build_db.py [--uploads-dir ./uploads] [--db gtfs_sncf.db]
|
| 4 |
+
"""
|
| 5 |
+
import sqlite3
|
| 6 |
+
import pandas as pd
|
| 7 |
+
import argparse
|
| 8 |
+
import os
|
| 9 |
+
|
| 10 |
+
def build(uploads_dir: str, db_path: str):
|
| 11 |
+
conn = sqlite3.connect(db_path)
|
| 12 |
+
|
| 13 |
+
files = {
|
| 14 |
+
"agency": ("agency.txt", ","),
|
| 15 |
+
"feed_info": ("feed_info.txt", ","),
|
| 16 |
+
"routes": ("routes.csv", ","),
|
| 17 |
+
"stops": ("stops.csv", ","),
|
| 18 |
+
"trips": ("trips.txt", ","),
|
| 19 |
+
"calendar_dates": ("calendar_dates.txt", ","),
|
| 20 |
+
"stop_times": ("stop_times2.csv", ";"), # séparateur point-virgule
|
| 21 |
+
"transfers": ("transfers.txt", ","),
|
| 22 |
+
}
|
| 23 |
+
|
| 24 |
+
for table, (filename, sep) in files.items():
|
| 25 |
+
path = os.path.join(uploads_dir, filename)
|
| 26 |
+
if not os.path.exists(path):
|
| 27 |
+
print(f" ⚠️ {filename} introuvable — table {table} ignorée")
|
| 28 |
+
continue
|
| 29 |
+
df = pd.read_csv(path, sep=sep, dtype=str)
|
| 30 |
+
df.to_sql(table, conn, if_exists="replace", index=False)
|
| 31 |
+
print(f" ✅ {table:20s} {len(df):>8,} lignes")
|
| 32 |
+
|
| 33 |
+
print("\nCréation des index…")
|
| 34 |
+
indexes = [
|
| 35 |
+
"CREATE INDEX IF NOT EXISTS idx_st_stop ON stop_times(stop_id)",
|
| 36 |
+
"CREATE INDEX IF NOT EXISTS idx_st_trip ON stop_times(trip_id)",
|
| 37 |
+
"CREATE INDEX IF NOT EXISTS idx_st_dep ON stop_times(departure_time)",
|
| 38 |
+
"CREATE INDEX IF NOT EXISTS idx_tr_route ON trips(route_id)",
|
| 39 |
+
"CREATE INDEX IF NOT EXISTS idx_tr_svc ON trips(service_id)",
|
| 40 |
+
"CREATE INDEX IF NOT EXISTS idx_cd_svc ON calendar_dates(service_id, date)",
|
| 41 |
+
"CREATE INDEX IF NOT EXISTS idx_stops_nm ON stops(stop_name)",
|
| 42 |
+
]
|
| 43 |
+
for idx in indexes:
|
| 44 |
+
conn.execute(idx)
|
| 45 |
+
|
| 46 |
+
conn.commit()
|
| 47 |
+
conn.close()
|
| 48 |
+
size_mb = os.path.getsize(db_path) / 1024 / 1024
|
| 49 |
+
print(f"\n✅ Base créée : {db_path} ({size_mb:.1f} MB)")
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
if __name__ == "__main__":
|
| 53 |
+
parser = argparse.ArgumentParser()
|
| 54 |
+
parser.add_argument("--uploads-dir", default="./uploads")
|
| 55 |
+
parser.add_argument("--db", default="gtfs_sncf.db")
|
| 56 |
+
args = parser.parse_args()
|
| 57 |
+
build(args.uploads_dir, args.db)
|
backend/main.py
ADDED
|
@@ -0,0 +1,273 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
API SNCF - Horaires des prochains trains
|
| 3 |
+
Basée sur les données GTFS SNCF
|
| 4 |
+
"""
|
| 5 |
+
from fastapi import FastAPI, Query, HTTPException
|
| 6 |
+
from fastapi.responses import JSONResponse
|
| 7 |
+
import sqlite3
|
| 8 |
+
from datetime import datetime, date
|
| 9 |
+
from typing import Optional
|
| 10 |
+
import os
|
| 11 |
+
|
| 12 |
+
DB_PATH = os.environ.get("DB_PATH", "./gtfs_sncf.db")
|
| 13 |
+
|
| 14 |
+
app = FastAPI(
|
| 15 |
+
title="API Horaires SNCF",
|
| 16 |
+
description="API de consultation des horaires de trains à partir des données GTFS SNCF",
|
| 17 |
+
version="1.0.0",
|
| 18 |
+
)
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def get_conn():
|
| 22 |
+
conn = sqlite3.connect(DB_PATH)
|
| 23 |
+
conn.row_factory = sqlite3.Row
|
| 24 |
+
return conn
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
# ─────────────────────────────────────────────
|
| 28 |
+
# UTILITAIRES
|
| 29 |
+
# ─────────────────────────────────────────────
|
| 30 |
+
|
| 31 |
+
def current_gtfs_date() -> str:
|
| 32 |
+
"""Date du jour au format GTFS : YYYYMMDD"""
|
| 33 |
+
return datetime.now().strftime("%Y%m%d")
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def current_time_str() -> str:
|
| 37 |
+
"""Heure actuelle HH:MM:SS"""
|
| 38 |
+
return datetime.now().strftime("%H:%M:%S")
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
# ─────────────────────────────────────────────
|
| 42 |
+
# ENDPOINTS
|
| 43 |
+
# ─────────────────────────────────────────────
|
| 44 |
+
|
| 45 |
+
@app.get("/", summary="Bienvenue")
|
| 46 |
+
def root():
|
| 47 |
+
return {
|
| 48 |
+
"message": "API Horaires SNCF - GTFS",
|
| 49 |
+
"endpoints": {
|
| 50 |
+
"recherche_gare": "/stops/search?q=Paris",
|
| 51 |
+
"prochains_trains": "/next-trains?stop_id=StopPoint:OCETGV INOUI-71043075",
|
| 52 |
+
"trains_entre_gares": "/trains?from_stop_id=...&to_stop_id=...&date=20260218",
|
| 53 |
+
"details_gare": "/stops/{stop_id}",
|
| 54 |
+
"lignes": "/routes?q=TGV",
|
| 55 |
+
},
|
| 56 |
+
}
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
@app.get("/stops/search", summary="Rechercher une gare par nom")
|
| 60 |
+
def search_stops(
|
| 61 |
+
q: str = Query(..., description="Nom ou partie du nom de la gare", min_length=2),
|
| 62 |
+
limit: int = Query(20, le=100),
|
| 63 |
+
):
|
| 64 |
+
"""Recherche une gare par son nom (recherche partielle insensible à la casse)."""
|
| 65 |
+
conn = get_conn()
|
| 66 |
+
rows = conn.execute(
|
| 67 |
+
"""
|
| 68 |
+
SELECT stop_id, stop_name, stop_lat, stop_lon, location_type, parent_station
|
| 69 |
+
FROM stops
|
| 70 |
+
WHERE stop_name LIKE ?
|
| 71 |
+
ORDER BY location_type, stop_name
|
| 72 |
+
LIMIT ?
|
| 73 |
+
""",
|
| 74 |
+
(f"%{q}%", limit),
|
| 75 |
+
).fetchall()
|
| 76 |
+
conn.close()
|
| 77 |
+
return [dict(r) for r in rows]
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
@app.get("/stops/{stop_id}", summary="Détails d'une gare")
|
| 81 |
+
def get_stop(stop_id: str):
|
| 82 |
+
"""Retourne les informations complètes d'un arrêt."""
|
| 83 |
+
conn = get_conn()
|
| 84 |
+
row = conn.execute(
|
| 85 |
+
"SELECT * FROM stops WHERE stop_id = ?", (stop_id,)
|
| 86 |
+
).fetchone()
|
| 87 |
+
conn.close()
|
| 88 |
+
if not row:
|
| 89 |
+
raise HTTPException(404, f"Arrêt '{stop_id}' introuvable")
|
| 90 |
+
return dict(row)
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
@app.get("/next-trains", summary="Prochains trains depuis une gare")
|
| 94 |
+
def next_trains(
|
| 95 |
+
stop_id: str = Query(..., description="Identifiant de l'arrêt (stop_id)"),
|
| 96 |
+
date: Optional[str] = Query(None, description="Date YYYYMMDD (défaut: aujourd'hui)"),
|
| 97 |
+
time: Optional[str] = Query(None, description="Heure de départ HH:MM:SS (défaut: maintenant)"),
|
| 98 |
+
limit: int = Query(10, le=50, description="Nombre de trains à retourner"),
|
| 99 |
+
):
|
| 100 |
+
"""
|
| 101 |
+
Retourne les prochains trains au départ d'un arrêt donné.
|
| 102 |
+
|
| 103 |
+
Les trains sont filtrés sur la date (via calendar_dates) et triés par heure de départ.
|
| 104 |
+
Attention : le GTFS SNCF peut avoir des heures > 24:00 (service nocturne).
|
| 105 |
+
"""
|
| 106 |
+
gtfs_date = date or current_gtfs_date()
|
| 107 |
+
from_time = time or current_time_str()
|
| 108 |
+
|
| 109 |
+
conn = get_conn()
|
| 110 |
+
|
| 111 |
+
# Vérifier que l'arrêt existe
|
| 112 |
+
stop = conn.execute("SELECT stop_name FROM stops WHERE stop_id = ?", (stop_id,)).fetchone()
|
| 113 |
+
if not stop:
|
| 114 |
+
conn.close()
|
| 115 |
+
raise HTTPException(404, f"Arrêt '{stop_id}' introuvable")
|
| 116 |
+
|
| 117 |
+
rows = conn.execute(
|
| 118 |
+
"""
|
| 119 |
+
SELECT
|
| 120 |
+
st.departure_time,
|
| 121 |
+
st.arrival_time,
|
| 122 |
+
st.stop_sequence,
|
| 123 |
+
t.trip_headsign AS destination,
|
| 124 |
+
t.direction_id,
|
| 125 |
+
t.trip_id,
|
| 126 |
+
r.route_short_name AS ligne,
|
| 127 |
+
r.route_long_name,
|
| 128 |
+
r.route_type,
|
| 129 |
+
ag.agency_name
|
| 130 |
+
FROM stop_times st
|
| 131 |
+
JOIN trips t ON st.trip_id = t.trip_id
|
| 132 |
+
JOIN routes r ON t.route_id = r.route_id
|
| 133 |
+
JOIN agency ag ON r.agency_id = ag.agency_id
|
| 134 |
+
JOIN calendar_dates cd ON t.service_id = cd.service_id
|
| 135 |
+
WHERE st.stop_id = ?
|
| 136 |
+
AND cd.date = ?
|
| 137 |
+
AND cd.exception_type = 1
|
| 138 |
+
AND st.departure_time >= ?
|
| 139 |
+
ORDER BY st.departure_time
|
| 140 |
+
LIMIT ?
|
| 141 |
+
""",
|
| 142 |
+
(stop_id, gtfs_date, from_time, limit),
|
| 143 |
+
).fetchall()
|
| 144 |
+
conn.close()
|
| 145 |
+
|
| 146 |
+
return {
|
| 147 |
+
"stop_id": stop_id,
|
| 148 |
+
"stop_name": stop["stop_name"],
|
| 149 |
+
"date": gtfs_date,
|
| 150 |
+
"from_time": from_time,
|
| 151 |
+
"count": len(rows),
|
| 152 |
+
"trains": [dict(r) for r in rows],
|
| 153 |
+
}
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
@app.get("/trains", summary="Trains entre deux gares")
|
| 157 |
+
def trains_between(
|
| 158 |
+
from_stop_id: str = Query(..., description="Arrêt de départ (stop_id)"),
|
| 159 |
+
to_stop_id: str = Query(..., description="Arrêt d'arrivée (stop_id)"),
|
| 160 |
+
date: Optional[str] = Query(None, description="Date YYYYMMDD (défaut: aujourd'hui)"),
|
| 161 |
+
time: Optional[str] = Query(None, description="Heure mini HH:MM:SS (défaut: maintenant)"),
|
| 162 |
+
limit: int = Query(10, le=50),
|
| 163 |
+
):
|
| 164 |
+
"""
|
| 165 |
+
Trains directs entre deux gares à une date donnée.
|
| 166 |
+
Seuls les trains directs (sans correspondance) sont retournés.
|
| 167 |
+
"""
|
| 168 |
+
gtfs_date = date or current_gtfs_date()
|
| 169 |
+
from_time = time or current_time_str()
|
| 170 |
+
|
| 171 |
+
conn = get_conn()
|
| 172 |
+
|
| 173 |
+
# Vérifier les arrêts
|
| 174 |
+
for sid, label in [(from_stop_id, "départ"), (to_stop_id, "arrivée")]:
|
| 175 |
+
if not conn.execute("SELECT 1 FROM stops WHERE stop_id=?", (sid,)).fetchone():
|
| 176 |
+
conn.close()
|
| 177 |
+
raise HTTPException(404, f"Arrêt de {label} '{sid}' introuvable")
|
| 178 |
+
|
| 179 |
+
rows = conn.execute(
|
| 180 |
+
"""
|
| 181 |
+
SELECT
|
| 182 |
+
st_from.departure_time AS depart,
|
| 183 |
+
st_to.arrival_time AS arrivee,
|
| 184 |
+
t.trip_headsign AS destination,
|
| 185 |
+
t.trip_id,
|
| 186 |
+
r.route_short_name AS ligne,
|
| 187 |
+
r.route_long_name,
|
| 188 |
+
ag.agency_name
|
| 189 |
+
FROM stop_times st_from
|
| 190 |
+
JOIN stop_times st_to ON st_from.trip_id = st_to.trip_id
|
| 191 |
+
AND st_to.stop_sequence > st_from.stop_sequence
|
| 192 |
+
JOIN trips t ON st_from.trip_id = t.trip_id
|
| 193 |
+
JOIN routes r ON t.route_id = r.route_id
|
| 194 |
+
JOIN agency ag ON r.agency_id = ag.agency_id
|
| 195 |
+
JOIN calendar_dates cd ON t.service_id = cd.service_id
|
| 196 |
+
WHERE st_from.stop_id = ?
|
| 197 |
+
AND st_to.stop_id = ?
|
| 198 |
+
AND cd.date = ?
|
| 199 |
+
AND cd.exception_type = 1
|
| 200 |
+
AND st_from.departure_time >= ?
|
| 201 |
+
ORDER BY st_from.departure_time
|
| 202 |
+
LIMIT ?
|
| 203 |
+
""",
|
| 204 |
+
(from_stop_id, to_stop_id, gtfs_date, from_time, limit),
|
| 205 |
+
).fetchall()
|
| 206 |
+
conn.close()
|
| 207 |
+
|
| 208 |
+
return {
|
| 209 |
+
"from_stop_id": from_stop_id,
|
| 210 |
+
"to_stop_id": to_stop_id,
|
| 211 |
+
"date": gtfs_date,
|
| 212 |
+
"from_time": from_time,
|
| 213 |
+
"count": len(rows),
|
| 214 |
+
"trains": [dict(r) for r in rows],
|
| 215 |
+
}
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
@app.get("/routes", summary="Rechercher une ligne")
|
| 219 |
+
def search_routes(
|
| 220 |
+
q: Optional[str] = Query(None, description="Nom ou numéro de ligne"),
|
| 221 |
+
route_type: Optional[int] = Query(None, description="Type GTFS (2=rail, 3=bus…)"),
|
| 222 |
+
limit: int = Query(20, le=100),
|
| 223 |
+
):
|
| 224 |
+
"""Liste des lignes avec filtre optionnel par nom ou type."""
|
| 225 |
+
conn = get_conn()
|
| 226 |
+
query = "SELECT route_id, route_short_name, route_long_name, route_type, agency_id FROM routes WHERE 1=1"
|
| 227 |
+
params = []
|
| 228 |
+
if q:
|
| 229 |
+
query += " AND (route_short_name LIKE ? OR route_long_name LIKE ?)"
|
| 230 |
+
params += [f"%{q}%", f"%{q}%"]
|
| 231 |
+
if route_type is not None:
|
| 232 |
+
query += " AND route_type = ?"
|
| 233 |
+
params.append(route_type)
|
| 234 |
+
query += f" ORDER BY route_short_name LIMIT {limit}"
|
| 235 |
+
rows = conn.execute(query, params).fetchall()
|
| 236 |
+
conn.close()
|
| 237 |
+
return [dict(r) for r in rows]
|
| 238 |
+
|
| 239 |
+
|
| 240 |
+
@app.get("/routes/{route_id}/stops", summary="Arrêts d'une ligne")
|
| 241 |
+
def route_stops(
|
| 242 |
+
route_id: str,
|
| 243 |
+
date: Optional[str] = Query(None, description="Date YYYYMMDD (défaut: aujourd'hui)"),
|
| 244 |
+
):
|
| 245 |
+
"""Retourne tous les arrêts desservis par une ligne à une date donnée."""
|
| 246 |
+
gtfs_date = date or current_gtfs_date()
|
| 247 |
+
conn = get_conn()
|
| 248 |
+
rows = conn.execute(
|
| 249 |
+
"""
|
| 250 |
+
SELECT DISTINCT s.stop_id, s.stop_name, s.stop_lat, s.stop_lon
|
| 251 |
+
FROM stop_times st
|
| 252 |
+
JOIN trips t ON st.trip_id = t.trip_id
|
| 253 |
+
JOIN stops s ON st.stop_id = s.stop_id
|
| 254 |
+
JOIN calendar_dates cd ON t.service_id = cd.service_id
|
| 255 |
+
WHERE t.route_id = ?
|
| 256 |
+
AND cd.date = ?
|
| 257 |
+
AND cd.exception_type = 1
|
| 258 |
+
ORDER BY s.stop_name
|
| 259 |
+
""",
|
| 260 |
+
(route_id, gtfs_date),
|
| 261 |
+
).fetchall()
|
| 262 |
+
conn.close()
|
| 263 |
+
return [dict(r) for r in rows]
|
| 264 |
+
|
| 265 |
+
|
| 266 |
+
@app.get("/health", summary="Santé de l'API")
|
| 267 |
+
def health():
|
| 268 |
+
conn = get_conn()
|
| 269 |
+
stats = {}
|
| 270 |
+
for table in ["stops", "routes", "trips", "stop_times", "calendar_dates"]:
|
| 271 |
+
stats[table] = conn.execute(f"SELECT COUNT(*) FROM {table}").fetchone()[0]
|
| 272 |
+
conn.close()
|
| 273 |
+
return {"status": "ok", "db": DB_PATH, "tables": stats}
|
backend/requirements.txt
ADDED
|
File without changes
|
docker-compose.yml
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version: "3.12"
|
| 2 |
+
|
| 3 |
+
# ═══════════════════════════════════════════════════════════
|
| 4 |
+
# SNCF GTFS — Docker Compose
|
| 5 |
+
#
|
| 6 |
+
# Services :
|
| 7 |
+
# backend → API REST FastAPI (port 8013)
|
| 8 |
+
# frontend → Interface web Jinja2 (port 8011)
|
| 9 |
+
#
|
| 10 |
+
# Volume partagé :
|
| 11 |
+
# ./datas/DBS/ → gtfs_sncf.db (lecture seule en prod)
|
| 12 |
+
#
|
| 13 |
+
# Démarrage :
|
| 14 |
+
# docker compose up --build
|
| 15 |
+
#
|
| 16 |
+
# API docs : http://localhost:8013/docs
|
| 17 |
+
# Interface : http://localhost:8011
|
| 18 |
+
# ═══════════════════════════════════════════════════════════
|
| 19 |
+
|
| 20 |
+
services:
|
| 21 |
+
|
| 22 |
+
# ── Base de données (volume partagé, pas de service dédié pour SQLite) ──
|
| 23 |
+
# SQLite est un fichier — pas besoin d'un conteneur DB séparé.
|
| 24 |
+
# Les deux services montent le même volume en lecture.
|
| 25 |
+
|
| 26 |
+
# ── API Backend ─────────────────────────────────────────────────────────
|
| 27 |
+
backend:
|
| 28 |
+
build:
|
| 29 |
+
context: ./backend
|
| 30 |
+
dockerfile: Dockerfile
|
| 31 |
+
container_name: sncf_backend
|
| 32 |
+
restart: unless-stopped
|
| 33 |
+
environment:
|
| 34 |
+
DB_PATH: /datas/DBS/gtfs_sncf.db
|
| 35 |
+
volumes:
|
| 36 |
+
- ./datas/DBS/:/data:ro # Lecture seule — protège la DB
|
| 37 |
+
ports:
|
| 38 |
+
- "8013:8013" # API REST accessible directement
|
| 39 |
+
healthcheck:
|
| 40 |
+
test: ["CMD", "python3", "-c", "import urllib.request; urllib.request.urlopen('http://localhost:8013/health')"]
|
| 41 |
+
interval: 30s
|
| 42 |
+
timeout: 10s
|
| 43 |
+
retries: 3
|
| 44 |
+
start_period: 15s
|
| 45 |
+
networks:
|
| 46 |
+
- sncf_net
|
| 47 |
+
|
| 48 |
+
# ── Frontend ─────────────────────────────────────────────────────────────
|
| 49 |
+
frontend:
|
| 50 |
+
build:
|
| 51 |
+
context: ./frontend
|
| 52 |
+
dockerfile: Dockerfile
|
| 53 |
+
container_name: sncf_frontend
|
| 54 |
+
restart: unless-stopped
|
| 55 |
+
environment:
|
| 56 |
+
BACKEND_URL: http://happytrain.local:8013
|
| 57 |
+
ports:
|
| 58 |
+
- "8011:8011" # Interface web
|
| 59 |
+
depends_on:
|
| 60 |
+
backend:
|
| 61 |
+
condition: service_healthy
|
| 62 |
+
networks:
|
| 63 |
+
- sncf_net
|
| 64 |
+
|
| 65 |
+
# ── Réseau interne ────────────────────────────────────────────────────────
|
| 66 |
+
networks:
|
| 67 |
+
sncf_net:
|
| 68 |
+
driver: bridge
|
| 69 |
+
name: sncf_network
|
frontend/Dockerfile
ADDED
|
File without changes
|
frontend/README.md
ADDED
|
File without changes
|
frontend/requirements.txt
ADDED
|
File without changes
|