import pandas as pd
import plotly.graph_objects as go
import gradio as gr
import requests
import os
from dotenv import load_dotenv
load_dotenv()
backendurl = os.getenv("backendurl")
"""username = str(os.getenv("username"))
password = str(os.getenv("password"))"""
def faculty(request:gr.Request) ->list:
if request.username == "sarath":
return [54000,"Route-42"]
return ["NA","NA"]
def update_message(request:gr.Request):
username = f"{request.username}"
if username == "sarath":
return ["Sarath Rajan Senthilkumar","21BCE5965","Route-42","Thillai Ganga Nagar Subway","6:57 AM","7:50 AM"]
else:
return [username,None,None,None,None,None]
def getAllRoutes():
url = backendurl+"/routeNames"
try:
response = requests.get(url)
response.raise_for_status()
return response.json()
except requests.exceptions.RequestException as e:
print(f"Error occurred: {e}")
return None
def getTimeBasedOnTraffic():
url = backendurl+"/trafficTime"
try:
response = requests.get(url)
response.raise_for_status()
return response.json()
except requests.exceptions.RequestException as e:
print(f"Error occurred: {e}")
return None
def getRoutesData(routes):
url = backendurl+"/routes"
params = {
"routes":routes
}
try:
response = requests.get(url, json=params)
response.raise_for_status()
return response.json()
except requests.exceptions.RequestException as e:
print(f"Error occurred: {e}")
return None
def showTrafficTimeStops(routes:list):
data =dict(getTimeBasedOnTraffic())
#print(data)
latData=[]
lonData=[]
routeNoData=[]
stopNameData=[]
timeData =[]
data.pop('status',None)
for key,val in data.items():
latData.append(val['Latitude'])
lonData.append(val['Longitude'])
routeNoData.append(val["Route_no"])
stopNameData.append(val['Stop_name'])
timeData.append(val["trafficTime"])
stops2d = [[v['Route_no'], v['Stop_name'],v['trafficTime']] for k, v in data.items()]
fig = go.Figure(go.Scattermapbox(
lat=latData,
lon=lonData,
mode='markers',
marker=go.scattermapbox.Marker(
size=9
),
hoverinfo="text",
hovertemplate='ROUTE_NO: %{text}
Stop_Name: %{customdata}',
text=routeNoData,
customdata=stopNameData
))
fig.update_layout(
mapbox_style="open-street-map",
hovermode='closest',
mapbox=dict(
bearing=0,
center=go.layout.mapbox.Center(
lat= 12.987872236090185,
lon=80.19545499870578
),
pitch=0,
zoom=9
),
)
return fig,stops2d
def showRoutes(routes:list):
data = dict(getRoutesData(routes))
#print(data)
latData=[]
lonData=[]
routeNoData=[]
stopNameData=[]
timeData =[]
data.pop('status',None)
for key,val in data.items():
latData.append(val['Latitude'])
lonData.append(val['Longitude'])
routeNoData.append(val["Route_no"])
stopNameData.append(val['Stop_name'])
timeData.append(val["Timing"])
stops2d = [[v['Route_no'], v['Stop_name'],v['Timing']] for k, v in data.items()]
fig = go.Figure(go.Scattermapbox(
lat=latData,
lon=lonData,
mode='markers',
marker=go.scattermapbox.Marker(
size=9
),
hoverinfo="text",
hovertemplate='ROUTE_NO: %{text}
Stop_Name: %{customdata}',
text=routeNoData,
customdata=stopNameData
))
fig.update_layout(
mapbox_style="open-street-map",
hovermode='closest',
mapbox=dict(
bearing=0,
center=go.layout.mapbox.Center(
lat=12.99468,
lon=80.25892
),
pitch=0,
zoom=9
),
)
return fig,stops2d
def showStops(stops):
fig = go.Figure(go.Scattermapbox(
lat=[i[2] for i in stops],
lon=[i[3] for i in stops],
mode='markers',
marker=go.scattermapbox.Marker(
size=6
),
hoverinfo="text",
hovertemplate='ROUTE_NO: %{text}
Stop_Name: %{customdata}',
text=[i[0] for i in stops],
customdata=[i[1] for i in stops]
))
fig.update_layout(
mapbox_style="open-street-map",
hovermode='closest',
mapbox=dict(
bearing=0,
center=go.layout.mapbox.Center(
lat=12.99468,
lon=80.25892
),
pitch=0,
zoom=9
),
)
return fig
def geocode(address:str):
url = backendurl+"/findGeoCoordinates"
params = {
"address":address
}
try:
response = requests.get(url, json=params)
response.raise_for_status()
return response.json()
except requests.exceptions.RequestException as e:
print(f"Error occurred: {e}")
return None
def calculate_distance(latitude: float, longitude: float, distance: float):
url = backendurl+"/calculateDistance"
params = {
"latitude": latitude,
"longitude": longitude,
"distance": distance
}
try:
response = requests.get(url, json=params)
response.raise_for_status()
return response.json()
except requests.exceptions.RequestException as e:
print(f"Error occurred: {e}")
return None
def nearestStops(address,dist):
geocoordinates = dict(geocode(address))
lat = geocoordinates["latitude"]
lon = geocoordinates["longitude"]
stops = dict(calculate_distance(lat,lon,dist))
stops.pop('status',None)
stops2d = [[v['Route_no'], v['Stop_name'], v['Latitude'], v['Longitude'], v['Timing']] for k, v in stops.items()]
map=showStops(stops2d)
stops2d = [[v['Route_no'], v['Stop_name'],v['Timing'],round(v['Distance'],2)] for k, v in stops.items()]
stops2d.sort(key=lambda x:x[3])
return map,stops2d
def startGradio():
Routes=["All Routes"]
Routes.extend(dict(getAllRoutes())["routeNames"])
# Create the Gradio interface
with gr.Blocks() as demo:
state = gr.State({})
def setFaculty(request:gr.Request):
if request.username == "sarath":
state.value={"faculty":True}
gr.update(elem_id="faculty",visible=True)
else:
state.value={"faculty":False}
text1 = gr.Text(value="College Bus Route Tracker",interactive=False,show_label=False)
with gr.Column():
with gr.Row():
username = gr.Text(label="Student/Faculty Name",interactive=False)
registerNo = gr.Text(label="Register No/ Employee ID",interactive=False)
with gr.Row():
busRoute = gr.Text(label="Route No",interactive=False)
stopName = gr.Text(label="Stop Name",interactive=False)
with gr.Row():
busBoarding = gr.Text(label="Bus Boarding Time",interactive=False,)
busDeBoarding = gr.Text(label="Bus Disembarking time",interactive=False)
demo.load(update_message,None,outputs=[username,registerNo,busRoute,stopName,busBoarding,busDeBoarding])
with gr.Tab("Route Map"):
with gr.Column():
routes = gr.CheckboxGroup(choices=Routes,label="Routes",value=["All Routes"])
map_component = gr.Plot(min_width=600)
table = gr.DataFrame(min_width=600,headers=["Route_no","Stop_name","Timing"])
#btn = gr.Button(value="Update Filter")
#demo.load(fn=showRoutes,inputs=[routes],outputs=[map_component,table])
demo.load(fn=showRoutes,inputs=[routes],outputs=[map_component,table])
routes.change(fn=showRoutes,inputs=[routes],outputs=[map_component,table])
#btn.click(fn=showRoutes,inputs=[routes],outputs=[map_component,table])
with gr.Tab("Nearest Stop Finder"):
with gr.Column():
text3 = gr.Text(show_label=False,placeholder="Enter your address")
slider1 = gr.Slider(minimum=1,maximum=4,label="Select range")
btn1 = gr.Button()
map_component1 = gr.Plot()
table1 = gr.DataFrame(min_width=600,headers=["Route_no","Stop_name","Timing","Distance (K.M)"])
btn1.click(fn=nearestStops,inputs=[text3,slider1],outputs=[map_component1,table1])
demo.load()
with gr.Tab("Request to Change Bus",elem_id="faculty"):
with gr.Column():
facultyId = gr.Text(interactive=False,label="FacultyId")
FacultyBus = gr.Text(interactive=False,label="Faculty Bus No")
changeBus = gr.Dropdown(choices=["Route 27","Route 27A","Route 42"],label="Change to route")
changeButton = gr.Button(value="Request Change to Bus")
demo.load(faculty,None,outputs=[facultyId,FacultyBus])
with gr.Tab("Incident Report"):
with gr.Column():
busRoute = gr.Dropdown(interactive=True,label="Route No",choices=(dict(getAllRoutes())["routeNames"]))
incidentType = gr.Dropdown(choices=["Accident","Discipline Releated","Rash Driving","Rude Behaviour of Driver","Bus late to Stop","Bus early to Stop"])
description = gr.Textbox(placeholder="Give a brief overview of your situation")
submit = gr.Button(value="Submit")
with gr.Tab("Time to Stop based on Traffic"):
with gr.Column():
Routes = ["Route-42"]
routes = gr.CheckboxGroup(choices=Routes,label="Routes",value=["Route-42"])
map_component2 = gr.Plot()
table = gr.DataFrame(min_width=600,headers=["Route_no","Stop_name","Timing"])
demo.load(fn=showTrafficTimeStops,inputs=[routes],outputs=[map_component2,table])
demo.load(setFaculty,None,None)
#text2 = gr.Textbox(value="A app based on the research done by \n1.Sarath Rajan Senthilkumar \n2.Veer Jabak \n3.Gautham Vidyashankar \n4.Divij D\n5.Dr Srisakthi Saravanan",show_label=False,interactive=False)
demo.launch()
if __name__ == "__main__":
startGradio()