Spaces:
Sleeping
Sleeping
Upload tools/getdetailsfromstopname_v2.py with huggingface_hub
Browse files
tools/getdetailsfromstopname_v2.py
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import json
|
| 3 |
+
from PIL import Image
|
| 4 |
+
import numpy as np
|
| 5 |
+
|
| 6 |
+
# --- User Defined Logic ---
|
| 7 |
+
import duckdb
|
| 8 |
+
import requests
|
| 9 |
+
import pandas as pd
|
| 10 |
+
import os
|
| 11 |
+
import time
|
| 12 |
+
from datetime import datetime, timedelta
|
| 13 |
+
|
| 14 |
+
def getdetailsfromstopname(stop_name_pattern):
|
| 15 |
+
"""
|
| 16 |
+
Recherche des arrêts de transport en commun en Île-de-France par nom partiel.
|
| 17 |
+
|
| 18 |
+
Args:
|
| 19 |
+
stop_name_pattern: Le nom ou partie du nom de l'arrêt à rechercher (ex: "Grigny", "Charles de Gaulle", etc.)
|
| 20 |
+
|
| 21 |
+
Returns:
|
| 22 |
+
Une liste de dictionnaires contenant les informations des arrêts trouvés:
|
| 23 |
+
- route_long_name: Nom de la ligne
|
| 24 |
+
- stop_id: Identifiant de l'arrêt
|
| 25 |
+
- stop_name: Nom complet de l'arrêt
|
| 26 |
+
- stop_lon: Longitude
|
| 27 |
+
- stop_lat: Latitude
|
| 28 |
+
- OperatorName: Nom de l'opérateur
|
| 29 |
+
- Nom_commune: Nom de la commune
|
| 30 |
+
- Code_insee: Code INSEE de la commune
|
| 31 |
+
- Pointgeo: Coordonnées géographiques
|
| 32 |
+
"""
|
| 33 |
+
|
| 34 |
+
# URL du fichier parquet
|
| 35 |
+
parquet_url = "https://data.iledefrance-mobilites.fr/api/explore/v2.1/catalog/datasets/arrets-lignes/exports/parquet"
|
| 36 |
+
|
| 37 |
+
# Chemin local pour le cache
|
| 38 |
+
cache_dir = "/tmp/mcp_cache"
|
| 39 |
+
cache_file = os.path.join(cache_dir, "arrets-lignes.parquet")
|
| 40 |
+
|
| 41 |
+
try:
|
| 42 |
+
# Créer le dossier de cache s'il n'existe pas
|
| 43 |
+
os.makedirs(cache_dir, exist_ok=True)
|
| 44 |
+
|
| 45 |
+
# Vérifier si le fichier existe et n'est pas trop vieux (24h)
|
| 46 |
+
if os.path.exists(cache_file):
|
| 47 |
+
file_age = datetime.now() - datetime.fromtimestamp(os.path.getmtime(cache_file))
|
| 48 |
+
if file_age > timedelta(hours=24):
|
| 49 |
+
os.remove(cache_file) # Supprimer le cache expiré
|
| 50 |
+
|
| 51 |
+
# Télécharger le fichier s'il n'existe pas
|
| 52 |
+
if not os.path.exists(cache_file):
|
| 53 |
+
print(f"Téléchargement du fichier parquet depuis {parquet_url}...")
|
| 54 |
+
response = requests.get(parquet_url, timeout=300) # 5 minutes de timeout
|
| 55 |
+
response.raise_for_status()
|
| 56 |
+
|
| 57 |
+
with open(cache_file, 'wb') as f:
|
| 58 |
+
f.write(response.content)
|
| 59 |
+
print("Téléchargement terminé.")
|
| 60 |
+
|
| 61 |
+
# Créer une connexion DuckDB en mémoire
|
| 62 |
+
conn = duckdb.connect(':memory:')
|
| 63 |
+
|
| 64 |
+
# Charger le fichier parquet depuis le cache local
|
| 65 |
+
query = f"""
|
| 66 |
+
SELECT *
|
| 67 |
+
FROM read_parquet('{cache_file}')
|
| 68 |
+
WHERE LOWER(stop_name) LIKE LOWER('%{stop_name_pattern}%')
|
| 69 |
+
ORDER BY stop_name, route_long_name
|
| 70 |
+
LIMIT 50 -- Limiter pour éviter les résultats trop volumineux
|
| 71 |
+
"""
|
| 72 |
+
|
| 73 |
+
# Exécuter la requête
|
| 74 |
+
result_df = conn.execute(query).fetch_df()
|
| 75 |
+
|
| 76 |
+
# Fermer la connexion
|
| 77 |
+
conn.close()
|
| 78 |
+
|
| 79 |
+
if result_df.empty:
|
| 80 |
+
return f"Aucun arrêt trouvé contenant '{stop_name_pattern}'"
|
| 81 |
+
|
| 82 |
+
# Convertir le DataFrame en liste de dictionnaires
|
| 83 |
+
stops_info = []
|
| 84 |
+
for _, row in result_df.iterrows():
|
| 85 |
+
stop_info = {
|
| 86 |
+
'route_long_name': str(row.get('route_long_name', 'N/A')),
|
| 87 |
+
'stop_id': str(row.get('stop_id', 'N/A')),
|
| 88 |
+
'stop_name': str(row.get('stop_name', 'N/A')),
|
| 89 |
+
'stop_lon': float(row.get('stop_lon', 0.0)) if pd.notna(row.get('stop_lon')) else 0.0,
|
| 90 |
+
'stop_lat': float(row.get('stop_lat', 0.0)) if pd.notna(row.get('stop_lat')) else 0.0,
|
| 91 |
+
'OperatorName': str(row.get('OperatorName', 'N/A')),
|
| 92 |
+
'Nom_commune': str(row.get('Nom_commune', 'N/A')),
|
| 93 |
+
'Code_insee': str(row.get('Code_insee', 'N/A')),
|
| 94 |
+
'Pointgeo': str(row.get('Pointgeo', 'N/A'))
|
| 95 |
+
}
|
| 96 |
+
stops_info.append(stop_info)
|
| 97 |
+
|
| 98 |
+
return stops_info
|
| 99 |
+
|
| 100 |
+
except requests.exceptions.Timeout:
|
| 101 |
+
return "Erreur: Le téléchargement a pris trop de temps. Veuillez réessayer plus tard."
|
| 102 |
+
except requests.exceptions.RequestException as e:
|
| 103 |
+
return f"Erreur lors du téléchargement des données: {str(e)}"
|
| 104 |
+
except Exception as e:
|
| 105 |
+
return f"Erreur lors de la recherche: {str(e)}"
|
| 106 |
+
|
| 107 |
+
# --- Interface Factory ---
|
| 108 |
+
def create_interface():
|
| 109 |
+
return gr.Interface(
|
| 110 |
+
fn=getdetailsfromstopname,
|
| 111 |
+
inputs=[gr.Textbox(label=k) for k in ['stop_name_pattern']],
|
| 112 |
+
outputs=gr.Textbox(label="Liste de dictionnaires contenant les informations des arrêts trouvés avec leurs identifiants, lignes et coordonnées géographiques"),
|
| 113 |
+
title="getdetailsfromstopname-v2",
|
| 114 |
+
description="Auto-generated tool: getdetailsfromstopname-v2"
|
| 115 |
+
)
|