z4hid commited on
Commit
98d74fb
·
verified ·
1 Parent(s): 0adb0d0

source code added

Browse files

`src` folder contains model.py and serve.py files

Files changed (3) hide show
  1. src/__init__.py +1 -0
  2. src/model.py +87 -0
  3. src/serve.py +73 -0
src/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+
src/model.py ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from torch import nn
3
+ import torch.nn.functional as F
4
+
5
+
6
+ malware_classes = ['7ev3n', 'APosT', 'Adposhel', 'Agent', 'Agentb', 'Allaple', 'Alueron.gen!J', 'Amonetize',
7
+ 'Androm', 'Bashlite', 'Bingoml', 'Blacksoul', 'BrowseFox', 'C2LOP.gen!g', 'Convagent', 'Copak',
8
+ 'Delf', 'Dialplatform.B', 'Dinwod', 'Elex', 'Emotet', 'Escelar', 'Expiro', 'Fakerean', 'Fareit',
9
+ 'Fasong', 'GandCrab', 'GlobelImposter', 'GootLoader', 'HLLP', 'HackKMS', 'Hlux', 'IcedId', 'Infy',
10
+ 'Inject', 'Injector', 'InstallCore', 'KRBanker', 'Koadic', 'Kryptik', 'Kwampirs', 'Lamer',
11
+ 'LemonDuck', 'Loki', 'Lolyda.AA1', 'Lolyda.AA2', 'Mimail', 'MultiPlug', 'Mydoom', 'Neoreklami',
12
+ 'Neshta', 'NetWireRAT', 'Ngrbot', 'OnlinerSpambot', 'Orcus', 'Padodor', 'Plite', 'PolyRansom',
13
+ 'QakBot', 'QtBot', 'Qukart', 'REvil', 'Ramdo', 'Regrun', 'Rekt Loader', 'Sakula', 'Salgorea',
14
+ 'Scar', 'SelfDel', 'Small', 'Snarasite', 'Stantinko', 'Trickpak', 'Upantix', 'Upatre', 'VB',
15
+ 'VBA', 'VBKrypt', 'VBNA', 'Vilsel', 'Vobfus', 'WBNA', 'Wecod', 'XTunnel', 'Zenpak', 'Zeus', 'benign']
16
+
17
+ class DenseLayer(nn.Module):
18
+ def __init__(self, in_channels, growth_rate, bn_size):
19
+ super(DenseLayer, self).__init__()
20
+ self.bn1 = nn.BatchNorm2d(in_channels)
21
+ self.conv1 = nn.Conv2d(in_channels, bn_size * growth_rate, kernel_size=1, bias=False)
22
+ self.bn2 = nn.BatchNorm2d(bn_size * growth_rate)
23
+ self.conv2 = nn.Conv2d(bn_size * growth_rate, growth_rate, kernel_size=3, padding=1, bias=False)
24
+
25
+ def forward(self, x):
26
+ out = self.conv1(F.relu(self.bn1(x)))
27
+ out = self.conv2(F.relu(self.bn2(out)))
28
+ return torch.cat([x, out], 1)
29
+
30
+ class DenseBlock(nn.Module):
31
+ def __init__(self, num_layers, in_channels, growth_rate, bn_size):
32
+ super(DenseBlock, self).__init__()
33
+ layers = []
34
+ for i in range(num_layers):
35
+ layers.append(DenseLayer(in_channels + i * growth_rate, growth_rate, bn_size))
36
+ self.layers = nn.Sequential(*layers)
37
+
38
+ def forward(self, x):
39
+ return self.layers(x)
40
+
41
+ class TransitionLayer(nn.Module):
42
+ def __init__(self, in_channels, out_channels):
43
+ super(TransitionLayer, self).__init__()
44
+ self.bn = nn.BatchNorm2d(in_channels)
45
+ self.conv = nn.Conv2d(in_channels, out_channels, kernel_size=1, bias=False)
46
+ self.pool = nn.AvgPool2d(kernel_size=2, stride=2)
47
+
48
+ def forward(self, x):
49
+ out = self.conv(F.relu(self.bn(x)))
50
+ return self.pool(out)
51
+
52
+ class MalwareNet(nn.Module):
53
+ def __init__(self, growth_rate=32, block_config=(6, 12, 24, 16), num_init_features=64, bn_size=4, compression_rate=0.5, num_classes=87):
54
+ super(MalwareNet, self).__init__()
55
+
56
+ # First convolution
57
+ self.features = nn.Sequential(
58
+ nn.Conv2d(3, num_init_features, kernel_size=7, stride=2, padding=3, bias=False),
59
+ nn.BatchNorm2d(num_init_features),
60
+ nn.ReLU(inplace=True),
61
+ nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
62
+ )
63
+
64
+ # Dense blocks
65
+ num_features = num_init_features
66
+ for i, num_layers in enumerate(block_config):
67
+ block = DenseBlock(num_layers, num_features, growth_rate, bn_size)
68
+ self.features.add_module(f'denseblock{i+1}', block)
69
+ num_features += num_layers * growth_rate
70
+ if i != len(block_config) - 1:
71
+ transition = TransitionLayer(num_features, int(num_features * compression_rate))
72
+ self.features.add_module(f'transition{i+1}', transition)
73
+ num_features = int(num_features * compression_rate)
74
+
75
+ # Final batch norm
76
+ self.features.add_module('norm5', nn.BatchNorm2d(num_features))
77
+
78
+ # Linear layer
79
+ self.classifier = nn.Linear(num_features, num_classes)
80
+
81
+ def forward(self, x):
82
+ features = self.features(x)
83
+ out = F.relu(features)
84
+ out = F.adaptive_avg_pool2d(out, (1, 1))
85
+ out = torch.flatten(out, 1)
86
+ out = self.classifier(out)
87
+ return out
src/serve.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from PIL import Image
2
+ from torchvision import transforms
3
+ import torch
4
+ import os
5
+ from fastapi import FastAPI, HTTPException
6
+ from fastapi.responses import JSONResponse
7
+ from io import BytesIO
8
+
9
+ # from dotenv import load_dotenv
10
+ from .model import MalwareNet, malware_classes # assuming malware_classes contains class names
11
+
12
+ # load_dotenv()
13
+
14
+ app = FastAPI()
15
+
16
+ # Preprocessing function for the model
17
+ def preprocess_image(image_path):
18
+ image = Image.open(image_path).convert("RGB")
19
+ preprocess = transforms.Compose([
20
+ transforms.Resize((224, 224)), # Resize to the input size expected by the model
21
+ transforms.ToTensor(), # Convert to tensor
22
+ transforms.Normalize( # Normalize using model's requirements (e.g. ImageNet)
23
+ mean=[0.485, 0.456, 0.406],
24
+ std=[0.229, 0.224, 0.225]
25
+ )
26
+ ])
27
+ return preprocess(image).unsqueeze(0) # Add batch dimension
28
+
29
+ # Load model and its weights
30
+ def load_model():
31
+ model = MalwareNet()
32
+ base_dir = os.path.dirname(os.path.abspath(__file__))
33
+ model_location = os.path.join(base_dir, '../model/malwareNet.pt') # Relative path to the model file
34
+ state_dict = torch.load(model_location, map_location=torch.device('cpu'), weights_only=True)
35
+ model.load_state_dict(state_dict)
36
+ model.eval() # Set the model to evaluation mode
37
+ return model
38
+
39
+ @app.get("/")
40
+ def status():
41
+ return {"status": "ok"}
42
+
43
+ @app.post("/predict")
44
+ async def predict(data: dict):
45
+ image_path = data.get("image_url")
46
+ if not os.path.exists(image_path):
47
+ raise HTTPException(status_code=400, detail="Image path does not exist.")
48
+
49
+ try:
50
+ # Load and preprocess the image
51
+ img_tensor = preprocess_image(image_path)
52
+
53
+ # Load the model and make the prediction
54
+ model = load_model()
55
+ with torch.no_grad(): # No gradient calculation is needed
56
+ prediction = model(img_tensor)
57
+
58
+ # Get the predicted class
59
+ predicted_class = malware_classes[torch.argmax(prediction).item()]
60
+
61
+ return JSONResponse(content={"image": image_path, "prediction": predicted_class})
62
+
63
+ except Exception as e:
64
+ raise HTTPException(status_code=500, detail=f"Error processing the image: {e}")
65
+
66
+ if __name__ == "__main__":
67
+ import uvicorn
68
+ uvicorn.run(
69
+ "src.serve:app",
70
+ host=os.environ.get("HOST", "localhost"),
71
+ port=int(os.environ.get("PORT", 5000)),
72
+ reload=True,
73
+ )