lavanya121 commited on
Commit
357a70f
·
verified ·
1 Parent(s): cc45209

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +94 -52
app.py CHANGED
@@ -1,13 +1,24 @@
1
  from flask import Flask, request, jsonify
2
- from transformers import pipeline
3
  import pandas as pd
4
  from datetime import datetime, timedelta
5
  import json
 
 
6
 
7
  app = Flask(__name__)
8
 
9
- # Initialize Hugging Face summarization pipeline
10
- summarizer = pipeline("text2text-generation", model="t5-small")
 
 
 
 
 
 
 
 
 
 
11
 
12
  # Helper function to calculate days until AMC expiry
13
  def days_until_expiry(expiry_date_str):
@@ -15,82 +26,110 @@ def days_until_expiry(expiry_date_str):
15
  expiry_date = datetime.strptime(expiry_date_str, "%Y-%m-%d")
16
  current_date = datetime.now()
17
  return (expiry_date - current_date).days
18
- except ValueError:
 
19
  return None
20
 
21
- # Helper function to detect anomalies (rule-based)
22
  def detect_anomalies(logs):
23
  anomalies = []
24
  for log in logs:
25
- # Rule 1: Flag ERROR status as high severity
26
- if log["status"] == "ERROR":
27
- anomalies.append({
28
- "device_id": log["device_id"],
29
- "issue": "ERROR status detected",
30
- "detected_on": log["timestamp"],
31
- "severity": "high"
32
- })
33
- # Rule 2: Flag usage spikes (>7 hours as example threshold)
34
- if log["usage_hours"] > 7:
35
- anomalies.append({
36
- "device_id": log["device_id"],
37
- "issue": "Usage spike",
38
- "detected_on": log["timestamp"],
39
- "severity": "high"
40
- })
41
- # Rule 3: Flag downtime (usage_hours = 0 with DOWN status)
42
- if log["status"] == "DOWN" and log["usage_hours"] == 0:
43
- anomalies.append({
44
- "device_id": log["device_id"],
45
- "issue": "Unplanned downtime",
46
- "detected_on": log["timestamp"],
47
- "severity": "medium"
48
- })
 
 
 
49
  return anomalies
50
 
51
  # Helper function to generate AMC reminders
52
  def generate_amc_reminders(logs):
53
  reminders = []
54
  for log in logs:
55
- days_left = days_until_expiry(log["amc_expiry"])
56
- if days_left is not None and 0 < days_left <= 30:
57
- reminders.append({
58
- "device_id": log["device_id"],
59
- "amc_expiry": log["amc_expiry"],
60
- "days_remaining": days_left,
61
- "alert": f"AMC expires in {days_left} days"
62
- })
 
 
 
63
  return reminders
64
 
65
  # Helper function to summarize logs
66
  def summarize_logs(logs, prompt):
67
- # Convert logs to text for summarization
68
- log_text = "\n".join([f"Device {log['device_id']} ({log['log_type']}): Status {log['status']}, Usage {log['usage_hours']} hours, Timestamp {log['timestamp']}, AMC Expiry {log['amc_expiry']}" for log in logs])
69
- input_text = f"{prompt}\n\nLogs:\n{log_text}"
70
-
71
- # Use Hugging Face summarizer
72
- summary = summarizer(input_text, max_length=150, min_length=50, do_sample=False)[0]["generated_text"]
73
- return summary
 
 
 
 
 
 
 
 
74
 
75
  # API endpoint to process logs
76
  @app.route("/process-logs", methods=["POST"])
77
  def process_logs():
78
  try:
79
  data = request.get_json()
 
 
 
 
80
  logs = data.get("logs", [])
81
  prompt = data.get("prompt", "Summarize downtime and usage patterns for SmartLab-1 from May 1 to May 14")
82
 
83
  if not logs:
84
- return jsonify({"error": "No logs provided"}), 400
 
85
 
86
  # Convert logs to DataFrame for analysis
87
- df = pd.DataFrame(logs)
88
-
 
 
 
 
89
  # Calculate summary metrics
90
- total_devices = len(df["device_id"].unique())
91
- avg_uptime = len(df[df["status"] == "OK"]) / len(df) * 100 if len(df) > 0 else 0
92
- downtime_events = len(df[df["status"] == "DOWN"])
93
- most_used_device = df.groupby("device_id")["usage_hours"].sum().idxmax() if not df.empty else "N/A"
 
 
 
 
94
 
95
  # Generate outputs
96
  summary = {
@@ -124,6 +163,7 @@ Generated on: {datetime.now().strftime('%Y-%m-%d')}
124
  {text_summary}
125
  """
126
 
 
127
  return jsonify({
128
  "summary": summary,
129
  "anomalies": anomalies,
@@ -132,7 +172,9 @@ Generated on: {datetime.now().strftime('%Y-%m-%d')}
132
  })
133
 
134
  except Exception as e:
135
- return jsonify({"error": str(e)}), 500
 
136
 
137
  if __name__ == "__main__":
 
138
  app.run(debug=True, host="0.0.0.0", port=5000)
 
1
  from flask import Flask, request, jsonify
 
2
  import pandas as pd
3
  from datetime import datetime, timedelta
4
  import json
5
+ import logging
6
+ import sys
7
 
8
  app = Flask(__name__)
9
 
10
+ # Configure logging to diagnose issues
11
+ logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
12
+ logger = logging.getLogger(__name__)
13
+
14
+ # Try to load Hugging Face summarization pipeline with fallback
15
+ try:
16
+ from transformers import pipeline
17
+ summarizer = pipeline("text2text-generation", model="t5-small", framework="pt")
18
+ logger.info("Hugging Face model 't5-small' loaded successfully.")
19
+ except Exception as e:
20
+ logger.error(f"Failed to load Hugging Face model: {str(e)}")
21
+ summarizer = None # Fallback to skip summarization if model fails
22
 
23
  # Helper function to calculate days until AMC expiry
24
  def days_until_expiry(expiry_date_str):
 
26
  expiry_date = datetime.strptime(expiry_date_str, "%Y-%m-%d")
27
  current_date = datetime.now()
28
  return (expiry_date - current_date).days
29
+ except ValueError as e:
30
+ logger.warning(f"Invalid date format for AMC expiry: {expiry_date_str}, error: {str(e)}")
31
  return None
32
 
33
+ # Helper function to detect anomalies (rule-based, simplified)
34
  def detect_anomalies(logs):
35
  anomalies = []
36
  for log in logs:
37
+ try:
38
+ # Rule 1: Flag ERROR status as high severity
39
+ if log.get("status") == "ERROR":
40
+ anomalies.append({
41
+ "device_id": log.get("device_id", "Unknown"),
42
+ "issue": "ERROR status detected",
43
+ "detected_on": log.get("timestamp", "N/A"),
44
+ "severity": "high"
45
+ })
46
+ # Rule 2: Flag usage spikes (>7 hours as example threshold)
47
+ if log.get("usage_hours", 0) > 7:
48
+ anomalies.append({
49
+ "device_id": log.get("device_id", "Unknown"),
50
+ "issue": "Usage spike",
51
+ "detected_on": log.get("timestamp", "N/A"),
52
+ "severity": "high"
53
+ })
54
+ # Rule 3: Flag downtime (usage_hours = 0 with DOWN status)
55
+ if log.get("status") == "DOWN" and log.get("usage_hours", 0) == 0:
56
+ anomalies.append({
57
+ "device_id": log.get("device_id", "Unknown"),
58
+ "issue": "Unplanned downtime",
59
+ "detected_on": log.get("timestamp", "N/A"),
60
+ "severity": "medium"
61
+ })
62
+ except Exception as e:
63
+ logger.error(f"Error processing log entry {log}: {str(e)}")
64
  return anomalies
65
 
66
  # Helper function to generate AMC reminders
67
  def generate_amc_reminders(logs):
68
  reminders = []
69
  for log in logs:
70
+ try:
71
+ days_left = days_until_expiry(log.get("amc_expiry", ""))
72
+ if days_left is not None and 0 < days_left <= 30:
73
+ reminders.append({
74
+ "device_id": log.get("device_id", "Unknown"),
75
+ "amc_expiry": log.get("amc_expiry", "N/A"),
76
+ "days_remaining": days_left,
77
+ "alert": f"AMC expires in {days_left} days"
78
+ })
79
+ except Exception as e:
80
+ logger.error(f"Error processing AMC for log {log}: {str(e)}")
81
  return reminders
82
 
83
  # Helper function to summarize logs
84
  def summarize_logs(logs, prompt):
85
+ try:
86
+ if summarizer is None:
87
+ logger.warning("Summarizer model not available, returning basic summary.")
88
+ return "Summary unavailable: Model not loaded. Please check logs for details."
89
+
90
+ # Convert logs to text for summarization
91
+ log_text = "\n".join([f"Device {log.get('device_id', 'Unknown')} ({log.get('log_type', 'N/A')}): Status {log.get('status', 'N/A')}, Usage {log.get('usage_hours', 0)} hours, Timestamp {log.get('timestamp', 'N/A')}, AMC Expiry {log.get('amc_expiry', 'N/A')}" for log in logs])
92
+ input_text = f"{prompt}\n\nLogs:\n{log_text}"
93
+
94
+ # Use Hugging Face summarizer
95
+ summary = summarizer(input_text, max_length=150, min_length=50, do_sample=False)[0]["generated_text"]
96
+ return summary
97
+ except Exception as e:
98
+ logger.error(f"Error generating summary: {str(e)}")
99
+ return f"Summary unavailable: {str(e)}"
100
 
101
  # API endpoint to process logs
102
  @app.route("/process-logs", methods=["POST"])
103
  def process_logs():
104
  try:
105
  data = request.get_json()
106
+ if not data or "logs" not in data:
107
+ logger.error("Invalid or missing logs in request.")
108
+ return jsonify({"error": "No logs provided in the request"}), 400
109
+
110
  logs = data.get("logs", [])
111
  prompt = data.get("prompt", "Summarize downtime and usage patterns for SmartLab-1 from May 1 to May 14")
112
 
113
  if not logs:
114
+ logger.error("Empty logs list provided.")
115
+ return jsonify({"error": "Logs list is empty"}), 400
116
 
117
  # Convert logs to DataFrame for analysis
118
+ try:
119
+ df = pd.DataFrame(logs)
120
+ except Exception as e:
121
+ logger.error(f"Failed to convert logs to DataFrame: {str(e)}")
122
+ return jsonify({"error": f"Invalid log format: {str(e)}"}), 400
123
+
124
  # Calculate summary metrics
125
+ try:
126
+ total_devices = len(df["device_id"].unique())
127
+ avg_uptime = len(df[df["status"] == "OK"]) / len(df) * 100 if len(df) > 0 else 0
128
+ downtime_events = len(df[df["status"] == "DOWN"])
129
+ most_used_device = df.groupby("device_id")["usage_hours"].sum().idxmax() if not df.empty else "N/A"
130
+ except Exception as e:
131
+ logger.error(f"Error calculating summary metrics: {str(e)}")
132
+ total_devices, avg_uptime, downtime_events, most_used_device = 0, 0, 0, "N/A"
133
 
134
  # Generate outputs
135
  summary = {
 
163
  {text_summary}
164
  """
165
 
166
+ logger.info("Successfully processed logs and generated response.")
167
  return jsonify({
168
  "summary": summary,
169
  "anomalies": anomalies,
 
172
  })
173
 
174
  except Exception as e:
175
+ logger.error(f"Unexpected error in process_logs: {str(e)}")
176
+ return jsonify({"error": f"Internal server error: {str(e)}"}), 500
177
 
178
  if __name__ == "__main__":
179
+ logger.info(f"Starting Flask app with Python version {sys.version}")
180
  app.run(debug=True, host="0.0.0.0", port=5000)