Spaces:
Sleeping
Sleeping
import requests | |
from datetime import datetime | |
class PerturbationScraper: | |
def __init__(self): | |
self.headers = { | |
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36' | |
} | |
self.api_url = 'https://mobilille.fr/api/v1/lines' | |
def get_perturbations(self): | |
try: | |
response = requests.get(self.api_url, headers=self.headers) | |
response.raise_for_status() | |
lines = response.json() | |
perturbations = [] | |
for line in lines: | |
# Filtrer les alertes importantes (perturbations, déviations, travaux) | |
important_alerts = [ | |
alert for alert in line.get('alerts', []) | |
if any(keyword in alert.get('alert_title', '').lower() | |
for keyword in ['perturbation', 'déviation', 'travaux']) | |
and 'descente à la demande' not in alert.get('alert_title', '').lower() | |
and 'forte affluence' not in alert.get('alert_title', '').lower() | |
] | |
if important_alerts: | |
perturbation = { | |
'line': line.get('line_name', 'Inconnue'), | |
'line_trace': line.get('line_trace', ''), | |
'line_type': line.get('line_type', ''), | |
'alerts': [] | |
} | |
for alert in important_alerts: | |
date_modif = datetime.strptime(alert.get('date_modif', ''), '%Y-%m-%d %H:%M:%S') | |
formatted_time = date_modif.strftime('%d/%m/%Y à %H:%M') | |
perturbation['alerts'].append({ | |
'title': alert.get('alert_title', ''), | |
'description': alert.get('message_app', ''), | |
'update_time': formatted_time | |
}) | |
perturbations.append(perturbation) | |
# Trier les perturbations par type de ligne (métro, tram, bus) | |
type_order = {'metro_lines': 0, 'tram_lines': 1, 'bus_lines': 2} | |
perturbations.sort(key=lambda x: type_order.get(x['line_type'], 999)) | |
return perturbations | |
except Exception as e: | |
print(f"Erreur lors de la récupération des perturbations : {e}") | |
return [] | |
def main(): | |
scraper = PerturbationScraper() | |
perturbations = scraper.get_perturbations() | |
print("\n=== Perturbations en cours ===\n") | |
if not perturbations: | |
print("Aucune perturbation n'est actuellement signalée.") | |
else: | |
current_type = None | |
for p in perturbations: | |
# Afficher un en-tête pour chaque type de transport | |
line_type = p['line_type'] | |
if line_type != current_type: | |
if current_type is not None: | |
print("\n" + "=" * 50 + "\n") | |
current_type = line_type | |
type_name = { | |
'metro_lines': '🚇 Métro', | |
'tram_lines': '🚊 Tramway', | |
'bus_lines': '🚌 Bus' | |
}.get(line_type, 'Autre') | |
print(f"{type_name}:") | |
print(f"\nLigne {p['line']} - {p['line_trace']}") | |
for alert in p['alerts']: | |
print(f"\n🚨 {alert['title']}") | |
print(f"{alert['description']}") | |
print(f"\nℹ️ Mise à jour : {alert['update_time']}") | |
print("-" * 50) | |
if __name__ == "__main__": | |
main() | |