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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +64 -37
app.py CHANGED
@@ -5,13 +5,14 @@ from torchvision import models, transforms
5
  from simple_salesforce import Salesforce
6
  import base64
7
  from io import BytesIO
8
- import os
 
9
 
10
- # Salesforce Credentials (replace with your values)
11
  SALESFORCE_USERNAME = "drone@sathkrutha.com"
12
  SALESFORCE_PASSWORD = "Komal1303@"
13
  SALESFORCE_SECURITY_TOKEN = "53AWRskW9EjWUsSL5LU6nFTy3"
14
- SALESFORCE_INSTANCE_URL = "https://login.salesforce.com" # or your sandbox URL
15
 
16
  # Connect to Salesforce
17
  try:
@@ -26,20 +27,11 @@ except Exception as e:
26
  print(f"Failed to connect to Salesforce: {e}")
27
  sf = None
28
 
29
- # Load Model (Option 1: Pretrained Faster R-CNN from torchvision)
30
- model = models.detection.fasterrcnn_resnet50_fpn(pretrained=True)
31
  model.eval()
32
 
33
- # Option 2: Load a fine-tuned model from Hugging Face (Placeholder)
34
- # Example: If you have a fine-tuned Faster R-CNN on Hugging Face for structural defects
35
- """
36
- from transformers import AutoModelForObjectDetection
37
- model = AutoModelForObjectDetection.from_pretrained("your_huggingface_username/defect-detection-model")
38
- model.eval()
39
- # Note: Ensure the model is compatible with torchvision's detection pipeline or adapt the inference logic.
40
- """
41
-
42
- # Define labels (customize for structural defects if fine-tuned)
43
  COCO_INSTANCE_CATEGORY_NAMES = [
44
  '__background__', 'person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus',
45
  'train', 'truck', 'boat', 'traffic light', 'fire hydrant', 'stop sign', 'parking meter',
@@ -59,17 +51,32 @@ transform = transforms.Compose([
59
  transforms.ToTensor(),
60
  ])
61
 
62
- # Severity labels
63
  def get_severity(score):
64
  if score >= 0.9:
65
- return "High"
66
  elif score >= 0.7:
67
- return "Medium"
68
  else:
69
- return "Low"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70
 
71
  # Function to upload image to Salesforce as a ContentVersion (file)
72
- def upload_image_to_salesforce(image, filename="detected_image.jpg"):
73
  if not sf:
74
  return None
75
  try:
@@ -83,7 +90,7 @@ def upload_image_to_salesforce(image, filename="detected_image.jpg"):
83
  "Title": filename,
84
  "PathOnClient": filename,
85
  "VersionData": img_data,
86
- "FirstPublishLocationId": None # Optionally link to a record
87
  })
88
  return content_version["id"]
89
  except Exception as e:
@@ -108,34 +115,54 @@ def detect_defects(image):
108
 
109
  box = predictions[0]['boxes'][i].tolist()
110
  label_idx = predictions[0]['labels'][i].item()
111
- label = COCO_INSTANCE_CATEGORY_NAMES[label_idx]
 
112
  severity = get_severity(score)
113
 
114
  output.append({
115
- "type": label,
116
  "confidence": round(score, 2),
117
- "severity": severity
 
118
  })
119
 
120
  draw.rectangle(box, outline="red", width=3)
121
- draw.text((box[0], box[1]), f"{label}: {severity}", fill="red")
122
 
123
- # Upload image to Salesforce
124
- content_version_id = upload_image_to_salesforce(result_image, filename="detected_defect.jpg")
125
-
126
- # Store detection results in Salesforce
127
  if sf and output:
128
  try:
129
- for defect in output:
130
- sf.Defect__c.create({
131
- "Defect_Type__c": defect["type"],
132
- "Confidence__c": defect["confidence"],
133
- "Severity__c": defect["severity"],
134
- "Image_URL__c": f"ContentVersion ID: {content_version_id}" if content_version_id else ""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
135
  })
136
- print("Defect records created in Salesforce!")
137
  except Exception as e:
138
- print(f"Failed to create defect records: {e}")
139
 
140
  return result_image, output
141
 
 
5
  from simple_salesforce import Salesforce
6
  import base64
7
  from io import BytesIO
8
+ import json
9
+ from datetime import datetime
10
 
11
+ # Salesforce Credentials
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:
 
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',
 
51
  transforms.ToTensor(),
52
  ])
53
 
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:
 
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:
 
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