RathodHarish commited on
Commit
b8aab66
·
verified ·
1 Parent(s): 7116f2e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +50 -50
app.py CHANGED
@@ -5,7 +5,7 @@ import logging
5
  import plotly.express as px
6
  import plotly.graph_objects as go
7
  from sklearn.ensemble import IsolationForest
8
- from concurrent.futures import ThreadPoolExecutor # Added missing import
9
  import os
10
  import io
11
  import time
@@ -314,61 +314,61 @@ def generate_pdf_content(summary, preview_df, anomalies, amc_reminders, insights
314
  logging.error(f"Failed to generate PDF: {str(e)}")
315
  return None
316
 
317
- # Main processing function
318
  async def process_logs(file_obj, lab_site_filter, equipment_type_filter, date_range, last_modified_state, cached_df_state, cached_filtered_df_state):
319
  start_time = time.time()
320
  try:
321
  if not file_obj:
322
- 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, cached_filtered_df_state
323
 
324
  file_path = file_obj.name
325
  current_modified_time = os.path.getmtime(file_path)
326
- if last_modified_state and current_modified_time == last_modified_state and cached_filtered_df_state is not None:
327
- filtered_df = cached_filtered_df_state
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
328
  else:
329
- if cached_df_state is None or current_modified_time != last_modified_state:
330
- logging.info(f"Processing file: {file_path}")
331
- if not file_path.endswith(".csv"):
332
- 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, cached_filtered_df_state
333
-
334
- required_columns = ["device_id", "log_type", "status", "timestamp", "usage_hours", "downtime", "amc_date"]
335
- dtypes = {
336
- "device_id": "string",
337
- "log_type": "string",
338
- "status": "string",
339
- "usage_hours": "float32",
340
- "downtime": "float32",
341
- "amc_date": "string"
342
- }
343
- df = pd.read_csv(file_path, dtype=dtypes)
344
- missing_columns = [col for col in required_columns if col not in df.columns]
345
- if missing_columns:
346
- 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, cached_filtered_df_state
347
-
348
- df["timestamp"] = pd.to_datetime(df["timestamp"], errors='coerce')
349
- df["amc_date"] = pd.to_datetime(df["amc_date"], errors='coerce')
350
- if df["timestamp"].dt.tz is None:
351
- df["timestamp"] = df["timestamp"].dt.tz_localize('UTC').dt.tz_convert('Asia/Kolkata')
352
- if df.empty:
353
- 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, cached_filtered_df_state
354
- else:
355
- df = cached_df_state
356
-
357
- # Apply filters
358
- filtered_df = df.copy()
359
- if lab_site_filter and lab_site_filter != 'All' and 'lab_site' in filtered_df.columns:
360
- filtered_df = filtered_df[filtered_df['lab_site'] == lab_site_filter]
361
- if equipment_type_filter and equipment_type_filter != 'All' and 'equipment_type' in filtered_df.columns:
362
- filtered_df = filtered_df[filtered_df['equipment_type'] == equipment_type_filter]
363
- if date_range and len(date_range) == 2:
364
- days_start, days_end = date_range
365
- today = pd.to_datetime(datetime.now().date()).tz_localize('Asia/Kolkata')
366
- start_date = today + pd.Timedelta(days=days_start)
367
- end_date = today + pd.Timedelta(days=days_end) + pd.Timedelta(days=1) - pd.Timedelta(seconds=1)
368
- filtered_df = filtered_df[(filtered_df['timestamp'] >= start_date) & (filtered_df['timestamp'] <= end_date)]
369
-
370
- if filtered_df.empty:
371
- 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, df, filtered_df
372
 
373
  # Generate table for preview
374
  preview_df = filtered_df[['device_id', 'log_type', 'status', 'timestamp', 'usage_hours', 'downtime', 'amc_date']].head(5)
@@ -407,10 +407,10 @@ async def process_logs(file_obj, lab_site_filter, equipment_type_filter, date_ra
407
  if elapsed_time > 3:
408
  logging.warning(f"Processing time exceeded 3 seconds: {elapsed_time:.2f} seconds")
409
 
410
- 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, df, filtered_df)
411
  except Exception as e:
412
  logging.error(f"Failed to process file: {str(e)}")
413
- 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, cached_filtered_df_state
414
 
415
  # Generate PDF separately
416
  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):
 
5
  import plotly.express as px
6
  import plotly.graph_objects as go
7
  from sklearn.ensemble import IsolationForest
8
+ from concurrent.futures import ThreadPoolExecutor
9
  import os
10
  import io
11
  import time
 
314
  logging.error(f"Failed to generate PDF: {str(e)}")
315
  return None
316
 
317
+ # Main processing function (Updated)
318
  async def process_logs(file_obj, lab_site_filter, equipment_type_filter, date_range, last_modified_state, cached_df_state, cached_filtered_df_state):
319
  start_time = time.time()
320
  try:
321
  if not file_obj:
322
+ 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
323
 
324
  file_path = file_obj.name
325
  current_modified_time = os.path.getmtime(file_path)
326
+
327
+ # Load or use cached original dataframe
328
+ if cached_df_state is None or current_modified_time != last_modified_state:
329
+ logging.info(f"Processing file: {file_path}")
330
+ if not file_path.endswith(".csv"):
331
+ 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
332
+
333
+ required_columns = ["device_id", "log_type", "status", "timestamp", "usage_hours", "downtime", "amc_date"]
334
+ dtypes = {
335
+ "device_id": "string",
336
+ "log_type": "string",
337
+ "status": "string",
338
+ "usage_hours": "float32",
339
+ "downtime": "float32",
340
+ "amc_date": "string"
341
+ }
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}", pd.DataFrame(), None, '<p>No device cards available.</p>', None, None, None, None, None, None, None, None, last_modified_state, cached_df_state, None
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.", pd.DataFrame(), None, '<p>No device cards available.</p>', None, None, None, None, None, None, None, None, last_modified_state, df, None
353
+ cached_df_state = df
354
  else:
355
+ df = cached_df_state
356
+
357
+ # Always apply current filters to the original dataframe
358
+ filtered_df = df.copy()
359
+ if lab_site_filter and lab_site_filter != 'All' and 'lab_site' in filtered_df.columns:
360
+ filtered_df = filtered_df[filtered_df['lab_site'] == lab_site_filter]
361
+ if equipment_type_filter and equipment_type_filter != 'All' and 'equipment_type' in filtered_df.columns:
362
+ filtered_df = filtered_df[filtered_df['equipment_type'] == equipment_type_filter]
363
+ if date_range and len(date_range) == 2:
364
+ days_start, days_end = date_range
365
+ today = pd.to_datetime(datetime.now().date()).tz_localize('Asia/Kolkata')
366
+ start_date = today + pd.Timedelta(days=days_start)
367
+ end_date = today + pd.Timedelta(days=days_end) + pd.Timedelta(days=1) - pd.Timedelta(seconds=1)
368
+ filtered_df = filtered_df[(filtered_df['timestamp'] >= start_date) & (filtered_df['timestamp'] <= end_date)]
369
+
370
+ if filtered_df.empty:
371
+ 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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
372
 
373
  # Generate table for preview
374
  preview_df = filtered_df[['device_id', 'log_type', 'status', 'timestamp', 'usage_hours', 'downtime', 'amc_date']].head(5)
 
407
  if elapsed_time > 3:
408
  logging.warning(f"Processing time exceeded 3 seconds: {elapsed_time:.2f} seconds")
409
 
410
+ 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)
411
  except Exception as e:
412
  logging.error(f"Failed to process file: {str(e)}")
413
+ 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
414
 
415
  # Generate PDF separately
416
  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):