Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -15,16 +15,9 @@ 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 |
-
"""
|
| 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,89 +26,64 @@ def analyze_uv_coverage(img, brightness_threshold=150, kernel_size=5, apply_blur
|
|
| 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]
|
| 51 |
-
overlay[binary_mask == 0] = [0, 0, 255]
|
| 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 |
-
|
| 88 |
-
and return as a valid URL string to store in Salesforce.
|
| 89 |
"""
|
| 90 |
-
|
| 91 |
-
img_bytes = img_file.read()
|
| 92 |
-
encoded_str = base64.b64encode(img_bytes).decode('utf-8')
|
| 93 |
-
data_uri = f"data:image/jpeg;base64,{encoded_str}"
|
| 94 |
-
return data_uri
|
| 95 |
|
| 96 |
def save_record_to_salesforce(annotated_image_url, coverage_percent, original_image_pil, compliance_threshold=80):
|
| 97 |
sf = Salesforce(
|
| 98 |
username=os.environ['SF_USERNAME'],
|
| 99 |
password=os.environ['SF_PASSWORD'],
|
| 100 |
security_token=os.environ['SF_SECURITY_TOKEN'],
|
| 101 |
-
domain=os.environ.get('SF_DOMAIN', 'login')
|
| 102 |
)
|
| 103 |
-
|
| 104 |
-
# Encode original image to base64 data URI string for storage
|
| 105 |
buffered = io.BytesIO()
|
| 106 |
original_image_pil.save(buffered, format="JPEG")
|
| 107 |
original_img_bytes = buffered.getvalue()
|
| 108 |
original_img_b64 = base64.b64encode(original_img_bytes).decode('utf-8')
|
| 109 |
original_img_data_uri = f"data:image/jpeg;base64,{original_img_b64}"
|
| 110 |
-
|
| 111 |
compliance_status = 'Pass' if coverage_percent >= compliance_threshold else 'Fail'
|
| 112 |
-
technician_id = os.environ.get('SF_TECHNICIAN_ID')
|
| 113 |
-
|
| 114 |
record_name = f"UV Verification - {datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S')}"
|
| 115 |
-
|
| 116 |
sf.UV_Verification__c.create({
|
| 117 |
'Name': record_name,
|
| 118 |
-
'Annotated_Image__c': annotated_image_url,
|
| 119 |
'Coverage_Percentage__c': round(coverage_percent, 2),
|
| 120 |
'Original_Image__c': original_img_data_uri,
|
| 121 |
'Compliance_Status__c': compliance_status,
|
|
@@ -125,18 +93,14 @@ def save_record_to_salesforce(annotated_image_url, coverage_percent, original_im
|
|
| 125 |
|
| 126 |
def process_image(input_img, brightness_threshold=150):
|
| 127 |
img = cv2.cvtColor(np.array(input_img), cv2.COLOR_RGB2BGR)
|
| 128 |
-
|
| 129 |
-
# Resize large images for faster processing, preserving aspect ratio
|
| 130 |
max_dim = 640
|
| 131 |
h, w = img.shape[:2]
|
| 132 |
if max(h, w) > max_dim:
|
| 133 |
scale = max_dim / max(h, w)
|
| 134 |
img = cv2.resize(img, (int(w * scale), int(h * scale)))
|
| 135 |
-
|
| 136 |
start_time = time.time()
|
| 137 |
-
ocr_result = ocr_model.ocr(img)
|
| 138 |
ocr_time = time.time() - start_time
|
| 139 |
-
|
| 140 |
extracted_texts = []
|
| 141 |
for line in ocr_result:
|
| 142 |
if line:
|
|
@@ -144,30 +108,18 @@ def process_image(input_img, brightness_threshold=150):
|
|
| 144 |
text = word_info[1][0].strip()
|
| 145 |
if len(text) > 1:
|
| 146 |
extracted_texts.append(text)
|
| 147 |
-
|
| 148 |
annotated_img, coverage_percent = analyze_uv_coverage(img, brightness_threshold)
|
| 149 |
-
|
| 150 |
with tempfile.NamedTemporaryFile(delete=False, suffix=".jpg") as temp_img_file:
|
| 151 |
cv2.imwrite(temp_img_file.name, annotated_img)
|
| 152 |
annotated_img_path = temp_img_file.name
|
| 153 |
-
|
| 154 |
temp_pdf_file = tempfile.NamedTemporaryFile(delete=False, suffix=".pdf")
|
| 155 |
temp_pdf_file.close()
|
| 156 |
create_pdf_report(coverage_percent, extracted_texts, annotated_img_path, temp_pdf_file.name)
|
| 157 |
-
|
| 158 |
-
# Upload annotated image and get URL (now base64 data URI)
|
| 159 |
annotated_image_url = upload_image_and_get_url(annotated_img_path)
|
| 160 |
-
|
| 161 |
-
# Save record in Salesforce
|
| 162 |
save_record_to_salesforce(annotated_image_url, coverage_percent, input_img)
|
| 163 |
-
|
| 164 |
annotated_img_rgb = cv2.cvtColor(annotated_img, cv2.COLOR_BGR2RGB)
|
| 165 |
-
|
| 166 |
report_text = f"UV Sterilization Coverage: {coverage_percent:.2f}%"
|
| 167 |
-
|
| 168 |
-
# Clean up temp image file after PDF generation
|
| 169 |
os.unlink(annotated_img_path)
|
| 170 |
-
|
| 171 |
return annotated_img_rgb, report_text, temp_pdf_file.name
|
| 172 |
|
| 173 |
iface = gr.Interface(
|
|
@@ -185,7 +137,7 @@ iface = gr.Interface(
|
|
| 185 |
description="Upload a post-UV sterilization image to analyze surface coverage and generate a compliance report."
|
| 186 |
)
|
| 187 |
|
| 188 |
-
iface.queue()
|
| 189 |
|
| 190 |
if __name__ == "__main__":
|
| 191 |
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 |
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 |
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 |
+
Return empty string because storing base64 data URI exceeds Salesforce field limit.
|
|
|
|
| 66 |
"""
|
| 67 |
+
return ""
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
original_img_bytes = buffered.getvalue()
|
| 79 |
original_img_b64 = base64.b64encode(original_img_bytes).decode('utf-8')
|
| 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, # will be empty string here
|
| 87 |
'Coverage_Percentage__c': round(coverage_percent, 2),
|
| 88 |
'Original_Image__c': original_img_data_uri,
|
| 89 |
'Compliance_Status__c': compliance_status,
|
|
|
|
| 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) # Warning about deprecated method remains; you can ignore or update PaddleOCR package
|
| 103 |
ocr_time = time.time() - start_time
|
|
|
|
| 104 |
extracted_texts = []
|
| 105 |
for line in ocr_result:
|
| 106 |
if line:
|
|
|
|
| 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 |
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()
|