lavanya121 commited on
Commit
6376c2b
·
verified ·
1 Parent(s): 5ffa9be

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +78 -34
app.py CHANGED
@@ -3,68 +3,112 @@ import pandas as pd
3
  from datetime import datetime
4
  import json
5
  from transformers import pipeline
 
 
 
 
 
6
 
7
  # Load Hugging Face summarization model
8
- summarizer = pipeline("text2text-generation", model="google/flan-t5-base")
 
 
 
 
 
9
 
10
  # Sample rule-based anomaly detector
11
  def detect_anomalies(df):
12
  anomalies = []
13
- for _, row in df.iterrows():
14
- if row.get("usage_hours", 0) > 10: # Example threshold
15
- anomalies.append({
16
- "device_id": row["device_id"],
17
- "issue": "Usage spike",
18
- "detected_on": row["timestamp"].split("T")[0],
19
- "severity": "high"
20
- })
 
 
 
 
 
21
  return anomalies
22
 
23
  # Format summary prompt and generate report
24
  def summarize_logs(df, lab_name, start_date, end_date):
25
- # Simple aggregation
26
- total_devices = df["device_id"].nunique()
27
- avg_uptime = "97%" # Placeholder
28
- most_used = df.groupby("device_id")["usage_hours"].sum().idxmax()
29
- downtime_events = 3 # Placeholder
30
 
31
- prompt = (
32
- f"Summarize maintenance and usage logs for lab {lab_name} "
33
- f"from {start_date} to {end_date}. "
34
- f"There were {total_devices} devices. "
35
- f"The most used device was {most_used}."
36
- )
37
- summary = summarizer(prompt, max_length=200, do_sample=False)[0]["generated_text"]
38
- return summary
 
 
 
 
39
 
40
  # Main Gradio function
41
  def process_logs(file_obj, lab_site, start_date, end_date):
42
  try:
43
- df = pd.read_json(file_obj.name) if file_obj.name.endswith(".json") else pd.read_csv(file_obj.name)
44
- except Exception as e:
45
- return f"Failed to read file: {str(e)}", None, None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46
 
47
- anomalies = detect_anomalies(df)
48
- summary = summarize_logs(df, lab_site, start_date, end_date)
 
49
 
50
- return summary, anomalies, df.head().to_markdown()
 
 
 
51
 
52
  # Gradio Interface
53
  iface = gr.Interface(
54
  fn=process_logs,
55
  inputs=[
56
- gr.File(label="Upload Logs (CSV or JSON)"),
57
- gr.Textbox(label="Lab Site"),
58
- gr.Textbox(label="Start Date (YYYY-MM-DD)"),
59
- gr.Textbox(label="End Date (YYYY-MM-DD)")
60
  ],
61
  outputs=[
62
  gr.Textbox(label="Summary Report"),
63
  gr.JSON(label="Anomalies"),
64
  gr.Markdown(label="Preview of Logs")
65
  ],
66
- title="LabOps Log Analyzer (Hugging Face AI)"
 
67
  )
68
 
69
  if __name__ == "__main__":
70
- iface.launch()
 
 
 
 
 
 
 
3
  from datetime import datetime
4
  import json
5
  from transformers import pipeline
6
+ import logging
7
+ import os
8
+
9
+ # Configure logging for debugging
10
+ logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
11
 
12
  # Load Hugging Face summarization model
13
+ try:
14
+ summarizer = pipeline("text2text-generation", model="google/flan-t5-base")
15
+ logging.info("Hugging Face model loaded successfully")
16
+ except Exception as_abi0 as e:
17
+ logging.error(f"Failed to load model: {str(e)}")
18
+ raise e
19
 
20
  # Sample rule-based anomaly detector
21
  def detect_anomalies(df):
22
  anomalies = []
23
+ try:
24
+ for _, row in df.iterrows():
25
+ usage_hours = row.get("usage_hours", 0)
26
+ if isinstance(usage_hours, (int, float)) and usage_hours > 10: # Example threshold
27
+ anomalies.append({
28
+ "device_id": row["device_id"],
29
+ "issue": "Usage spike",
30
+ "detected_on": row["timestamp"].split("T")[0] if isinstance(row["timestamp"], str) else str(row["timestamp"]),
31
+ "severity": "high"
32
+ })
33
+ except Exception as e:
34
+ logging.error(f"Anomaly detection failed: {str(e)}")
35
+ return []
36
  return anomalies
37
 
38
  # Format summary prompt and generate report
39
  def summarize_logs(df, lab_name, start_date, end_date):
40
+ try:
41
+ total_devices = df["device_id"].nunique()
42
+ avg_uptime = "97%" # Placeholder
43
+ most_used = df.groupby("device_id")["usage_hours"].sum().idxmax()
44
+ downtime_events = 3 # Placeholder
45
 
46
+ prompt = (
47
+ f"Summarize maintenance and usage logs for lab {lab_name} "
48
+ f"from {start_date} to {end_date}. "
49
+ f"There were {total_devices} devices. "
50
+ f"The most used device was {most_used}."
51
+ )
52
+ summary = summarizer(prompt, max_length=200, do_sample=False)[0]["generated_text"]
53
+ logging.info("Summary generated successfully")
54
+ return summary
55
+ except Exception as e:
56
+ logging.error(f"Summary generation failed: {str(e)}")
57
+ return "Failed to generate summary."
58
 
59
  # Main Gradio function
60
  def process_logs(file_obj, lab_site, start_date, end_date):
61
  try:
62
+ if file_obj is None:
63
+ logging.warning("No file uploaded, returning empty results")
64
+ return "No file uploaded.", [], "No data to preview."
65
+
66
+ # Read file based on extension
67
+ file_name = file_obj.name if hasattr(file_obj, 'name') else file_obj
68
+ logging.info(f"Processing file: {file_name}")
69
+
70
+ if file_name.endswith(".json"):
71
+ df = pd.read_json(file_name)
72
+ elif file_name.endswith(".csv"):
73
+ df = pd.read_csv(file_name)
74
+ else:
75
+ logging.error("Unsupported file format")
76
+ return "Unsupported file format. Please upload a CSV or JSON file.", [], None
77
+
78
+ logging.info(f"File loaded successfully with {len(df)} rows")
79
 
80
+ anomalies = detect_anomalies(df)
81
+ summary = summarize_logs(df, lab_site, start_date, end_date)
82
+ preview = df.head().to_markdown() if not df.empty else "No data available."
83
 
84
+ return summary, anomalies, preview
85
+ except Exception as e:
86
+ logging.error(f"Failed to process file: {str(e)}")
87
+ return f"Failed to process file: {str(e)}", [], None
88
 
89
  # Gradio Interface
90
  iface = gr.Interface(
91
  fn=process_logs,
92
  inputs=[
93
+ gr.File(label="Upload Logs (CSV or JSON)", file_types=[".csv", ".json"]),
94
+ gr.Textbox(label="Lab Site", placeholder="e.g., Lab A"),
95
+ gr.Textbox(label="Start Date (YYYY-MM-DD)", placeholder="e.g., 2025-01-01"),
96
+ gr.Textbox(label="End Date (YYYY-MM-DD)", placeholder="e.g., 2025-01-31")
97
  ],
98
  outputs=[
99
  gr.Textbox(label="Summary Report"),
100
  gr.JSON(label="Anomalies"),
101
  gr.Markdown(label="Preview of Logs")
102
  ],
103
+ title="LabOps Log Analyzer (Hugging Face AI)",
104
+ description="Upload a CSV or JSON file containing lab equipment logs to analyze usage and detect anomalies."
105
  )
106
 
107
  if __name__ == "__main__":
108
+ try:
109
+ logging.info("Launching Gradio interface")
110
+ # Launch with debug mode for local testing
111
+ iface.launch(server_name="0.0.0.0", server_port=7860, debug=True)
112
+ except Exception as e:
113
+ logging.error(f"Failed to launch Gradio interface: {str(e)}")
114
+ print(f"Error launching app: {str(e)}")