Spaces:
Sleeping
Sleeping
File size: 5,405 Bytes
bfaf81a |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 |
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 |