dperales commited on
Commit
76f7bad
1 Parent(s): bfa34a7

Create app_v1.txt

Browse files
Files changed (1) hide show
  1. app_v1.txt +255 -0
app_v1.txt ADDED
@@ -0,0 +1,255 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ try:
2
+ import detectron2
3
+ except:
4
+ import os
5
+ os.system('pip install git+https://github.com/facebookresearch/detectron2.git')
6
+
7
+ import streamlit as st
8
+ from PIL import Image
9
+ from matplotlib.pyplot import axis
10
+ import requests
11
+ import numpy as np
12
+ from torch import nn
13
+ import requests
14
+ from annotated_text import annotated_text
15
+ from streamlit_option_menu import option_menu
16
+ import torch
17
+ import detectron2
18
+ from detectron2 import model_zoo
19
+ from detectron2.engine import DefaultPredictor
20
+ from detectron2.config import get_cfg
21
+ from detectron2.utils.visualizer import Visualizer
22
+ from detectron2.data import MetadataCatalog
23
+ from detectron2.utils.visualizer import ColorMode
24
+
25
+ damage_model_path = 'model_final_damage.pth'
26
+ scratch_model_path = 'model_final_scratch.pth'
27
+ parts_model_path = 'model_final_parts.pth'
28
+
29
+ if torch.cuda.is_available():
30
+ device = 'cuda'
31
+ else:
32
+ device = 'cpu'
33
+
34
+ cfg_scratches = get_cfg()
35
+ cfg_scratches.merge_from_file(model_zoo.get_config_file("COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_3x.yaml"))
36
+ cfg_scratches.MODEL.ROI_HEADS.SCORE_THRESH_TEST = 0.8
37
+ cfg_scratches.MODEL.ROI_HEADS.NUM_CLASSES = 1
38
+ cfg_scratches.MODEL.WEIGHTS = scratch_model_path
39
+ cfg_scratches.MODEL.DEVICE = device
40
+
41
+ predictor_scratches = DefaultPredictor(cfg_scratches)
42
+
43
+ metadata_scratch = MetadataCatalog.get("car_dataset_val")
44
+ metadata_scratch.thing_classes = ["scratch"]
45
+
46
+ cfg_damage = get_cfg()
47
+ cfg_damage.merge_from_file(model_zoo.get_config_file("COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_3x.yaml"))
48
+ cfg_damage.MODEL.ROI_HEADS.SCORE_THRESH_TEST = 0.7
49
+ cfg_damage.MODEL.ROI_HEADS.NUM_CLASSES = 1
50
+ cfg_damage.MODEL.WEIGHTS = damage_model_path
51
+ cfg_damage.MODEL.DEVICE = device
52
+
53
+ predictor_damage = DefaultPredictor(cfg_damage)
54
+
55
+ metadata_damage = MetadataCatalog.get("car_damage_dataset_val")
56
+ metadata_damage.thing_classes = ["damage"]
57
+
58
+ cfg_parts = get_cfg()
59
+ cfg_parts.merge_from_file(model_zoo.get_config_file("COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_3x.yaml"))
60
+ cfg_parts.MODEL.ROI_HEADS.SCORE_THRESH_TEST = 0.75
61
+ cfg_parts.MODEL.ROI_HEADS.NUM_CLASSES = 19
62
+ cfg_parts.MODEL.WEIGHTS = parts_model_path
63
+ cfg_parts.MODEL.DEVICE = device
64
+
65
+ predictor_parts = DefaultPredictor(cfg_parts)
66
+
67
+ metadata_parts = MetadataCatalog.get("car_parts_dataset_val")
68
+ metadata_parts.thing_classes = ['_background_',
69
+ 'back_bumper',
70
+ 'back_glass',
71
+ 'back_left_door',
72
+ 'back_left_light',
73
+ 'back_right_door',
74
+ 'back_right_light',
75
+ 'front_bumper',
76
+ 'front_glass',
77
+ 'front_left_door',
78
+ 'front_left_light',
79
+ 'front_right_door',
80
+ 'front_right_light',
81
+ 'hood',
82
+ 'left_mirror',
83
+ 'right_mirror',
84
+ 'tailgate',
85
+ 'trunk',
86
+ 'wheel']
87
+
88
+ def merge_segment(pred_segm):
89
+ merge_dict = {}
90
+ for i in range(len(pred_segm)):
91
+ merge_dict[i] = []
92
+ for j in range(i+1,len(pred_segm)):
93
+ if torch.sum(pred_segm[i]*pred_segm[j])>0:
94
+ merge_dict[i].append(j)
95
+
96
+ to_delete = []
97
+ for key in merge_dict:
98
+ for element in merge_dict[key]:
99
+ to_delete.append(element)
100
+
101
+ for element in to_delete:
102
+ merge_dict.pop(element,None)
103
+
104
+ empty_delete = []
105
+ for key in merge_dict:
106
+ if merge_dict[key] == []:
107
+ empty_delete.append(key)
108
+
109
+ for element in empty_delete:
110
+ merge_dict.pop(element,None)
111
+
112
+ for key in merge_dict:
113
+ for element in merge_dict[key]:
114
+ pred_segm[key]+=pred_segm[element]
115
+
116
+ except_elem = list(set(to_delete))
117
+
118
+ new_indexes = list(range(len(pred_segm)))
119
+ for elem in except_elem:
120
+ new_indexes.remove(elem)
121
+
122
+ return pred_segm[new_indexes]
123
+
124
+ def inference(image):
125
+ img = np.array(image)
126
+ outputs_damage = predictor_damage(img)
127
+ outputs_parts = predictor_parts(img)
128
+ outputs_scratch = predictor_scratches(img)
129
+ out_dict = outputs_damage["instances"].to("cpu").get_fields()
130
+ merged_damage_masks = merge_segment(out_dict['pred_masks'])
131
+ scratch_data = outputs_scratch["instances"].get_fields()
132
+ scratch_masks = scratch_data['pred_masks']
133
+ damage_data = outputs_damage["instances"].get_fields()
134
+ damage_masks = damage_data['pred_masks']
135
+ parts_data = outputs_parts["instances"].get_fields()
136
+ parts_masks = parts_data['pred_masks']
137
+ parts_classes = parts_data['pred_classes']
138
+ new_inst = detectron2.structures.Instances((1024,1024))
139
+ new_inst.set('pred_masks',merge_segment(out_dict['pred_masks']))
140
+
141
+ parts_damage_dict = {}
142
+ parts_list_damages = []
143
+ for part in parts_classes:
144
+ parts_damage_dict[metadata_parts.thing_classes[part]] = []
145
+ for mask in scratch_masks:
146
+ for i in range(len(parts_masks)):
147
+ if torch.sum(parts_masks[i]*mask)>0:
148
+ parts_damage_dict[metadata_parts.thing_classes[parts_classes[i]]].append('scratch')
149
+ parts_list_damages.append(f'{metadata_parts.thing_classes[parts_classes[i]]} has scratch')
150
+ print(f'{metadata_parts.thing_classes[parts_classes[i]]} has scratch')
151
+ for mask in merged_damage_masks:
152
+ for i in range(len(parts_masks)):
153
+ if torch.sum(parts_masks[i]*mask)>0:
154
+ parts_damage_dict[metadata_parts.thing_classes[parts_classes[i]]].append('damage')
155
+ parts_list_damages.append(f'{metadata_parts.thing_classes[parts_classes[i]]} has damage')
156
+ print(f'{metadata_parts.thing_classes[parts_classes[i]]} has damage')
157
+
158
+ v_d = Visualizer(img[:, :, ::-1],
159
+ metadata=metadata_damage,
160
+ scale=0.5,
161
+ instance_mode=ColorMode.SEGMENTATION # remove the colors of unsegmented pixels. This option is only available for segmentation models
162
+ )
163
+ #v_d = Visualizer(img,scale=1.2)
164
+ #print(outputs["instances"].to('cpu'))
165
+ out_d = v_d.draw_instance_predictions(new_inst)
166
+ img1 = out_d.get_image()[:, :, ::-1]
167
+
168
+ v_s = Visualizer(img[:, :, ::-1],
169
+ metadata=metadata_scratch,
170
+ scale=0.5,
171
+ instance_mode=ColorMode.SEGMENTATION # remove the colors of unsegmented pixels. This option is only available for segmentation models
172
+ )
173
+ #v_s = Visualizer(img,scale=1.2)
174
+ out_s = v_s.draw_instance_predictions(outputs_scratch["instances"])
175
+ img2 = out_s.get_image()[:, :, ::-1]
176
+
177
+ v_p = Visualizer(img[:, :, ::-1],
178
+ metadata=metadata_parts,
179
+ scale=0.5,
180
+ instance_mode=ColorMode.SEGMENTATION # remove the colors of unsegmented pixels. This option is only available for segmentation models
181
+ )
182
+ #v_p = Visualizer(img,scale=1.2)
183
+ out_p = v_p.draw_instance_predictions(outputs_parts["instances"])
184
+ img3 = out_p.get_image()[:, :, ::-1]
185
+
186
+ return img1, img2, img3, parts_list_damages
187
+
188
+ def main():
189
+ hide_streamlit_style = """
190
+ <style>
191
+ #MainMenu {visibility: hidden;}
192
+ footer {visibility: hidden;}
193
+ </style>
194
+ """
195
+ st.markdown(hide_streamlit_style, unsafe_allow_html=True)
196
+
197
+ with st.sidebar:
198
+ image = Image.open('itaca_logo.png')
199
+ st.image(image, width=150) #,use_column_width=True)
200
+ page = option_menu(menu_title='Menu',
201
+ menu_icon="robot",
202
+ options=["Damage Detection",
203
+ "Under Construction"],
204
+ icons=["camera",
205
+ "key"],
206
+ default_index=0
207
+ )
208
+
209
+ # Additional section below the option menu
210
+ # st.markdown("---") # Add a separator line
211
+ # st.header("Settings")
212
+
213
+ st.title('ITACA Insurance Core AI Module')
214
+
215
+ if page == "Damage Detection":
216
+ st.header('Car Parts Damage Detection')
217
+
218
+ st.write(
219
+ """
220
+ """
221
+ )
222
+
223
+ uploaded_file = st.file_uploader("Upload an image:")
224
+
225
+ # Check if a file has been uploaded
226
+ if uploaded_file is not None:
227
+ # Load and display the image
228
+ image = Image.open(uploaded_file)
229
+ st.image(image, caption="Uploaded image")
230
+
231
+ else:
232
+ st.write("Please upload an image.")
233
+
234
+ if st.button("Prediction"):
235
+ with st.spinner("Loading..."):
236
+ # Call the inference function with the uploaded image
237
+ imagen1, imagen2, imagen3, partes = inference(image)
238
+
239
+ st.image(imagen1, caption="crash image1")
240
+ st.image(imagen2, caption="crash image2")
241
+ st.image(imagen3, caption="crash image3")
242
+ st.table(partes)
243
+
244
+ elif page == "Under Construction":
245
+ st.header('Under Construction')
246
+
247
+ st.write(
248
+ """
249
+ """
250
+ )
251
+
252
+ try:
253
+ main()
254
+ except Exception as e:
255
+ st.sidebar.error(f"An error occurred: {e}")