IAMTFRMZA's picture
Update app.py
a137762 verified
raw
history blame
3.8 kB
import pandas as pd
import gspread
from oauth2client.service_account import ServiceAccountCredentials
import gradio as gr
import plotly.express as px
# === Google Sheets Auth ===
scope = ["https://spreadsheets.google.com/feeds", "https://www.googleapis.com/auth/drive"]
creds = ServiceAccountCredentials.from_json_keyfile_name("tough-star.json", scope)
client = gspread.authorize(creds)
# === Load sheet data ===
sheet_url = "https://docs.google.com/spreadsheets/d/1bpeFS6yihb6niCavpwjWmVEypaSkGxONGg2jZfKX_sA"
sheet = client.open_by_url(sheet_url).worksheet("Calls")
data = sheet.get_all_records()
df = pd.DataFrame(data)
# === Parse and clean ===
df['Timestamp'] = pd.to_datetime(df['Timestamp'], dayfirst=True, errors='coerce')
df['Date'] = df['Timestamp'].dt.date.astype(str) # Convert to string
df['Time'] = df['Timestamp'].dt.time
location_split = df['Location'].str.split(',', expand=True)
df['Latitude'] = pd.to_numeric(location_split[0], errors='coerce')
df['Longitude'] = pd.to_numeric(location_split[1], errors='coerce')
df = df.dropna(subset=['Date', 'Rep Name', 'Latitude', 'Longitude'])
df = df[(df['Latitude'] != 0) & (df['Longitude'] != 0)]
df = df.sort_values(by=['Rep Name', 'Timestamp'])
df['Time Diff (min)'] = df.groupby(['Rep Name', 'Date'])['Timestamp'].diff().dt.total_seconds().div(60).fillna(0)
# === Functions ===
def get_reps(date_str):
reps = df[df['Date'] == date_str]['Rep Name'].dropna().unique()
return sorted(reps)
def show_map(date_str, rep):
subset = df[(df['Date'] == date_str) & (df['Rep Name'] == rep)]
if subset.empty:
return "No valid data", None
subset = subset.sort_values(by='Timestamp').copy()
subset['Visit Order'] = range(1, len(subset) + 1)
# Center and size for better visibility
center_lat = subset['Latitude'].mean()
center_lon = subset['Longitude'].mean()
# Line + colored scatter
fig = px.line_mapbox(
subset,
lat="Latitude", lon="Longitude",
hover_name="Dealership Name",
hover_data={"Time": True, "Time Diff (min)": True, "Visit Order": True},
height=700,
zoom=13,
center={"lat": center_lat, "lon": center_lon}
)
# Colored points by visit order
scatter = px.scatter_mapbox(
subset,
lat="Latitude", lon="Longitude",
color="Visit Order",
hover_name="Dealership Name",
hover_data=["Time", "Time Diff (min)"],
color_continuous_scale="Bluered"
)
for trace in scatter.data:
fig.add_trace(trace)
# Start/End markers
fig.add_trace(px.scatter_mapbox(
pd.DataFrame([subset.iloc[0]]),
lat="Latitude", lon="Longitude",
text=["Start"], color_discrete_sequence=["green"]).data[0])
fig.add_trace(px.scatter_mapbox(
pd.DataFrame([subset.iloc[-1]]),
lat="Latitude", lon="Longitude",
text=["End"], color_discrete_sequence=["red"]).data[0])
fig.update_layout(mapbox_style="open-street-map", title=f"πŸ“ {rep}'s Route on {date_str}")
table = subset[['Dealership Name', 'Time', 'Time Diff (min)', 'Visit Order']]
return table, fig
# === Gradio UI ===
def update(date_str):
return gr.Dropdown(choices=get_reps(date_str), label="Select Rep")
with gr.Blocks() as app:
gr.Markdown("## πŸ—ΊοΈ Rep Route & Visit Visualizer")
date_picker = gr.Dropdown(
label="Select Date",
choices=sorted(df['Date'].unique(), reverse=True)
)
rep_picker = gr.Dropdown(label="Select Rep")
btn = gr.Button("Show Route")
table = gr.Dataframe(label="Call Table")
map_plot = gr.Plot(label="Map")
date_picker.change(fn=update, inputs=date_picker, outputs=rep_picker)
btn.click(fn=show_map, inputs=[date_picker, rep_picker], outputs=[table, map_plot])
app.launch()