RathodHarish commited on
Commit
5007353
·
verified ·
1 Parent(s): 9dc56a1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +51 -17
app.py CHANGED
@@ -38,26 +38,41 @@ def upload_csv(file):
38
  debug_msg_local = debug_msg + "\nStarting CSV upload process...\n"
39
  try:
40
  if file is None:
41
- return ["All"], ["All"], ["All"], f"{debug_msg_local}No file uploaded. Please upload a CSV file.", "All", "All", "All", None, None, None, None
 
 
42
 
43
- # Read the CSV file
44
  debug_msg_local += "Reading CSV file...\n"
45
- df = pd.read_csv(file)
 
 
 
 
 
 
 
 
46
 
47
  if df.empty:
48
- return ["All"], ["All"], ["All"], f"{debug_msg_local}The uploaded CSV file is empty.", "All", "All", "All", None, None, None, None
 
 
49
 
50
- # Debug: Show the CSV content and column names
51
- debug_msg_local += f"CSV Columns: {', '.join(df.columns)}\nRaw CSV Content:\n{df.to_string()}\n\n"
52
 
53
  # Define required columns
54
  required_columns = {'DeviceID', 'Lab', 'Type', 'Timestamp', 'Status', 'UsageCount'}
55
  if not required_columns.issubset(df.columns):
56
  missing_cols = required_columns - set(df.columns)
57
- return ["All"], ["All"], ["All"], f"{debug_msg_local}Error: CSV is missing required columns: {', '.join(missing_cols)}", "All", "All", "All", None, None, None, None
 
 
58
 
59
- # Debug: Check data types and sample values
60
- debug_msg_local += f"Data Types:\n{df.dtypes}\n\nSample Values:\n{df.head().to_string()}\n\n"
 
61
 
62
  # Check for empty or all-NaN columns
63
  if df['Lab'].dropna().empty:
@@ -65,25 +80,31 @@ def upload_csv(file):
65
  if df['Type'].dropna().empty:
66
  debug_msg_local += "Error: Type column is empty or contains only NaN values.\n"
67
  if df['Lab'].dropna().empty or df['Type'].dropna().empty:
 
68
  return ["All"], ["All"], ["All"], debug_msg_local, "All", "All", "All", None, None, None, None
69
 
70
- # Convert Timestamp to datetime with error handling
71
  debug_msg_local += "Converting Timestamp column...\n"
72
  try:
73
- df['Timestamp'] = pd.to_datetime(df['Timestamp'], errors='coerce')
74
- debug_msg_local += f"Timestamps after conversion:\n{df['Timestamp'].to_string()}\n\n"
 
 
 
 
75
  timestamps_invalid = df['Timestamp'].isna().all()
76
  if timestamps_invalid:
77
  debug_msg_local += "Warning: All Timestamp values are invalid or unparseable. Date range filtering will be disabled.\n"
78
  except Exception as e:
79
  debug_msg_local += f"Error parsing Timestamp column: {str(e)}\n{traceback.format_exc()}\n"
 
80
  return ["All"], ["All"], ["All"], debug_msg_local, "All", "All", "All", None, None, None, None
81
 
82
  # Extract unique values for dropdowns
83
  debug_msg_local += "Extracting unique values for dropdowns...\n"
84
  labs = ['All'] + sorted([str(lab) for lab in df['Lab'].dropna().unique()])
85
  types = ['All'] + sorted([str(v) for v in df['Type'].dropna().unique()])
86
- debug_msg_local += f"Lab options: {', '.join(labs)}\nType options: {', '.join(types)}\n\n"
87
 
88
  # Extract date range for filter
89
  if timestamps_invalid:
@@ -110,9 +131,14 @@ def upload_csv(file):
110
  debug_msg_local += f"Initial Filter Error: {str(e)}\n{traceback.format_exc()}\n"
111
  device_cards, plot_daily, plot_uptime, anomaly_text = None, None, None, None
112
 
 
 
 
113
  return labs, types, date_ranges, debug_msg_local, "All", "All", "All", device_cards, plot_daily, plot_uptime, anomaly_text
114
  except Exception as e:
115
  debug_msg_local += f"Failed to process CSV: {str(e)}\n{traceback.format_exc()}\n"
 
 
116
  return ["All"], ["All"], ["All"], debug_msg_local, "All", "All", "All", None, None, None, None
117
 
118
  def filter_and_visualize(selected_lab, selected_type, selected_date_range):
@@ -120,7 +146,9 @@ def filter_and_visualize(selected_lab, selected_type, selected_date_range):
120
  error_msg = "Starting filter and visualize process...\n"
121
  try:
122
  if df.empty:
123
- return None, None, None, None, f"{error_msg}No data available."
 
 
124
 
125
  # Debug: Log the filter parameters
126
  error_msg += f"Applying filters: Lab={selected_lab}, Type={selected_type}, Date Range={selected_date_range}\n"
@@ -146,10 +174,12 @@ def filter_and_visualize(selected_lab, selected_type, selected_date_range):
146
  error_msg += f"Error parsing date range: {str(e)}\n{traceback.format_exc()}\n"
147
 
148
  if filtered_df.empty:
149
- return None, None, None, None, f"{error_msg}No data matches the selected filters."
 
 
150
 
151
- # Debug: Log the filtered DataFrame
152
- error_msg += f"Filtered DataFrame:\n{filtered_df.to_string()}\n"
153
 
154
  # Device Cards (as a table)
155
  device_cards = filtered_df[['DeviceID', 'Lab', 'Type', 'UsageCount', 'Timestamp']].sort_values(by='Timestamp', ascending=False)
@@ -260,6 +290,8 @@ def filter_and_visualize(selected_lab, selected_type, selected_date_range):
260
  error_msg += f"Error generating Anomaly Alerts: {str(e)}\n{traceback.format_exc()}\n"
261
  anomaly_text = "Error generating anomaly alerts."
262
 
 
 
263
  return device_cards, plot_daily, plot_uptime, anomaly_text, f"{error_msg}Filters applied successfully."
264
  except Exception as e:
265
  error_msg += f"Unexpected error in filter_and_visualize: {str(e)}\n{traceback.format_exc()}\n"
@@ -281,6 +313,8 @@ def filter_and_visualize(selected_lab, selected_type, selected_date_range):
281
  plt.close()
282
  plot_uptime.seek(0)
283
 
 
 
284
  return None, plot_daily, plot_uptime, "Error generating anomaly alerts.", error_msg
285
 
286
  def download_pdf(selected_lab, selected_type, selected_date_range):
 
38
  debug_msg_local = debug_msg + "\nStarting CSV upload process...\n"
39
  try:
40
  if file is None:
41
+ debug_msg_local += "No file uploaded. Please upload a CSV file.\n"
42
+ print(debug_msg_local) # Log to console for debugging
43
+ return ["All"], ["All"], ["All"], debug_msg_local, "All", "All", "All", None, None, None, None
44
 
45
+ # Read the CSV file with encoding handling
46
  debug_msg_local += "Reading CSV file...\n"
47
+ try:
48
+ df = pd.read_csv(file, encoding='utf-8')
49
+ except UnicodeDecodeError:
50
+ debug_msg_local += "Error: CSV file encoding is not UTF-8. Trying latin1 encoding...\n"
51
+ df = pd.read_csv(file, encoding='latin1')
52
+ except Exception as e:
53
+ debug_msg_local += f"Error reading CSV file: {str(e)}\n{traceback.format_exc()}\n"
54
+ print(debug_msg_local)
55
+ return ["All"], ["All"], ["All"], debug_msg_local, "All", "All", "All", None, None, None, None
56
 
57
  if df.empty:
58
+ debug_msg_local += "The uploaded CSV file is empty.\n"
59
+ print(debug_msg_local)
60
+ return ["All"], ["All"], ["All"], debug_msg_local, "All", "All", "All", None, None, None, None
61
 
62
+ # Debug: Show the CSV column names (limit verbosity)
63
+ debug_msg_local += f"CSV Columns: {', '.join(df.columns)}\n"
64
 
65
  # Define required columns
66
  required_columns = {'DeviceID', 'Lab', 'Type', 'Timestamp', 'Status', 'UsageCount'}
67
  if not required_columns.issubset(df.columns):
68
  missing_cols = required_columns - set(df.columns)
69
+ debug_msg_local += f"Error: CSV is missing required columns: {', '.join(missing_cols)}\n"
70
+ print(debug_msg_local)
71
+ return ["All"], ["All"], ["All"], debug_msg_local, "All", "All", "All", None, None, None, None
72
 
73
+ # Debug: Check data types and sample values (limit to 5 rows)
74
+ debug_msg_local += f"Data Types:\n{df.dtypes.to_string()}\n"
75
+ debug_msg_local += f"Sample Values (first 5 rows):\n{df.head(5).to_string()}\n"
76
 
77
  # Check for empty or all-NaN columns
78
  if df['Lab'].dropna().empty:
 
80
  if df['Type'].dropna().empty:
81
  debug_msg_local += "Error: Type column is empty or contains only NaN values.\n"
82
  if df['Lab'].dropna().empty or df['Type'].dropna().empty:
83
+ print(debug_msg_local)
84
  return ["All"], ["All"], ["All"], debug_msg_local, "All", "All", "All", None, None, None, None
85
 
86
+ # Convert Timestamp to datetime with a specific format and fallback
87
  debug_msg_local += "Converting Timestamp column...\n"
88
  try:
89
+ # Try parsing with a common format first
90
+ df['Timestamp'] = pd.to_datetime(df['Timestamp'], format='%Y-%m-%d %H:%M:%S', errors='coerce')
91
+ # If parsing fails for some rows, try without a specific format
92
+ if df['Timestamp'].isna().any():
93
+ debug_msg_local += "Some timestamps failed to parse with format '%Y-%m-%d %H:%M:%S'. Falling back to generic parsing...\n"
94
+ df['Timestamp'] = pd.to_datetime(df['Timestamp'], errors='coerce')
95
  timestamps_invalid = df['Timestamp'].isna().all()
96
  if timestamps_invalid:
97
  debug_msg_local += "Warning: All Timestamp values are invalid or unparseable. Date range filtering will be disabled.\n"
98
  except Exception as e:
99
  debug_msg_local += f"Error parsing Timestamp column: {str(e)}\n{traceback.format_exc()}\n"
100
+ print(debug_msg_local)
101
  return ["All"], ["All"], ["All"], debug_msg_local, "All", "All", "All", None, None, None, None
102
 
103
  # Extract unique values for dropdowns
104
  debug_msg_local += "Extracting unique values for dropdowns...\n"
105
  labs = ['All'] + sorted([str(lab) for lab in df['Lab'].dropna().unique()])
106
  types = ['All'] + sorted([str(v) for v in df['Type'].dropna().unique()])
107
+ debug_msg_local += f"Lab options: {', '.join(labs)}\nType options: {', '.join(types)}\n"
108
 
109
  # Extract date range for filter
110
  if timestamps_invalid:
 
131
  debug_msg_local += f"Initial Filter Error: {str(e)}\n{traceback.format_exc()}\n"
132
  device_cards, plot_daily, plot_uptime, anomaly_text = None, None, None, None
133
 
134
+ # Truncate debug message to prevent Gradio rendering issues
135
+ debug_msg_local = debug_msg_local[:5000] # Limit to 5000 characters
136
+ print(debug_msg_local)
137
  return labs, types, date_ranges, debug_msg_local, "All", "All", "All", device_cards, plot_daily, plot_uptime, anomaly_text
138
  except Exception as e:
139
  debug_msg_local += f"Failed to process CSV: {str(e)}\n{traceback.format_exc()}\n"
140
+ debug_msg_local = debug_msg_local[:5000] # Limit to 5000 characters
141
+ print(debug_msg_local)
142
  return ["All"], ["All"], ["All"], debug_msg_local, "All", "All", "All", None, None, None, None
143
 
144
  def filter_and_visualize(selected_lab, selected_type, selected_date_range):
 
146
  error_msg = "Starting filter and visualize process...\n"
147
  try:
148
  if df.empty:
149
+ error_msg += "No data available.\n"
150
+ print(error_msg)
151
+ return None, None, None, None, error_msg
152
 
153
  # Debug: Log the filter parameters
154
  error_msg += f"Applying filters: Lab={selected_lab}, Type={selected_type}, Date Range={selected_date_range}\n"
 
174
  error_msg += f"Error parsing date range: {str(e)}\n{traceback.format_exc()}\n"
175
 
176
  if filtered_df.empty:
177
+ error_msg += "No data matches the selected filters.\n"
178
+ print(error_msg)
179
+ return None, None, None, None, error_msg
180
 
181
+ # Debug: Log the filtered DataFrame (limit verbosity)
182
+ error_msg += f"Filtered DataFrame (first 5 rows):\n{filtered_df.head(5).to_string()}\n"
183
 
184
  # Device Cards (as a table)
185
  device_cards = filtered_df[['DeviceID', 'Lab', 'Type', 'UsageCount', 'Timestamp']].sort_values(by='Timestamp', ascending=False)
 
290
  error_msg += f"Error generating Anomaly Alerts: {str(e)}\n{traceback.format_exc()}\n"
291
  anomaly_text = "Error generating anomaly alerts."
292
 
293
+ error_msg = error_msg[:5000] # Limit to 5000 characters
294
+ print(error_msg)
295
  return device_cards, plot_daily, plot_uptime, anomaly_text, f"{error_msg}Filters applied successfully."
296
  except Exception as e:
297
  error_msg += f"Unexpected error in filter_and_visualize: {str(e)}\n{traceback.format_exc()}\n"
 
313
  plt.close()
314
  plot_uptime.seek(0)
315
 
316
+ error_msg = error_msg[:5000] # Limit to 5000 characters
317
+ print(error_msg)
318
  return None, plot_daily, plot_uptime, "Error generating anomaly alerts.", error_msg
319
 
320
  def download_pdf(selected_lab, selected_type, selected_date_range):