Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,7 +1,4 @@
|
|
1 |
import gradio as gr
|
2 |
-
import torch
|
3 |
-
from transformers import AutoModelForCausalLM, AutoTokenizer
|
4 |
-
from simple_salesforce import Salesforce
|
5 |
import os
|
6 |
import base64
|
7 |
import datetime
|
@@ -12,6 +9,7 @@ import html
|
|
12 |
import io
|
13 |
import matplotlib.pyplot as plt
|
14 |
import numpy as np
|
|
|
15 |
|
16 |
# Load environment variables
|
17 |
load_dotenv()
|
@@ -22,15 +20,9 @@ missing_vars = [var for var in required_env_vars if not os.getenv(var)]
|
|
22 |
if missing_vars:
|
23 |
raise EnvironmentError(f"Missing required environment variables: {missing_vars}")
|
24 |
|
25 |
-
#
|
26 |
-
|
27 |
-
|
28 |
-
model = AutoModelForCausalLM.from_pretrained(model_name, low_cpu_mem_usage=True)
|
29 |
-
|
30 |
-
if tokenizer.pad_token is None:
|
31 |
-
tokenizer.pad_token = tokenizer.eos_token
|
32 |
-
tokenizer.pad_token_id = tokenizer.convert_tokens_to_ids(tokenizer.pad_token)
|
33 |
-
model.config.pad_token_id = tokenizer.pad_token_id
|
34 |
|
35 |
# Function to generate progress chart
|
36 |
def show_dashboard_chart(start_date, end_date, tasks_completed):
|
@@ -38,7 +30,6 @@ def show_dashboard_chart(start_date, end_date, tasks_completed):
|
|
38 |
labels = list(tasks_completed.keys())
|
39 |
remaining_tasks = [5 - task for task in completed_tasks] # Assuming 5 tasks per date
|
40 |
|
41 |
-
# Create the bar chart with completed and remaining tasks
|
42 |
fig, ax = plt.subplots(figsize=(10, 6))
|
43 |
ax.bar(labels, completed_tasks, color='green', label="Completed")
|
44 |
ax.bar(labels, remaining_tasks, bottom=completed_tasks, color='gray', label="Remaining")
|
@@ -63,7 +54,6 @@ def get_dashboard_data_from_salesforce(supervisor_name, project_id):
|
|
63 |
domain=os.getenv('SF_DOMAIN', 'login')
|
64 |
)
|
65 |
|
66 |
-
# Get the start and end date from Salesforce
|
67 |
query = sf.query(f"SELECT Start_Date__c, End_Date__c FROM Project__c WHERE Name = '{project_id}' LIMIT 1")
|
68 |
if query['totalSize'] == 0:
|
69 |
return "", "", None, "Project not found"
|
@@ -71,11 +61,9 @@ def get_dashboard_data_from_salesforce(supervisor_name, project_id):
|
|
71 |
start_date_str = query['records'][0]['Start_Date__c']
|
72 |
end_date_str = query['records'][0]['End_Date__c']
|
73 |
|
74 |
-
# Convert the string dates to datetime objects
|
75 |
start_date = datetime.datetime.strptime(start_date_str, "%Y-%m-%d")
|
76 |
end_date = datetime.datetime.strptime(end_date_str, "%Y-%m-%d")
|
77 |
|
78 |
-
# Generate task dates and simulated completion data
|
79 |
task_dates = [start_date + datetime.timedelta(days=i) for i in range((end_date - start_date).days + 1)]
|
80 |
tasks_completed = {str(task_dates[i].date()): np.random.randint(1, 6) for i in range(len(task_dates))}
|
81 |
|
@@ -169,21 +157,49 @@ def get_projects_for_supervisor(supervisor_name):
|
|
169 |
|
170 |
# Function to generate daily checklist and focus suggestions
|
171 |
def generate_checklist_and_suggestions(role, project_id, milestones, reflection):
|
172 |
-
|
173 |
-
|
174 |
-
|
175 |
-
|
176 |
-
|
177 |
-
""
|
178 |
-
|
179 |
-
|
180 |
-
|
181 |
-
|
182 |
-
|
183 |
-
|
184 |
-
|
185 |
-
|
186 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
187 |
return checklist, suggestions
|
188 |
|
189 |
# Function to upload the report and create the Supervisor AI Coaching record in Salesforce
|
@@ -196,7 +212,6 @@ def upload_report_and_create_supervisor_ai_coaching(supervisor_name, project_id,
|
|
196 |
domain=os.getenv('SF_DOMAIN', 'login')
|
197 |
)
|
198 |
|
199 |
-
# Upload the PDF file to Salesforce as Content Version
|
200 |
with open(pdf_path, "rb") as f:
|
201 |
encoded = base64.b64encode(f.read()).decode()
|
202 |
|
@@ -209,7 +224,6 @@ def upload_report_and_create_supervisor_ai_coaching(supervisor_name, project_id,
|
|
209 |
content_id = content['id']
|
210 |
download_url = f"https://{sf.sf_instance}/sfc/servlet.shepherd/version/download/{content_id}"
|
211 |
|
212 |
-
# Create a Supervisor AI Coaching record
|
213 |
query = sf.query(f"SELECT Id FROM Supervisor__c WHERE Name = '{supervisor_name}' LIMIT 1")
|
214 |
supervisor_id = query['records'][0]['Id'] if query['totalSize'] > 0 else None
|
215 |
if not supervisor_id:
|
@@ -220,7 +234,6 @@ def upload_report_and_create_supervisor_ai_coaching(supervisor_name, project_id,
|
|
220 |
if not project_id_sf:
|
221 |
return "Project not found."
|
222 |
|
223 |
-
# Create Supervisor AI Coaching record with all necessary fields
|
224 |
sf.Supervisor_AI_Coaching__c.create({
|
225 |
'Project_ID__c': project_id_sf,
|
226 |
'Supervisor_ID__c': supervisor_id,
|
@@ -230,23 +243,22 @@ def upload_report_and_create_supervisor_ai_coaching(supervisor_name, project_id,
|
|
230 |
})
|
231 |
|
232 |
return "Supervisor AI Coaching record created and report uploaded successfully."
|
233 |
-
|
234 |
except Exception as e:
|
235 |
return f"Error: {str(e)}"
|
236 |
|
237 |
# Gradio interface
|
238 |
def create_interface():
|
239 |
-
roles = get_roles_from_salesforce()
|
240 |
with gr.Blocks(theme="soft", css=".footer { display: none; }") as demo:
|
241 |
gr.Markdown("## 🧠 AI-Powered Supervisor Assistant")
|
242 |
|
243 |
with gr.Row():
|
244 |
-
role = gr.Dropdown(choices=roles, label="Role")
|
245 |
-
supervisor_name = gr.Dropdown(choices=[], label="Supervisor Name")
|
246 |
-
project_id = gr.Textbox(label="Project ID", interactive=False)
|
247 |
|
248 |
-
milestones = gr.Textbox(label="Milestones (comma-separated KPIs)")
|
249 |
-
reflection = gr.Textbox(label="Reflection Log", lines=4)
|
250 |
|
251 |
with gr.Row():
|
252 |
generate = gr.Button("Generate")
|
@@ -263,9 +275,12 @@ def create_interface():
|
|
263 |
|
264 |
def handle_generate(role, supervisor_name, project_id, milestones, reflection):
|
265 |
checklist, suggestions = generate_checklist_and_suggestions(role, project_id, milestones, reflection)
|
|
|
|
|
266 |
pdf_path, pdf_name = save_report_as_pdf(role, supervisor_name, project_id, checklist, suggestions)
|
267 |
supervisor_ai_coaching_response = upload_report_and_create_supervisor_ai_coaching(supervisor_name, project_id, checklist, suggestions, pdf_path, pdf_name)
|
268 |
-
|
|
|
269 |
|
270 |
generate.click(fn=handle_generate,
|
271 |
inputs=[role, supervisor_name, project_id, milestones, reflection],
|
@@ -277,7 +292,6 @@ def create_interface():
|
|
277 |
|
278 |
refresh.click(fn=lambda: gr.update(choices=get_roles_from_salesforce()), outputs=role)
|
279 |
|
280 |
-
# Supervisor Dashboard Tab
|
281 |
with gr.Tab("📊 Supervisor Dashboard"):
|
282 |
dash_supervisor = gr.Textbox(label="Supervisor Name", placeholder="e.g., SUP-056")
|
283 |
dash_project = gr.Textbox(label="Project ID", placeholder="e.g., PROJ-078")
|
@@ -298,6 +312,4 @@ def create_interface():
|
|
298 |
|
299 |
if __name__ == "__main__":
|
300 |
app = create_interface()
|
301 |
-
app.launch()
|
302 |
-
|
303 |
-
|
|
|
1 |
import gradio as gr
|
|
|
|
|
|
|
2 |
import os
|
3 |
import base64
|
4 |
import datetime
|
|
|
9 |
import io
|
10 |
import matplotlib.pyplot as plt
|
11 |
import numpy as np
|
12 |
+
from simple_salesforce import Salesforce
|
13 |
|
14 |
# Load environment variables
|
15 |
load_dotenv()
|
|
|
20 |
if missing_vars:
|
21 |
raise EnvironmentError(f"Missing required environment variables: {missing_vars}")
|
22 |
|
23 |
+
# Defaults
|
24 |
+
KPI_FLAG_DEFAULT = os.getenv('KPI_FLAG', 'True') == 'True'
|
25 |
+
ENGAGEMENT_SCORE_DEFAULT = float(os.getenv('ENGAGEMENT_SCORE', '85.0'))
|
|
|
|
|
|
|
|
|
|
|
|
|
26 |
|
27 |
# Function to generate progress chart
|
28 |
def show_dashboard_chart(start_date, end_date, tasks_completed):
|
|
|
30 |
labels = list(tasks_completed.keys())
|
31 |
remaining_tasks = [5 - task for task in completed_tasks] # Assuming 5 tasks per date
|
32 |
|
|
|
33 |
fig, ax = plt.subplots(figsize=(10, 6))
|
34 |
ax.bar(labels, completed_tasks, color='green', label="Completed")
|
35 |
ax.bar(labels, remaining_tasks, bottom=completed_tasks, color='gray', label="Remaining")
|
|
|
54 |
domain=os.getenv('SF_DOMAIN', 'login')
|
55 |
)
|
56 |
|
|
|
57 |
query = sf.query(f"SELECT Start_Date__c, End_Date__c FROM Project__c WHERE Name = '{project_id}' LIMIT 1")
|
58 |
if query['totalSize'] == 0:
|
59 |
return "", "", None, "Project not found"
|
|
|
61 |
start_date_str = query['records'][0]['Start_Date__c']
|
62 |
end_date_str = query['records'][0]['End_Date__c']
|
63 |
|
|
|
64 |
start_date = datetime.datetime.strptime(start_date_str, "%Y-%m-%d")
|
65 |
end_date = datetime.datetime.strptime(end_date_str, "%Y-%m-%d")
|
66 |
|
|
|
67 |
task_dates = [start_date + datetime.timedelta(days=i) for i in range((end_date - start_date).days + 1)]
|
68 |
tasks_completed = {str(task_dates[i].date()): np.random.randint(1, 6) for i in range(len(task_dates))}
|
69 |
|
|
|
157 |
|
158 |
# Function to generate daily checklist and focus suggestions
|
159 |
def generate_checklist_and_suggestions(role, project_id, milestones, reflection):
|
160 |
+
if not all([role, project_id, milestones, reflection]):
|
161 |
+
return "Please fill all fields.", ""
|
162 |
+
|
163 |
+
# Generate Checklist
|
164 |
+
checklist_items = []
|
165 |
+
if role.lower() == "site supervisor":
|
166 |
+
checklist_items.append("- Conduct daily site safety briefing")
|
167 |
+
checklist_items.append("- Monitor progress against project timeline")
|
168 |
+
|
169 |
+
milestones_lower = milestones.lower()
|
170 |
+
if "excavation" in milestones_lower:
|
171 |
+
checklist_items.append("- Verify excavation progress and safety measures")
|
172 |
+
if "foundation work" in milestones_lower:
|
173 |
+
checklist_items.append("- Inspect foundation work for quality")
|
174 |
+
if "pour the foundation concrete" in milestones_lower:
|
175 |
+
checklist_items.append("- Ensure proper concrete pouring and curing")
|
176 |
+
if "set up reinforcement bars" in milestones_lower:
|
177 |
+
checklist_items.append("- Check reinforcement bar installation")
|
178 |
+
if "test soil compaction" in milestones_lower:
|
179 |
+
checklist_items.append("- Conduct soil compaction tests")
|
180 |
+
|
181 |
+
if not checklist_items:
|
182 |
+
checklist_items.append("- Perform general site inspection")
|
183 |
+
|
184 |
+
checklist = "\n".join(checklist_items)
|
185 |
+
|
186 |
+
# Generate Suggestions
|
187 |
+
suggestions_items = []
|
188 |
+
reflection_lower = reflection.lower()
|
189 |
+
if "weather conditions" in reflection_lower or "rainfall" in reflection_lower:
|
190 |
+
suggestions_items.append("- Adjust schedule for weather delays")
|
191 |
+
suggestions_items.append("- Implement weather protection measures")
|
192 |
+
if "delays" in reflection_lower:
|
193 |
+
suggestions_items.append("- Identify causes of delays and mitigate")
|
194 |
+
if "leveling" in reflection_lower or "base" in reflection_lower:
|
195 |
+
suggestions_items.append("- Verify leveling accuracy and resolve issues")
|
196 |
+
|
197 |
+
if not suggestions_items:
|
198 |
+
suggestions_items.append("- Monitor team performance")
|
199 |
+
suggestions_items.append("- Review safety protocols")
|
200 |
+
|
201 |
+
suggestions = "\n".join(suggestions_items)
|
202 |
+
|
203 |
return checklist, suggestions
|
204 |
|
205 |
# Function to upload the report and create the Supervisor AI Coaching record in Salesforce
|
|
|
212 |
domain=os.getenv('SF_DOMAIN', 'login')
|
213 |
)
|
214 |
|
|
|
215 |
with open(pdf_path, "rb") as f:
|
216 |
encoded = base64.b64encode(f.read()).decode()
|
217 |
|
|
|
224 |
content_id = content['id']
|
225 |
download_url = f"https://{sf.sf_instance}/sfc/servlet.shepherd/version/download/{content_id}"
|
226 |
|
|
|
227 |
query = sf.query(f"SELECT Id FROM Supervisor__c WHERE Name = '{supervisor_name}' LIMIT 1")
|
228 |
supervisor_id = query['records'][0]['Id'] if query['totalSize'] > 0 else None
|
229 |
if not supervisor_id:
|
|
|
234 |
if not project_id_sf:
|
235 |
return "Project not found."
|
236 |
|
|
|
237 |
sf.Supervisor_AI_Coaching__c.create({
|
238 |
'Project_ID__c': project_id_sf,
|
239 |
'Supervisor_ID__c': supervisor_id,
|
|
|
243 |
})
|
244 |
|
245 |
return "Supervisor AI Coaching record created and report uploaded successfully."
|
|
|
246 |
except Exception as e:
|
247 |
return f"Error: {str(e)}"
|
248 |
|
249 |
# Gradio interface
|
250 |
def create_interface():
|
251 |
+
roles = get_roles_from_salesforce()
|
252 |
with gr.Blocks(theme="soft", css=".footer { display: none; }") as demo:
|
253 |
gr.Markdown("## 🧠 AI-Powered Supervisor Assistant")
|
254 |
|
255 |
with gr.Row():
|
256 |
+
role = gr.Dropdown(choices=roles, label="Role", value="Site Supervisor")
|
257 |
+
supervisor_name = gr.Dropdown(choices=["SUP-056"], label="Supervisor Name", value="SUP-056")
|
258 |
+
project_id = gr.Textbox(label="Project ID", value="PROJ-078", interactive=False)
|
259 |
|
260 |
+
milestones = gr.Textbox(label="Milestones (comma-separated KPIs)", value="Excavation and Foundation Work, Pour the foundation concrete, Set up reinforcement bars for the foundation, Test soil compaction")
|
261 |
+
reflection = gr.Textbox(label="Reflection Log", lines=4, value="The excavation and foundation work was slower than expected due to unexpected weather conditions. We faced some delays because of heavy rainfall. The foundation team had some minor issues with leveling the base but they managed to resolve it in the end.")
|
262 |
|
263 |
with gr.Row():
|
264 |
generate = gr.Button("Generate")
|
|
|
275 |
|
276 |
def handle_generate(role, supervisor_name, project_id, milestones, reflection):
|
277 |
checklist, suggestions = generate_checklist_and_suggestions(role, project_id, milestones, reflection)
|
278 |
+
if not checklist or not suggestions:
|
279 |
+
return "Error generating checklist or suggestions.", "Error generating checklist or suggestions.", None, None, "Error: Generation failed."
|
280 |
pdf_path, pdf_name = save_report_as_pdf(role, supervisor_name, project_id, checklist, suggestions)
|
281 |
supervisor_ai_coaching_response = upload_report_and_create_supervisor_ai_coaching(supervisor_name, project_id, checklist, suggestions, pdf_path, pdf_name)
|
282 |
+
pdf_link_content = f'<a href="file={pdf_path}" download="{pdf_name}">Download PDF</a>'
|
283 |
+
return checklist, suggestions, pdf_path, pdf_link_content, supervisor_ai_coaching_response
|
284 |
|
285 |
generate.click(fn=handle_generate,
|
286 |
inputs=[role, supervisor_name, project_id, milestones, reflection],
|
|
|
292 |
|
293 |
refresh.click(fn=lambda: gr.update(choices=get_roles_from_salesforce()), outputs=role)
|
294 |
|
|
|
295 |
with gr.Tab("📊 Supervisor Dashboard"):
|
296 |
dash_supervisor = gr.Textbox(label="Supervisor Name", placeholder="e.g., SUP-056")
|
297 |
dash_project = gr.Textbox(label="Project ID", placeholder="e.g., PROJ-078")
|
|
|
312 |
|
313 |
if __name__ == "__main__":
|
314 |
app = create_interface()
|
315 |
+
app.launch()
|
|
|
|