pepperumo commited on
Commit
8826642
·
verified ·
1 Parent(s): feba1c7
Files changed (5) hide show
  1. LICENSE +201 -0
  2. data_processing.py +198 -0
  3. metrics_calculation.py +71 -0
  4. prediction.py +158 -0
  5. streamlit_app.py +783 -0
LICENSE ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
data_processing.py ADDED
@@ -0,0 +1,198 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pandas as pd
2
+ import plotly.graph_objects as go
3
+ import streamlit as st
4
+ from PIL import Image
5
+ from joypy import joyplot
6
+ import seaborn as sns
7
+ import matplotlib.pyplot as plt
8
+
9
+ # Function to load dataset
10
+ def load_dataset():
11
+ file_path = "Data/mvtec_meta_features_dataset.csv"
12
+ try:
13
+ complete_df = pd.read_csv(file_path)
14
+
15
+ # Show available column names for debugging
16
+ print("Available columns:", complete_df.columns)
17
+
18
+ # Verify column presence
19
+ required_columns = ["category", "set_type", "anomaly_status"]
20
+ for col in required_columns:
21
+ if col not in complete_df.columns:
22
+ raise KeyError(f"Missing required column: {col}")
23
+
24
+ # Define the subclasses for each category
25
+ subclasses = {
26
+ 'Texture-Based': ['carpet', 'wood', 'tile', 'leather', 'zipper'],
27
+ 'Industrial Components': ['cable', 'transistor', 'screw', 'grid', 'metal_nut'],
28
+ 'Consumer Products': ['bottle', 'capsule', 'toothbrush'],
29
+ 'Edible': ['hazelnut', 'pill']
30
+ }
31
+
32
+ # Add a new column to the DataFrame to store the subclass
33
+ complete_df['subclass'] = complete_df['category'].apply(
34
+ lambda x: next((key for key, value in subclasses.items() if x in value), 'Unknown')
35
+ )
36
+
37
+ # Reorder columns to place 'subclass' after 'category'
38
+ cols = list(complete_df.columns)
39
+ cols.insert(cols.index('category') + 1, cols.pop(cols.index('subclass')))
40
+ complete_df = complete_df[cols]
41
+
42
+ return complete_df
43
+ except Exception as e:
44
+ st.error(f"Error loading dataset: {e}")
45
+ return None
46
+
47
+ # Function to generate dataset statistics
48
+ def dataset_statistics():
49
+ df = load_dataset()
50
+ if df is not None:
51
+ print("Loaded dataset preview:\n", df.head()) # Debugging step
52
+
53
+ # Aggregate counts for each category and condition
54
+ train_normal = df[(df['set_type'] == 'train') & (df['anomaly_status'] == 'normal')].groupby('category').size()
55
+ test_normal = df[(df['set_type'] == 'test') & (df['anomaly_status'] == 'normal')].groupby('category').size()
56
+ test_anomalous = df[(df['set_type'] == 'test') & (df['anomaly_status'] == 'anomalous')].groupby('category').size()
57
+
58
+ # Combine into a single DataFrame
59
+ final_summary = pd.DataFrame({
60
+ 'Train Normal Images': train_normal,
61
+ 'Test Normal Images': test_normal,
62
+ 'Test Anomalous Images': test_anomalous
63
+ }).fillna(0).reset_index()
64
+
65
+ return final_summary
66
+ return None
67
+
68
+ # Function to generate the bar chart
69
+ def dataset_distribution_chart(df):
70
+ fig = go.Figure()
71
+
72
+ fig.add_trace(go.Bar(
73
+ x=df['category'],
74
+ y=df['Train Normal Images'],
75
+ name='Train Normal Images',
76
+ marker_color='blue'
77
+ ))
78
+ fig.add_trace(go.Bar(
79
+ x=df['category'],
80
+ y=df['Test Normal Images'],
81
+ name='Test Normal Images',
82
+ marker_color='red'
83
+ ))
84
+ fig.add_trace(go.Bar(
85
+ x=df['category'],
86
+ y=df['Test Anomalous Images'],
87
+ name='Test Anomalous Images',
88
+ marker_color='green'
89
+ ))
90
+
91
+ # Update layout
92
+ fig.update_layout(
93
+ title="Distribution of Normal and Anomalous Images per Category",
94
+ xaxis_title="Categories",
95
+ yaxis_title="Number of Images",
96
+ barmode='stack',
97
+ legend_title="Image Types"
98
+ )
99
+
100
+ # Display chart in Streamlit
101
+ st.plotly_chart(fig, use_container_width=True)
102
+
103
+ # Function to display the complete dataframe with expander
104
+ def display_dataframe():
105
+ df = load_dataset()
106
+ if df is not None:
107
+ with st.expander("Show Complete DataFrame"):
108
+ st.dataframe(df)
109
+
110
+
111
+
112
+ def plot_bgr_pixel_densities(df, pixel_columns=['num_pixels_b', 'num_pixels_g', 'num_pixels_r']):
113
+ """
114
+ Generate JoyPy density plots for pixel counts of BGR channels for a given category.
115
+
116
+ Parameters:
117
+ df (pd.DataFrame): Filtered DataFrame for a single category.
118
+ pixel_columns (list): List of column names for BGR pixel counts.
119
+
120
+ Returns:
121
+ None
122
+ """
123
+ if df.empty:
124
+ st.warning("⚠️ No data available for the selected category.")
125
+ return
126
+
127
+ # Plot JoyPy density plot
128
+ fig, axes = joyplot(
129
+ data=df,
130
+ by="category", # Group by category
131
+ column=pixel_columns,
132
+ color=['blue', 'green', 'red'], # Colors for BGR channels
133
+ alpha=0.5,
134
+ fade=True,
135
+ legend=True,
136
+ linewidth=1.0,
137
+ overlap=3,
138
+ figsize=(8, 6) # Adjust the figure size here
139
+ )
140
+
141
+ # Add title and labels
142
+ plt.title(f'Density Plots for {df["category"].unique()[0]}', fontsize=14)
143
+ plt.xlabel('Number of Pixels Density', fontsize=12)
144
+ plt.ylabel('Categories', fontsize=12)
145
+
146
+ # Show the plot in Streamlit
147
+ st.pyplot(fig)
148
+
149
+
150
+ def plot_pair_plots(complete_df):
151
+ """
152
+ Generate and display pair plots for each category in the dataset.
153
+
154
+ Parameters:
155
+ complete_df (pd.DataFrame): The input DataFrame containing image features and categories.
156
+
157
+ Returns:
158
+ None
159
+ """
160
+
161
+ # Define the features to be included in the pairplot
162
+ features = ['num_pixels_b', 'num_pixels_g', 'num_pixels_r', 'perceived_brightness']
163
+
164
+ # Create a separate pairplot for each category
165
+ for category in complete_df['category'].unique():
166
+ # Filter data for current category
167
+ category_df = complete_df[complete_df['category'] == category]
168
+
169
+ # Check if the filtered DataFrame is not empty
170
+ if not category_df.empty:
171
+ # Create PairGrid with hue and palette
172
+ g = sns.PairGrid(category_df, vars=features, hue='anomaly_status', palette={'normal': 'blue', 'anomalous': 'red'})
173
+
174
+ # Map the plots to the grid
175
+ g.map_upper(sns.scatterplot, alpha=0.6)
176
+ g.map_diag(sns.histplot, kde=True)
177
+ g.map_lower(sns.scatterplot, alpha=0.6)
178
+
179
+ # Add legend
180
+ g.add_legend()
181
+
182
+ # Customize the plot
183
+ g.figure.suptitle(f'Feature Relationships for {category.title()}', y=1.02, fontsize=14)
184
+
185
+ # Improve label readability
186
+ for i in range(len(g.axes)):
187
+ for j in range(len(g.axes)):
188
+ if g.axes[i][j] is not None:
189
+ g.axes[i][j].set_xlabel(g.axes[i][j].get_xlabel().replace('_', ' ').title())
190
+ g.axes[i][j].set_ylabel(g.axes[i][j].get_ylabel().replace('_', ' ').title())
191
+
192
+ # Adjust legend position to the right without overlapping the plots
193
+ g._legend.set_bbox_to_anchor((1.05, 0.5))
194
+ g._legend.set_loc('center left')
195
+
196
+ plt.tight_layout()
197
+ st.pyplot(g.figure)
198
+
metrics_calculation.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import pickle
3
+
4
+ import plotly.express as px
5
+ import plotly.graph_objects as go
6
+
7
+ def load_evaluation_metrics(filepath: str):
8
+ with open(filepath, 'rb') as f:
9
+ evaluation_metrics = pickle.load(f)
10
+ return (
11
+ evaluation_metrics['confusion_matrices'],
12
+ evaluation_metrics['roc_curves'],
13
+ evaluation_metrics['auc_scores'],
14
+ evaluation_metrics['f1_scores']
15
+ )
16
+
17
+ def plot_roc_curve(selected_category, roc_curves, auc_scores):
18
+ fig = go.Figure()
19
+ roc_data = roc_curves[selected_category]
20
+ fig.add_trace(go.Scatter(
21
+ x=roc_data['fpr'],
22
+ y=roc_data['tpr'],
23
+ name=selected_category
24
+ ))
25
+ fig.add_trace(go.Scatter(
26
+ x=[0, 1],
27
+ y=[0, 1],
28
+ mode='lines',
29
+ line=dict(dash='dash'),
30
+ name='Random'
31
+ ))
32
+ fig.update_layout(
33
+ title=f"AUC-ROC Curve - {selected_category}, AUC={auc_scores[selected_category]:.3f}",
34
+ xaxis_title="False Positive Rate",
35
+ yaxis_title="True Positive Rate",
36
+ width=500,
37
+ height=450,
38
+ showlegend=False
39
+ )
40
+ return fig
41
+
42
+ def plot_confusion_matrix(selected_category, confusion_matrices, f1_scores):
43
+ labels = ['OK', 'NOK']
44
+ conf_matrix = confusion_matrices[selected_category]
45
+ f1_score = f1_scores[selected_category]
46
+ fig = px.imshow(
47
+ conf_matrix,
48
+ labels=dict(x="True Label", y="Predicted Label"),
49
+ x=labels,
50
+ y=labels,
51
+ color_continuous_scale='Reds',
52
+ width=500,
53
+ height=500,
54
+ )
55
+ for i in range(len(labels)):
56
+ for j in range(len(labels)):
57
+ fig.add_annotation(
58
+ x=j,
59
+ y=i,
60
+ text=str(conf_matrix[i, j]),
61
+ showarrow=False,
62
+ font=dict(size=14)
63
+ )
64
+ fig.update_layout(
65
+ title=f"Confusion Matrix - {selected_category}, F1: {f1_score:.3f}",
66
+ xaxis_title="True Label",
67
+ yaxis_title="Predicted Label",
68
+ coloraxis_showscale=False # This line removes the vertical color scale
69
+ )
70
+ return fig
71
+
prediction.py ADDED
@@ -0,0 +1,158 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import torch
3
+ import dill
4
+ import pickle
5
+ import numpy as np
6
+ from PIL import Image
7
+ import cv2
8
+ from torchvision import transforms
9
+
10
+ # Define the image transformation
11
+ transform = transforms.Compose([
12
+ transforms.Resize(224),
13
+ transforms.ToTensor(),
14
+ ])
15
+
16
+ def decision_function(segm_map):
17
+ """
18
+ Calculate anomaly score from segmentation map using mean of top 10 values.
19
+ """
20
+ mean_top_10_values = []
21
+ for map in segm_map:
22
+ flattened_tensor = map.reshape(-1)
23
+ sorted_tensor, _ = torch.sort(flattened_tensor, descending=True)
24
+ mean_top_10_value = sorted_tensor[:10].mean()
25
+ mean_top_10_values.append(mean_top_10_value)
26
+
27
+ return torch.stack(mean_top_10_values)
28
+
29
+ def run_inference_autoencoder(image_path, model, backbone, threshold):
30
+ """
31
+ Run inference on a single image using Autoencoder.
32
+ """
33
+ # Load and preprocess the image
34
+ image = Image.open(image_path).convert('RGB')
35
+ test_image = transform(image).cuda().unsqueeze(0)
36
+
37
+ # Perform inference
38
+ with torch.no_grad():
39
+ features = backbone(test_image)
40
+ recon = model(features)
41
+
42
+ # Compute segmentation map and anomaly score
43
+ segm_map = ((features - recon) ** 2).mean(axis=(1))
44
+ y_score = decision_function(segm_map=segm_map)
45
+ is_anomaly = (y_score >= threshold).cpu().numpy().item()
46
+
47
+ # Create heatmap
48
+ heat_map = cv2.resize(segm_map.squeeze().cpu().numpy(), (224, 224))
49
+
50
+ return {
51
+ 'original_image': test_image.squeeze().permute(1, 2, 0).cpu().numpy(),
52
+ 'heat_map': heat_map,
53
+ 'anomaly_score': y_score.item(),
54
+ 'threshold': threshold,
55
+ 'is_anomaly': is_anomaly,
56
+ 'classification': 'NOK' if is_anomaly else 'OK'
57
+ }
58
+
59
+ def run_inference_knn(image_path, model, memory_bank, threshold):
60
+ """
61
+ Run inference on a single image using KNN.
62
+ """
63
+ # Load and preprocess the image
64
+ image = Image.open(image_path).convert('RGB')
65
+ test_image = transform(image).cuda().unsqueeze(0)
66
+
67
+ # Move memory bank to GPU **only once**
68
+ memory_bank = memory_bank.cuda()
69
+
70
+ # Extract features using the backbone
71
+ with torch.no_grad():
72
+ features = model(test_image)
73
+
74
+ # Compute distances (optimized)
75
+ distances = torch.cdist(features, memory_bank, p=2.0) # Batched distance calculation
76
+ dist_score, _ = torch.min(distances, dim=1) # Get the nearest neighbor
77
+ y_score = torch.max(dist_score) # Get the anomaly score
78
+
79
+ is_anomaly = (y_score >= threshold).cpu().item()
80
+
81
+ # Compute segmentation map
82
+ segm_map = dist_score.view(1, 1, 28, 28)
83
+ segm_map = torch.nn.functional.interpolate(segm_map, size=(224, 224), mode='bilinear').cpu().squeeze().numpy()
84
+
85
+ # Convert segmentation map to heatmap
86
+ heat_map = cv2.resize(segm_map, (224, 224))
87
+
88
+ return {
89
+ 'original_image': test_image.squeeze().permute(1, 2, 0).cpu().numpy(),
90
+ 'heat_map': heat_map,
91
+ 'anomaly_score': y_score.item(),
92
+ 'threshold': threshold,
93
+ 'is_anomaly': is_anomaly,
94
+ 'classification': 'NOK' if is_anomaly else 'OK',
95
+ }
96
+
97
+
98
+ def load_model_autoencoder(checkpoint_dir='models'):
99
+ """
100
+ Load the saved models and evaluation metrics for Autoencoder.
101
+ """
102
+ models_path = os.path.join(checkpoint_dir, 'models_autoencoder.dill')
103
+ backbone_path = os.path.join(checkpoint_dir, 'backbone_autoencoder.dill')
104
+ metrics_path = os.path.join(checkpoint_dir, 'evaluation_metrics_autoencoder.pkl')
105
+
106
+ # Ensure files exist before loading
107
+ if not os.path.exists(models_path):
108
+ raise FileNotFoundError(f"Autoencoder model file not found: {models_path}")
109
+ if not os.path.exists(backbone_path):
110
+ raise FileNotFoundError(f"Autoencoder backbone file not found: {backbone_path}")
111
+ if not os.path.exists(metrics_path):
112
+ raise FileNotFoundError(f"Autoencoder metrics file not found: {metrics_path}")
113
+
114
+ try:
115
+ with open(models_path, 'rb') as f:
116
+ models = dill.load(f)
117
+
118
+ with open(backbone_path, 'rb') as f:
119
+ backbone = dill.load(f)
120
+
121
+ with open(metrics_path, 'rb') as f:
122
+ evaluation_metrics = pickle.load(f)
123
+
124
+ return models, backbone, evaluation_metrics
125
+
126
+ except Exception as e:
127
+ raise RuntimeError(f"Error loading Autoencoder models: {e}")
128
+
129
+ def load_model_knn(checkpoint_dir='models'):
130
+ """
131
+ Load the saved models and evaluation metrics for KNN.
132
+ """
133
+ memory_bank_path = os.path.join(checkpoint_dir, 'memory_bank_selected.pkl')
134
+ backbone_path = os.path.join(checkpoint_dir, 'backbone_knn.dill') # Fixed incorrect backbone file
135
+ metrics_path = os.path.join(checkpoint_dir, 'evaluation_metrics_knn.pkl')
136
+
137
+ # Ensure files exist before loading
138
+ if not os.path.exists(memory_bank_path):
139
+ raise FileNotFoundError(f"KNN memory bank file not found: {memory_bank_path}")
140
+ if not os.path.exists(backbone_path):
141
+ raise FileNotFoundError(f"KNN backbone file not found: {backbone_path}")
142
+ if not os.path.exists(metrics_path):
143
+ raise FileNotFoundError(f"KNN metrics file not found: {metrics_path}")
144
+
145
+ try:
146
+ with open(memory_bank_path, 'rb') as f:
147
+ memory_bank = pickle.load(f)
148
+
149
+ with open(backbone_path, 'rb') as f:
150
+ backbone = dill.load(f)
151
+
152
+ with open(metrics_path, 'rb') as f:
153
+ evaluation_metrics = pickle.load(f)
154
+
155
+ return backbone, memory_bank, evaluation_metrics
156
+
157
+ except Exception as e:
158
+ raise RuntimeError(f"Error loading KNN models: {e}")
streamlit_app.py ADDED
@@ -0,0 +1,783 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import pandas as pd
3
+ import torch
4
+
5
+ import plotly.express as px
6
+ import plotly.graph_objects as go
7
+ import numpy as np
8
+ from PIL import Image
9
+ import os
10
+ import pickle
11
+ import joblib
12
+ import cv2
13
+ from data_processing import (
14
+ dataset_statistics, dataset_distribution_chart, load_dataset,
15
+ plot_bgr_pixel_densities, plot_pair_plots
16
+ )
17
+ from metrics_calculation import (
18
+ load_evaluation_metrics,
19
+ plot_roc_curve,
20
+ plot_confusion_matrix
21
+ )
22
+
23
+ from prediction import (
24
+ run_inference_autoencoder, load_model_autoencoder, run_inference_knn, load_model_knn
25
+ )
26
+
27
+
28
+ # Overview Page
29
+ def overview_page():
30
+ col1, col2, col3 = st.columns([1, 6, 1])
31
+
32
+ st.title("🚀 Beyond Normal: Unveiling Image Anomalies with AI")
33
+ st.markdown("---")
34
+
35
+ try:
36
+ st.image("images/overview_image.png", use_container_width=True,
37
+ caption="Normal vs. Anomalous Samples with Segmentation Masks")
38
+ except FileNotFoundError:
39
+ st.error("⚠️ Image file not found. Please check if 'images/overview_image.png' exists.")
40
+
41
+ # Create three columns for key metrics
42
+ col1, col2, col3 = st.columns(3)
43
+ with col1:
44
+ st.markdown("""
45
+ <div>
46
+ <h2>5,450</h2>
47
+ <p>High-Resolution Images</p>
48
+ </div>
49
+ """, unsafe_allow_html=True)
50
+ with col2:
51
+ st.markdown("""
52
+ <div>
53
+ <h2>15</h2>
54
+ <p>Object Categories</p>
55
+ </div>
56
+ """, unsafe_allow_html=True)
57
+ with col3:
58
+ st.markdown("""
59
+ <div>
60
+ <h2>70+</h2>
61
+ <p>Defect Types</p>
62
+ </div>
63
+ """, unsafe_allow_html=True)
64
+
65
+ st.markdown("---")
66
+
67
+
68
+ st.header("🔍 What is Anomaly Detection?")
69
+ st.write("""
70
+ Imagine a world where machines can **spot defects** in products just like human inspectors—but **faster and with higher accuracy**!
71
+ This is exactly what **MVTec AD**, a powerful dataset, helps us achieve. It is designed for **automated quality control** in manufacturing by detecting **flaws** such as scratches, dents, and missing parts in different objects and textures.
72
+
73
+ - 🖼️ **5,450 high-resolution images** across **15 object and texture categories**
74
+ - ✅ **Training set**: Only contains **defect-free** images
75
+ - 🐞 **Test set**: Includes images with **over 70 different types of defects**
76
+ - 🎯 **Goal**: Automatically **detect and highlight anomalies** with **pixel-precise segmentation**
77
+ """)
78
+
79
+ st.subheader("🧐 **How Does Anomaly Detection Work?**")
80
+ st.write("""
81
+ The AI model learns what a **perfect product** looks like by studying thousands of **defect-free images**.
82
+ When it sees a **new image**, it checks:
83
+
84
+ 1️⃣ **Does this image match what I’ve seen before?**
85
+ 2️⃣ **If not, where is the defect?**
86
+
87
+ The result? A **heatmap** showing the suspicious areas, along with a **segmentation mask** to pinpoint the defect.
88
+ """)
89
+
90
+ st.subheader("✨ **Bringing Anomalies to Light**: Real-World Examples")
91
+ st.write("""
92
+ Below are **three real examples** of AI-powered anomaly detection. Each image set follows this pattern:
93
+
94
+ 🔹 **First Column**: Original object with an anomaly
95
+ 🔹 **Second Column**: AI-generated **heatmap** highlighting the defect
96
+ 🔹 **Third Column**: Segmentation mask identifying **defect locations**
97
+ 🔹 **Fourth Column**: **Ground truth** (expert-labeled defect areas for verification)
98
+ """)
99
+
100
+ # Display anomaly detection images directly without additional data processing
101
+ st.image("images/anomaly_visual_example_1.png", use_container_width=True, caption="Defective Wood - Liquid Stain")
102
+ st.image("images/anomaly_visual_example_2.png", use_container_width=True, caption="Hazelnut - Hole Defect")
103
+ st.image("images/anomaly_visual_example_3.png", use_container_width=True, caption="Leather - Cut Defect")
104
+
105
+ st.write("""
106
+ 🔵 **The Heatmap (Second Column)**:
107
+ - AI scans the object and **highlights unusual areas** in **red/yellow**, indicating anomaly.
108
+
109
+ ⚫ **Segmentation Map (Third Column)**:
110
+ - Shows the **exact shape** of the detected anomaly, crucial for precise localization.
111
+
112
+ ✅ **Ground Truth (Fourth Column)**:
113
+ - The manually labeled anomaly **used for AI validation**.
114
+
115
+ This technology helps manufacturers **automate anomaly detection, reduce waste, and ensure top-tier product quality** at an industrial scale. 🚀
116
+ """)
117
+
118
+ st.success("🌟 With AI-powered anomaly detection, we bring **precision and automation** to manufacturing quality control! 🔍✨")
119
+
120
+ st.markdown("---")
121
+ col1, col2 = st.columns(2)
122
+
123
+ with col1:
124
+ st.subheader("🎯 Process Pipeline")
125
+ st.markdown("""
126
+ 1. **Data Collection & Preprocessing**
127
+ 2. **Feature Extraction**
128
+ 3. **Model Training**
129
+ 4. **Anomaly Detection**
130
+ 5. **Results Visualization**
131
+ """)
132
+
133
+ with col2:
134
+ st.subheader("🛠️ Key Technologies")
135
+ st.markdown("""
136
+ - **Deep Learning**: PyTorch
137
+ - **Computer Vision**: OpenCV, PIL
138
+ - **Data Analysis**: NumPy, Pandas
139
+ - **Visualization**: Plotly, Matplotlib
140
+ """)
141
+
142
+
143
+ # Dataset Page
144
+ def dataset_page():
145
+ st.title("📊 Dataset Analysis & Exploratory Data")
146
+
147
+ tab1, tab2 = st.tabs(["📈 Dataset Overview", "🎨 Feature Analysis"])
148
+
149
+ with tab1:
150
+ st.subheader("Dataset Structure")
151
+ complete_df = load_dataset()
152
+ if complete_df is not None:
153
+ st.markdown("""
154
+ <div>
155
+ <ul>
156
+ <li>Total Samples: {}</li>
157
+ <li>Categories: {}</li>
158
+ </ul>
159
+ </div>
160
+ """.format(
161
+ len(complete_df),
162
+ len(complete_df['category'].unique())
163
+ ), unsafe_allow_html=True)
164
+
165
+ with st.expander("🔍 View Full Dataset"):
166
+ st.dataframe(complete_df, use_container_width=True)
167
+ else:
168
+ st.error("❌ Error: Dataset could not be loaded.")
169
+
170
+
171
+ st.subheader("Statistical Analysis")
172
+ df = dataset_statistics()
173
+ if df is not None:
174
+
175
+ dataset_distribution_chart(df)
176
+
177
+ with st.expander("📊 Detailed Statistics"):
178
+ st.dataframe(df, use_container_width=True)
179
+ else:
180
+ st.error("❌ Error: Statistics could not be computed.")
181
+
182
+ with tab2:
183
+ st.subheader("Feature Engineering & Analysis")
184
+
185
+ st.markdown("""
186
+ <div>
187
+ <h3>🔄 Dimensionality Reduction (PCA)</h3>
188
+ <p>Our feature extraction pipeline includes:</p>
189
+ <ul>
190
+ <li>Image preprocessing and normalization</li>
191
+ <li>Feature extraction using ResNet50</li>
192
+ <li>PCA transformation preserving 95% variance</li>
193
+ </ul>
194
+ </div>
195
+ """, unsafe_allow_html=True)
196
+
197
+ complete_df = load_dataset()
198
+ if complete_df is not None:
199
+ selected_category = st.selectbox("Select a Category",
200
+ complete_df['category'].unique(), index=list(complete_df['category'].unique()).index('wood'))
201
+
202
+ col1, col2 = st.columns(2)
203
+ with col1:
204
+ plot_bgr_pixel_densities(
205
+ complete_df[complete_df['category'] == selected_category],
206
+ pixel_columns=['num_pixels_b', 'num_pixels_g', 'num_pixels_r']
207
+ )
208
+ with col2:
209
+ plot_pair_plots(complete_df[complete_df['category'] == selected_category])
210
+ st.write("""
211
+ **Key Takeaways from Feature Relationships:**
212
+
213
+ **Strong Correlations:**
214
+ - The BGR pixel values exhibit **strong linear relationships**, which is expected as they represent color intensity.
215
+ - **Perceived brightness** also shows a linear trend, confirming its dependence on RGB values.
216
+
217
+ **Separation of Normal vs. Anomalous Data:**
218
+ - Some categories, like `Hazelnut` and `Tile`, show **clear separation** between normal (blue) and anomalous (red) points, indicating that anomalies have **distinct feature distributions**.
219
+ - Other categories, such as `Screw` and `Transistor`, show **more overlap**, meaning their anomalies are harder to distinguish based only on pixel values.
220
+
221
+ **Density Distributions:**
222
+ - Categories like `Carpet` and `Capsule` show **multi-modal distributions**, meaning that anomalies have **different types of defects**.
223
+ - Categories like `Leather` and `Metal Nut` show anomalies with **different brightness levels**, suggesting that brightness-based anomaly detection could be effective.
224
+
225
+ Overall, this analysis helps us understand which **features are useful for distinguishing anomalies** and which categories might need **additional feature engineering**.
226
+ """)
227
+
228
+ st.success("✅ Using PCA, BGR pixel distributions, and feature relationships, we ensure that the dataset is **optimized for training accurate anomaly detection models**.")
229
+
230
+
231
+
232
+ def synthetic_data_page():
233
+ st.title("🔬 Data Enhancement Techniques")
234
+
235
+ tab1, tab2 = st.tabs(["🧪 Synthetic Data", "🔄 Data Augmentation"])
236
+
237
+ with tab1:
238
+ st.header("Synthetic Data Generation")
239
+
240
+ st.info("""
241
+ 🔍 **Synthetic Data** refers to artificially generated images that simulate anomalies
242
+ by modifying normal samples. Unlike data augmentation, synthetic data aims to create
243
+ new, realistic defect patterns that weren't present in the original dataset.
244
+ """)
245
+ st.write("""
246
+ #### 🔍 Why Do We Need Synthetic Data?
247
+ The **MVTec Anomaly Detection Dataset** contains **15 object categories**, but for each category:
248
+
249
+ - The dataset is relatively **small**.
250
+ - There are **far fewer anomaly images** than normal images.
251
+ - Splitting test data for validation would leave even **less data** to train the model.
252
+
253
+ To solve this problem, **we create additional "fake" anomaly images** to train the model better.
254
+ Instead of taking images of real defective objects (which are limited), we **manipulate normal images** by adding synthetic defects, such as **twisting, distorting, or overlaying textures**.
255
+
256
+ """)
257
+ st.image(
258
+ "images/synthetic_example.png",
259
+ caption="Synthetic Anomaly"
260
+ )
261
+ col1, col2 = st.columns(2)
262
+ with col1:
263
+ st.markdown("""
264
+ <div>
265
+ <h4>Synthetic Anomaly Generation</h4>
266
+ <ol>
267
+ <li><strong>Base Selection:</strong> Choose a normal image as base</li>
268
+ <li><strong>Defect Injection:</strong> Apply artificial defects:
269
+ <ul>
270
+ <li>Scratch patterns</li>
271
+ <li>Surface contamination</li>
272
+ <li>Structural deformations</li>
273
+ <li>Missing components</li>
274
+ </ul>
275
+ </li>
276
+ <li><strong>Validation:</strong> Ensure defect realism</li>
277
+ <li><strong>Integration:</strong> Add to validation dataset</li>
278
+ </ol>
279
+ </div>
280
+ """, unsafe_allow_html=True)
281
+
282
+ st.success("""
283
+ ✨ **Benefits of Synthetic Data**
284
+ - Creates diverse anomaly patterns
285
+ - Controls defect characteristics
286
+ - Balances class distribution
287
+ - Reduces data collection costs
288
+ """)
289
+
290
+ with col2:
291
+
292
+ st.warning("""
293
+ ⚠️ **Important Considerations**
294
+ - Synthetic defects must be realistic
295
+ - Validation against real defects is crucial
296
+ - Balance between synthetic and real data needed
297
+ """)
298
+
299
+ with tab2:
300
+ st.header("Data Augmentation Techniques")
301
+
302
+ st.info("""
303
+ 🔄 **Data Augmentation** applies label-preserving transformations to existing images
304
+ to increase dataset variety and prevent overfitting. Unlike synthetic data, augmentation
305
+ doesn't create new defect types but enhances model robustness through variations.
306
+ """)
307
+
308
+ st.write("""
309
+ **Augmented data** is different from synthetic data. Instead of creating **new artificial images**, we **modify existing images** by applying **small transformations** like flipping, rotating, and resizing.
310
+
311
+ #### 🔍 Why Do We Need Data Augmentation?
312
+ Even with synthetic data, **our dataset is still small** compared to what is needed for deep learning.
313
+ If we train a model on a **limited number of images**, the model might **memorize** the training data instead of **learning general patterns**. This is called **overfitting**.
314
+
315
+ **To prevent overfitting, we increase the dataset size by applying transformations to images.**
316
+ """)
317
+
318
+ col1, col2, col3 = st.columns(3)
319
+ with col1:
320
+ st.markdown("""
321
+ <div>
322
+ <h5>🔲 Basic Transformations</h5>
323
+ <ul>
324
+ <li><strong>Resizing</strong>: Fixed 224×224 pixels</li>
325
+ <li><strong>Horizontal Flip</strong>: 50% probability</li>
326
+ <li><strong>Impact</strong>: Standardized input size</li>
327
+ </ul>
328
+ </div>
329
+ """, unsafe_allow_html=True)
330
+ with col2:
331
+ st.markdown("""
332
+ <div>
333
+ <h5>🎨 Geometric Operations</h5>
334
+ <ul>
335
+ <li><strong>Rotation</strong>: 75% prob. (-90°, 90°, 180°)</li>
336
+ <li><strong>Scaling & Translation</strong>: 75% probability</li>
337
+ <li><strong>Impact</strong>: Position invariance</li>
338
+ </ul>
339
+ </div>
340
+ """, unsafe_allow_html=True)
341
+ with col3:
342
+ st.markdown("""
343
+ <div>
344
+ <h5>🔄 Advanced Processing</h5>
345
+ <ul>
346
+ <li><strong>Gaussian Blur</strong>: Kernel size 3</li>
347
+ <li><strong>Sigma Range</strong>: 0.01-0.05</li>
348
+ <li><strong>Final Step</strong>: Tensor conversion</li>
349
+ </ul>
350
+ </div>
351
+ """, unsafe_allow_html=True)
352
+
353
+ st.markdown("### 📈 Augmentation examples")
354
+ col1, col2 = st.columns(2)
355
+ with col1:
356
+ st.image(
357
+ "images/augmented_example.png",
358
+ caption="Augmented Images Examples",
359
+ use_container_width=True
360
+ )
361
+ with col2:
362
+ st.image(
363
+ "images/original_example.png",
364
+ caption="Original Images Examples",
365
+ use_container_width=True
366
+ )
367
+
368
+ st.success("""
369
+ ✨ **Benefits of Data Augmentation**
370
+ - Prevents overfitting
371
+ - Improves model generalization
372
+ - Increases effective dataset size
373
+ - Maintains label validity
374
+ """)
375
+
376
+ def resnet50_page():
377
+ st.title("🔍 ResNet50 Feature Extraction")
378
+ col1, col2= st.columns([3, 2])
379
+ with col1:
380
+ st.markdown("""
381
+ ### Why Use a Pretrained Model (Transfer Learning)? 🧠
382
+ Instead of starting from scratch, we take advantage of **ResNet50**,
383
+ a popular neural network that has already been trained on a large image dataset (ImageNet).
384
+ Because ResNet50 has “seen” many kinds of shapes, objects, and patterns,
385
+ it has learned to recognize important features in images.
386
+
387
+ By using these **pretrained features**, we:
388
+ 1. ⏱️ Save time and resources (no need to train a big model from zero).
389
+ 2. 🖼️ Gain access to a representation that already captures key visual patterns.
390
+ 3. 🎯 Focus on fine-tuning the model for our specific task (anomaly detection).
391
+ """)
392
+
393
+ with col2:
394
+ st.image("images/resnet50.png", caption="Resnet50 Latent features extraction", use_container_width=True)
395
+
396
+ st.markdown("""
397
+
398
+ ### How We Extract Features from ResNet50
399
+ We focus on two parts (or “blocks”) of ResNet50 and gather their outputs:
400
+ - **Block 1**: Produces 512 features.
401
+ - **Block 2**: Produces 1024 features.
402
+
403
+ We then **combine** (concatenate) these for a total of **(512 + 1024) = 1536** features.
404
+ These numbers come from the internal layers of ResNet50.
405
+
406
+ Essentially, these **1536 features** act like a summary of the image’s most important elements. 📝
407
+
408
+ """)
409
+ def models_page():
410
+ st.title("🤖 Anomaly Detection Models")
411
+
412
+ tab1, tab2 = st.tabs(["KNN", "Autoencoder"])
413
+
414
+ with tab1:
415
+ st.header("KNN for Anomaly Detection")
416
+ col1, col2 = st.columns([2.5,2])
417
+ with col1:
418
+ st.markdown("""
419
+ KNN (K-Nearest Neighbors) is a simple method that checks how "close" a new sample is
420
+ to existing samples. Here's the idea:
421
+ 1. We first collect "normal" images and extract their 1536 features.
422
+ We call this collection our **memory bank** of normal features. 🏦
423
+ 2. When a **test** image comes in:
424
+ - ⚙️ We **extract** its 1536 features with the exact same process (ResNet blocks).
425
+ - 📏 We measure its **distance** to each normal feature vector in the memory bank.
426
+ - 🔎 We pick the **1 closest** neighbor (because k=1) and calculate the **average distance**.
427
+ - If this average distance is **small**, it is likely "normal." ✅
428
+ - If this average distance is **large**, it might be "anomalous" or unusual. 🐞
429
+ """)
430
+ st.image("images/k-nearest-neighbors-algorithm.png", caption="Visualizing the K-Nearest Neighbors approach")
431
+ with col2:
432
+ st.image("images/KNN_Pipeline.png", caption="KNN Anomaly Detection Pipeline")
433
+
434
+
435
+
436
+ with tab2:
437
+ st.header("Autoencoder for Anomaly Detection")
438
+ col1, col2 = st.columns([2.5,2])
439
+ with col1:
440
+ st.write("""
441
+ Deep learning models have demonstrated remarkable performance in anomaly detection tasks,
442
+ particularly in complex scenarios where traditional methods often struggle.
443
+ These models can automatically learn intricate patterns and features from data,
444
+ making them highly effective at identifying subtle anomalies.
445
+ """)
446
+
447
+ st.write("""
448
+ ### What is an autoencoder?
449
+
450
+ An autoencoder is a specialized type of neural network designed to compress and reconstruct input images.
451
+ When applied to anomaly detection, the model is trained exclusively on normal images to learn the typical characteristics of the dataset.
452
+ """)
453
+
454
+ st.write("""
455
+ ### Anomaly Detection Workflow
456
+
457
+ #### 1. Feature Extraction
458
+ - Collect a set of normal images.
459
+ - Extract 1,536 features from each image using a **ResNet50** model.
460
+
461
+ #### 2. Training Process
462
+ - Train the autoencoder exclusively on normal data.
463
+ - The autoencoder learns to efficiently encode and decode normal patterns.
464
+ - The model optimizes its reconstruction error using normal samples.
465
+
466
+ #### 3. Anomaly Detection
467
+ - A new test image is passed through the trained autoencoder.
468
+ - The reconstructed output is compared to the original input.
469
+ - A high reconstruction error suggests an anomaly.
470
+ - A low reconstruction error indicates that the sample is likely normal.
471
+ """)
472
+
473
+ st.success("""
474
+ ## Key Advantages
475
+ - **Fully Unsupervised Learning** – No need for labeled anomaly data.
476
+ - **Ability to Capture Complex Normal Patterns** – The model generalizes well to unseen normal variations.
477
+ - **Effective for High-Dimensional Image Data** – Works well with large and detailed datasets.
478
+ """)
479
+ st.warning("""
480
+ ## Limitations
481
+ - **Computationally Intensive Training** – Training deep autoencoders requires significant computational resources.
482
+ - **Performance Sensitivity to Model Architecture** – The effectiveness depends heavily on model design.
483
+ - **Difficulty Detecting Subtle Anomalies** – If anomalies resemble normal patterns closely, they may be overlooked.
484
+ """)
485
+
486
+ with col2:
487
+ st.image("images/Autoencoder_Pipeline.png", caption="Autoencoder Anomaly Detection Pipeline", use_container_width=True)
488
+ st.image("images/encoder_decoder.png", caption="Autoencoder structure", use_container_width=True)
489
+
490
+ def analysis_page():
491
+ st.title("📊 Model Performance Analysis")
492
+
493
+ # Move category selection outside of tabs
494
+ selected_category = st.selectbox(
495
+ "Select Category",
496
+ ["bottle", "cable", "capsule", "carpet", "grid",
497
+ "hazelnut", "leather", "metal_nut", "pill", "screw",
498
+ "tile", "toothbrush", "transistor", "wood", "zipper"],
499
+ index=1 # Default to 'cable'
500
+ )
501
+
502
+ # Create two columns
503
+ col1, col2 = st.columns(2)
504
+
505
+ with col1:
506
+ st.subheader("KNN Model")
507
+ try:
508
+ confusion_matrices, roc_curves, auc_scores, f1_scores = load_evaluation_metrics('models/evaluation_metrics_knn.pkl')
509
+
510
+ # Display ROC curve with unique key
511
+ roc_fig = plot_roc_curve(selected_category, roc_curves, auc_scores)
512
+ st.plotly_chart(roc_fig, use_container_width=True, key="knn_roc")
513
+
514
+ # Display confusion matrix with unique key
515
+ cm_fig = plot_confusion_matrix(selected_category, confusion_matrices, f1_scores)
516
+ st.plotly_chart(cm_fig, use_container_width=True, key="knn_cm")
517
+
518
+ except FileNotFoundError:
519
+ st.error("KNN evaluation metrics file not found. Please run model evaluation first.")
520
+ except Exception as e:
521
+ st.error(f"Error loading KNN metrics: {str(e)}")
522
+
523
+ with col2:
524
+ st.subheader("Autoencoder Model")
525
+ try:
526
+ confusion_matrices, roc_curves, auc_scores, f1_scores = load_evaluation_metrics('models/evaluation_metrics_autoencoder.pkl')
527
+
528
+ # Display ROC curve with unique key
529
+ roc_fig = plot_roc_curve(selected_category, roc_curves, auc_scores)
530
+ st.plotly_chart(roc_fig, use_container_width=True, key="ae_roc")
531
+
532
+ # Display confusion matrix with unique key
533
+ cm_fig = plot_confusion_matrix(selected_category, confusion_matrices, f1_scores)
534
+ st.plotly_chart(cm_fig, use_container_width=True, key="ae_cm")
535
+
536
+ except FileNotFoundError:
537
+ st.error("Autoencoder evaluation metrics file not found. Please run model evaluation first.")
538
+ except Exception as e:
539
+ st.error(f"Error loading Autoencoder metrics: {e}")
540
+
541
+
542
+
543
+ def prediction_page():
544
+ """
545
+ Streamlit page to view anomaly detection images.
546
+ """
547
+ st.title("🔍 Anomaly Detection - Image Viewer")
548
+
549
+ st.info("Select a category and image to view the anomaly detection result.")
550
+
551
+ # Select a category
552
+ selected_category = st.selectbox(
553
+ "Select a Category",
554
+ ["bottle", "cable", "capsule", "carpet", "grid",
555
+ "hazelnut", "leather", "metal_nut", "pill", "screw",
556
+ "tile", "toothbrush", "transistor", "wood", "zipper"],
557
+ key="shared_category" # Unique key for each selectbox
558
+ )
559
+
560
+ # List available images in the selected category
561
+ category_dir_knn = os.path.join("images/Dataset_knn", selected_category)
562
+ category_dir_autoencoder = os.path.join("images/Dataset_autoencoder", selected_category)
563
+
564
+ available_images_knn = []
565
+ if os.path.exists(category_dir_knn):
566
+ available_images_knn = [f for f in os.listdir(category_dir_knn) if os.path.isfile(os.path.join(category_dir_knn, f))]
567
+
568
+ available_images_autoencoder = []
569
+ if os.path.exists(category_dir_autoencoder):
570
+ available_images_autoencoder = [f for f in os.listdir(category_dir_autoencoder) if os.path.isfile(os.path.join(category_dir_autoencoder, f))]
571
+
572
+ # Find common images
573
+ available_images = list(set(available_images_knn) & set(available_images_autoencoder))
574
+
575
+ selected_image = st.selectbox(
576
+ "Select an Image",
577
+ available_images,
578
+ key="shared_image" # Unique key for each selectbox
579
+ )
580
+
581
+ run_prediction = st.button("Run Prediction")
582
+
583
+ tab1, tab2 = st.tabs(["KNN", "Autoencoder"])
584
+
585
+ with tab1:
586
+ st.subheader("KNN Model")
587
+ if run_prediction:
588
+ display_image("knn", selected_category, selected_image)
589
+
590
+ with tab2:
591
+ st.subheader("Autoencoder Model")
592
+ if run_prediction:
593
+ display_image("autoencoder", selected_category, selected_image)
594
+
595
+ def display_image(model_type, selected_category, selected_image):
596
+ """
597
+ Helper function to display a single image based on the selected model type.
598
+ """
599
+ if selected_image:
600
+ # Construct file paths
601
+ image_path = os.path.join(f"images/Dataset_{model_type}", selected_category, selected_image)
602
+
603
+ # Display image
604
+ if os.path.exists(image_path):
605
+ try:
606
+ image = Image.open(image_path)
607
+ st.image(image, use_container_width=True)
608
+ except Exception as e:
609
+ st.error(f"Error displaying {model_type} image: {e}")
610
+ else:
611
+ st.error(f"{model_type} Image not found: {image_path}")
612
+
613
+ st.markdown("""
614
+ ### Explanation of the displayed image:
615
+
616
+ 1️⃣ **Top Left: Original Image**
617
+ - This is the raw image from the dataset.
618
+ - The object is analyzed to detect potential anomalies.
619
+
620
+ 2️⃣ **Top Right: Heatmap**
621
+ - The heatmap represents the anomaly score distribution.
622
+ - Color Legend:
623
+ - 🔴 Red/Yellow: High anomaly score (defective region).
624
+ - 🔵 Blue: Normal areas with low anomaly probability.
625
+ - The defect region is highlighted based on the anomaly model’s prediction.
626
+
627
+ 3️⃣ **Bottom Left: Segmentation Map**
628
+ - This is a binary mask that highlights the detected defect areas.
629
+ - White pixels represent anomalous regions identified by the model.
630
+ - It is created by thresholding the heatmap to localize defects.
631
+
632
+ 4️⃣ **Bottom Right: Ground Truth**
633
+ - The ground truth mask is a manually labeled reference.
634
+ - It defines the true defective areas for validation.
635
+ - The segmentation map should ideally match this mask for accurate detection.
636
+ """)
637
+
638
+
639
+
640
+ def conclusion_and_improvements_page():
641
+ st.title("🏁 Conclusion and Future Improvements")
642
+
643
+ st.write("""
644
+ ## Conclusion
645
+
646
+ Throughout the project, several Machine Learning and Deep Learning models have been applied to the available image data. We compared different models and approaches in data preparation to optimize anomaly detection performance.
647
+
648
+ The evaluation shows that the Convolutional Autoencoder and the KNN approach significantly outperform other models, and both yield better results using the deep feature extraction approach.
649
+
650
+ ### Key Takeaways
651
+
652
+ - **Deep Feature Extraction**: Significantly outperforms manual extracted features, as seen in the consistently better performance of ResNet50-based methods.
653
+ - **ResNet50 Block Performance**: Two evaluated deep feature extraction approaches, one using ResNet50 blocks 1 and 2, the other using block 3, both seem similarly suitable on average over all categories. However, within single categories, one often showed significantly better performance than the other.
654
+ - **KNN Approach**: Leverages memory-based similarity comparisons, providing a robust alternative to parametric models.
655
+ - **Autoencoder Approach**: Deep learning using an autoencoder provides strong reconstruction-based anomaly detection, ensuring comprehensive feature learning.
656
+ - **Synthetic Validation Data**: Introduced diversity and improved cross-validation but also posed challenges, as some anomalies may not perfectly mimic real-world defects.
657
+
658
+ ## Future Improvements
659
+
660
+ - **Data Augmentation Refinement**: Exploring more advanced augmentation techniques, such as generative models (e.g., GANs), could enhance training diversity.
661
+ - **Model Ensembling**: Combining multiple anomaly detection models could improve robustness and generalization.
662
+ - **Hyperparameter Optimization**: Fine-tuning model hyperparameters further, using techniques like Bayesian optimization, could boost performance.
663
+ - **Alternative Architectures**: Exploring transformer-based architectures or vision encoders like ViTs for anomaly detection could yield even better results.
664
+ - **Better Synthetic Data**: Refining the process of synthetic anomaly generation to better align with real-world defects.
665
+
666
+ Overall, the introduced approaches provide a solid foundation for industrial anomaly detection tasks. Further optimizations and explorations in feature extraction and model selection could push performance even higher in future studies.
667
+ """)
668
+
669
+ # Bibliography Page
670
+ def bibliography_page():
671
+ st.title("📚 Bibliography & References")
672
+
673
+ st.markdown("""
674
+ ### Core Papers & Methods
675
+
676
+ 1. Liu, J., Xie, G., Wang, J., Li, S., Wang, C., Zheng, F., & Jin, Y. (2023).
677
+ _Deep Industrial Image Anomaly Detection: A Survey_. Springer Nature.
678
+ [arXiv:2301.11514](https://arxiv.org/abs/2301.11514)
679
+
680
+ 2. Yang, J., Shi, Y., & Qi, Z. (2020).
681
+ _DFR: Deep Feature Reconstruction for Unsupervised Anomaly Segmentation_.
682
+ [arXiv:2012.07122](https://arxiv.org/abs/2012.07122)
683
+
684
+ 3. Bühler, J., Fehrenbach, J., Steinmann, L., Nauck, C., & Koulakis, M. (2024).
685
+ _Domain-independent detection of known anomalies_. Karlsruhe Institute of Technology (KIT) & preML GmbH.
686
+ [arXiv:2407.02910](https://arxiv.org/abs/2407.02910)
687
+
688
+ 4. Heckler, L., & König, R. (2024).
689
+ _Feature Selection for Unsupervised Anomaly Detection and Localization Using Synthetic Defects_.
690
+ MVTec Software GmbH & Technical University of Munich.
691
+ In Proceedings of the 19th International Joint Conference on Computer Vision, Imaging and Computer Graphics Theory and Applications (VISIGRAPP 2024), 154-165.
692
+ [DOI: 10.5220/0012385500003660](https://doi.org/10.5220/0012385500003660)
693
+
694
+ 5. Rippel, O., Mertens, P., & Merhof, D. (2020).
695
+ _Modeling the Distribution of Normal Data in Pre-Trained Deep Features for Anomaly Detection_.
696
+ RWTH Aachen University.
697
+ [arXiv:2005.14140](https://arxiv.org/abs/2005.14140)
698
+
699
+ 6. Bergmann, P., Fauser, M., Sattlegger, D., & Steger, C. (2019).
700
+ _MVTec AD – A Comprehensive Real-World Dataset for Unsupervised Anomaly Detection_.
701
+ MVTec Software GmbH.
702
+ [MVTec AD Dataset](https://www.mvtec.com/company/research/datasets/mvtec-ad)
703
+
704
+ 7. Roth, K., Pemula, L., Zepeda, J., Schölkopf, B., Brox, T., & Gehler, P. (2022).
705
+ _Towards Total Recall in Industrial Anomaly Detection_.
706
+ University of Tübingen & Amazon AWS.
707
+ [arXiv:2106.08265](https://arxiv.org/abs/2106.08265)
708
+
709
+ 8. Zheng, Y., Wang, X., Qi, Y., Li, W., & Wu, L. (2022).
710
+ _Benchmarking Unsupervised Anomaly Detection and Localization_.
711
+ University of Chinese Academy of Sciences, SenseTime Research, & Tsinghua University.
712
+ [arXiv:2205.14852](https://arxiv.org/abs/2205.14852)
713
+ """)
714
+
715
+ def main():
716
+ with st.sidebar:
717
+ st.image("images/logo.png", width=100) # Add your logo here
718
+ st.title("Navigation")
719
+
720
+
721
+ selection = st.radio(
722
+ "Select a Section",
723
+ ["Overview",
724
+ "Dataset & EDM",
725
+ "Synthetic Data & Augmentation",
726
+ "Transfer Learning - Resnet50",
727
+ "Models",
728
+ "Analysis",
729
+ "Prediction",
730
+ "Conclusion and Improvements",
731
+ "Bibliography"],
732
+ format_func=lambda x: f" {x}"
733
+ )
734
+ st.markdown("---")
735
+ st.markdown("""
736
+ <div style='text-align: center; color: #666;'>
737
+
738
+ <div style='margin: 10px 0;'>
739
+ This app is maintained by:<br>
740
+ <a href="https://www.linkedin.com/in/giuseppe-rumore-b2599961" target="_blank">Giuseppe Rumore</a> |
741
+ <a href="https://www.linkedin.com/in/micaela-w%C3%BCnsche-9baaa710b/" target="_blank">Micaela Wünsche</a> |
742
+ <a href="https://www.linkedin.com/in/majid-jafari-62909071/" target="_blank">Majid Jafari</a>
743
+ </div>
744
+ </a>
745
+ <img src="https://content.linkedin.com/content/dam/me/business/en-us/amp/brand-site/v2/bg/LI-Logo.svg.original.svg"
746
+ width="80"
747
+ alt="LinkedIn"
748
+ style="margin-top: 10px;">
749
+ </a>
750
+ <br>
751
+ <a href="https://github.com/DataScientest-Studio/nov24_bds_mvtec-anomaly-detection" target="_blank">
752
+ <img src="https://github.githubassets.com/images/modules/logos_page/GitHub-Mark.png"
753
+ width="40"
754
+ alt="GitHub"
755
+ style="margin-top: 10px; border-radius: 50%;">
756
+ </a>
757
+ <div style='text-align: center; color: #666;'>
758
+ <small>Version 1.0.0</small><br>
759
+ <small>© 2025 MVTec Anomaly Detection</small><br>
760
+ </div>
761
+ """, unsafe_allow_html=True)
762
+
763
+ if selection == "Overview":
764
+ overview_page()
765
+ elif selection == "Dataset & EDM":
766
+ dataset_page()
767
+ elif selection == "Synthetic Data & Augmentation":
768
+ synthetic_data_page()
769
+ elif selection == "Transfer Learning - Resnet50":
770
+ resnet50_page()
771
+ elif selection == "Models":
772
+ models_page()
773
+ elif selection == "Analysis":
774
+ analysis_page()
775
+ elif selection == "Prediction":
776
+ prediction_page()
777
+ elif selection == "Conclusion and Improvements":
778
+ conclusion_and_improvements_page()
779
+ elif selection == "Bibliography":
780
+ bibliography_page()
781
+
782
+ if __name__ == "__main__":
783
+ main()