lavanya121 commited on
Commit
6e360bb
·
verified ·
1 Parent(s): 4a584ba

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +109 -150
app.py CHANGED
@@ -1,214 +1,173 @@
1
  import gradio as gr
2
  import pandas as pd
3
  from datetime import datetime
4
- import logging
5
- import io
6
  from transformers import pipeline
 
 
 
7
 
8
- # Configure logging
9
  logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
10
 
11
- # Load Hugging Face model
12
  try:
13
- logging.info("Loading Hugging Face model...")
14
- summarizer = pipeline("text2text-generation", model="t5-small") # Using t5-small for faster loading
15
- logging.info("Model loaded successfully")
16
  except Exception as e:
17
  logging.error(f"Failed to load model: {str(e)}")
18
  raise e
19
 
20
- # Summarize logs
21
  def summarize_logs(df, lab_name, start_date, end_date):
22
  try:
23
  total_devices = df["device_id"].nunique()
 
24
  most_used = df.groupby("device_id")["usage_hours"].sum().idxmax() if not df.empty else "N/A"
 
 
25
  prompt = (
26
- f"Summarize maintenance logs for lab {lab_name} "
27
  f"from {start_date} to {end_date}. "
28
- f"Total devices: {total_devices}. Most used device: {most_used}."
 
29
  )
30
- logging.info("Generating summary with prompt: %s", prompt)
31
- summary = summarizer(prompt, max_length=150, do_sample=False)[0]["generated_text"]
32
- logging.info("Summary generated: %s", summary)
33
  return summary
34
  except Exception as e:
35
  logging.error(f"Summary generation failed: {str(e)}")
36
- return f"Error generating summary: {str(e)}"
37
 
38
- # Generate text response
39
- def generate_text_response(df, lab_name, start_date, end_date):
40
  try:
41
- total_usage = df["usage_hours"].sum()
42
- avg_usage_per_device = df.groupby("device_id")["usage_hours"].sum().mean()
43
- response = (
44
- f"Maintenance Report for {lab_name} ({start_date} to {end_date}):\n"
45
- f"- Total Usage Hours: {total_usage:.2f} hours\n"
46
- f"- Average Usage per Device: {avg_usage_per_device:.2f} hours\n"
47
- f"- Number of Devices: {df['device_id'].nunique()}\n"
48
- f"- Period Covered: {start_date} to {end_date}"
 
49
  )
50
- logging.info("Text response generated: %s", response)
51
- return response
 
 
 
 
 
 
52
  except Exception as e:
53
- logging.error(f"Text response generation failed: {str(e)}")
54
- return f"Error generating text response: {str(e)}"
55
 
56
- # Generate suggested actions
57
- def generate_suggested_actions(df):
58
  try:
59
- high_usage_devices = df.groupby("device_id")["usage_hours"].sum()
60
- high_usage_devices = high_usage_devices[high_usage_devices > 5].index.tolist() # Lowered threshold
61
- if high_usage_devices:
62
- actions = (
63
- f"Suggested Actions:\n"
64
- f"- Inspect Devices: {', '.join(map(str, high_usage_devices))} have high usage (>5 hours). Schedule maintenance.\n"
65
- f"- Load Balancing: Redistribute workload.\n"
66
- f"- Monitor Downtime: Minimize downtime events."
67
- )
 
 
 
68
  else:
69
- actions = (
70
- "Suggested Actions:\n"
71
- "- Routine Maintenance: No devices exceed usage thresholds.\n"
72
- "- Monitor Trends: Track usage patterns."
73
- )
74
- logging.info("Suggested actions generated: %s", actions)
75
- return actions
76
- except Exception as e:
77
- logging.error(f"Suggested actions generation failed: {str(e)}")
78
- return f"Error generating suggested actions: {str(e)}"
79
 
80
- # Generate downloadable report
81
- def generate_maintenance_report(df, lab_name, start_date, end_date):
82
- try:
83
- report_data = {
84
- "Lab Name": [lab_name] * len(df),
85
- "Device ID": df["device_id"],
86
- "Usage Hours": df["usage_hours"],
87
- "Timestamp": df["timestamp"],
88
- "Report Period Start": [start_date] * len(df),
89
- "Report Period End": [end_date] * len(df)
90
- }
91
- report_df = pd.DataFrame(report_data)
92
- output = io.StringIO()
93
- report_df.to_csv(output, index=False)
94
- output.seek(0)
95
- logging.info("Maintenance report generated")
96
- return output.getvalue(), f"{lab_name}_maintenance_report_{datetime.now().strftime('%Y%m%d_%H%M%S')}.csv"
97
- except Exception as e:
98
- logging.error(f"Report generation failed: {str(e)}")
99
- return None, None
100
 
101
- # Main processing function
102
- def process_logs(file_obj, lab_site, start_date, end_date):
103
- try:
104
- # Fallback data if no file is uploaded
105
- if not file_obj:
106
- logging.warning("No file uploaded, using sample data")
107
- df = pd.DataFrame({
108
- "device_id": ["Device1", "Device2", "Device1"],
109
- "usage_hours": [5.5, 3.2, 4.0],
110
- "timestamp": ["2025-05-01 10:00:00", "2025-05-02 12:00:00", "2025-05-03 14:00:00"]
111
- })
112
- df["timestamp"] = pd.to_datetime(df["timestamp"])
113
- else:
114
- logging.info(f"Processing file: {file_obj.name}")
115
- if file_obj.name.endswith(".json"):
116
- df = pd.read_json(file_obj)
117
- elif file_obj.name.endswith(".csv"):
118
- df = pd.read_csv(file_obj)
119
- else:
120
- logging.error("Unsupported file format")
121
- return "Upload a CSV or JSON file.", None, None, None, None
122
-
123
- logging.info(f"Loaded data with {len(df)} rows")
124
-
125
- # Filter by date range
126
  try:
127
  df["timestamp"] = pd.to_datetime(df["timestamp"])
128
  start_date = pd.to_datetime(start_date)
129
  end_date = pd.to_datetime(end_date)
130
  df = df[(df["timestamp"] >= start_date) & (df["timestamp"] <= end_date)]
131
- logging.info(f"Filtered to {len(df)} rows")
132
- if df.empty:
133
- return "No data in date range.", None, None, None, None
134
  except Exception as e:
135
  logging.error(f"Date filtering failed: {str(e)}")
136
- return f"Date filtering error: {str(e)}", None, None, None, None
 
 
 
 
137
 
138
- text_response = generate_text_response(df, lab_site, start_date, end_date)
139
- maintenance_report, report_filename = generate_maintenance_report(df, lab_site, start_date, end_date)
140
- suggested_actions = generate_suggested_actions(df)
141
  summary = summarize_logs(df, lab_site, start_date, end_date)
 
 
142
 
143
- return text_response, maintenance_report, suggested_actions, summary, report_filename
144
  except Exception as e:
145
- logging.error(f"Processing failed: {str(e)}")
146
- return f"Error processing file: {str(e)}", None, None, None, None
147
-
148
- # Gradio Interface
149
- def create_gradio_interface():
150
- css = """
151
- .report-container {border: 1px solid #e0e0e0; padding: 15px; border-radius: 8px; background-color: #f5f5f5;}
152
- .report-title {font-size: 28px; font-weight: bold; margin-bottom: 15px; color: #333;}
153
- .report-section {margin-bottom: 20px;}
154
- .report-section h3 {font-size: 20px; margin-bottom: 8px; color: #555;}
155
- """
156
-
157
- with gr.Blocks(css=css, theme=gr.themes.Soft()) as iface:
158
- gr.Markdown("<h1>LabOps Maintenance Report Generator</h1>")
159
- gr.Markdown("Upload a CSV or JSON file to generate a maintenance report. Use format: device_id, usage_hours, timestamp.")
160
 
161
  with gr.Row():
162
  with gr.Column(scale=1):
163
  file_input = gr.File(label="Upload Logs (CSV or JSON)", file_types=[".csv", ".json"])
164
  lab_site_input = gr.Textbox(label="Lab Site", placeholder="e.g., Lab A")
165
- start_date_input = gr.Textbox(label="Start Date (YYYY-MM-DD)", placeholder="e.g., 2025-05-01")
166
- end_date_input = gr.Textbox(label="End Date (YYYY-MM-DD)", placeholder="e.g., 2025-05-30")
167
- submit_button = gr.Button("Generate Report", variant="primary")
168
 
169
  with gr.Column(scale=2):
170
- with gr.Group(elem_classes="report-container"):
171
- gr.Markdown("<div class='report-title'>Maintenance Report</div>")
172
-
173
- with gr.Row():
174
- with gr.Column():
175
- with gr.Group(elem_classes="report-section"):
176
- gr.Markdown("### Report Overview")
177
- text_response_output = gr.Textbox(lines=6, show_copy_button=True, label="")
178
 
179
  with gr.Row():
180
- with gr.Column():
181
- with gr.Group(elem_classes="report-section"):
182
- gr.Markdown("### Download Report")
183
- maintenance_report_output = gr.File(label="Download CSV")
184
 
185
  with gr.Row():
186
- with gr.Column():
187
- with gr.Group(elem_classes="report-section"):
188
- gr.Markdown("### Suggested Actions")
189
- suggested_actions_output = gr.Textbox(lines=6, show_copy_button=True, label="")
190
-
191
- with gr.Row():
192
- with gr.Column():
193
- with gr.Group(elem_classes="report-section"):
194
- gr.Markdown("### Summary")
195
- summary_output = gr.Textbox(lines=6, show_copy_button=True, label="")
196
 
197
  submit_button.click(
198
  fn=process_logs,
199
  inputs=[file_input, lab_site_input, start_date_input, end_date_input],
200
- outputs=[text_response_output, maintenance_report_output, suggested_actions_output, summary_output, maintenance_report_output]
201
  )
202
-
203
- return iface
 
 
 
204
 
205
  if __name__ == "__main__":
206
  try:
207
- logging.info("Starting Gradio interface...")
208
- iface = create_gradio_interface()
209
- iface.launch(server_name="0.0.0.0", server_port=7860, debug=True)
210
- logging.info("Interface launched successfully")
211
  except Exception as e:
212
- logging.error(f"Failed to launch interface: {str(e)}")
213
  print(f"Error launching app: {str(e)}")
214
  raise e
 
1
  import gradio as gr
2
  import pandas as pd
3
  from datetime import datetime
4
+ import json
 
5
  from transformers import pipeline
6
+ import logging
7
+ import os
8
+ import plotly.express as px
9
 
10
+ # Configure logging for debugging
11
  logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
12
 
13
+ # Load Hugging Face summarization model
14
  try:
15
+ logging.info("Attempting to load Hugging Face model...")
16
+ summarizer = pipeline("text2text-generation", model="google/flan-t5-base")
17
+ logging.info("Hugging Face model loaded successfully")
18
  except Exception as e:
19
  logging.error(f"Failed to load model: {str(e)}")
20
  raise e
21
 
22
+ # Format summary prompt and generate report
23
  def summarize_logs(df, lab_name, start_date, end_date):
24
  try:
25
  total_devices = df["device_id"].nunique()
26
+ avg_uptime = "97%" # Placeholder
27
  most_used = df.groupby("device_id")["usage_hours"].sum().idxmax() if not df.empty else "N/A"
28
+ downtime_events = 3 # Placeholder
29
+
30
  prompt = (
31
+ f"Summarize maintenance and usage logs for lab {lab_name} "
32
  f"from {start_date} to {end_date}. "
33
+ f"There were {total_devices} devices. "
34
+ f"The most used device was {most_used}."
35
  )
36
+ summary = summarizer(prompt, max_length=200, do_sample=False)[0]["generated_text"]
37
+ logging.info("Summary generated successfully")
 
38
  return summary
39
  except Exception as e:
40
  logging.error(f"Summary generation failed: {str(e)}")
41
+ return "Failed to generate summary."
42
 
43
+ # Create a bar chart for usage hours per device
44
+ def create_usage_chart(df):
45
  try:
46
+ usage_data = df.groupby("device_id")["usage_hours"].sum().reset_index()
47
+ fig = px.bar(
48
+ usage_data,
49
+ x="device_id",
50
+ y="usage_hours",
51
+ title="Usage Hours per Device",
52
+ labels={"device_id": "Device ID", "usage_hours": "Usage Hours"},
53
+ color="usage_hours",
54
+ color_continuous_scale="Blues"
55
  )
56
+ fig.update_layout(
57
+ title_font_size=16,
58
+ margin=dict(l=20, r=20, t=40, b=20),
59
+ plot_bgcolor="white",
60
+ paper_bgcolor="white",
61
+ font=dict(size=12)
62
+ )
63
+ return fig
64
  except Exception as e:
65
+ logging.error(f"Failed to create usage chart: {str(e)}")
66
+ return None
67
 
68
+ # Main Gradio function
69
+ def process_logs(file_obj, lab_site, start_date, end_date):
70
  try:
71
+ if file_obj is None:
72
+ logging.warning("No file uploaded, returning empty results")
73
+ return "No file uploaded.", "No data to preview.", None
74
+
75
+ # Read file based on extension
76
+ file_name = file_obj.name if hasattr(file_obj, 'name') else file_obj
77
+ logging.info(f"Processing file: {file_name}")
78
+
79
+ if file_name.endswith(".json"):
80
+ df = pd.read_json(file_name)
81
+ elif file_name.endswith(".csv"):
82
+ df = pd.read_csv(file_name)
83
  else:
84
+ logging.error("Unsupported file format")
85
+ return "Unsupported file format. Please upload a CSV or JSON file.", None, None
 
 
 
 
 
 
 
 
86
 
87
+ logging.info(f"File loaded successfully with {len(df)} rows")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
88
 
89
+ # Convert timestamp to datetime and filter by date range
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
90
  try:
91
  df["timestamp"] = pd.to_datetime(df["timestamp"])
92
  start_date = pd.to_datetime(start_date)
93
  end_date = pd.to_datetime(end_date)
94
  df = df[(df["timestamp"] >= start_date) & (df["timestamp"] <= end_date)]
95
+ logging.info(f"Filtered to {len(df)} rows within date range {start_date} to {end_date}")
 
 
96
  except Exception as e:
97
  logging.error(f"Date filtering failed: {str(e)}")
98
+ return f"Failed to filter data by date: {str(e)}", None, None
99
+
100
+ if df.empty:
101
+ logging.warning("No data within the specified date range")
102
+ return "No data available for the specified date range.", "No data to preview.", None
103
 
 
 
 
104
  summary = summarize_logs(df, lab_site, start_date, end_date)
105
+ preview = df.head().to_markdown() if not df.empty else "No data available."
106
+ chart = create_usage_chart(df)
107
 
108
+ return summary, preview, chart
109
  except Exception as e:
110
+ logging.error(f"Failed to process file: {str(e)}")
111
+ return f"Failed to process file: {str(e)}", None, None
112
+
113
+ # Gradio Interface with Dashboard Layout
114
+ try:
115
+ logging.info("Initializing Gradio Blocks interface...")
116
+ with gr.Blocks(css="""
117
+ .dashboard-container {border: 1px solid #e0e0e0; padding: 10px; border-radius: 5px; background-color: #f9f9f9;}
118
+ .dashboard-title {font-size: 24px; font-weight: bold; margin-bottom: 10px;}
119
+ .dashboard-section {margin-bottom: 15px;}
120
+ .dashboard-section h3 {font-size: 18px; margin-bottom: 5px;}
121
+ """) as iface:
122
+ gr.Markdown("<h1>LabOps Log Analyzer Dashboard (Hugging Face AI)</h1>")
123
+ gr.Markdown("Upload a CSV or JSON file containing lab equipment logs to analyze usage.")
 
124
 
125
  with gr.Row():
126
  with gr.Column(scale=1):
127
  file_input = gr.File(label="Upload Logs (CSV or JSON)", file_types=[".csv", ".json"])
128
  lab_site_input = gr.Textbox(label="Lab Site", placeholder="e.g., Lab A")
129
+ start_date_input = gr.Textbox(label="Start Date (YYYY-MM-DD)", placeholder="e.g., 2025-01-01")
130
+ end_date_input = gr.Textbox(label="End Date (YYYY-MM-DD)", placeholder="e.g., 2025-01-31")
131
+ submit_button = gr.Button("Submit", variant="primary")
132
 
133
  with gr.Column(scale=2):
134
+ with gr.Group(elem_classes="dashboard-container"):
135
+ gr.Markdown("<div class='dashboard-title'>Analysis Dashboard</div>")
 
 
 
 
 
 
136
 
137
  with gr.Row():
138
+ with gr.Column(scale=1):
139
+ with gr.Group(elem_classes="dashboard-section"):
140
+ gr.Markdown("### Summary Report")
141
+ summary_output = gr.Textbox(lines=5)
142
 
143
  with gr.Row():
144
+ with gr.Column(scale=1):
145
+ with gr.Group(elem_classes="dashboard-section"):
146
+ gr.Markdown("### Usage Chart")
147
+ chart_output = gr.Plot()
148
+
149
+ with gr.Column(scale=1):
150
+ with gr.Group(elem_classes="dashboard-section"):
151
+ gr.Markdown("### Log Preview")
152
+ preview_output = gr.Markdown()
 
153
 
154
  submit_button.click(
155
  fn=process_logs,
156
  inputs=[file_input, lab_site_input, start_date_input, end_date_input],
157
+ outputs=[summary_output, preview_output, chart_output]
158
  )
159
+
160
+ logging.info("Gradio interface initialized successfully")
161
+ except Exception as e:
162
+ logging.error(f"Failed to initialize Gradio interface: {str(e)}")
163
+ raise e
164
 
165
  if __name__ == "__main__":
166
  try:
167
+ logging.info("Launching Gradio interface...")
168
+ iface.launch(server_name="0.0.0.0", server_port=7860, debug=True, share=False)
169
+ logging.info("Gradio interface launched successfully")
 
170
  except Exception as e:
171
+ logging.error(f"Failed to launch Gradio interface: {str(e)}")
172
  print(f"Error launching app: {str(e)}")
173
  raise e