Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -2,9 +2,14 @@ from flask import Flask, request, jsonify
|
|
| 2 |
from transformers import pipeline
|
| 3 |
from simple_salesforce import Salesforce
|
| 4 |
import datetime
|
|
|
|
| 5 |
|
| 6 |
app = Flask(__name__)
|
| 7 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
# Hardcode Salesforce credentials
|
| 9 |
SF_USERNAME = "app@coach.com"
|
| 10 |
SF_PASSWORD = "Geetha@1"
|
|
@@ -15,7 +20,7 @@ SF_DOMAIN = "login"
|
|
| 15 |
try:
|
| 16 |
generator = pipeline("text-generation", model="distilgpt2")
|
| 17 |
except Exception as e:
|
| 18 |
-
|
| 19 |
generator = None
|
| 20 |
|
| 21 |
# Initialize Salesforce connection with hardcoded credentials
|
|
@@ -27,12 +32,13 @@ try:
|
|
| 27 |
domain=SF_DOMAIN
|
| 28 |
)
|
| 29 |
except Exception as e:
|
| 30 |
-
|
| 31 |
sf = None
|
| 32 |
|
| 33 |
# Add a default route for the root URL
|
| 34 |
@app.route('/')
|
| 35 |
def home():
|
|
|
|
| 36 |
return jsonify({
|
| 37 |
"status": "running",
|
| 38 |
"message": "This is the AI Coach App backend API. Use the /generate-ai-data endpoint to generate AI coaching data and reports.",
|
|
@@ -71,14 +77,18 @@ def generate_ai_data():
|
|
| 71 |
- AI_Coaching_Data__c: Daily_Checklist__c, Suggested_Tips__c, Risk_Alerts__c, Upcoming_Milestones__c, Performance_Trends__c, Generated_Date__c
|
| 72 |
- Report_Download__c: Report_Type__c, Report_Data__c, Download_Link__c, Generated_Date__c
|
| 73 |
"""
|
|
|
|
|
|
|
| 74 |
# Check if dependencies are initialized
|
| 75 |
if generator is None:
|
|
|
|
| 76 |
return jsonify({
|
| 77 |
"status": "error",
|
| 78 |
"message": "Hugging Face model failed to initialize."
|
| 79 |
}), 500
|
| 80 |
|
| 81 |
if sf is None:
|
|
|
|
| 82 |
return jsonify({
|
| 83 |
"status": "error",
|
| 84 |
"message": "Salesforce connection failed. Check credentials in app.py."
|
|
@@ -88,6 +98,7 @@ def generate_ai_data():
|
|
| 88 |
# Extract and validate inputs from the POST request
|
| 89 |
data = request.get_json()
|
| 90 |
if not data:
|
|
|
|
| 91 |
return jsonify({
|
| 92 |
"status": "error",
|
| 93 |
"message": "No data provided in the request."
|
|
@@ -97,6 +108,7 @@ def generate_ai_data():
|
|
| 97 |
required_fields = ['supervisor_id', 'project_id', 'supervisor_data', 'project_data']
|
| 98 |
for field in required_fields:
|
| 99 |
if field not in data or not data[field]:
|
|
|
|
| 100 |
return jsonify({
|
| 101 |
"status": "error",
|
| 102 |
"message": f"Missing or empty required field: {field}"
|
|
@@ -111,6 +123,7 @@ def generate_ai_data():
|
|
| 111 |
required_supervisor_fields = ['Role__c', 'Location__c']
|
| 112 |
for field in required_supervisor_fields:
|
| 113 |
if field not in supervisor_data or not supervisor_data[field]:
|
|
|
|
| 114 |
return jsonify({
|
| 115 |
"status": "error",
|
| 116 |
"message": f"Missing or empty field in supervisor_data: {field}"
|
|
@@ -120,6 +133,7 @@ def generate_ai_data():
|
|
| 120 |
required_project_fields = ['Name', 'Start_Date__c', 'End_Date__c', 'Milestones__c', 'Project_Schedule__c']
|
| 121 |
for field in required_project_fields:
|
| 122 |
if field not in project_data or not project_data[field]:
|
|
|
|
| 123 |
return jsonify({
|
| 124 |
"status": "error",
|
| 125 |
"message": f"Missing or empty field in project_data: {field}"
|
|
@@ -130,9 +144,10 @@ def generate_ai_data():
|
|
| 130 |
checklists = sf.query(
|
| 131 |
f"SELECT Task_Name__c, Status__c FROM Daily_Checklist__c WHERE Project_ID__c = '{project_id}' AND Date__c = TODAY"
|
| 132 |
)['records']
|
|
|
|
| 133 |
except Exception as e:
|
| 134 |
checklists = []
|
| 135 |
-
|
| 136 |
|
| 137 |
completed_tasks = [c['Task_Name__c'] for c in checklists if c.get('Status__c') == 'Completed']
|
| 138 |
pending_tasks = [c['Task_Name__c'] for c in checklists if c.get('Status__c') == 'Pending']
|
|
@@ -151,14 +166,16 @@ def generate_ai_data():
|
|
| 151 |
# Generate AI output
|
| 152 |
try:
|
| 153 |
ai_response = generator(prompt, max_length=500, num_return_sequences=1)[0]['generated_text']
|
|
|
|
| 154 |
except Exception as e:
|
|
|
|
| 155 |
return jsonify({
|
| 156 |
"status": "error",
|
| 157 |
"message": f"Error generating AI response: {str(e)}"
|
| 158 |
}), 500
|
| 159 |
|
| 160 |
# Parse AI response (more dynamic parsing based on project progress)
|
| 161 |
-
today =
|
| 162 |
daily_checklist = (
|
| 163 |
f"1. Review pending tasks from yesterday (General, Pending)\n"
|
| 164 |
f"2. Conduct daily safety inspection for {project_data['Name']} (Safety, Pending)\n"
|
|
@@ -190,7 +207,9 @@ def generate_ai_data():
|
|
| 190 |
}
|
| 191 |
try:
|
| 192 |
sf.AI_Coaching_Data__c.create(ai_data)
|
|
|
|
| 193 |
except Exception as e:
|
|
|
|
| 194 |
return jsonify({
|
| 195 |
"status": "error",
|
| 196 |
"message": f"Error saving to AI_Coaching_Data__c: {str(e)}"
|
|
@@ -208,12 +227,15 @@ def generate_ai_data():
|
|
| 208 |
}
|
| 209 |
try:
|
| 210 |
sf.Report_Download__c.create(report_data)
|
|
|
|
| 211 |
except Exception as e:
|
|
|
|
| 212 |
return jsonify({
|
| 213 |
"status": "error",
|
| 214 |
"message": f"Error saving to Report_Download__c: {str(e)}"
|
| 215 |
}), 500
|
| 216 |
|
|
|
|
| 217 |
return jsonify({
|
| 218 |
"status": "success",
|
| 219 |
"message": "AI data and report generated successfully",
|
|
@@ -222,6 +244,7 @@ def generate_ai_data():
|
|
| 222 |
})
|
| 223 |
|
| 224 |
except Exception as e:
|
|
|
|
| 225 |
return jsonify({
|
| 226 |
"status": "error",
|
| 227 |
"message": f"Error generating AI data: {str(e)}"
|
|
|
|
| 2 |
from transformers import pipeline
|
| 3 |
from simple_salesforce import Salesforce
|
| 4 |
import datetime
|
| 5 |
+
import logging
|
| 6 |
|
| 7 |
app = Flask(__name__)
|
| 8 |
|
| 9 |
+
# Set up logging
|
| 10 |
+
logging.basicConfig(level=logging.INFO)
|
| 11 |
+
logger = logging.getLogger(__name__)
|
| 12 |
+
|
| 13 |
# Hardcode Salesforce credentials
|
| 14 |
SF_USERNAME = "app@coach.com"
|
| 15 |
SF_PASSWORD = "Geetha@1"
|
|
|
|
| 20 |
try:
|
| 21 |
generator = pipeline("text-generation", model="distilgpt2")
|
| 22 |
except Exception as e:
|
| 23 |
+
logger.error(f"Error initializing Hugging Face model: {str(e)}")
|
| 24 |
generator = None
|
| 25 |
|
| 26 |
# Initialize Salesforce connection with hardcoded credentials
|
|
|
|
| 32 |
domain=SF_DOMAIN
|
| 33 |
)
|
| 34 |
except Exception as e:
|
| 35 |
+
logger.error(f"Error connecting to Salesforce: {str(e)}")
|
| 36 |
sf = None
|
| 37 |
|
| 38 |
# Add a default route for the root URL
|
| 39 |
@app.route('/')
|
| 40 |
def home():
|
| 41 |
+
logger.info("Received request to root URL")
|
| 42 |
return jsonify({
|
| 43 |
"status": "running",
|
| 44 |
"message": "This is the AI Coach App backend API. Use the /generate-ai-data endpoint to generate AI coaching data and reports.",
|
|
|
|
| 77 |
- AI_Coaching_Data__c: Daily_Checklist__c, Suggested_Tips__c, Risk_Alerts__c, Upcoming_Milestones__c, Performance_Trends__c, Generated_Date__c
|
| 78 |
- Report_Download__c: Report_Type__c, Report_Data__c, Download_Link__c, Generated_Date__c
|
| 79 |
"""
|
| 80 |
+
logger.info("Received request to /generate-ai-data endpoint")
|
| 81 |
+
|
| 82 |
# Check if dependencies are initialized
|
| 83 |
if generator is None:
|
| 84 |
+
logger.error("Hugging Face model failed to initialize")
|
| 85 |
return jsonify({
|
| 86 |
"status": "error",
|
| 87 |
"message": "Hugging Face model failed to initialize."
|
| 88 |
}), 500
|
| 89 |
|
| 90 |
if sf is None:
|
| 91 |
+
logger.error("Salesforce connection failed")
|
| 92 |
return jsonify({
|
| 93 |
"status": "error",
|
| 94 |
"message": "Salesforce connection failed. Check credentials in app.py."
|
|
|
|
| 98 |
# Extract and validate inputs from the POST request
|
| 99 |
data = request.get_json()
|
| 100 |
if not data:
|
| 101 |
+
logger.error("No data provided in the request")
|
| 102 |
return jsonify({
|
| 103 |
"status": "error",
|
| 104 |
"message": "No data provided in the request."
|
|
|
|
| 108 |
required_fields = ['supervisor_id', 'project_id', 'supervisor_data', 'project_data']
|
| 109 |
for field in required_fields:
|
| 110 |
if field not in data or not data[field]:
|
| 111 |
+
logger.error(f"Missing or empty required field: {field}")
|
| 112 |
return jsonify({
|
| 113 |
"status": "error",
|
| 114 |
"message": f"Missing or empty required field: {field}"
|
|
|
|
| 123 |
required_supervisor_fields = ['Role__c', 'Location__c']
|
| 124 |
for field in required_supervisor_fields:
|
| 125 |
if field not in supervisor_data or not supervisor_data[field]:
|
| 126 |
+
logger.error(f"Missing or empty field in supervisor_data: {field}")
|
| 127 |
return jsonify({
|
| 128 |
"status": "error",
|
| 129 |
"message": f"Missing or empty field in supervisor_data: {field}"
|
|
|
|
| 133 |
required_project_fields = ['Name', 'Start_Date__c', 'End_Date__c', 'Milestones__c', 'Project_Schedule__c']
|
| 134 |
for field in required_project_fields:
|
| 135 |
if field not in project_data or not project_data[field]:
|
| 136 |
+
logger.error(f"Missing or empty field in project_data: {field}")
|
| 137 |
return jsonify({
|
| 138 |
"status": "error",
|
| 139 |
"message": f"Missing or empty field in project_data: {field}"
|
|
|
|
| 144 |
checklists = sf.query(
|
| 145 |
f"SELECT Task_Name__c, Status__c FROM Daily_Checklist__c WHERE Project_ID__c = '{project_id}' AND Date__c = TODAY"
|
| 146 |
)['records']
|
| 147 |
+
logger.info(f"Fetched {len(checklists)} checklists for project {project_id}")
|
| 148 |
except Exception as e:
|
| 149 |
checklists = []
|
| 150 |
+
logger.warning(f"Error querying Daily_Checklist__c: {str(e)}")
|
| 151 |
|
| 152 |
completed_tasks = [c['Task_Name__c'] for c in checklists if c.get('Status__c') == 'Completed']
|
| 153 |
pending_tasks = [c['Task_Name__c'] for c in checklists if c.get('Status__c') == 'Pending']
|
|
|
|
| 166 |
# Generate AI output
|
| 167 |
try:
|
| 168 |
ai_response = generator(prompt, max_length=500, num_return_sequences=1)[0]['generated_text']
|
| 169 |
+
logger.info("Successfully generated AI response")
|
| 170 |
except Exception as e:
|
| 171 |
+
logger.error(f"Error generating AI response: {str(e)}")
|
| 172 |
return jsonify({
|
| 173 |
"status": "error",
|
| 174 |
"message": f"Error generating AI response: {str(e)}"
|
| 175 |
}), 500
|
| 176 |
|
| 177 |
# Parse AI response (more dynamic parsing based on project progress)
|
| 178 |
+
today = "2025-05-22" # Hardcoded to current date (May 22, 2025)
|
| 179 |
daily_checklist = (
|
| 180 |
f"1. Review pending tasks from yesterday (General, Pending)\n"
|
| 181 |
f"2. Conduct daily safety inspection for {project_data['Name']} (Safety, Pending)\n"
|
|
|
|
| 207 |
}
|
| 208 |
try:
|
| 209 |
sf.AI_Coaching_Data__c.create(ai_data)
|
| 210 |
+
logger.info(f"Successfully saved AI data to AI_Coaching_Data__c for project {project_id}")
|
| 211 |
except Exception as e:
|
| 212 |
+
logger.error(f"Error saving to AI_Coaching_Data__c: {str(e)}")
|
| 213 |
return jsonify({
|
| 214 |
"status": "error",
|
| 215 |
"message": f"Error saving to AI_Coaching_Data__c: {str(e)}"
|
|
|
|
| 227 |
}
|
| 228 |
try:
|
| 229 |
sf.Report_Download__c.create(report_data)
|
| 230 |
+
logger.info(f"Successfully saved report to Report_Download__c for project {project_id}")
|
| 231 |
except Exception as e:
|
| 232 |
+
logger.error(f"Error saving to Report_Download__c: {str(e)}")
|
| 233 |
return jsonify({
|
| 234 |
"status": "error",
|
| 235 |
"message": f"Error saving to Report_Download__c: {str(e)}"
|
| 236 |
}), 500
|
| 237 |
|
| 238 |
+
logger.info("Successfully processed request to /generate-ai-data")
|
| 239 |
return jsonify({
|
| 240 |
"status": "success",
|
| 241 |
"message": "AI data and report generated successfully",
|
|
|
|
| 244 |
})
|
| 245 |
|
| 246 |
except Exception as e:
|
| 247 |
+
logger.error(f"Error generating AI data: {str(e)}")
|
| 248 |
return jsonify({
|
| 249 |
"status": "error",
|
| 250 |
"message": f"Error generating AI data: {str(e)}"
|