import streamlit as st import streamlit.components.v1 as components import pandas as pd import numpy as np import utils # personal library utils.py file import gmplot import os from dotenv import load_dotenv # Load the .env file load_dotenv() # Get the Hugging Face token from the environment variables google_map_token = os.getenv('GOOGLE_MAP_API_KEY') url_dict = {"Incidents": "http://datamall2.mytransport.sg/ltaodataservice/TrafficIncidents", "SpeedBands": "http://datamall2.mytransport.sg/ltaodataservice/v3/TrafficSpeedBands"} # st.balloons() st.title("LTA Singapore Traffic Watch") st.write("Welcome to the app for live traffic reporting, where you may find relevant road conditions ✨ " "This app reports any road incidents, roadworks in Singapore at a given time from " "Singapore's Land Transport Authority and also points out location and detailed information about the incident. ") st.write("The table below displays the traffic report: ") incidents_df, speedbands_df = utils.get_lta_data(url_dict) # Add the 'Issue' column to the front of the DataFrame incidents_df.insert(0, 'Issue', True) new_df = st.data_editor( incidents_df, column_config = { "Issue":st.column_config.CheckboxColumn( "Issue or Non-issue?", default = True ) } ) issue_cnt = len(new_df[new_df['Issue']==True]) total_cnt = len(new_df) issue_perc = f"{issue_cnt/total_cnt*100:.0f}%" col1, col2 = st.columns([1,1]) with col1: st.metric("Number of issues",issue_cnt) with col2: st.metric("Percent of reported incidents", issue_perc) st.markdown("Real-Time Accident or Roadworks Monitoring using Streamlit Map") #plotting a map with the above defined points new_df = new_df.rename(columns={"Latitude": "latitude", "Longitude": "longitude"}) st.map(new_df[new_df['Issue']==True][['latitude', 'longitude']]) st.divider() st.write("*First*, I created some filters to slice and dice the traffic report") col1, col2 = st.columns([1,1]) with col1: issue_filter = st.selectbox("Issues or Non-issues", options = new_df.Issue.unique()) with col2: category_filter = st.selectbox("Choose a category", options = new_df[new_df["Issue"]==issue_filter].Type.unique()) st.dataframe(new_df[(new_df['Issue'] == issue_filter) & (new_df['Type'] == category_filter)]) st.write("*Next*, we can visualize our data quickly using `st.metrics` and `st.bar_plot`") df_plot = new_df[new_df['Type']!=''].Type.value_counts().reset_index() st.bar_chart(df_plot, x = 'Type', y = 'count') st.divider() # code for Google map plotting # Indicate traffic disruption as 1 else 0 minor_disruption_list = ["Roadwork"] incidents_df['Color_Indicator'] = incidents_df['Type'].apply(lambda x: 0 if x in minor_disruption_list else 1) # Pack the coordinates for polygon speedbands_df['polygon'] = speedbands_df.apply(utils.zip_columns, axis=1) # Create the map plotter: center_lat = incidents_df['Latitude'].iloc[incidents_df.shape[0] // 2] center_lng = incidents_df['Longitude'].iloc[incidents_df.shape[0] // 2] zoom = 5 x = incidents_df['Longitude'].to_numpy() y = incidents_df['Latitude'].to_numpy() z = incidents_df['Color_Indicator'].to_numpy() polygons = speedbands_df['polygon'] speeds = speedbands_df['SpeedBand'] colors = list(map(utils.get_color_from_value, z)) # gmap = gmplot.GoogleMapPlotter(center_lat, center_lng, zoom, apikey=google_map_token, map_type='roadmap') # gmap.scatter(y, x, color=colors, size=2, marker=True) # utils.plot_polygon_with_speed(polygons, speeds, gmap, 'map2.html') # --------------------------------------------------------------------------------- st.markdown("Embedded Google Maps HTML from web-hosting site") st.write("This part shows the Google Map where the incidents and speedbands are plotted. " "Unfortunately, I am unable to embed my Google Maps HTML file on Streamlit." "Therefore, I have used a web-hosting site to host my html file and then display it here " "for the assignment. I have indicated red as an accident and yellow of all other incident " "types. For speedbands, blue indicates slow traffic speed whereas magenta indicates " "fast. Both incidents and speedbands are plotted on the same map to give users information " "on traffic conditions and incidents happening on the road, and if there is connection between them.") # Read the HTML file map_url = "https://lta-sg-archived-traffic-monitoring.tiiny.site" # Adjust the path if necessary # HTML content with iframe to embed the Google Map iframe_html = f""" Embedded Google Map """ # Embed the iframe in the Streamlit app components.html(iframe_html, height=800) st.write("Here we are at the end of the traffic report, powered by Streamlit! :balloon:")