Khush24Shah commited on
Commit
07bfeb2
·
verified ·
1 Parent(s): 0d241de

Added AQI Calculator in the chat directly and made some tine changes

Browse files
Files changed (1) hide show
  1. app.py +133 -145
app.py CHANGED
@@ -26,7 +26,7 @@ st.write(
26
  )
27
 
28
  # Displaying the centered title
29
- st.markdown("<h2 class='title'>VayuBuddy</h2>", unsafe_allow_html=True)
30
 
31
  # os.environ["PANDASAI_API_KEY"] = "$2a$10$gbmqKotzJOnqa7iYOun8eO50TxMD/6Zw1pLI2JEoqncwsNx4XeBS2"
32
 
@@ -80,49 +80,97 @@ for response in st.session_state.responses:
80
 
81
  show = True
82
 
83
- prompt = st.sidebar.selectbox("Select a Prompt:", questions)
84
-
85
- # add a note "select custom prompt to ask your own question"
86
-
87
-
88
- if prompt == 'Custom Prompt':
89
- show = False
90
- # React to user input
91
- prompt = st.chat_input("Ask me anything about air quality!", key=10)
92
- if prompt:
93
- show = True
 
 
 
 
 
 
 
 
94
 
95
- if show:
96
-
97
- # Add user input to chat history
98
- response = get_from_user(prompt)
99
- response["no_response"] = False
100
- st.session_state.responses.append(response)
101
-
102
- # Display user input
103
- show_response(st, response)
104
 
105
- no_response = False
 
 
 
 
106
 
107
- # select random waiting line
108
- with st.spinner(random.choice(waiting_lines)):
109
- ran = False
110
- for i in range(5):
111
- llm = ChatGroq(model=models[model_name], api_key=os.getenv("GROQ_API"), temperature=0.1)
112
 
113
- df_check = pd.read_csv("Data.csv")
114
- df_check["Timestamp"] = pd.to_datetime(df_check["Timestamp"])
115
- df_check = df_check.head(5)
116
 
117
- new_line = "\n"
118
 
119
- template = f"""```python
120
  import pandas as pd
121
  import matplotlib.pyplot as plt
122
 
 
 
123
  df = pd.read_csv("Data.csv")
124
  df["Timestamp"] = pd.to_datetime(df["Timestamp"])
125
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
126
  # df.dtypes
127
  {new_line.join(map(lambda x: '# '+x, str(df_check.dtypes).split(new_line)))}
128
 
@@ -131,117 +179,57 @@ df["Timestamp"] = pd.to_datetime(df["Timestamp"])
131
  ```
132
  """
133
 
134
- query = f"""I have a pandas dataframe data of PM2.5 and PM10.
135
- * Frequency of data is daily.
136
- * Number of stations in a city is determined by finding the unique stations in the dataset along with their city
137
- * `pollution` generally means `PM2.5`.
138
- * PM2.5 guidelines: India: 60, WHO: 25.
139
- * PM10 guidelines: India: 100, WHO: 50.
140
- * You already have df, so don't read the csv file
141
- * Don't print, but save result in a variable `answer` and make it global.
142
- * Unless explicitly mentioned, don't consider the result as a plot.
143
- * If result is a plot make it in tight layout, save it and save path in `answer`. Example: `answer='plot.png'`
144
- * If result is not a plot, save it as a string in `answer`. Example: `answer='The city is Mumbai'`
145
- * If result is not a plot, return a csv file containing the data and the corresponding answer, as well as the data samples used
146
- * If result is a plot, show the India and WHO guidelines in the plot.
147
- * Whenever you do an aggregation, do it via mean and report the standard deviation and standard error, report the number of data points.
148
- * Whenever you're reporting a floating point number, round it to 2 decimal places.
149
- * Always report the unit of the data. Example: `The average PM2.5 is 45.67 µg/m³`
150
- * If the result is a plot, make it using tableau 20 colour scheme and big font size.
151
- * Consider station and sensor synonymously.
152
- Complete the following code.
153
-
154
- {template}
155
-
156
- """
157
-
158
- answer = llm.invoke(query)
159
- code = f"""
160
- {template.split("```python")[1].split("```")[0]}
161
- {answer.content.split("```python")[1].split("```")[0]}
162
- """
163
- # update variable `answer` when code is executed
164
- try:
165
- exec(code)
166
- ran = True
167
- no_response = False
168
- except Exception as e:
169
- no_response = True
170
- exception = e
171
-
172
- response = {"role": "assistant", "content": answer, "gen_code": code, "ex_code": code, "last_prompt": prompt, "no_response": no_response}
173
-
174
- # Get response from agent
175
- # response = ask_question(model_name=model_name, question=prompt)
176
- # response = ask_agent(agent, prompt)
177
-
178
- if ran:
179
- break
180
-
181
- if no_response:
182
- st.error(f"Failed to generate right output due to the following error:\n\n{exception}")
183
- # Add agent response to chat history
184
- st.session_state.responses.append(response)
185
-
186
- # Display agent response
187
- if not no_response:
188
- show_response(st, response)
189
-
190
- del prompt
191
-
192
-
193
-
194
- st.sidebar.info("\nCalculator")
195
- Pollutant = ["O3", "PM2.5", "PM10", "CO", "SO2", "NO2"]
196
- Calculator_index = st.sidebar.selectbox("Select a Prompt:", Pollutant)
197
-
198
- if Calculator_index:
199
- concentration = st.sidebar.number_input(f"Enter {Calculator_index} concentration (µg/m³):")
200
- calculate_button = st.sidebar.button("Calculate")
201
- if concentration:
202
- if calculate_button:
203
- # Define breakpoints and AQI categories for the selected pollutant
204
- breakpoints_low = {
205
- "O3": [0, 50, 100, 168, 208, 748],
206
- "PM2.5": [0, 30, 60, 90, 120, 250],
207
- "PM10": [0, 50, 100, 250, 350, 430],
208
- "CO": [0, 1000, 2000, 10000, 17000, 34000],
209
- "SO2": [0, 40, 80, 380, 800, 1600],
210
- "NO2": [0, 40, 80, 180, 280, 400]
211
- }
212
-
213
- breakpoints_high = {
214
- "O3": [50, 100, 168, 208, 748,1000],
215
- "PM2.5": [30, 60, 90, 120, 250,1000],
216
- "PM10": [50, 100, 250, 350, 430,1000],
217
- "CO": [1000, 2000, 10000, 17000, 34000,50000],
218
- "SO2": [40, 80, 380, 800, 1600,2000],
219
- "NO2": [ 40, 80, 180, 280, 400,1000]
220
- }
221
- # Define corresponding AQI categories
222
- categories_low= [0, 50, 100, 200, 300, 400]
223
- categories_high = [50, 100, 200, 300, 400,500]
224
-
225
- # Find the appropriate AQI category based on concentration
226
-
227
- for i in range(len(breakpoints_high[Calculator_index])):
228
- if concentration <= breakpoints_high[Calculator_index][i]:
229
- BPHI = breakpoints_high[Calculator_index][i]
230
- IHI = categories_high[i]
231
- # Calculate AQI using India formula
232
- #AQI = ((categories[i] - categories[i-1]) / (breakpoints[Calculator_index][i] - breakpoints[Calculator_index][i-1])) * (concentration - breakpoints[Calculator_index][i-1]) + categories[i-1]
233
- #st.sidebar.write(f"The Air Quality Index (AQI) for {Calculator_index} is: {AQI}")
234
- break
235
-
236
- for i in range(len(breakpoints_low[Calculator_index])):
237
- if concentration >= breakpoints_low[Calculator_index][i]:
238
- BPLI = breakpoints_low[Calculator_index][i]
239
- ILI = categories_low[i]
240
- # Calculate AQI using India formula
241
- #AQI = ((categories[i] - categories[i-1]) / (breakpoints[Calculator_index][i] - breakpoints[Calculator_index][i-1])) * (concentration - breakpoints[Calculator_index][i-1]) + categories[i-1]
242
- #st.sidebar.write(f"The Air Quality Index (AQI) for {Calculator_index} is: {AQI}")
243
  break
244
-
245
- AQI = ((IHI - ILI) / (BPHI - BPLI)) * (round(concentration) - BPLI) + ILI
246
- st.sidebar.write(f"The Air Quality Index (AQI) for {Calculator_index} is: {AQI}")
247
-
 
 
 
 
 
 
 
 
26
  )
27
 
28
  # Displaying the centered title
29
+ st.markdown("<h2 class='title'>GovBuddy</h2>", unsafe_allow_html=True)
30
 
31
  # os.environ["PANDASAI_API_KEY"] = "$2a$10$gbmqKotzJOnqa7iYOun8eO50TxMD/6Zw1pLI2JEoqncwsNx4XeBS2"
32
 
 
80
 
81
  show = True
82
 
83
+ if prompt := st.sidebar.selectbox("Select a Prompt:", questions):
84
+
85
+ # add a note "select custom prompt to ask your own question"
86
+ st.sidebar.info("Select 'Custom Prompt' to ask your own question.")
87
+
88
+ if prompt == 'Custom Prompt':
89
+ show = False
90
+ # React to user input
91
+ prompt = st.chat_input("Ask me anything about air quality!", key=10)
92
+ if prompt : show = True
93
+ if show :
94
+
95
+ # Add user input to chat history
96
+ response = get_from_user(prompt)
97
+ response["no_response"] = False
98
+ st.session_state.responses.append(response)
99
+
100
+ # Display user input
101
+ show_response(st, response)
102
 
103
+ no_response = False
 
 
 
 
 
 
 
 
104
 
105
+ # select random waiting line
106
+ with st.spinner(random.choice(waiting_lines)):
107
+ ran = False
108
+ for i in range(5):
109
+ llm = ChatGroq(model=models[model_name], api_key=os.getenv("GROQ_API"), temperature=0.1)
110
 
111
+ df_check = pd.read_csv("Data.csv")
112
+ df_check["Timestamp"] = pd.to_datetime(df_check["Timestamp"])
113
+ df_check = df_check.head(5)
 
 
114
 
115
+ new_line = "\n"
 
 
116
 
117
+ parameters = {"font.size": 18}
118
 
119
+ template = f"""```python
120
  import pandas as pd
121
  import matplotlib.pyplot as plt
122
 
123
+ plt.rcParams.update({parameters})
124
+
125
  df = pd.read_csv("Data.csv")
126
  df["Timestamp"] = pd.to_datetime(df["Timestamp"])
127
 
128
+ def calculator(Pollutant, concentration):
129
+ Calculator_index = Pollutant
130
+ breakpoints_low = {{
131
+ "O3": [0, 50, 100, 168, 208, 748],
132
+ "PM2.5": [0, 30, 60, 90, 120, 250],
133
+ "PM10": [0, 50, 100, 250, 350, 430],
134
+ "CO": [0, 1000, 2000, 10000, 17000, 34000],
135
+ "SO2": [0, 40, 80, 380, 800, 1600],
136
+ "NO2": [0, 40, 80, 180, 280, 400]
137
+ }}
138
+
139
+ breakpoints_high = {{
140
+ "O3": [50, 100, 168, 208, 748,1000],
141
+ "PM2.5": [30, 60, 90, 120, 250,1000],
142
+ "PM10": [50, 100, 250, 350, 430,1000],
143
+ "CO": [1000, 2000, 10000, 17000, 34000,50000],
144
+ "SO2": [40, 80, 380, 800, 1600,2000],
145
+ "NO2": [ 40, 80, 180, 280, 400,1000]
146
+ }}
147
+ # Define corresponding AQI categories
148
+ categories_low= [0, 50, 100, 200, 300, 400]
149
+ categories_high = [50, 100, 200, 300, 400,500]
150
+
151
+ # Find the appropriate AQI category based on concentration
152
+
153
+ for i in range(len(breakpoints_high[Calculator_index])):
154
+ if concentration <= breakpoints_high[Calculator_index][i]:
155
+ BPHI = breakpoints_high[Calculator_index][i]
156
+ IHI = categories_high[i]
157
+ # Calculate AQI using India formula
158
+ #AQI = ((categories[i] - categories[i-1]) / (breakpoints[Calculator_index][i] - breakpoints[Calculator_index][i-1])) * (concentration - breakpoints[Calculator_index][i-1]) + categories[i-1]
159
+ #st.sidebar.write(f"The Air Quality Index (AQI) for {{Calculator_index}} is: {{AQI}}")
160
+ break
161
+
162
+ for i in range(len(breakpoints_low[Calculator_index])):
163
+ if concentration >= breakpoints_low[Calculator_index][i]:
164
+ BPLI = breakpoints_low[Calculator_index][i]
165
+ ILI = categories_low[i]
166
+ # Calculate AQI using India formula
167
+ #AQI = ((categories[i] - categories[i-1]) / (breakpoints[Calculator_index][i] - breakpoints[Calculator_index][i-1])) * (concentration - breakpoints[Calculator_index][i-1]) + categories[i-1]
168
+ #st.sidebar.write(f"The Air Quality Index (AQI) for {{Calculator_index}} is: {{AQI}}")
169
+ break
170
+
171
+ AQI = ((IHI - ILI) / (BPHI - BPLI)) * (round(concentration) - BPLI) + ILI
172
+ return AQI
173
+
174
  # df.dtypes
175
  {new_line.join(map(lambda x: '# '+x, str(df_check.dtypes).split(new_line)))}
176
 
 
179
  ```
180
  """
181
 
182
+ query = f"""I have a pandas dataframe data of PM2.5 and PM10.
183
+ * Frequency of data is daily.
184
+ * `pollution` generally means `PM2.5`.
185
+ * You already have df, so don't read the csv file
186
+ * Don't print, but save result in a variable `answer` and make it global.
187
+ * Unless explicitly mentioned, don't consider the result as a plot.
188
+ * PM2.5 guidelines: India: 60, WHO: 15.
189
+ * PM10 guidelines: India: 100, WHO: 50.
190
+ * If result is a plot, show the India and WHO guidelines in the plot.
191
+ * If result is a plot make it in tight layout, save it and save path in `answer`. Example: `answer='plot.png'`
192
+ * If result is not a plot, save it as a string in `answer`. Example: `answer='The city is Mumbai'`
193
+ * Whenever you do any sort of aggregation, report the corresponding standard deviation, standard error and the number of data points.
194
+ * Whenever you're reporting a floating point number, round it to 2 decimal places.
195
+ * Always report the unit of the data. Example: `The average PM2.5 is 45.67 µg/m³`
196
+
197
+ Complete the following code.
198
+
199
+ {template}
200
+
201
+ """
202
+
203
+ answer = llm.invoke(query)
204
+ code = f"""
205
+ {template.split("```python")[1].split("```")[0]}
206
+ {answer.content.split("```python")[1].split("```")[0]}
207
+ """
208
+ # update variable `answer` when code is executed
209
+ try:
210
+ exec(code)
211
+ ran = True
212
+ no_response = False
213
+ except Exception as e:
214
+ no_response = True
215
+ exception = e
216
+
217
+ response = {"role": "assistant", "content": answer, "gen_code": code, "ex_code": code, "last_prompt": prompt, "no_response": no_response}
218
+
219
+ # Get response from agent
220
+ # response = ask_question(model_name=model_name, question=prompt)
221
+ # response = ask_agent(agent, prompt)
222
+
223
+ if ran:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
224
  break
225
+
226
+ if no_response:
227
+ st.error(f"Failed to generate right output due to the following error:\n\n{exception}")
228
+ # Add agent response to chat history
229
+ st.session_state.responses.append(response)
230
+
231
+ # Display agent response
232
+ if not no_response:
233
+ show_response(st, response)
234
+
235
+ del prompt