RathodHarish commited on
Commit
2470f7b
·
verified ·
1 Parent(s): cb666ca

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +25 -14
app.py CHANGED
@@ -12,13 +12,13 @@ def upload_csv(file):
12
  global df
13
  try:
14
  if file is None:
15
- return ["All"], ["All"], ["All"], "No file uploaded. Please upload a CSV file.", "All", "All", "All"
16
 
17
  # Read the CSV file
18
  df = pd.read_csv(file)
19
 
20
  if df.empty:
21
- return ["All"], ["All"], ["All"], "The uploaded CSV file is empty.", "All", "All", "All"
22
 
23
  # Debug: Show the CSV content and column names
24
  csv_info = f"CSV Columns: {', '.join(df.columns)}\nRaw CSV Content:\n{df.to_string()}"
@@ -27,19 +27,19 @@ def upload_csv(file):
27
  required_columns = {'DeviceID', 'Lab', 'Type', 'Timestamp', 'Status', 'UsageCount'}
28
  if not required_columns.issubset(df.columns):
29
  missing_cols = required_columns - set(df.columns)
30
- return ["All"], ["All"], ["All"], f"{csv_info}\n\nError: CSV is missing required columns: {', '.join(missing_cols)}", "All", "All", "All"
31
 
32
  # Check for empty or all-NaN columns
33
  if df['Lab'].dropna().empty or df['Type'].dropna().empty:
34
- return ["All"], ["All"], ["All"], f"{csv_info}\n\nError: Lab or Type columns are empty or contain only NaN values.", "All", "All", "All"
35
 
36
  # Convert Timestamp to datetime with error handling
37
  try:
38
  df['Timestamp'] = pd.to_datetime(df['Timestamp'], errors='coerce')
39
  if df['Timestamp'].isna().all():
40
- return ["All"], ["All"], ["All"], f"{csv_info}\n\nError: All Timestamp values are invalid or unparseable.", "All", "All", "All"
41
  except Exception as e:
42
- return ["All"], ["All"], ["All"], f"{csv_info}\n\nError: Failed to parse Timestamp column: {str(e)}", "All", "All", "All"
43
 
44
  # Extract unique values for dropdowns
45
  labs = ['All'] + sorted([str(lab) for lab in df['Lab'].fillna('Unknown').unique()])
@@ -50,15 +50,21 @@ def upload_csv(file):
50
  max_date = df['Timestamp'].max().strftime('%Y-%m-%d')
51
  date_ranges = ['All', f"{min_date} to {max_date}"]
52
 
53
- return labs, types, date_ranges, "CSV loaded successfully.", "All", "All", "All"
 
 
 
54
  except Exception as e:
55
- return ["All"], ["All"], ["All"], f"Failed to load CSV: {str(e)}", "All", "All", "All"
56
 
57
  def filter_and_visualize(selected_lab, selected_type, selected_date_range):
58
  global df
59
  if df.empty:
60
  return None, None, None, None, "No data available."
61
 
 
 
 
62
  # Filter the DataFrame
63
  filtered_df = df.copy()
64
  if selected_lab != "All":
@@ -72,7 +78,10 @@ def filter_and_visualize(selected_lab, selected_type, selected_date_range):
72
  filtered_df = filtered_df[(filtered_df["Timestamp"] >= start_date) & (filtered_df["Timestamp"] < end_date)]
73
 
74
  if filtered_df.empty:
75
- return None, None, None, None, "No data matches the selected filters."
 
 
 
76
 
77
  # Device Cards (as a table)
78
  device_cards = filtered_df[['DeviceID', 'Lab', 'Type', 'UsageCount', 'Timestamp']].sort_values(by='Timestamp', ascending=False)
@@ -113,7 +122,7 @@ def filter_and_visualize(selected_lab, selected_type, selected_date_range):
113
  else:
114
  anomaly_text = "Anomalies Detected:\n" + anomalies[['DeviceID', 'Lab', 'Type', 'Status', 'UsageCount']].to_string(index=False)
115
 
116
- return device_cards, buf1, buf2, anomaly_text, "Filters applied successfully."
117
 
118
  def download_pdf(selected_lab, selected_type, selected_date_range):
119
  global df
@@ -162,7 +171,7 @@ with gr.Blocks() as demo:
162
  date_dropdown = gr.Dropdown(label="Filter by Date Range", choices=["All"], value="All")
163
 
164
  with gr.Row():
165
- submit_btn = gr.Button("Submit") # Added Submit button
166
 
167
  with gr.Row():
168
  device_table = gr.DataFrame(label="Device Cards (Usage, Last Log)")
@@ -170,17 +179,19 @@ with gr.Blocks() as demo:
170
  plot_uptime = gr.Image(label="Weekly Uptime %")
171
 
172
  anomaly_output = gr.Textbox(label="Anomaly Alerts")
173
- download_btn = gr.Button("Download PDF Report")
 
 
 
174
  error_box = gr.Textbox(label="Status/Error Message", visible=True, interactive=False)
175
 
176
  # Connect the components
177
  csv_input.change(
178
  fn=upload_csv,
179
  inputs=csv_input,
180
- outputs=[lab_dropdown, type_dropdown, date_dropdown, error_box, lab_dropdown, type_dropdown, date_dropdown]
181
  )
182
 
183
- # Bind filter_and_visualize to the Submit button
184
  submit_btn.click(
185
  fn=filter_and_visualize,
186
  inputs=[lab_dropdown, type_dropdown, date_dropdown],
 
12
  global df
13
  try:
14
  if file is None:
15
+ return ["All"], ["All"], ["All"], "No file uploaded. Please upload a CSV file.", "All", "All", "All", None, None, None, None
16
 
17
  # Read the CSV file
18
  df = pd.read_csv(file)
19
 
20
  if df.empty:
21
+ return ["All"], ["All"], ["All"], "The uploaded CSV file is empty.", "All", "All", "All", None, None, None, None
22
 
23
  # Debug: Show the CSV content and column names
24
  csv_info = f"CSV Columns: {', '.join(df.columns)}\nRaw CSV Content:\n{df.to_string()}"
 
27
  required_columns = {'DeviceID', 'Lab', 'Type', 'Timestamp', 'Status', 'UsageCount'}
28
  if not required_columns.issubset(df.columns):
29
  missing_cols = required_columns - set(df.columns)
30
+ return ["All"], ["All"], ["All"], f"{csv_info}\n\nError: CSV is missing required columns: {', '.join(missing_cols)}", "All", "All", "All", None, None, None, None
31
 
32
  # Check for empty or all-NaN columns
33
  if df['Lab'].dropna().empty or df['Type'].dropna().empty:
34
+ return ["All"], ["All"], ["All"], f"{csv_info}\n\nError: Lab or Type columns are empty or contain only NaN values.", "All", "All", "All", None, None, None, None
35
 
36
  # Convert Timestamp to datetime with error handling
37
  try:
38
  df['Timestamp'] = pd.to_datetime(df['Timestamp'], errors='coerce')
39
  if df['Timestamp'].isna().all():
40
+ return ["All"], ["All"], ["All"], f"{csv_info}\n\nError: All Timestamp values are invalid or unparseable.", "All", "All", "All", None, None, None, None
41
  except Exception as e:
42
+ return ["All"], ["All"], ["All"], f"{csv_info}\n\nError: Failed to parse Timestamp column: {str(e)}", "All", "All", "All", None, None, None, None
43
 
44
  # Extract unique values for dropdowns
45
  labs = ['All'] + sorted([str(lab) for lab in df['Lab'].fillna('Unknown').unique()])
 
50
  max_date = df['Timestamp'].max().strftime('%Y-%m-%d')
51
  date_ranges = ['All', f"{min_date} to {max_date}"]
52
 
53
+ # Automatically trigger filter_and_visualize after upload with default filters
54
+ device_cards, plot_daily, plot_uptime, anomaly_text = filter_and_visualize("All", "All", "All")[:4]
55
+
56
+ return labs, types, date_ranges, "CSV loaded successfully.", "All", "All", "All", device_cards, plot_daily, plot_uptime, anomaly_text
57
  except Exception as e:
58
+ return ["All"], ["All"], ["All"], f"Failed to load CSV: {str(e)}", "All", "All", "All", None, None, None, None
59
 
60
  def filter_and_visualize(selected_lab, selected_type, selected_date_range):
61
  global df
62
  if df.empty:
63
  return None, None, None, None, "No data available."
64
 
65
+ # Debug: Log the filter parameters
66
+ error_msg = f"Applying filters: Lab={selected_lab}, Type={selected_type}, Date Range={selected_date_range}"
67
+
68
  # Filter the DataFrame
69
  filtered_df = df.copy()
70
  if selected_lab != "All":
 
78
  filtered_df = filtered_df[(filtered_df["Timestamp"] >= start_date) & (filtered_df["Timestamp"] < end_date)]
79
 
80
  if filtered_df.empty:
81
+ return None, None, None, None, f"{error_msg}\nNo data matches the selected filters."
82
+
83
+ # Debug: Log the filtered DataFrame
84
+ error_msg += f"\nFiltered DataFrame:\n{filtered_df.to_string()}"
85
 
86
  # Device Cards (as a table)
87
  device_cards = filtered_df[['DeviceID', 'Lab', 'Type', 'UsageCount', 'Timestamp']].sort_values(by='Timestamp', ascending=False)
 
122
  else:
123
  anomaly_text = "Anomalies Detected:\n" + anomalies[['DeviceID', 'Lab', 'Type', 'Status', 'UsageCount']].to_string(index=False)
124
 
125
+ return device_cards, buf1, buf2, anomaly_text, f"{error_msg}\nFilters applied successfully."
126
 
127
  def download_pdf(selected_lab, selected_type, selected_date_range):
128
  global df
 
171
  date_dropdown = gr.Dropdown(label="Filter by Date Range", choices=["All"], value="All")
172
 
173
  with gr.Row():
174
+ submit_btn = gr.Button("Submit Filters") # Renamed for clarity
175
 
176
  with gr.Row():
177
  device_table = gr.DataFrame(label="Device Cards (Usage, Last Log)")
 
179
  plot_uptime = gr.Image(label="Weekly Uptime %")
180
 
181
  anomaly_output = gr.Textbox(label="Anomaly Alerts")
182
+
183
+ with gr.Row():
184
+ download_btn = gr.Button("Download PDF Report")
185
+
186
  error_box = gr.Textbox(label="Status/Error Message", visible=True, interactive=False)
187
 
188
  # Connect the components
189
  csv_input.change(
190
  fn=upload_csv,
191
  inputs=csv_input,
192
+ outputs=[lab_dropdown, type_dropdown, date_dropdown, error_box, lab_dropdown, type_dropdown, date_dropdown, device_table, plot_daily, plot_uptime, anomaly_output]
193
  )
194
 
 
195
  submit_btn.click(
196
  fn=filter_and_visualize,
197
  inputs=[lab_dropdown, type_dropdown, date_dropdown],