Mapu142 commited on
Commit
32b677a
·
verified ·
1 Parent(s): c10da80

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +137 -145
app.py CHANGED
@@ -1,146 +1,138 @@
1
- import streamlit as st
2
- from pyproj import CRS
3
- import pandas as pd
4
- import geopandas as gpd
5
- from shapely.geometry import LineString, Point
6
- import folium
7
- from streamlit_folium import st_folium
8
-
9
- import os, sys
10
- import traceback
11
-
12
- def catch_errors():
13
- try:
14
- yield
15
- except Exception:
16
- st.error("Error en la aplicación:")
17
- st.code(traceback.format_exc())
18
-
19
- with catch_errors():
20
- print(">>> Ejecutando archivo:", os.path.abspath(__file__))
21
- print("Python ejecutado:", sys.executable)
22
-
23
- # Cargar shapes.txt manteniendo la precisión
24
- shapes = pd.read_csv('shapes.txt')
25
- routes = pd.read_csv('routes.txt')
26
- stops = pd.read_csv('stops.txt')
27
- stop_times = pd.read_csv('stop_times.txt')
28
- trips = pd.read_csv('trips.txt')
29
-
30
- # Convertir puntos a geometría
31
- shapes_gdf = (
32
- shapes.sort_values(["shape_id", "shape_pt_sequence"])
33
- .groupby("shape_id")
34
- .apply(lambda x: LineString(zip(x.shape_pt_lon, x.shape_pt_lat)))
35
- .reset_index()
36
- )
37
-
38
- shapes_gdf.columns = ["shape_id", "geometry"]
39
- crs_obj = CRS.from_epsg(4326) # Crea el objeto CRS correctamente
40
- shapes_gdf = gpd.GeoDataFrame(shapes_gdf, geometry="geometry", crs=crs_obj)
41
-
42
- # =========================
43
- # UI
44
- # =========================
45
- st.title("🚍 Planificador inteligente — TransMilenio")
46
-
47
- st.write("Esta app detecta si la ruta **en la que ya vas** te sirve para llegar al destino.")
48
-
49
-
50
- # =========================
51
- # INPUTS DEL USUARIO
52
- # =========================
53
-
54
- st.header("1️⃣ ¿En qué ruta vas?")
55
- ruta_seleccionada = st.selectbox(
56
- "Selecciona tu ruta",
57
- routes.route_short_name.unique(),
58
- )
59
-
60
- st.header("2️⃣ ¿Dónde estás?")
61
- col1, col2 = st.columns(2)
62
- with col1:
63
- modo_origen = st.radio("Selecciona cómo indicar dónde estás:", ["Parada", "Coordenadas"])
64
-
65
- if modo_origen == "Parada":
66
- parada_origen = st.selectbox("Selecciona tu parada actual", stops.stop_name.unique())
67
- stop_actual = stops[stops.stop_name == parada_origen].iloc[0]
68
-
69
- else:
70
- lat = st.number_input("Latitud", value=4.65)
71
- lon = st.number_input("Longitud", value=-74.1)
72
- stop_actual = {"stop_lat": lat, "stop_lon": lon}
73
-
74
-
75
- st.header("3️⃣ ¿A dónde vas?")
76
- destino = st.text_input("Escribe la parada o dirección de destino")
77
-
78
- calcular = st.button("Calcular ruta")
79
-
80
- # =========================
81
- # PROCESAMIENTO
82
- # =========================
83
-
84
- if calcular:
85
-
86
- # ---- 1. Filtrar rutas por route_short_name ----
87
- route_id = routes.loc[routes.route_short_name == ruta_seleccionada, "route_id"].iloc[0]
88
- trips_ruta = trips[trips.route_id == route_id]
89
-
90
- if trips_ruta.empty:
91
- st.error("No se encontraron viajes para esta ruta.")
92
- st.stop()
93
-
94
- # ---- 2. Seleccionar un trip (en GTFS cada ruta tiene varios) ----
95
- trip_id = trips_ruta.iloc[0].trip_id
96
- st.write(f"Usando trip: `{trip_id}`")
97
-
98
- stops_trip = stop_times[stop_times.trip_id == trip_id].merge(stops, on="stop_id")
99
-
100
- # ---- 3. Buscar destino por nombre aproximado ----
101
- destino_results = stops_trip[stops_trip.stop_name.str.contains(destino, case=False, na=False)]
102
-
103
- if not destino_results.empty:
104
- parada_destino = destino_results.iloc[0]
105
- st.success(f"Esta ruta **SÍ** te sirve. Debes bajarte en: **{parada_destino.stop_name}**")
106
- else:
107
- st.warning("Esta ruta NO te lleva directamente al destino. (Transbordos: próximo paso)")
108
- parada_destino = None
109
-
110
- # =========================
111
- # MAPA
112
- # =========================
113
-
114
- st.header("🗺️ Mapa de tu ruta y posición")
115
-
116
- # Crear mapa centrado en la posición actual
117
- m = folium.Map(location=[stop_actual["stop_lat"], stop_actual["stop_lon"]], zoom_start=13)
118
-
119
- # ---- Marcar posición actual ----
120
- folium.Marker(
121
- [stop_actual["stop_lat"], stop_actual["stop_lon"]],
122
- tooltip="Estás aquí",
123
- icon=folium.Icon(color="blue")
124
- ).add_to(m)
125
-
126
- # ---- Dibujar route shape ----
127
- # Buscar shape_id asociado
128
- shape_id = trips_ruta.iloc[0].shape_id
129
- shape_geom = shapes_gdf[shapes_gdf.shape_id == shape_id].geometry.iloc[0]
130
-
131
- folium.PolyLine(
132
- locations=[(lat, lon) for lon, lat in zip(shape_geom.coords.xy[0], shape_geom.coords.xy[1])],
133
- weight=5,
134
- color="red",
135
- tooltip=f"Ruta {ruta_seleccionada}"
136
- ).add_to(m)
137
-
138
- # ---- Marcar destino si existe----
139
- if parada_destino is not None:
140
- folium.Marker(
141
- [parada_destino.stop_lat, parada_destino.stop_lon],
142
- tooltip=f"Destino: {parada_destino.stop_name}",
143
- icon=folium.Icon(color="green")
144
- ).add_to(m)
145
-
146
  st_folium(m, width=700, height=500)
 
1
+ import streamlit as st
2
+ from pyproj import CRS
3
+ import pandas as pd
4
+ import geopandas as gpd
5
+ from shapely.geometry import LineString, Point
6
+ import folium
7
+ from streamlit_folium import st_folium
8
+
9
+ import os, sys
10
+ import traceback
11
+
12
+ print(">>> Ejecutando archivo:", os.path.abspath(__file__))
13
+ print("Python ejecutado:", sys.executable)
14
+
15
+ # Cargar shapes.txt manteniendo la precisión
16
+ shapes = pd.read_csv('shapes.txt')
17
+ routes = pd.read_csv('routes.txt')
18
+ stops = pd.read_csv('stops.txt')
19
+ stop_times = pd.read_csv('stop_times.txt')
20
+ trips = pd.read_csv('trips.txt')
21
+
22
+ # Convertir puntos a geometría
23
+ shapes_gdf = (
24
+ shapes.sort_values(["shape_id", "shape_pt_sequence"])
25
+ .groupby("shape_id")
26
+ .apply(lambda x: LineString(zip(x.shape_pt_lon, x.shape_pt_lat)))
27
+ .reset_index()
28
+ )
29
+
30
+ shapes_gdf.columns = ["shape_id", "geometry"]
31
+ crs_obj = CRS.from_epsg(4326) # Crea el objeto CRS correctamente
32
+ shapes_gdf = gpd.GeoDataFrame(shapes_gdf, geometry="geometry", crs=crs_obj)
33
+
34
+ # =========================
35
+ # UI
36
+ # =========================
37
+ st.title("🚍 Planificador inteligente — TransMilenio")
38
+
39
+ st.write("Esta app detecta si la ruta **en la que ya vas** te sirve para llegar al destino.")
40
+
41
+
42
+ # =========================
43
+ # INPUTS DEL USUARIO
44
+ # =========================
45
+
46
+ st.header("1️⃣ ¿En qué ruta vas?")
47
+ ruta_seleccionada = st.selectbox(
48
+ "Selecciona tu ruta",
49
+ routes.route_short_name.unique(),
50
+ )
51
+
52
+ st.header("2️⃣ ¿Dónde estás?")
53
+ col1, col2 = st.columns(2)
54
+ with col1:
55
+ modo_origen = st.radio("Selecciona cómo indicar dónde estás:", ["Parada", "Coordenadas"])
56
+
57
+ if modo_origen == "Parada":
58
+ parada_origen = st.selectbox("Selecciona tu parada actual", stops.stop_name.unique())
59
+ stop_actual = stops[stops.stop_name == parada_origen].iloc[0]
60
+
61
+ else:
62
+ lat = st.number_input("Latitud", value=4.65)
63
+ lon = st.number_input("Longitud", value=-74.1)
64
+ stop_actual = {"stop_lat": lat, "stop_lon": lon}
65
+
66
+
67
+ st.header("3️⃣ ¿A dónde vas?")
68
+ destino = st.text_input("Escribe la parada o dirección de destino")
69
+
70
+ calcular = st.button("Calcular ruta")
71
+
72
+ # =========================
73
+ # PROCESAMIENTO
74
+ # =========================
75
+
76
+ if calcular:
77
+
78
+ # ---- 1. Filtrar rutas por route_short_name ----
79
+ route_id = routes.loc[routes.route_short_name == ruta_seleccionada, "route_id"].iloc[0]
80
+ trips_ruta = trips[trips.route_id == route_id]
81
+
82
+ if trips_ruta.empty:
83
+ st.error("No se encontraron viajes para esta ruta.")
84
+ st.stop()
85
+
86
+ # ---- 2. Seleccionar un trip (en GTFS cada ruta tiene varios) ----
87
+ trip_id = trips_ruta.iloc[0].trip_id
88
+ st.write(f"Usando trip: `{trip_id}`")
89
+
90
+ stops_trip = stop_times[stop_times.trip_id == trip_id].merge(stops, on="stop_id")
91
+
92
+ # ---- 3. Buscar destino por nombre aproximado ----
93
+ destino_results = stops_trip[stops_trip.stop_name.str.contains(destino, case=False, na=False)]
94
+
95
+ if not destino_results.empty:
96
+ parada_destino = destino_results.iloc[0]
97
+ st.success(f"Esta ruta **SÍ** te sirve. Debes bajarte en: **{parada_destino.stop_name}**")
98
+ else:
99
+ st.warning("Esta ruta NO te lleva directamente al destino. (Transbordos: próximo paso)")
100
+ parada_destino = None
101
+
102
+ # =========================
103
+ # MAPA
104
+ # =========================
105
+
106
+ st.header("🗺️ Mapa de tu ruta y posición")
107
+
108
+ # Crear mapa centrado en la posición actual
109
+ m = folium.Map(location=[stop_actual["stop_lat"], stop_actual["stop_lon"]], zoom_start=13)
110
+
111
+ # ---- Marcar posición actual ----
112
+ folium.Marker(
113
+ [stop_actual["stop_lat"], stop_actual["stop_lon"]],
114
+ tooltip="Estás aquí",
115
+ icon=folium.Icon(color="blue")
116
+ ).add_to(m)
117
+
118
+ # ---- Dibujar route shape ----
119
+ # Buscar shape_id asociado
120
+ shape_id = trips_ruta.iloc[0].shape_id
121
+ shape_geom = shapes_gdf[shapes_gdf.shape_id == shape_id].geometry.iloc[0]
122
+
123
+ folium.PolyLine(
124
+ locations=[(lat, lon) for lon, lat in zip(shape_geom.coords.xy[0], shape_geom.coords.xy[1])],
125
+ weight=5,
126
+ color="red",
127
+ tooltip=f"Ruta {ruta_seleccionada}"
128
+ ).add_to(m)
129
+
130
+ # ---- Marcar destino si existe----
131
+ if parada_destino is not None:
132
+ folium.Marker(
133
+ [parada_destino.stop_lat, parada_destino.stop_lon],
134
+ tooltip=f"Destino: {parada_destino.stop_name}",
135
+ icon=folium.Icon(color="green")
136
+ ).add_to(m)
137
+
 
 
 
 
 
 
 
 
138
  st_folium(m, width=700, height=500)