pavansuresh commited on
Commit
d78686b
·
verified ·
1 Parent(s): 23a00d7

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +31 -35
app.py CHANGED
@@ -10,35 +10,15 @@ from simple_salesforce import Salesforce
10
  from datetime import datetime
11
  import base64
12
  import io
13
- import boto3
14
- from botocore.exceptions import NoCredentialsError
15
- from dotenv import load_dotenv
16
-
17
- # Load environment variables from .env file
18
- load_dotenv()
19
 
20
  # Initialize PaddleOCR once with updated parameters
21
  ocr_model = PaddleOCR(use_textline_orientation=True, lang='en')
22
 
23
- def upload_image_and_get_url(image_path):
24
- """
25
- Upload image to AWS S3 and return the public URL.
26
- """
27
- s3 = boto3.client('s3')
28
- bucket_name = os.getenv("AWS_S3_BUCKET_NAME")
29
- file_name = os.path.basename(image_path)
30
-
31
- try:
32
- s3.upload_file(image_path, bucket_name, file_name, ExtraArgs={'ACL': 'public-read'})
33
- image_url = f'https://{bucket_name}.s3.amazonaws.com/{file_name}'
34
- return image_url
35
- except NoCredentialsError:
36
- print("Credentials not available")
37
- return None
38
-
39
  def analyze_uv_coverage(img, brightness_threshold=150, kernel_size=5, apply_blur=True, adaptive_thresh=False):
40
  """
41
  Analyze UV sterilization coverage by thresholding the grayscale image.
 
 
42
  """
43
  gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
44
 
@@ -54,21 +34,24 @@ def analyze_uv_coverage(img, brightness_threshold=150, kernel_size=5, apply_blur
54
  else:
55
  _, binary_mask = cv2.threshold(gray, brightness_threshold, 255, cv2.THRESH_BINARY)
56
 
57
- # Morphological operations
58
  kernel = np.ones((kernel_size, kernel_size), np.uint8)
59
  binary_mask = cv2.morphologyEx(binary_mask, cv2.MORPH_OPEN, kernel, iterations=1)
 
 
60
  binary_mask = cv2.morphologyEx(binary_mask, cv2.MORPH_CLOSE, kernel, iterations=1)
61
 
62
  total_pixels = binary_mask.size
63
  sterilized_pixels = cv2.countNonZero(binary_mask)
64
  coverage_percent = (sterilized_pixels / total_pixels) * 100
65
 
66
- # Create overlay for visualization
67
  overlay = img.copy()
68
  overlay[binary_mask == 255] = [0, 255, 0] # Green
69
  overlay[binary_mask == 0] = [0, 0, 255] # Red
70
 
71
  annotated_img = cv2.addWeighted(img, 0.6, overlay, 0.4, 0)
 
72
  return annotated_img, coverage_percent
73
 
74
  def create_pdf_report(coverage_percent, extracted_texts, annotated_image_path, output_path):
@@ -99,12 +82,21 @@ def create_pdf_report(coverage_percent, extracted_texts, annotated_image_path, o
99
 
100
  pdf.output(output_path)
101
 
 
 
 
 
 
 
 
 
 
102
  def save_record_to_salesforce(annotated_image_url, coverage_percent, original_image_pil, compliance_threshold=80):
103
  sf = Salesforce(
104
- username=os.getenv('SF_USERNAME'),
105
- password=os.getenv('SF_PASSWORD'),
106
- security_token=os.getenv('SF_SECURITY_TOKEN'),
107
- domain=os.getenv('SF_DOMAIN', 'login') # 'test' for sandbox
108
  )
109
 
110
  # Save original image temporarily, upload it, get URL
@@ -116,7 +108,7 @@ def save_record_to_salesforce(annotated_image_url, coverage_percent, original_im
116
  os.unlink(temp_orig_img_path)
117
 
118
  compliance_status = 'Pass' if coverage_percent >= compliance_threshold else 'Fail'
119
- technician_id = os.getenv('SF_TECHNICIAN_ID') # Salesforce UserId lookup
120
 
121
  record_name = f"UV Verification - {datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S')}"
122
 
@@ -124,7 +116,7 @@ def save_record_to_salesforce(annotated_image_url, coverage_percent, original_im
124
  'Name': record_name,
125
  'Annotated_Image__c': annotated_image_url,
126
  'Coverage_Percentage__c': round(coverage_percent, 2),
127
- 'Original_Image__c': original_image_url,
128
  'Compliance_Status__c': compliance_status,
129
  'Technician_ID__c': technician_id,
130
  'Verified_On__c': datetime.utcnow().isoformat()
@@ -179,11 +171,15 @@ def process_image(input_img, brightness_threshold=150):
179
 
180
  iface = gr.Interface(
181
  fn=process_image,
182
- inputs=[gr.Image(type="pil", label="Upload Post-UV Sterilization Image"),
183
- gr.Slider(50, 255, value=150, step=1, label="Brightness Threshold")],
184
- outputs=[gr.Image(type="numpy", label="Annotated Image"),
185
- gr.Textbox(label="UV Sterilization Report", lines=5),
186
- gr.File(label="Download PDF Report")],
 
 
 
 
187
  title="UV Sterilization Coverage Analyzer",
188
  description="Upload a post-UV sterilization image to analyze surface coverage and generate a compliance report."
189
  )
 
10
  from datetime import datetime
11
  import base64
12
  import io
 
 
 
 
 
 
13
 
14
  # Initialize PaddleOCR once with updated parameters
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
 
 
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):
 
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
  # Save original image temporarily, upload it, get URL
 
108
  os.unlink(temp_orig_img_path)
109
 
110
  compliance_status = 'Pass' if coverage_percent >= compliance_threshold else 'Fail'
111
+ technician_id = os.environ.get('SF_TECHNICIAN_ID') # Salesforce UserId lookup
112
 
113
  record_name = f"UV Verification - {datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S')}"
114
 
 
116
  'Name': record_name,
117
  'Annotated_Image__c': annotated_image_url,
118
  'Coverage_Percentage__c': round(coverage_percent, 2),
119
+ 'Original_Image__c': original_image_url, # Correct field API name here
120
  'Compliance_Status__c': compliance_status,
121
  'Technician_ID__c': technician_id,
122
  'Verified_On__c': datetime.utcnow().isoformat()
 
171
 
172
  iface = gr.Interface(
173
  fn=process_image,
174
+ inputs=[
175
+ gr.Image(type="pil", label="Upload Post-UV Sterilization Image"),
176
+ gr.Slider(50, 255, value=150, step=1, label="Brightness Threshold")
177
+ ],
178
+ outputs=[
179
+ gr.Image(type="numpy", label="Annotated Image"),
180
+ gr.Textbox(label="UV Sterilization Report", lines=5),
181
+ gr.File(label="Download PDF Report")
182
+ ],
183
  title="UV Sterilization Coverage Analyzer",
184
  description="Upload a post-UV sterilization image to analyze surface coverage and generate a compliance report."
185
  )