Advertisement
pankaj13

My source code

May 22nd, 2025 (edited)
170
0
364 days
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.78 KB | Source Code | 0 0
  1. import hassapi as hass
  2. from influxdb import InfluxDBClient
  3. import datetime
  4. import pandas as pd
  5. from langchain_openai import OpenAI
  6.  
  7. class InfluxDBTelemetry(hass.Hass):
  8.     def initialize(self):
  9.         """Initialize the InfluxDB connection and settings."""
  10.         # Get configuration from AppDaemon args
  11.         self.influx_host = self.args["influx_host"]
  12.         self.influx_port = self.args["influx_port"]
  13.         self.influx_user = self.args["influx_user"]
  14.         self.influx_password = self.args["influx_password"]
  15.         self.database = self.args["database"]
  16.        
  17.         # Get OpenAI configuration
  18.         self.openai_api_key = self.args["openai_api_key"]
  19.         self.role = self.args["role"]
  20.         self.instructions = self.args["instructions"]
  21.        
  22.         # Initialize OpenAI client
  23.         try:
  24.             self.openai = OpenAI(
  25.                 api_key=self.openai_api_key,
  26.                 temperature=0
  27.             )
  28.             self.log("Successfully initialized OpenAI client")
  29.         except Exception as e:
  30.             self.error(f"Failed to initialize OpenAI client: {str(e)}")
  31.             return
  32.        
  33.         # Initialize InfluxDB client
  34.         try:
  35.             self.client = InfluxDBClient(
  36.                 host=self.influx_host,
  37.                 port=self.influx_port,
  38.                 username=self.influx_user,
  39.                 password=self.influx_password,
  40.                 database=self.database
  41.             )
  42.             self.log("Successfully connected to InfluxDB")
  43.             self.query_and_process_data()
  44.         except Exception as e:
  45.             self.error(f"Failed to connect to InfluxDB: {str(e)}")
  46.             return
  47.  
  48.     def query_and_process_data(self):
  49.         """Query data from InfluxDB, process it using pandas, and send to OpenAI"""
  50.         try:
  51.             self.log("Querying data from InfluxDB")
  52.             self.query = self.args["query"]
  53.             self.result = self.client.query(self.query)
  54.            
  55.             # Convert query results to pandas DataFrame
  56.             self.df = pd.DataFrame(self.result.get_points())
  57.            
  58.             if not self.df.empty:
  59.                 # Get all columns except 'time'
  60.                 self.value_columns = [col for col in self.df.columns if col != 'time']
  61.                
  62.                 # Check if there are any non-null values in columns other than timestamp
  63.                 self.df['has_values'] = self.df[self.value_columns].notna().any(axis=1)
  64.                
  65.                 # Filter out rows that only contain timestamp
  66.                 self.filtered_df = self.df[self.df['has_values']].drop('has_values', axis=1)
  67.                
  68.                 self.log(f"Original dataset shape: {self.df.shape}")
  69.                 self.log(f"Filtered dataset shape: {self.filtered_df.shape}")
  70.                 self.log(f"Removed {self.df.shape[0] - self.filtered_df.shape[0]} rows with only timestamp values")
  71.                
  72.                 # Prepare prompt for OpenAI
  73.                 self.prompt = f"{self.role}\n\n{self.instructions}\n\nData:\n{self.filtered_df.to_string()}"
  74.                
  75.                 # Send to OpenAI
  76.                 try:
  77.                     self.response = self.openai.predict(self.prompt)
  78.                     self.log("Successfully received response from OpenAI")
  79.                     self.log(f"OpenAI Response: {self.response}")
  80.                     return self.response
  81.                 except Exception as e:
  82.                     self.error(f"OpenAI API call failed: {str(e)}")
  83.                     return None
  84.             else:
  85.                 self.log("Query returned no data")
  86.                 return None
  87.                
  88.         except Exception as e:
  89.             self.error(f"Query or data processing failed: {str(e)}")
  90.             return None
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement