Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import pandas as pd
|
| 3 |
+
import streamlit as st
|
| 4 |
+
import matplotlib.pyplot as plt
|
| 5 |
+
import seaborn as sns
|
| 6 |
+
from groq import Groq
|
| 7 |
+
from typing import List
|
| 8 |
+
|
| 9 |
+
# ---- Setup Groq Client ---- #
|
| 10 |
+
client = Groq(api_key=("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"))
|
| 11 |
+
|
| 12 |
+
# ---- File Upload ---- #
|
| 13 |
+
st.title("🚦 Real-Time Traffic Optimization using RAG + Groq")
|
| 14 |
+
st.subheader("Upload Traffic Data (CSV)")
|
| 15 |
+
|
| 16 |
+
# Upload CSV file
|
| 17 |
+
uploaded_file = st.file_uploader("Choose a CSV file", type="csv")
|
| 18 |
+
|
| 19 |
+
if uploaded_file is not None:
|
| 20 |
+
# Read the CSV file into a DataFrame
|
| 21 |
+
df = pd.read_csv(uploaded_file)
|
| 22 |
+
|
| 23 |
+
# ---- Utility: Summarize traffic data to context ---- #
|
| 24 |
+
def summarize_traffic_data(df: pd.DataFrame) -> List[str]:
|
| 25 |
+
summaries = []
|
| 26 |
+
for index, row in df.iterrows():
|
| 27 |
+
summary = (
|
| 28 |
+
f"On {row['Date']} ({row['Day of the week']}) at {row['Time']}, "
|
| 29 |
+
f"there were {row['CarCount']} cars, {row['BikeCount']} bikes, "
|
| 30 |
+
f"{row['BusCount']} buses, and {row['TruckCount']} trucks. "
|
| 31 |
+
f"Total traffic: {row['Total']}. Situation: {row['Traffic Situation']}."
|
| 32 |
+
)
|
| 33 |
+
summaries.append(summary)
|
| 34 |
+
return summaries
|
| 35 |
+
|
| 36 |
+
# ---- Prompt Constructor ---- #
|
| 37 |
+
def generate_traffic_prompt(user_query: str, context: List[str]) -> str:
|
| 38 |
+
context_text = "\n".join(context)
|
| 39 |
+
prompt = f"""
|
| 40 |
+
Context:
|
| 41 |
+
{context_text}
|
| 42 |
+
|
| 43 |
+
User Query:
|
| 44 |
+
{user_query}
|
| 45 |
+
|
| 46 |
+
Based on the context above, generate a traffic optimization strategy.
|
| 47 |
+
"""
|
| 48 |
+
return prompt
|
| 49 |
+
|
| 50 |
+
# ---- Groq Query ---- #
|
| 51 |
+
def get_optimization_recommendation(prompt: str) -> str:
|
| 52 |
+
response = client.chat.completions.create(
|
| 53 |
+
messages=[{"role": "user", "content": prompt}],
|
| 54 |
+
model="llama-3-70b-versatile",
|
| 55 |
+
stream=False
|
| 56 |
+
)
|
| 57 |
+
return response.choices[0].message.content
|
| 58 |
+
|
| 59 |
+
# ---- Data Visualization ---- #
|
| 60 |
+
st.subheader("📊 Traffic Data Visualization")
|
| 61 |
+
st.dataframe(df.head(10))
|
| 62 |
+
|
| 63 |
+
st.write("### Traffic Volume Over Time")
|
| 64 |
+
fig, ax = plt.subplots(figsize=(10, 4))
|
| 65 |
+
df['Timestamp'] = pd.to_datetime(df['Date'] + ' ' + df['Time'])
|
| 66 |
+
df_sorted = df.sort_values("Timestamp")
|
| 67 |
+
ax.plot(df_sorted['Timestamp'], df_sorted['Total'], marker='o')
|
| 68 |
+
ax.set_xlabel("Time")
|
| 69 |
+
ax.set_ylabel("Total Traffic Volume")
|
| 70 |
+
ax.set_title("Traffic Volume Over Time")
|
| 71 |
+
st.pyplot(fig)
|
| 72 |
+
|
| 73 |
+
st.write("### Vehicle Count Distribution")
|
| 74 |
+
fig2, ax2 = plt.subplots(figsize=(10, 4))
|
| 75 |
+
df[['CarCount', 'BikeCount', 'BusCount', 'TruckCount']].plot(kind='box', ax=ax2)
|
| 76 |
+
ax2.set_title("Distribution of Vehicle Counts")
|
| 77 |
+
st.pyplot(fig2)
|
| 78 |
+
|
| 79 |
+
# ---- User Query and RAG Output ---- #
|
| 80 |
+
user_query = st.text_area("Enter your traffic-related query")
|
| 81 |
+
if user_query:
|
| 82 |
+
with st.spinner("Processing traffic data and generating strategy..."):
|
| 83 |
+
traffic_context = summarize_traffic_data(df)
|
| 84 |
+
prompt = generate_traffic_prompt(user_query, traffic_context[:10]) # Limit to first 10 rows
|
| 85 |
+
result = get_optimization_recommendation(prompt)
|
| 86 |
+
st.success("Strategy Generated:")
|
| 87 |
+
st.write(result)
|
| 88 |
+
|
| 89 |
+
else:
|
| 90 |
+
st.warning("Please upload a CSV file to proceed.")
|
| 91 |
+
|
| 92 |
+
st.markdown("---")
|
| 93 |
+
st.caption("🔁 This app analyzes traffic data using RAG + Groq and visualizes traffic patterns.")
|