Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -15,9 +15,16 @@ import io
|
|
| 15 |
ocr_model = PaddleOCR(use_textline_orientation=True, lang='en')
|
| 16 |
|
| 17 |
def analyze_uv_coverage(img, brightness_threshold=150, kernel_size=5, apply_blur=True, adaptive_thresh=False):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
|
|
|
|
| 19 |
if apply_blur:
|
| 20 |
gray = cv2.GaussianBlur(gray, (5, 5), 0)
|
|
|
|
| 21 |
if adaptive_thresh:
|
| 22 |
binary_mask = cv2.adaptiveThreshold(
|
| 23 |
gray, 255,
|
|
@@ -26,66 +33,87 @@ def analyze_uv_coverage(img, brightness_threshold=150, kernel_size=5, apply_blur
|
|
| 26 |
11, 2)
|
| 27 |
else:
|
| 28 |
_, binary_mask = cv2.threshold(gray, brightness_threshold, 255, cv2.THRESH_BINARY)
|
|
|
|
|
|
|
| 29 |
kernel = np.ones((kernel_size, kernel_size), np.uint8)
|
| 30 |
binary_mask = cv2.morphologyEx(binary_mask, cv2.MORPH_OPEN, kernel, iterations=1)
|
|
|
|
|
|
|
| 31 |
binary_mask = cv2.morphologyEx(binary_mask, cv2.MORPH_CLOSE, kernel, iterations=1)
|
|
|
|
| 32 |
total_pixels = binary_mask.size
|
| 33 |
sterilized_pixels = cv2.countNonZero(binary_mask)
|
| 34 |
coverage_percent = (sterilized_pixels / total_pixels) * 100
|
|
|
|
|
|
|
| 35 |
overlay = img.copy()
|
| 36 |
-
overlay[binary_mask == 255] = [0, 255, 0]
|
| 37 |
-
overlay[binary_mask == 0] = [0, 0, 255]
|
|
|
|
| 38 |
annotated_img = cv2.addWeighted(img, 0.6, overlay, 0.4, 0)
|
|
|
|
| 39 |
return annotated_img, coverage_percent
|
| 40 |
|
| 41 |
def create_pdf_report(coverage_percent, extracted_texts, annotated_image_path, output_path):
|
| 42 |
pdf = FPDF()
|
| 43 |
pdf.add_page()
|
|
|
|
| 44 |
pdf.set_font("Arial", 'B', 16)
|
| 45 |
pdf.cell(200, 10, txt="UV Sterilization Report", ln=True, align='C')
|
| 46 |
pdf.ln(10)
|
|
|
|
| 47 |
pdf.set_font("Arial", size=12)
|
| 48 |
pdf.cell(0, 10, f"Sterilization Coverage: {coverage_percent:.2f}%", ln=True)
|
| 49 |
pdf.ln(5)
|
|
|
|
| 50 |
pdf.cell(0, 10, "Extracted Text from Image (OCR):", ln=True)
|
| 51 |
pdf.set_font("Arial", size=10)
|
| 52 |
if extracted_texts:
|
| 53 |
for text in extracted_texts:
|
|
|
|
| 54 |
if len(text.strip()) > 1:
|
| 55 |
pdf.multi_cell(0, 8, f"- {text}")
|
| 56 |
else:
|
| 57 |
pdf.cell(0, 8, "No text detected.", ln=True)
|
|
|
|
| 58 |
pdf.ln(10)
|
| 59 |
pdf.cell(0, 10, "Annotated Image:", ln=True)
|
| 60 |
pdf.image(annotated_image_path, x=10, y=pdf.get_y(), w=pdf.w - 20)
|
|
|
|
| 61 |
pdf.output(output_path)
|
| 62 |
|
| 63 |
def upload_image_and_get_url(image_path):
|
| 64 |
"""
|
| 65 |
-
|
|
|
|
| 66 |
"""
|
| 67 |
-
|
|
|
|
|
|
|
| 68 |
|
| 69 |
def save_record_to_salesforce(annotated_image_url, coverage_percent, original_image_pil, compliance_threshold=80):
|
| 70 |
sf = Salesforce(
|
| 71 |
username=os.environ['SF_USERNAME'],
|
| 72 |
password=os.environ['SF_PASSWORD'],
|
| 73 |
security_token=os.environ['SF_SECURITY_TOKEN'],
|
| 74 |
-
domain=os.environ.get('SF_DOMAIN', 'login')
|
| 75 |
)
|
|
|
|
|
|
|
| 76 |
buffered = io.BytesIO()
|
| 77 |
original_image_pil.save(buffered, format="JPEG")
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
original_img_data_uri = f"data:image/jpeg;base64,{original_img_b64}"
|
| 81 |
compliance_status = 'Pass' if coverage_percent >= compliance_threshold else 'Fail'
|
| 82 |
-
technician_id = os.environ.get('SF_TECHNICIAN_ID')
|
|
|
|
| 83 |
record_name = f"UV Verification - {datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S')}"
|
|
|
|
| 84 |
sf.UV_Verification__c.create({
|
| 85 |
'Name': record_name,
|
| 86 |
-
'Annotated_Image__c': annotated_image_url,
|
| 87 |
'Coverage_Percentage__c': round(coverage_percent, 2),
|
| 88 |
-
'Original_Image__c':
|
| 89 |
'Compliance_Status__c': compliance_status,
|
| 90 |
'Technician_ID__c': technician_id,
|
| 91 |
'Verified_On__c': datetime.utcnow().isoformat()
|
|
@@ -93,14 +121,18 @@ def save_record_to_salesforce(annotated_image_url, coverage_percent, original_im
|
|
| 93 |
|
| 94 |
def process_image(input_img, brightness_threshold=150):
|
| 95 |
img = cv2.cvtColor(np.array(input_img), cv2.COLOR_RGB2BGR)
|
|
|
|
|
|
|
| 96 |
max_dim = 640
|
| 97 |
h, w = img.shape[:2]
|
| 98 |
if max(h, w) > max_dim:
|
| 99 |
scale = max_dim / max(h, w)
|
| 100 |
img = cv2.resize(img, (int(w * scale), int(h * scale)))
|
|
|
|
| 101 |
start_time = time.time()
|
| 102 |
-
ocr_result = ocr_model.ocr(img)
|
| 103 |
ocr_time = time.time() - start_time
|
|
|
|
| 104 |
extracted_texts = []
|
| 105 |
for line in ocr_result:
|
| 106 |
if line:
|
|
@@ -108,18 +140,30 @@ def process_image(input_img, brightness_threshold=150):
|
|
| 108 |
text = word_info[1][0].strip()
|
| 109 |
if len(text) > 1:
|
| 110 |
extracted_texts.append(text)
|
|
|
|
| 111 |
annotated_img, coverage_percent = analyze_uv_coverage(img, brightness_threshold)
|
|
|
|
| 112 |
with tempfile.NamedTemporaryFile(delete=False, suffix=".jpg") as temp_img_file:
|
| 113 |
cv2.imwrite(temp_img_file.name, annotated_img)
|
| 114 |
annotated_img_path = temp_img_file.name
|
|
|
|
| 115 |
temp_pdf_file = tempfile.NamedTemporaryFile(delete=False, suffix=".pdf")
|
| 116 |
temp_pdf_file.close()
|
| 117 |
create_pdf_report(coverage_percent, extracted_texts, annotated_img_path, temp_pdf_file.name)
|
|
|
|
|
|
|
| 118 |
annotated_image_url = upload_image_and_get_url(annotated_img_path)
|
|
|
|
|
|
|
| 119 |
save_record_to_salesforce(annotated_image_url, coverage_percent, input_img)
|
|
|
|
| 120 |
annotated_img_rgb = cv2.cvtColor(annotated_img, cv2.COLOR_BGR2RGB)
|
|
|
|
| 121 |
report_text = f"UV Sterilization Coverage: {coverage_percent:.2f}%"
|
|
|
|
|
|
|
| 122 |
os.unlink(annotated_img_path)
|
|
|
|
| 123 |
return annotated_img_rgb, report_text, temp_pdf_file.name
|
| 124 |
|
| 125 |
iface = gr.Interface(
|
|
@@ -137,7 +181,7 @@ iface = gr.Interface(
|
|
| 137 |
description="Upload a post-UV sterilization image to analyze surface coverage and generate a compliance report."
|
| 138 |
)
|
| 139 |
|
| 140 |
-
iface.queue()
|
| 141 |
|
| 142 |
if __name__ == "__main__":
|
| 143 |
iface.launch()
|
|
|
|
| 15 |
ocr_model = PaddleOCR(use_textline_orientation=True, lang='en')
|
| 16 |
|
| 17 |
def analyze_uv_coverage(img, brightness_threshold=150, kernel_size=5, apply_blur=True, adaptive_thresh=False):
|
| 18 |
+
"""
|
| 19 |
+
Analyze UV sterilization coverage by thresholding the grayscale image.
|
| 20 |
+
Optional adaptive thresholding and Gaussian blur for noise reduction.
|
| 21 |
+
Morphological operations clean the mask for better accuracy.
|
| 22 |
+
"""
|
| 23 |
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
|
| 24 |
+
|
| 25 |
if apply_blur:
|
| 26 |
gray = cv2.GaussianBlur(gray, (5, 5), 0)
|
| 27 |
+
|
| 28 |
if adaptive_thresh:
|
| 29 |
binary_mask = cv2.adaptiveThreshold(
|
| 30 |
gray, 255,
|
|
|
|
| 33 |
11, 2)
|
| 34 |
else:
|
| 35 |
_, binary_mask = cv2.threshold(gray, brightness_threshold, 255, cv2.THRESH_BINARY)
|
| 36 |
+
|
| 37 |
+
# Morphological opening (erosion followed by dilation) to remove noise
|
| 38 |
kernel = np.ones((kernel_size, kernel_size), np.uint8)
|
| 39 |
binary_mask = cv2.morphologyEx(binary_mask, cv2.MORPH_OPEN, kernel, iterations=1)
|
| 40 |
+
|
| 41 |
+
# Morphological closing (dilation followed by erosion) to close small holes inside foreground
|
| 42 |
binary_mask = cv2.morphologyEx(binary_mask, cv2.MORPH_CLOSE, kernel, iterations=1)
|
| 43 |
+
|
| 44 |
total_pixels = binary_mask.size
|
| 45 |
sterilized_pixels = cv2.countNonZero(binary_mask)
|
| 46 |
coverage_percent = (sterilized_pixels / total_pixels) * 100
|
| 47 |
+
|
| 48 |
+
# Create overlay for visualization: Green = sterilized, Red = unsterilized
|
| 49 |
overlay = img.copy()
|
| 50 |
+
overlay[binary_mask == 255] = [0, 255, 0] # Green
|
| 51 |
+
overlay[binary_mask == 0] = [0, 0, 255] # Red
|
| 52 |
+
|
| 53 |
annotated_img = cv2.addWeighted(img, 0.6, overlay, 0.4, 0)
|
| 54 |
+
|
| 55 |
return annotated_img, coverage_percent
|
| 56 |
|
| 57 |
def create_pdf_report(coverage_percent, extracted_texts, annotated_image_path, output_path):
|
| 58 |
pdf = FPDF()
|
| 59 |
pdf.add_page()
|
| 60 |
+
|
| 61 |
pdf.set_font("Arial", 'B', 16)
|
| 62 |
pdf.cell(200, 10, txt="UV Sterilization Report", ln=True, align='C')
|
| 63 |
pdf.ln(10)
|
| 64 |
+
|
| 65 |
pdf.set_font("Arial", size=12)
|
| 66 |
pdf.cell(0, 10, f"Sterilization Coverage: {coverage_percent:.2f}%", ln=True)
|
| 67 |
pdf.ln(5)
|
| 68 |
+
|
| 69 |
pdf.cell(0, 10, "Extracted Text from Image (OCR):", ln=True)
|
| 70 |
pdf.set_font("Arial", size=10)
|
| 71 |
if extracted_texts:
|
| 72 |
for text in extracted_texts:
|
| 73 |
+
# Filter out very short or empty OCR texts to improve clarity
|
| 74 |
if len(text.strip()) > 1:
|
| 75 |
pdf.multi_cell(0, 8, f"- {text}")
|
| 76 |
else:
|
| 77 |
pdf.cell(0, 8, "No text detected.", ln=True)
|
| 78 |
+
|
| 79 |
pdf.ln(10)
|
| 80 |
pdf.cell(0, 10, "Annotated Image:", ln=True)
|
| 81 |
pdf.image(annotated_image_path, x=10, y=pdf.get_y(), w=pdf.w - 20)
|
| 82 |
+
|
| 83 |
pdf.output(output_path)
|
| 84 |
|
| 85 |
def upload_image_and_get_url(image_path):
|
| 86 |
"""
|
| 87 |
+
TODO: Implement your image upload to public storage here.
|
| 88 |
+
For now, returns a placeholder URL.
|
| 89 |
"""
|
| 90 |
+
# Example: upload to AWS S3, Azure Blob Storage, or other service
|
| 91 |
+
# Return the public URL to the uploaded image
|
| 92 |
+
return "https://example.com/path/to/your/annotated_image.jpg"
|
| 93 |
|
| 94 |
def save_record_to_salesforce(annotated_image_url, coverage_percent, original_image_pil, compliance_threshold=80):
|
| 95 |
sf = Salesforce(
|
| 96 |
username=os.environ['SF_USERNAME'],
|
| 97 |
password=os.environ['SF_PASSWORD'],
|
| 98 |
security_token=os.environ['SF_SECURITY_TOKEN'],
|
| 99 |
+
domain=os.environ.get('SF_DOMAIN', 'login') # 'test' for sandbox
|
| 100 |
)
|
| 101 |
+
|
| 102 |
+
# Encode original image to base64 string for storage
|
| 103 |
buffered = io.BytesIO()
|
| 104 |
original_image_pil.save(buffered, format="JPEG")
|
| 105 |
+
original_img_b64 = base64.b64encode(buffered.getvalue()).decode('utf-8')
|
| 106 |
+
|
|
|
|
| 107 |
compliance_status = 'Pass' if coverage_percent >= compliance_threshold else 'Fail'
|
| 108 |
+
technician_id = os.environ.get('SF_TECHNICIAN_ID') # Salesforce UserId lookup
|
| 109 |
+
|
| 110 |
record_name = f"UV Verification - {datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S')}"
|
| 111 |
+
|
| 112 |
sf.UV_Verification__c.create({
|
| 113 |
'Name': record_name,
|
| 114 |
+
'Annotated_Image__c': annotated_image_url,
|
| 115 |
'Coverage_Percentage__c': round(coverage_percent, 2),
|
| 116 |
+
'Original_Image__c': original_img_b64,
|
| 117 |
'Compliance_Status__c': compliance_status,
|
| 118 |
'Technician_ID__c': technician_id,
|
| 119 |
'Verified_On__c': datetime.utcnow().isoformat()
|
|
|
|
| 121 |
|
| 122 |
def process_image(input_img, brightness_threshold=150):
|
| 123 |
img = cv2.cvtColor(np.array(input_img), cv2.COLOR_RGB2BGR)
|
| 124 |
+
|
| 125 |
+
# Resize large images for faster processing, preserving aspect ratio
|
| 126 |
max_dim = 640
|
| 127 |
h, w = img.shape[:2]
|
| 128 |
if max(h, w) > max_dim:
|
| 129 |
scale = max_dim / max(h, w)
|
| 130 |
img = cv2.resize(img, (int(w * scale), int(h * scale)))
|
| 131 |
+
|
| 132 |
start_time = time.time()
|
| 133 |
+
ocr_result = ocr_model.ocr(img)
|
| 134 |
ocr_time = time.time() - start_time
|
| 135 |
+
|
| 136 |
extracted_texts = []
|
| 137 |
for line in ocr_result:
|
| 138 |
if line:
|
|
|
|
| 140 |
text = word_info[1][0].strip()
|
| 141 |
if len(text) > 1:
|
| 142 |
extracted_texts.append(text)
|
| 143 |
+
|
| 144 |
annotated_img, coverage_percent = analyze_uv_coverage(img, brightness_threshold)
|
| 145 |
+
|
| 146 |
with tempfile.NamedTemporaryFile(delete=False, suffix=".jpg") as temp_img_file:
|
| 147 |
cv2.imwrite(temp_img_file.name, annotated_img)
|
| 148 |
annotated_img_path = temp_img_file.name
|
| 149 |
+
|
| 150 |
temp_pdf_file = tempfile.NamedTemporaryFile(delete=False, suffix=".pdf")
|
| 151 |
temp_pdf_file.close()
|
| 152 |
create_pdf_report(coverage_percent, extracted_texts, annotated_img_path, temp_pdf_file.name)
|
| 153 |
+
|
| 154 |
+
# Upload annotated image and get URL
|
| 155 |
annotated_image_url = upload_image_and_get_url(annotated_img_path)
|
| 156 |
+
|
| 157 |
+
# Save record in Salesforce
|
| 158 |
save_record_to_salesforce(annotated_image_url, coverage_percent, input_img)
|
| 159 |
+
|
| 160 |
annotated_img_rgb = cv2.cvtColor(annotated_img, cv2.COLOR_BGR2RGB)
|
| 161 |
+
|
| 162 |
report_text = f"UV Sterilization Coverage: {coverage_percent:.2f}%"
|
| 163 |
+
|
| 164 |
+
# Clean up temp image file after PDF generation
|
| 165 |
os.unlink(annotated_img_path)
|
| 166 |
+
|
| 167 |
return annotated_img_rgb, report_text, temp_pdf_file.name
|
| 168 |
|
| 169 |
iface = gr.Interface(
|
|
|
|
| 181 |
description="Upload a post-UV sterilization image to analyze surface coverage and generate a compliance report."
|
| 182 |
)
|
| 183 |
|
| 184 |
+
iface.queue() # Enable request queuing to improve UX on heavy processing
|
| 185 |
|
| 186 |
if __name__ == "__main__":
|
| 187 |
iface.launch()
|