geethareddy commited on
Commit
e06a887
·
verified ·
1 Parent(s): 19a80df

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +44 -69
app.py CHANGED
@@ -4,10 +4,6 @@ from transformers import AutoModelForCausalLM, AutoTokenizer
4
  from simple_salesforce import Salesforce
5
  import os
6
  from dotenv import load_dotenv
7
- import pandas as pd
8
- from reportlab.lib.pagesizes import letter
9
- from reportlab.pdfgen import canvas
10
- from io import BytesIO
11
 
12
  # Load environment variables
13
  load_dotenv()
@@ -18,7 +14,7 @@ missing_vars = [var for var in required_env_vars if not os.getenv(var)]
18
  if missing_vars:
19
  raise EnvironmentError(f"Missing required environment variables: {missing_vars}")
20
 
21
- # Default settings
22
  KPI_FLAG_DEFAULT = os.getenv('KPI_FLAG', 'True') == 'True'
23
  ENGAGEMENT_SCORE_DEFAULT = float(os.getenv('ENGAGEMENT_SCORE', '85.0'))
24
 
@@ -107,16 +103,26 @@ def get_projects_for_supervisor(supervisor_name):
107
  print(f"⚠️ Error fetching project: {e}")
108
  return ""
109
 
 
 
 
 
 
 
 
 
110
  # New function to generate Salesforce dashboard URL (Visualforce Page)
111
  def generate_salesforce_dashboard_url(supervisor_name, project_id):
 
112
  return f"https://aicoachforsitesupervisors-dev-ed--c.develop.vf.force.com/apex/DashboardPage?supervisorName={supervisor_name}&projectId={project_id}"
113
 
114
  # Dashboard button function
115
  def open_dashboard(role, supervisor_name, project_id):
 
116
  dashboard_url = generate_salesforce_dashboard_url(supervisor_name, project_id)
117
  return f'<a href="{dashboard_url}" target="_blank" rel="noopener noreferrer" style="font-size:16px;">Open Salesforce Dashboard</a>'
118
 
119
- # Function to generate day-by-day tasks
120
  def generate_outputs(role, supervisor_name, project_id, milestones, reflection):
121
  if not all([role, supervisor_name, project_id, milestones, reflection]):
122
  return "❗ Please fill all fields.", ""
@@ -133,7 +139,7 @@ def generate_outputs(role, supervisor_name, project_id, milestones, reflection):
133
  with torch.no_grad():
134
  outputs = model.generate(
135
  inputs['input_ids'],
136
- max_new_tokens=150,
137
  no_repeat_ngram_size=2,
138
  do_sample=True,
139
  top_p=0.9,
@@ -150,9 +156,11 @@ def generate_outputs(role, supervisor_name, project_id, milestones, reflection):
150
  e = text.find(end, s) if end else len(text)
151
  return text[s + len(start):e].strip() if s != -1 else ""
152
 
 
153
  checklist = extract_between(result, "Checklist:\n", "Suggestions:")
154
  suggestions = extract_between(result, "Suggestions:\n", None)
155
 
 
156
  if not checklist.strip():
157
  checklist = generate_fallback_checklist(role, milestones)
158
  if not suggestions.strip():
@@ -160,110 +168,77 @@ def generate_outputs(role, supervisor_name, project_id, milestones, reflection):
160
 
161
  return checklist, suggestions
162
 
163
- # Fallback checklist and suggestions generation
164
  def generate_fallback_checklist(role, milestones):
165
  checklist_items = []
166
- if milestones:
 
 
167
  kpis = [kpi.strip() for kpi in milestones.split(",")]
168
  for kpi in kpis:
169
  checklist_items.append(f"- Ensure progress on {kpi}")
170
  else:
171
  checklist_items.append("- Perform daily safety inspection")
 
172
  return "\n".join(checklist_items)
173
 
174
  def generate_fallback_suggestions(reflection):
175
  suggestions_items = []
176
  reflection_lower = reflection.lower()
 
 
 
177
  if "incident" in reflection_lower:
178
  suggestions_items.append("- Follow up on reported incidents with corrective actions")
 
179
  if not suggestions_items:
180
  suggestions_items.append("- Monitor team coordination")
 
 
181
  return "\n".join(suggestions_items)
182
 
183
- # Function to generate the PDF report
184
- def generate_pdf_report(supervisor_name, project_id, checklist, suggestions):
185
- file_path = f"reports/{supervisor_name}_{project_id}_report.pdf"
186
- buffer = BytesIO()
187
- c = canvas.Canvas(buffer, pagesize=letter)
188
- c.drawString(100, 750, f"Supervisor: {supervisor_name}")
189
- c.drawString(100, 735, f"Project ID: {project_id}")
190
- c.drawString(100, 700, "Daily Checklist:")
191
- y_position = 685
192
- for task in checklist.splitlines():
193
- c.drawString(100, y_position, f"- {task}")
194
- y_position -= 15
195
- c.drawString(100, y_position - 20, "Focus Suggestions:")
196
- y_position -= 40
197
- for suggestion in suggestions.splitlines():
198
- c.drawString(100, y_position, f"- {suggestion}")
199
- y_position -= 15
200
- c.showPage()
201
- c.save()
202
- buffer.seek(0)
203
- with open(file_path, 'wb') as f:
204
- f.write(buffer.read())
205
- return file_path
206
-
207
- # Function to generate CSV report
208
- def generate_csv_report(supervisor_name, project_id, checklist, suggestions):
209
- file_path = f"reports/{supervisor_name}_{project_id}_report.csv"
210
- data = {
211
- "Supervisor": [supervisor_name],
212
- "Project ID": [project_id],
213
- "Checklist": [checklist],
214
- "Suggestions": [suggestions]
215
- }
216
- df = pd.DataFrame(data)
217
- df.to_csv(file_path, index=False)
218
- return file_path
219
-
220
- # Function to store the download link in Salesforce
221
- def store_download_link_in_salesforce(supervisor_name, download_link):
222
- try:
223
- sf = Salesforce(
224
- username=os.getenv('SF_USERNAME'),
225
- password=os.getenv('SF_PASSWORD'),
226
- security_token=os.getenv('SF_SECURITY_TOKEN'),
227
- domain=os.getenv('SF_DOMAIN', 'login')
228
- )
229
- result = sf.query(f"SELECT Id FROM Supervisor_AI_Coaching__c WHERE Supervisor_Name__c = '{supervisor_name}' LIMIT 1")
230
- if result['totalSize'] == 0:
231
- return "Supervisor not found."
232
- supervisor_ai_coaching_id = result['records'][0]['Id']
233
- sf.Supervisor_AI_Coaching__c.update(supervisor_ai_coaching_id, {
234
- 'Download_Link__c': download_link
235
- })
236
- return "Download link stored successfully."
237
- except Exception as e:
238
- return f"Error storing download link: {e}"
239
-
240
- # Interface function
241
  def create_interface():
242
  roles = get_roles_from_salesforce()
243
  with gr.Blocks(theme="soft") as demo:
244
  gr.Markdown("## 🧠 AI-Powered Supervisor Assistant")
 
245
  with gr.Row():
246
  role = gr.Dropdown(choices=roles, label="Role")
247
  supervisor_name = gr.Dropdown(choices=[], label="Supervisor Name")
248
  project_id = gr.Textbox(label="Project ID", interactive=False)
 
249
  milestones = gr.Textbox(label="Milestones (comma-separated KPIs)", placeholder="E.g. Safety training, daily inspection")
250
  reflection = gr.Textbox(label="Reflection Log", lines=4, placeholder="Any concerns, delays, updates...")
 
251
  with gr.Row():
252
  generate = gr.Button("Generate")
253
  clear = gr.Button("Clear")
254
  refresh = gr.Button("🔄 Refresh Roles")
255
  dashboard_btn = gr.Button("Dashboard")
 
256
  checklist_output = gr.Textbox(label="✅ Daily Checklist")
257
  suggestions_output = gr.Textbox(label="💡 Focus Suggestions")
258
  dashboard_link = gr.HTML("")
 
259
  role.change(fn=lambda r: gr.update(choices=get_supervisor_name_by_role(r)), inputs=role, outputs=supervisor_name)
260
  supervisor_name.change(fn=get_projects_for_supervisor, inputs=supervisor_name, outputs=project_id)
261
- generate.click(fn=generate_outputs, inputs=[role, supervisor_name, project_id, milestones, reflection], outputs=[checklist_output, suggestions_output])
262
- clear.click(fn=lambda: ("", "", "", "", ""), inputs=None, outputs=[role, supervisor_name, project_id, milestones, reflection])
 
 
 
 
 
 
263
  refresh.click(fn=lambda: gr.update(choices=get_roles_from_salesforce()), outputs=role)
 
264
  dashboard_btn.click(fn=open_dashboard, inputs=[role, supervisor_name, project_id], outputs=dashboard_link)
 
265
  return demo
266
 
267
  if __name__ == "__main__":
268
  app = create_interface()
269
  app.launch()
 
 
 
4
  from simple_salesforce import Salesforce
5
  import os
6
  from dotenv import load_dotenv
 
 
 
 
7
 
8
  # Load environment variables
9
  load_dotenv()
 
14
  if missing_vars:
15
  raise EnvironmentError(f"Missing required environment variables: {missing_vars}")
16
 
17
+ # Defaults
18
  KPI_FLAG_DEFAULT = os.getenv('KPI_FLAG', 'True') == 'True'
19
  ENGAGEMENT_SCORE_DEFAULT = float(os.getenv('ENGAGEMENT_SCORE', '85.0'))
20
 
 
103
  print(f"⚠️ Error fetching project: {e}")
104
  return ""
105
 
106
+ def field_exists(sf, object_name, field_name):
107
+ try:
108
+ obj_desc = getattr(sf, object_name).describe()
109
+ return field_name in [field['name'] for field in obj_desc['fields']]
110
+ except Exception as e:
111
+ print(f"⚠️ Error checking field {field_name}: {e}")
112
+ return False
113
+
114
  # New function to generate Salesforce dashboard URL (Visualforce Page)
115
  def generate_salesforce_dashboard_url(supervisor_name, project_id):
116
+ # Use the provided Salesforce Visualforce URL with supervisorName and projectId as parameters
117
  return f"https://aicoachforsitesupervisors-dev-ed--c.develop.vf.force.com/apex/DashboardPage?supervisorName={supervisor_name}&projectId={project_id}"
118
 
119
  # Dashboard button function
120
  def open_dashboard(role, supervisor_name, project_id):
121
+ # Generate dynamic URL based on supervisor and project
122
  dashboard_url = generate_salesforce_dashboard_url(supervisor_name, project_id)
123
  return f'<a href="{dashboard_url}" target="_blank" rel="noopener noreferrer" style="font-size:16px;">Open Salesforce Dashboard</a>'
124
 
125
+ # Generate function
126
  def generate_outputs(role, supervisor_name, project_id, milestones, reflection):
127
  if not all([role, supervisor_name, project_id, milestones, reflection]):
128
  return "❗ Please fill all fields.", ""
 
139
  with torch.no_grad():
140
  outputs = model.generate(
141
  inputs['input_ids'],
142
+ max_new_tokens=150, # Increased max tokens to capture more content
143
  no_repeat_ngram_size=2,
144
  do_sample=True,
145
  top_p=0.9,
 
156
  e = text.find(end, s) if end else len(text)
157
  return text[s + len(start):e].strip() if s != -1 else ""
158
 
159
+ # Extract the checklist and suggestions
160
  checklist = extract_between(result, "Checklist:\n", "Suggestions:")
161
  suggestions = extract_between(result, "Suggestions:\n", None)
162
 
163
+ # If checklist or suggestions are empty, generate fallback content
164
  if not checklist.strip():
165
  checklist = generate_fallback_checklist(role, milestones)
166
  if not suggestions.strip():
 
168
 
169
  return checklist, suggestions
170
 
171
+ # Fallback generation for checklist and suggestions
172
  def generate_fallback_checklist(role, milestones):
173
  checklist_items = []
174
+
175
+ # If milestones are provided, add them to the checklist directly
176
+ if milestones and milestones.strip():
177
  kpis = [kpi.strip() for kpi in milestones.split(",")]
178
  for kpi in kpis:
179
  checklist_items.append(f"- Ensure progress on {kpi}")
180
  else:
181
  checklist_items.append("- Perform daily safety inspection")
182
+
183
  return "\n".join(checklist_items)
184
 
185
  def generate_fallback_suggestions(reflection):
186
  suggestions_items = []
187
  reflection_lower = reflection.lower()
188
+ if "student" in reflection_lower or "learning" in reflection_lower:
189
+ suggestions_items.append("- Ensure students are logging incidents consistently")
190
+ suggestions_items.append("- Provide guidance on timely incident recording")
191
  if "incident" in reflection_lower:
192
  suggestions_items.append("- Follow up on reported incidents with corrective actions")
193
+
194
  if not suggestions_items:
195
  suggestions_items.append("- Monitor team coordination")
196
+ suggestions_items.append("- Review safety protocols with the team")
197
+
198
  return "\n".join(suggestions_items)
199
 
200
+ # Interface
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
201
  def create_interface():
202
  roles = get_roles_from_salesforce()
203
  with gr.Blocks(theme="soft") as demo:
204
  gr.Markdown("## 🧠 AI-Powered Supervisor Assistant")
205
+
206
  with gr.Row():
207
  role = gr.Dropdown(choices=roles, label="Role")
208
  supervisor_name = gr.Dropdown(choices=[], label="Supervisor Name")
209
  project_id = gr.Textbox(label="Project ID", interactive=False)
210
+
211
  milestones = gr.Textbox(label="Milestones (comma-separated KPIs)", placeholder="E.g. Safety training, daily inspection")
212
  reflection = gr.Textbox(label="Reflection Log", lines=4, placeholder="Any concerns, delays, updates...")
213
+
214
  with gr.Row():
215
  generate = gr.Button("Generate")
216
  clear = gr.Button("Clear")
217
  refresh = gr.Button("🔄 Refresh Roles")
218
  dashboard_btn = gr.Button("Dashboard")
219
+
220
  checklist_output = gr.Textbox(label="✅ Daily Checklist")
221
  suggestions_output = gr.Textbox(label="💡 Focus Suggestions")
222
  dashboard_link = gr.HTML("")
223
+
224
  role.change(fn=lambda r: gr.update(choices=get_supervisor_name_by_role(r)), inputs=role, outputs=supervisor_name)
225
  supervisor_name.change(fn=get_projects_for_supervisor, inputs=supervisor_name, outputs=project_id)
226
+
227
+ generate.click(fn=generate_outputs,
228
+ inputs=[role, supervisor_name, project_id, milestones, reflection],
229
+ outputs=[checklist_output, suggestions_output])
230
+
231
+ clear.click(fn=lambda: ("", "", "", "", ""), inputs=None,
232
+ outputs=[role, supervisor_name, project_id, milestones, reflection])
233
+
234
  refresh.click(fn=lambda: gr.update(choices=get_roles_from_salesforce()), outputs=role)
235
+
236
  dashboard_btn.click(fn=open_dashboard, inputs=[role, supervisor_name, project_id], outputs=dashboard_link)
237
+
238
  return demo
239
 
240
  if __name__ == "__main__":
241
  app = create_interface()
242
  app.launch()
243
+
244
+