VivekM8737 commited on
Commit
7f266e0
·
verified ·
1 Parent(s): d230276

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +128 -127
app.py CHANGED
@@ -1,127 +1,128 @@
1
- import pandas as pd
2
- import numpy as np
3
- from sklearn.preprocessing import MinMaxScaler
4
-
5
- def preprocess_data(input_data, pmap, fmap, features, sc):
6
- """Preprocesses the input data."""
7
- input_df = pd.DataFrame([input_data], columns=features)
8
- input_df['protocol_type'] = input_df['protocol_type'].map(pmap)
9
- input_df['flag'] = input_df['flag'].map(fmap)
10
- input_df = input_df[features]
11
- input_data_scaled = sc.transform(input_df)
12
- return input_data_scaled.reshape((-1,30,1)) # Reshape for CNN
13
- def predict_attack(preprocessed_data, cnn_model):
14
- """Predicts the attack type using the CNN model."""
15
- prediction = cnn_model.predict(preprocessed_data)
16
- amap = {0: 'dos', 1: 'normal', 2: 'probe', 3: 'r2l', 4: 'u2r'}
17
- predicted_attack_type = amap[np.argmax(prediction)]
18
- return predicted_attack_type
19
-
20
- def network_attack_pipeline(input_data, cnn_model, pmap, fmap, features, sc):
21
- """
22
- A pipeline for predicting network attacks.
23
-
24
- Args:
25
- input_data (dict): Input data dictionary.
26
- cnn_model (keras.Model): Trained CNN model.
27
- pmap (dict): Mapping for protocol_type.
28
- fmap (dict): Mapping for flag.
29
- features (list): List of features used in training.
30
- sc (MinMaxScaler): Scaler object.
31
-
32
- Returns:
33
- str: Predicted attack type.
34
- """
35
- preprocessed_data = preprocess_data(input_data, pmap, fmap, features, sc)
36
- predicted_attack = predict_attack(preprocessed_data, cnn_model)
37
- return predicted_attack
38
-
39
- pmap = {'icmp': 0, 'tcp': 1, 'udp': 2}
40
- fmap = {'SF': 0, 'S0': 1, 'REJ': 2, 'RSTR': 3, 'RSTO': 4, 'SH': 5, 'S1': 6, 'S2': 7, 'RSTOS0': 8, 'S3': 9, 'OTH': 10}
41
- features = ['duration', 'protocol_type', 'flag', 'src_bytes', 'dst_bytes', 'land',
42
- 'wrong_fragment', 'urgent', 'hot', 'num_failed_logins', 'logged_in',
43
- 'num_compromised', 'root_shell', 'su_attempted', 'num_file_creations',
44
- 'num_shells', 'num_access_files', 'is_guest_login', 'count',
45
- 'srv_count', 'serror_rate', 'rerror_rate', 'same_srv_rate',
46
- 'diff_srv_rate', 'srv_diff_host_rate', 'dst_host_count',
47
- 'dst_host_srv_count', 'dst_host_diff_srv_rate',
48
- 'dst_host_same_src_port_rate', 'dst_host_srv_diff_host_rate']
49
-
50
- from tensorflow.keras.models import load_model
51
- import joblib
52
- import pickle
53
- cnn_model = load_model("cnn_model.h5")
54
-
55
- # Load the MinMaxScaler
56
- scaler = joblib.load("scaler.pkl")
57
-
58
-
59
- # Now this section in for frontend....
60
- import streamlit as st
61
- st.caption('Input must be in given sequence: ')
62
- st.caption(features)
63
- input=st.text_input("Enter the input with comma Seprated value: ")
64
- listVal=input.split(',')
65
- def predict():
66
- inputList=[]
67
- inputList.append((int)(listVal[0]))
68
- inputList.append(listVal[1])
69
- inputList.append(listVal[2])
70
- inputList.append((int)(listVal[3]))
71
- inputList.append((int)(listVal[4]))
72
- inputList.append((int)(listVal[5]))
73
- inputList.append((int)(listVal[6]))
74
- inputList.append((int)(listVal[7]))
75
- inputList.append((int)(listVal[8]))
76
- inputList.append((int)(listVal[9]))
77
- inputList.append((int)(listVal[10]))
78
- inputList.append((int)(listVal[11]))
79
- inputList.append((int)(listVal[12]))
80
- inputList.append((int)(listVal[13]))
81
- inputList.append((int)(listVal[14]))
82
- inputList.append((int)(listVal[15]))
83
- inputList.append((int)(listVal[16]))
84
- inputList.append((int)(listVal[17]))
85
- inputList.append((int)(listVal[18]))
86
- inputList.append((int)(listVal[19]))
87
- inputList.append((float)(listVal[20]))
88
- inputList.append((float)(listVal[21]))
89
- inputList.append((float)(listVal[22]))
90
- inputList.append((float)(listVal[23]))
91
- inputList.append((float)(listVal[24]))
92
- inputList.append((int)(listVal[25]))
93
- inputList.append((int)(listVal[26]))
94
- inputList.append((float)(listVal[27]))
95
- inputList.append((float)(listVal[28]))
96
- inputList.append((float)(listVal[29]))
97
- ans=''
98
- try:
99
- ans=network_attack_pipeline(inputList,cnn_model, pmap, fmap, features, scaler)
100
- except:
101
- return "Input is not in valid form:"
102
- return ans
103
-
104
- if(st.button('Predict')):
105
- st.title(predict())
106
-
107
-
108
- input2 =st.number_input("Enter the input between(0-494021)",step=1)
109
- def predict1():
110
- df=pd.read_csv('validation.csv')
111
- x=df.iloc[input2,:-1]
112
- lb=df.iloc[input2,-1]
113
- st.title(f"Labeled as: {lb.upper()}")
114
- print(df.iloc[input2,-1])
115
- try:
116
- res=network_attack_pipeline(x,cnn_model, pmap, fmap, features, scaler)
117
- st.title(f"Predicted as: {res.upper()}")
118
- except:
119
- st.title("There is some essue try on another value...")
120
-
121
- if(st.button('Validate')):
122
- predict1()
123
-
124
-
125
-
126
-
127
-
 
 
1
+ import pandas as pd
2
+ import numpy as np
3
+ from sklearn.preprocessing import MinMaxScaler
4
+
5
+ def preprocess_data(input_data, pmap, fmap, features, sc):
6
+ """Preprocesses the input data."""
7
+ input_df = pd.DataFrame([input_data], columns=features)
8
+ input_df['protocol_type'] = input_df['protocol_type'].map(pmap)
9
+ input_df['flag'] = input_df['flag'].map(fmap)
10
+ input_df = input_df[features]
11
+ input_data_scaled = sc.transform(input_df)
12
+ return input_data_scaled.reshape((-1,30,1)) # Reshape for CNN
13
+ def predict_attack(preprocessed_data, cnn_model):
14
+ """Predicts the attack type using the CNN model."""
15
+ prediction = cnn_model.predict(preprocessed_data)
16
+ amap = {0: 'dos', 1: 'normal', 2: 'probe', 3: 'r2l', 4: 'u2r'}
17
+ predicted_attack_type = amap[np.argmax(prediction)]
18
+ return predicted_attack_type
19
+
20
+ def network_attack_pipeline(input_data, cnn_model, pmap, fmap, features, sc):
21
+ """
22
+ A pipeline for predicting network attacks.
23
+
24
+ Args:
25
+ input_data (dict): Input data dictionary.
26
+ cnn_model (keras.Model): Trained CNN model.
27
+ pmap (dict): Mapping for protocol_type.
28
+ fmap (dict): Mapping for flag.
29
+ features (list): List of features used in training.
30
+ sc (MinMaxScaler): Scaler object.
31
+
32
+ Returns:
33
+ str: Predicted attack type.
34
+ """
35
+ preprocessed_data = preprocess_data(input_data, pmap, fmap, features, sc)
36
+ predicted_attack = predict_attack(preprocessed_data, cnn_model)
37
+ return predicted_attack
38
+
39
+ pmap = {'icmp': 0, 'tcp': 1, 'udp': 2}
40
+ fmap = {'SF': 0, 'S0': 1, 'REJ': 2, 'RSTR': 3, 'RSTO': 4, 'SH': 5, 'S1': 6, 'S2': 7, 'RSTOS0': 8, 'S3': 9, 'OTH': 10}
41
+ features = ['duration', 'protocol_type', 'flag', 'src_bytes', 'dst_bytes', 'land',
42
+ 'wrong_fragment', 'urgent', 'hot', 'num_failed_logins', 'logged_in',
43
+ 'num_compromised', 'root_shell', 'su_attempted', 'num_file_creations',
44
+ 'num_shells', 'num_access_files', 'is_guest_login', 'count',
45
+ 'srv_count', 'serror_rate', 'rerror_rate', 'same_srv_rate',
46
+ 'diff_srv_rate', 'srv_diff_host_rate', 'dst_host_count',
47
+ 'dst_host_srv_count', 'dst_host_diff_srv_rate',
48
+ 'dst_host_same_src_port_rate', 'dst_host_srv_diff_host_rate']
49
+
50
+ from tensorflow.keras.models import load_model
51
+ import joblib
52
+ import pickle
53
+ cnn_model = load_model("cnn_model.h5")
54
+
55
+ # Load the MinMaxScaler
56
+ scaler = joblib.load("scaler.pkl")
57
+
58
+
59
+ # Now this section in for frontend....
60
+ import streamlit as st
61
+ st.caption('Input must be in given sequence: ')
62
+ st.caption(features)
63
+ st.caption("Eg: '0, 1,0,181,5450,0,0,0,0,0,1,0,0,0,0,0,0,0,8,8,0,0,1,0,0,9,9,0,0.11,0'")
64
+ input=st.text_input("Enter the input with comma Seprated value: ")
65
+ listVal=input.split(',')
66
+ def predict():
67
+ inputList=[]
68
+ inputList.append((int)(listVal[0]))
69
+ inputList.append(listVal[1])
70
+ inputList.append(listVal[2])
71
+ inputList.append((int)(listVal[3]))
72
+ inputList.append((int)(listVal[4]))
73
+ inputList.append((int)(listVal[5]))
74
+ inputList.append((int)(listVal[6]))
75
+ inputList.append((int)(listVal[7]))
76
+ inputList.append((int)(listVal[8]))
77
+ inputList.append((int)(listVal[9]))
78
+ inputList.append((int)(listVal[10]))
79
+ inputList.append((int)(listVal[11]))
80
+ inputList.append((int)(listVal[12]))
81
+ inputList.append((int)(listVal[13]))
82
+ inputList.append((int)(listVal[14]))
83
+ inputList.append((int)(listVal[15]))
84
+ inputList.append((int)(listVal[16]))
85
+ inputList.append((int)(listVal[17]))
86
+ inputList.append((int)(listVal[18]))
87
+ inputList.append((int)(listVal[19]))
88
+ inputList.append((float)(listVal[20]))
89
+ inputList.append((float)(listVal[21]))
90
+ inputList.append((float)(listVal[22]))
91
+ inputList.append((float)(listVal[23]))
92
+ inputList.append((float)(listVal[24]))
93
+ inputList.append((int)(listVal[25]))
94
+ inputList.append((int)(listVal[26]))
95
+ inputList.append((float)(listVal[27]))
96
+ inputList.append((float)(listVal[28]))
97
+ inputList.append((float)(listVal[29]))
98
+ ans=''
99
+ try:
100
+ ans=network_attack_pipeline(inputList,cnn_model, pmap, fmap, features, scaler)
101
+ except:
102
+ return "Input is not in valid form:"
103
+ return ans
104
+
105
+ if(st.button('Predict')):
106
+ st.title(predict())
107
+
108
+
109
+ input2 =st.number_input("Enter the input between(0-494021)",step=1)
110
+ def predict1():
111
+ df=pd.read_csv('validation.csv')
112
+ x=df.iloc[input2,:-1]
113
+ lb=df.iloc[input2,-1]
114
+ st.title(f"Labeled as: {lb.upper()}")
115
+ print(df.iloc[input2,-1])
116
+ try:
117
+ res=network_attack_pipeline(x,cnn_model, pmap, fmap, features, scaler)
118
+ st.title(f"Predicted as: {res.upper()}")
119
+ except:
120
+ st.title("There is some essue try on another value...")
121
+
122
+ if(st.button('Validate')):
123
+ predict1()
124
+
125
+
126
+
127
+
128
+