Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -109,6 +109,7 @@ def fetch_huggingface_records(dataset_name: str = "imdb"):
|
|
109 |
return []
|
110 |
|
111 |
def fetch_vendor_logs_from_salesforce():
|
|
|
112 |
try:
|
113 |
query = """
|
114 |
SELECT Id, Name, Vendor__c, Work_Completion_Percentage__c, Quality_Percentage__c,
|
@@ -122,17 +123,25 @@ def fetch_vendor_logs_from_salesforce():
|
|
122 |
if not record['Vendor__c']:
|
123 |
logger.warning(f"Skipping Vendor_Log__c record with ID {record['Id']} due to missing Vendor__c")
|
124 |
continue
|
125 |
-
# Handle null
|
126 |
-
delay_days = record.get('Delay_Days__c')
|
127 |
if delay_days is None:
|
128 |
logger.warning(f"Delay_Days__c is null for record ID {record['Id']}, defaulting to 0")
|
129 |
delay_days = 0
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
130 |
log = VendorLog(
|
131 |
vendorLogId=record.get('Id', 'Unknown'),
|
132 |
vendorId=record.get('Name', 'Unknown'),
|
133 |
vendorRecordId=record.get('Vendor__c', 'Unknown'),
|
134 |
-
workDetails=str(
|
135 |
-
qualityReport=str(
|
136 |
incidentLog=record.get('Incident_Severity__c', 'None'),
|
137 |
workCompletionDate=record.get('Work_Completion_Date__c', 'N/A'),
|
138 |
actualCompletionDate=record.get('Actual_Completion_Date__c', 'N/A'),
|
@@ -148,6 +157,7 @@ def fetch_vendor_logs_from_salesforce():
|
|
148 |
raise HTTPException(status_code=500, detail=f"Error fetching vendor logs: {str(e)}")
|
149 |
|
150 |
def calculate_scores(log: VendorLog):
|
|
|
151 |
try:
|
152 |
work_completion_percentage = float(log.workDetails or 0.0)
|
153 |
quality_percentage = float(log.qualityReport or 0.0)
|
@@ -169,6 +179,7 @@ def calculate_scores(log: VendorLog):
|
|
169 |
raise HTTPException(status_code=500, detail=f"Error calculating scores: {str(e)}")
|
170 |
|
171 |
def get_feedback(score: float, metric: str) -> str:
|
|
|
172 |
try:
|
173 |
if score >= 90:
|
174 |
return "Excellent: Maintain this standard"
|
@@ -197,6 +208,7 @@ def get_feedback(score: float, metric: str) -> str:
|
|
197 |
return "Feedback unavailable"
|
198 |
|
199 |
def generate_pdf(vendor_id: str, vendor_log_name: str, scores: dict):
|
|
|
200 |
try:
|
201 |
filename = f'report_{vendor_id}_{datetime.now().strftime("%Y%m%d%H%M%S")}.pdf'
|
202 |
c = canvas.Canvas(filename, pagesize=letter)
|
@@ -219,6 +231,7 @@ def generate_pdf(vendor_id: str, vendor_log_name: str, scores: dict):
|
|
219 |
raise HTTPException(status_code=500, detail=f"Error generating PDF: {str(e)}")
|
220 |
|
221 |
def determine_alert_flag(scores: dict, all_logs: list):
|
|
|
222 |
try:
|
223 |
if not all_logs:
|
224 |
return False
|
@@ -232,6 +245,7 @@ def determine_alert_flag(scores: dict, all_logs: list):
|
|
232 |
return False
|
233 |
|
234 |
def store_scores_in_salesforce(log: VendorLog, scores: dict, pdf_content: bytes, alert_flag: bool):
|
|
|
235 |
try:
|
236 |
score_record = sf.Subcontractor_Performance_Score__c.create({
|
237 |
'Vendor_Log__c': log.vendorLogId,
|
@@ -268,6 +282,7 @@ def store_scores_in_salesforce(log: VendorLog, scores: dict, pdf_content: bytes,
|
|
268 |
|
269 |
@app.post('/score')
|
270 |
async def score_vendor(log: VendorLog, authorization: str = Header(...)):
|
|
|
271 |
try:
|
272 |
logger.info(f"Received Vendor Log: {log}")
|
273 |
if authorization != f'Bearer {API_KEY}':
|
@@ -313,6 +328,7 @@ async def score_vendor(log: VendorLog, authorization: str = Header(...)):
|
|
313 |
|
314 |
@app.get('/', response_class=HTMLResponse)
|
315 |
async def get_dashboard():
|
|
|
316 |
try:
|
317 |
global vendor_logs
|
318 |
fetched_logs = fetch_vendor_logs_from_salesforce()
|
@@ -344,190 +360,4 @@ async def get_dashboard():
|
|
344 |
<title>Subcontractor Performance Score App</title>
|
345 |
<style>
|
346 |
body { font-family: Arial, sans-serif; margin: 20px; }
|
347 |
-
table { width: 100%; border-collapse: collapse; margin-top: 20px; }
|
348 |
-
th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
|
349 |
-
th { background-color: #f2f2f2; }
|
350 |
-
h1, h2 { text-align: center; }
|
351 |
-
.generate-btn {
|
352 |
-
display: block;
|
353 |
-
margin: 20px auto;
|
354 |
-
padding: 10px 20px;
|
355 |
-
background-color: #4CAF50;
|
356 |
-
color: white;
|
357 |
-
border: none;
|
358 |
-
border-radius: 5px;
|
359 |
-
cursor: pointer;
|
360 |
-
font-size: 16px;
|
361 |
-
}
|
362 |
-
.generate-btn:hover { background-color: #45a049; }
|
363 |
-
</style>
|
364 |
-
<script>
|
365 |
-
async function generateScores() {
|
366 |
-
try {
|
367 |
-
const response = await fetch('/generate', { method: 'POST' });
|
368 |
-
if (response.ok) {
|
369 |
-
window.location.reload();
|
370 |
-
} else {
|
371 |
-
alert('Error generating scores');
|
372 |
-
}
|
373 |
-
} catch (error) {
|
374 |
-
alert('Error: ' + error.message);
|
375 |
-
}
|
376 |
-
}
|
377 |
-
</script>
|
378 |
-
</head>
|
379 |
-
<body>
|
380 |
-
<h1>SUBCONTRACTOR PERFORMANCE SCORE APP GENERATOR</h1>
|
381 |
-
<h2>VENDOR LOGS SUBMISSION</h2>
|
382 |
-
<table>
|
383 |
-
<tr>
|
384 |
-
<th>Vendor ID</th>
|
385 |
-
<th>Vendor Log Name</th>
|
386 |
-
<th>Project</th>
|
387 |
-
<th>Work Completion Percentage</th>
|
388 |
-
<th>Quality Percentage</th>
|
389 |
-
<th>Incident Severity</th>
|
390 |
-
<th>Work Completion Date</th>
|
391 |
-
<th>Actual Completion Date</th>
|
392 |
-
<th>Delay Days</th>
|
393 |
-
</tr>
|
394 |
-
"""
|
395 |
-
|
396 |
-
if not vendor_logs:
|
397 |
-
html_content += """
|
398 |
-
<tr>
|
399 |
-
<td colspan="9" style="text-align: center;">No vendor logs available</td>
|
400 |
-
</tr>
|
401 |
-
"""
|
402 |
-
else:
|
403 |
-
for log in vendor_logs:
|
404 |
-
html_content += f"""
|
405 |
-
<tr>
|
406 |
-
<td>{log['vendorId']}</td>
|
407 |
-
<td>{log['vendorLogName']}</td>
|
408 |
-
<td>{log['project']}</td>
|
409 |
-
<td>{log['workDetails']}</td>
|
410 |
-
<td>{log['qualityReport']}</td>
|
411 |
-
<td>{log['incidentLog']}</td>
|
412 |
-
<td>{log['workCompletionDate']}</td>
|
413 |
-
<td>{log['actualCompletionDate']}</td>
|
414 |
-
<td>{log['delayDays']}</td>
|
415 |
-
</tr>
|
416 |
-
"""
|
417 |
-
|
418 |
-
html_content += """
|
419 |
-
</table>
|
420 |
-
<button class="generate-btn" onclick="generateScores()">Generate</button>
|
421 |
-
<h2>SUBCONTRACTOR PERFORMANCE SCORES</h2>
|
422 |
-
<table>
|
423 |
-
<tr>
|
424 |
-
<th>Vendor ID</th>
|
425 |
-
<th>Vendor Log Name</th>
|
426 |
-
<th>Project</th>
|
427 |
-
<th>Quality Score</th>
|
428 |
-
<th>Timeliness Score</th>
|
429 |
-
<th>Safety Score</th>
|
430 |
-
<th>Communication Score</th>
|
431 |
-
<th>Alert Flag</th>
|
432 |
-
</tr>
|
433 |
-
"""
|
434 |
-
|
435 |
-
if not vendor_logs:
|
436 |
-
html_content += """
|
437 |
-
<tr>
|
438 |
-
<td colspan="8" style="text-align: center;">No scores available</td>
|
439 |
-
</tr>
|
440 |
-
"""
|
441 |
-
else:
|
442 |
-
for log in vendor_logs:
|
443 |
-
scores = log['scores']
|
444 |
-
alert_flag = determine_alert_flag(scores, vendor_logs)
|
445 |
-
html_content += f"""
|
446 |
-
<tr>
|
447 |
-
<td>{log['vendorId']}</td>
|
448 |
-
<td>{log['vendorLogName']}</td>
|
449 |
-
<td>{log['project']}</td>
|
450 |
-
<td>{scores['qualityScore']}%</td>
|
451 |
-
<td>{scores['timelinessScore']}%</td>
|
452 |
-
<td>{scores['safetyScore']}%</td>
|
453 |
-
<td>{scores['communicationScore']}%</td>
|
454 |
-
<td>{'Checked' if alert_flag else 'Unchecked'}</td>
|
455 |
-
</tr>
|
456 |
-
"""
|
457 |
-
|
458 |
-
html_content += """
|
459 |
-
</table>
|
460 |
-
</body>
|
461 |
-
</html>
|
462 |
-
"""
|
463 |
-
return HTMLResponse(content=html_content)
|
464 |
-
except Exception as e:
|
465 |
-
logger.error(f"Error in / endpoint: {str(e)}")
|
466 |
-
raise HTTPException(status_code=500, detail=f"Error generating dashboard: {str(e)}")
|
467 |
-
|
468 |
-
@app.post('/generate')
|
469 |
-
async def generate_scores():
|
470 |
-
try:
|
471 |
-
global vendor_logs
|
472 |
-
fetched_logs = fetch_vendor_logs_from_salesforce()
|
473 |
-
vendor_logs = []
|
474 |
-
for log in fetched_logs:
|
475 |
-
scores = calculate_scores(log)
|
476 |
-
pdf_content = generate_pdf(log.vendorId, log.vendorLogName, scores)
|
477 |
-
pdf_base64 = base64.b64encode(pdf_content).decode('utf-8')
|
478 |
-
alert_flag = determine_alert_flag(scores, vendor_logs)
|
479 |
-
store_scores_in_salesforce(log, scores, pdf_content, alert_flag)
|
480 |
-
vendor_logs.append({
|
481 |
-
'vendorLogId': log.vendorLogId,
|
482 |
-
'vendorId': log.vendorId,
|
483 |
-
'vendorLogName': log.vendorLogName,
|
484 |
-
'workDetails': log.workDetails,
|
485 |
-
'qualityReport': log.qualityReport,
|
486 |
-
'incidentLog': log.incidentLog,
|
487 |
-
'workCompletionDate': log.workCompletionDate,
|
488 |
-
'actualCompletionDate': log.actualCompletionDate,
|
489 |
-
'delayDays': log.delayDays,
|
490 |
-
'project': log.project,
|
491 |
-
'scores': scores,
|
492 |
-
'extracted': True
|
493 |
-
})
|
494 |
-
logger.info(f"Generated scores for {len(vendor_logs)} logs")
|
495 |
-
return {"status": "success"}
|
496 |
-
except Exception as e:
|
497 |
-
logger.error(f"Error in /generate endpoint: {str(e)}")
|
498 |
-
raise HTTPException(status_code=500, detail=f"Error generating scores: {str(e)}")
|
499 |
-
|
500 |
-
@app.get('/huggingface-records')
|
501 |
-
async def get_huggingface_records():
|
502 |
-
"""Fetch and return Hugging Face dataset records."""
|
503 |
-
try:
|
504 |
-
records = fetch_huggingface_records()
|
505 |
-
if not records:
|
506 |
-
raise HTTPException(status_code=404, detail="No records fetched from Hugging Face")
|
507 |
-
return {"records": records}
|
508 |
-
except Exception as e:
|
509 |
-
logger.error(f"Error fetching Hugging Face records: {str(e)}")
|
510 |
-
raise HTTPException(status_code=500, detail=f"Failed to fetch Hugging Face records: {str(e)}")
|
511 |
-
|
512 |
-
@app.get('/debug')
|
513 |
-
async def debug_info():
|
514 |
-
"""Return debug information about Salesforce and Hugging Face."""
|
515 |
-
try:
|
516 |
-
log_count = sf.query("SELECT COUNT() FROM Vendor_Log__c")['totalSize']
|
517 |
-
fields = [f['name'] for f in sf.Vendor_Log__c.describe()['fields']]
|
518 |
-
score_fields = [f['name'] for f in sf.Subcontractor_Performance_Score__c.describe()['fields']]
|
519 |
-
hf_records = fetch_huggingface_records()
|
520 |
-
return {
|
521 |
-
"salesforce_connected": True,
|
522 |
-
"vendor_log_count": log_count,
|
523 |
-
"vendor_log_fields": fields,
|
524 |
-
"score_fields": score_fields,
|
525 |
-
"huggingface_records_sample": hf_records
|
526 |
-
}
|
527 |
-
except Exception as e:
|
528 |
-
logger.error(f"Debug error: {str(e)}")
|
529 |
-
return {"salesforce_connected": False, "error": str(e)}
|
530 |
-
|
531 |
-
if __name__ == "__main__":
|
532 |
-
import uvicorn
|
533 |
-
uvicorn.run(app, host="0.0.0.0", port=7860)
|
|
|
109 |
return []
|
110 |
|
111 |
def fetch_vendor_logs_from_salesforce():
|
112 |
+
"""Fetch vendor logs from Salesforce with null handling."""
|
113 |
try:
|
114 |
query = """
|
115 |
SELECT Id, Name, Vendor__c, Work_Completion_Percentage__c, Quality_Percentage__c,
|
|
|
123 |
if not record['Vendor__c']:
|
124 |
logger.warning(f"Skipping Vendor_Log__c record with ID {record['Id']} due to missing Vendor__c")
|
125 |
continue
|
126 |
+
# Handle null values for all fields
|
127 |
+
delay_days = record.get('Delay_Days__c', 0)
|
128 |
if delay_days is None:
|
129 |
logger.warning(f"Delay_Days__c is null for record ID {record['Id']}, defaulting to 0")
|
130 |
delay_days = 0
|
131 |
+
work_completion = record.get('Work_Completion_Percentage__c', 0.0)
|
132 |
+
if work_completion is None:
|
133 |
+
logger.warning(f"Work_Completion_Percentage__c is null for record ID {record['Id']}, defaulting to 0.0")
|
134 |
+
work_completion = 0.0
|
135 |
+
quality_percentage = record.get('Quality_Percentage__c', 0.0)
|
136 |
+
if quality_percentage is None:
|
137 |
+
logger.warning(f"Quality_Percentage__c is null for record ID {record['Id']}, defaulting to 0.0")
|
138 |
+
quality_percentage = 0.0
|
139 |
log = VendorLog(
|
140 |
vendorLogId=record.get('Id', 'Unknown'),
|
141 |
vendorId=record.get('Name', 'Unknown'),
|
142 |
vendorRecordId=record.get('Vendor__c', 'Unknown'),
|
143 |
+
workDetails=str(work_completion),
|
144 |
+
qualityReport=str(quality_percentage),
|
145 |
incidentLog=record.get('Incident_Severity__c', 'None'),
|
146 |
workCompletionDate=record.get('Work_Completion_Date__c', 'N/A'),
|
147 |
actualCompletionDate=record.get('Actual_Completion_Date__c', 'N/A'),
|
|
|
157 |
raise HTTPException(status_code=500, detail=f"Error fetching vendor logs: {str(e)}")
|
158 |
|
159 |
def calculate_scores(log: VendorLog):
|
160 |
+
"""Calculate vendor performance scores."""
|
161 |
try:
|
162 |
work_completion_percentage = float(log.workDetails or 0.0)
|
163 |
quality_percentage = float(log.qualityReport or 0.0)
|
|
|
179 |
raise HTTPException(status_code=500, detail=f"Error calculating scores: {str(e)}")
|
180 |
|
181 |
def get_feedback(score: float, metric: str) -> str:
|
182 |
+
"""Generate feedback based on score and metric."""
|
183 |
try:
|
184 |
if score >= 90:
|
185 |
return "Excellent: Maintain this standard"
|
|
|
208 |
return "Feedback unavailable"
|
209 |
|
210 |
def generate_pdf(vendor_id: str, vendor_log_name: str, scores: dict):
|
211 |
+
"""Generate a PDF report for vendor performance."""
|
212 |
try:
|
213 |
filename = f'report_{vendor_id}_{datetime.now().strftime("%Y%m%d%H%M%S")}.pdf'
|
214 |
c = canvas.Canvas(filename, pagesize=letter)
|
|
|
231 |
raise HTTPException(status_code=500, detail=f"Error generating PDF: {str(e)}")
|
232 |
|
233 |
def determine_alert_flag(scores: dict, all_logs: list):
|
234 |
+
"""Determine if an alert flag should be set."""
|
235 |
try:
|
236 |
if not all_logs:
|
237 |
return False
|
|
|
245 |
return False
|
246 |
|
247 |
def store_scores_in_salesforce(log: VendorLog, scores: dict, pdf_content: bytes, alert_flag: bool):
|
248 |
+
"""Store scores and PDF in Salesforce."""
|
249 |
try:
|
250 |
score_record = sf.Subcontractor_Performance_Score__c.create({
|
251 |
'Vendor_Log__c': log.vendorLogId,
|
|
|
282 |
|
283 |
@app.post('/score')
|
284 |
async def score_vendor(log: VendorLog, authorization: str = Header(...)):
|
285 |
+
"""Score a vendor and generate a PDF report."""
|
286 |
try:
|
287 |
logger.info(f"Received Vendor Log: {log}")
|
288 |
if authorization != f'Bearer {API_KEY}':
|
|
|
328 |
|
329 |
@app.get('/', response_class=HTMLResponse)
|
330 |
async def get_dashboard():
|
331 |
+
"""Render the dashboard with vendor logs and scores."""
|
332 |
try:
|
333 |
global vendor_logs
|
334 |
fetched_logs = fetch_vendor_logs_from_salesforce()
|
|
|
360 |
<title>Subcontractor Performance Score App</title>
|
361 |
<style>
|
362 |
body { font-family: Arial, sans-serif; margin: 20px; }
|
363 |
+
table { width: 100%; border-collapse: collapse; margin-top: 20px; }
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|