waqasbm commited on
Commit
bfaf81a
·
verified ·
1 Parent(s): b1d4a00

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +153 -0
app.py ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import pandas as pd
3
+ import folium
4
+ from streamlit_folium import st_folium
5
+ from datetime import datetime
6
+ from geopy.distance import geodesic
7
+ import requests
8
+ import os
9
+ import json
10
+
11
+ # -----------------------------
12
+ # GROQ API Configuration
13
+ # -----------------------------
14
+ GROQ_API_URL = "https://api.groq.com/openai/v1/chat/completions"
15
+ GROQ_API_KEY = st.secrets["TMS"] if "GROQ_API_KEY" in st.secrets else os.getenv("GROQ_API_KEY")
16
+
17
+ HEADERS = {
18
+ "Authorization": f"Bearer {GROQ_API_KEY}",
19
+ "Content-Type": "application/json"
20
+ }
21
+
22
+ # -----------------------------
23
+ # Traccar API Configuration (Simulated Setup)
24
+ # -----------------------------
25
+ TRACCAR_API_URL = "https://demo.traccar.org/api"
26
+ TRACCAR_USERNAME = st.secrets["TRACCAR_USERNAME"] if "TRACCAR_USERNAME" in st.secrets else os.getenv("TRACCAR_USERNAME")
27
+ TRACCAR_PASSWORD = st.secrets["TRACCAR_PASSWORD"] if "TRACCAR_PASSWORD" in st.secrets else os.getenv("TRACCAR_PASSWORD")
28
+
29
+ # -----------------------------
30
+ # Simulated Databases
31
+ # -----------------------------
32
+ employee_data = pd.DataFrame({
33
+ "Employee ID": ["E001", "E002", "E003"],
34
+ "Name": ["Alice", "Bob", "Charlie"],
35
+ "Pickup Location": [(28.6139, 77.2090), (28.7041, 77.1025), (28.5355, 77.3910)]
36
+ })
37
+
38
+ vehicle_data = pd.DataFrame({
39
+ "Vehicle ID": ["V001", "V002"],
40
+ "Driver Name": ["Ravi", "Sunil"],
41
+ "Capacity": [2, 2],
42
+ "Current Location": [(28.6448, 77.2167), (28.4595, 77.0266)]
43
+ })
44
+
45
+ allocation = {}
46
+
47
+ # -----------------------------
48
+ # Utility Functions
49
+ # -----------------------------
50
+ def allocate_vehicles():
51
+ global allocation
52
+ allocation = {v_id: [] for v_id in vehicle_data["Vehicle ID"]}
53
+ emp_index = 0
54
+ for v_id in allocation:
55
+ cap = int(vehicle_data[vehicle_data["Vehicle ID"] == v_id]["Capacity"].values[0])
56
+ while cap > 0 and emp_index < len(employee_data):
57
+ allocation[v_id].append(employee_data.iloc[emp_index].to_dict())
58
+ emp_index += 1
59
+ cap -= 1
60
+
61
+ def show_map():
62
+ m = folium.Map(location=[28.6139, 77.2090], zoom_start=10)
63
+ # Employee locations
64
+ for _, row in employee_data.iterrows():
65
+ folium.Marker(location=row["Pickup Location"], tooltip=f"{row['Name']}").add_to(m)
66
+ # Vehicle locations
67
+ for _, row in vehicle_data.iterrows():
68
+ folium.Marker(location=row["Current Location"], tooltip=f"Vehicle: {row['Vehicle ID']} (Driver: {row['Driver Name']})", icon=folium.Icon(color='green')).add_to(m)
69
+ st_folium(m, width=700)
70
+
71
+ def generate_summary(log_text):
72
+ if not GROQ_API_KEY:
73
+ return "GROQ API key not provided."
74
+ payload = {
75
+ "model": "mixtral-8x7b-32768",
76
+ "messages": [
77
+ {"role": "system", "content": "You are a helpful assistant summarizing GPS log data."},
78
+ {"role": "user", "content": log_text}
79
+ ]
80
+ }
81
+ try:
82
+ response = requests.post(GROQ_API_URL, headers=HEADERS, data=json.dumps(payload))
83
+ result = response.json()
84
+ return result['choices'][0]['message']['content']
85
+ except Exception as e:
86
+ return f"Error: {e}"
87
+
88
+ def fetch_traccar_device_locations():
89
+ if not TRACCAR_USERNAME or not TRACCAR_PASSWORD:
90
+ return []
91
+ try:
92
+ response = requests.get(
93
+ f"{TRACCAR_API_URL}/positions",
94
+ auth=(TRACCAR_USERNAME, TRACCAR_PASSWORD)
95
+ )
96
+ if response.status_code == 200:
97
+ return response.json()
98
+ else:
99
+ st.warning("Failed to fetch real-time data from Traccar API.")
100
+ return []
101
+ except Exception as e:
102
+ st.error(f"Traccar API error: {e}")
103
+ return []
104
+
105
+ # -----------------------------
106
+ # Streamlit UI
107
+ # -----------------------------
108
+ st.title("Company Vehicle Transport Management System")
109
+
110
+ menu = st.sidebar.selectbox("Menu", ["Dashboard", "Allocate Vehicles", "Track Vehicles", "Summarize Logs"])
111
+
112
+ if menu == "Dashboard":
113
+ st.subheader("Employee Data")
114
+ st.dataframe(employee_data)
115
+ st.subheader("Vehicle Data")
116
+ st.dataframe(vehicle_data)
117
+
118
+ elif menu == "Allocate Vehicles":
119
+ allocate_vehicles()
120
+ st.subheader("Allocation Result")
121
+ for v_id, emp_list in allocation.items():
122
+ st.write(f"**Vehicle {v_id}**")
123
+ for emp in emp_list:
124
+ st.write(f"- {emp['Name']} (ID: {emp['Employee ID']})")
125
+
126
+ elif menu == "Track Vehicles":
127
+ st.subheader("Live Vehicle and Employee Location Map")
128
+ positions = fetch_traccar_device_locations()
129
+ if positions:
130
+ m = folium.Map(location=[28.6139, 77.2090], zoom_start=10)
131
+ for pos in positions:
132
+ lat = pos.get("latitude")
133
+ lon = pos.get("longitude")
134
+ device_id = pos.get("deviceId")
135
+ folium.Marker(location=[lat, lon], tooltip=f"Device ID: {device_id}", icon=folium.Icon(color='blue')).add_to(m)
136
+ st_folium(m, width=700)
137
+ else:
138
+ show_map()
139
+
140
+ elif menu == "Summarize Logs":
141
+ st.subheader("Summarize Driver/Vehicle Logs")
142
+ log_text = st.text_area("Paste GPS or Driver Log Text:")
143
+ if st.button("Summarize with GROQ"):
144
+ with st.spinner("Generating summary..."):
145
+ summary = generate_summary(log_text)
146
+ st.success("Summary:")
147
+ st.write(summary)
148
+
149
+ # -----------------------------
150
+ # TODO: Integration Points
151
+ # -----------------------------
152
+ # - Add user authentication system
153
+ # - Store and retrieve persistent data from a database like Firebase or Supabase