Komal133 commited on
Commit
a16e911
·
verified ·
1 Parent(s): cf21dd1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +72 -106
app.py CHANGED
@@ -1,114 +1,80 @@
1
- from flask import Flask, request, jsonify
2
- from ultralytics import YOLO
3
- from PIL import Image
4
- import io
5
- import os
6
- from simple_salesforce import Salesforce
7
 
8
- app = Flask(__name__)
 
 
 
 
9
 
10
- # Salesforce configuration
11
- SALESFORCE_USERNAME = "drone@sathkrutha.com"
12
- SALESFORCE_PASSWORD = "Komal1303@"
13
- SALESFORCE_SECURITY_TOKEN = "53AWRskW9EjWUsSL5LU6nFTy3"
14
 
15
- # Initialize Salesforce client
16
- sf = Salesforce(
17
- username=SALESFORCE_USERNAME,
18
- password=SALESFORCE_PASSWORD,
19
- security_token=SALESFORCE_SECURITY_TOKEN
20
- )
21
 
22
- # Load YOLOv8 model (assumes model is in Space's root or a subdirectory)
23
- model = YOLO("yolov8n.pt") # Replace with path to your fine-tuned model, e.g., "models/drone-inspection.pt"
 
 
 
24
 
25
- # Define fault types and severities for mapping
26
- FAULT_TYPES = ["Crack", "Rust", "Deformation", "Corrosion", "Spalling"]
27
- SEVERITIES = ["Minor", "Moderate", "Critical"]
 
 
 
28
 
29
- @app.route("/process-image", methods=["POST"])
30
- def process_image():
31
- try:
32
- # Validate request
33
- if "image" not in request.files:
34
- return jsonify({"error": "No image provided"}), 400
35
-
36
- image_file = request.files["image"]
37
- site_id = request.form.get("site_id")
38
- inspection_date = request.form.get("inspection_date")
39
-
40
- if not site_id or not inspection_date:
41
- return jsonify({"error": "Missing site_id or inspection_date"}), 400
42
 
43
- # Load and preprocess image
44
- image = Image.open(image_file).convert("RGB")
45
-
46
- # Run YOLOv8 inference
47
- results = model(image)
48
-
49
- # Process predictions
50
- fault_type = "None"
51
- severity = "None"
52
- confidence = 0.0
53
-
54
- # Extract top prediction (assuming YOLOv8 output format)
55
- if results and results[0].boxes:
56
- top_box = results[0].boxes[0] # Get highest confidence detection
57
- class_id = int(top_box.cls)
58
- confidence = float(top_box.conf)
59
-
60
- # Map class_id to fault_type and severity
61
- # Assume class IDs are structured: 0-14 (5 fault types x 3 severities)
62
- fault_idx = class_id // len(SEVERITIES)
63
- severity_idx = class_id % len(SEVERITIES)
64
- if fault_idx < len(FAULT_TYPES):
65
- fault_type = FAULT_TYPES[fault_idx]
66
- severity = SEVERITIES[severity_idx]
67
-
68
- # Generate placeholder URLs (replace with actual logic for annotated images/reports)
69
- annotated_image_url = "https://example.com/annotated_image.png"
70
- report_pdf_url = "https://example.com/report.pdf"
71
-
72
- # Create Salesforce record
73
- inspection_data = {
74
- "Site__c": site_id,
75
- "Inspection_Date__c": inspection_date,
76
- "Fault_Type__c": fault_type,
77
- "Severity__c": severity,
78
- "Annotated_Image_URL__c": annotated_image_url,
79
- "Report_PDF__c": report_pdf_url,
80
- "Fault_Summary__c": f"Detected {fault_type} with {severity} severity (Confidence: {confidence:.2f})",
81
- "Status__c": "New"
82
- }
83
-
84
- # Upload image to Salesforce as ContentVersion
85
- img_byte_arr = io.BytesIO()
86
- image.save(img_byte_arr, format="PNG")
87
- img_byte_arr = img_byte_arr.getvalue()
88
-
89
- content_version = {
90
- "Title": f"Drone_Image_{site_id}_{inspection_date}",
91
- "PathOnClient": image_file.filename,
92
- "VersionData": img_byte_arr
93
- }
94
- content_result = sf.ContentVersion.create(content_version)
95
-
96
- # Link ContentVersion to inspection record
97
- inspection_data["Drone_Image__c"] = content_result["id"]
98
-
99
- # Create Drone_Structure_Inspection__c record
100
- result = sf.Drone_Structure_Inspection__c.create(inspection_data)
101
-
102
- return jsonify({
103
- "message": "Inspection processed successfully",
104
- "record_id": result["id"],
105
- "fault_type": fault_type,
106
- "severity": severity,
107
- "confidence": confidence
108
- }), 200
109
-
110
- except Exception as e:
111
- return jsonify({"error": str(e)}), 500
112
 
113
- if __name__ == "__main__":
114
- app.run(debug=True, host="0.0.0.0", port=5000)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ def detect_defects(image):
2
+ if not image:
3
+ return None, {"error": "No image provided"}
 
 
 
4
 
5
+ try:
6
+ # Perform detection
7
+ image_tensor = transform(image).unsqueeze(0)
8
+ with torch.no_grad():
9
+ predictions = model(image_tensor)
10
 
11
+ result_image = image.copy()
12
+ draw = ImageDraw.Draw(result_image)
13
+ output = []
 
14
 
15
+ for i in range(len(predictions[0]['boxes'])):
16
+ score = predictions[0]['scores'][i].item()
17
+ if score < 0.5: # Increased threshold for better quality detections
18
+ continue
 
 
19
 
20
+ box = predictions[0]['boxes'][i].tolist()
21
+ label_idx = predictions[0]['labels'][i].item()
22
+ coco_label = COCO_INSTANCE_CATEGORY_NAMES[label_idx]
23
+ defect_type = map_defect_type(coco_label)
24
+ severity = get_severity(score)
25
 
26
+ output.append({
27
+ "type": defect_type,
28
+ "confidence": round(score, 2),
29
+ "severity": severity,
30
+ "coco_label": coco_label
31
+ })
32
 
33
+ draw.rectangle(box, outline="red", width=3)
34
+ draw.text((box[0], box[1]), f"{defect_type}: {severity}", fill="red")
 
 
 
 
 
 
 
 
 
 
 
35
 
36
+ # Apply NMS to filter overlapping detections
37
+ boxes = predictions[0]['boxes']
38
+ scores = predictions[0]['scores']
39
+ keep = apply_nms(boxes, scores, threshold=0.5)
40
+ boxes = boxes[keep]
41
+ output = [output[i] for i in keep]
42
+
43
+ # Create Salesforce record if detections exist
44
+ if output:
45
+ try:
46
+ current_date = datetime.now().strftime("%Y-%m-%d")
47
+ inspection_name = f"Inspection-{current_date}-{len(output):03d}"
48
+
49
+ # Creating the Salesforce record with updated fields
50
+ inspection_record = sf.Drone_Structure_Inspection__c.create({
51
+ "Inspection_Date__c": current_date,
52
+ "Fault_Type__c": output[0]["type"], # Mapping defect type
53
+ "Severity__c": output[0]["severity"], # Mapping severity
54
+ "Fault_Summary__c": str(output), # Summarizing the defects
55
+ "Status__c": "New", # Default status
56
+ "Annotated_Image_URL__c": "", # Placeholder for image URL
57
+ "Report_PDF__c": "" # Placeholder for report PDF URL
58
+ })
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59
 
60
+ record_id = inspection_record.get("id")
61
+ content_version_id = upload_image_to_salesforce(
62
+ result_image,
63
+ filename=f"detected_defect_{record_id}.jpg",
64
+ record_id=record_id
65
+ )
66
+
67
+ if content_version_id:
68
+ sf.Drone_Structure_Inspection__c.update(record_id, {
69
+ "Annotated_Image_URL__c": f"/sfc/servlet.shepherd/version/download/{content_version_id}"
70
+ })
71
+
72
+ output.append({"salesforce_record_id": record_id})
73
+ except Exception as e:
74
+ output.append({"error": f"Failed to create Salesforce record: {str(e)}"})
75
+
76
+ return result_image, output
77
+
78
+ except Exception as e:
79
+ logging.error(f"Processing failed: {str(e)}")
80
+ return None, {"error": f"Processing failed: {str(e)}"}