Komal133 commited on
Commit
76e08f4
·
verified ·
1 Parent(s): 842add9

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +147 -25
app.py CHANGED
@@ -1,23 +1,109 @@
1
- from PIL import ImageFont
 
 
 
 
 
 
 
 
2
 
3
- # Update transform
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4
  transform = transforms.Compose([
5
  transforms.ToTensor(),
6
- transforms.Normalize(mean=[0.485, 0.456, 0.406],
7
- std=[0.229, 0.224, 0.225])
8
  ])
9
 
10
- # Load font for drawing text
11
- try:
12
- font = ImageFont.truetype("arial.ttf", 16)
13
- except IOError:
14
- font = ImageFont.load_default()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
  def detect_defects(image):
17
  if not image:
18
  return None, {"error": "No image provided"}
19
 
20
  try:
 
21
  image_tensor = transform(image).unsqueeze(0)
22
  with torch.no_grad():
23
  predictions = model(image_tensor)
@@ -26,20 +112,14 @@ def detect_defects(image):
26
  draw = ImageDraw.Draw(result_image)
27
  output = []
28
 
29
- boxes = predictions[0]['boxes']
30
- labels = predictions[0]['labels']
31
- scores = predictions[0]['scores']
32
-
33
- for i in range(len(boxes)):
34
- score = scores[i].item()
35
- if score < 0.5:
36
  continue
37
 
38
- box = boxes[i].tolist()
39
- label_idx = labels[i].item()
40
  coco_label = COCO_INSTANCE_CATEGORY_NAMES[label_idx]
41
-
42
- # Use your custom mapping if available
43
  defect_type = map_defect_type(coco_label)
44
  severity = get_severity(score)
45
 
@@ -50,17 +130,59 @@ def detect_defects(image):
50
  "coco_label": coco_label
51
  })
52
 
53
- # Draw bounding box and label
54
  draw.rectangle(box, outline="red", width=3)
55
- draw.text((box[0], box[1] - 15), f"{defect_type}: {severity}", fill="red", font=font)
56
 
57
- if not output:
58
- output = [{"message": "No defects detected above threshold"}]
 
 
 
59
 
60
- # Continue with Salesforce upload code as before...
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61
 
62
  return result_image, output
63
 
64
  except Exception as e:
65
  logging.error(f"Processing failed: {str(e)}")
66
  return None, {"error": f"Processing failed: {str(e)}"}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from PIL import Image, ImageDraw
3
+ import torch
4
+ from torchvision import models, transforms
5
+ from simple_salesforce import Salesforce
6
+ import base64
7
+ from io import BytesIO
8
+ import logging
9
+ from datetime import datetime
10
 
11
+ # Setup logging
12
+ logging.basicConfig(level=logging.INFO)
13
+
14
+ # Salesforce Credentials
15
+ SALESFORCE_USERNAME = "drone@sathkrutha.com"
16
+ SALESFORCE_PASSWORD = "Komal1303@"
17
+ SALESFORCE_SECURITY_TOKEN = "53AWRskW9EjWUsSL5LU6nFTy3"
18
+ SALESFORCE_INSTANCE_URL = "https://sathikrutha-a-dev-ed.my.salesforce.com"
19
+
20
+ # Replace with a valid Site__c record ID from your Salesforce org
21
+ SITE_RECORD_ID = "a003000000xxxxx" # TODO: Update with actual ID from Site__c
22
+
23
+ # Connect to Salesforce
24
+ try:
25
+ sf = Salesforce(
26
+ username=SALESFORCE_USERNAME,
27
+ password=SALESFORCE_PASSWORD,
28
+ security_token=SALESFORCE_SECURITY_TOKEN,
29
+ instance_url=SALESFORCE_INSTANCE_URL
30
+ )
31
+ logging.info("Salesforce connection established.")
32
+ except Exception as e:
33
+ logging.error(f"Failed to connect to Salesforce: {str(e)}")
34
+ raise Exception(f"Failed to connect to Salesforce: {str(e)}")
35
+
36
+ # Load Model
37
+ model = models.detection.fasterrcnn_resnet50_fpn(weights="FasterRCNN_ResNet50_FPN_Weights.COCO_V1")
38
+ model.eval()
39
+
40
+ # Define labels (COCO labels; fine-tune for structural defects)
41
+ COCO_INSTANCE_CATEGORY_NAMES = [
42
+ '__background__', 'person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus',
43
+ 'train', 'truck', 'boat', 'traffic light', 'fire hydrant', 'stop sign', 'parking meter',
44
+ 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep', 'cow', 'elephant', 'bear', 'zebra',
45
+ 'giraffe', 'backpack', 'umbrella', 'handbag', 'tie', 'suitcase', 'frisbee', 'skis',
46
+ 'snowboard', 'sports ball', 'kite', 'baseball bat', 'baseball glove', 'skateboard',
47
+ 'surfboard', 'tennis racket', 'bottle', 'wine glass', 'cup', 'fork', 'knife', 'spoon',
48
+ 'bowl', 'banana', 'apple', 'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza',
49
+ 'donut', 'cake', 'chair', 'couch', 'potted plant', 'bed', 'dining table', 'toilet',
50
+ 'tv', 'laptop', 'mouse', 'remote', 'keyboard', 'cell phone', 'microwave', 'oven',
51
+ 'toaster', 'sink', 'refrigerator', 'book', 'clock', 'vase', 'scissors', 'teddy bear',
52
+ 'hair drier', 'toothbrush'
53
+ ]
54
+
55
+ # Image transformations
56
  transform = transforms.Compose([
57
  transforms.ToTensor(),
 
 
58
  ])
59
 
60
+ # Map model severity to Salesforce picklist values
61
+ def get_severity(score):
62
+ if score >= 0.9:
63
+ return "Critical"
64
+ elif score >= 0.7:
65
+ return "Moderate"
66
+ else:
67
+ return "Minor"
68
+
69
+ # Temporary mapping for COCO labels to structural defects
70
+ COCO_TO_DEFECT_MAPPING = {
71
+ 'car': 'Crack',
72
+ 'person': 'Rust',
73
+ 'bicycle': 'Deformation',
74
+ 'truck': 'Corrosion',
75
+ 'boat': 'Spalling',
76
+ }
77
+
78
+ def map_defect_type(coco_label):
79
+ return COCO_TO_DEFECT_MAPPING.get(coco_label, "Crack")
80
 
81
+ # Function to upload image to Salesforce as ContentVersion
82
+ def upload_image_to_salesforce(image, filename="detected_image.jpg", record_id=None):
83
+ try:
84
+ buffered = BytesIO()
85
+ image.save(buffered, format="JPEG")
86
+ img_data = base64.b64encode(buffered.getvalue()).decode("utf-8")
87
+
88
+ content_version = sf.ContentVersion.create({
89
+ "Title": filename,
90
+ "PathOnClient": filename,
91
+ "VersionData": img_data,
92
+ "FirstPublishLocationId": record_id if record_id else None
93
+ })
94
+ logging.info(f"Image uploaded to Salesforce with ContentVersion ID: {content_version['id']}")
95
+ return content_version["id"]
96
+ except Exception as e:
97
+ logging.error(f"Failed to upload image to Salesforce: {str(e)}")
98
+ raise Exception(f"Failed to upload image to Salesforce: {str(e)}")
99
+
100
+ # Detect defects and integrate with Salesforce
101
  def detect_defects(image):
102
  if not image:
103
  return None, {"error": "No image provided"}
104
 
105
  try:
106
+ # Perform detection
107
  image_tensor = transform(image).unsqueeze(0)
108
  with torch.no_grad():
109
  predictions = model(image_tensor)
 
112
  draw = ImageDraw.Draw(result_image)
113
  output = []
114
 
115
+ for i in range(len(predictions[0]['boxes'])):
116
+ score = predictions[0]['scores'][i].item()
117
+ if score < 0.5: # Lowered threshold for testing
 
 
 
 
118
  continue
119
 
120
+ box = predictions[0]['boxes'][i].tolist()
121
+ label_idx = predictions[0]['labels'][i].item()
122
  coco_label = COCO_INSTANCE_CATEGORY_NAMES[label_idx]
 
 
123
  defect_type = map_defect_type(coco_label)
124
  severity = get_severity(score)
125
 
 
130
  "coco_label": coco_label
131
  })
132
 
 
133
  draw.rectangle(box, outline="red", width=3)
134
+ draw.text((box[0], box[1]), f"{defect_type}: {severity}", fill="red")
135
 
136
+ # Create Salesforce record if detections exist
137
+ if output:
138
+ try:
139
+ current_date = datetime.now().strftime("%Y-%m-%d")
140
+ inspection_name = f"Inspection-{current_date}-{len(output):03d}"
141
 
142
+ # Creating the Salesforce record with updated fields
143
+ inspection_record = sf.Drone_Structure_Inspection__c.create({
144
+ "Inspection_Date__c": current_date,
145
+ "Fault_Type__c": output[0]["type"], # Mapping defect type
146
+ "Severity__c": output[0]["severity"], # Mapping severity
147
+ "Fault_Summary__c": str(output), # Summarizing the defects
148
+ "Status__c": "New", # Default status
149
+ "Annotated_Image_URL__c": "", # Placeholder for image URL
150
+ "Report_PDF__c": "" # Placeholder for report PDF URL
151
+ })
152
+
153
+ record_id = inspection_record.get("id")
154
+ content_version_id = upload_image_to_salesforce(
155
+ result_image,
156
+ filename=f"detected_defect_{record_id}.jpg",
157
+ record_id=record_id
158
+ )
159
+
160
+ if content_version_id:
161
+ sf.Drone_Structure_Inspection__c.update(record_id, {
162
+ "Annotated_Image_URL__c": f"/sfc/servlet.shepherd/version/download/{content_version_id}"
163
+ })
164
+
165
+ output.append({"salesforce_record_id": record_id})
166
+ except Exception as e:
167
+ output.append({"error": f"Failed to create Salesforce record: {str(e)}"})
168
 
169
  return result_image, output
170
 
171
  except Exception as e:
172
  logging.error(f"Processing failed: {str(e)}")
173
  return None, {"error": f"Processing failed: {str(e)}"}
174
+
175
+ # Gradio Interface
176
+ demo = gr.Interface(
177
+ fn=detect_defects,
178
+ inputs=gr.Image(type="pil", label="Upload Drone Image"),
179
+ outputs=[
180
+ gr.Image(label="Detection Result"),
181
+ gr.Textbox(label="Detected Faults with Severity")
182
+ ],
183
+ title="Structural Defect Detection with Salesforce Integration",
184
+ description="Detects objects using Faster R-CNN and stores results in Salesforce. Fine-tune the model for structural defects like cracks, rust, and spalling."
185
+ )
186
+
187
+ if __name__ == "__main__":
188
+ demo.launch()