MaheshP98 commited on
Commit
694ca7d
·
verified ·
1 Parent(s): d71ae30

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +41 -45
app.py CHANGED
@@ -111,7 +111,7 @@ def create_usage_chart(df):
111
  fig.update_layout(title_font_size=16, margin=dict(l=20, r=20, t=40, b=20))
112
  return fig
113
  except Exception as e:
114
- logging.error Hodgkin(f"Failed to create usage chart: {str(e)}")
115
  return create_placeholder_chart("Usage Hours per Device")
116
 
117
  # Create downtime chart
@@ -162,7 +162,8 @@ def create_daily_log_trends_chart(df):
162
  # Create weekly uptime chart
163
  def create_weekly_uptime_chart(df):
164
  try:
165
- if df.empty or "timestamp" not in df.columns or "usage_hours" Basic(f"Failed to create weekly uptime chart: {str(e)}")
 
166
  return create_placeholder_chart("Weekly Uptime Percentage")
167
  df['week'] = pd.to_datetime(df['timestamp'], errors='coerce').dt.isocalendar().week
168
  df['year'] = pd.to_datetime(df['timestamp'], errors='coerce').dt.year
@@ -314,20 +315,20 @@ def generate_pdf_content(summary, preview_df, anomalies, amc_reminders, insights
314
  return None
315
 
316
  # Main processing function
317
- async def process_logs(file_obj, lab_site_filter, equipment_type_filter, date_range, last_modified_state, cached_df_state, cached_filtered_df_state):
318
  start_time = time.time()
319
  try:
320
  if not file_obj:
321
- return "No file uploaded.", pd.DataFrame(), None, '<p>No device cards available.</p>', None, None, None, None, "No anomalies detected.", "No AMC reminders.", "No insights generated.", None, last_modified_state, cached_df_state, None
322
 
323
  file_path = file_obj.name
324
  current_modified_time = os.path.getmtime(file_path)
325
 
326
- # Load or use cached original dataframe
327
  if cached_df_state is None or current_modified_time != last_modified_state:
328
- logging.info(f"Processing file: {file_path}")
329
  if not file_path.endswith(".csv"):
330
- return "Please upload a CSV file.", pd.DataFrame(), None, '<p>No device cards available.</p>', None, None, None, None, "", "", "", None, last_modified_state, cached_df_state, None
331
 
332
  required_columns = ["device_id", "log_type", "status", "timestamp", "usage_hours", "downtime", "amc_date"]
333
  dtypes = {
@@ -341,57 +342,53 @@ async def process_logs(file_obj, lab_site_filter, equipment_type_filter, date_ra
341
  df = pd.read_csv(file_path, dtype=dtypes)
342
  missing_columns = [col for col in required_columns if col not in df.columns]
343
  if missing_columns:
344
- return f"Missing columns: {missing_columns}", pd.DataFrame(), None, '<p>No device cards available.</p>', None, None, None, None, None, None, None, None, last_modified_state, cached_df_state, None
345
 
346
  df["timestamp"] = pd.to_datetime(df["timestamp"], errors='coerce')
347
  df["amc_date"] = pd.to_datetime(df["amc_date"], errors='coerce')
348
  if df["timestamp"].dt.tz is None:
349
  df["timestamp"] = df["timestamp"].dt.tz_localize('UTC').dt.tz_convert('Asia/Kolkata')
350
  if df.empty:
351
- return "No data available.", pd.DataFrame(), None, '<p>No device cards available.</p>', None, None, None, None, None, None, None, None, last_modified_state, df, None
352
- cached_df_state = df
353
  else:
354
  df = cached_df_state
355
 
356
- # Always apply current filters to the original dataframe
357
  filtered_df = df.copy()
358
  if lab_site_filter and lab_site_filter != 'All' and 'lab_site' in filtered_df.columns:
359
  filtered_df = filtered_df[filtered_df['lab_site'] == lab_site_filter]
360
  if equipment_type_filter and equipment_type_filter != 'All' and 'equipment_type' in filtered_df.columns:
361
- filtered_df = filtered_df[filtered_df['equipmentYear'] == equipment_type_filter]
362
  if date_range and len(date_range) == 2:
363
  days_start, days_end = date_range
364
- today = pd.to_datetime(datetime.now().date()).tz_localize('Asia/Kolkata')
365
  start_date = today + pd.Timedelta(days=days_start)
366
  end_date = today + pd.Timedelta(days=days_end) + pd.Timedelta(days=1) - pd.Timedelta(seconds=1)
 
 
 
 
367
  filtered_df = filtered_df[(filtered_df['timestamp'] >= start_date) & (filtered_df['timestamp'] <= end_date)]
 
368
 
369
  if filtered_df.empty:
370
- return "No data after applying filters.", pd.DataFrame(), None, '<p>No device cards available.</p>', None, None, None, None, None, None, None, None, last_modified_state, cached_df_state, None
371
 
372
  # Generate table for preview
373
  preview_df = filtered_df[['device_id', 'log_type', 'status', 'timestamp', 'usage_hours', 'downtime', 'amc_date']].head(5)
374
  preview_html = preview_df.to_html(index=False, classes='table table-striped', border=0)
375
 
376
  # Run critical tasks concurrently
377
- try:
378
- with ThreadPoolExecutor(max_workers=2) as executor:
379
- future_anomalies = executor.submit(detect_anomalies, filtered_df)
380
- future_amc = executor.submit(check_amc_reminders, filtered_df, datetime.now())
381
-
382
- summary = f"Step 1: Summary Report\n{summarize_logs(filtered_df)}"
383
- anomalies, anomalies_df = future_anomalies.result()
384
- anomalies = f"Anomaly Detection\n{anomalies}"
385
- amc_reminders, reminders_df = future_amc.result()
386
- amc_reminders = f"AMC Reminders\n{amc_reminders}"
387
- insights = f"Dashboard Insights\n{generate_dashboard_insights(filtered_df)}"
388
- except Exception as e:
389
- logging.error(f"Concurrent task execution failed: {str(e)}")
390
- summary = "Failed to generate summary due to processing error."
391
- anomalies = "Anomaly detection failed due to processing error."
392
- amc_reminders = "AMC reminders failed due to processing error."
393
- insights = "Insights generation failed due to processing error."
394
- anomalies_df = pd.DataFrame()
395
 
396
  # Generate charts sequentially
397
  usage_chart = create_usage_chart(filtered_df)
@@ -406,10 +403,10 @@ async def process_logs(file_obj, lab_site_filter, equipment_type_filter, date_ra
406
  if elapsed_time > 3:
407
  logging.warning(f"Processing time exceeded 3 seconds: {elapsed_time:.2f} seconds")
408
 
409
- return (summary, preview_html, usage_chart, device_cards, daily_log_chart, weekly_uptime_chart, anomaly_alerts_chart, downtime_chart, anomalies, amc_reminders, insights, None, current_modified_time, cached_df_state, filtered_df)
410
  except Exception as e:
411
  logging.error(f"Failed to process file: {str(e)}")
412
- return f"Error: {str(e)}", pd.DataFrame(), None, '<p>Error processing data.</p>', None, None, None, None, None, None, None, None, last_modified_state, cached_df_state, None
413
 
414
  # Generate PDF separately
415
  async def generate_pdf(summary, preview_html, usage_chart, device_cards, daily_log_chart, weekly_uptime_chart, anomaly_alerts_chart, downtime_chart, anomalies, amc_reminders, insights):
@@ -428,13 +425,13 @@ def update_filters(file_obj, current_file_state):
428
  try:
429
  with open(file_obj.name, 'rb') as f:
430
  csv_content = f.read().decode('utf-8')
431
- df = pd.read_csv(io.StringIO(csv_content))
432
- df['timestamp'] = pd.to_datetime(df['timestamp'], errors='coerce')
433
 
434
- lab_site_options = ['All'] + [site for site in df['lab_site'].dropna().astype(str).unique().tolist() if site.strip()] if 'lab_site' in df.columns else ['All']
435
- equipment_type_options = ['All'] + [equip for equip in df['equipment_type'].dropna().astype(str).unique().tolist() if equip.strip()] if 'equipment_type' in df.columns else ['All']
436
 
437
- return gr.update(choices=lab_site_options, value='All'), gr.update(choices=equipment_type_options, value='All'), file_obj.name
438
  except Exception as e:
439
  logging.error(f"Failed to update filters: {str(e)}")
440
  return gr.update(choices=['All'], value='All'), gr.update(choices=['All'], value='All'), current_file_state
@@ -451,7 +448,7 @@ try:
451
  .dashboard-section ul {margin: 2px 0; padding-left: 20px;}
452
  .table {width: 100%; border-collapse: collapse;}
453
  .table th, .table td {border: 1px solid #ddd; padding: 8px; text-align: left;}
454
- .table th {background-color: #f2f2f2;}\
455
  .table tr:nth-child(even) {background-color: #f9f9f9;}
456
  """) as iface:
457
  gr.Markdown("<h1>LabOps Log Analyzer Dashboard</h1>")
@@ -460,7 +457,6 @@ try:
460
  last_modified_state = gr.State(value=None)
461
  current_file_state = gr.State(value=None)
462
  cached_df_state = gr.State(value=None)
463
- cached_filtered_df_state = gr.State(value=None)
464
 
465
  with gr.Row():
466
  with gr.Column(scale=1):
@@ -469,7 +465,7 @@ try:
469
  gr.Markdown("### Filters")
470
  lab_site_filter = gr.Dropdown(label="Lab Site", choices=['All'], value='All', interactive=True)
471
  equipment_type_filter = gr.Dropdown(label="Equipment Type", choices=['All'], value='All', interactive=True)
472
- date_range_filter = gr.Slider(label="Date Range (Days from Today)", minimum=-365, maximum=0, step=1, value=[-30, 0])
473
  submit_button = gr.Button("Analyze", variant="primary")
474
  pdf_button = gr.Button("Export PDF", variant="secondary")
475
 
@@ -519,8 +515,8 @@ try:
519
 
520
  submit_button.click(
521
  fn=process_logs,
522
- inputs=[file_input, lab_site_filter, equipment_type_filter, date_range_filter, last_modified_state, cached_df_state, cached_filtered_df_state],
523
- outputs=[summary_output, preview_output, usage_chart_output, device_cards_output, daily_log_trends_output, weekly_uptime_output, anomaly_alerts_output, downtime_chart_output, anomaly_output, amc_output, insights_output, pdf_output, last_modified_state, cached_df_state, cached_filtered_df_state]
524
  )
525
 
526
  pdf_button.click(
@@ -529,7 +525,7 @@ try:
529
  outputs=[pdf_output]
530
  )
531
 
532
- logging.info("Gradio interface initialized successfully")
533
  except Exception as e:
534
  logging.error(f"Failed to initialize Gradio interface: {str(e)}")
535
  raise e
 
111
  fig.update_layout(title_font_size=16, margin=dict(l=20, r=20, t=40, b=20))
112
  return fig
113
  except Exception as e:
114
+ logging.error(f"Failed to create usage chart: {str(e)}")
115
  return create_placeholder_chart("Usage Hours per Device")
116
 
117
  # Create downtime chart
 
162
  # Create weekly uptime chart
163
  def create_weekly_uptime_chart(df):
164
  try:
165
+ if df.empty or "timestamp" not in df.columns or "usage_hours" not in df.columns or "downtime" not in df.columns:
166
+ logging.warning("Insufficient data for weekly uptime chart")
167
  return create_placeholder_chart("Weekly Uptime Percentage")
168
  df['week'] = pd.to_datetime(df['timestamp'], errors='coerce').dt.isocalendar().week
169
  df['year'] = pd.to_datetime(df['timestamp'], errors='coerce').dt.year
 
315
  return None
316
 
317
  # Main processing function
318
+ async def process_logs(file_obj, lab_site_filter, equipment_type_filter, date_range, cached_df_state, last_modified_state):
319
  start_time = time.time()
320
  try:
321
  if not file_obj:
322
+ return "No file uploaded.", "<p>No data available.</p>", None, '<p>No device cards available.</p>', None, None, None, None, "No anomalies detected.", "No AMC reminders.", "No insights generated.", None, cached_df_state, last_modified_state
323
 
324
  file_path = file_obj.name
325
  current_modified_time = os.path.getmtime(file_path)
326
 
327
+ # Read file only if it's new or modified
328
  if cached_df_state is None or current_modified_time != last_modified_state:
329
+ logging.info(f"Processing new or modified file: {file_path}")
330
  if not file_path.endswith(".csv"):
331
+ return "Please upload a CSV file.", "<p>Invalid file format.</p>", None, '<p>No device cards available.</p>', None, None, None, None, "", "", "", None, cached_df_state, last_modified_state
332
 
333
  required_columns = ["device_id", "log_type", "status", "timestamp", "usage_hours", "downtime", "amc_date"]
334
  dtypes = {
 
342
  df = pd.read_csv(file_path, dtype=dtypes)
343
  missing_columns = [col for col in required_columns if col not in df.columns]
344
  if missing_columns:
345
+ return f"Missing columns: {missing_columns}", "<p>Missing required columns.</p>", None, '<p>No device cards available.</p>', None, None, None, None, "", "", "", None, cached_df_state, last_modified_state
346
 
347
  df["timestamp"] = pd.to_datetime(df["timestamp"], errors='coerce')
348
  df["amc_date"] = pd.to_datetime(df["amc_date"], errors='coerce')
349
  if df["timestamp"].dt.tz is None:
350
  df["timestamp"] = df["timestamp"].dt.tz_localize('UTC').dt.tz_convert('Asia/Kolkata')
351
  if df.empty:
352
+ return "No data available.", "<p>No data available.</p>", None, '<p>No device cards available.</p>', None, None, None, None, "", "", "", None, df, current_modified_time
 
353
  else:
354
  df = cached_df_state
355
 
356
+ # Apply filters
357
  filtered_df = df.copy()
358
  if lab_site_filter and lab_site_filter != 'All' and 'lab_site' in filtered_df.columns:
359
  filtered_df = filtered_df[filtered_df['lab_site'] == lab_site_filter]
360
  if equipment_type_filter and equipment_type_filter != 'All' and 'equipment_type' in filtered_df.columns:
361
+ filtered_df = filtered_df[filtered_df['equipment_type'] == equipment_type_filter]
362
  if date_range and len(date_range) == 2:
363
  days_start, days_end = date_range
364
+ today = pd.to_datetime(datetime.now()).tz_localize('Asia/Kolkata')
365
  start_date = today + pd.Timedelta(days=days_start)
366
  end_date = today + pd.Timedelta(days=days_end) + pd.Timedelta(days=1) - pd.Timedelta(seconds=1)
367
+ start_date = start_date.tz_convert('Asia/Kolkata') if start_date.tzinfo else start_date.tz_localize('Asia/Kolkata')
368
+ end_date = end_date.tz_convert('Asia/Kolkata') if end_date.tzinfo else end_date.tz_localize('Asia/Kolkata')
369
+ logging.info(f"Date range filter: start_date={start_date}, end_date={end_date}")
370
+ logging.info(f"Before date filter: {len(filtered_df)} rows")
371
  filtered_df = filtered_df[(filtered_df['timestamp'] >= start_date) & (filtered_df['timestamp'] <= end_date)]
372
+ logging.info(f"After date filter: {len(filtered_df)} rows")
373
 
374
  if filtered_df.empty:
375
+ return "No data after applying filters.", "<p>No data after filters.</p>", None, '<p>No device cards available.</p>', None, None, None, None, "", "", "", None, df, current_modified_time
376
 
377
  # Generate table for preview
378
  preview_df = filtered_df[['device_id', 'log_type', 'status', 'timestamp', 'usage_hours', 'downtime', 'amc_date']].head(5)
379
  preview_html = preview_df.to_html(index=False, classes='table table-striped', border=0)
380
 
381
  # Run critical tasks concurrently
382
+ with ThreadPoolExecutor(max_workers=2) as executor:
383
+ future_anomalies = executor.submit(detect_anomalies, filtered_df)
384
+ future_amc = executor.submit(check_amc_reminders, filtered_df, datetime.now())
385
+
386
+ summary = f"Step 1: Summary Report\n{summarize_logs(filtered_df)}"
387
+ anomalies, anomalies_df = future_anomalies.result()
388
+ anomalies = f"Anomaly Detection\n{anomalies}"
389
+ amc_reminders, reminders_df = future_amc.result()
390
+ amc_reminders = f"AMC Reminders\n{amc_reminders}"
391
+ insights = f"Dashboard Insights\n{generate_dashboard_insights(filtered_df)}"
 
 
 
 
 
 
 
 
392
 
393
  # Generate charts sequentially
394
  usage_chart = create_usage_chart(filtered_df)
 
403
  if elapsed_time > 3:
404
  logging.warning(f"Processing time exceeded 3 seconds: {elapsed_time:.2f} seconds")
405
 
406
+ return (summary, preview_html, usage_chart, device_cards, daily_log_chart, weekly_uptime_chart, anomaly_alerts_chart, downtime_chart, anomalies, amc_reminders, insights, None, df, current_modified_time)
407
  except Exception as e:
408
  logging.error(f"Failed to process file: {str(e)}")
409
+ return f"Error: {str(e)}", "<p>Error processing data.</p>", None, '<p>Error processing data.</p>', None, None, None, None, "", "", "", None, cached_df_state, last_modified_state
410
 
411
  # Generate PDF separately
412
  async def generate_pdf(summary, preview_html, usage_chart, device_cards, daily_log_chart, weekly_uptime_chart, anomaly_alerts_chart, downtime_chart, anomalies, amc_reminders, insights):
 
425
  try:
426
  with open(file_obj.name, 'rb') as f:
427
  csv_content = f.read().decode('utf-8')
428
+ df = pd.read_csv(io.StringIO(csv_content))
429
+ df['timestamp'] = pd.to_datetime(df['timestamp'], errors='coerce')
430
 
431
+ lab_site_options = ['All'] + [site for site in df['lab_site'].dropna().astype(str).unique().tolist() if site.strip()] if 'lab_site' in df.columns else ['All']
432
+ equipment_type_options = ['All'] + [equip for equip in df['equipment_type'].dropna().astype(str).unique().tolist() if equip.strip()] if 'equipment_type' in df.columns else ['All']
433
 
434
+ return gr.update(choices=lab_site_options, value='All'), gr.update(choices=equipment_type_options, value='All'), file_obj.name
435
  except Exception as e:
436
  logging.error(f"Failed to update filters: {str(e)}")
437
  return gr.update(choices=['All'], value='All'), gr.update(choices=['All'], value='All'), current_file_state
 
448
  .dashboard-section ul {margin: 2px 0; padding-left: 20px;}
449
  .table {width: 100%; border-collapse: collapse;}
450
  .table th, .table td {border: 1px solid #ddd; padding: 8px; text-align: left;}
451
+ .table th {background-color: #f2f2f2;}
452
  .table tr:nth-child(even) {background-color: #f9f9f9;}
453
  """) as iface:
454
  gr.Markdown("<h1>LabOps Log Analyzer Dashboard</h1>")
 
457
  last_modified_state = gr.State(value=None)
458
  current_file_state = gr.State(value=None)
459
  cached_df_state = gr.State(value=None)
 
460
 
461
  with gr.Row():
462
  with gr.Column(scale=1):
 
465
  gr.Markdown("### Filters")
466
  lab_site_filter = gr.Dropdown(label="Lab Site", choices=['All'], value='All', interactive=True)
467
  equipment_type_filter = gr.Dropdown(label="Equipment Type", choices=['All'], value='All', interactive=True)
468
+ date_range_filter = gr.Slider(label="Date Range (Days from Today, e.g., -7 to 0 means last 7 days)", minimum=-365, maximum=0, step=1, value=[-7, 0])
469
  submit_button = gr.Button("Analyze", variant="primary")
470
  pdf_button = gr.Button("Export PDF", variant="secondary")
471
 
 
515
 
516
  submit_button.click(
517
  fn=process_logs,
518
+ inputs=[file_input, lab_site_filter, equipment_type_filter, date_range_filter, cached_df_state, last_modified_state],
519
+ outputs=[summary_output, preview_output, usage_chart_output, device_cards_output, daily_log_trends_output, weekly_uptime_output, anomaly_alerts_output, downtime_chart_output, anomaly_output, amc_output, insights_output, pdf_output, cached_df_state, last_modified_state]
520
  )
521
 
522
  pdf_button.click(
 
525
  outputs=[pdf_output]
526
  )
527
 
528
+ logging.info("Gradio interface initialized successfully")
529
  except Exception as e:
530
  logging.error(f"Failed to initialize Gradio interface: {str(e)}")
531
  raise e