pavansuresh commited on
Commit
ff51fda
·
verified ·
1 Parent(s): dfcd327

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +38 -62
app.py CHANGED
@@ -12,19 +12,13 @@ import base64
12
  import io
13
  import logging
14
 
15
- # Set up logging to debug file writing issues
16
  logging.basicConfig(level=logging.INFO)
17
  logger = logging.getLogger(__name__)
18
 
19
- # Initialize PaddleOCR once with updated parameters
20
  ocr_model = PaddleOCR(use_textline_orientation=True, lang='en')
21
 
22
  def analyze_uv_coverage(img, brightness_threshold=150, kernel_size=5, apply_blur=True, adaptive_thresh=False):
23
- """
24
- Analyze UV sterilization coverage by thresholding the grayscale image.
25
- Optional adaptive thresholding and Gaussian blur for noise reduction.
26
- Morphological operations clean the mask for better accuracy.
27
- """
28
  gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
29
 
30
  if apply_blur:
@@ -39,18 +33,14 @@ def analyze_uv_coverage(img, brightness_threshold=150, kernel_size=5, apply_blur
39
  else:
40
  _, binary_mask = cv2.threshold(gray, brightness_threshold, 255, cv2.THRESH_BINARY)
41
 
42
- # Morphological opening (erosion followed by dilation) to remove noise
43
  kernel = np.ones((kernel_size, kernel_size), np.uint8)
44
  binary_mask = cv2.morphologyEx(binary_mask, cv2.MORPH_OPEN, kernel, iterations=1)
45
-
46
- # Morphological closing (dilation followed by erosion) to close small holes inside foreground
47
  binary_mask = cv2.morphologyEx(binary_mask, cv2.MORPH_CLOSE, kernel, iterations=1)
48
 
49
  total_pixels = binary_mask.size
50
  sterilized_pixels = cv2.countNonZero(binary_mask)
51
  coverage_percent = (sterilized_pixels / total_pixels) * 100
52
 
53
- # Create overlay for visualization: Green = sterilized, Red = unsterilized
54
  overlay = img.copy()
55
  overlay[binary_mask == 255] = [0, 255, 0] # Green
56
  overlay[binary_mask == 0] = [0, 0, 255] # Red
@@ -75,7 +65,6 @@ def create_pdf_report(coverage_percent, extracted_texts, annotated_image_path, o
75
  pdf.set_font("Arial", size=10)
76
  if extracted_texts:
77
  for text in extracted_texts:
78
- # Filter out very short or empty OCR texts to improve clarity
79
  if len(text.strip()) > 1:
80
  pdf.multi_cell(0, 8, f"- {text}")
81
  else:
@@ -87,11 +76,7 @@ def create_pdf_report(coverage_percent, extracted_texts, annotated_image_path, o
87
 
88
  pdf.output(output_path)
89
 
90
- # New function to upload image to Salesforce and get URL (adapted from reference code)
91
  def upload_image_to_salesforce(image_path, image_name, record_id=None):
92
- """
93
- Upload the image to Salesforce as a ContentVersion and return a public URL.
94
- """
95
  try:
96
  sf = Salesforce(
97
  username=os.environ['SF_USERNAME'],
@@ -99,15 +84,12 @@ def upload_image_to_salesforce(image_path, image_name, record_id=None):
99
  security_token=os.environ['SF_SECURITY_TOKEN'],
100
  domain=os.environ.get('SF_DOMAIN', 'login')
101
  )
102
- logger.debug(f"Uploading image {image_name} for record ID: {record_id}")
103
 
104
- # Read the image file and encode it as base64
105
  with open(image_path, "rb") as f:
106
  image_data = f.read()
107
 
108
  encoded_image_data = base64.b64encode(image_data).decode('utf-8')
109
 
110
- # Create a ContentVersion in Salesforce
111
  content_version_data = {
112
  "Title": image_name,
113
  "PathOnClient": image_name,
@@ -119,43 +101,28 @@ def upload_image_to_salesforce(image_path, image_name, record_id=None):
119
 
120
  content_version = sf.ContentVersion.create(content_version_data)
121
  content_version_id = content_version["id"]
122
- logger.info(f"Image uploaded to Salesforce with ContentVersion ID: {content_version_id}")
123
 
124
- # Generate the public URL for the image
125
  image_url = f"https://{sf.sf_instance}/sfc/servlet.shepherd/version/download/{content_version_id}"
126
- logger.debug(f"Generated image URL: {image_url}")
127
  return image_url
128
  except Exception as e:
129
  logger.error(f"Error uploading image to Salesforce: {str(e)}", exc_info=True)
130
  raise
131
 
132
  def upload_image_and_get_url(image_path):
133
- """
134
- Upload the image to Salesforce and return a public URL.
135
- """
136
  from datetime import datetime
137
  import uuid
138
 
139
- # Generate a unique filename to avoid conflicts
140
  unique_filename = f"{uuid.uuid4().hex}_{datetime.utcnow().strftime('%Y%m%d_%H%M%S')}.jpg"
141
-
142
- # Upload the image to Salesforce and get the URL
143
- try:
144
- image_url = upload_image_to_salesforce(image_path, unique_filename)
145
- return image_url
146
- except Exception as e:
147
- logger.error(f"Failed to upload image to Salesforce: {e}")
148
- raise
149
 
150
  def save_record_to_salesforce(annotated_image_url, coverage_percent, original_image_pil, compliance_threshold=80):
151
  sf = Salesforce(
152
  username=os.environ['SF_USERNAME'],
153
  password=os.environ['SF_PASSWORD'],
154
  security_token=os.environ['SF_SECURITY_TOKEN'],
155
- domain=os.environ.get('SF_DOMAIN', 'login') # 'test' for sandbox
156
  )
157
 
158
- # Save original image temporarily, upload it, get URL
159
  with tempfile.NamedTemporaryFile(delete=False, suffix=".jpg") as temp_orig_img_file:
160
  original_image_pil.save(temp_orig_img_file.name, format="JPEG")
161
  temp_orig_img_path = temp_orig_img_file.name
@@ -164,8 +131,7 @@ def save_record_to_salesforce(annotated_image_url, coverage_percent, original_im
164
  os.unlink(temp_orig_img_path)
165
 
166
  compliance_status = 'Pass' if coverage_percent >= compliance_threshold else 'Fail'
167
- technician_id = os.environ.get('SF_TECHNICIAN_ID') # Salesforce UserId lookup
168
-
169
  record_name = f"UV Verification - {datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S')}"
170
 
171
  sf.UV_Verification__c.create({
@@ -179,19 +145,17 @@ def save_record_to_salesforce(annotated_image_url, coverage_percent, original_im
179
  })
180
 
181
  def process_image(input_img, brightness_threshold=150):
182
- # Resize the image early to improve processing speed
183
- img = np.array(input_img) # Convert PIL Image to NumPy array
184
- img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR) # Convert from RGB to BGR
185
-
186
- # Resize image to reduce the processing time
187
- max_dim = 640 # Max dimension for resizing
188
  h, w = img.shape[:2]
189
  if max(h, w) > max_dim:
190
  scale = max_dim / max(h, w)
191
  img = cv2.resize(img, (int(w * scale), int(h * scale)))
192
 
193
  start_time = time.time()
194
- ocr_result = ocr_model.predict(img) # Use the `predict` method here instead of `ocr`
195
  ocr_time = time.time() - start_time
196
 
197
  extracted_texts = []
@@ -212,33 +176,45 @@ def process_image(input_img, brightness_threshold=150):
212
  temp_pdf_file.close()
213
  create_pdf_report(coverage_percent, extracted_texts, annotated_img_path, temp_pdf_file.name)
214
 
215
- # Upload annotated image and get URL
216
  annotated_image_url = upload_image_and_get_url(annotated_img_path)
217
-
218
- # Save record in Salesforce
219
  save_record_to_salesforce(annotated_image_url, coverage_percent, input_img)
220
 
221
  annotated_img_rgb = cv2.cvtColor(annotated_img, cv2.COLOR_BGR2RGB)
222
-
223
  report_text = f"UV Sterilization Coverage: {coverage_percent:.2f}%"
224
 
225
- # Clean up temp image file after PDF generation
226
  os.unlink(annotated_img_path)
227
 
228
  return annotated_img_rgb, report_text, temp_pdf_file.name
229
 
230
- iface = gr.Interface(
231
- fn=process_image,
232
- inputs=[gr.Image(type="pil", label="Upload Post-UV Sterilization Image"),
233
- gr.Slider(50, 255, value=150, step=1, label="Brightness Threshold")],
234
- outputs=[gr.Image(type="numpy", label="Annotated Image"),
235
- gr.Textbox(label="UV Sterilization Report", lines=5),
236
- gr.File(label="Download PDF Report")],
237
- title="UV Sterilization Coverage Analyzer",
238
- description="Upload a post-UV sterilization image to analyze surface coverage and generate a compliance report."
239
- )
240
-
241
- iface.queue() # Enable request queuing to improve UX on heavy processing
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
242
 
243
  if __name__ == "__main__":
244
  iface.launch()
 
12
  import io
13
  import logging
14
 
15
+ # Set up logging
16
  logging.basicConfig(level=logging.INFO)
17
  logger = logging.getLogger(__name__)
18
 
 
19
  ocr_model = PaddleOCR(use_textline_orientation=True, lang='en')
20
 
21
  def analyze_uv_coverage(img, brightness_threshold=150, kernel_size=5, apply_blur=True, adaptive_thresh=False):
 
 
 
 
 
22
  gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
23
 
24
  if apply_blur:
 
33
  else:
34
  _, binary_mask = cv2.threshold(gray, brightness_threshold, 255, cv2.THRESH_BINARY)
35
 
 
36
  kernel = np.ones((kernel_size, kernel_size), np.uint8)
37
  binary_mask = cv2.morphologyEx(binary_mask, cv2.MORPH_OPEN, kernel, iterations=1)
 
 
38
  binary_mask = cv2.morphologyEx(binary_mask, cv2.MORPH_CLOSE, kernel, iterations=1)
39
 
40
  total_pixels = binary_mask.size
41
  sterilized_pixels = cv2.countNonZero(binary_mask)
42
  coverage_percent = (sterilized_pixels / total_pixels) * 100
43
 
 
44
  overlay = img.copy()
45
  overlay[binary_mask == 255] = [0, 255, 0] # Green
46
  overlay[binary_mask == 0] = [0, 0, 255] # Red
 
65
  pdf.set_font("Arial", size=10)
66
  if extracted_texts:
67
  for text in extracted_texts:
 
68
  if len(text.strip()) > 1:
69
  pdf.multi_cell(0, 8, f"- {text}")
70
  else:
 
76
 
77
  pdf.output(output_path)
78
 
 
79
  def upload_image_to_salesforce(image_path, image_name, record_id=None):
 
 
 
80
  try:
81
  sf = Salesforce(
82
  username=os.environ['SF_USERNAME'],
 
84
  security_token=os.environ['SF_SECURITY_TOKEN'],
85
  domain=os.environ.get('SF_DOMAIN', 'login')
86
  )
 
87
 
 
88
  with open(image_path, "rb") as f:
89
  image_data = f.read()
90
 
91
  encoded_image_data = base64.b64encode(image_data).decode('utf-8')
92
 
 
93
  content_version_data = {
94
  "Title": image_name,
95
  "PathOnClient": image_name,
 
101
 
102
  content_version = sf.ContentVersion.create(content_version_data)
103
  content_version_id = content_version["id"]
 
104
 
 
105
  image_url = f"https://{sf.sf_instance}/sfc/servlet.shepherd/version/download/{content_version_id}"
 
106
  return image_url
107
  except Exception as e:
108
  logger.error(f"Error uploading image to Salesforce: {str(e)}", exc_info=True)
109
  raise
110
 
111
  def upload_image_and_get_url(image_path):
 
 
 
112
  from datetime import datetime
113
  import uuid
114
 
 
115
  unique_filename = f"{uuid.uuid4().hex}_{datetime.utcnow().strftime('%Y%m%d_%H%M%S')}.jpg"
116
+ return upload_image_to_salesforce(image_path, unique_filename)
 
 
 
 
 
 
 
117
 
118
  def save_record_to_salesforce(annotated_image_url, coverage_percent, original_image_pil, compliance_threshold=80):
119
  sf = Salesforce(
120
  username=os.environ['SF_USERNAME'],
121
  password=os.environ['SF_PASSWORD'],
122
  security_token=os.environ['SF_SECURITY_TOKEN'],
123
+ domain=os.environ.get('SF_DOMAIN', 'login')
124
  )
125
 
 
126
  with tempfile.NamedTemporaryFile(delete=False, suffix=".jpg") as temp_orig_img_file:
127
  original_image_pil.save(temp_orig_img_file.name, format="JPEG")
128
  temp_orig_img_path = temp_orig_img_file.name
 
131
  os.unlink(temp_orig_img_path)
132
 
133
  compliance_status = 'Pass' if coverage_percent >= compliance_threshold else 'Fail'
134
+ technician_id = os.environ.get('SF_TECHNICIAN_ID')
 
135
  record_name = f"UV Verification - {datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S')}"
136
 
137
  sf.UV_Verification__c.create({
 
145
  })
146
 
147
  def process_image(input_img, brightness_threshold=150):
148
+ img = np.array(input_img)
149
+ img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
150
+
151
+ max_dim = 640
 
 
152
  h, w = img.shape[:2]
153
  if max(h, w) > max_dim:
154
  scale = max_dim / max(h, w)
155
  img = cv2.resize(img, (int(w * scale), int(h * scale)))
156
 
157
  start_time = time.time()
158
+ ocr_result = ocr_model.predict(img)
159
  ocr_time = time.time() - start_time
160
 
161
  extracted_texts = []
 
176
  temp_pdf_file.close()
177
  create_pdf_report(coverage_percent, extracted_texts, annotated_img_path, temp_pdf_file.name)
178
 
 
179
  annotated_image_url = upload_image_and_get_url(annotated_img_path)
 
 
180
  save_record_to_salesforce(annotated_image_url, coverage_percent, input_img)
181
 
182
  annotated_img_rgb = cv2.cvtColor(annotated_img, cv2.COLOR_BGR2RGB)
 
183
  report_text = f"UV Sterilization Coverage: {coverage_percent:.2f}%"
184
 
 
185
  os.unlink(annotated_img_path)
186
 
187
  return annotated_img_rgb, report_text, temp_pdf_file.name
188
 
189
+ # === Gradio Interface with Resetting Brightness Threshold ===
190
+
191
+ with gr.Blocks() as iface:
192
+ gr.Markdown("# UV Sterilization Coverage Analyzer")
193
+ gr.Markdown("Upload a post-UV sterilization image to analyze surface coverage and generate a compliance report.")
194
+
195
+ with gr.Row():
196
+ image_input = gr.Image(type="pil", label="Upload Post-UV Sterilization Image")
197
+ brightness_slider = gr.Slider(50, 255, value=150, step=1, label="Brightness Threshold")
198
+
199
+ output_image = gr.Image(type="numpy", label="Annotated Image")
200
+ output_text = gr.Textbox(label="UV Sterilization Report", lines=5)
201
+ output_pdf = gr.File(label="Download PDF Report")
202
+
203
+ clear_btn = gr.Button("Clear and Reset")
204
+
205
+ # Reset slider to default 150 when a new image is uploaded
206
+ image_input.change(fn=lambda _: gr.update(value=150), inputs=image_input, outputs=brightness_slider, queue=False)
207
+
208
+ # Process image on brightness change or after image upload
209
+ brightness_slider.change(fn=process_image, inputs=[image_input, brightness_slider], outputs=[output_image, output_text, output_pdf])
210
+ image_input.upload(fn=process_image, inputs=[image_input, brightness_slider], outputs=[output_image, output_text, output_pdf])
211
+
212
+ # Optional: Clear/reset button
213
+ clear_btn.click(fn=lambda: (None, 150, None, "", None),
214
+ inputs=[],
215
+ outputs=[image_input, brightness_slider, output_image, output_text, output_pdf])
216
+
217
+ iface.queue()
218
 
219
  if __name__ == "__main__":
220
  iface.launch()