<reponame>fauzan923/Malware-Detection-on-PE-File-using-Hybrid-Machine-Learning
# import yfinance as yf
import streamlit as st
import pandas as pd
import ember
import numpy as np
import re
import joblib

from sklearn.metrics import accuracy_score

st.set_page_config(page_title="Malware Detection Application")

st.write("""
# Malware Detection on PE Files using Hybrid Machine Learning (.exe File)
""")

# st.sidebar.markdown("""
# [Example CSV input file](https://raw.githubusercontent.com/dataprofessor/data/master/penguins_example.csv)
# """)

st.sidebar.header('SIDEBAR')

# Collects user input features into dataframe
uploaded_file = st.sidebar.file_uploader("Upload the .exe file here", type=["exe"])


if uploaded_file is not None:

    # Memprediksi PE File yang akan Diprediksi Ekstraksi fitur PE Filenya dahulu, lalu hasil ekstraksinya diprediksi pakai model yang sudah dibuat dan ditraining
    df_columns = pd.read_csv('../Bodmas/ember_2381_feature_names.txt', delimiter='\n')
    df_columns = list(df_columns['0'])
    extractor = ember.PEFeatureExtractor() 
    file_data = uploaded_file.read()
    extracted_features = np.array(extractor.feature_vector(file_data), dtype=np.float32)
    df_PE = pd.DataFrame([extracted_features], columns=df_columns)
    df_PE = df_PE.rename(columns = lambda x:re.sub('[^A-Za-z0-9_]+', '', x))

    # NGEDROP FEATURE YANG TIDAK TERPAKAI PADA df_PE SESUAI DENGAN HASIL SELEKSI FITUR YANG SUDAH PERNAH DILAKUKAN
    selected_feat = pd.read_csv('output.txt', delimiter='\n')
    selected_feat = list(selected_feat['0'])
    columns_train_not_used = [column for column in df_PE.columns if column not in selected_feat]
    df_PE = df_PE.drop(columns_train_not_used,axis=1)

    # Ngeload hasil dari model hybrid machine learning yang sudah di training 
    sclfjl = joblib.load('sclf_joblib')
    sclfjl_pred = sclfjl.predict(df_PE)
    sclf_pred_prob = sclfjl.predict_proba(df_PE)
    # y_test = pd.read_csv('y_test.csv')
    # score = accuracy_score(y_test, sclfjl_pred)*100
    # classification_report(y_test, CAT_pred, target_names=['Benign', 'Malware'])

    st.write('## The first line of the detected PE File feature extraction \n',df_PE)
    st.write('## The number of features used based on the results of feature selection \n')
    st.info(len(df_PE.columns))
    st.write('## The hybrid machine learning malware probability value of the detected PE File \n')
    st.info("The PE File has the probability of {:.4f}% of being a Malware File".format(sclf_pred_prob[0,1]))
    hasil_file = lambda x: "Malware File" if (x == 1) else "Benign File"
    st.write('## The Hybrid machine learning prediction results based on the probability value \n')
    st.info("The analyzed PE File is detected as a {}".format(hasil_file(sclfjl_pred[0])))

else:
    # def user_input_features():
    #     data = {'test': 'test'}
    #     features = pd.DataFrame(data, index=[0])
    #     return features
    # df_PE = user_input_features()
    # sclfjl_pred = user_input_features()
    # sclf_pred_prob = user_input_features()
    st.info('To start analyzing your .exe file, insert your .exe file by pressing the **Browse File** button on the left **SIDEBAR** of your screen')
    

# Ngeload hasil dari model hybrid machine learning yang sudah di training 
# sclfjl = joblib.load('sclf_joblib')



# # https://towardsdatascience.com/how-to-get-stock-data-using-python-c0de1df17e75
# # define the ticker symbol
# tickerSymbol = 'GOOGL'
# #get data on this ticker
# tickerData = yf.Ticker(tickerSymbol)
# #get the historical prices for this ticker
# tickerDf = tickerData.history(period='1d', start='2010-5-31', end='2020-5-31')
# # Open	High	Low	Close	Volume	Dividends	Stock Splits

# st.line_chart(tickerDf.Close)
# st.line_chart(tickerDf.Volume)
# import yfinance as yf
import streamlit as st
import pandas as pd
import ember
import numpy as np
import re
import joblib

from sklearn.metrics import accuracy_score

st.set_page_config(page_title="Malware Detection Application")

st.write("""
# Malware Detection on PE Files using Hybrid Machine Learning (.exe File)
""")

# st.sidebar.markdown("""
# [Example CSV input file](https://raw.githubusercontent.com/dataprofessor/data/master/penguins_example.csv)
# """)

st.sidebar.header('SIDEBAR')

# Collects user input features into dataframe
uploaded_file = st.sidebar.file_uploader("Upload the .exe file here", type=["exe"])


if uploaded_file is not None:

    # Memprediksi PE File yang akan Diprediksi Ekstraksi fitur PE Filenya dahulu, lalu hasil ekstraksinya diprediksi pakai model yang sudah dibuat dan ditraining
    df_columns = pd.read_csv('../Bodmas/ember_2381_feature_names.txt', delimiter='\n')
    df_columns = list(df_columns['0'])
    extractor = ember.PEFeatureExtractor() 
    file_data = uploaded_file.read()
    extracted_features = np.array(extractor.feature_vector(file_data), dtype=np.float32)
    df_PE = pd.DataFrame([extracted_features], columns=df_columns)
    df_PE = df_PE.rename(columns = lambda x:re.sub('[^A-Za-z0-9_]+', '', x))

    # NGEDROP FEATURE YANG TIDAK TERPAKAI PADA df_PE SESUAI DENGAN HASIL SELEKSI FITUR YANG SUDAH PERNAH DILAKUKAN
    selected_feat = pd.read_csv('output.txt', delimiter='\n')
    selected_feat = list(selected_feat['0'])
    columns_train_not_used = [column for column in df_PE.columns if column not in selected_feat]
    df_PE = df_PE.drop(columns_train_not_used,axis=1)

    # Ngeload hasil dari model hybrid machine learning yang sudah di training 
    sclfjl = joblib.load('sclf_joblib')
    sclfjl_pred = sclfjl.predict(df_PE)
    sclf_pred_prob = sclfjl.predict_proba(df_PE)
    # y_test = pd.read_csv('y_test.csv')
    # score = accuracy_score(y_test, sclfjl_pred)*100
    # classification_report(y_test, CAT_pred, target_names=['Benign', 'Malware'])

    st.write('## The first line of the detected PE File feature extraction \n',df_PE)
    st.write('## The number of features used based on the results of feature selection \n')
    st.info(len(df_PE.columns))
    st.write('## The hybrid machine learning malware probability value of the detected PE File \n')
    st.info("The PE File has the probability of {:.4f}% of being a Malware File".format(sclf_pred_prob[0,1]))
    hasil_file = lambda x: "Malware File" if (x == 1) else "Benign File"
    st.write('## The Hybrid machine learning prediction results based on the probability value \n')
    st.info("The analyzed PE File is detected as a {}".format(hasil_file(sclfjl_pred[0])))

else:
    # def user_input_features():
    #     data = {'test': 'test'}
    #     features = pd.DataFrame(data, index=[0])
    #     return features
    # df_PE = user_input_features()
    # sclfjl_pred = user_input_features()
    # sclf_pred_prob = user_input_features()
    st.info('To start analyzing your .exe file, insert your .exe file by pressing the **Browse File** button on the left **SIDEBAR** of your screen')
    

# Ngeload hasil dari model hybrid machine learning yang sudah di training 
# sclfjl = joblib.load('sclf_joblib')



# # https://towardsdatascience.com/how-to-get-stock-data-using-python-c0de1df17e75
# # define the ticker symbol
# tickerSymbol = 'GOOGL'
# #get data on this ticker
# tickerData = yf.Ticker(tickerSymbol)
# #get the historical prices for this ticker
# tickerDf = tickerData.history(period='1d', start='2010-5-31', end='2020-5-31')
# # Open	High	Low	Close	Volume	Dividends	Stock Splits

# st.line_chart(tickerDf.Close)
# st.line_chart(tickerDf.Volume)
# import yfinance as yf # Malware Detection on PE Files using Hybrid Machine Learning (.exe File) # st.sidebar.markdown(""" # [Example CSV input file](https://raw.githubusercontent.com/dataprofessor/data/master/penguins_example.csv) # """) # Collects user input features into dataframe # Memprediksi PE File yang akan Diprediksi Ekstraksi fitur PE Filenya dahulu, lalu hasil ekstraksinya diprediksi pakai model yang sudah dibuat dan ditraining # NGEDROP FEATURE YANG TIDAK TERPAKAI PADA df_PE SESUAI DENGAN HASIL SELEKSI FITUR YANG SUDAH PERNAH DILAKUKAN # Ngeload hasil dari model hybrid machine learning yang sudah di training # y_test = pd.read_csv('y_test.csv') # score = accuracy_score(y_test, sclfjl_pred)*100 # classification_report(y_test, CAT_pred, target_names=['Benign', 'Malware']) # The first line of the detected PE File feature extraction \n',df_PE) # The number of features used based on the results of feature selection \n') # The hybrid machine learning malware probability value of the detected PE File \n') # The Hybrid machine learning prediction results based on the probability value \n') # def user_input_features(): #     data = {'test': 'test'} #     features = pd.DataFrame(data, index=[0]) #     return features # df_PE = user_input_features() # sclfjl_pred = user_input_features() # sclf_pred_prob = user_input_features() # Ngeload hasil dari model hybrid machine learning yang sudah di training # sclfjl = joblib.load('sclf_joblib') # # https://towardsdatascience.com/how-to-get-stock-data-using-python-c0de1df17e75 # # define the ticker symbol # tickerSymbol = 'GOOGL' # #get data on this ticker # tickerData = yf.Ticker(tickerSymbol) # #get the historical prices for this ticker # tickerDf = tickerData.history(period='1d', start='2010-5-31', end='2020-5-31') # # Open	High	Low	Close	Volume	Dividends	Stock Splits # st.line_chart(tickerDf.Close) # st.line_chart(tickerDf.Volume)