Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -20,7 +20,6 @@ missing_vars = [var for var in required_env_vars if not os.getenv(var)]
|
|
20 |
if missing_vars:
|
21 |
raise EnvironmentError(f"Missing required environment variables: {missing_vars}")
|
22 |
|
23 |
-
# Load model and tokenizer
|
24 |
model_name = "distilgpt2"
|
25 |
tokenizer = AutoTokenizer.from_pretrained(model_name, use_fast=True)
|
26 |
model = AutoModelForCausalLM.from_pretrained(model_name, low_cpu_mem_usage=True)
|
@@ -30,7 +29,6 @@ if tokenizer.pad_token is None:
|
|
30 |
tokenizer.pad_token_id = tokenizer.convert_tokens_to_ids(tokenizer.pad_token)
|
31 |
model.config.pad_token_id = tokenizer.pad_token_id
|
32 |
|
33 |
-
# Prompt template
|
34 |
PROMPT_TEMPLATE = """You are an AI assistant for construction supervisors. Given the role, project, milestones, and a reflection log, generate:
|
35 |
|
36 |
1. A Daily Checklist with clear and concise tasks based on the role and milestones.
|
@@ -99,31 +97,23 @@ def upload_pdf_to_salesforce_and_update_link(supervisor_name, project_id, pdf_pa
|
|
99 |
security_token=os.getenv('SF_SECURITY_TOKEN'),
|
100 |
domain=os.getenv('SF_DOMAIN', 'login')
|
101 |
)
|
102 |
-
|
103 |
with open(pdf_path, "rb") as f:
|
104 |
encoded = base64.b64encode(f.read()).decode()
|
105 |
-
|
106 |
content = sf.ContentVersion.create({
|
107 |
'Title': pdf_name,
|
108 |
'PathOnClient': pdf_name,
|
109 |
'VersionData': encoded
|
110 |
})
|
111 |
-
|
112 |
content_id = content['id']
|
113 |
download_url = f"https://{sf.sf_instance}/sfc/servlet.shepherd/version/download/{content_id}"
|
114 |
-
|
115 |
query = sf.query(f"SELECT Id FROM Supervisor__c WHERE Name = '{supervisor_name}' LIMIT 1")
|
116 |
if query['totalSize'] == 0:
|
117 |
return ""
|
118 |
-
|
119 |
supervisor_id = query['records'][0]['Id']
|
120 |
-
|
121 |
project_query = sf.query(f"SELECT Id FROM Project__c WHERE Name = '{project_id}' LIMIT 1")
|
122 |
if project_query['totalSize'] == 0:
|
123 |
return ""
|
124 |
-
|
125 |
project_id_sf = project_query['records'][0]['Id']
|
126 |
-
|
127 |
sf.Supervisor_AI_Coaching__c.create({
|
128 |
'Project_ID__c': project_id_sf,
|
129 |
'Supervisor_ID__c': supervisor_id,
|
@@ -131,10 +121,8 @@ def upload_pdf_to_salesforce_and_update_link(supervisor_name, project_id, pdf_pa
|
|
131 |
'Suggested_Tips__c': suggestions,
|
132 |
'Download_Link__c': download_url
|
133 |
})
|
134 |
-
|
135 |
return download_url
|
136 |
-
|
137 |
-
except Exception as e:
|
138 |
return ""
|
139 |
|
140 |
def get_roles_from_salesforce():
|
@@ -147,7 +135,7 @@ def get_roles_from_salesforce():
|
|
147 |
)
|
148 |
result = sf.query("SELECT Role__c FROM Supervisor__c WHERE Role__c != NULL")
|
149 |
return list(set(record['Role__c'] for record in result['records']))
|
150 |
-
except
|
151 |
return []
|
152 |
|
153 |
def get_supervisor_name_by_role(role):
|
@@ -160,7 +148,7 @@ def get_supervisor_name_by_role(role):
|
|
160 |
)
|
161 |
result = sf.query(f"SELECT Name FROM Supervisor__c WHERE Role__c = '{role}'")
|
162 |
return [record['Name'] for record in result['records']]
|
163 |
-
except
|
164 |
return []
|
165 |
|
166 |
def get_projects_for_supervisor(supervisor_name):
|
@@ -177,7 +165,7 @@ def get_projects_for_supervisor(supervisor_name):
|
|
177 |
supervisor_id = result['records'][0]['Id']
|
178 |
project_result = sf.query(f"SELECT Name FROM Project__c WHERE Supervisor_ID__c = '{supervisor_id}' LIMIT 1")
|
179 |
return project_result['records'][0]['Name'] if project_result['totalSize'] > 0 else ""
|
180 |
-
except
|
181 |
return ""
|
182 |
|
183 |
def get_dashboard_data_from_salesforce(supervisor_name, project_id):
|
@@ -208,17 +196,6 @@ def get_dashboard_data_from_salesforce(supervisor_name, project_id):
|
|
208 |
except Exception as e:
|
209 |
return f"Error loading dashboard: {e}", "", "", ""
|
210 |
|
211 |
-
# Function to compare start and end date
|
212 |
-
def compare_dates(start_date, end_date):
|
213 |
-
current_date = datetime.datetime.now()
|
214 |
-
if current_date >= end_date:
|
215 |
-
return "Completed"
|
216 |
-
elif current_date < start_date:
|
217 |
-
return "Not Started"
|
218 |
-
else:
|
219 |
-
return "In Progress"
|
220 |
-
|
221 |
-
# Render bar chart (updated)
|
222 |
def render_bar_chart(completed, total):
|
223 |
fig, ax = plt.subplots(figsize=(4, 3))
|
224 |
ax.bar(["Completed", "Remaining"], [completed, max(0, total - completed)], color=["green", "gray"])
|
@@ -231,45 +208,47 @@ def render_bar_chart(completed, total):
|
|
231 |
encoded = base64.b64encode(buf.read()).decode("utf-8")
|
232 |
return f"<img src='data:image/png;base64,{encoded}'/>"
|
233 |
|
234 |
-
|
235 |
-
|
236 |
-
|
237 |
-
|
238 |
-
|
239 |
-
|
240 |
-
|
241 |
-
|
242 |
-
|
243 |
-
|
244 |
-
|
245 |
-
|
246 |
-
|
247 |
-
|
248 |
-
|
249 |
-
|
250 |
-
|
251 |
-
|
252 |
-
|
253 |
-
|
254 |
-
|
255 |
-
|
256 |
-
|
257 |
-
|
258 |
-
|
259 |
-
|
260 |
-
|
261 |
-
|
262 |
-
|
263 |
-
|
264 |
-
|
265 |
-
|
266 |
-
|
267 |
-
|
268 |
-
|
269 |
-
|
270 |
-
|
271 |
-
|
272 |
-
|
|
|
|
|
273 |
def create_interface():
|
274 |
roles = get_roles_from_salesforce()
|
275 |
with gr.Blocks(theme="soft", css=".footer { display: none; }") as demo:
|
|
|
20 |
if missing_vars:
|
21 |
raise EnvironmentError(f"Missing required environment variables: {missing_vars}")
|
22 |
|
|
|
23 |
model_name = "distilgpt2"
|
24 |
tokenizer = AutoTokenizer.from_pretrained(model_name, use_fast=True)
|
25 |
model = AutoModelForCausalLM.from_pretrained(model_name, low_cpu_mem_usage=True)
|
|
|
29 |
tokenizer.pad_token_id = tokenizer.convert_tokens_to_ids(tokenizer.pad_token)
|
30 |
model.config.pad_token_id = tokenizer.pad_token_id
|
31 |
|
|
|
32 |
PROMPT_TEMPLATE = """You are an AI assistant for construction supervisors. Given the role, project, milestones, and a reflection log, generate:
|
33 |
|
34 |
1. A Daily Checklist with clear and concise tasks based on the role and milestones.
|
|
|
97 |
security_token=os.getenv('SF_SECURITY_TOKEN'),
|
98 |
domain=os.getenv('SF_DOMAIN', 'login')
|
99 |
)
|
|
|
100 |
with open(pdf_path, "rb") as f:
|
101 |
encoded = base64.b64encode(f.read()).decode()
|
|
|
102 |
content = sf.ContentVersion.create({
|
103 |
'Title': pdf_name,
|
104 |
'PathOnClient': pdf_name,
|
105 |
'VersionData': encoded
|
106 |
})
|
|
|
107 |
content_id = content['id']
|
108 |
download_url = f"https://{sf.sf_instance}/sfc/servlet.shepherd/version/download/{content_id}"
|
|
|
109 |
query = sf.query(f"SELECT Id FROM Supervisor__c WHERE Name = '{supervisor_name}' LIMIT 1")
|
110 |
if query['totalSize'] == 0:
|
111 |
return ""
|
|
|
112 |
supervisor_id = query['records'][0]['Id']
|
|
|
113 |
project_query = sf.query(f"SELECT Id FROM Project__c WHERE Name = '{project_id}' LIMIT 1")
|
114 |
if project_query['totalSize'] == 0:
|
115 |
return ""
|
|
|
116 |
project_id_sf = project_query['records'][0]['Id']
|
|
|
117 |
sf.Supervisor_AI_Coaching__c.create({
|
118 |
'Project_ID__c': project_id_sf,
|
119 |
'Supervisor_ID__c': supervisor_id,
|
|
|
121 |
'Suggested_Tips__c': suggestions,
|
122 |
'Download_Link__c': download_url
|
123 |
})
|
|
|
124 |
return download_url
|
125 |
+
except:
|
|
|
126 |
return ""
|
127 |
|
128 |
def get_roles_from_salesforce():
|
|
|
135 |
)
|
136 |
result = sf.query("SELECT Role__c FROM Supervisor__c WHERE Role__c != NULL")
|
137 |
return list(set(record['Role__c'] for record in result['records']))
|
138 |
+
except:
|
139 |
return []
|
140 |
|
141 |
def get_supervisor_name_by_role(role):
|
|
|
148 |
)
|
149 |
result = sf.query(f"SELECT Name FROM Supervisor__c WHERE Role__c = '{role}'")
|
150 |
return [record['Name'] for record in result['records']]
|
151 |
+
except:
|
152 |
return []
|
153 |
|
154 |
def get_projects_for_supervisor(supervisor_name):
|
|
|
165 |
supervisor_id = result['records'][0]['Id']
|
166 |
project_result = sf.query(f"SELECT Name FROM Project__c WHERE Supervisor_ID__c = '{supervisor_id}' LIMIT 1")
|
167 |
return project_result['records'][0]['Name'] if project_result['totalSize'] > 0 else ""
|
168 |
+
except:
|
169 |
return ""
|
170 |
|
171 |
def get_dashboard_data_from_salesforce(supervisor_name, project_id):
|
|
|
196 |
except Exception as e:
|
197 |
return f"Error loading dashboard: {e}", "", "", ""
|
198 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
199 |
def render_bar_chart(completed, total):
|
200 |
fig, ax = plt.subplots(figsize=(4, 3))
|
201 |
ax.bar(["Completed", "Remaining"], [completed, max(0, total - completed)], color=["green", "gray"])
|
|
|
208 |
encoded = base64.b64encode(buf.read()).decode("utf-8")
|
209 |
return f"<img src='data:image/png;base64,{encoded}'/>"
|
210 |
|
211 |
+
def generate_outputs(role, supervisor_name, project_id, milestones, reflection):
|
212 |
+
if not all([role, supervisor_name, project_id, milestones, reflection]):
|
213 |
+
return "β Please fill all fields.", "", None, ""
|
214 |
+
prompt = PROMPT_TEMPLATE.format(role=role, project_id=project_id, milestones=milestones, reflection=reflection)
|
215 |
+
inputs = tokenizer(prompt, return_tensors="pt", padding=True, truncation=True, max_length=512)
|
216 |
+
try:
|
217 |
+
with torch.no_grad():
|
218 |
+
outputs = model.generate(
|
219 |
+
inputs['input_ids'],
|
220 |
+
max_new_tokens=150,
|
221 |
+
no_repeat_ngram_size=2,
|
222 |
+
do_sample=True,
|
223 |
+
top_p=0.9,
|
224 |
+
temperature=0.7,
|
225 |
+
pad_token_id=tokenizer.pad_token_id
|
226 |
+
)
|
227 |
+
result = tokenizer.decode(outputs[0], skip_special_tokens=True)
|
228 |
+
except:
|
229 |
+
return "", "", None, ""
|
230 |
+
|
231 |
+
def extract_between(text, start, end):
|
232 |
+
s = text.find(start)
|
233 |
+
e = text.find(end, s) if end else len(text)
|
234 |
+
return text[s + len(start):e].strip() if s != -1 else ""
|
235 |
+
|
236 |
+
checklist = extract_between(result, "Checklist:\n", "Suggestions:")
|
237 |
+
suggestions = extract_between(result, "Suggestions:\n", None)
|
238 |
+
|
239 |
+
if not checklist.strip():
|
240 |
+
checklist = "- Perform daily safety inspection"
|
241 |
+
if not suggestions.strip():
|
242 |
+
suggestions = "- Monitor team coordination\n- Review safety protocols with the team"
|
243 |
+
|
244 |
+
pdf_path, pdf_name = save_report_as_pdf(role, supervisor_name, project_id, checklist, suggestions)
|
245 |
+
pdf_url = upload_pdf_to_salesforce_and_update_link(supervisor_name, project_id, pdf_path, pdf_name, checklist, suggestions)
|
246 |
+
|
247 |
+
if pdf_url:
|
248 |
+
suggestions += f"\n\nπ [Download PDF Report]({pdf_url})"
|
249 |
+
|
250 |
+
return checklist, suggestions, pdf_path, pdf_name
|
251 |
+
|
252 |
def create_interface():
|
253 |
roles = get_roles_from_salesforce()
|
254 |
with gr.Blocks(theme="soft", css=".footer { display: none; }") as demo:
|