maaz21 commited on
Commit
c717601
Β·
verified Β·
1 Parent(s): d5a564d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +91 -79
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
- # ---- 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.")
 
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.")