Update app.py
Browse files
app.py
CHANGED
@@ -6,35 +6,54 @@ from simple_salesforce import Salesforce
|
|
6 |
from transformers import pipeline
|
7 |
from utils import fetch_salesforce_data, detect_anomalies, generate_pdf_report
|
8 |
import os
|
|
|
|
|
|
|
|
|
|
|
9 |
|
10 |
# Streamlit app configuration
|
11 |
-
|
|
|
|
|
|
|
|
|
|
|
12 |
|
13 |
# Cache Salesforce connection
|
14 |
@st.cache_resource
|
15 |
def init_salesforce():
|
|
|
16 |
try:
|
17 |
-
|
18 |
username=os.getenv("SF_USERNAME", st.secrets.get("sf_username")),
|
19 |
password=os.getenv("SF_PASSWORD", st.secrets.get("sf_password")),
|
20 |
security_token=os.getenv("SF_SECURITY_TOKEN", st.secrets.get("sf_security_token"))
|
21 |
)
|
|
|
|
|
22 |
except Exception as e:
|
23 |
-
|
|
|
24 |
return None
|
25 |
|
26 |
# Cache Hugging Face model
|
27 |
@st.cache_resource
|
28 |
def init_anomaly_detector():
|
|
|
29 |
try:
|
30 |
-
|
|
|
31 |
"text-classification",
|
32 |
-
model="
|
33 |
-
tokenizer="
|
34 |
clean_up_tokenization_spaces=True
|
35 |
)
|
|
|
|
|
36 |
except Exception as e:
|
37 |
-
|
|
|
38 |
return None
|
39 |
|
40 |
# Initialize connections
|
@@ -42,24 +61,33 @@ sf = init_salesforce()
|
|
42 |
anomaly_detector = init_anomaly_detector()
|
43 |
|
44 |
# Cache data fetching
|
45 |
-
@st.cache_data(ttl=10)
|
46 |
def get_filtered_data(lab_site, equipment_type, date_start, date_end):
|
47 |
-
|
48 |
-
|
49 |
-
|
50 |
-
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
-
|
55 |
-
|
56 |
-
|
57 |
-
|
58 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
59 |
|
60 |
def main():
|
|
|
61 |
if sf is None or anomaly_detector is None:
|
62 |
-
st.error("
|
|
|
63 |
return
|
64 |
|
65 |
st.title("Multi-Device LabOps Dashboard")
|
@@ -73,9 +101,9 @@ def main():
|
|
73 |
|
74 |
date_range = st.date_input("Date Range", [datetime.now() - timedelta(days=7), datetime.now()])
|
75 |
|
76 |
-
# Validate date range
|
77 |
if len(date_range) != 2:
|
78 |
st.warning("Please select a valid date range.")
|
|
|
79 |
return
|
80 |
date_start, date_end = date_range
|
81 |
|
@@ -84,6 +112,7 @@ def main():
|
|
84 |
data = get_filtered_data(lab_site, equipment_type, date_start, date_end)
|
85 |
if not data:
|
86 |
st.warning("No data available for the selected filters.")
|
|
|
87 |
return
|
88 |
|
89 |
df = pd.DataFrame(data)
|
@@ -156,8 +185,15 @@ def main():
|
|
156 |
pdf_file = generate_pdf_report(df, lab_site, equipment_type, [date_start, date_end])
|
157 |
with open(pdf_file, "rb") as f:
|
158 |
st.download_button("Download PDF", f, file_name="LabOps_Report.pdf", mime="application/pdf")
|
|
|
159 |
except Exception as e:
|
160 |
st.error(f"Failed to generate PDF: {e}")
|
|
|
161 |
|
162 |
if __name__ == "__main__":
|
163 |
-
|
|
|
|
|
|
|
|
|
|
|
|
6 |
from transformers import pipeline
|
7 |
from utils import fetch_salesforce_data, detect_anomalies, generate_pdf_report
|
8 |
import os
|
9 |
+
import logging
|
10 |
+
|
11 |
+
# Configure logging
|
12 |
+
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
|
13 |
+
logger = logging.getLogger(__name__)
|
14 |
|
15 |
# Streamlit app configuration
|
16 |
+
try:
|
17 |
+
st.set_page_config(page_title="LabOps Dashboard", layout="wide")
|
18 |
+
logger.info("Streamlit page configuration set successfully.")
|
19 |
+
except Exception as e:
|
20 |
+
logger.error(f"Failed to set Streamlit page configuration: {e}")
|
21 |
+
raise
|
22 |
|
23 |
# Cache Salesforce connection
|
24 |
@st.cache_resource
|
25 |
def init_salesforce():
|
26 |
+
logger.info("Initializing Salesforce connection...")
|
27 |
try:
|
28 |
+
sf = Salesforce(
|
29 |
username=os.getenv("SF_USERNAME", st.secrets.get("sf_username")),
|
30 |
password=os.getenv("SF_PASSWORD", st.secrets.get("sf_password")),
|
31 |
security_token=os.getenv("SF_SECURITY_TOKEN", st.secrets.get("sf_security_token"))
|
32 |
)
|
33 |
+
logger.info("Salesforce connection initialized successfully.")
|
34 |
+
return sf
|
35 |
except Exception as e:
|
36 |
+
logger.error(f"Failed to initialize Salesforce: {e}")
|
37 |
+
st.error(f"Cannot connect to Salesforce: {e}")
|
38 |
return None
|
39 |
|
40 |
# Cache Hugging Face model
|
41 |
@st.cache_resource
|
42 |
def init_anomaly_detector():
|
43 |
+
logger.info("Initializing anomaly detector...")
|
44 |
try:
|
45 |
+
# Use lighter model for Hugging Face Spaces
|
46 |
+
detector = pipeline(
|
47 |
"text-classification",
|
48 |
+
model="prajjwal1/bert-tiny",
|
49 |
+
tokenizer="prajjwal1/bert-tiny",
|
50 |
clean_up_tokenization_spaces=True
|
51 |
)
|
52 |
+
logger.info("Anomaly detector initialized successfully.")
|
53 |
+
return detector
|
54 |
except Exception as e:
|
55 |
+
logger.error(f"Failed to initialize anomaly detector: {e}")
|
56 |
+
st.error(f"Cannot initialize anomaly detector: {e}")
|
57 |
return None
|
58 |
|
59 |
# Initialize connections
|
|
|
61 |
anomaly_detector = init_anomaly_detector()
|
62 |
|
63 |
# Cache data fetching
|
64 |
+
@st.cache_data(ttl=10)
|
65 |
def get_filtered_data(lab_site, equipment_type, date_start, date_end):
|
66 |
+
logger.info(f"Fetching data for lab: {lab_site}, equipment: {equipment_type}, date range: {date_start} to {date_end}")
|
67 |
+
try:
|
68 |
+
query = f"""
|
69 |
+
SELECT Equipment__c, Log_Timestamp__c, Status__c, Usage_Count__c, Lab__c, Equipment_Type__c
|
70 |
+
FROM SmartLog__c
|
71 |
+
WHERE Log_Timestamp__c >= {date_start.strftime('%Y-%m-%d')}
|
72 |
+
AND Log_Timestamp__c <= {date_end.strftime('%Y-%m-%d')}
|
73 |
+
"""
|
74 |
+
if lab_site != "All":
|
75 |
+
query += f" AND Lab__c = '{lab_site}'"
|
76 |
+
if equipment_type != "All":
|
77 |
+
query += f" AND Equipment_Type__c = '{equipment_type}'"
|
78 |
+
query += " LIMIT 100"
|
79 |
+
data = fetch_salesforce_data(sf, query)
|
80 |
+
logger.info(f"Fetched {len(data)} records from Salesforce.")
|
81 |
+
return data
|
82 |
+
except Exception as e:
|
83 |
+
logger.error(f"Failed to fetch data: {e}")
|
84 |
+
return []
|
85 |
|
86 |
def main():
|
87 |
+
logger.info("Starting main application...")
|
88 |
if sf is None or anomaly_detector is None:
|
89 |
+
st.error("Application cannot start due to initialization failures. Check logs for details.")
|
90 |
+
logger.error("Application initialization failed: Salesforce or anomaly detector not available.")
|
91 |
return
|
92 |
|
93 |
st.title("Multi-Device LabOps Dashboard")
|
|
|
101 |
|
102 |
date_range = st.date_input("Date Range", [datetime.now() - timedelta(days=7), datetime.now()])
|
103 |
|
|
|
104 |
if len(date_range) != 2:
|
105 |
st.warning("Please select a valid date range.")
|
106 |
+
logger.warning("Invalid date range selected.")
|
107 |
return
|
108 |
date_start, date_end = date_range
|
109 |
|
|
|
112 |
data = get_filtered_data(lab_site, equipment_type, date_start, date_end)
|
113 |
if not data:
|
114 |
st.warning("No data available for the selected filters.")
|
115 |
+
logger.warning("No data returned for the selected filters.")
|
116 |
return
|
117 |
|
118 |
df = pd.DataFrame(data)
|
|
|
185 |
pdf_file = generate_pdf_report(df, lab_site, equipment_type, [date_start, date_end])
|
186 |
with open(pdf_file, "rb") as f:
|
187 |
st.download_button("Download PDF", f, file_name="LabOps_Report.pdf", mime="application/pdf")
|
188 |
+
logger.info("PDF report generated successfully.")
|
189 |
except Exception as e:
|
190 |
st.error(f"Failed to generate PDF: {e}")
|
191 |
+
logger.error(f"Failed to generate PDF: {e}")
|
192 |
|
193 |
if __name__ == "__main__":
|
194 |
+
try:
|
195 |
+
logger.info("Application starting...")
|
196 |
+
main()
|
197 |
+
except Exception as e:
|
198 |
+
logger.error(f"Application failed to start: {e}")
|
199 |
+
raise
|