Spaces:
Sleeping
Sleeping
cheikhdeme
commited on
Update app.py
Browse files
app.py
CHANGED
@@ -1,4 +1,3 @@
|
|
1 |
-
|
2 |
import os
|
3 |
import joblib
|
4 |
import pefile
|
@@ -6,18 +5,57 @@ import numpy as np
|
|
6 |
import pandas as pd
|
7 |
import gradio as gr
|
8 |
import hashlib
|
9 |
-
import pickle
|
10 |
import traceback
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
11 |
|
|
|
|
|
12 |
|
13 |
-
#
|
14 |
-
model
|
15 |
-
|
16 |
-
|
17 |
-
except Exception as e:
|
18 |
-
print(f"Erreur de chargement du modèle : {e}")
|
19 |
-
traceback.print_exc() # Affiche la trace de l'erreur
|
20 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
21 |
def calculate_file_hash(file_path):
|
22 |
"""Calculer le hash SHA-256 du fichier."""
|
23 |
sha256_hash = hashlib.sha256()
|
@@ -30,9 +68,7 @@ def extract_pe_attributes(file_path):
|
|
30 |
"""Extraction avancée des attributs du fichier PE."""
|
31 |
try:
|
32 |
pe = pefile.PE(file_path)
|
33 |
-
|
34 |
attributes = {
|
35 |
-
# Attributs PE standard
|
36 |
'AddressOfEntryPoint': pe.OPTIONAL_HEADER.AddressOfEntryPoint,
|
37 |
'MajorLinkerVersion': pe.OPTIONAL_HEADER.MajorLinkerVersion,
|
38 |
'MajorImageVersion': pe.OPTIONAL_HEADER.MajorImageVersion,
|
@@ -40,26 +76,12 @@ def extract_pe_attributes(file_path):
|
|
40 |
'DllCharacteristics': pe.OPTIONAL_HEADER.DllCharacteristics,
|
41 |
'SizeOfStackReserve': pe.OPTIONAL_HEADER.SizeOfStackReserve,
|
42 |
'NumberOfSections': pe.FILE_HEADER.NumberOfSections,
|
43 |
-
|
44 |
}
|
45 |
-
|
46 |
-
"""## Ressources
|
47 |
-
data_directory_entries = pe.OPTIONAL_HEADER.DATA_DIRECTORY
|
48 |
-
# Parcourir la liste pour trouver l'entrée du répertoire des ressources
|
49 |
-
for entry in data_directory_entries:
|
50 |
-
if entry.name == "IMAGE_DIRECTORY_ENTRY_RESOURCE":
|
51 |
-
resource_size = entry.Size
|
52 |
-
attributes['ResourceSize'] = resource_size
|
53 |
-
break
|
54 |
-
else:
|
55 |
-
attributes['ResourceSize'] = 0"""
|
56 |
-
|
57 |
-
|
58 |
-
|
59 |
return attributes
|
60 |
except Exception as e:
|
61 |
print(f"Erreur de traitement du fichier {file_path}: {str(e)}")
|
62 |
-
return
|
63 |
|
64 |
def predict_malware(file):
|
65 |
"""Prédiction de malware avec gestion d'erreurs."""
|
@@ -70,7 +92,7 @@ def predict_malware(file):
|
|
70 |
# Extraire les attributs du fichier
|
71 |
attributes = extract_pe_attributes(file.name)
|
72 |
if "Erreur" in attributes:
|
73 |
-
return attributes
|
74 |
|
75 |
# Convertir en DataFrame
|
76 |
df = pd.DataFrame([attributes])
|
@@ -97,4 +119,4 @@ demo = gr.Interface(
|
|
97 |
)
|
98 |
|
99 |
if __name__ == "__main__":
|
100 |
-
demo.launch(share=True)
|
|
|
|
|
1 |
import os
|
2 |
import joblib
|
3 |
import pefile
|
|
|
5 |
import pandas as pd
|
6 |
import gradio as gr
|
7 |
import hashlib
|
|
|
8 |
import traceback
|
9 |
+
from sklearn.ensemble import RandomForestClassifier
|
10 |
+
from sklearn.model_selection import train_test_split
|
11 |
+
from sklearn.metrics import accuracy_score, recall_score
|
12 |
+
|
13 |
+
# Chemin vers le modèle sauvegardé
|
14 |
+
MODEL_PATH = 'random_forest_model.pkl'
|
15 |
+
|
16 |
+
def train_and_save_model():
|
17 |
+
"""Entraîner et sauvegarder le modèle si nécessaire."""
|
18 |
+
print("Aucun modèle trouvé. Entraînement en cours...")
|
19 |
+
# Chargement des données
|
20 |
+
data = pd.read_csv("DatasetmalwareExtrait.csv")
|
21 |
+
|
22 |
+
# Traitement des données
|
23 |
+
X = data.drop(['legitimate'], axis=1)
|
24 |
+
y = data['legitimate']
|
25 |
+
|
26 |
+
# Entraînement du modèle
|
27 |
+
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
|
28 |
+
model = RandomForestClassifier(
|
29 |
+
n_estimators=196,
|
30 |
+
random_state=42,
|
31 |
+
criterion="gini",
|
32 |
+
max_depth=25,
|
33 |
+
min_samples_split=4,
|
34 |
+
min_samples_leaf=1
|
35 |
+
)
|
36 |
+
model.fit(X_train, y_train)
|
37 |
+
|
38 |
+
# Évaluation du modèle
|
39 |
+
y_pred = model.predict(X_test)
|
40 |
+
accuracy = accuracy_score(y_test, y_pred)
|
41 |
+
recall = recall_score(y_test, y_pred, average='weighted')
|
42 |
|
43 |
+
print(f"Précision du modèle supervisé : {accuracy:.3f}")
|
44 |
+
print(f"Rappel du modèle supervisé : {recall:.3f}")
|
45 |
|
46 |
+
# Sauvegarde du modèle
|
47 |
+
joblib.dump(model, MODEL_PATH)
|
48 |
+
print(f"Modèle sauvegardé sous : {MODEL_PATH}")
|
49 |
+
return model
|
|
|
|
|
|
|
50 |
|
51 |
+
# Chargement ou entraînement du modèle
|
52 |
+
if os.path.exists(MODEL_PATH):
|
53 |
+
print("Chargement du modèle existant...")
|
54 |
+
model = joblib.load(MODEL_PATH)
|
55 |
+
else:
|
56 |
+
model = train_and_save_model()
|
57 |
+
|
58 |
+
# Fonctions utilitaires
|
59 |
def calculate_file_hash(file_path):
|
60 |
"""Calculer le hash SHA-256 du fichier."""
|
61 |
sha256_hash = hashlib.sha256()
|
|
|
68 |
"""Extraction avancée des attributs du fichier PE."""
|
69 |
try:
|
70 |
pe = pefile.PE(file_path)
|
|
|
71 |
attributes = {
|
|
|
72 |
'AddressOfEntryPoint': pe.OPTIONAL_HEADER.AddressOfEntryPoint,
|
73 |
'MajorLinkerVersion': pe.OPTIONAL_HEADER.MajorLinkerVersion,
|
74 |
'MajorImageVersion': pe.OPTIONAL_HEADER.MajorImageVersion,
|
|
|
76 |
'DllCharacteristics': pe.OPTIONAL_HEADER.DllCharacteristics,
|
77 |
'SizeOfStackReserve': pe.OPTIONAL_HEADER.SizeOfStackReserve,
|
78 |
'NumberOfSections': pe.FILE_HEADER.NumberOfSections,
|
79 |
+
'ResourceSize': pe.OPTIONAL_HEADER.DATA_DIRECTORY[2].Size
|
80 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
81 |
return attributes
|
82 |
except Exception as e:
|
83 |
print(f"Erreur de traitement du fichier {file_path}: {str(e)}")
|
84 |
+
return {"Erreur": str(e)}
|
85 |
|
86 |
def predict_malware(file):
|
87 |
"""Prédiction de malware avec gestion d'erreurs."""
|
|
|
92 |
# Extraire les attributs du fichier
|
93 |
attributes = extract_pe_attributes(file.name)
|
94 |
if "Erreur" in attributes:
|
95 |
+
return attributes["Erreur"]
|
96 |
|
97 |
# Convertir en DataFrame
|
98 |
df = pd.DataFrame([attributes])
|
|
|
119 |
)
|
120 |
|
121 |
if __name__ == "__main__":
|
122 |
+
demo.launch(share=True)
|