handex commited on
Commit
52ed03c
ยท
verified ยท
1 Parent(s): 18f5c54

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +116 -38
src/streamlit_app.py CHANGED
@@ -1,40 +1,118 @@
1
- import altair as alt
2
- import numpy as np
3
- import pandas as pd
4
  import streamlit as st
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
 
6
- """
7
- # Welcome to Streamlit!
8
-
9
- Edit `/streamlit_app.py` to customize this app to your heart's desire :heart:.
10
- If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [community
11
- forums](https://discuss.streamlit.io).
12
-
13
- In the meantime, below is an example of what you can do with just a few lines of code:
14
- """
15
-
16
- num_points = st.slider("Number of points in spiral", 1, 10000, 1100)
17
- num_turns = st.slider("Number of turns in spiral", 1, 300, 31)
18
-
19
- indices = np.linspace(0, 1, num_points)
20
- theta = 2 * np.pi * num_turns * indices
21
- radius = indices
22
-
23
- x = radius * np.cos(theta)
24
- y = radius * np.sin(theta)
25
-
26
- df = pd.DataFrame({
27
- "x": x,
28
- "y": y,
29
- "idx": indices,
30
- "rand": np.random.randn(num_points),
31
- })
32
-
33
- st.altair_chart(alt.Chart(df, height=700, width=700)
34
- .mark_point(filled=True)
35
- .encode(
36
- x=alt.X("x", axis=None),
37
- y=alt.Y("y", axis=None),
38
- color=alt.Color("idx", legend=None, scale=alt.Scale()),
39
- size=alt.Size("rand", legend=None, scale=alt.Scale(range=[1, 150])),
40
- ))
 
 
 
 
1
  import streamlit as st
2
+ import pandas as pd
3
+ import numpy as np
4
+ import joblib
5
+
6
+ # --- PAGE CONFIGURATION ---
7
+ st.set_page_config(
8
+ page_title="Steel Plate Defect Prediction",
9
+ page_icon="๐Ÿ—๏ธ",
10
+ layout="wide")
11
+
12
+ @st.cache_resource
13
+ def load_artifacts():
14
+ artifacts = joblib.load('src/steel_defect_model.pkl')
15
+ return artifacts
16
+
17
+ try:
18
+ artifacts = load_artifacts()
19
+ models = artifacts['models']
20
+ scaler = artifacts['scaler']
21
+ feature_names = artifacts['features']
22
+ targets = artifacts['targets']
23
+ except FileNotFoundError:
24
+ st.error("Model file 'steel_defect_model.pkl' not found.")
25
+ st.stop()
26
+
27
+ st.title("๐Ÿ—๏ธ Steel Plate Defect Prediction AI")
28
+ st.markdown("""
29
+ This AI model predicts the probability of **7 different types of defects** in steel plates based on their geometric and radiometric properties.
30
+ """)
31
+
32
+ st.sidebar.header("Input Parameters")
33
+ st.sidebar.info("Adjust the sliders to simulate different steel plate properties.")
34
+
35
+ def user_input_features():
36
+ data = {}
37
+
38
+ st.sidebar.subheader("1. Geometry")
39
+ data['X_Minimum'] = st.sidebar.number_input('X Minimum', 0, 1700, 0)
40
+ data['X_Maximum'] = st.sidebar.number_input('X Maximum', 0, 1700, 50)
41
+ data['Y_Minimum'] = st.sidebar.number_input('Y Minimum', 0, 13000000, 600000)
42
+ data['Y_Maximum'] = st.sidebar.number_input('Y Maximum', 0, 13000000, 600050)
43
+ data['Pixels_Areas'] = st.sidebar.number_input('Pixels Areas', 0, 20000, 200)
44
+ data['Steel_Plate_Thickness'] = st.sidebar.slider('Steel Plate Thickness', 40, 300, 80)
45
+
46
+ st.sidebar.subheader("2. Luminosity")
47
+ data['Sum_of_Luminosity'] = st.sidebar.number_input('Sum of Luminosity', 0, 12000000, 20000)
48
+ data['Minimum_of_Luminosity'] = st.sidebar.slider('Minimum Luminosity', 0, 200, 80)
49
+ data['Maximum_of_Luminosity'] = st.sidebar.slider('Maximum Luminosity', 0, 260, 130)
50
+
51
+ data['Length_of_Conveyer'] = 1459
52
+ data['TypeOfSteel_A300'] = st.sidebar.selectbox('Type of Steel A300', [0, 1], index=0)
53
+ data['Edges_Index'] = 0.35
54
+ data['Empty_Index'] = 0.4
55
+ data['Square_Index'] = 0.57
56
+ data['Outside_X_Index'] = 0.03
57
+ data['Edges_X_Index'] = 0.61
58
+ data['Edges_Y_Index'] = 0.83
59
+ data['Outside_Global_Index'] = 0.5
60
+ data['LogOfAreas'] = np.log(data['Pixels_Areas']) if data['Pixels_Areas'] > 0 else 0
61
+ data['Log_X_Index'] = 0
62
+ data['Log_Y_Index'] = 0
63
+ data['Orientation_Index'] = 0.1
64
+ data['Luminosity_Index'] = -0.13
65
+ data['SigmoidOfAreas'] = 0.5
66
+
67
+ df = pd.DataFrame(data, index=[0])
68
+ return df
69
+
70
+ input_df = user_input_features()
71
+
72
+ def preprocess_input(df):
73
+ df = df.copy()
74
+
75
+ df['X_Range'] = df['X_Maximum'] - df['X_Minimum']
76
+ df['Y_Range'] = df['Y_Maximum'] - df['Y_Minimum']
77
+
78
+ x_range = df['X_Range'].replace(0, 1)
79
+ y_range = df['Y_Range'].replace(0, 1)
80
+
81
+ df['Density'] = df['Pixels_Areas'] / (x_range * y_range)
82
+ df['Aspect_Ratio'] = df['X_Range'] / y_range
83
+ df['Luminosity_Range'] = df['Maximum_of_Luminosity'] - df['Minimum_of_Luminosity']
84
+
85
+ skewed_features = ['Pixels_Areas', 'Sum_of_Luminosity',
86
+ 'X_Range', 'Y_Range', 'Aspect_Ratio']
87
+
88
+ for col in feature_names:
89
+ if col not in df.columns:
90
+ df[col] = 0
91
+
92
+ for feature in skewed_features:
93
+ if feature in df.columns:
94
+ df[feature] = np.log1p(df[feature].abs())
95
+
96
+ df = df[feature_names]
97
+ return df
98
 
99
+ if st.button('๐Ÿ”Ž Analyze Steel Plate'):
100
+ processed_df = preprocess_input(input_df)
101
+ scaled_array = scaler.transform(processed_df)
102
+ scaled_df = pd.DataFrame(scaled_array, columns=feature_names)
103
+ results = {}
104
+ for target in targets:
105
+ model = models[target]
106
+ prob = model.predict_proba(scaled_df)[0][1]
107
+ results[target] = prob
108
+ st.subheader("Analysis Results")
109
+ results_df = pd.DataFrame(list(results.items()), columns=['Defect Type', 'Probability'])
110
+ results_df = results_df.sort_values(by='Probability', ascending=False)
111
+ top_defect = results_df.iloc[0]
112
+ if top_defect['Probability'] > 0.5:
113
+ st.error(f"โš ๏ธ High Risk Detected: **{top_defect['Defect Type']}** ({top_defect['Probability']:.1%})")
114
+ else:
115
+ st.success("โœ… No severe defects detected (All probabilities < 50%)")
116
+ st.bar_chart(results_df.set_index('Defect Type'))
117
+ with st.expander("See Detailed Probabilities"):
118
+ st.dataframe(results_df.style.format({'Probability': '{:.2%}'}))