Komal133 commited on
Commit
2c5f171
·
verified ·
1 Parent(s): 2c88ff4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +152 -27
app.py CHANGED
@@ -1,28 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  def detect_defects(image):
2
- if not image:
3
- return None, {"error": "No image provided"}
4
 
5
  try:
6
- # Perform detection
7
  image_tensor = transform(image).unsqueeze(0)
 
8
  with torch.no_grad():
9
  predictions = model(image_tensor)
10
 
 
11
  result_image = image.copy()
12
  draw = ImageDraw.Draw(result_image)
13
- output = []
14
 
 
 
 
 
 
 
 
15
  for i in range(len(predictions[0]['boxes'])):
16
  score = predictions[0]['scores'][i].item()
17
- if score < 0.5: # Increased threshold for better quality detections
18
  continue
19
 
20
  box = predictions[0]['boxes'][i].tolist()
21
  label_idx = predictions[0]['labels'][i].item()
22
  coco_label = COCO_INSTANCE_CATEGORY_NAMES[label_idx]
 
23
  defect_type = map_defect_type(coco_label)
24
  severity = get_severity(score)
25
 
 
26
  output.append({
27
  "type": defect_type,
28
  "confidence": round(score, 2),
@@ -30,34 +140,29 @@ def detect_defects(image):
30
  "coco_label": coco_label
31
  })
32
 
 
33
  draw.rectangle(box, outline="red", width=3)
34
- draw.text((box[0], box[1]), f"{defect_type}: {severity}", fill="red")
35
-
36
- # Apply NMS to filter overlapping detections
37
- boxes = predictions[0]['boxes']
38
- scores = predictions[0]['scores']
39
- keep = apply_nms(boxes, scores, threshold=0.5)
40
- boxes = boxes[keep]
41
- output = [output[i] for i in keep]
42
 
43
- # Create Salesforce record if detections exist
44
  if output:
45
- try:
46
- current_date = datetime.now().strftime("%Y-%m-%d")
47
- inspection_name = f"Inspection-{current_date}-{len(output):03d}"
48
 
49
- # Creating the Salesforce record with updated fields
50
  inspection_record = sf.Drone_Structure_Inspection__c.create({
51
  "Inspection_Date__c": current_date,
52
- "Fault_Type__c": output[0]["type"], # Mapping defect type
53
- "Severity__c": output[0]["severity"], # Mapping severity
54
- "Fault_Summary__c": str(output), # Summarizing the defects
55
- "Status__c": "New", # Default status
56
- "Annotated_Image_URL__c": "", # Placeholder for image URL
57
- "Report_PDF__c": "" # Placeholder for report PDF URL
58
  })
59
 
60
  record_id = inspection_record.get("id")
 
61
  content_version_id = upload_image_to_salesforce(
62
  result_image,
63
  filename=f"detected_defect_{record_id}.jpg",
@@ -73,8 +178,28 @@ def detect_defects(image):
73
  except Exception as e:
74
  output.append({"error": f"Failed to create Salesforce record: {str(e)}"})
75
 
76
- return result_image, output
 
 
77
 
78
  except Exception as e:
79
- logging.error(f"Processing failed: {str(e)}")
80
- return None, {"error": f"Processing failed: {str(e)}"}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from PIL import Image, ImageDraw, ImageFont
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 (replace with your own or environment variables)
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
+ # Salesforce Site or parent record ID where content will be linked
21
+ SITE_RECORD_ID = "a003000000xxxxx" # TODO: Replace with actual Site__c record ID
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 the Faster R-CNN pretrained model (replace with your fine-tuned weights if any)
37
+ model = models.detection.fasterrcnn_resnet50_fpn(weights="FasterRCNN_ResNet50_FPN_Weights.COCO_V1")
38
+ model.eval()
39
+
40
+ # COCO categories list for mapping labels (standard)
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 transformation for the model input
56
+ transform = transforms.Compose([
57
+ transforms.ToTensor(),
58
+ ])
59
+
60
+ # Map confidence score to severity level
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 from COCO labels to defect types (replace with your own)
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
+ # Upload annotated image to Salesforce as ContentVersion record
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 SITE_RECORD_ID
93
+ })
94
+ logging.info(f"Image uploaded to Salesforce 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
+ # Main defect detection and Salesforce integration function
101
  def detect_defects(image):
102
+ if image is None:
103
+ return None, "No image provided"
104
 
105
  try:
106
+ # Convert image and prepare input tensor
107
  image_tensor = transform(image).unsqueeze(0)
108
+
109
  with torch.no_grad():
110
  predictions = model(image_tensor)
111
 
112
+ # Copy original image to draw bounding boxes and labels
113
  result_image = image.copy()
114
  draw = ImageDraw.Draw(result_image)
 
115
 
116
+ # Optional: Use a truetype font for nicer text, fallback if not available
117
+ try:
118
+ font = ImageFont.truetype("arial.ttf", 18)
119
+ except:
120
+ font = ImageFont.load_default()
121
+
122
+ output = []
123
  for i in range(len(predictions[0]['boxes'])):
124
  score = predictions[0]['scores'][i].item()
125
+ if score < 0.3: # confidence threshold
126
  continue
127
 
128
  box = predictions[0]['boxes'][i].tolist()
129
  label_idx = predictions[0]['labels'][i].item()
130
  coco_label = COCO_INSTANCE_CATEGORY_NAMES[label_idx]
131
+
132
  defect_type = map_defect_type(coco_label)
133
  severity = get_severity(score)
134
 
135
+ # Append defect info to output list
136
  output.append({
137
  "type": defect_type,
138
  "confidence": round(score, 2),
 
140
  "coco_label": coco_label
141
  })
142
 
143
+ # Draw rectangle and label
144
  draw.rectangle(box, outline="red", width=3)
145
+ text = f"{defect_type}: {severity}"
146
+ draw.text((box[0], box[1] - 20 if box[1] > 20 else box[1],), text, fill="red", font=font)
 
 
 
 
 
 
147
 
148
+ # If defects found, create Salesforce record & upload annotated image
149
  if output:
150
+ current_date = datetime.now().strftime("%Y-%m-%d")
151
+ inspection_name = f"Inspection-{current_date}-{len(output):03d}"
 
152
 
153
+ try:
154
  inspection_record = sf.Drone_Structure_Inspection__c.create({
155
  "Inspection_Date__c": current_date,
156
+ "Fault_Type__c": output[0]["type"],
157
+ "Severity__c": output[0]["severity"],
158
+ "Fault_Summary__c": str(output),
159
+ "Status__c": "New",
160
+ "Annotated_Image_URL__c": "",
161
+ "Report_PDF__c": ""
162
  })
163
 
164
  record_id = inspection_record.get("id")
165
+
166
  content_version_id = upload_image_to_salesforce(
167
  result_image,
168
  filename=f"detected_defect_{record_id}.jpg",
 
178
  except Exception as e:
179
  output.append({"error": f"Failed to create Salesforce record: {str(e)}"})
180
 
181
+ return result_image, str(output)
182
+
183
+ return result_image, "No defects detected above confidence threshold."
184
 
185
  except Exception as e:
186
+ logging.error(f"Detection failed: {str(e)}")
187
+ return None, f"Detection failed: {str(e)}"
188
+
189
+ # Gradio interface definition
190
+ demo = gr.Interface(
191
+ fn=detect_defects,
192
+ inputs=gr.Image(type="pil", label="Upload Drone Image"),
193
+ outputs=[
194
+ gr.Image(label="Detection Result"),
195
+ gr.Textbox(label="Detected Faults with Severity")
196
+ ],
197
+ title="Structural Defect Detection with Salesforce Integration",
198
+ description=(
199
+ "Upload drone-captured images to detect structural defects like cracks, rust, spalling, "
200
+ "and deformations using Faster R-CNN. Detected faults are stored in Salesforce with annotated images."
201
+ )
202
+ )
203
+
204
+ if __name__ == "__main__":
205
+ demo.launch()