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