hedtorresca commited on
Commit
05bd3a4
Β·
verified Β·
1 Parent(s): 98da995

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +41 -35
app.py CHANGED
@@ -1,23 +1,26 @@
1
- import os, json, pathlib
 
 
2
  import pandas as pd
3
  import plotly.express as px
4
  import gradio as gr
5
  import folium
6
  from folium.plugins import MarkerCluster
7
 
8
- # ──────────────────────────────────────────────────────────────────────────────
9
- # 1. Cargar y preparar datos
10
- # ──────────────────────────────────────────────────────────────────────────────
11
- DATA_XLSX = "Base de Datos Prueba.xlsx" # Debe estar junto a este script
 
 
12
  df = pd.read_excel(DATA_XLSX, parse_dates=["FECHA_APERTURA"])
13
  df["MES"] = df["FECHA_APERTURA"].dt.to_period("M").dt.to_timestamp()
14
- oficinas = sorted(df["OFICINA"].dropna().unique())
15
- productos = sorted(df["TIPO PRODUCTO"].dropna().unique())
 
16
  min_amt, max_amt = int(df["MONTO_I"].min()), int(df["MONTO_I"].max())
17
 
18
- # ──────────────────────────────────────────────────────────────────────────────
19
- # 2. Coordenadas hard-coded de oficinas
20
- # ──────────────────────────────────────────────────────────────────────────────
21
  office_coords = {
22
  "MonterΓ­a Centro": (8.74733, -75.88145),
23
  "Monteria": (8.74733, -75.88145),
@@ -41,26 +44,26 @@ office_coords = {
41
  "Buenos Aires": (2.28889, -76.14583),
42
  }
43
 
44
- # ──────────────────────────────────────────────────────────────────────────────
45
- # 3. FunciΓ³n principal para generar grΓ‘ficos + mapa Folium
46
- # ──────────────────────────────────────────────────────────────────────────────
47
- def dashboard(f_inicio, f_fin, tipos, ofis, rango_monto):
48
  d = df.copy()
49
- if f_inicio: d = d[d["FECHA_APERTURA"] >= pd.to_datetime(f_inicio)]
50
- if f_fin: d = d[d["FECHA_APERTURA"] <= pd.to_datetime(f_fin)]
51
  if tipos: d = d[d["TIPO PRODUCTO"].isin(tipos)]
52
  if ofis: d = d[d["OFICINA"].isin(ofis)]
53
- d = d[(d["MONTO_I"] >= rango_monto[0]) & (d["MONTO_I"] <= rango_monto[1])]
54
 
55
  # GrΓ‘fico 1: barras mensuales
56
  fig1 = px.bar(
57
  d.groupby("MES")["MONTO_I"].sum().reset_index(),
58
  x="MES", y="MONTO_I",
59
- labels={"MES":"Mes", "MONTO_I":"Monto (COP)"},
60
  title="Monto desembolsado por mes"
61
  )
62
 
63
- # GrΓ‘fico 2: pastel de productos
64
  df2 = d["TIPO PRODUCTO"].value_counts().reset_index()
65
  df2.columns = ["TIPO PRODUCTO","CANT"]
66
  fig2 = px.pie(df2, names="TIPO PRODUCTO", values="CANT",
@@ -77,35 +80,36 @@ def dashboard(f_inicio, f_fin, tipos, ofis, rango_monto):
77
  m = folium.Map(location=[4.6, -74.1], zoom_start=6, tiles="OpenStreetMap")
78
  mc = MarkerCluster().add_to(m)
79
  for ofi, (lat, lon) in office_coords.items():
80
- if (lat is None) or (lon is None): continue
81
- sub = d[d["OFICINA"] == ofi]
82
- if sub.empty: continue
83
- total = sub["MONTO_I"].sum()
84
  folium.CircleMarker(
85
- location=(lat, lon),
86
- radius=7,
87
- color="blue",
88
  fill=True,
89
- fill_opacity=0.6,
90
  popup=f"{ofi}<br>Total: {total:,.0f} COP"
91
  ).add_to(mc)
92
  map_html = m._repr_html_()
93
 
94
  return fig1, fig2, fig3, map_html
95
 
96
- # ───────────────────────────────────────��──────────────────────────────────────
97
- # 4. Interfaz Gradio v4 – pestaΓ±as + HTML para Folium
98
- # ──────────────────────────────────────────────────────────────────────────────
99
- with gr.Blocks(theme=gr.themes.Soft()) as demo:
100
  gr.Markdown("## Dashboard BancamΓ­a – Aperturas Q1 2025")
 
101
  with gr.Row():
102
  with gr.Column(scale=1):
103
- dp1 = gr.Date(label="Desde", value="2025-01-01")
104
- dp2 = gr.Date(label="Hasta", value="2025-03-31")
105
  dd1 = gr.Dropdown(productos, multiselect=True, label="Tipo de Producto")
106
  dd2 = gr.Dropdown(oficinas, multiselect=True, label="Oficina")
107
- rs = gr.RangeSlider(min_amt, max_amt, value=[min_amt, max_amt], label="Monto (COP)")
 
108
  btn = gr.Button("Actualizar")
 
109
  with gr.Column(scale=3):
110
  with gr.Tab("Monto"):
111
  out1 = gr.Plot()
@@ -115,7 +119,9 @@ with gr.Blocks(theme=gr.themes.Soft()) as demo:
115
  out3 = gr.Plot()
116
  with gr.Tab("Mapa"):
117
  out4 = gr.HTML()
 
118
  btn.click(dashboard, [dp1, dp2, dd1, dd2, rs], [out1, out2, out3, out4])
119
 
120
  if __name__ == "__main__":
121
- demo.launch(server_name="0.0.0.0", server_port=int(os.environ.get("PORT", 7860)))
 
 
1
+ import os
2
+ import json
3
+ import pathlib
4
  import pandas as pd
5
  import plotly.express as px
6
  import gradio as gr
7
  import folium
8
  from folium.plugins import MarkerCluster
9
 
10
+ # -------------------------------
11
+ # 1. ConfiguraciΓ³n y datos
12
+ # -------------------------------
13
+ DATA_XLSX = "Base de Datos Prueba.xlsx"
14
+ COORDS_JSON = "office_coords.json"
15
+
16
  df = pd.read_excel(DATA_XLSX, parse_dates=["FECHA_APERTURA"])
17
  df["MES"] = df["FECHA_APERTURA"].dt.to_period("M").dt.to_timestamp()
18
+
19
+ oficinas = sorted(df["OFICINA"].dropna().unique().tolist())
20
+ productos = sorted(df["TIPO PRODUCTO"].dropna().unique().tolist())
21
  min_amt, max_amt = int(df["MONTO_I"].min()), int(df["MONTO_I"].max())
22
 
23
+ # Coordenadas hard-coded (todas)
 
 
24
  office_coords = {
25
  "MonterΓ­a Centro": (8.74733, -75.88145),
26
  "Monteria": (8.74733, -75.88145),
 
44
  "Buenos Aires": (2.28889, -76.14583),
45
  }
46
 
47
+ # -------------------------------
48
+ # 2. FunciΓ³n de filtrado y grΓ‘ficos
49
+ # -------------------------------
50
+ def dashboard(f_inicio, f_fin, tipos, ofis, rango):
51
  d = df.copy()
52
+ if f_inicio: d = d[d.FECHA_APERTURA >= pd.to_datetime(f_inicio)]
53
+ if f_fin: d = d[d.FECHA_APERTURA <= pd.to_datetime(f_fin)]
54
  if tipos: d = d[d["TIPO PRODUCTO"].isin(tipos)]
55
  if ofis: d = d[d["OFICINA"].isin(ofis)]
56
+ d = d[(d["MONTO_I"] >= rango[0]) & (d["MONTO_I"] <= rango[1])]
57
 
58
  # GrΓ‘fico 1: barras mensuales
59
  fig1 = px.bar(
60
  d.groupby("MES")["MONTO_I"].sum().reset_index(),
61
  x="MES", y="MONTO_I",
62
+ labels={"MES":"Mes","MONTO_I":"Monto (COP)"},
63
  title="Monto desembolsado por mes"
64
  )
65
 
66
+ # GrΓ‘fico 2: pie de productos
67
  df2 = d["TIPO PRODUCTO"].value_counts().reset_index()
68
  df2.columns = ["TIPO PRODUCTO","CANT"]
69
  fig2 = px.pie(df2, names="TIPO PRODUCTO", values="CANT",
 
80
  m = folium.Map(location=[4.6, -74.1], zoom_start=6, tiles="OpenStreetMap")
81
  mc = MarkerCluster().add_to(m)
82
  for ofi, (lat, lon) in office_coords.items():
83
+ if lat is None or ofi not in d["OFICINA"].values: continue
84
+ total = d.loc[d["OFICINA"]==ofi, "MONTO_I"].sum()
 
 
85
  folium.CircleMarker(
86
+ location=[lat, lon],
87
+ radius=6,
88
+ color="navy",
89
  fill=True,
90
+ fill_opacity=0.7,
91
  popup=f"{ofi}<br>Total: {total:,.0f} COP"
92
  ).add_to(mc)
93
  map_html = m._repr_html_()
94
 
95
  return fig1, fig2, fig3, map_html
96
 
97
+ # -------------------------------
98
+ # 3. Interfaz Gradio v3 (Blocks API)
99
+ # -------------------------------
100
+ with gr.Blocks() as demo:
101
  gr.Markdown("## Dashboard BancamΓ­a – Aperturas Q1 2025")
102
+
103
  with gr.Row():
104
  with gr.Column(scale=1):
105
+ dp1 = gr.DatePicker(label="Desde", value="2025-01-01")
106
+ dp2 = gr.DatePicker(label="Hasta", value="2025-03-31")
107
  dd1 = gr.Dropdown(productos, multiselect=True, label="Tipo de Producto")
108
  dd2 = gr.Dropdown(oficinas, multiselect=True, label="Oficina")
109
+ rs = gr.Slider(minimum=min_amt, maximum=max_amt, value=[min_amt, max_amt],
110
+ step=1_000_000, label="Rango de Monto (COP)")
111
  btn = gr.Button("Actualizar")
112
+
113
  with gr.Column(scale=3):
114
  with gr.Tab("Monto"):
115
  out1 = gr.Plot()
 
119
  out3 = gr.Plot()
120
  with gr.Tab("Mapa"):
121
  out4 = gr.HTML()
122
+
123
  btn.click(dashboard, [dp1, dp2, dd1, dd2, rs], [out1, out2, out3, out4])
124
 
125
  if __name__ == "__main__":
126
+ demo.launch(server_name="0.0.0.0",
127
+ server_port=int(os.environ.get("PORT", 7860)))