varshakolanu commited on
Commit
59fdb92
·
verified ·
1 Parent(s): 67259ed

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +51 -297
app.py CHANGED
@@ -1,306 +1,60 @@
1
- import os
2
- import requests
3
- import json
4
- import logging
5
- from datetime import datetime
6
- from simple_salesforce import Salesforce, SalesforceAuthenticationFailed
7
- from flask import Flask, jsonify, request, render_template, redirect, url_for
8
 
9
- # Set up logging to capture errors and debug information
10
- logging.basicConfig(level=logging.INFO)
11
- logger = logging.getLogger(__name__)
12
-
13
- app = FastAPI()
14
-
15
- # Salesforce credentials
16
- SF_USERNAME = os.getenv("SF_USERNAME", "Ai@Coach.com")
17
- SF_PASSWORD = os.getenv("SF_PASSWORD", "Teja90325@")
18
- SF_SECURITY_TOKEN = os.getenv("SF_SECURITY_TOKEN", "clceSdBgQ30Rx9BSC66gAcRx")
19
- SF_DOMAIN = os.getenv("SF_DOMAIN", "login")
20
-
21
- # Verify API key is set
22
- API_KEY = os.getenv("HUGGING_FACE_API_KEY")
23
- if not API_KEY:
24
- logger.error("HUGGING_FACE_API_KEY environment variable not set")
25
- raise ValueError("HUGGING_FACE_API_KEY environment variable not set")
26
-
27
- # Connect to Salesforce
28
- try:
29
- sf = Salesforce(
30
- username=SF_USERNAME,
31
- password=SF_PASSWORD,
32
- security_token=SF_SECURITY_TOKEN,
33
- domain=SF_DOMAIN
34
- )
35
- logger.info("Successfully connected to Salesforce")
36
- except Exception as e:
37
- logger.error(f"Failed to connect to Salesforce: {str(e)}")
38
- raise
39
-
40
-
41
-
42
-
43
- # Validate configuration
44
- if not HUGGING_FACE_API_TOKEN:
45
- logger.error("HUGGING_FACE_API_TOKEN is not set")
46
- raise ValueError("HUGGING_FACE_API_TOKEN must be provided")
47
- if not HUGGING_FACE_API_URL.startswith("https://api-inference.huggingface.co/models/"):
48
- logger.error("Invalid HUGGING_FACE_API_URL: %s", HUGGING_FACE_API_URL)
49
- raise ValueError("HUGGING_FACE_API_URL must point to a valid Hugging Face model")
50
- if not all([SALESFORCE_USERNAME, SALESFORCE_PASSWORD, SALESFORCE_SECURITY_TOKEN]):
51
- logger.error("Salesforce credentials are incomplete")
52
- raise ValueError("Salesforce credentials must be set")
53
-
54
- # Initialize Flask app
55
  app = Flask(__name__)
56
 
57
- def test_salesforce_connection():
58
- """
59
- Test the Salesforce connection and log the result.
60
- """
61
- try:
62
- logger.debug("Attempting to connect to Salesforce with username: %s, domain: %s", SALESFORCE_USERNAME, SALESFORCE_DOMAIN)
63
- sf = Salesforce(
64
- username=SALESFORCE_USERNAME,
65
- password=SALESFORCE_PASSWORD,
66
- security_token=SALESFORCE_SECURITY_TOKEN,
67
- domain=SALESFORCE_DOMAIN
68
- )
69
- logger.info("Successfully connected to Salesforce. Session ID: %s", sf.session_id)
70
- # Test a simple query to verify object access
71
- sf.query("SELECT Id FROM Account LIMIT 1")
72
- logger.info("Successfully queried Account object. Connection is working.")
73
- return True
74
- except SalesforceAuthenticationFailed as e:
75
- logger.error("Salesforce authentication failed: %s", e)
76
- return False
77
- except Exception as e:
78
- logger.error("Salesforce connection error: %s", e)
79
- return False
80
-
81
- def fetch_salesforce_input(supervisor_id, project_id):
82
- """
83
- Fetch input data from Salesforce for a given supervisor and project.
84
- """
85
- try:
86
- logger.debug("Connecting to Salesforce to fetch input data")
87
- sf = Salesforce(
88
- username=SALESFORCE_USERNAME,
89
- password=SALESFORCE_PASSWORD,
90
- security_token=SALESFORCE_SECURITY_TOKEN,
91
- domain=SALESFORCE_DOMAIN
92
- )
93
- logger.info("Connected to Salesforce for input fetch")
94
- query = f"""
95
- SELECT Supervisor_ID__c, Role__c, Project_ID__c, Weather__c, Milestones__c, Reflection_Log__c
96
- FROM Supervisor_AI_Coaching__c
97
- WHERE Supervisor_ID__c = '{supervisor_id}' AND Project_ID__c = '{project_id}'
98
- ORDER BY Generated_Date__c DESC
99
- LIMIT 1
100
- """
101
- logger.debug("Executing Salesforce query: %s", query)
102
- result = sf.query(query)
103
- if result['totalSize'] > 0:
104
- record = result['records'][0]
105
- logger.info("Fetched record from Salesforce: %s", record)
106
- return {
107
- 'supervisor_id': record['Supervisor_ID__c'] or '',
108
- 'role': record['Role__c'] or '',
109
- 'project_id': record['Project_ID__c'] or '',
110
- 'weather': record['Weather__c'] or '',
111
- 'milestones': record['Milestones__c'] or '',
112
- 'reflection': record['Reflection_Log__c'] or ''
113
- }
114
- else:
115
- logger.info("No input data found for supervisor %s and project %s", supervisor_id, project_id)
116
- return None
117
- except Exception as e:
118
- logger.error("Salesforce fetch error: %s", e)
119
- return None
120
 
121
- def generate_coaching_output(data):
122
- """
123
- Generate daily checklist and tips using Hugging Face LLM.
124
- """
125
- logger.info("Generating coaching output for supervisor %s", data['supervisor_id'])
126
- milestones_json = json.dumps(data['milestones'], indent=2)
127
- prompt = f"""You are an AI Coach for construction site supervisors. Based on the following data, generate a daily checklist, three focus tips, and a motivational quote. Ensure outputs are concise, actionable, and tailored to the supervisor's role, project status, and reflection log.Supervisor Role: {data['role']}Project Milestones: {milestones_json}Reflection Log: {data['reflection_log']}Weather: {data['weather']}Format the response as JSON:{{ "checklist": ["item1", "item2", ...], "tips": ["tip1", "tip2", "tip3"], "quote": "motivational quote"}}"""
128
- headers = {
129
- "Authorization": f"Bearer {HUGGING_FACE_API_TOKEN}",
130
- "Content-Type": "application/json"
131
- }
132
- payload = {
133
- "inputs": prompt,
134
- "parameters": {
135
- "max_length": 200,
136
- "temperature": 0.7,
137
- "top_p": 0.9,
138
- "debug": True # Enable Hugging Face debug mode
139
- }
140
- }
141
- try:
142
- logger.debug("Sending request to Hugging Face API: %s", payload)
143
- response = requests.post(HUGGING_FACE_API_URL, headers=headers, json=payload, timeout=5)
144
- response.raise_for_status()
145
- result = response.json()
146
- logger.debug("Hugging Face API response: %s", result)
147
- generated_text = result[0]["generated_text"] if isinstance(result, list) else result["generated_text"]
148
- start_idx = generated_text.find('{')
149
- end_idx = generated_text.rfind('}') + 1
150
- if start_idx == -1 or end_idx == 0:
151
- logger.error("No valid JSON found in LLM output: %s", generated_text)
152
- raise ValueError("No valid JSON found in LLM output")
153
- json_str = generated_text[start_idx:end_idx]
154
- output = json.loads(json_str)
155
- logger.info("Successfully generated coaching output: %s", output)
156
- return output
157
- except requests.exceptions.HTTPError as e:
158
- logger.error("Hugging Face API HTTP error: %s", e)
159
- return None
160
- except (json.JSONDecodeError, ValueError) as e:
161
- logger.error("Error parsing LLM output: %s", e)
162
- return None
163
- except Exception as e:
164
- logger.error("Unexpected error in Hugging Face API call: %s", e)
165
- return None
166
-
167
- def save_to_salesforce(output, supervisor_id, project_id):
168
- """
169
- Save coaching output to Salesforce Supervisor_AI_Coaching__c object.
170
- """
171
- if not output:
172
- logger.error("No coaching output to save")
173
- return False
174
- try:
175
- logger.debug("Connecting to Salesforce to save output")
176
- sf = Salesforce(
177
- username=SALESFORCE_USERNAME,
178
- password=SALESFORCE_PASSWORD,
179
- security_token=SALESFORCE_SECURITY_TOKEN,
180
- domain=SALESFORCE_DOMAIN
181
- )
182
- logger.info("Connected to Salesforce for saving output")
183
- coaching_record = {
184
- "Supervisor_ID__c": supervisor_id,
185
- "Project_ID__c": project_id,
186
- "Daily_Checklist__c": "\n".join(output["checklist"]),
187
- "Suggested_Tips__c": "\n".join(output["tips"]),
188
- "Quote__c": output["quote"],
189
- "Generated_Date__c": datetime.now().strftime("%Y-%m-%d")
190
- }
191
- logger.debug("Saving record to Salesforce: %s", coaching_record)
192
- sf.Supervisor_AI_Coaching__c.upsert(
193
- f"Supervisor_ID__c/{supervisor_id}_{datetime.now().strftime('%Y-%m-%d')}",
194
- coaching_record
195
- )
196
- logger.info("Successfully saved coaching record to Salesforce for supervisor %s", supervisor_id)
197
- return True
198
- except Exception as e:
199
- logger.error("Salesforce save error: %s", e)
200
- return False
201
-
202
- @app.route('/', methods=['GET'])
203
- def redirect_to_ui():
204
- """
205
- Redirect root URL to the UI.
206
- """
207
- return redirect(url_for('ui'))
208
-
209
- @app.route('/ui', methods=['GET'])
210
- def ui():
211
- """
212
- Serve the HTML user interface, fetch input from Salesforce, generate output, and save to Salesforce.
213
- """
214
- form_data = {}
215
- output = {}
216
- # Test Salesforce connection first
217
- if not test_salesforce_connection():
218
- logger.error("Salesforce connection test failed. Check logs for details.")
219
- return "Salesforce connection failed. Check logs for details.", 500
220
- # Hardcoded supervisor_id and project_id for demonstration
221
- supervisor_id = "SUP-001"
222
- project_id = "PROJ-123"
223
- # Fetch input data from Salesforce
224
- logger.info("Fetching input data from Salesforce for supervisor %s and project %s", supervisor_id, project_id)
225
- sf_input = fetch_salesforce_input(supervisor_id, project_id)
226
- if sf_input:
227
- form_data = sf_input
228
- # Prepare data for generating output
229
- data = {
230
- 'supervisor_id': form_data['supervisor_id'],
231
- 'role': form_data['role'],
232
- 'project_id': form_data['project_id'],
233
- 'milestones': [m.strip() for m in form_data['milestones'].split(',') if m.strip()],
234
- 'reflection_log': form_data['reflection'],
235
- 'weather': form_data['weather']
236
- }
237
- # Generate output automatically
238
- logger.info("Generating output for fetched Salesforce data")
239
- coaching_output = generate_coaching_output(data)
240
- if coaching_output:
241
- # Save the generated output to Salesforce
242
- logger.info("Saving generated output to Salesforce")
243
- success = save_to_salesforce(coaching_output, supervisor_id, project_id)
244
- if success:
245
- output = coaching_output
246
- else:
247
- logger.error("Failed to save generated output to Salesforce")
248
- else:
249
- logger.error("Failed to generate coaching output")
250
- else:
251
- logger.warning("No input data found in Salesforce. Displaying empty fields.")
252
- return render_template('index.html', form_data=form_data, output=output)
253
 
254
- @app.route('/health', methods=['GET'])
255
- def health_check():
256
- """
257
- Health check endpoint.
258
- """
259
- return jsonify({"status": "healthy", "message": "Application is running"}), 200
260
-
261
- # NEW ENDPOINT TO RECEIVE DATA FROM SALESFORCE
262
- @app.route('/salesforce_data', methods=['POST'])
263
- def salesforce_data():
264
- """
265
- Receives data from Salesforce, generates coaching output, and saves it.
266
- """
267
  data = request.json
268
- logger.debug("Received data from Salesforce: %s", data)
269
-
270
- # Extract relevant data from the request. Adjust these keys
271
- # based on how Salesforce sends the data.
272
- supervisor_id = data.get('supervisor_id')
273
- project_id = data.get('project_id')
274
- role = data.get('role')
275
- weather = data.get('weather')
276
- milestones = data.get('milestones', '').split(',') # Handle potential empty string
277
- reflection_log = data.get('reflection_log')
278
-
279
- if not all([supervisor_id, project_id, role, milestones, reflection_log]):
280
- logger.error("Missing data from Salesforce: %s", data)
281
- return jsonify({"status": "error", "message": "Missing required data"}), 400
282
-
283
- coaching_data = {
284
- 'supervisor_id': supervisor_id,
285
- 'role': role,
286
- 'project_id': project_id,
287
- 'milestones': [m.strip() for m in milestones if m.strip()],
288
- 'reflection_log': reflection_log,
289
- 'weather': weather,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
290
  }
 
291
 
292
- coaching_output = generate_coaching_output(coaching_data)
293
- if coaching_output:
294
- success = save_to_salesforce(coaching_output, supervisor_id, project_id)
295
- if success:
296
- logger.info("Coaching output generated and saved successfully.")
297
- return jsonify({"status": "success", "message": "Coaching output generated and saved"}), 200
298
- else:
299
- logger.error("Failed to save coaching output to Salesforce.")
300
- return jsonify({"status": "error", "message": "Failed to save to Salesforce"}), 500
301
- else:
302
- logger.error("Failed to generate coaching output.")
303
- return jsonify({"status": "error", "message": "Failed to generate coaching output"}), 500
304
 
305
- if __name__ == "__main__":
306
- app.run(host="0.0.0.0", port=7860)
 
1
+ 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
+ # Initialize Hugging Face LLM (simulated for this example)
9
+ generator = pipeline("text-generation", model="distilgpt2")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10
 
11
+ # Salesforce credentials (to be filled by you)
12
+ sf = Salesforce(username='YOUR_USERNAME', password='YOUR_PASSWORD', security_token='YOUR_SECURITY_TOKEN')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13
 
14
+ @app.route('/generate', methods=['POST'])
15
+ def generate_ai_data():
 
 
 
 
 
 
 
 
 
 
 
16
  data = request.json
17
+ supervisor_id = data['supervisor_id']
18
+ project_id = data['project_id']
19
+ supervisor_data = data['supervisor_data'] # Role__c, Location__c
20
+ project_data = data['project_data'] # Name, Start_Date__c, End_Date__c, Milestones__c, Project_Schedule__c
21
+
22
+ # Generate AI data using LLM
23
+ prompt = f"Generate daily checklist, tips, risk alerts, milestones, and performance trends for a {supervisor_data['Role__c']} at {supervisor_data['Location__c']} working on project {project_data['Name']} with milestones {project_data['Milestones__c']} and schedule {project_data['Project_Schedule__c']}."
24
+ ai_response = generator(prompt, max_length=500, num_return_sequences=1)[0]['generated_text']
25
+
26
+ # Parse AI response (simplified for this example)
27
+ daily_checklist = "1. Inspect concrete quality (Safety, Pending)\n2. Schedule team briefing (General, Pending)\n3. Check equipment (High Priority, Pending)"
28
+ suggested_tips = "1. Prioritize safety checks.\n2. Focus on delayed tasks.\n3. Schedule a team review."
29
+ risk_alerts = "Risk of delay: Rain expected on May 22, 2025."
30
+ upcoming_milestones = "Foundation completion by May 22, 2025."
31
+ performance_trends = "Task completion rate: 80% this week."
32
+
33
+ # Save AI data to Salesforce
34
+ ai_data = {
35
+ 'Supervisor_ID__c': supervisor_id,
36
+ 'Project_ID__c': project_id,
37
+ 'Daily_Checklist__c': daily_checklist,
38
+ 'Suggested_Tips__c': suggested_tips,
39
+ 'Risk_Alerts__c': risk_alerts,
40
+ 'Upcoming_Milestones__c': upcoming_milestones,
41
+ 'Performance_Trends__c': performance_trends,
42
+ 'Generated_Date__c': datetime.datetime.now().strftime('%Y-%m-%d')
43
+ }
44
+ sf.AI_Coaching_Data__c.create(ai_data)
45
+
46
+ # Generate reports
47
+ report_data = {
48
+ 'Supervisor_ID__c': supervisor_id,
49
+ 'Project_ID__c': project_id,
50
+ 'Report_Type__c': 'Performance',
51
+ 'Report_Data__c': f"Performance Report: Task completion rate: 80%, Engagement score: 85%.",
52
+ 'Download_Link__c': 'https://salesforce-site.com/reports/RPT-0001.pdf',
53
+ 'Generated_Date__c': datetime.datetime.now().strftime('%Y-%m-%d')
54
  }
55
+ sf.Report_Download__c.create(report_data)
56
 
57
+ return jsonify({'status': 'success'})
 
 
 
 
 
 
 
 
 
 
 
58
 
59
+ if __name__ == '__main__':
60
+ app.run(host='0.0.0.0', port=5000)