Mohaddz commited on
Commit
a4bb933
·
verified ·
1 Parent(s): 12ee925

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +96 -83
app.py CHANGED
@@ -1,83 +1,96 @@
1
- import gradio as gr
2
- import torch
3
- from PIL import Image
4
- import numpy as np
5
- import tensorflow as tf
6
- from transformers import SegformerForSemanticSegmentation, AutoFeatureExtractor
7
- import cv2
8
- import json
9
-
10
- # Load models
11
- part_seg_model = SegformerForSemanticSegmentation.from_pretrained("Mohaddz/huggingCars")
12
- damage_seg_model = SegformerForSemanticSegmentation.from_pretrained("Mohaddz/DamageSeg")
13
- feature_extractor = AutoFeatureExtractor.from_pretrained("Mohaddz/huggingCars")
14
- dl_model = tf.keras.models.load_model('improved_car_damage_prediction_model.h5')
15
-
16
- # Load parts list
17
- with open('cars117.json', 'r', encoding='utf-8') as f:
18
- data = json.load(f)
19
- all_parts = sorted(list(set(part for entry in data.values() for part in entry.get('replaced_parts', []))))
20
-
21
- def process_image(image):
22
- # Convert to RGB if it's not
23
- if image.mode != 'RGB':
24
- image = image.convert('RGB')
25
-
26
- # Prepare input for the model
27
- inputs = feature_extractor(images=image, return_tensors="pt")
28
-
29
- # Get damage segmentation
30
- with torch.no_grad():
31
- damage_output = damage_seg_model(**inputs).logits
32
- damage_features = damage_output.squeeze().detach().numpy()
33
-
34
- # Create damage segmentation heatmap
35
- damage_heatmap = create_heatmap(damage_features)
36
- damage_heatmap_resized = cv2.resize(damage_heatmap, (image.size[0], image.size[1]))
37
-
38
- # Create annotated damage image
39
- image_array = np.array(image)
40
- damage_mask = np.argmax(damage_features, axis=0)
41
- damage_mask_resized = cv2.resize(damage_mask, (image.size[0], image.size[1]), interpolation=cv2.INTER_NEAREST)
42
- overlay = np.zeros_like(image_array)
43
- overlay[damage_mask_resized > 0] = [255, 0, 0] # Red color for damage
44
- annotated_image = cv2.addWeighted(image_array, 1, overlay, 0.5, 0)
45
-
46
- # Process for part prediction and heatmap
47
- with torch.no_grad():
48
- part_output = part_seg_model(**inputs).logits
49
- part_features = part_output.squeeze().detach().numpy()
50
- part_heatmap = create_heatmap(part_features)
51
- part_heatmap_resized = cv2.resize(part_heatmap, (image.size[0], image.size[1]))
52
-
53
- # Predict parts to replace
54
- input_vector = np.concatenate([part_features.mean(axis=(1, 2)), damage_features.mean(axis=(1, 2))])
55
- prediction = dl_model.predict(np.array([input_vector]))
56
- predicted_parts = [(all_parts[i], float(prob)) for i, prob in enumerate(prediction[0]) if prob > 0.1]
57
- predicted_parts.sort(key=lambda x: x[1], reverse=True)
58
-
59
- return (Image.fromarray(annotated_image),
60
- Image.fromarray(damage_heatmap_resized),
61
- Image.fromarray(part_heatmap_resized),
62
- "\n".join([f"{part}: {prob:.2f}" for part, prob in predicted_parts[:5]]))
63
-
64
- def create_heatmap(features):
65
- heatmap = np.sum(features, axis=0)
66
- heatmap = (heatmap - heatmap.min()) / (heatmap.max() - heatmap.min())
67
- heatmap = np.uint8(255 * heatmap)
68
- return cv2.applyColorMap(heatmap, cv2.COLORMAP_JET)
69
-
70
- iface = gr.Interface(
71
- fn=process_image,
72
- inputs=gr.Image(type="pil"),
73
- outputs=[
74
- gr.Image(type="pil", label="Annotated Damage"),
75
- gr.Image(type="pil", label="Damage Heatmap"),
76
- gr.Image(type="pil", label="Part Segmentation Heatmap"),
77
- gr.Textbox(label="Predicted Parts to Replace")
78
- ],
79
- title="Car Damage Assessment",
80
- description="Upload an image of a damaged car to get an assessment."
81
- )
82
-
83
- iface.launch(share=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import torch
3
+ from PIL import Image
4
+ import numpy as np
5
+ import tensorflow as tf
6
+ from transformers import SegformerForSemanticSegmentation, AutoFeatureExtractor
7
+ import cv2
8
+ import json
9
+
10
+ # Load models
11
+ part_seg_model = SegformerForSemanticSegmentation.from_pretrained("Mohaddz/huggingCars")
12
+ damage_seg_model = SegformerForSemanticSegmentation.from_pretrained("Mohaddz/DamageSeg")
13
+ feature_extractor = AutoFeatureExtractor.from_pretrained("Mohaddz/huggingCars")
14
+
15
+ # Recreate the model architecture
16
+ def create_model(input_shape, num_classes):
17
+ inputs = tf.keras.Input(shape=input_shape)
18
+ x = tf.keras.layers.Dense(64, activation='relu')(inputs)
19
+ x = tf.keras.layers.Dense(32, activation='relu')(x)
20
+ outputs = tf.keras.layers.Dense(num_classes, activation='sigmoid')(x)
21
+ return tf.keras.Model(inputs=inputs, outputs=outputs)
22
+
23
+ # Load model weights
24
+ input_shape = 33 # Adjust this based on your actual input shape
25
+ num_classes = 29 # Adjust this based on your actual number of classes
26
+ dl_model = create_model(input_shape, num_classes)
27
+ dl_model.load_weights('improved_car_damage_prediction_model_weights.h5')
28
+
29
+ # Load parts list
30
+ with open('cars117.json', 'r', encoding='utf-8') as f:
31
+ data = json.load(f)
32
+ all_parts = sorted(list(set(part for entry in data.values() for part in entry.get('replaced_parts', []))))
33
+
34
+ def process_image(image):
35
+ # Convert to RGB if it's not
36
+ if image.mode != 'RGB':
37
+ image = image.convert('RGB')
38
+
39
+ # Prepare input for the model
40
+ inputs = feature_extractor(images=image, return_tensors="pt")
41
+
42
+ # Get damage segmentation
43
+ with torch.no_grad():
44
+ damage_output = damage_seg_model(**inputs).logits
45
+ damage_features = damage_output.squeeze().detach().numpy()
46
+
47
+ # Create damage segmentation heatmap
48
+ damage_heatmap = create_heatmap(damage_features)
49
+ damage_heatmap_resized = cv2.resize(damage_heatmap, (image.size[0], image.size[1]))
50
+
51
+ # Create annotated damage image
52
+ image_array = np.array(image)
53
+ damage_mask = np.argmax(damage_features, axis=0)
54
+ damage_mask_resized = cv2.resize(damage_mask, (image.size[0], image.size[1]), interpolation=cv2.INTER_NEAREST)
55
+ overlay = np.zeros_like(image_array)
56
+ overlay[damage_mask_resized > 0] = [255, 0, 0] # Red color for damage
57
+ annotated_image = cv2.addWeighted(image_array, 1, overlay, 0.5, 0)
58
+
59
+ # Process for part prediction and heatmap
60
+ with torch.no_grad():
61
+ part_output = part_seg_model(**inputs).logits
62
+ part_features = part_output.squeeze().detach().numpy()
63
+ part_heatmap = create_heatmap(part_features)
64
+ part_heatmap_resized = cv2.resize(part_heatmap, (image.size[0], image.size[1]))
65
+
66
+ # Predict parts to replace
67
+ input_vector = np.concatenate([part_features.mean(axis=(1, 2)), damage_features.mean(axis=(1, 2))])
68
+ prediction = dl_model.predict(np.array([input_vector]))
69
+ predicted_parts = [(all_parts[i], float(prob)) for i, prob in enumerate(prediction[0]) if prob > 0.1]
70
+ predicted_parts.sort(key=lambda x: x[1], reverse=True)
71
+
72
+ return (Image.fromarray(annotated_image),
73
+ Image.fromarray(damage_heatmap_resized),
74
+ Image.fromarray(part_heatmap_resized),
75
+ "\n".join([f"{part}: {prob:.2f}" for part, prob in predicted_parts[:5]]))
76
+
77
+ def create_heatmap(features):
78
+ heatmap = np.sum(features, axis=0)
79
+ heatmap = (heatmap - heatmap.min()) / (heatmap.max() - heatmap.min())
80
+ heatmap = np.uint8(255 * heatmap)
81
+ return cv2.applyColorMap(heatmap, cv2.COLORMAP_JET)
82
+
83
+ iface = gr.Interface(
84
+ fn=process_image,
85
+ inputs=gr.Image(type="pil"),
86
+ outputs=[
87
+ gr.Image(type="pil", label="Annotated Damage"),
88
+ gr.Image(type="pil", label="Damage Heatmap"),
89
+ gr.Image(type="pil", label="Part Segmentation Heatmap"),
90
+ gr.Textbox(label="Predicted Parts to Replace")
91
+ ],
92
+ title="Car Damage Assessment",
93
+ description="Upload an image of a damaged car to get an assessment."
94
+ )
95
+
96
+ iface.launch()