Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -2,12 +2,44 @@ import gradio as gr
|
|
| 2 |
from PIL import Image, ImageDraw
|
| 3 |
import torch
|
| 4 |
from torchvision import models, transforms
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
|
| 6 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
model = models.detection.fasterrcnn_resnet50_fpn(pretrained=True)
|
| 8 |
model.eval()
|
| 9 |
|
| 10 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
COCO_INSTANCE_CATEGORY_NAMES = [
|
| 12 |
'__background__', 'person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus',
|
| 13 |
'train', 'truck', 'boat', 'traffic light', 'fire hydrant', 'stop sign', 'parking meter',
|
|
@@ -27,7 +59,7 @@ transform = transforms.Compose([
|
|
| 27 |
transforms.ToTensor(),
|
| 28 |
])
|
| 29 |
|
| 30 |
-
#
|
| 31 |
def get_severity(score):
|
| 32 |
if score >= 0.9:
|
| 33 |
return "High"
|
|
@@ -36,25 +68,47 @@ def get_severity(score):
|
|
| 36 |
else:
|
| 37 |
return "Low"
|
| 38 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 39 |
def detect_defects(image):
|
|
|
|
| 40 |
image_tensor = transform(image).unsqueeze(0)
|
| 41 |
-
|
| 42 |
with torch.no_grad():
|
| 43 |
predictions = model(image_tensor)
|
| 44 |
|
| 45 |
result_image = image.copy()
|
| 46 |
draw = ImageDraw.Draw(result_image)
|
| 47 |
-
|
| 48 |
output = []
|
|
|
|
| 49 |
for i in range(len(predictions[0]['boxes'])):
|
| 50 |
score = predictions[0]['scores'][i].item()
|
| 51 |
-
if score < 0.7: #
|
| 52 |
continue
|
| 53 |
|
| 54 |
box = predictions[0]['boxes'][i].tolist()
|
| 55 |
label_idx = predictions[0]['labels'][i].item()
|
| 56 |
label = COCO_INSTANCE_CATEGORY_NAMES[label_idx]
|
| 57 |
-
|
| 58 |
severity = get_severity(score)
|
| 59 |
|
| 60 |
output.append({
|
|
@@ -66,6 +120,23 @@ def detect_defects(image):
|
|
| 66 |
draw.rectangle(box, outline="red", width=3)
|
| 67 |
draw.text((box[0], box[1]), f"{label}: {severity}", fill="red")
|
| 68 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 69 |
return result_image, output
|
| 70 |
|
| 71 |
# Gradio Interface
|
|
@@ -76,9 +147,9 @@ demo = gr.Interface(
|
|
| 76 |
gr.Image(label="Detection Result"),
|
| 77 |
gr.JSON(label="Detected Faults with Severity")
|
| 78 |
],
|
| 79 |
-
title="Structural Defect Detection
|
| 80 |
-
description="Detects
|
| 81 |
)
|
| 82 |
|
| 83 |
if __name__ == "__main__":
|
| 84 |
-
demo.launch()
|
|
|
|
| 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 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:
|
| 18 |
+
sf = Salesforce(
|
| 19 |
+
username=SALESFORCE_USERNAME,
|
| 20 |
+
password=SALESFORCE_PASSWORD,
|
| 21 |
+
security_token=SALESFORCE_SECURITY_TOKEN,
|
| 22 |
+
instance_url=SALESFORCE_INSTANCE_URL
|
| 23 |
+
)
|
| 24 |
+
print("Connected to Salesforce successfully!")
|
| 25 |
+
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 |
transforms.ToTensor(),
|
| 60 |
])
|
| 61 |
|
| 62 |
+
# Severity labels
|
| 63 |
def get_severity(score):
|
| 64 |
if score >= 0.9:
|
| 65 |
return "High"
|
|
|
|
| 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:
|
| 76 |
+
# Convert PIL image to base64
|
| 77 |
+
buffered = BytesIO()
|
| 78 |
+
image.save(buffered, format="JPEG")
|
| 79 |
+
img_data = base64.b64encode(buffered.getvalue()).decode("utf-8")
|
| 80 |
+
|
| 81 |
+
# Create ContentVersion (Salesforce File)
|
| 82 |
+
content_version = sf.ContentVersion.create({
|
| 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:
|
| 90 |
+
print(f"Failed to upload image to Salesforce: {e}")
|
| 91 |
+
return None
|
| 92 |
+
|
| 93 |
+
# Detect defects and integrate with Salesforce
|
| 94 |
def detect_defects(image):
|
| 95 |
+
# Perform detection
|
| 96 |
image_tensor = transform(image).unsqueeze(0)
|
|
|
|
| 97 |
with torch.no_grad():
|
| 98 |
predictions = model(image_tensor)
|
| 99 |
|
| 100 |
result_image = image.copy()
|
| 101 |
draw = ImageDraw.Draw(result_image)
|
|
|
|
| 102 |
output = []
|
| 103 |
+
|
| 104 |
for i in range(len(predictions[0]['boxes'])):
|
| 105 |
score = predictions[0]['scores'][i].item()
|
| 106 |
+
if score < 0.7: # Filter low-confidence predictions
|
| 107 |
continue
|
| 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({
|
|
|
|
| 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 |
|
| 142 |
# Gradio Interface
|
|
|
|
| 147 |
gr.Image(label="Detection Result"),
|
| 148 |
gr.JSON(label="Detected Faults with Severity")
|
| 149 |
],
|
| 150 |
+
title="Structural Defect Detection with Salesforce Integration",
|
| 151 |
+
description="Detects objects using Faster R-CNN and stores results in Salesforce. Fine-tune the model for structural defects like cracks, rust, and spalling."
|
| 152 |
)
|
| 153 |
|
| 154 |
if __name__ == "__main__":
|
| 155 |
+
demo.launch()
|