duplicati_analysis_server.py 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. from http.server import BaseHTTPRequestHandler, HTTPServer
  2. from urllib.parse import parse_qs
  3. import json
  4. import logging
  5. from datetime import datetime
  6. import requests # For making HTTP requests to DeepSeek API
  7. # Configure logging
  8. logging.basicConfig(
  9. filename="duplicati_logs.log",
  10. level=logging.INFO,
  11. format="%(asctime)s - %(message)s",
  12. )
  13. # DeepSeek API configuration
  14. DEEPSEEK_API_URL = "https://api.deepseek.com/v1/chat/completions" # DeepSeek Chat API endpoint
  15. DEEPSEEK_API_KEY = "sk-175159668af9430ea6208f5636b24198" # Replace with your DeepSeek API key
  16. class DuplicatiLogHandler(BaseHTTPRequestHandler):
  17. def do_POST(self):
  18. # Get the length of the data
  19. content_length = int(self.headers["Content-Length"])
  20. # Read the POST data
  21. post_data = self.rfile.read(content_length).decode("utf-8")
  22. # Parse the form-urlencoded data
  23. data = parse_qs(post_data)
  24. # Log the data
  25. self.log_data(data)
  26. # Send the log message to DeepSeek Chat API for analysis
  27. analysis_result, diagnostic_message = self.send_to_deepseek_chat(data)
  28. if analysis_result:
  29. logging.info(f"DeepSeek Analysis Result: {analysis_result}")
  30. if diagnostic_message:
  31. logging.info(f"Diagnostic Message: {diagnostic_message}")
  32. # Send a response
  33. self.send_response(200)
  34. self.send_header("Content-type", "application/json")
  35. self.end_headers()
  36. response = {
  37. "status": "success",
  38. "message": "Log received",
  39. "analysis_result": analysis_result,
  40. "diagnostic_message": diagnostic_message,
  41. }
  42. self.wfile.write(json.dumps(response).encode("utf-8"))
  43. def log_data(self, data):
  44. """Log the received data to a file."""
  45. log_entry = {
  46. "timestamp": datetime.now().isoformat(),
  47. "data": data,
  48. }
  49. logging.info(json.dumps(log_entry))
  50. def send_to_deepseek_chat(self, data):
  51. """Send the log message to DeepSeek Chat API for analysis."""
  52. try:
  53. # Prepare the payload for DeepSeek Chat API
  54. payload = {
  55. "model": "deepseek-chat", # Specify the model to use
  56. "messages": [
  57. {
  58. "role": "system",
  59. "content": "You are an operator analyzing backup logs. "
  60. "Check the log message for abnormalities and respond with 'normal' or 'abnormal'. "
  61. "If the backup is abnormal, provide a detailed diagnostic message explaining the issue and suggesting possible fixes.",
  62. },
  63. {
  64. "role": "user",
  65. "content": json.dumps(data), # Pass the raw data as a JSON string
  66. },
  67. ],
  68. }
  69. # Make a POST request to DeepSeek Chat API
  70. headers = {
  71. "Authorization": f"Bearer {DEEPSEEK_API_KEY}",
  72. "Content-Type": "application/json",
  73. }
  74. response = requests.post(DEEPSEEK_API_URL, headers=headers, json=payload)
  75. response.raise_for_status() # Raise an error for bad status codes
  76. # Parse the response
  77. result = response.json()
  78. chat_response = result["choices"][0]["message"]["content"]
  79. # Extract analysis result and diagnostic message
  80. if "abnormal" in chat_response.lower():
  81. analysis_result = "abnormal"
  82. diagnostic_message = chat_response # Use the full response as the diagnostic message
  83. else:
  84. analysis_result = "normal"
  85. diagnostic_message = None
  86. return analysis_result, diagnostic_message
  87. except requests.exceptions.RequestException as e:
  88. logging.error(f"Failed to send data to DeepSeek Chat API: {e}")
  89. return None, None
  90. def run(server_class=HTTPServer, handler_class=DuplicatiLogHandler, port=8680):
  91. server_address = ("", port)
  92. httpd = server_class(server_address, handler_class)
  93. print(f"Starting Duplicati log server on port {port}...")
  94. httpd.serve_forever()
  95. if __name__ == "__main__":
  96. run()