RathodHarish commited on
Commit
ad87f6c
·
verified ·
1 Parent(s): 3be9769

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +135 -32
app.py CHANGED
@@ -1,4 +1,5 @@
1
  from flask import Flask, request, jsonify
 
2
  import pandas as pd
3
  from datetime import datetime
4
  import logging
@@ -8,17 +9,19 @@ import torch
8
  import os
9
  import time
10
  import sys
 
 
11
 
12
- # Configure logging to console first (force output even if file logging fails)
13
  logging.basicConfig(
14
  level=logging.INFO,
15
  format='%(asctime)s - %(levelname)s - %(message)s',
16
  handlers=[
17
- logging.StreamHandler(sys.stdout) # Force console output
18
  ]
19
  )
20
 
21
- # Add file handler for logging (if possible)
22
  try:
23
  file_handler = logging.FileHandler('app.log')
24
  file_handler.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(message)s'))
@@ -31,18 +34,48 @@ except Exception as e:
31
  app = Flask(__name__)
32
  logging.info("Flask app initialized")
33
 
 
 
 
 
 
 
 
 
 
34
  # Global variable for Hugging Face model (lazy initialization)
35
  summarizer = None
36
  logging.info("Hugging Face model set to lazy initialization")
37
 
38
- # Health check endpoint to confirm the app is running
39
  @app.route('/health', methods=['GET'])
40
  def health_check():
41
  return jsonify({"status": "App is running"}), 200
42
 
43
- # Dummy Salesforce connection placeholder (disabled for now)
44
- sf = None
45
- logging.info("Salesforce connection disabled for troubleshooting")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46
 
47
  # Lazy load the Hugging Face model
48
  def load_huggingface_model():
@@ -52,32 +85,61 @@ def load_huggingface_model():
52
  start_time = time.time()
53
  try:
54
  device = 0 if torch.cuda.is_available() else -1
55
- summarizer = pipeline("summarization", model="sshleifer/distilbart-cnn-12-6", device=device)
56
  logging.info(f"Hugging Face model loaded successfully in {time.time() - start_time:.2f} seconds on device: {'GPU' if device == 0 else 'CPU'}")
57
  except Exception as e:
58
  logging.error(f"Failed to load Hugging Face model: {str(e)}")
59
  summarizer = None
60
 
61
- # Dummy fetch function (since Salesforce is disabled)
62
  def fetch_smartlog_records(lab_site, start_date, end_date, equipment_type):
63
- logging.info("Salesforce connection is disabled. Returning dummy data for testing.")
64
- # Return a small dummy DataFrame to test processing
65
- data = [
66
- {
67
- 'device_id': 'D001',
68
- 'log_type': 'SmartLog',
69
- 'status': 'OK',
70
- 'timestamp': '2025-05-14T10:15:00Z',
71
- 'usage_hours': 5.0,
72
- 'downtime': 0.0,
73
- 'amc_date': '2025-06-15'
74
- }
75
- ]
76
- df = pd.DataFrame(data)
77
- df['timestamp'] = pd.to_datetime(df['timestamp'], errors='coerce')
78
- df['amc_date'] = pd.to_datetime(df['amc_date'], errors='coerce')
79
- logging.info(f"Returning dummy DataFrame with {len(df)} records")
80
- return df
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81
 
82
  # Format summary prompt and generate report
83
  def summarize_logs(df):
@@ -179,6 +241,9 @@ def create_usage_chart_data(df):
179
  @app.route('/process_logs', methods=['POST'])
180
  def process_logs():
181
  try:
 
 
 
182
  data = request.get_json()
183
  lab_site = data.get('lab_site')
184
  start_date = data.get('start_date')
@@ -186,15 +251,53 @@ def process_logs():
186
  equipment_type = data.get('equipment_type')
187
  amc_threshold = data.get('amc_threshold', 30)
188
 
189
- # Fetch SmartLog records (using dummy data for now)
190
  df = fetch_smartlog_records(lab_site, start_date, end_date, equipment_type)
191
  if df.empty:
192
- return jsonify({"error": "No data available."}), 400
193
 
194
- # Step 1: Summary Report
195
  summary = summarize_logs(df)
196
 
197
- # Step 2: Log Preview (First 5 Rows)
198
  preview_lines = []
199
  for idx, row in df.head().iterrows():
200
- preview
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  from flask import Flask, request, jsonify
2
+ from simple_salesforce import Salesforce
3
  import pandas as pd
4
  from datetime import datetime
5
  import logging
 
9
  import os
10
  import time
11
  import sys
12
+ import requests
13
+ from requests.exceptions import Timeout
14
 
15
+ # Configure logging to console first
16
  logging.basicConfig(
17
  level=logging.INFO,
18
  format='%(asctime)s - %(levelname)s - %(message)s',
19
  handlers=[
20
+ logging.StreamHandler(sys.stdout)
21
  ]
22
  )
23
 
24
+ # Add file handler for logging
25
  try:
26
  file_handler = logging.FileHandler('app.log')
27
  file_handler.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(message)s'))
 
34
  app = Flask(__name__)
35
  logging.info("Flask app initialized")
36
 
37
+ # Salesforce credentials
38
+ SF_USERNAME = os.getenv('SF_USERNAME', 'your_salesforce_username')
39
+ SF_PASSWORD = os.getenv('SF_PASSWORD', 'your_salesforce_password')
40
+ SF_SECURITY_TOKEN = os.getenv('SF_SECURITY_TOKEN', 'your_security_token')
41
+ SF_INSTANCE_URL = os.getenv('SF_INSTANCE_URL', 'https://login.salesforce.com')
42
+
43
+ # Global variable for Salesforce connection
44
+ sf = None
45
+
46
  # Global variable for Hugging Face model (lazy initialization)
47
  summarizer = None
48
  logging.info("Hugging Face model set to lazy initialization")
49
 
50
+ # Health check endpoint
51
  @app.route('/health', methods=['GET'])
52
  def health_check():
53
  return jsonify({"status": "App is running"}), 200
54
 
55
+ # Connect to Salesforce with a timeout
56
+ def connect_to_salesforce():
57
+ global sf
58
+ logging.info("Attempting to connect to Salesforce...")
59
+ start_time = time.time()
60
+ try:
61
+ session = requests.Session()
62
+ adapter = requests.adapters.HTTPAdapter(max_retries=3)
63
+ session.mount('https://', adapter)
64
+ session.request('GET', SF_INSTANCE_URL, timeout=10)
65
+ sf = Salesforce(
66
+ username=SF_USERNAME,
67
+ password=SF_PASSWORD,
68
+ security_token=SF_SECURITY_TOKEN,
69
+ instance_url=SF_INSTANCE_URL,
70
+ session=session
71
+ )
72
+ logging.info(f"Connected to Salesforce successfully in {time.time() - start_time:.2f} seconds")
73
+ except Timeout:
74
+ logging.error("Salesforce connection timed out after 10 seconds")
75
+ sf = None
76
+ except Exception as e:
77
+ logging.error(f"Failed to connect to Salesforce: {str(e)}")
78
+ sf = None
79
 
80
  # Lazy load the Hugging Face model
81
  def load_huggingface_model():
 
85
  start_time = time.time()
86
  try:
87
  device = 0 if torch.cuda.is_available() else -1
88
+ summarizer = pipeline("summarization", model="t5-small", device=device) # Use a smaller model
89
  logging.info(f"Hugging Face model loaded successfully in {time.time() - start_time:.2f} seconds on device: {'GPU' if device == 0 else 'CPU'}")
90
  except Exception as e:
91
  logging.error(f"Failed to load Hugging Face model: {str(e)}")
92
  summarizer = None
93
 
94
+ # Fetch SmartLog records from Salesforce
95
  def fetch_smartlog_records(lab_site, start_date, end_date, equipment_type):
96
+ if sf is None:
97
+ raise Exception("Salesforce connection not established")
98
+ try:
99
+ logging.info("Fetching SmartLog records from Salesforce...")
100
+ query = "SELECT Device_Id__c, Log_Type__c, Status__c, Timestamp__c, Usage_Hours__c, Downtime__c, AMC_Date__c FROM SmartLog__c WHERE "
101
+ conditions = []
102
+ params = {}
103
+ if lab_site:
104
+ conditions.append("Lab_Site__c = :lab_site")
105
+ params['lab_site'] = lab_site
106
+ if start_date:
107
+ conditions.append("Timestamp__c >= :start_date")
108
+ params['start_date'] = start_date
109
+ if end_date:
110
+ conditions.append("Timestamp__c <= :end_date")
111
+ params['end_date'] = end_date
112
+ if equipment_type:
113
+ conditions.append("Log_Type__c = :equipment_type")
114
+ params['equipment_type'] = equipment_type
115
+
116
+ if not conditions:
117
+ query = query.replace(" WHERE ", "")
118
+ else:
119
+ query += " AND ".join(conditions)
120
+
121
+ result = sf.query_all(query, **params)
122
+ records = result['records']
123
+
124
+ data = []
125
+ for record in records:
126
+ data.append({
127
+ 'device_id': record['Device_Id__c'],
128
+ 'log_type': record['Log_Type__c'],
129
+ 'status': record['Status__c'],
130
+ 'timestamp': record['Timestamp__c'],
131
+ 'usage_hours': record['Usage_Hours__c'],
132
+ 'downtime': record['Downtime__c'],
133
+ 'amc_date': record['AMC_Date__c']
134
+ })
135
+ df = pd.DataFrame(data)
136
+ df['timestamp'] = pd.to_datetime(df['timestamp'], errors='coerce')
137
+ df['amc_date'] = pd.to_datetime(df['amc_date'], errors='coerce')
138
+ logging.info(f"Fetched {len(df)} SmartLog records")
139
+ return df
140
+ except Exception as e:
141
+ logging.error(f"Failed to fetch SmartLog records: {str(e)}")
142
+ raise e
143
 
144
  # Format summary prompt and generate report
145
  def summarize_logs(df):
 
241
  @app.route('/process_logs', methods=['POST'])
242
  def process_logs():
243
  try:
244
+ if sf is None:
245
+ return jsonify({"error": "Salesforce connection not established. Check server logs for details."}), 500
246
+
247
  data = request.get_json()
248
  lab_site = data.get('lab_site')
249
  start_date = data.get('start_date')
 
251
  equipment_type = data.get('equipment_type')
252
  amc_threshold = data.get('amc_threshold', 30)
253
 
 
254
  df = fetch_smartlog_records(lab_site, start_date, end_date, equipment_type)
255
  if df.empty:
256
+ return jsonify({"error": "No data available in SmartLog__c."}), 400
257
 
 
258
  summary = summarize_logs(df)
259
 
 
260
  preview_lines = []
261
  for idx, row in df.head().iterrows():
262
+ preview_lines.append({
263
+ "row": idx + 1,
264
+ "device_id": row['device_id'],
265
+ "timestamp": row['timestamp'].isoformat() if pd.notnull(row['timestamp']) else None,
266
+ "usage_hours": float(row['usage_hours']) if pd.notnull(row['usage_hours']) else 0,
267
+ "downtime": float(row['downtime']) if pd.notnull(row['downtime']) else 0,
268
+ "amc_date": row['amc_date'].isoformat() if pd.notnull(row['amc_date']) else None
269
+ })
270
+
271
+ chart_data = create_usage_chart_data(df)
272
+
273
+ anomaly_lines, anomaly_error = detect_anomalies(df)
274
+ if anomaly_error:
275
+ anomaly_lines = [{"error": anomaly_error}]
276
+
277
+ reminder_lines, reminder_error = check_amc_reminders(df, datetime.now())
278
+ if reminder_error:
279
+ reminder_lines = [{"error": reminder_error}]
280
+
281
+ insights = generate_dashboard_insights(df)
282
+
283
+ response = {
284
+ "summary": summary,
285
+ "log_preview": preview_lines,
286
+ "usage_chart": chart_data,
287
+ "anomalies": anomaly_lines,
288
+ "amc_reminders": reminder_lines,
289
+ "insights": insights
290
+ }
291
+
292
+ return jsonify(response), 200
293
+
294
+ except Exception as e:
295
+ logging.error(f"Failed to process logs: {str(e)}")
296
+ return jsonify({"error": str(e)}), 500
297
+
298
+ if __name__ == "__main__":
299
+ logging.info("Starting Flask application...")
300
+ start_time = time.time()
301
+ connect_to_salesforce()
302
+ logging.info(f"Flask application startup completed in {time.time() - start_time:.2f} seconds")
303
+ app.run(host="0.0.0.0", port=5000, debug=True)