Spaces:
Sleeping
Sleeping
Update utils.py
Browse files
utils.py
CHANGED
|
@@ -1,22 +1,17 @@
|
|
| 1 |
import os
|
| 2 |
import cv2
|
| 3 |
import numpy as np
|
|
|
|
|
|
|
| 4 |
import time
|
| 5 |
from reportlab.lib.pagesizes import letter
|
| 6 |
from reportlab.pdfgen import canvas
|
| 7 |
from reportlab.lib.units import inch
|
| 8 |
-
from io import BytesIO
|
| 9 |
-
import base64
|
| 10 |
-
import asyncio
|
| 11 |
-
import logging
|
| 12 |
-
from simple_salesforce import Salesforce
|
| 13 |
-
import tenacity
|
| 14 |
from config import CONFIG
|
| 15 |
-
import dlib
|
| 16 |
|
| 17 |
logger = logging.getLogger(__name__)
|
| 18 |
|
| 19 |
-
|
| 20 |
frame = cv2.resize(frame, CONFIG["TARGET_RESOLUTION"], interpolation=cv2.INTER_LINEAR)
|
| 21 |
frame = cv2.convertScaleAbs(frame, alpha=1.2, beta=20)
|
| 22 |
return frame
|
|
@@ -55,7 +50,7 @@ async def generate_violation_pdf(violations, score, output_dir):
|
|
| 55 |
try:
|
| 56 |
pdf_filename = f"violations_{int(time.time())}.pdf"
|
| 57 |
pdf_path = os.path.join(output_dir, pdf_filename)
|
| 58 |
-
pdf_file =
|
| 59 |
c = canvas.Canvas(pdf_file, pagesize=letter)
|
| 60 |
c.setFont("Helvetica-Bold", 16)
|
| 61 |
c.drawString(1 * inch, 10 * inch, "Worksite Safety Violation Report")
|
|
@@ -80,87 +75,18 @@ async def generate_violation_pdf(violations, score, output_dir):
|
|
| 80 |
c.showPage()
|
| 81 |
y_position = 10 * inch
|
| 82 |
c.save()
|
| 83 |
-
pdf_file.
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
return pdf_path, f"{CONFIG['PUBLIC_URL_BASE']}{pdf_filename}", pdf_file
|
| 87 |
except Exception as e:
|
| 88 |
logger.error(f"Error generating PDF: {e}")
|
| 89 |
-
return "", "", None
|
| 90 |
-
|
| 91 |
-
@tenacity.retry(stop=tenacity.stop_after_attempt(3), wait=tenacity.wait_fixed(2))
|
| 92 |
-
async def connect_to_salesforce():
|
| 93 |
-
sf = Salesforce(**CONFIG["SF_CREDENTIALS"])
|
| 94 |
-
logger.info("Connected to Salesforce")
|
| 95 |
-
return sf
|
| 96 |
-
|
| 97 |
-
async def upload_pdf_to_salesforce(sf, pdf_file, record_id):
|
| 98 |
-
try:
|
| 99 |
-
encoded_pdf = base64.b64encode(pdf_file.getvalue()).decode('utf-8')
|
| 100 |
-
content_version = sf.ContentVersion.create({
|
| 101 |
-
"Title": f"Safety_Violation_Report_{int(time.time())}",
|
| 102 |
-
"PathOnClient": f"safety_violation_{int(time.time())}.pdf",
|
| 103 |
-
"VersionData": encoded_pdf,
|
| 104 |
-
"FirstPublishLocationId": record_id
|
| 105 |
-
})
|
| 106 |
-
result = sf.query(f"SELECT Id, ContentDocumentId FROM ContentVersion WHERE Id = '{content_version['id']}'")
|
| 107 |
-
return f"https://{sf.sf_instance}/sfc/servlet.shepherd/version/download/{content_version['id']}"
|
| 108 |
-
except Exception as e:
|
| 109 |
-
logger.error(f"Error uploading PDF to Salesforce: {e}")
|
| 110 |
return ""
|
| 111 |
|
| 112 |
-
async def push_report_to_salesforce(violations, score, pdf_path, pdf_file):
|
| 113 |
-
try:
|
| 114 |
-
sf = await connect_to_salesforce()
|
| 115 |
-
violations_text = "".join(
|
| 116 |
-
f"Worker {v.get('worker_id', 'Unknown')}: {CONFIG['DISPLAY_NAMES'].get(v.get('violation', 'Unknown'), 'Unknown')} at {v.get('timestamp', 0.0):.2f}s (Conf: {v.get('confidence', 0.0):.2f})\n"
|
| 117 |
-
for v in violations
|
| 118 |
-
) or "No violations detected."
|
| 119 |
-
record_data = {
|
| 120 |
-
"Compliance_Score__c": score,
|
| 121 |
-
"Violations_Found__c": len(violations),
|
| 122 |
-
"Violations_Details__c": violations_text,
|
| 123 |
-
"Status__c": "Pending",
|
| 124 |
-
"PDF_Report_URL__c": f"{CONFIG['PUBLIC_URL_BASE']}{os.path.basename(pdf_path)}" if pdf_path else ""
|
| 125 |
-
}
|
| 126 |
-
record = sf.Safety_Video_Report__c.create(record_data)
|
| 127 |
-
if pdf_file:
|
| 128 |
-
uploaded_url = await upload_pdf_to_salesforce(sf, pdf_file, record["id"])
|
| 129 |
-
if uploaded_url:
|
| 130 |
-
sf.Safety_Video_Report__c.update(record["id"], {"PDF_Report_URL__c": uploaded_url})
|
| 131 |
-
return record["id"], uploaded_url or record_data["PDF_Report_URL__c"]
|
| 132 |
-
except Exception as e:
|
| 133 |
-
logger.error(f"Salesforce record creation failed: {e}")
|
| 134 |
-
return "N/A", "Salesforce integration failed."
|
| 135 |
-
|
| 136 |
-
@tenacity.retry(
|
| 137 |
-
stop=tenacity.stop_after_attempt(3),
|
| 138 |
-
wait=tenacity.wait_fixed(1),
|
| 139 |
-
retry=tenacity.retry_if_exception_type((IOError, OSError))
|
| 140 |
-
)
|
| 141 |
-
def verify_and_open_video(video_path):
|
| 142 |
-
if not os.path.exists(video_path) or os.path.getsize(video_path) == 0:
|
| 143 |
-
raise ValueError(f"Invalid video file: {video_path}")
|
| 144 |
-
cap = cv2.VideoCapture(video_path)
|
| 145 |
-
if not cap.isOpened():
|
| 146 |
-
raise ValueError("Could not open video file.")
|
| 147 |
-
return cap
|
| 148 |
-
|
| 149 |
-
def blur_faces(frame):
|
| 150 |
-
detector = dlib.get_frontal_face_detector()
|
| 151 |
-
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
|
| 152 |
-
faces = detector(gray)
|
| 153 |
-
for face in faces:
|
| 154 |
-
x, y, w, h = face.left(), face.top(), face.width(), face.height()
|
| 155 |
-
roi = frame[y:y+h, x:x+w]
|
| 156 |
-
roi = cv2.GaussianBlur(roi, (23, 23), 30)
|
| 157 |
-
frame[y:y+h, x:x+w] = roi
|
| 158 |
-
return frame
|
| 159 |
-
|
| 160 |
def clean_output_directory(max_age_seconds=86400):
|
| 161 |
output_dir = os.path.join("static", "output")
|
| 162 |
if not os.path.exists(output_dir):
|
| 163 |
return
|
|
|
|
| 164 |
current_time = time.time()
|
| 165 |
for filename in os.listdir(output_dir):
|
| 166 |
file_path = os.path.join(output_dir, filename)
|
|
|
|
| 1 |
import os
|
| 2 |
import cv2
|
| 3 |
import numpy as np
|
| 4 |
+
import asyncio
|
| 5 |
+
import logging
|
| 6 |
import time
|
| 7 |
from reportlab.lib.pagesizes import letter
|
| 8 |
from reportlab.pdfgen import canvas
|
| 9 |
from reportlab.lib.units import inch
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
from config import CONFIG
|
|
|
|
| 11 |
|
| 12 |
logger = logging.getLogger(__name__)
|
| 13 |
|
| 14 |
+
def preprocess_frame(frame):
|
| 15 |
frame = cv2.resize(frame, CONFIG["TARGET_RESOLUTION"], interpolation=cv2.INTER_LINEAR)
|
| 16 |
frame = cv2.convertScaleAbs(frame, alpha=1.2, beta=20)
|
| 17 |
return frame
|
|
|
|
| 50 |
try:
|
| 51 |
pdf_filename = f"violations_{int(time.time())}.pdf"
|
| 52 |
pdf_path = os.path.join(output_dir, pdf_filename)
|
| 53 |
+
pdf_file = open(pdf_path, "wb")
|
| 54 |
c = canvas.Canvas(pdf_file, pagesize=letter)
|
| 55 |
c.setFont("Helvetica-Bold", 16)
|
| 56 |
c.drawString(1 * inch, 10 * inch, "Worksite Safety Violation Report")
|
|
|
|
| 75 |
c.showPage()
|
| 76 |
y_position = 10 * inch
|
| 77 |
c.save()
|
| 78 |
+
pdf_file.close()
|
| 79 |
+
logger.info(f"PDF generated: {pdf_path}")
|
| 80 |
+
return pdf_path
|
|
|
|
| 81 |
except Exception as e:
|
| 82 |
logger.error(f"Error generating PDF: {e}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 83 |
return ""
|
| 84 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 85 |
def clean_output_directory(max_age_seconds=86400):
|
| 86 |
output_dir = os.path.join("static", "output")
|
| 87 |
if not os.path.exists(output_dir):
|
| 88 |
return
|
| 89 |
+
|
| 90 |
current_time = time.time()
|
| 91 |
for filename in os.listdir(output_dir):
|
| 92 |
file_path = os.path.join(output_dir, filename)
|