| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109 |
- from http.server import BaseHTTPRequestHandler, HTTPServer
- from urllib.parse import parse_qs
- import json
- import logging
- from datetime import datetime
- from openai import OpenAI # OpenAI Python client
- # Configure logging
- logging.basicConfig(
- filename="duplicati_logs.log",
- level=logging.INFO,
- format="%(asctime)s - %(message)s",
- )
- # OpenAI API configuration
- API_KEY = "sk-175159668af9430ea6208f5636b24198" # Replace with your OpenAI API key
- MODEL = "deepseek-chat"
- class DuplicatiLogHandler(BaseHTTPRequestHandler):
- def do_POST(self):
- # Get the length of the data
- content_length = int(self.headers["Content-Length"])
- # Read the POST data
- post_data = self.rfile.read(content_length).decode("utf-8")
- # Parse the form-urlencoded data
- data = parse_qs(post_data)
- # Log the data
- self.log_data(data)
- # Send the log message to OpenAI API for analysis
- analysis_result, diagnostic_message = self.send_to_openai(data)
- if analysis_result:
- logging.info(f"OpenAI Analysis Result: {analysis_result}")
- if diagnostic_message:
- logging.info(f"Diagnostic Message: {diagnostic_message}")
- # Send a response
- self.send_response(200)
- self.send_header("Content-type", "application/json")
- self.end_headers()
- response = {
- "status": "success",
- "message": "Log received",
- "analysis_result": analysis_result,
- "diagnostic_message": diagnostic_message,
- }
- self.wfile.write(json.dumps(response).encode("utf-8"))
- def log_data(self, data):
- """Log the received data to a file."""
- log_entry = {
- "timestamp": datetime.now().isoformat(),
- "data": data,
- }
- logging.info(json.dumps(log_entry))
- def send_to_openai(self, data):
- """Send the raw log data to OpenAI API for analysis."""
- try:
- # Prepare the messages for OpenAI API
- messages = [
- {
- "role": "system",
- "content": "You are an operator analyzing backup logs. "
- "Check the log message for abnormalities and respond with 'normal' or 'abnormal'. "
- "If the backup is abnormal, provide a detailed diagnostic message explaining the issue and suggesting possible fixes.",
- },
- {
- "role": "user",
- "content": json.dumps(data), # Pass the raw data as a JSON string
- },
- ]
- # Make a request to OpenAI API
- client = OpenAI(api_key=API_KEY, base_url="https://api.deepseek.com")
- response = client.chat.completions.create(
- model=MODEL,
- messages=messages,
- max_tokens=1024,
- temperature=0.7,
- stream=False
- )
- # Parse the response
- chat_response = response.choices[0].message.content
- # Extract analysis result and diagnostic message
- if "abnormal" in chat_response.lower():
- analysis_result = "abnormal"
- diagnostic_message = chat_response # Use the full response as the diagnostic message
- else:
- analysis_result = "normal"
- diagnostic_message = chat_response
- return analysis_result, diagnostic_message
- except Exception as e:
- logging.error(f"Failed to send data to OpenAI API: {e}")
- return None, None
- def run(server_class=HTTPServer, handler_class=DuplicatiLogHandler, port=8680):
- server_address = ("", port)
- httpd = server_class(server_address, handler_class)
- print(f"Starting Duplicati log server on port {port}...")
- httpd.serve_forever()
- if __name__ == "__main__":
- run()
|