Update app.py
Browse files
app.py
CHANGED
@@ -6,43 +6,77 @@ import cv2
|
|
6 |
from tensorflow.keras.models import load_model
|
7 |
from keras.preprocessing.image import img_to_array
|
8 |
from keras.applications.inception_v3 import preprocess_input
|
9 |
-
import
|
|
|
|
|
10 |
from PIL import Image
|
11 |
import io
|
12 |
from datetime import datetime
|
13 |
import pandas as pd
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
"dpoc_category_id": 1, # You can dynamically set this if needed
|
24 |
-
"title": title,
|
25 |
-
"description": description,
|
26 |
-
"created_at": now,
|
27 |
-
"updated_at": now,
|
28 |
-
"deleted_at": ""
|
29 |
-
}
|
30 |
-
st.session_state.dpoc_list.append(entry)
|
31 |
-
# Defect categories
|
32 |
class_labels = [
|
33 |
-
"
|
34 |
-
"
|
35 |
-
"
|
36 |
-
"
|
37 |
-
"
|
38 |
-
|
39 |
-
"Pot holes",
|
40 |
-
"Shade fading"
|
41 |
]
|
42 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
43 |
@st.cache_resource
|
44 |
def load_trained_model():
|
45 |
-
|
|
|
|
|
|
|
|
|
46 |
|
47 |
def compress_image(image_bytes, max_size_kb=500):
|
48 |
img = Image.open(io.BytesIO(image_bytes))
|
@@ -57,283 +91,797 @@ def compress_image(image_bytes, max_size_kb=500):
|
|
57 |
quality -= 5
|
58 |
return output_bytes.getvalue()
|
59 |
|
60 |
-
def
|
61 |
-
|
62 |
-
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
|
67 |
-
|
68 |
-
|
69 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
70 |
|
71 |
-
|
72 |
-
|
73 |
-
if category_choice == "Flooring":
|
74 |
-
st.markdown("Upload a wall surface image to detect potential defects and generate a structured AI analysis.")
|
75 |
-
|
76 |
-
|
77 |
-
uploaded_file = st.file_uploader("π€ Upload an Image", type=["jpg", "jpeg", "png"])
|
78 |
-
|
79 |
-
if uploaded_file is not None:
|
80 |
-
file_bytes = uploaded_file.getvalue()
|
81 |
-
|
82 |
-
st.image(file_bytes, caption="πΌοΈ Uploaded Image", use_column_width=True)
|
83 |
-
|
84 |
-
# Preprocess for prediction
|
85 |
-
input_img = cv2.imdecode(np.frombuffer(file_bytes, np.uint8), cv2.IMREAD_COLOR)
|
86 |
-
input_img_resized = cv2.resize(input_img, (256, 256))
|
87 |
x = img_to_array(input_img_resized)
|
88 |
x = np.expand_dims(x, axis=0)
|
89 |
x = preprocess_input(x)
|
90 |
-
|
91 |
-
|
92 |
-
|
93 |
-
|
94 |
-
|
95 |
-
|
96 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
97 |
class_name = class_labels[class_index]
|
98 |
-
print(class_name)
|
99 |
-
|
100 |
-
# Classification Result Display
|
101 |
-
st.subheader("π Classification Result")
|
102 |
-
st.success(f"**Predicted Defect:** {class_name}")
|
103 |
-
st.progress(min(int(max_probability * 100), 100))
|
104 |
-
st.markdown(f"**Confidence Level:** {max_probability:.2%}")
|
105 |
-
|
106 |
-
if max_probability < 0.59:
|
107 |
-
st.warning("β οΈ The confidence score is below 59%. Please manually verify this result.")
|
108 |
-
else:
|
109 |
-
compressed_base64 = process_image_for_openai(file_bytes)
|
110 |
-
ai_content = """
|
111 |
-
You are an expert in identifying and resolving wall and flooring defects. Use the dataset below to generate all applicable recommended solutions for any provided defect or combination of defects.
|
112 |
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
|
117 |
-
|
118 |
-
|
119 |
-
|
120 |
-
If the defect is not found in the dataset, use semantic analysis and your domain expertise to generate a logical and professional solution.
|
121 |
-
|
122 |
-
Do not mention whether the defect is listed in the dataset or not β simply return the recommended solution.
|
123 |
-
|
124 |
-
Use clear steps such as: surface preparation, grinding, priming, coating, sealing, repairing, joint treatment, or finishing, depending on the nature of the defect
|
125 |
-
|
126 |
-
|
127 |
-
|
128 |
-
|
129 |
-
Dataset:
|
130 |
-
|
131 |
-
|
132 |
-
Defect: Spike Roller Mark
|
133 |
-
Sub-Defect Type: Epoxy
|
134 |
-
Recommended Solution:
|
135 |
-
1. Surface preparation on existing resinious flooring by light grinding.
|
136 |
-
2. Application of Primer.
|
137 |
-
3. Application of thin film coating with Apcoflor TC 510
|
138 |
-
|
139 |
-
Defect: Spike Roller Mark
|
140 |
-
Sub-Defect Type: PU
|
141 |
-
Recommended Solution:
|
142 |
-
1. Surface preparation on existing resinious flooring by light grinding.
|
143 |
-
2. Application of Primer.
|
144 |
-
3. Application of thin film coating with Apcoflor PUV
|
145 |
-
|
146 |
-
Defect: Trowel Mark
|
147 |
-
Sub-Defect Type: Epoxy
|
148 |
-
Recommended Solution:
|
149 |
-
1. Surface preparation on existing resinious flooring by light grinding.
|
150 |
-
2. Application of Primer.
|
151 |
-
3. Application of epoxy topcoat with 1mm thickness using Apcoflor SL1TC
|
152 |
-
|
153 |
-
Defect: Trowel Mark
|
154 |
-
Sub-Defect Type: PU
|
155 |
-
Recommended Solution:
|
156 |
-
1. Surface preparation on existing resinious flooring by light grinding
|
157 |
-
2. Groove cutting
|
158 |
-
3. Application of PU scratch coat
|
159 |
-
4. Application of Topcoat with 1 to 2 mm thickness
|
160 |
-
|
161 |
-
Defect: Bubble Formation
|
162 |
-
Sub-Defect Type: Epoxy
|
163 |
-
Recommended Solution:
|
164 |
-
1. Surface preparation on existing resinious flooring by light grinding.
|
165 |
-
2. Application of Primer.
|
166 |
-
3. Application of thin film coating with Apcoflor TC 510
|
167 |
-
|
168 |
-
Defect: Bubble Formation
|
169 |
-
Sub-Defect Type: PU
|
170 |
-
Recommended Solution:
|
171 |
-
1. Surface preparation on existing resinious flooring by light grinding
|
172 |
-
2. Groove cutting
|
173 |
-
3. Application of PU scratch coat
|
174 |
-
4. Application of Topcoat with 1 to 5 mm thickness
|
175 |
-
|
176 |
-
Defect: Peel off/Debonding
|
177 |
-
Sub-Defect Type: Epoxy
|
178 |
-
Recommended Solution:
|
179 |
-
1. Surface preparation on existing resinious flooring by light grinding
|
180 |
-
2. Removing all loose resinious flooring
|
181 |
-
3. Application of Primer
|
182 |
-
4. Application of thin film coating with Apcoflor TC 510/Apcoflor SL1TC
|
183 |
|
184 |
-
|
185 |
-
|
186 |
-
|
187 |
-
|
188 |
-
|
189 |
-
|
190 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
191 |
|
192 |
-
Defect: Shade Variation
|
193 |
-
Sub-Defect Type: Epoxy
|
194 |
-
Recommended Solution:
|
195 |
-
1. Surface preparation on existing resinious flooring by light grinding
|
196 |
-
2. Application of Primer
|
197 |
-
3. Application of thin film coating with Apcoflor TC 510/Apcoflor SL1 TC
|
198 |
|
199 |
-
|
200 |
-
|
201 |
-
|
202 |
-
|
203 |
-
|
204 |
-
|
|
|
|
|
205 |
|
206 |
-
|
207 |
-
|
208 |
-
Recommended Solution:
|
209 |
-
1. Surface preparation - opening the cracks in "V" groove
|
210 |
-
2. Application of Primer
|
211 |
-
3. Application of epoxy putty using Apcoflor LSC3 XL
|
212 |
|
213 |
-
|
214 |
-
Sub-Defect Type: Cracking & Spalling of Joint Edge
|
215 |
-
Recommended Solution:
|
216 |
-
1. Crack Treatment - Open cracks in "V" groove
|
217 |
-
- Apply Epoxy Primer
|
218 |
-
- Apply epoxy putty using Apcoflor LSC3 XL
|
219 |
-
2. Joint Edge Treatment
|
220 |
-
- Remove loose concrete
|
221 |
-
- Apply Epoxy mortar using Apcoflor HFP 120 + special sand at 1:3.5 mix ratio
|
222 |
-
- Apply at damaged joint edges
|
223 |
|
224 |
-
|
225 |
-
Sub-Defect Type: Sealant Failure
|
226 |
-
Recommended Solution:
|
227 |
-
1. Apply PU-based backer rod
|
228 |
-
2. Apply PU/Polysulphide Sealant over the backer rod up to the top of the joint edges
|
229 |
-
3. Provide protection using self-adhesive tapes or aluminum stripping
|
230 |
-
|
231 |
-
Defect: Construction Joint
|
232 |
-
Sub-Defect Type: -
|
233 |
-
Recommended Solution:
|
234 |
-
1. Remove dust/impurities from joints
|
235 |
-
2. Apply Primer
|
236 |
-
3. Apply Epoxy SL Screed or PU Screed
|
237 |
-
|
238 |
-
Defect: Wall & Floor Junction Coving
|
239 |
-
Sub-Defect Type: -
|
240 |
-
Recommended Solution:
|
241 |
-
1. Surface preparation
|
242 |
-
2. Apply Epoxy Primer or scratch coat
|
243 |
-
3. Apply Epoxy mortar using Apcoflor HFP 120 + special graded sand at 1:3 mixing ratio
|
244 |
-
|
245 |
-
Defect: Flooring - POT Holes
|
246 |
-
Sub-Defect Type: -
|
247 |
-
Recommended Solution:
|
248 |
-
1. Surface preparation - Cut the pothole in square/rectangle shape, remove dust/oil
|
249 |
-
2. Apply Epoxy Primer
|
250 |
-
3. Apply Apcoflor HFP 120 + special graded sand at 1:3 mix ratio
|
251 |
-
4. Finish/level the surface
|
252 |
-
|
253 |
-
Fallback Logic for Unknown Defects:
|
254 |
-
Use these patterns to infer the solution without stating the defect is not listed.
|
255 |
-
|
256 |
-
Structural Defect:
|
257 |
-
|
258 |
-
Cut/clean damaged area
|
259 |
-
|
260 |
-
Surface preparation (light grinding or cutting)
|
261 |
-
|
262 |
-
Apply epoxy/PU primer
|
263 |
-
|
264 |
-
Apply screed or mortar (e.g., Apcoflor HFP 120 + sand)
|
265 |
|
266 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
267 |
|
268 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
269 |
|
270 |
-
Surface preparation by light grinding
|
271 |
|
272 |
-
Application of appropriate primer
|
273 |
|
274 |
-
|
|
|
|
|
|
|
275 |
|
276 |
-
|
277 |
|
278 |
-
|
279 |
|
280 |
-
|
|
|
|
|
281 |
|
282 |
-
|
283 |
|
284 |
-
Fill with epoxy putty (e.g., Apcoflor LSC3 XL)
|
285 |
|
286 |
-
Joint Issues:
|
287 |
|
288 |
-
|
|
|
|
|
289 |
|
290 |
-
Apply epoxy primer
|
291 |
|
292 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
293 |
|
294 |
-
|
|
|
295 |
|
|
|
|
|
296 |
|
297 |
-
|
|
|
|
|
298 |
|
299 |
-
ai_prompt = (
|
300 |
-
f"Our trained model predicts the following defect: {class_name}. "
|
301 |
-
|
302 |
-
f"for this defect? The output format should be:\n"
|
303 |
-
f"Category ID: <Insert Category ID>\n"
|
304 |
-
f"Title: <Short Title of the Defect>\n"
|
305 |
-
f"Description: <A concise, technical description in 100 words or less>"
|
306 |
-
)
|
307 |
|
308 |
-
|
309 |
-
|
310 |
-
response = openai.ChatCompletion.create(
|
311 |
-
model="gpt-4o",
|
312 |
-
messages=[
|
313 |
-
{
|
314 |
-
"role": "system",
|
315 |
-
"content": ai_content
|
316 |
-
},
|
317 |
-
{
|
318 |
-
"role":"user",
|
319 |
-
"content":f"Generate recommended solutions for this defect '{class_name}'"
|
320 |
-
}
|
321 |
-
],
|
322 |
-
max_tokens=600,
|
323 |
-
)
|
324 |
-
ai_description = response.choices[0].message.content
|
325 |
-
st.subheader("π AI-Generated Defect Description")
|
326 |
-
st.text_area("Output", value=ai_description.strip(), height=250)
|
327 |
-
except Exception as e:
|
328 |
-
st.error(f"β An error occurred while generating the description:\n{e}")
|
329 |
-
add_dpoc_entry(class_name, ai_description.strip())
|
330 |
-
st.subheader("π DPOC")
|
331 |
-
if st.session_state.dpoc_list:
|
332 |
-
dpoc_df = pd.DataFrame(st.session_state.dpoc_list)
|
333 |
-
st.dataframe(dpoc_df, use_container_width=True)
|
334 |
-
st.download_button("π₯ Download CSV", dpoc_df.to_csv(index=False), "dpoc_log.csv", "text/csv")
|
335 |
-
else:
|
336 |
-
st.info("No entries yet. Upload an image to start.")
|
337 |
|
338 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
339 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
6 |
from tensorflow.keras.models import load_model
|
7 |
from keras.preprocessing.image import img_to_array
|
8 |
from keras.applications.inception_v3 import preprocess_input
|
9 |
+
import requests
|
10 |
+
import json_repair
|
11 |
+
import json
|
12 |
from PIL import Image
|
13 |
import io
|
14 |
from datetime import datetime
|
15 |
import pandas as pd
|
16 |
+
import re
|
17 |
+
from json_repair import repair_json
|
18 |
+
from dotenv import load_dotenv
|
19 |
+
import os
|
20 |
+
|
21 |
+
# Load environment variables
|
22 |
+
load_dotenv()
|
23 |
+
|
24 |
+
# Class labels for defect prediction
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
25 |
class_labels = [
|
26 |
+
"algae",
|
27 |
+
"bubbles",
|
28 |
+
"Cracks",
|
29 |
+
"Fungus",
|
30 |
+
"peeling",
|
31 |
+
|
|
|
|
|
32 |
]
|
33 |
|
34 |
+
# Set OpenAI API key
|
35 |
+
openai.api_key = os.getenv("OPENAI_API_KEY")
|
36 |
+
|
37 |
+
# Page configuration
|
38 |
+
st.set_page_config(
|
39 |
+
page_title="Painting Defect Detection System",
|
40 |
+
page_icon="π",
|
41 |
+
layout="wide",
|
42 |
+
initial_sidebar_state="expanded"
|
43 |
+
)
|
44 |
+
|
45 |
+
# Custom CSS for better styling
|
46 |
+
st.markdown("""
|
47 |
+
<style>
|
48 |
+
.main {
|
49 |
+
padding-top: 2rem;
|
50 |
+
}
|
51 |
+
.stAlert {
|
52 |
+
margin-top: 1rem;
|
53 |
+
}
|
54 |
+
.defect-card {
|
55 |
+
border: 1px solid #ddd;
|
56 |
+
border-radius: 8px;
|
57 |
+
padding: 1rem;
|
58 |
+
margin: 1rem 0;
|
59 |
+
background-color: #f9f9f9;
|
60 |
+
}
|
61 |
+
.metric-card {
|
62 |
+
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
63 |
+
padding: 1rem;
|
64 |
+
border-radius: 8px;
|
65 |
+
color: white;
|
66 |
+
text-align: center;
|
67 |
+
margin: 0.5rem 0;
|
68 |
+
}
|
69 |
+
</style>
|
70 |
+
""", unsafe_allow_html=True)
|
71 |
+
|
72 |
+
# Cache the model loading to improve performance
|
73 |
@st.cache_resource
|
74 |
def load_trained_model():
|
75 |
+
try:
|
76 |
+
return load_model('painting.keras')
|
77 |
+
except Exception as e:
|
78 |
+
st.error(f"Error loading model: {str(e)}")
|
79 |
+
return None
|
80 |
|
81 |
def compress_image(image_bytes, max_size_kb=500):
|
82 |
img = Image.open(io.BytesIO(image_bytes))
|
|
|
91 |
quality -= 5
|
92 |
return output_bytes.getvalue()
|
93 |
|
94 |
+
def get_direct_drive_url(share_url):
|
95 |
+
if "drive.google.com/file/d/" in share_url:
|
96 |
+
file_id = share_url.split("/file/d/")[1].split("/")[0]
|
97 |
+
return f"https://drive.google.com/uc?export=download&id={file_id}"
|
98 |
+
return share_url
|
99 |
+
|
100 |
+
def process_image(url):
|
101 |
+
try:
|
102 |
+
file_id = re.search(r'/d/(.*?)/', url)
|
103 |
+
if file_id: # Google Drive share link
|
104 |
+
url = f'https://drive.google.com/uc?export=download&id={file_id.group(1)}'
|
105 |
+
|
106 |
+
resp = requests.get(url, timeout=15)
|
107 |
+
resp.raise_for_status()
|
108 |
+
|
109 |
+
if 'image' not in resp.headers.get('Content-Type', ''):
|
110 |
+
raise ValueError('URL does not point to an image')
|
111 |
|
112 |
+
img = cv2.imdecode(np.frombuffer(resp.content, np.uint8), cv2.IMREAD_COLOR)
|
113 |
+
input_img_resized = cv2.resize(img, (256, 256))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
114 |
x = img_to_array(input_img_resized)
|
115 |
x = np.expand_dims(x, axis=0)
|
116 |
x = preprocess_input(x)
|
117 |
+
return x, resp.content
|
118 |
+
except Exception as e:
|
119 |
+
st.error(f"Error processing image from URL: {e}")
|
120 |
+
return None, None
|
121 |
+
|
122 |
+
def process_uploaded_image(uploaded_file):
|
123 |
+
try:
|
124 |
+
image_bytes = uploaded_file.read()
|
125 |
+
img = Image.open(io.BytesIO(image_bytes))
|
126 |
+
img_array = np.array(img)
|
127 |
+
|
128 |
+
# Convert RGB to BGR for OpenCV
|
129 |
+
if len(img_array.shape) == 3:
|
130 |
+
img_array = cv2.cvtColor(img_array, cv2.COLOR_RGB2BGR)
|
131 |
+
|
132 |
+
input_img_resized = cv2.resize(img_array, (256, 256))
|
133 |
+
x = img_to_array(input_img_resized)
|
134 |
+
x = np.expand_dims(x, axis=0)
|
135 |
+
x = preprocess_input(x)
|
136 |
+
|
137 |
+
return x, image_bytes
|
138 |
+
except Exception as e:
|
139 |
+
st.error(f"Error processing uploaded image: {e}")
|
140 |
+
return None, None
|
141 |
+
|
142 |
+
def predict_defect(processed_image, model):
|
143 |
+
try:
|
144 |
+
preds = model.predict(processed_image)[0]
|
145 |
+
class_index = int(np.argmax(preds))
|
146 |
+
confidence = float(preds[class_index])
|
147 |
class_name = class_labels[class_index]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
148 |
|
149 |
+
return {
|
150 |
+
"type": class_name,
|
151 |
+
"severity": confidence
|
152 |
+
}, class_index
|
153 |
+
except Exception as e:
|
154 |
+
return {"error": str(e)}, []
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
155 |
|
156 |
+
def compress_image_to_base64(image_bytes, max_size_kb=500):
|
157 |
+
img = Image.open(io.BytesIO(image_bytes)).convert("RGB")
|
158 |
+
output_bytes = io.BytesIO()
|
159 |
+
quality = 95
|
160 |
+
while True:
|
161 |
+
output_bytes.seek(0)
|
162 |
+
output_bytes.truncate()
|
163 |
+
img.save(output_bytes, format='JPEG', quality=quality)
|
164 |
+
if len(output_bytes.getvalue()) <= max_size_kb * 1024 or quality <= 5:
|
165 |
+
break
|
166 |
+
quality -= 5
|
167 |
+
return base64.b64encode(output_bytes.getvalue()).decode('utf-8')
|
168 |
+
|
169 |
+
def generate_openai_description(classification, image_bytes):
|
170 |
+
try:
|
171 |
+
if isinstance(classification, dict) and 'type' in classification:
|
172 |
+
defect_type = classification['type']
|
173 |
+
elif isinstance(classification, dict) and 'error' in classification:
|
174 |
+
defect_type = "Unknown defect"
|
175 |
+
else:
|
176 |
+
defect_type = str(classification)
|
177 |
+
|
178 |
+
# Compress and encode image to base64
|
179 |
+
compressed_base64 = compress_image_to_base64(image_bytes)
|
180 |
+
ai_prompt = (
|
181 |
+
f"You are an expert painting inspector analyzing surface defects."
|
182 |
+
f"DETECTED DEFECTS: {defect_type}"
|
183 |
+
f"TASK: Examine the painted surface image and provide a technical description of the visible defects."
|
184 |
+
f"REQUIREMENTS:"
|
185 |
+
f"- Write 200 characters describing what you observe"
|
186 |
+
f"- Focus on visible paint failures, surface irregularities, or coating issues"
|
187 |
+
f"- Use professional painting and coating terminology"
|
188 |
+
f"- Be specific about location, extent, and characteristics of defects"
|
189 |
+
f"- If multiple defects are present, describe each one"
|
190 |
+
f"- Maintain an objective, technical tone"
|
191 |
+
f"Dont use \\n"
|
192 |
+
f"IMPORTANT: Always provide a description based on what you can see in the image. "
|
193 |
+
f"Even if the detected defect types seem unclear, describe the actual visible conditions "
|
194 |
+
f"in the painted surface. Only respond with 'Unable to generate description due to "
|
195 |
+
f"image quality issues' if the image is genuinely too blurry, dark, or corrupted to analyze."
|
196 |
+
f"Begin your description now:")
|
197 |
+
|
198 |
+
|
199 |
+
|
200 |
+
# Call OpenAI with image and text
|
201 |
+
response = openai.chat.completions.create(
|
202 |
+
model="gpt-4o",
|
203 |
+
messages=[
|
204 |
+
{
|
205 |
+
"role": "user",
|
206 |
+
"content": [
|
207 |
+
{"type": "text", "text": ai_prompt},
|
208 |
+
{"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{compressed_base64}"}}
|
209 |
+
]
|
210 |
+
}
|
211 |
+
]
|
212 |
+
)
|
213 |
+
|
214 |
+
result_text = response.choices[0].message.content.strip()
|
215 |
+
return result_text
|
216 |
+
|
217 |
+
except Exception as e:
|
218 |
+
return f"Error generating description: {str(e)}"
|
219 |
|
|
|
|
|
|
|
|
|
|
|
|
|
220 |
|
221 |
+
|
222 |
+
|
223 |
+
def get_sps(defect_type, flooring_type,defect_category="flooring"):
|
224 |
+
ai_content = """ You are an expert in identifying and resolving painting and wall surface defects.
|
225 |
+
Your task is to accept a defect name and surface type as input and return applicable solutions using the structured dataset below.
|
226 |
+
IMPORTANT: You MUST respond with valid JSON only. Do not include any explanatory text before or after the JSON.
|
227 |
+
Instructions:
|
228 |
+
Return TWO separate categories of solutions:
|
229 |
|
230 |
+
MANDATORY SPS: Solutions specifically matching the input defect
|
231 |
+
OPTIONAL SPS: Solutions from 'All Defects' records (universal solutions)
|
|
|
|
|
|
|
|
|
232 |
|
233 |
+
For MANDATORY SPS:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
234 |
|
235 |
+
Match the input defect against the 'Defects' column using:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
236 |
|
237 |
+
Exact match
|
238 |
+
Partial match (e.g. 'Cracks' matches all 'Cracks' records)
|
239 |
+
|
240 |
+
|
241 |
+
EXCLUDE any 'All Defects' records from this section
|
242 |
+
Only return records where the 'Category' matches the specified surface type (NonWaterproofing or Waterproofing)
|
243 |
+
|
244 |
+
For OPTIONAL SPS:
|
245 |
+
|
246 |
+
ONLY include records where 'Defects' is 'All Defects', 'ALL Defects', or 'All Defect'
|
247 |
+
Filter by surface type:
|
248 |
+
|
249 |
+
If surface_type is "NonWaterproofing": Return records with Category="NonWaterproofing"
|
250 |
+
If surface_type is "Waterproofing": Return records with Category="Waterproofing"
|
251 |
+
|
252 |
+
|
253 |
+
Return only those matching the specified surface type
|
254 |
+
|
255 |
+
For each valid record in both categories:
|
256 |
+
|
257 |
+
Use the id from the dataset. If not available, generate a unique numeric ID.
|
258 |
+
Use the title from the dataset. If not available, use appropriate fallback title based on surface type
|
259 |
+
Use the description from the dataset exactly (verbatim). If not found, generate fallback content based on best practices.
|
260 |
+
CRITICAL FOR PRODUCT EXTRACTION:
|
261 |
+
|
262 |
+
Carefully analyze the description content for ANY product names, brand names, or material references
|
263 |
+
Extract ALL product names mentioned in the description, including:
|
264 |
+
|
265 |
+
Brand names (e.g., "Asian Paints SmartCare Crack Seal")
|
266 |
+
Generic product names (e.g., "Economy Primer", "Ace Suprema")
|
267 |
+
Material names (e.g., "white cement", "fine sand")
|
268 |
+
Tool names (e.g., "Putty Knife", "Paint Scraper")
|
269 |
+
Chemical names (e.g., "oxygen bleach", "chlorinated bleach")
|
270 |
+
|
271 |
+
|
272 |
+
List them in products array, assigning a unique ID per product
|
273 |
+
NEVER leave products array empty - if no specific products are mentioned, include generic alternatives like "Primer", "Paint", "Cleaning Solution", etc.
|
274 |
+
|
275 |
+
|
276 |
+
Include all records where Category matches the filtering condition
|
277 |
+
IMPORTANT: Remove all HTML tags from the description content. Convert HTML lists to plain text format.
|
278 |
+
|
279 |
+
Product Extraction Examples:
|
280 |
+
|
281 |
+
"Use Asian Paints SmartCare Crack Seal" β Extract: "Asian Paints SmartCare Crack Seal"
|
282 |
+
"Economy Primer, Ace Suprema" β Extract: "Economy Primer", "Ace Suprema"
|
283 |
+
"Use boiling water, pressure washers, oxygen bleach" β Extract: "Pressure Washer", "Oxygen Bleach"
|
284 |
+
"Sand with medium-grit sandpaper" β Extract: "Medium-grit Sandpaper"
|
285 |
+
|
286 |
+
|
287 |
+
|
288 |
+
If no matching dataset entry is found for MANDATORY SPS, return one fallback solution following industry-standard practices for the specified surface type (without stating it is a fallback).
|
289 |
+
Each solution must follow standard practices such as:
|
290 |
+
|
291 |
+
Surface preparation
|
292 |
+
Cleaning and washing
|
293 |
+
Priming
|
294 |
+
Crack filling
|
295 |
+
Sanding
|
296 |
+
Paint application
|
297 |
+
Sealing
|
298 |
+
Moisture treatment
|
299 |
+
Finishing
|
300 |
+
Each solution must follow standard practices such as:
|
301 |
+
- Surface preparation
|
302 |
+
- Cleaning and washing
|
303 |
+
- Priming
|
304 |
+
- Crack filling
|
305 |
+
- Sanding
|
306 |
+
- Paint application
|
307 |
+
- Sealing
|
308 |
+
- Moisture treatment
|
309 |
+
- Finishing
|
310 |
+
|
311 |
+
Return ONLY this JSON format (no other text):
|
312 |
+
|
313 |
+
{
|
314 |
+
"mandatory_sps": [
|
315 |
+
{
|
316 |
+
"id": 181,
|
317 |
+
"title": "Surface Preparation for Cracks - NonWaterproofing",
|
318 |
+
"content": "New masonry surfaces must be allowed to cure completely. It is recommended to allow 28 days as the curing time for new masonry surfaces. Opening the cracks with the help of a grinder/cutter and cleaning the surface with pressure washers for further treatment. FILLING FOR CRACKS For filling cracks up to 3mm, use Asian Paints SmartCare Crack Seal. For filling cracks more than 3mm, use Asian Paints SmartCare Textured Crack Filler. FILLING FOR HOLES & DENTS In case of dents and holes, use TruCare Wall Putty Suprema or a mix of white cement and fine sand in the ratio 1:3.",
|
319 |
+
"products": [
|
320 |
+
{
|
321 |
+
"id": 1,
|
322 |
+
"product_name": "Asian Paints SmartCare Crack Seal"
|
323 |
+
},
|
324 |
+
{
|
325 |
+
"id": 2,
|
326 |
+
"product_name": "Asian Paints SmartCare Textured Crack Filler"
|
327 |
+
},
|
328 |
+
{
|
329 |
+
"id": 3,
|
330 |
+
"product_name": "TruCare Wall Putty Suprema"
|
331 |
+
}
|
332 |
+
]
|
333 |
+
}
|
334 |
+
],
|
335 |
+
"optional_sps": [
|
336 |
+
{
|
337 |
+
"id": 211,
|
338 |
+
"title": "4 Year Paint Warranty System - NonWaterproofing",
|
339 |
+
"content": "Economy Primer, Ace Suprema",
|
340 |
+
"products": [
|
341 |
+
{
|
342 |
+
"id": 4,
|
343 |
+
"product_name": "Economy Primer"
|
344 |
+
},
|
345 |
+
{
|
346 |
+
"id": 5,
|
347 |
+
"product_name": "Ace Suprema"
|
348 |
+
}
|
349 |
+
]
|
350 |
+
}
|
351 |
+
]
|
352 |
+
}
|
353 |
|
354 |
+
Dataset:
|
355 |
+
|
356 |
+
id: 181
|
357 |
+
Defects: Cracks
|
358 |
+
Category: NonWaterproofing
|
359 |
+
title: Surface Preparation for Cracks - NonWaterproofing
|
360 |
+
description: New masonry surfaces must be allowed to cure completely. It is recommended to allow 28 days as the curing time for new masonry surfaces. Opening the cracks with the help of a grinder/cutter and cleaning the surface with pressure washers for further treatment.
|
361 |
+
|
362 |
+
FILLING FOR CRACKS
|
363 |
+
For filling cracks up to 3mm, use Asian Paints SmartCare Crack Seal.
|
364 |
+
For filling cracks more than 3mm, use Asian Paints SmartCare Textured Crack Filler.
|
365 |
+
|
366 |
+
FILLING FOR HOLES & DENTS
|
367 |
+
In case of dents and holes, use TruCare Wall Putty Suprema or a mix of white cement and fine sand in the ratio 1:3.
|
368 |
+
|
369 |
+
id: 182
|
370 |
+
Defects: Cracks
|
371 |
+
Category: Waterproofing
|
372 |
+
title: Surface Preparation for Cracks - Waterproofing
|
373 |
+
description: New masonry surfaces must be allowed to cure completely. It is recommended to allow 28 days as the curing time for new masonry surfaces. Opening the cracks with the help of a grinder/cutter and cleaning the surface with pressure washers for further treatment.
|
374 |
+
|
375 |
+
FILLING FOR CRACKS
|
376 |
+
For filling cracks up to 3mm, use Asian Paints SmartCare Crack Seal.
|
377 |
+
For filling cracks more than 3mm, use Asian Paints SmartCare Textured Crack Filler.
|
378 |
+
|
379 |
+
FILLING FOR HOLES & DENTS
|
380 |
+
In case of dents and holes, use TruCare Wall Putty Suprema or a mix of white cement and fine sand in the ratio 1:3.
|
381 |
+
|
382 |
+
id: 183
|
383 |
+
Defects: Patchiness
|
384 |
+
Category: NonWaterproofing
|
385 |
+
title: Surface Preparation for Patchiness - NonWaterproofing
|
386 |
+
description: Sand the surface with medium-grit sandpaper to remove major surface irregularities bumps and rough patches. Switch to fine-grit sandpaper for final smoothing. Work in small circular motions overlapping each area. Remove all sanding dust by cleaning the surface with pressure washers for further treatment
|
387 |
+
|
388 |
+
id: 184
|
389 |
+
Defects: Patchiness
|
390 |
+
Category: Waterproofing
|
391 |
+
title: Surface Preparation for Patchiness - Waterproofing
|
392 |
+
description: Sand the surface with medium-grit sandpaper to remove major surface irregularities bumps and rough patches. Switch to fine-grit sandpaper for final smoothing. Work in small circular motions overlapping each area. Remove all sanding dust by cleaning the surface with pressure washers for further treatment
|
393 |
+
|
394 |
+
id: 185
|
395 |
+
Defects: Peeling
|
396 |
+
Category: NonWaterproofing
|
397 |
+
title: Surface Preparation for Peeling - NonWaterproofing
|
398 |
+
description: Use Putty Knife or Paint Scraper for removing loose and peeling paint without damaging the underlying surface.Sand the surface with medium-grit sandpaper to remove major surface irregularities bumps and rough patches. Switch to fine-grit sandpaper for final smoothing. Work in small circular motions overlapping each area. Remove all sanding dust by cleaning the surface for further treatment
|
399 |
+
Surface should be free from any loose paint, dust or grease.Growths of fungus, algae or moss should be removed by wire brushing and water.
|
400 |
+
|
401 |
+
id: 186
|
402 |
+
Defects: Peeling
|
403 |
+
Category: Waterproofing
|
404 |
+
title: Surface Preparation for Peeling - Waterproofing
|
405 |
+
description: Use Putty Knife or Paint Scraper for removing loose and peeling paint without damaging the underlying surface.Sand the surface with medium-grit sandpaper to remove major surface irregularities bumps and rough patches. Switch to fine-grit sandpaper for final smoothing. Work in small circular motions overlapping each area. Remove all sanding dust by cleaning the surface for further treatment
|
406 |
+
Surface should be free from any loose paint, dust or grease.Growths of fungus, algae or moss should be removed by wire brushing and water.
|
407 |
+
|
408 |
+
id: 187
|
409 |
+
Defects: Algae
|
410 |
+
Category: NonWaterproofing
|
411 |
+
title: Surface Preparation for Algae - NonWaterproofing
|
412 |
+
description: Use boiling water, pressure washers, oxygen bleach, chlorinated bleach, and commercial algae removers to get rid of green algae on concrete. Pressure wash and scrape the wall with a soft brush
|
413 |
+
|
414 |
+
id: 188
|
415 |
+
Defects: Algae
|
416 |
+
Category: Waterproofing
|
417 |
+
title: Surface Preparation for Algae - Waterproofing
|
418 |
+
description: Use boiling water, pressure washers, oxygen bleach, chlorinated bleach, and commercial algae removers to get rid of green algae on concrete. Pressure wash and scrape the wall with a soft brush
|
419 |
+
|
420 |
+
id: 189
|
421 |
+
Defects: Bubble
|
422 |
+
Category: NonWaterproofing
|
423 |
+
title: Surface Preparation for Bubble - NonWaterproofing
|
424 |
+
description: If moisture is the issue, fix any leaks or dampness before proceeding. Moisture must be fully resolved to prevent new bubbling. Remove the buubled paint by using the scraper to peel off the loose and raised areas.Sand the surface with medium-grit sandpaper to remove major surface irregularities bumps and rough patches. Switch to fine-grit sandpaper for final smoothing. Work in small circular motions overlapping each area. Remove all sanding dust by cleaning the surface with pressure washers for further treatment
|
425 |
+
|
426 |
+
id: 190
|
427 |
+
Defects: Bubble
|
428 |
+
Category: Waterproofing
|
429 |
+
title: Surface Preparation for Bubble - Waterproofing
|
430 |
+
description: If moisture is the issue, fix any leaks or dampness before proceeding. Moisture must be fully resolved to prevent new bubbling. Remove the buubled paint by using the scraper to peel off the loose and raised areas.Sand the surface with medium-grit sandpaper to remove major surface irregularities bumps and rough patches. Switch to fine-grit sandpaper for final smoothing. Work in small circular motions overlapping each area. Remove all sanding dust by cleaning the surface with pressure washers for further treatment
|
431 |
+
|
432 |
+
id: 191
|
433 |
+
Defects: Blisters
|
434 |
+
Category: NonWaterproofing
|
435 |
+
title: Surface Preparation for Blisters - NonWaterproofing
|
436 |
+
description: Remove blisters by scraping, sanding or pressure-washing down to underlying coats of paint or primer.Repair loose caulking and improve ventilation of the building to prevent a recurring problem
|
437 |
+
|
438 |
+
id: 192
|
439 |
+
Defects: Blisters
|
440 |
+
Category: Waterproofing
|
441 |
+
title: Surface Preparation for Blisters - Waterproofing
|
442 |
+
description: Remove blisters by scraping, sanding or pressure-washing down to underlying coats of paint or primer.Repair loose caulking and improve ventilation of the building to prevent a recurring problem
|
443 |
+
|
444 |
+
id: 193
|
445 |
+
Defects: Efflorescense
|
446 |
+
Category: NonWaterproofing
|
447 |
+
title: Surface Preparation for Efflorescense - NonWaterproofing
|
448 |
+
description: Stiff brushes are used to sweep away efflorescence from smoother surfaces.Apply a forceful water rinse to efflorescence with a pressure washer to clean it up
|
449 |
+
|
450 |
+
id: 194
|
451 |
+
Defects: Efflorescense
|
452 |
+
Category: Waterproofing
|
453 |
+
title: Surface Preparation for Efflorescense - Waterproofing
|
454 |
+
description: Stiff brushes are used to sweep away efflorescence from smoother surfaces.Apply a forceful water rinse to efflorescence with a pressure washer to clean it up
|
455 |
+
|
456 |
+
id: 195
|
457 |
+
Defects: Fungus
|
458 |
+
Category: NonWaterproofing
|
459 |
+
title: Surface Preparation for Fungus - NonWaterproofing
|
460 |
+
description: Use boiling water, pressure washers, oxygen bleach, chlorinated bleach, and commercial fungus removers to get rid of fungus on concrete. Pressure wash and scrape the wall with a soft brush
|
461 |
+
|
462 |
+
id: 196
|
463 |
+
Defects: Fungus
|
464 |
+
Category: Waterproofing
|
465 |
+
title: Surface Preparation for Fungus - Waterproofing
|
466 |
+
description: Use boiling water, pressure washers, oxygen bleach, chlorinated bleach, and commercial fungus removers to get rid of fungus on concrete. Pressure wash and scrape the wall with a soft brush
|
467 |
+
|
468 |
+
id: 197
|
469 |
+
Defects: Poor Hiding
|
470 |
+
Category: NonWaterproofing
|
471 |
+
title: Surface Preparation for Poor Hiding - NonWaterproofing
|
472 |
+
description: Sand the surface with medium-grit sandpaper to remove major surface irregularities bumps and rough patches. Switch to fine-grit sandpaper for final smoothing. Work in small circular motions overlapping each area. Remove all sanding dust by cleaning the surface with pressure washers for further treatment
|
473 |
+
|
474 |
+
id: 198
|
475 |
+
Defects: Poor Hiding
|
476 |
+
Category: Waterproofing
|
477 |
+
title: Surface Preparation for Poor Hiding - Waterproofing
|
478 |
+
description: Sand the surface with medium-grit sandpaper to remove major surface irregularities bumps and rough patches. Switch to fine-grit sandpaper for final smoothing. Work in small circular motions overlapping each area. Remove all sanding dust by cleaning the surface with pressure washers for further treatment
|
479 |
+
|
480 |
+
id: 199
|
481 |
+
Defects: Shade variation
|
482 |
+
Category: NonWaterproofing
|
483 |
+
title: Surface Preparation for Shade variation - NonWaterproofing
|
484 |
+
description: Remove Loose Material: Carefully strip away loose or blistered paint to expose a firm surface.Spot Priming: Apply an appropriate primer to the affected area, ensuring adhesion.
|
485 |
+
|
486 |
+
id: 200
|
487 |
+
Defects: Shade variation
|
488 |
+
Category: Waterproofing
|
489 |
+
title: Surface Preparation for Shade variation - Waterproofing
|
490 |
+
description: Remove Loose Material: Carefully strip away loose or blistered paint to expose a firm surface.Spot Priming: Apply an appropriate primer to the affected area, ensuring adhesion.
|
491 |
+
|
492 |
+
id: 211
|
493 |
+
Defects: All Defects
|
494 |
+
Category: NonWaterproofing
|
495 |
+
title: 4 Year Paint Warranty System - NonWaterproofing
|
496 |
+
description: Economy Primer, Ace Suprema
|
497 |
+
|
498 |
+
id: 212
|
499 |
+
Defects: All Defects
|
500 |
+
Category: NonWaterproofing
|
501 |
+
title: 7 year Paint Warranty System - NonWaterproofing
|
502 |
+
description: Economy Primer, Apex Suprema
|
503 |
+
|
504 |
+
id: 213
|
505 |
+
Defects: All Defects
|
506 |
+
Category: NonWaterproofing
|
507 |
+
title: 8 year Paint Warranty System - NonWaterproofing
|
508 |
+
description: Exterior Primer, Ultima Strech Suprema
|
509 |
+
|
510 |
+
id: 214
|
511 |
+
Defects: All Defects
|
512 |
+
Category: NonWaterproofing
|
513 |
+
title: 9 year Paint Warranty System - NonWaterproofing
|
514 |
+
description: Exterior Primer, Ultima Suprema
|
515 |
+
|
516 |
+
id: 215
|
517 |
+
Defects: All Defects
|
518 |
+
Category: NonWaterproofing
|
519 |
+
title: 12 year Paint Warranty System - NonWaterproofing
|
520 |
+
description: Exterior Primer, Protek Topcoat
|
521 |
+
|
522 |
+
id: 216
|
523 |
+
Defects: All Defects
|
524 |
+
Category: NonWaterproofing
|
525 |
+
title: 15 year Paint Warranty System - NonWaterproofing
|
526 |
+
description: Exterior Primer, Duralife Topcoat
|
527 |
+
|
528 |
+
id: 217
|
529 |
+
Defects: All Defects
|
530 |
+
Category: Waterproofing
|
531 |
+
title: 4 year Complete Paint Warranty System - Waterproofing
|
532 |
+
description: Damp Sheath suprema, Ace Suprema
|
533 |
+
|
534 |
+
id: 218
|
535 |
+
Defects: All Defects
|
536 |
+
Category: Waterproofing
|
537 |
+
title: 6 year Complete Paint Warranty System - Waterproofing
|
538 |
+
description: Damp Proof Suprema, Apex Suprema
|
539 |
+
|
540 |
+
id: 219
|
541 |
+
Defects: All Defects
|
542 |
+
Category: Waterproofing
|
543 |
+
title: 8 year Complete Paint Warranty System - Waterproofing
|
544 |
+
description: Damp Proof Suprema, Ultima Strech Suprema
|
545 |
+
|
546 |
+
id: 220
|
547 |
+
Defects: All Defects
|
548 |
+
Category: Waterproofing
|
549 |
+
title: 10 year Complete Paint Warranty System - Waterproofing
|
550 |
+
description: Damp Prime Xtreme, Ultima Stretch Suprema
|
551 |
+
|
552 |
+
id: 221
|
553 |
+
Defects: All Defects
|
554 |
+
Category: Waterproofing
|
555 |
+
title: 12 year Complete Paint Warranty System - Waterproofing
|
556 |
+
description: Protek Basecoat, Protek Topcoat
|
557 |
+
|
558 |
+
id: 222
|
559 |
+
Defects: All Defects
|
560 |
+
Category: Waterproofing
|
561 |
+
title: 15 year Complete Paint Warranty System - Waterproofing
|
562 |
+
description: Duralife Basecoat, Duralife Topcoat
|
563 |
+
|
564 |
+
"""
|
565 |
+
|
566 |
+
|
567 |
+
|
568 |
|
|
|
569 |
|
|
|
570 |
|
571 |
+
def remove_html_tags(text):
|
572 |
+
"""Remove HTML tags and convert lists to plain text format"""
|
573 |
+
if not text:
|
574 |
+
return text
|
575 |
|
576 |
+
text = re.sub(r'<li>(.*?)</li>', r'β’ \1', text, flags=re.IGNORECASE | re.DOTALL)
|
577 |
|
578 |
+
text = re.sub(r'<[^>]+>', '', text)
|
579 |
|
580 |
+
text = re.sub(r'\s+', ' ', text).strip()
|
581 |
+
|
582 |
+
text = text.replace('\n', ' ').replace('\r', '')
|
583 |
|
584 |
+
return text
|
585 |
|
|
|
586 |
|
|
|
587 |
|
588 |
+
try:
|
589 |
+
|
590 |
+
|
591 |
|
|
|
592 |
|
593 |
+
response = openai.chat.completions.create(
|
594 |
+
model="gpt-4o",
|
595 |
+
messages=[
|
596 |
+
{
|
597 |
+
"role": "system",
|
598 |
+
"content": ai_content
|
599 |
+
},
|
600 |
+
{
|
601 |
+
"role": "user",
|
602 |
+
"content": f"Generate recommended solutions for defect '{defect_type}' with painting type '{flooring_type}'. Return valid JSON only with both mandatory SPS and optional SPS that match the '{type}' . Remove HTML tags from content."
|
603 |
+
}
|
604 |
+
],
|
605 |
+
max_tokens=2000, # Increased token limit
|
606 |
+
temperature=0.1, # Lower temperature for more consistent responses
|
607 |
+
)
|
608 |
+
|
609 |
+
|
610 |
+
ai_description = response.choices[0].message.content.strip()
|
611 |
+
|
612 |
+
ai_description = ai_description.replace('\n', ' ').replace('\r', '')
|
613 |
+
|
614 |
+
clean_response = ai_description
|
615 |
+
if clean_response.startswith('```json'):
|
616 |
+
clean_response = clean_response[7:]
|
617 |
+
elif clean_response.startswith('```'):
|
618 |
+
clean_response = clean_response[3:]
|
619 |
+
if clean_response.endswith('```'):
|
620 |
+
clean_response = clean_response[:-3]
|
621 |
+
clean_response = clean_response.strip()
|
622 |
+
|
623 |
+
try:
|
624 |
+
import json
|
625 |
+
response_data = json.loads(clean_response)
|
626 |
+
|
627 |
+
mandatory_sps = []
|
628 |
+
if 'mandatory_sps' in response_data and isinstance(response_data['mandatory_sps'], list):
|
629 |
+
for item in response_data['mandatory_sps']:
|
630 |
+
if isinstance(item, dict) and 'content' in item:
|
631 |
+
item['content'] = remove_html_tags(item['content'])
|
632 |
+
mandatory_sps.append(item)
|
633 |
+
|
634 |
+
optional_sps = []
|
635 |
+
if 'optional_sps' in response_data and isinstance(response_data['optional_sps'], list):
|
636 |
+
for item in response_data['optional_sps']:
|
637 |
+
if isinstance(item, dict) and 'content' in item:
|
638 |
+
item['content'] = remove_html_tags(item['content'])
|
639 |
+
optional_sps.append(item)
|
640 |
+
|
641 |
+
if not mandatory_sps and not optional_sps:
|
642 |
+
print("AI returned empty response")
|
643 |
+
# return create_fallback_response(defect_type, flooring_type)
|
644 |
+
|
645 |
+
return mandatory_sps, optional_sps
|
646 |
+
|
647 |
+
except json.JSONDecodeError as json_error:
|
648 |
+
|
649 |
+
|
650 |
+
try:
|
651 |
+
json_start = clean_response.find('{')
|
652 |
+
json_end = clean_response.rfind('}')
|
653 |
+
|
654 |
+
if json_start != -1 and json_end != -1 and json_end > json_start:
|
655 |
+
potential_json = clean_response[json_start:json_end+1]
|
656 |
+
|
657 |
+
potential_json = potential_json.replace("'", '"') # Replace single quotes
|
658 |
+
potential_json = re.sub(r',\s*}', '}', potential_json) # Remove trailing commas
|
659 |
+
potential_json = re.sub(r',\s*]', ']', potential_json) # Remove trailing commas in arrays
|
660 |
+
|
661 |
+
response_data = json.loads(potential_json)
|
662 |
+
|
663 |
+
mandatory_sps = []
|
664 |
+
if 'mandatory_sps' in response_data and isinstance(response_data['mandatory_sps'], list):
|
665 |
+
for item in response_data['mandatory_sps']:
|
666 |
+
if isinstance(item, dict) and 'content' in item:
|
667 |
+
item['content'] = remove_html_tags(item['content'])
|
668 |
+
mandatory_sps.append(item)
|
669 |
+
|
670 |
+
optional_sps = []
|
671 |
+
if 'optional_sps' in response_data and isinstance(response_data['optional_sps'], list):
|
672 |
+
for item in response_data['optional_sps']:
|
673 |
+
if isinstance(item, dict) and 'content' in item:
|
674 |
+
item['content'] = remove_html_tags(item['content'])
|
675 |
+
optional_sps.append(item)
|
676 |
+
|
677 |
+
return mandatory_sps, optional_sps
|
678 |
+
|
679 |
+
except Exception as recovery_error:
|
680 |
+
print(f"JSON recovery failed: {recovery_error}")
|
681 |
+
|
682 |
+
print("Using fallback response due to JSON parsing failure")
|
683 |
+
|
684 |
+
except Exception as e:
|
685 |
+
print(f"Error in OpenAI API call: {str(e)}")
|
686 |
+
|
687 |
+
|
688 |
+
def main():
|
689 |
+
st.title("π Painting Defect Detection System")
|
690 |
+
st.markdown("---")
|
691 |
+
|
692 |
+
# Load the model
|
693 |
+
model = load_trained_model()
|
694 |
+
if model is None:
|
695 |
+
st.error("Failed to load the defect detection model. Please check if the model file exists.")
|
696 |
+
return
|
697 |
+
|
698 |
+
# Sidebar for input options
|
699 |
+
st.sidebar.header("π Input Configuration")
|
700 |
+
|
701 |
+
# Report details
|
702 |
+
st.sidebar.subheader("Report Details")
|
703 |
+
report_submission_id = st.sidebar.text_input("Report Submission Id", value=1)
|
704 |
+
report_section_page_id = st.sidebar.text_input("Page ID", value=7)
|
705 |
+
report_section_id = st.sidebar.text_input("Section ID", value=10)
|
706 |
+
defect_type = st.sidebar.text_input("Defect Type", value="painting")
|
707 |
+
type = st.sidebar.text_input("Type", value="NonWaterproofing")
|
708 |
|
709 |
+
# Input method selection
|
710 |
+
input_method = "Image URLs"
|
711 |
|
712 |
+
# Main content area
|
713 |
+
col1, col2 = st.columns([2, 1])
|
714 |
|
715 |
+
with col1:
|
716 |
+
st.header("πΈ Image Input")
|
717 |
+
st.subheader("Enter Image URLs")
|
718 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
719 |
|
720 |
+
image_data_list = []
|
721 |
+
classifications = []
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
722 |
|
723 |
+
|
724 |
+
|
725 |
+
|
726 |
+
num_urls = st.number_input("Number of images", min_value=1, max_value=10, value=1)
|
727 |
+
|
728 |
+
urls = []
|
729 |
+
for i in range(num_urls):
|
730 |
+
url = st.text_input(f"Image URL {i+1}", key=f"url_{i}")
|
731 |
+
if url:
|
732 |
+
urls.append(url)
|
733 |
+
|
734 |
+
if st.button("Process URLs", type="primary"):
|
735 |
+
for i, url in enumerate(urls):
|
736 |
+
if url.strip():
|
737 |
+
st.subheader(f"Image {i+1}")
|
738 |
+
|
739 |
+
with st.spinner(f"Processing image {i+1}..."):
|
740 |
+
processed_img, image_bytes = process_image(url)
|
741 |
+
|
742 |
+
if processed_img is not None and image_bytes is not None:
|
743 |
+
# Display the image
|
744 |
+
image = Image.open(io.BytesIO(image_bytes))
|
745 |
+
st.image(image, caption=f"Image {i+1}", width=300)
|
746 |
+
|
747 |
+
classification, dpoc = predict_defect(processed_img, model)
|
748 |
+
classifications.append(classification['type'] if 'type' in classification else 'Unknown')
|
749 |
+
|
750 |
+
# Generate OpenAI description
|
751 |
+
openai_desc = generate_openai_description(classification, image_bytes)
|
752 |
+
|
753 |
+
image_data_list.append({
|
754 |
+
"url": url,
|
755 |
+
"defect_classification": classification,
|
756 |
+
"individual_dopc": dpoc,
|
757 |
+
"tags": [classification['type']] if 'type' in classification else ["Unknown"],
|
758 |
+
"openai_desc": openai_desc,
|
759 |
+
})
|
760 |
+
|
761 |
+
# Display results
|
762 |
+
if 'type' in classification:
|
763 |
+
st.success(f"**Detected Defect:** {classification['type']}")
|
764 |
+
st.info(f"**Confidence:** {classification['severity']:.2%}")
|
765 |
+
else:
|
766 |
+
st.error(f"**Error:** {classification.get('error', 'Unknown error')}")
|
767 |
+
|
768 |
+
st.markdown("---")
|
769 |
+
|
770 |
+
with col2:
|
771 |
+
st.header("π Analysis Summary")
|
772 |
+
|
773 |
+
if classifications:
|
774 |
+
# Display metrics
|
775 |
+
st.markdown('<div class="metric-card">', unsafe_allow_html=True)
|
776 |
+
st.metric("Total Images", len(classifications))
|
777 |
+
st.markdown('</div>', unsafe_allow_html=True)
|
778 |
|
779 |
+
st.markdown('<div class="metric-card">', unsafe_allow_html=True)
|
780 |
+
st.metric("Unique Defects", len(set(classifications)))
|
781 |
+
st.markdown('</div>', unsafe_allow_html=True)
|
782 |
+
|
783 |
+
# Defect distribution
|
784 |
+
if len(classifications) > 1:
|
785 |
+
st.subheader("Defect Distribution")
|
786 |
+
defect_counts = pd.Series(classifications).value_counts()
|
787 |
+
st.bar_chart(defect_counts)
|
788 |
+
|
789 |
+
# Display class labels
|
790 |
+
st.subheader("π·οΈ Supported Defect Types")
|
791 |
+
for label in class_labels:
|
792 |
+
st.write(f"β’ {label}")
|
793 |
+
|
794 |
+
# Generate comprehensive report
|
795 |
+
if image_data_list:
|
796 |
+
st.markdown("---")
|
797 |
+
st.header("π Detailed Analysis Report")
|
798 |
+
|
799 |
+
# Generate SPS recommendations
|
800 |
+
if classifications:
|
801 |
+
with st.spinner("Generating recommended solutions..."):
|
802 |
+
user_message = ", ".join(set(classifications))
|
803 |
+
mandatory_sps, optional_sps = get_sps(user_message,type)
|
804 |
+
|
805 |
+
|
806 |
+
|
807 |
+
# Display detailed results for each image
|
808 |
+
for i, image_data in enumerate(image_data_list):
|
809 |
+
with st.expander(f"π· Image {i+1} - Detailed Analysis", expanded=True):
|
810 |
+
col1, col2 = st.columns([1, 2])
|
811 |
+
|
812 |
+
with col1:
|
813 |
+
if 'file_name' in image_data:
|
814 |
+
st.write(f"**File:** {image_data['file_name']}")
|
815 |
+
if 'url' in image_data:
|
816 |
+
st.write(f"**URL:** {image_data['url'][:50]}...")
|
817 |
+
|
818 |
+
classification = image_data['defect_classification']
|
819 |
+
if 'type' in classification:
|
820 |
+
st.write(f"**Defect Type:** {classification['type']}")
|
821 |
+
st.write(f"**Severity:** {classification['severity']:.2%}")
|
822 |
+
|
823 |
+
with col2:
|
824 |
+
st.write("**OpenAI Analysis:**")
|
825 |
+
st.text_area("", image_data['openai_desc'], height=150, key=f"desc_{i}")
|
826 |
+
|
827 |
+
# Display SPS recommendations
|
828 |
+
|
829 |
+
# Export results
|
830 |
+
# Export results
|
831 |
+
ai_response = {}
|
832 |
+
boq_list = []
|
833 |
+
ids = [sps["id"] for sps in optional_sps]
|
834 |
+
sps_boq_map = {
|
835 |
+
211:58,
|
836 |
+
212:59,
|
837 |
+
213:60,
|
838 |
+
214:61,
|
839 |
+
215:62,
|
840 |
+
216:63,
|
841 |
+
217:64,
|
842 |
+
218:65,
|
843 |
+
219:66,
|
844 |
+
220:67,
|
845 |
+
221:57,
|
846 |
+
222:49
|
847 |
+
}
|
848 |
+
boq_list = list([sps_boq_map[sps_id] for sps_id in ids if sps_id in sps_boq_map])
|
849 |
+
|
850 |
+
|
851 |
+
ai_response = {
|
852 |
+
"report_id": report_submission_id,
|
853 |
+
"page_id": report_section_page_id,
|
854 |
+
"section_id": report_section_id,
|
855 |
+
"defect_type": defect_type,
|
856 |
+
"images": image_data_list,
|
857 |
+
"mandatory_sps": mandatory_sps,
|
858 |
+
"optional_sps": optional_sps,
|
859 |
+
"boq_list": boq_list
|
860 |
+
}
|
861 |
+
# if st.button("π€ Export Results as JSON", type="secondary"):
|
862 |
+
# ai_response = {
|
863 |
+
# "report_id": report_submission_id,
|
864 |
+
# "page_id": report_section_page_id,
|
865 |
+
# "section_id": report_section_id,
|
866 |
+
# "defect_type": defect_type,
|
867 |
+
# "images": image_data_list,
|
868 |
+
# "mandatory_sps": mandatory_sps,
|
869 |
+
# "optional_sps": optional_sps
|
870 |
+
# }
|
871 |
+
st.subheader("π¦ JSON Response Preview")
|
872 |
+
with st.expander("View JSON Response", expanded=False):
|
873 |
+
st.json(json.loads(json.dumps(ai_response, indent=2, ensure_ascii=False)))
|
874 |
+
|
875 |
+
|
876 |
+
# π₯ Download button
|
877 |
+
st.download_button(
|
878 |
+
label="Download JSON Report",
|
879 |
+
data=json.dumps(ai_response, indent=2),
|
880 |
+
file_name=f"defect_report_{report_submission_id}_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json",
|
881 |
+
mime="application/json"
|
882 |
+
)
|
883 |
+
|
884 |
+
|
885 |
+
|
886 |
+
if __name__ == "__main__":
|
887 |
+
main()
|