waqasbm's picture
Create app.py
bfaf81a verified
import streamlit as st
import pandas as pd
import folium
from streamlit_folium import st_folium
from datetime import datetime
from geopy.distance import geodesic
import requests
import os
import json
# -----------------------------
# GROQ API Configuration
# -----------------------------
GROQ_API_URL = "https://api.groq.com/openai/v1/chat/completions"
GROQ_API_KEY = st.secrets["TMS"] if "GROQ_API_KEY" in st.secrets else os.getenv("GROQ_API_KEY")
HEADERS = {
"Authorization": f"Bearer {GROQ_API_KEY}",
"Content-Type": "application/json"
}
# -----------------------------
# Traccar API Configuration (Simulated Setup)
# -----------------------------
TRACCAR_API_URL = "https://demo.traccar.org/api"
TRACCAR_USERNAME = st.secrets["TRACCAR_USERNAME"] if "TRACCAR_USERNAME" in st.secrets else os.getenv("TRACCAR_USERNAME")
TRACCAR_PASSWORD = st.secrets["TRACCAR_PASSWORD"] if "TRACCAR_PASSWORD" in st.secrets else os.getenv("TRACCAR_PASSWORD")
# -----------------------------
# Simulated Databases
# -----------------------------
employee_data = pd.DataFrame({
"Employee ID": ["E001", "E002", "E003"],
"Name": ["Alice", "Bob", "Charlie"],
"Pickup Location": [(28.6139, 77.2090), (28.7041, 77.1025), (28.5355, 77.3910)]
})
vehicle_data = pd.DataFrame({
"Vehicle ID": ["V001", "V002"],
"Driver Name": ["Ravi", "Sunil"],
"Capacity": [2, 2],
"Current Location": [(28.6448, 77.2167), (28.4595, 77.0266)]
})
allocation = {}
# -----------------------------
# Utility Functions
# -----------------------------
def allocate_vehicles():
global allocation
allocation = {v_id: [] for v_id in vehicle_data["Vehicle ID"]}
emp_index = 0
for v_id in allocation:
cap = int(vehicle_data[vehicle_data["Vehicle ID"] == v_id]["Capacity"].values[0])
while cap > 0 and emp_index < len(employee_data):
allocation[v_id].append(employee_data.iloc[emp_index].to_dict())
emp_index += 1
cap -= 1
def show_map():
m = folium.Map(location=[28.6139, 77.2090], zoom_start=10)
# Employee locations
for _, row in employee_data.iterrows():
folium.Marker(location=row["Pickup Location"], tooltip=f"{row['Name']}").add_to(m)
# Vehicle locations
for _, row in vehicle_data.iterrows():
folium.Marker(location=row["Current Location"], tooltip=f"Vehicle: {row['Vehicle ID']} (Driver: {row['Driver Name']})", icon=folium.Icon(color='green')).add_to(m)
st_folium(m, width=700)
def generate_summary(log_text):
if not GROQ_API_KEY:
return "GROQ API key not provided."
payload = {
"model": "mixtral-8x7b-32768",
"messages": [
{"role": "system", "content": "You are a helpful assistant summarizing GPS log data."},
{"role": "user", "content": log_text}
]
}
try:
response = requests.post(GROQ_API_URL, headers=HEADERS, data=json.dumps(payload))
result = response.json()
return result['choices'][0]['message']['content']
except Exception as e:
return f"Error: {e}"
def fetch_traccar_device_locations():
if not TRACCAR_USERNAME or not TRACCAR_PASSWORD:
return []
try:
response = requests.get(
f"{TRACCAR_API_URL}/positions",
auth=(TRACCAR_USERNAME, TRACCAR_PASSWORD)
)
if response.status_code == 200:
return response.json()
else:
st.warning("Failed to fetch real-time data from Traccar API.")
return []
except Exception as e:
st.error(f"Traccar API error: {e}")
return []
# -----------------------------
# Streamlit UI
# -----------------------------
st.title("Company Vehicle Transport Management System")
menu = st.sidebar.selectbox("Menu", ["Dashboard", "Allocate Vehicles", "Track Vehicles", "Summarize Logs"])
if menu == "Dashboard":
st.subheader("Employee Data")
st.dataframe(employee_data)
st.subheader("Vehicle Data")
st.dataframe(vehicle_data)
elif menu == "Allocate Vehicles":
allocate_vehicles()
st.subheader("Allocation Result")
for v_id, emp_list in allocation.items():
st.write(f"**Vehicle {v_id}**")
for emp in emp_list:
st.write(f"- {emp['Name']} (ID: {emp['Employee ID']})")
elif menu == "Track Vehicles":
st.subheader("Live Vehicle and Employee Location Map")
positions = fetch_traccar_device_locations()
if positions:
m = folium.Map(location=[28.6139, 77.2090], zoom_start=10)
for pos in positions:
lat = pos.get("latitude")
lon = pos.get("longitude")
device_id = pos.get("deviceId")
folium.Marker(location=[lat, lon], tooltip=f"Device ID: {device_id}", icon=folium.Icon(color='blue')).add_to(m)
st_folium(m, width=700)
else:
show_map()
elif menu == "Summarize Logs":
st.subheader("Summarize Driver/Vehicle Logs")
log_text = st.text_area("Paste GPS or Driver Log Text:")
if st.button("Summarize with GROQ"):
with st.spinner("Generating summary..."):
summary = generate_summary(log_text)
st.success("Summary:")
st.write(summary)
# -----------------------------
# TODO: Integration Points
# -----------------------------
# - Add user authentication system
# - Store and retrieve persistent data from a database like Firebase or Supabase