Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -7,87 +7,99 @@ 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 |
-
# ----
|
| 13 |
-
st.
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 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 |
-
|
| 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 |
st.markdown("---")
|
| 93 |
st.caption("π This app analyzes traffic data using RAG + Groq and visualizes traffic patterns.")
|
|
|
|
| 7 |
from typing import List
|
| 8 |
|
| 9 |
# ---- Setup Groq Client ---- #
|
| 10 |
+
client = Groq(api_key=os.getenv("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"))
|
| 11 |
|
| 12 |
+
# ---- Load and Hardcode CSV Data ---- #
|
| 13 |
+
@st.cache_data
|
| 14 |
+
def load_data():
|
| 15 |
+
return pd.read_csv("traffic_data.csv") # Replace with your file path if needed
|
| 16 |
+
|
| 17 |
+
df = load_data()
|
| 18 |
+
|
| 19 |
+
# ---- Utility: Summarize traffic data to context ---- #
|
| 20 |
+
def summarize_traffic_data(df: pd.DataFrame) -> List[str]:
|
| 21 |
+
summaries = []
|
| 22 |
+
for index, row in df.iterrows():
|
| 23 |
+
summary = (
|
| 24 |
+
f"On {row['Date']} ({row['Day of the week']}) at {row['Time']}, "
|
| 25 |
+
f"there were {row['CarCount']} cars, {row['BikeCount']} bikes, "
|
| 26 |
+
f"{row['BusCount']} buses, and {row['TruckCount']} trucks. "
|
| 27 |
+
f"Total traffic: {row['Total']}. Situation: {row['Traffic Situation']}."
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 28 |
)
|
| 29 |
+
summaries.append(summary)
|
| 30 |
+
return summaries
|
| 31 |
+
|
| 32 |
+
# ---- Prompt Constructor ---- #
|
| 33 |
+
def generate_traffic_prompt(user_query: str, context: List[str]) -> str:
|
| 34 |
+
context_text = "\n".join(context)
|
| 35 |
+
prompt = f"""
|
| 36 |
+
Context:
|
| 37 |
+
{context_text}
|
| 38 |
+
|
| 39 |
+
User Query:
|
| 40 |
+
{user_query}
|
| 41 |
+
|
| 42 |
+
Based on the context above, generate a traffic optimization strategy.
|
| 43 |
+
"""
|
| 44 |
+
return prompt
|
| 45 |
+
|
| 46 |
+
# ---- Groq Query ---- #
|
| 47 |
+
def get_optimization_recommendation(prompt: str) -> str:
|
| 48 |
+
response = client.chat.completions.create(
|
| 49 |
+
messages=[{"role": "user", "content": prompt}],
|
| 50 |
+
model="llama-3-70b-versatile",
|
| 51 |
+
stream=False
|
| 52 |
+
)
|
| 53 |
+
return response.choices[0].message.content
|
| 54 |
+
|
| 55 |
+
# ---- Streamlit App ---- #
|
| 56 |
+
st.set_page_config(page_title="π¦ Traffic Optimization RAG App")
|
| 57 |
+
st.title("π¦ Real-Time Traffic Optimization using RAG + Groq")
|
| 58 |
+
|
| 59 |
+
# ---- Data Visualization ---- #
|
| 60 |
+
st.subheader("π Traffic Data Visualization")
|
| 61 |
+
st.dataframe(df.head(10))
|
| 62 |
+
|
| 63 |
+
# Handle 'Date' and 'Time' columns
|
| 64 |
+
df['Date'] = df['Date'].astype(str)
|
| 65 |
+
df['Time'] = df['Time'].astype(str)
|
| 66 |
+
|
| 67 |
+
# Handle missing values if any
|
| 68 |
+
df['Date'] = df['Date'].fillna('')
|
| 69 |
+
df['Time'] = df['Time'].fillna('')
|
| 70 |
+
|
| 71 |
+
# Combine 'Date' and 'Time' to create a timestamp
|
| 72 |
+
df['Timestamp'] = pd.to_datetime(df['Date'] + ' ' + df['Time'], errors='coerce') # `errors='coerce'` will turn invalid dates into NaT
|
| 73 |
+
|
| 74 |
+
# Check if 'Timestamp' is created successfully
|
| 75 |
+
st.write(f"Timestamp column created successfully: {df['Timestamp'].head()}")
|
| 76 |
+
|
| 77 |
+
# ---- Traffic Volume Over Time ---- #
|
| 78 |
+
st.write("### Traffic Volume Over Time")
|
| 79 |
+
fig, ax = plt.subplots(figsize=(10, 4))
|
| 80 |
+
df_sorted = df.sort_values("Timestamp")
|
| 81 |
+
ax.plot(df_sorted['Timestamp'], df_sorted['Total'], marker='o')
|
| 82 |
+
ax.set_xlabel("Time")
|
| 83 |
+
ax.set_ylabel("Total Traffic Volume")
|
| 84 |
+
ax.set_title("Traffic Volume Over Time")
|
| 85 |
+
st.pyplot(fig)
|
| 86 |
+
|
| 87 |
+
# ---- Vehicle Count Distribution ---- #
|
| 88 |
+
st.write("### Vehicle Count Distribution")
|
| 89 |
+
fig2, ax2 = plt.subplots(figsize=(10, 4))
|
| 90 |
+
df[['CarCount', 'BikeCount', 'BusCount', 'TruckCount']].plot(kind='box', ax=ax2)
|
| 91 |
+
ax2.set_title("Distribution of Vehicle Counts")
|
| 92 |
+
st.pyplot(fig2)
|
| 93 |
+
|
| 94 |
+
# ---- User Query and RAG Output ---- #
|
| 95 |
+
user_query = st.text_area("Enter your traffic-related query")
|
| 96 |
+
if user_query:
|
| 97 |
+
with st.spinner("Processing traffic data and generating strategy..."):
|
| 98 |
+
traffic_context = summarize_traffic_data(df)
|
| 99 |
+
prompt = generate_traffic_prompt(user_query, traffic_context[:10]) # Limit to first 10 rows
|
| 100 |
+
result = get_optimization_recommendation(prompt)
|
| 101 |
+
st.success("Strategy Generated:")
|
| 102 |
+
st.write(result)
|
| 103 |
|
| 104 |
st.markdown("---")
|
| 105 |
st.caption("π This app analyzes traffic data using RAG + Groq and visualizes traffic patterns.")
|