Komal133 commited on
Commit
b84ad8d
·
verified ·
1 Parent(s): 00507bf

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +166 -48
app.py CHANGED
@@ -1,71 +1,189 @@
 
 
 
 
 
 
 
 
 
1
  import logging
2
- import requests
3
 
4
  # Setup logging
5
  logging.basicConfig(level=logging.INFO)
6
 
7
- MODEL_URL = "https://huggingface.co/your_huggingface_model_path" # Replace with actual model URL
8
- HEADERS = {
9
- "Authorization": "Bearer YOUR_HUGGINGFACE_API_KEY" # Replace with your Hugging Face API key
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10
  }
11
 
12
- def detect_defects(image):
13
- if not image:
14
- return None, "No image provided"
15
 
 
 
16
  try:
17
- # Prepare image for model inference
18
  buffered = BytesIO()
19
  image.save(buffered, format="JPEG")
20
  img_data = base64.b64encode(buffered.getvalue()).decode("utf-8")
 
 
 
 
 
 
 
 
 
 
 
 
21
 
22
- # Send image to Hugging Face hosted model for detection (assuming YOLOv8 model)
23
- response = requests.post(MODEL_URL, headers=HEADERS, json={"inputs": img_data})
24
-
25
- # Debugging the raw response
26
- logging.info(f"Response Status Code: {response.status_code}")
27
- logging.info(f"Response Text: {response.text}") # Log the raw response
28
-
29
- # Check for valid response
30
- if response.status_code != 200:
31
- logging.error(f"Error in API request: {response.status_code}")
32
- return None, f"API Error: {response.status_code}"
33
-
34
- # Attempt to parse the JSON response
35
- try:
36
- response_data = response.json()
37
- except ValueError:
38
- logging.error("API response is not valid JSON")
39
- return None, "API response is not valid JSON"
40
-
41
- # Assuming response is a list of detected objects with bounding boxes, labels, and scores
42
- faults = []
43
- for item in response_data:
44
- defect_type = item["label"]
45
- severity = "Critical" if item["score"] > 0.9 else "Moderate" if item["score"] > 0.7 else "Minor"
46
- faults.append({
47
- "type": defect_type,
48
- "confidence": round(item["score"], 2),
49
- "severity": severity,
50
- "box": item["bbox"]
51
- })
52
 
53
  result_image = image.copy()
54
  draw = ImageDraw.Draw(result_image)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55
 
56
- # Annotate image with bounding boxes and labels
57
- for fault in faults:
58
- box = fault["box"]
59
  draw.rectangle(box, outline="red", width=3)
60
- draw.text((box[0], box[1]), f"{fault['type']}: {fault['severity']}", fill="red")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61
 
62
- # Return a more readable, text-based format instead of JSON
63
- result_text = "\nDetected Faults and Severities:\n"
64
- for fault in faults:
65
- result_text += f"- {fault['type']} (Confidence: {fault['confidence']}, Severity: {fault['severity']})\n"
66
 
67
- return result_image, result_text
 
 
 
 
68
 
69
  except Exception as e:
70
  logging.error(f"Processing failed: {str(e)}")
71
- return None, f"Processing failed: {str(e)}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from PIL import Image, ImageDraw
3
+ import torch
4
+ from torchvision import models, transforms
5
+ from si mple_salesforce import Salesforce
6
+ import base64
7
+ 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)
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
+ # Map model severity to Salesforce picklist values
62
+ def get_severity(score):
63
+ if score >= 0.9:
64
+ return "Critical"
65
+ elif score >= 0.7:
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)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ box = predictions[0]['boxes'][i].tolist()
122
+ label_idx = predictions[0]['labels'][i].item()
123
+ coco_label = COCO_INSTANCE_CATEGORY_NAMES[label_idx]
124
+ defect_type = map_defect_type(coco_label)
125
+ severity = get_severity(score)
126
+
127
+ output.append({
128
+ "type": defect_type,
129
+ "confidence": round(score, 2),
130
+ "severity": severity,
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
+ # Create Salesforce record if detections exist
138
+ if output:
139
+ try:
140
+ current_date = datetime.now().strftime("%Y-%m-%d")
141
+ inspection_name = f"Inspection-{current_date}-{len(output):03d}"
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": 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()