Komal133 commited on
Commit
e0a16bd
·
verified ·
1 Parent(s): caa3f81

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +80 -84
app.py CHANGED
@@ -12,7 +12,10 @@ from datetime import datetime
12
  SALESFORCE_USERNAME = "drone@sathkrutha.com"
13
  SALESFORCE_PASSWORD = "Komal1303@"
14
  SALESFORCE_SECURITY_TOKEN = "53AWRskW9EjWUsSL5LU6nFTy3"
15
- SALESFORCE_INSTANCE_URL = "https://sathikrutha-a-dev-ed.my.salesforce.com" # Updated to your Developer Edition org
 
 
 
16
 
17
  # Connect to Salesforce
18
  try:
@@ -22,16 +25,14 @@ try:
22
  security_token=SALESFORCE_SECURITY_TOKEN,
23
  instance_url=SALESFORCE_INSTANCE_URL
24
  )
25
- print("Connected to Salesforce successfully!")
26
  except Exception as e:
27
- print(f"Failed to connect to Salesforce: {e}")
28
- sf = None
29
 
30
- # Load Model (Updated to use weights instead of deprecated pretrained parameter)
31
  model = models.detection.fasterrcnn_resnet50_fpn(weights="FasterRCNN_ResNet50_FPN_Weights.COCO_V1")
32
  model.eval()
33
 
34
- # Define labels (COCO labels; ideally, fine-tune for structural defects)
35
  COCO_INSTANCE_CATEGORY_NAMES = [
36
  '__background__', 'person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus',
37
  'train', 'truck', 'boat', 'traffic light', 'fire hydrant', 'stop sign', 'parking meter',
@@ -54,117 +55,112 @@ transform = transforms.Compose([
54
  # Map model severity to Salesforce picklist values
55
  def get_severity(score):
56
  if score >= 0.9:
57
- return "Critical" # Maps "High" to "Critical"
58
  elif score >= 0.7:
59
- return "Moderate" # Maps "Medium" to "Moderate"
60
  else:
61
- return "Minor" # Maps "Low" to "Minor"
62
 
63
- # Temporary mapping for COCO labels to structural defects (for demo purposes)
64
- # In a production scenario, fine-tune the model to detect actual defects
65
  COCO_TO_DEFECT_MAPPING = {
66
- 'car': 'Crack', # Example mapping; adjust based on your needs
67
  'person': 'Rust',
68
  'bicycle': 'Deformation',
69
  'truck': 'Corrosion',
70
  'boat': 'Spalling',
71
- # Add more mappings as needed for other COCO labels
72
  }
73
 
74
- # Function to map COCO labels to Salesforce picklist values
75
  def map_defect_type(coco_label):
76
- return COCO_TO_DEFECT_MAPPING.get(coco_label, "Crack") # Default to "Crack" if no mapping
77
 
78
- # Function to upload image to Salesforce as a ContentVersion (file)
79
  def upload_image_to_salesforce(image, filename="detected_image.jpg", record_id=None):
80
- if not sf:
81
- return None
82
  try:
83
- # Convert PIL image to base64
84
  buffered = BytesIO()
85
  image.save(buffered, format="JPEG")
86
  img_data = base64.b64encode(buffered.getvalue()).decode("utf-8")
87
 
88
- # Create ContentVersion (Salesforce File)
89
  content_version = sf.ContentVersion.create({
90
  "Title": filename,
91
  "PathOnClient": filename,
92
  "VersionData": img_data,
93
- "FirstPublishLocationId": record_id if record_id else None # Link to the record
94
  })
95
  return content_version["id"]
96
  except Exception as e:
97
- print(f"Failed to upload image to Salesforce: {e}")
98
- return None
99
 
100
  # Detect defects and integrate with Salesforce
101
  def detect_defects(image):
102
- # Perform detection
103
- image_tensor = transform(image).unsqueeze(0)
104
- with torch.no_grad():
105
- predictions = model(image_tensor)
106
-
107
- result_image = image.copy()
108
- draw = ImageDraw.Draw(result_image)
109
- output = []
110
-
111
- for i in range(len(predictions[0]['boxes'])):
112
- score = predictions[0]['scores'][i].item()
113
- if score < 0.7: # Filter low-confidence predictions
114
- continue
115
-
116
- box = predictions[0]['boxes'][i].tolist()
117
- label_idx = predictions[0]['labels'][i].item()
118
- coco_label = COCO_INSTANCE_CATEGORY_NAMES[label_idx]
119
- defect_type = map_defect_type(coco_label) # Map COCO label to defect type
120
- severity = get_severity(score)
121
-
122
- output.append({
123
- "type": defect_type,
124
- "confidence": round(score, 2),
125
- "severity": severity,
126
- "coco_label": coco_label # Include original label for reference
127
- })
128
 
129
- draw.rectangle(box, outline="red", width=3)
130
- draw.text((box[0], box[1]), f"{defect_type}: {severity}", fill="red")
131
-
132
- # Create a single record for the inspection
133
- if sf and output:
134
- try:
135
- current_date = datetime.now().strftime("%Y-%m-%d")
136
- inspection_name = f"Inspection-{current_date}-{len(output):03d}"
137
-
138
- # Create the inspection record
139
- inspection_record = sf.Drone_Structure_Inspection__c.create({
140
- "Name": inspection_name,
141
- "Fault_Type__c": output[0]["type"], # Use the mapped defect type
142
- "Severity__c": output[0]["severity"], # Use the mapped severity
143
- "Fault_Summary__c": json.dumps(output), # Store all defects as JSON
144
- "Inspection_Date__c": current_date,
145
- "Status__c": "New" # Default status
146
- # Note: Site__c and Report_PDF__c are not set as they require additional input
 
 
 
 
 
 
 
 
147
  })
148
- print("Inspection record created in Salesforce!")
149
-
150
- # Upload the annotated image and link it to the record
151
- record_id = inspection_record.get("id")
152
- content_version_id = upload_image_to_salesforce(
153
- result_image,
154
- filename="detected_defect.jpg",
155
- record_id=record_id
156
- )
157
-
158
- # Update the record with the ContentVersion ID
159
- if content_version_id:
160
- sf.Drone_Structure_Inspection__c.update(record_id, {
161
- "Annotated_Image_URL__c": f"ContentVersion ID: {content_version_id}"
 
 
 
162
  })
163
 
164
- except Exception as e:
165
- print(f"Failed to create inspection record: {e}")
 
 
 
 
166
 
167
- return result_image, output
 
 
 
 
 
 
 
 
 
 
 
 
168
 
169
  # Gradio Interface
170
  demo = gr.Interface(
 
12
  SALESFORCE_USERNAME = "drone@sathkrutha.com"
13
  SALESFORCE_PASSWORD = "Komal1303@"
14
  SALESFORCE_SECURITY_TOKEN = "53AWRskW9EjWUsSL5LU6nFTy3"
15
+ SALESFORCE_INSTANCE_URL = "https://sathikrutha-a-dev-ed.my.salesforce.com"
16
+
17
+ # Replace with a valid Site__c record ID from your Salesforce org
18
+ SITE_RECORD_ID = "a00xxxxxxxxxxxx" # TODO: Update with actual ID
19
 
20
  # Connect to Salesforce
21
  try:
 
25
  security_token=SALESFORCE_SECURITY_TOKEN,
26
  instance_url=SALESFORCE_INSTANCE_URL
27
  )
 
28
  except Exception as e:
29
+ raise Exception(f"Failed to connect to Salesforce: {str(e)}")
 
30
 
31
+ # Load Model
32
  model = models.detection.fasterrcnn_resnet50_fpn(weights="FasterRCNN_ResNet50_FPN_Weights.COCO_V1")
33
  model.eval()
34
 
35
+ # Define labels (COCO labels; fine-tune for structural defects)
36
  COCO_INSTANCE_CATEGORY_NAMES = [
37
  '__background__', 'person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus',
38
  'train', 'truck', 'boat', 'traffic light', 'fire hydrant', 'stop sign', 'parking meter',
 
55
  # Map model severity to Salesforce picklist values
56
  def get_severity(score):
57
  if score >= 0.9:
58
+ return "Critical"
59
  elif score >= 0.7:
60
+ return "Moderate"
61
  else:
62
+ return "Minor"
63
 
64
+ # Temporary mapping for COCO labels to structural defects
 
65
  COCO_TO_DEFECT_MAPPING = {
66
+ 'car': 'Crack',
67
  'person': 'Rust',
68
  'bicycle': 'Deformation',
69
  'truck': 'Corrosion',
70
  'boat': 'Spalling',
 
71
  }
72
 
 
73
  def map_defect_type(coco_label):
74
+ return COCO_TO_DEFECT_MAPPING.get(coco_label, "Crack")
75
 
76
+ # Function to upload image to Salesforce as ContentVersion
77
  def upload_image_to_salesforce(image, filename="detected_image.jpg", record_id=None):
 
 
78
  try:
 
79
  buffered = BytesIO()
80
  image.save(buffered, format="JPEG")
81
  img_data = base64.b64encode(buffered.getvalue()).decode("utf-8")
82
 
 
83
  content_version = sf.ContentVersion.create({
84
  "Title": filename,
85
  "PathOnClient": filename,
86
  "VersionData": img_data,
87
+ "FirstPublishLocationId": record_id if record_id else None
88
  })
89
  return content_version["id"]
90
  except Exception as e:
91
+ raise Exception(f"Failed to upload image to Salesforce: {str(e)}")
 
92
 
93
  # Detect defects and integrate with Salesforce
94
  def detect_defects(image):
95
+ if not image:
96
+ return None, {"error": "No image provided"}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
97
 
98
+ try:
99
+ # Perform detection
100
+ image_tensor = transform(image).unsqueeze(0)
101
+ with torch.no_grad():
102
+ predictions = model(image_tensor)
103
+
104
+ result_image = image.copy()
105
+ draw = ImageDraw.Draw(result_image)
106
+ output = []
107
+
108
+ for i in range(len(predictions[0]['boxes'])):
109
+ score = predictions[0]['scores'][i].item()
110
+ if score < 0.7:
111
+ continue
112
+
113
+ box = predictions[0]['boxes'][i].tolist()
114
+ label_idx = predictions[0]['labels'][i].item()
115
+ coco_label = COCO_INSTANCE_CATEGORY_NAMES[label_idx]
116
+ defect_type = map_defect_type(coco_label)
117
+ severity = get_severity(score)
118
+
119
+ output.append({
120
+ "type": defect_type,
121
+ "confidence": round(score, 2),
122
+ "severity": severity,
123
+ "coco_label": coco_label
124
  })
125
+
126
+ draw.rectangle(box, outline="red", width=3)
127
+ draw.text((box[0], box[1]), f"{defect_type}: {severity}", fill="red")
128
+
129
+ # Create Salesforce record if detections exist
130
+ if output:
131
+ try:
132
+ current_date = datetime.now().strftime("%Y-%m-%d")
133
+ inspection_name = f"Inspection-{current_date}-{len(output):03d}"
134
+
135
+ inspection_record = sf.Drone_Structure_Inspection__c.create({
136
+ "Site__c": SITE_RECORD_ID,
137
+ "Fault_Type__c": output[0]["type"],
138
+ "Severity__c": output[0]["severity"],
139
+ "Fault_Summary__c": json.dumps(output),
140
+ "Inspection_Date__c": current_date,
141
+ "Status__c": "New"
142
  })
143
 
144
+ record_id = inspection_record.get("id")
145
+ content_version_id = upload_image_to_salesforce(
146
+ result_image,
147
+ filename=f"detected_defect_{record_id}.jpg",
148
+ record_id=record_id
149
+ )
150
 
151
+ if content_version_id:
152
+ sf.Drone_Structure_Inspection__c.update(record_id, {
153
+ "Annotated_Image_URL__c": f"/sfc/servlet.shepherd/version/download/{content_version_id}"
154
+ })
155
+
156
+ output.append({"salesforce_record_id": record_id})
157
+ except Exception as e:
158
+ output.append({"error": f"Failed to create Salesforce record: {str(e)}"})
159
+
160
+ return result_image, output
161
+
162
+ except Exception as e:
163
+ return None, {"error": f"Processing failed: {str(e)}"}
164
 
165
  # Gradio Interface
166
  demo = gr.Interface(