Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -8,6 +8,8 @@ from io import BytesIO
|
|
| 8 |
import json
|
| 9 |
from datetime import datetime
|
| 10 |
import logging
|
|
|
|
|
|
|
| 11 |
|
| 12 |
# Setup logging
|
| 13 |
logging.basicConfig(level=logging.INFO)
|
|
@@ -34,50 +36,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
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 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 |
-
def
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
'car': 'Crack',
|
| 73 |
-
'person': 'Rust',
|
| 74 |
-
'bicycle': 'Deformation',
|
| 75 |
-
'truck': 'Corrosion',
|
| 76 |
-
'boat': 'Spalling',
|
| 77 |
-
}
|
| 78 |
|
| 79 |
-
|
| 80 |
-
|
|
|
|
|
|
|
| 81 |
|
| 82 |
# Function to upload image to Salesforce as ContentVersion
|
| 83 |
def upload_image_to_salesforce(image, filename="detected_image.jpg", record_id=None):
|
|
@@ -101,51 +86,51 @@ def upload_image_to_salesforce(image, filename="detected_image.jpg", record_id=N
|
|
| 101 |
# Detect defects and integrate with Salesforce
|
| 102 |
def detect_defects(image):
|
| 103 |
if not image:
|
| 104 |
-
return None,
|
| 105 |
|
| 106 |
try:
|
| 107 |
-
#
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
result_image = image.copy()
|
| 113 |
-
draw = ImageDraw.Draw(result_image)
|
| 114 |
-
output = []
|
| 115 |
-
|
| 116 |
-
for i in range(len(predictions[0]['boxes'])):
|
| 117 |
-
score = predictions[0]['scores'][i].item()
|
| 118 |
-
if score < 0.5: # Lowered threshold for testing
|
| 119 |
-
continue
|
| 120 |
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
defect_type = map_defect_type(coco_label)
|
| 125 |
-
severity = get_severity(score)
|
| 126 |
|
| 127 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 128 |
"type": defect_type,
|
| 129 |
-
"confidence": round(score, 2),
|
| 130 |
"severity": severity,
|
| 131 |
-
"
|
| 132 |
})
|
| 133 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 134 |
draw.rectangle(box, outline="red", width=3)
|
| 135 |
-
draw.text((box[0], box[1]), f"{
|
| 136 |
|
| 137 |
# Create Salesforce record if detections exist
|
| 138 |
-
if
|
| 139 |
try:
|
| 140 |
current_date = datetime.now().strftime("%Y-%m-%d")
|
| 141 |
-
inspection_name = f"Inspection-{current_date}-{len(
|
| 142 |
|
| 143 |
# Creating the Salesforce record with updated fields
|
| 144 |
inspection_record = sf.Drone_Structure_Inspection__c.create({
|
| 145 |
"Inspection_Date__c": current_date,
|
| 146 |
-
"Fault_Type__c":
|
| 147 |
-
"Severity__c":
|
| 148 |
-
"Fault_Summary__c":
|
| 149 |
"Status__c": "New", # Default status
|
| 150 |
"Annotated_Image_URL__c": "", # Placeholder for image URL
|
| 151 |
"Report_PDF__c": "" # Placeholder for report PDF URL
|
|
@@ -158,20 +143,43 @@ def detect_defects(image):
|
|
| 158 |
record_id=record_id
|
| 159 |
)
|
| 160 |
|
| 161 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
-
|
| 167 |
except Exception as e:
|
| 168 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 169 |
|
| 170 |
-
return result_image,
|
| 171 |
|
| 172 |
except Exception as e:
|
| 173 |
logging.error(f"Processing failed: {str(e)}")
|
| 174 |
-
return None,
|
| 175 |
|
| 176 |
# Gradio Interface
|
| 177 |
demo = gr.Interface(
|
|
@@ -179,10 +187,10 @@ demo = gr.Interface(
|
|
| 179 |
inputs=gr.Image(type="pil", label="Upload Drone Image"),
|
| 180 |
outputs=[
|
| 181 |
gr.Image(label="Detection Result"),
|
| 182 |
-
gr.
|
| 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__":
|
|
|
|
| 8 |
import json
|
| 9 |
from datetime import datetime
|
| 10 |
import logging
|
| 11 |
+
import requests
|
| 12 |
+
from fpdf import FPDF
|
| 13 |
|
| 14 |
# Setup logging
|
| 15 |
logging.basicConfig(level=logging.INFO)
|
|
|
|
| 36 |
logging.error(f"Failed to connect to Salesforce: {str(e)}")
|
| 37 |
raise Exception(f"Failed to connect to Salesforce: {str(e)}")
|
| 38 |
|
| 39 |
+
# Load model from Hugging Face (Assuming you have a YOLOv8 model hosted)
|
| 40 |
+
MODEL_URL = "https://huggingface.co/your_huggingface_model_path" # Replace with actual model URL
|
| 41 |
+
HEADERS = {
|
| 42 |
+
"Authorization": "Bearer YOUR_HUGGINGFACE_API_KEY" # Replace with your Hugging Face API key
|
| 43 |
+
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 44 |
|
| 45 |
# Image transformations
|
| 46 |
transform = transforms.Compose([
|
| 47 |
transforms.ToTensor(),
|
| 48 |
])
|
| 49 |
|
| 50 |
+
# Function to generate PDF report
|
| 51 |
+
def generate_pdf_report(faults):
|
| 52 |
+
pdf = FPDF()
|
| 53 |
+
pdf.set_auto_page_break(auto=True, margin=15)
|
| 54 |
+
pdf.add_page()
|
| 55 |
+
|
| 56 |
+
pdf.set_font("Arial", size=12)
|
| 57 |
+
pdf.cell(200, 10, txt="Drone Fault Detection Report", ln=True, align='C')
|
| 58 |
+
|
| 59 |
+
pdf.ln(10)
|
| 60 |
+
pdf.cell(200, 10, txt="Faults Detected:", ln=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 61 |
|
| 62 |
+
for fault in faults:
|
| 63 |
+
pdf.cell(200, 10, txt=f"Defect: {fault['type']}, Severity: {fault['severity']}, Confidence: {fault['confidence']}", ln=True)
|
| 64 |
+
|
| 65 |
+
return pdf
|
| 66 |
|
| 67 |
# Function to upload image to Salesforce as ContentVersion
|
| 68 |
def upload_image_to_salesforce(image, filename="detected_image.jpg", record_id=None):
|
|
|
|
| 86 |
# Detect defects and integrate with Salesforce
|
| 87 |
def detect_defects(image):
|
| 88 |
if not image:
|
| 89 |
+
return None, "No image provided"
|
| 90 |
|
| 91 |
try:
|
| 92 |
+
# Prepare image for model inference
|
| 93 |
+
buffered = BytesIO()
|
| 94 |
+
image.save(buffered, format="JPEG")
|
| 95 |
+
img_data = base64.b64encode(buffered.getvalue()).decode("utf-8")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 96 |
|
| 97 |
+
# Send image to Hugging Face hosted model for detection (assuming YOLOv8 model)
|
| 98 |
+
response = requests.post(MODEL_URL, headers=HEADERS, json={"inputs": img_data})
|
| 99 |
+
response_data = response.json()
|
|
|
|
|
|
|
| 100 |
|
| 101 |
+
# Assuming response is a list of detected objects with bounding boxes, labels, and scores
|
| 102 |
+
faults = []
|
| 103 |
+
for item in response_data:
|
| 104 |
+
defect_type = item["label"]
|
| 105 |
+
severity = "Critical" if item["score"] > 0.9 else "Moderate" if item["score"] > 0.7 else "Minor"
|
| 106 |
+
faults.append({
|
| 107 |
"type": defect_type,
|
| 108 |
+
"confidence": round(item["score"], 2),
|
| 109 |
"severity": severity,
|
| 110 |
+
"box": item["bbox"]
|
| 111 |
})
|
| 112 |
|
| 113 |
+
result_image = image.copy()
|
| 114 |
+
draw = ImageDraw.Draw(result_image)
|
| 115 |
+
|
| 116 |
+
# Annotate image with bounding boxes and labels
|
| 117 |
+
for fault in faults:
|
| 118 |
+
box = fault["box"]
|
| 119 |
draw.rectangle(box, outline="red", width=3)
|
| 120 |
+
draw.text((box[0], box[1]), f"{fault['type']}: {fault['severity']}", fill="red")
|
| 121 |
|
| 122 |
# Create Salesforce record if detections exist
|
| 123 |
+
if faults:
|
| 124 |
try:
|
| 125 |
current_date = datetime.now().strftime("%Y-%m-%d")
|
| 126 |
+
inspection_name = f"Inspection-{current_date}-{len(faults):03d}"
|
| 127 |
|
| 128 |
# Creating the Salesforce record with updated fields
|
| 129 |
inspection_record = sf.Drone_Structure_Inspection__c.create({
|
| 130 |
"Inspection_Date__c": current_date,
|
| 131 |
+
"Fault_Type__c": faults[0]["type"], # Mapping defect type
|
| 132 |
+
"Severity__c": faults[0]["severity"], # Mapping severity
|
| 133 |
+
"Fault_Summary__c": "\n".join([f"{fault['type']} (Confidence: {fault['confidence']})" for fault in faults]), # Summarizing the defects
|
| 134 |
"Status__c": "New", # Default status
|
| 135 |
"Annotated_Image_URL__c": "", # Placeholder for image URL
|
| 136 |
"Report_PDF__c": "" # Placeholder for report PDF URL
|
|
|
|
| 143 |
record_id=record_id
|
| 144 |
)
|
| 145 |
|
| 146 |
+
# Generate and upload the PDF report
|
| 147 |
+
pdf = generate_pdf_report(faults)
|
| 148 |
+
pdf_output = "/tmp/report.pdf"
|
| 149 |
+
pdf.output(pdf_output)
|
| 150 |
+
|
| 151 |
+
# Upload the PDF report to Salesforce (ContentVersion)
|
| 152 |
+
with open(pdf_output, "rb") as f:
|
| 153 |
+
report_data = f.read()
|
| 154 |
+
|
| 155 |
+
pdf_data = base64.b64encode(report_data).decode("utf-8")
|
| 156 |
+
content_version = sf.ContentVersion.create({
|
| 157 |
+
"Title": f"Report_{record_id}.pdf",
|
| 158 |
+
"PathOnClient": f"Report_{record_id}.pdf",
|
| 159 |
+
"VersionData": pdf_data,
|
| 160 |
+
"FirstPublishLocationId": record_id
|
| 161 |
+
})
|
| 162 |
+
|
| 163 |
+
if content_version:
|
| 164 |
sf.Drone_Structure_Inspection__c.update(record_id, {
|
| 165 |
+
"Report_PDF__c": f"/sfc/servlet.shepherd/version/download/{content_version['id']}",
|
| 166 |
"Annotated_Image_URL__c": f"/sfc/servlet.shepherd/version/download/{content_version_id}"
|
| 167 |
})
|
| 168 |
|
| 169 |
+
faults.append(f"Salesforce record ID: {record_id}")
|
| 170 |
except Exception as e:
|
| 171 |
+
faults.append(f"Failed to create Salesforce record: {str(e)}")
|
| 172 |
+
|
| 173 |
+
# Return a more readable, text-based format instead of JSON
|
| 174 |
+
result_text = "\nDetected Faults and Severities:\n"
|
| 175 |
+
for fault in faults:
|
| 176 |
+
result_text += f"- {fault}\n"
|
| 177 |
|
| 178 |
+
return result_image, result_text
|
| 179 |
|
| 180 |
except Exception as e:
|
| 181 |
logging.error(f"Processing failed: {str(e)}")
|
| 182 |
+
return None, f"Processing failed: {str(e)}"
|
| 183 |
|
| 184 |
# Gradio Interface
|
| 185 |
demo = gr.Interface(
|
|
|
|
| 187 |
inputs=gr.Image(type="pil", label="Upload Drone Image"),
|
| 188 |
outputs=[
|
| 189 |
gr.Image(label="Detection Result"),
|
| 190 |
+
gr.Textbox(label="Detected Faults with Severity", lines=10) # Updated to use text output
|
| 191 |
],
|
| 192 |
title="Structural Defect Detection with Salesforce Integration",
|
| 193 |
+
description="Detects objects using YOLOv8 or Faster R-CNN hosted on Hugging Face and stores results in Salesforce. Fine-tune the model for structural defects like cracks, rust, and spalling."
|
| 194 |
)
|
| 195 |
|
| 196 |
if __name__ == "__main__":
|