Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -45,7 +45,6 @@ except ImportError:
|
|
| 45 |
logging.info("Preloading Hugging Face model...")
|
| 46 |
try:
|
| 47 |
device = 0 if torch.cuda.is_available() else -1
|
| 48 |
-
# Use a smaller model for faster inference
|
| 49 |
summarizer = pipeline(
|
| 50 |
"summarization",
|
| 51 |
model="t5-small",
|
|
@@ -159,6 +158,7 @@ def create_salesforce_reports(df):
|
|
| 159 |
# Save to Salesforce
|
| 160 |
def save_to_salesforce(df, reminders_df):
|
| 161 |
if sf is None:
|
|
|
|
| 162 |
return
|
| 163 |
try:
|
| 164 |
current_date = datetime.now()
|
|
@@ -167,40 +167,61 @@ def save_to_salesforce(df, reminders_df):
|
|
| 167 |
reminder_device_ids = set(reminders_df['device_id']) if not reminders_df.empty else set()
|
| 168 |
|
| 169 |
for _, row in df.iterrows():
|
| 170 |
-
status = str(row['status'])
|
| 171 |
-
log_type = str(row['log_type'])
|
| 172 |
-
status = picklist_mapping['Status__c'].get(status.lower(), status_values[0] if status_values else None)
|
| 173 |
-
log_type = picklist_mapping['Log_Type__c'].get(log_type.lower(), log_type_values[0] if log_type_values else None)
|
| 174 |
-
if status is None or log_type is None:
|
| 175 |
-
continue
|
| 176 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 177 |
amc_date_str = None
|
| 178 |
if pd.notna(row['amc_date']):
|
| 179 |
try:
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
if
|
| 183 |
-
logging.info(f"AMC Reminder for Device ID {row['device_id']}")
|
| 184 |
-
except:
|
|
|
|
| 185 |
amc_date_str = None
|
| 186 |
|
|
|
|
| 187 |
record = {
|
| 188 |
'Device_Id__c': str(row['device_id'])[:50],
|
| 189 |
-
'Log_Type__c':
|
| 190 |
-
'Status__c':
|
| 191 |
'Timestamp__c': row['timestamp'].isoformat() if pd.notna(row['timestamp']) else None,
|
| 192 |
'Usage_Hours__c': float(row['usage_hours']) if pd.notna(row['usage_hours']) else 0.0,
|
| 193 |
'Downtime__c': float(row['downtime']) if pd.notna(row['downtime']) else 0.0,
|
| 194 |
'AMC_Date__c': amc_date_str
|
| 195 |
}
|
|
|
|
|
|
|
| 196 |
if row['device_id'] not in reminder_device_ids:
|
| 197 |
records.append(record)
|
| 198 |
|
| 199 |
if records:
|
| 200 |
-
|
| 201 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 202 |
except Exception as e:
|
| 203 |
logging.error(f"Failed to save to Salesforce: {str(e)}")
|
|
|
|
| 204 |
|
| 205 |
# Summarize logs
|
| 206 |
def summarize_logs(df):
|
|
@@ -564,7 +585,6 @@ async def process_logs(file_obj, lab_site_filter, equipment_type_filter, date_ra
|
|
| 564 |
future_downtime_chart = executor.submit(create_downtime_chart, filtered_df)
|
| 565 |
future_daily_log_chart = executor.submit(create_daily_log_trends_chart, filtered_df)
|
| 566 |
future_weekly_uptime_chart = executor.submit(create_weekly_uptime_chart, filtered_df)
|
| 567 |
-
future_anomaly_alerts_chart = executor.submit(create_anomaly_alerts_chart, pd.DataFrame())
|
| 568 |
future_device_cards = executor.submit(generate_device_cards, filtered_df)
|
| 569 |
future_reports = executor.submit(create_salesforce_reports, filtered_df)
|
| 570 |
|
|
@@ -578,7 +598,7 @@ async def process_logs(file_obj, lab_site_filter, equipment_type_filter, date_ra
|
|
| 578 |
downtime_chart = future_downtime_chart.result()
|
| 579 |
daily_log_chart = future_daily_log_chart.result()
|
| 580 |
weekly_uptime_chart = future_weekly_uptime_chart.result()
|
| 581 |
-
anomaly_alerts_chart =
|
| 582 |
device_cards = future_device_cards.result()
|
| 583 |
|
| 584 |
save_to_salesforce(filtered_df, reminders_df)
|
|
|
|
| 45 |
logging.info("Preloading Hugging Face model...")
|
| 46 |
try:
|
| 47 |
device = 0 if torch.cuda.is_available() else -1
|
|
|
|
| 48 |
summarizer = pipeline(
|
| 49 |
"summarization",
|
| 50 |
model="t5-small",
|
|
|
|
| 158 |
# Save to Salesforce
|
| 159 |
def save_to_salesforce(df, reminders_df):
|
| 160 |
if sf is None:
|
| 161 |
+
logging.error("Salesforce connection not established, cannot save records.")
|
| 162 |
return
|
| 163 |
try:
|
| 164 |
current_date = datetime.now()
|
|
|
|
| 167 |
reminder_device_ids = set(reminders_df['device_id']) if not reminders_df.empty else set()
|
| 168 |
|
| 169 |
for _, row in df.iterrows():
|
| 170 |
+
status = str(row['status']).strip().lower()
|
| 171 |
+
log_type = str(row['log_type']).strip().lower()
|
|
|
|
|
|
|
|
|
|
|
|
|
| 172 |
|
| 173 |
+
# Map status and log_type to valid picklist values
|
| 174 |
+
status_mapped = picklist_mapping['Status__c'].get(status, None)
|
| 175 |
+
if status_mapped is None:
|
| 176 |
+
status_mapped = status_values[0] if status_values else 'Active'
|
| 177 |
+
logging.warning(f"Invalid status '{status}' for device {row['device_id']}, defaulting to {status_mapped}")
|
| 178 |
+
|
| 179 |
+
log_type_mapped = picklist_mapping['Log_Type__c'].get(log_type, None)
|
| 180 |
+
if log_type_mapped is None:
|
| 181 |
+
log_type_mapped = log_type_values[0] if log_type_values else 'Smart Log'
|
| 182 |
+
logging.warning(f"Invalid log_type '{log_type}' for device {row['device_id']}, defaulting to {log_type_mapped}")
|
| 183 |
+
|
| 184 |
+
# Handle AMC date
|
| 185 |
amc_date_str = None
|
| 186 |
if pd.notna(row['amc_date']):
|
| 187 |
try:
|
| 188 |
+
amc_date_dt = pd.to_datetime(row['amc_date'])
|
| 189 |
+
amc_date_str = amc_date_dt.strftime('%Y-%m-%d')
|
| 190 |
+
if status_mapped == "Active" and current_date.date() <= amc_date_dt.date() <= next_30_days.date():
|
| 191 |
+
logging.info(f"AMC Reminder for Device ID {row['device_id']} on {amc_date_str}")
|
| 192 |
+
except Exception as e:
|
| 193 |
+
logging.warning(f"Invalid AMC date for device {row['device_id']}: {str(e)}")
|
| 194 |
amc_date_str = None
|
| 195 |
|
| 196 |
+
# Prepare record
|
| 197 |
record = {
|
| 198 |
'Device_Id__c': str(row['device_id'])[:50],
|
| 199 |
+
'Log_Type__c': log_type_mapped,
|
| 200 |
+
'Status__c': status_mapped,
|
| 201 |
'Timestamp__c': row['timestamp'].isoformat() if pd.notna(row['timestamp']) else None,
|
| 202 |
'Usage_Hours__c': float(row['usage_hours']) if pd.notna(row['usage_hours']) else 0.0,
|
| 203 |
'Downtime__c': float(row['downtime']) if pd.notna(row['downtime']) else 0.0,
|
| 204 |
'AMC_Date__c': amc_date_str
|
| 205 |
}
|
| 206 |
+
|
| 207 |
+
# Skip records already in reminders to avoid duplicates
|
| 208 |
if row['device_id'] not in reminder_device_ids:
|
| 209 |
records.append(record)
|
| 210 |
|
| 211 |
if records:
|
| 212 |
+
# Perform bulk insert and handle results
|
| 213 |
+
result = sf.bulk.SmartLog__c.insert(records)
|
| 214 |
+
success_count = sum(1 for r in result if r['success'])
|
| 215 |
+
error_count = len(result) - success_count
|
| 216 |
+
logging.info(f"Saved {success_count} records to Salesforce, {error_count} failed")
|
| 217 |
+
for r in result:
|
| 218 |
+
if not r['success']:
|
| 219 |
+
logging.error(f"Failed to save record: {r['errors']}")
|
| 220 |
+
else:
|
| 221 |
+
logging.info("No records to save to Salesforce")
|
| 222 |
except Exception as e:
|
| 223 |
logging.error(f"Failed to save to Salesforce: {str(e)}")
|
| 224 |
+
raise
|
| 225 |
|
| 226 |
# Summarize logs
|
| 227 |
def summarize_logs(df):
|
|
|
|
| 585 |
future_downtime_chart = executor.submit(create_downtime_chart, filtered_df)
|
| 586 |
future_daily_log_chart = executor.submit(create_daily_log_trends_chart, filtered_df)
|
| 587 |
future_weekly_uptime_chart = executor.submit(create_weekly_uptime_chart, filtered_df)
|
|
|
|
| 588 |
future_device_cards = executor.submit(generate_device_cards, filtered_df)
|
| 589 |
future_reports = executor.submit(create_salesforce_reports, filtered_df)
|
| 590 |
|
|
|
|
| 598 |
downtime_chart = future_downtime_chart.result()
|
| 599 |
daily_log_chart = future_daily_log_chart.result()
|
| 600 |
weekly_uptime_chart = future_weekly_uptime_chart.result()
|
| 601 |
+
anomaly_alerts_chart = create_anomaly_alerts_chart(anomalies_df) # Use anomalies_df directly
|
| 602 |
device_cards = future_device_cards.result()
|
| 603 |
|
| 604 |
save_to_salesforce(filtered_df, reminders_df)
|