ddooling commited on
Commit
eca2645
·
verified ·
1 Parent(s): 78bbf84

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +766 -0
app.py ADDED
@@ -0,0 +1,766 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from dotenv import load_dotenv
2
+ import os
3
+
4
+ # Add these imports
5
+ from threading import Thread
6
+ import queue
7
+ from openai import AssistantEventHandler
8
+ from typing_extensions import override
9
+
10
+ load_dotenv()
11
+
12
+ import openai
13
+ import time
14
+ import gradio as gr
15
+ from autogen import UserProxyAgent, config_list_from_json
16
+ from datetime import timedelta, datetime
17
+ import pandas as pd
18
+ import numpy as np
19
+ from gradio_datetimerange import DateTimeRange
20
+ import os
21
+ from time import sleep
22
+ from gradio_pdf import PDF
23
+
24
+ from pandasai.llm.openai import OpenAI
25
+ from pandasai import Agent
26
+ import matplotlib.pyplot as plt
27
+ import io
28
+ from pandasai import SmartDataframe
29
+ from collections import Counter
30
+
31
+ # llmmodel = OpenAI(api_token=os.environ["OPENAI_API_KEY"], model='gpt-4o')
32
+
33
+ import requests
34
+
35
+
36
+
37
+ functions = [
38
+ {
39
+ "name": "update_weather",
40
+ "description": "Fetches and returns the current weather information for a specified location.",
41
+ "parameters": {
42
+ "type": "object",
43
+ "properties": {
44
+ "location": {
45
+ "type": "string",
46
+ "description": "The name of the city or location to get weather information for."
47
+ }
48
+ },
49
+ "required": ["location"]
50
+ }
51
+ }
52
+ ]
53
+
54
+ tools=[
55
+ {
56
+ "type": "function",
57
+ "function": {
58
+ "name": "update_weather",
59
+ "description": "Fetches and returns the current weather information for a specified location.",
60
+ "parameters": {
61
+ "type": "object",
62
+ "properties": {
63
+ "location": {
64
+ "type": "string",
65
+ "description": "The name of the city or location to get weather information for."
66
+ }
67
+ },
68
+ "required": ["location"]
69
+ }
70
+ }
71
+ }
72
+ ]
73
+
74
+
75
+ def get_weather(location: str) -> str:
76
+ """
77
+ Fetches the weather for a given location and returns a dictionary
78
+
79
+ Parameters:
80
+ - location: the search term to find current weather information
81
+ Returns:
82
+ The current weather for that location
83
+ """
84
+ api_key = os.environ["OPENWEATHERMAP_API_KEY"]
85
+ base_url = "http://api.openweathermap.org/data/2.5/weather"
86
+ params = {"q": location, "appid": api_key, "units": "imperial"}
87
+ response = requests.get(base_url, params=params)
88
+ weather_data = response.json()
89
+ return weather_data
90
+
91
+
92
+ get_weather_schema = """
93
+ {
94
+ "name": "get_weather",
95
+ "description": "Fetches the weather for a location based on a search term.",
96
+ "parameters": {
97
+ "type": "object",
98
+ "properties": {
99
+ "location": {
100
+ "type": "string",
101
+ "description": "Name of the city"
102
+ }
103
+ },
104
+ "required": [
105
+ "location"
106
+ ]
107
+ }
108
+ }
109
+ """
110
+
111
+
112
+ # Function to generate a date range
113
+ def generate_date_range(start_date, end_date, freq="D"):
114
+ return pd.date_range(start=start_date, end=end_date, freq=freq)
115
+
116
+
117
+ # Function to generate synthetic data for each component
118
+ def generate_synthetic_data(dates):
119
+ # Define random seed for reproducibility
120
+ np.random.seed(0)
121
+
122
+ # Generate random data for each component
123
+ data = {
124
+ "Temperature_Pressure_Relief_Valve": np.random.choice(
125
+ [0, 1], size=len(dates)
126
+ ), # 0 = OK, 1 = Faulty
127
+ "Outlet_Nipple_Assembly": np.random.normal(
128
+ loc=80, scale=10, size=len(dates)
129
+ ), # Temperature in °F
130
+ "Inlet_Nipple": np.random.normal(
131
+ loc=50, scale=5, size=len(dates)
132
+ ), # Temperature in °F
133
+ "Upper_Element": np.random.normal(
134
+ loc=150, scale=20, size=len(dates)
135
+ ), # Wattage (Watts)
136
+ "Lower_Element": np.random.normal(
137
+ loc=150, scale=20, size=len(dates)
138
+ ), # Wattage (Watts)
139
+ "Anode_Rod": np.random.normal(
140
+ loc=7, scale=1.5, size=len(dates)
141
+ ), # Length in inches
142
+ "Drain_Valve": np.random.choice(
143
+ [0, 1], size=len(dates)
144
+ ), # 0 = Closed, 1 = Open
145
+ "Upper_Thermostat": np.random.normal(
146
+ loc=120, scale=10, size=len(dates)
147
+ ), # Temperature in °F
148
+ "Lower_Thermostat": np.random.normal(
149
+ loc=120, scale=10, size=len(dates)
150
+ ), # Temperature in °F
151
+ "Operating_Time": np.random.randint(
152
+ 1, 25, size=len(dates)
153
+ ), # Operating time in hours
154
+ }
155
+
156
+ # Inject an anomaly in the Upper Thermostat values around the midpoint
157
+ midpoint_index = len(dates) // 2
158
+ anomaly_range = (midpoint_index - 5, midpoint_index + 5)
159
+
160
+ # Create a spike in Upper Thermostat values
161
+ data["Upper_Thermostat"][anomaly_range[0] : anomaly_range[1]] = np.random.normal(
162
+ loc=200, scale=5, size=anomaly_range[1] - anomaly_range[0]
163
+ )
164
+
165
+ return pd.DataFrame(data, index=dates)
166
+
167
+
168
+ # Generate the dataset
169
+ start_date = datetime(2023, 10, 1)
170
+ end_date = datetime(2024, 10, 1)
171
+ dates = generate_date_range(start_date, end_date)
172
+
173
+ # Create a DataFrame with synthetic data
174
+ synthetic_dataset = generate_synthetic_data(dates)
175
+
176
+ now = datetime.now()
177
+
178
+ synthetic_dataset["time"] = [
179
+ now - timedelta(hours=5 * i) for i in range(synthetic_dataset.shape[0])
180
+ ]
181
+
182
+ # something whcky happened with the vector store. i don't know what the fuck happened.
183
+ # have to create a new assistant.
184
+
185
+ # you need to have system instructions ilke this
186
+ # You are a helpful assistant and expert at ansewring building automation questions. Always carry out a file search for the desired information. You can augment that information with your general knowledge, but alwasy carry out a file seaach with every query first to see if the relevant information is there, and then add to that afterwards.
187
+
188
+ # name : Building Energy and Efficiency Expert
189
+
190
+ # And also added repitiion of the instructions in the thread / run creation.
191
+
192
+ VECTOR_STORE_ID = os.environ["VECTOR_STORE_ID"] # will need to be updated. what the hell happened??
193
+ ASSISTANT_ID = os.environ["ASSISTANT_ID"]
194
+
195
+
196
+
197
+ # small medium offices are waht is relevant to this dataset.
198
+
199
+ # Initialize the client
200
+ client = openai.OpenAI()
201
+
202
+
203
+ # Step 2: Create a Thread
204
+ thread = client.beta.threads.create()
205
+ thread_id = thread.id
206
+
207
+
208
+ # Define the EventHandler class
209
+ class EventHandler(AssistantEventHandler):
210
+ def __init__(self, response_queue):
211
+ super().__init__()
212
+ self.response_queue = response_queue
213
+
214
+ # @override
215
+ # def on_event(self, event):
216
+ # # Retrieve events that are denoted with 'requires_action'
217
+ # # since these will have our tool_calls
218
+ # if event.event == 'thread.run.requires_action':
219
+ # run_id = event.data.id # Retrieve the run ID from the event data
220
+ # self.handle_requires_action(event.data, run_id)
221
+
222
+ # def handle_requires_action(self, data, run_id):
223
+ # tool_outputs = []
224
+
225
+ # for tool in data.required_action.submit_tool_outputs.tool_calls:
226
+ # if tool.function.name == "update_weather":
227
+ # tool_outputs.append({"tool_call_id": tool.id, "output": "57"})
228
+
229
+ # Submit all tool_outputs at the same time
230
+ # self.submit_tool_outputs(tool_outputs, run_id)
231
+
232
+ # def submit_tool_outputs(self, tool_outputs, run_id):
233
+ # # Use the submit_tool_outputs_stream helper
234
+ # with client.beta.threads.runs.submit_tool_outputs_stream(
235
+ # thread_id=self.current_run.thread_id,
236
+ # run_id=self.current_run.id,
237
+ # tool_outputs=tool_outputs,
238
+ # event_handler=EventHandler(),
239
+ # ) as stream:
240
+ # for text in stream.text_deltas:
241
+ # print(text, end="", flush=True)
242
+ # print()
243
+
244
+ @override
245
+ def on_text_created(self, text) -> None:
246
+ pass
247
+
248
+ @override
249
+ def on_text_delta(self, delta, snapshot):
250
+ text = delta.value
251
+ self.response_queue.put(text)
252
+
253
+
254
+ def chat(usr_message, history):
255
+ global thread_id
256
+ # start_conversation()
257
+ user_input = usr_message
258
+
259
+ if not thread_id:
260
+ print("Error: Missing thread_id") # Debugging line
261
+ return json.dumps({"error": "Missing thread_id"}), 400
262
+
263
+ print(
264
+ f"Received message: {user_input} for thread ID: {thread_id}"
265
+ ) # Debugging line
266
+
267
+ # Add the user's message to the thread
268
+ client.beta.threads.messages.create(
269
+ thread_id=thread_id, role="user", content=user_input
270
+ )
271
+
272
+ # Create a queue to hold the assistant's response chunks
273
+ response_queue = queue.Queue()
274
+
275
+ # Instantiate the event handler with the queue
276
+ event_handler = EventHandler(response_queue)
277
+
278
+ # Start the streaming run in a separate thread
279
+ def run_stream():
280
+ with client.beta.threads.runs.stream(
281
+ thread_id=thread_id,
282
+ assistant_id=ASSISTANT_ID,
283
+ # parallel_tool_calls = False,
284
+ tool_choice = "required",
285
+ # functions=functions,
286
+ # function_call="auto",
287
+ # tools=[
288
+ # {
289
+ # "type": "function",
290
+ # "function": {
291
+ # "name": "update_weather",
292
+ # "description": "Fetches and returns the current weather information for a specified location.",
293
+ # "parameters": {
294
+ # "type": "object",
295
+ # "properties": {
296
+ # "location": {
297
+ # "type": "string",
298
+ # "description": "The name of the city or location to get weather information for."
299
+ # }
300
+ # },
301
+ # "required": ["location"]
302
+ # }
303
+ # }
304
+ # }
305
+ # ],
306
+ # tool_choice = {"type": "file_search"},
307
+ # tools = [{"type": "file_search"}],
308
+ # tool_resources={"file_search": {"vector_store_ids": [VECTOR_STORE_ID]}},
309
+ # additional_instructions="Always carry out a file search for the desired information",
310
+ event_handler=event_handler,
311
+ ) as stream:
312
+ stream.until_done()
313
+
314
+ stream_thread = Thread(target=run_stream)
315
+ stream_thread.start()
316
+
317
+ assistant_response = ""
318
+ while True:
319
+ try:
320
+ # Get response chunks from the queue
321
+ chunk = response_queue.get(timeout=0.1)
322
+ assistant_response += chunk
323
+ yield assistant_response
324
+ except queue.Empty:
325
+ # Check if the stream has finished
326
+ if not stream_thread.is_alive():
327
+ break
328
+
329
+ # Wait for the stream thread to finish
330
+ stream_thread.join()
331
+
332
+
333
+ #def update_weather(location):
334
+ # api_key = os.environ["OPENWEATHERMAP_API_KEY"]
335
+ # base_url = "http://api.openweathermap.org/data/2.5/weather"
336
+ # params = {"q": location, "appid": api_key, "units": "metric"}
337
+ # response = requests.get(base_url, params=params)
338
+ # weather_data = response.json()
339
+
340
+ # {'coord': {'lon': -106.6645, 'lat': 35.2334}, 'weather': [{'id': 800, 'main': 'Clear', 'description': 'clear sky', 'icon': '01d'}], 'base': 'stations', 'main': {'temp': 21.79, 'feels_like': 20.89, 'temp_min': 20.06, 'temp_max': 23.22, 'pressure': 1024, 'humidity': 33, 'sea_level': 1024, 'grnd_level': 836}, 'visibility': 10000, 'wind': {'speed': 9.26, 'deg': 140}, 'clouds': {'all': 0}, 'dt': 1727798647, 'sys': {'type': 2, 'id': 2080227, 'country': 'US', 'sunrise': 1727787706, 'sunset': 1727830218}, 'timezone': -21600, 'id': 5487811, 'name': 'Rio Rancho', 'cod': 200}
341
+
342
+ # lon = weather_data["coord"]["lon"]
343
+ # lat = weather_data["coord"]["lat"]
344
+ # main = weather_data["weather"][0]["main"]
345
+ # feels_like = weather_data["main"]["feels_like"]
346
+ # temp_min = weather_data["main"]["temp_min"]
347
+ # temp_max = weather_data["main"]["temp_max"]
348
+ # pressure = weather_data["main"]["pressure"]
349
+ # visibility = weather_data["visibility"]
350
+ # wind_speed = weather_data["wind"]["speed"]
351
+ # wind_deg = weather_data["wind"]["deg"]
352
+ # sunrise = weather_data["sys"]["sunrise"]
353
+ # sunset = weather_data["sys"]["sunset"]
354
+ # temp = weather_data["main"]["temp"]
355
+ # humidity = weather_data["main"]["humidity"]
356
+ # condition = weather_data["weather"][0]["description"]
357
+
358
+ # return f"""Weather in {location}:
359
+ # (lon: {lon}, lat: {lat}),
360
+ # Temperature: {temp:.2f}°C, Feels like: {feels_like:.2f}°C,
361
+ # Temperature_min: {temp_min:.2f}°C, Temperature_max: {temp_max:.2f}°C,
362
+ # Humidity: {humidity}, Condition: {condition},
363
+ # Pressure: {pressure}, Visibility: {visibility}, Wind speed: {wind_speed},
364
+ # Wind deg: {wind_deg}, Sunrise: {sunrise}, Sunset: {sunset}"""
365
+
366
+
367
+
368
+ # Function to update weather information
369
+
370
+ def update_weather(location):
371
+ api_key = os.environ["OPENWEATHERMAP_API_KEY"]
372
+ base_url = "http://api.openweathermap.org/data/2.5/weather"
373
+ params = {"q": location, "appid": api_key, "units": "imperial"}
374
+ response = requests.get(base_url, params=params)
375
+ weather_data = response.json()
376
+
377
+ if response.status_code != 200:
378
+ return f"Error fetching weather data: {weather_data.get('message', 'Unknown error')}"
379
+
380
+ lon = weather_data["coord"]["lon"]
381
+ lat = weather_data["coord"]["lat"]
382
+ main = weather_data["weather"][0]["main"]
383
+ feels_like = weather_data["main"]["feels_like"]
384
+ temp_min = weather_data["main"]["temp_min"]
385
+ temp_max = weather_data["main"]["temp_max"]
386
+ pressure = weather_data["main"]["pressure"]
387
+ visibility = weather_data["visibility"]
388
+ wind_speed = weather_data["wind"]["speed"]
389
+ wind_deg = weather_data["wind"]["deg"]
390
+ sunrise = datetime.fromtimestamp(weather_data["sys"]["sunrise"]).strftime('%H:%M:%S')
391
+ sunset = datetime.fromtimestamp(weather_data["sys"]["sunset"]).strftime('%H:%M:%S')
392
+ temp = weather_data["main"]["temp"]
393
+ humidity = weather_data["main"]["humidity"]
394
+ condition = weather_data["weather"][0]["description"]
395
+
396
+ return f"""**Weather in {location}:**
397
+ - **Coordinates:** (lon: {lon}, lat: {lat})
398
+ - **Temperature:** {temp:.2f}°F (Feels like: {feels_like:.2f}°F)
399
+ - **Min Temperature:** {temp_min:.2f}°F, **Max Temperature:** {temp_max:.2f}°F
400
+ - **Humidity:** {humidity}%
401
+ - **Condition:** {condition.capitalize()}
402
+ - **Pressure:** {pressure} hPa
403
+ - **Visibility:** {visibility} meters
404
+ - **Wind Speed:** {wind_speed} m/s, **Wind Direction:** {wind_deg}°
405
+ - **Sunrise:** {sunrise}, **Sunset:** {sunset}"""
406
+
407
+
408
+
409
+ def update_weather_forecast(location: str) -> str:
410
+ """ Fetches the weather forecast for a given location and returns a formatted string
411
+ Parameters:
412
+ - location: the search term to find weather information
413
+ Returns:
414
+ A formatted string containing the weather forecast data
415
+ """
416
+
417
+ api_key = os.environ["OPENWEATHERMAP_API_KEY"]
418
+ base_url = "http://api.openweathermap.org/data/2.5/forecast"
419
+ params = {
420
+ "q": location,
421
+ "appid": api_key,
422
+ "units": "imperial",
423
+ "cnt": 40 # Request 40 data points (5 days * 8 three-hour periods)
424
+ }
425
+ response = requests.get(base_url, params=params)
426
+ weather_data = response.json()
427
+ if response.status_code != 200:
428
+ return f"Error fetching weather data: {weather_data.get('message', 'Unknown error')}"
429
+
430
+ # Organize forecast data per date
431
+ forecast_data = {}
432
+ for item in weather_data['list']:
433
+ dt_txt = item['dt_txt'] # 'YYYY-MM-DD HH:MM:SS'
434
+ date_str = dt_txt.split(' ')[0] # 'YYYY-MM-DD'
435
+ time_str = dt_txt.split(' ')[1] # 'HH:MM:SS'
436
+ forecast_data.setdefault(date_str, [])
437
+ forecast_data[date_str].append({
438
+ 'time': time_str,
439
+ 'temp': item['main']['temp'],
440
+ 'feels_like': item['main']['feels_like'],
441
+ 'humidity': item['main']['humidity'],
442
+ 'pressure': item['main']['pressure'],
443
+ 'wind_speed': item['wind']['speed'],
444
+ 'wind_deg': item['wind']['deg'],
445
+ 'condition': item['weather'][0]['description'],
446
+ 'visibility': item.get('visibility', 'N/A'), # sometimes visibility may be missing
447
+ })
448
+
449
+ # Process data to create daily summaries
450
+ daily_summaries = {}
451
+ for date_str, forecasts in forecast_data.items():
452
+ temps = [f['temp'] for f in forecasts]
453
+ feels_likes = [f['feels_like'] for f in forecasts]
454
+ humidities = [f['humidity'] for f in forecasts]
455
+ pressures = [f['pressure'] for f in forecasts]
456
+ wind_speeds = [f['wind_speed'] for f in forecasts]
457
+ conditions = [f['condition'] for f in forecasts]
458
+
459
+ min_temp = min(temps)
460
+ max_temp = max(temps)
461
+ avg_temp = sum(temps) / len(temps)
462
+ avg_feels_like = sum(feels_likes) / len(feels_likes)
463
+ avg_humidity = sum(humidities) / len(humidities)
464
+ avg_pressure = sum(pressures) / len(pressures)
465
+ avg_wind_speed = sum(wind_speeds) / len(wind_speeds)
466
+
467
+ # Find the most common weather condition
468
+ condition_counts = Counter(conditions)
469
+ most_common_condition = condition_counts.most_common(1)[0][0]
470
+
471
+ daily_summaries[date_str] = {
472
+ 'min_temp': min_temp,
473
+ 'max_temp': max_temp,
474
+ 'avg_temp': avg_temp,
475
+ 'avg_feels_like': avg_feels_like,
476
+ 'avg_humidity': avg_humidity,
477
+ 'avg_pressure': avg_pressure,
478
+ 'avg_wind_speed': avg_wind_speed,
479
+ 'condition': most_common_condition,
480
+ }
481
+
482
+ # Build the formatted string
483
+ city_name = weather_data['city']['name']
484
+ ret_str = f"**5-Day Weather Forecast for {city_name}:**\n"
485
+
486
+ for date_str in sorted(daily_summaries.keys()):
487
+ summary = daily_summaries[date_str]
488
+ ret_str += f"\n**{date_str}:**\n"
489
+ ret_str += f"- **Condition:** {summary['condition'].capitalize()}\n"
490
+ ret_str += f"- **Min Temperature:** {summary['min_temp']:.2f}°F\n"
491
+ ret_str += f"- **Max Temperature:** {summary['max_temp']:.2f}°F\n"
492
+ ret_str += f"- **Average Temperature:** {summary['avg_temp']:.2f}°F (Feels like {summary['avg_feels_like']:.2f}°F)\n"
493
+ ret_str += f"- **Humidity:** {summary['avg_humidity']:.0f}%\n"
494
+ ret_str += f"- **Pressure:** {summary['avg_pressure']:.0f} hPa\n"
495
+ ret_str += f"- **Wind Speed:** {summary['avg_wind_speed']:.2f} m/s\n"
496
+
497
+ return ret_str
498
+
499
+
500
+
501
+
502
+
503
+ llmmodel = OpenAI(api_token=os.environ["OPENAI_API_KEY"], model='gpt-4o')
504
+
505
+ # Load dataframes
506
+ dfcleaned = pd.read_csv("dfcleaned.csv")
507
+ dfcleaned['Timestamp'] = pd.to_datetime(dfcleaned['Timestamp'])
508
+ dfcleaned['off-nominal'] = dfcleaned['off-nominal'].apply(str)
509
+ dfshaps = pd.read_csv("shaps.csv")
510
+ dfshaps['Timestamp'] = pd.to_datetime(dfshaps['Timestamp'])
511
+
512
+ # Initialize Agent
513
+ agent = Agent([dfcleaned, dfshaps], config={"llm": llmmodel})
514
+
515
+ sdfshaps = SmartDataframe(dfshaps, config={"llm": llmmodel})
516
+ sdfcleaned = SmartDataframe(dfcleaned, config={"llm": llmmodel})
517
+
518
+
519
+
520
+ #def process_query(query):
521
+ # response = agent.chat(query) # or agent chat, gr.Image
522
+ # print(response)
523
+ # if isinstance(response, str) and ".png" in response:
524
+ # return response, response, None
525
+ # elif isinstance(response, str) and ".png" not in response:
526
+ # return response, None, None
527
+ # elif isinstance(response, pd.DataFrame):
528
+ # return None, None, response
529
+
530
+
531
+ def process_query(query):
532
+ response = agent.chat(query) # Replace with your actual agent chat implementation
533
+ print(response)
534
+
535
+ # Initialize outputs and visibility flags
536
+ text_output = None
537
+ image_output = None
538
+ dataframe_output = None
539
+ text_visible = False
540
+ image_visible = False
541
+ dataframe_visible = False
542
+
543
+ if isinstance(response, str) and ".png" not in response:
544
+ text_output = response
545
+ text_visible = True
546
+ elif isinstance(response, str) and ".png" in response:
547
+ image_output = response # Assuming response is a filepath or URL to the image
548
+ image_visible = True
549
+ elif isinstance(response, pd.DataFrame):
550
+ dataframe_output = response
551
+ dataframe_visible = True
552
+
553
+ return (
554
+ text_output,
555
+ image_output,
556
+ dataframe_output,
557
+ gr.update(visible=text_visible),
558
+ gr.update(visible=image_visible),
559
+ gr.update(visible=dataframe_visible)
560
+ )
561
+
562
+
563
+
564
+
565
+
566
+ def gradio_app():
567
+ iface = gr.Interface(
568
+ fn=process_query,
569
+ inputs="text",
570
+ outputs=[
571
+ gr.Textbox(label="Response"),
572
+ gr.Image(label="Plot"),
573
+ gr.DataFrame(label="Dataframe")
574
+ ],
575
+ title="pandasai Query Processor",
576
+ description="Enter your query related to the csv data files."
577
+ )
578
+ return iface
579
+
580
+ with gr.Blocks(
581
+ # theme=gr.themes.Monochrome(primary_hue="green"),
582
+ theme = gr.themes.Soft(),
583
+ ) as demo:
584
+ with gr.Row(): # Combine the two weather functions into a single row
585
+ with gr.Column():
586
+ location1 = gr.Textbox(label="Enter location for weather (e.g., Rio Rancho, New Mexico)",
587
+ value="Cambridge, Massachusetts")
588
+ weather_button = gr.Button("Get Weather")
589
+ # output1 = gr.Markdown(label="Weather Information")
590
+ output1 = gr.Textbox(label="Weather Information", lines=8, max_lines=8, show_label=True, show_copy_button=True)
591
+ weather_button.click(
592
+ fn=update_weather,
593
+ inputs=location1,
594
+ outputs=output1,
595
+ api_name="update_weather",
596
+ )
597
+ with gr.Column():
598
+ location2 = gr.Textbox(label="Enter location for weather forecast (e.g., Rio Rancho, New Mexico)",
599
+ value="Cambridge, Massachusetts")
600
+ weather_forecast_button = gr.Button("Get 5-Day Weather Forecast")
601
+ # output2 = gr.Markdown(label="Weather Forecast Information")
602
+ output2 = gr.Textbox(label="Weather 5-Day Forecast Information", lines=8, max_lines=8,
603
+ show_label=True, show_copy_button=True)
604
+ weather_forecast_button.click(
605
+ fn=update_weather_forecast,
606
+ inputs=location2,
607
+ outputs=output2,
608
+ api_name="update_weather_forecast",
609
+ )
610
+
611
+ with gr.Row():
612
+ with gr.Column(scale=1):
613
+ gr.Markdown("# Building Automation Assistant")
614
+
615
+ gr.Markdown(
616
+ "I'm an AI assistant that can help with building maintenance and equipment questions."
617
+ )
618
+
619
+ gr.Markdown("---")
620
+
621
+ # Update the ChatInterface to handle streaming
622
+ chat_interface = gr.ChatInterface(
623
+ chat,
624
+ #show_label=True,
625
+ # show_copy_button=True,
626
+ chatbot=gr.Chatbot(height=750, show_copy_button=True, show_copy_all_button=True,
627
+ avatar_images=("user_avatar.png", "assistant_avatar.png")),
628
+ title="Ask Me Anything",
629
+ examples_per_page= 5,
630
+ # theme="soft", # glass
631
+ description="Type your question about building automation here.",
632
+ examples=[
633
+ "Tell me about the HouseZero dataset. Retrieve information from the publication you have access to. Use your file retrieval tool.",
634
+ "Describe in detail the relationshp between the columns in the two uploaded CSV files and the information you have access to regarding the HouseZero dataset. Be verbose. Use your file retrieval tool.",
635
+ "Tell be in great detail any advice you have to maintain a small to midsize office building, like the HouseZero data corresponds to. Be verbose. Use your file retrieval tool.",
636
+ "please caculate the correlation of each feature with the anomaly_score and retuen the values in descending order. return the top 10 rows.",
637
+ "Tell me in great detail any advice you have for the building managers of large hospitals. Be verbose. Use your file retrieval tool.",
638
+ "Show massachusetts electricity billing rates during the same time span as the CSV data",
639
+ "Use those rates and the relevant columns in the CSV files to estimate how much it costs to operate this building per month.",
640
+ "What is the estimated average electricity cost for operating the building using massachusetts energy rates. use your file retrieval tool. use data csv files for building data. Limit your response to 140 characters. Use your file retrieval tool.",
641
+ "The anomaly_score field on one of the CSVs indicates that that row is an anomaly if it has value greater than zero.. can you please list a few of the rows with the highest value for this column and using your building efficiency knowledge explain why they may represent a problem? Use your file retrieval tool.",
642
+ "Based on the data in these CSV files, can you assign an EnergyIQ score from 1-10 that reflects how well the building is operating? Explain the reason for your score and provide any recommendations on actions to take that can improve it in the future. Be verbose. Use your file retrieval tool.",
643
+ "What would be a good feature to plot as a function of time to illustrate the problems of why the EnergyIQ score is low? Use your file retreival tool.",
644
+ ],
645
+ fill_height=True,
646
+ )
647
+
648
+ gr.Markdown("---")
649
+ with gr.Column():
650
+ # with gr.Column():
651
+ # Define the three ScatterPlot components
652
+ anomaly_plot = gr.ScatterPlot(
653
+ dfcleaned,
654
+ x="Timestamp",
655
+ y="Z5_RH",
656
+ color="off-nominal",
657
+ title="Anomaly Score"
658
+ )
659
+
660
+ zone3_plot = gr.ScatterPlot(
661
+ dfcleaned,
662
+ x="Timestamp",
663
+ y="Z3_RH",
664
+ color="off-nominal",
665
+ title="Zone 3 Relative Humidity",
666
+ )
667
+
668
+ zone4_plot = gr.ScatterPlot(
669
+ dfcleaned,
670
+ x="Timestamp",
671
+ y="Z4_RH",
672
+ color="off-nominal",
673
+ title="Zone 4 Relative Humidity",
674
+ )
675
+
676
+ # Group all plots into a list for easy management
677
+ plots = [anomaly_plot, zone3_plot, zone4_plot]
678
+
679
+ def select_region(selection: gr.SelectData):
680
+ """
681
+ Handles the region selection event.
682
+
683
+ Args:
684
+ selection (gr.SelectData): The data from the selection event.
685
+
686
+ Returns:
687
+ List[gr.Plot.update]: A list of update instructions for each plot.
688
+ """
689
+ if selection is None or selection.index is None:
690
+ return [gr.Plot.update() for _ in plots]
691
+
692
+ min_x, max_x = selection.index
693
+ # Update the x_lim for each plot
694
+ return [gr.ScatterPlot(x_lim=(min_x, max_x)) for _ in plots]
695
+
696
+ def reset_region():
697
+ """
698
+ Resets the x-axis limits for all plots.
699
+
700
+ Returns:
701
+ List[gr.Plot.update]: A list of update instructions to reset x_lim.
702
+ """
703
+ return [gr.ScatterPlot(x_lim=None) for _ in plots]
704
+
705
+ # Attach event listeners to each plot
706
+ for plot in plots:
707
+ plot.select(
708
+ select_region,
709
+ inputs=None,
710
+ outputs=plots # Update all plots
711
+ )
712
+ plot.double_click(
713
+ reset_region,
714
+ inputs=None,
715
+ outputs=plots # Reset all plots
716
+ )
717
+
718
+ # plots = [plt, first_plot, second_plot]
719
+
720
+ # def select_region(selection: gr.SelectData):
721
+ # min_w, max_w = selection.index
722
+ # return gr.ScatterPlot(x_lim=(min_w, max_w))
723
+
724
+ # for p in plots:
725
+ # p.select(select_region, None, plots)
726
+ # p.double_click(lambda: [gr.LinePlot(x_lim=None)] * len(plots), None, plots)
727
+
728
+ # second_plot.select(select_second_region, None, plt)
729
+ # second_plot.double_click(lambda: gr.ScatterPlot(x_lim=None), None, plt)
730
+ # gr.Column([anomaly_plot, first_plot, second_plot])
731
+
732
+ # anomaly_info = gr.Markdown("Anomaly detected around October 15, 2023")
733
+ with gr.Column():
734
+ query = gr.Textbox(label="Enter your question about the data",
735
+ value="Plot the anomaly_score as a function of time and highlight the highest 20 values")
736
+ query_button = gr.Button("Submit Data Query")
737
+ with gr.Row():
738
+ with gr.Column(visible=False) as output_col1:
739
+ out1 = gr.Textbox(label="Response")
740
+ with gr.Column(visible=False) as output_col2:
741
+ out2 = gr.Image(label="Plot")
742
+ with gr.Column(visible=False) as output_col3:
743
+ out3 = gr.DataFrame(label="DataFrame")
744
+ query_button.click(
745
+ fn=process_query,
746
+ inputs=query,
747
+ outputs=[
748
+ out1, # Text output
749
+ out2, # Image output
750
+ out3, # DataFrame output
751
+ output_col1, # Visibility for Text output
752
+ output_col2, # Visibility for Image output
753
+ output_col3 # Visibility for DataFrame output
754
+ ],
755
+ api_name="process_query"
756
+ )
757
+
758
+ # hide visibility until its ready
759
+
760
+
761
+ # Weather input
762
+ # with gr.Row():
763
+ # iface = gradio_app()
764
+
765
+
766
+ demo.launch(share=False)