-
Notifications
You must be signed in to change notification settings - Fork 2
/
utils.py
103 lines (79 loc) · 2.91 KB
/
utils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
import os
import pickle
import config
import warnings
import pandas as pd
import joblib as jl
import tldextract as xt
from nltk.util import ngrams
from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer
from sklearn.preprocessing import LabelEncoder
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
warnings.filterwarnings(action='ignore')
# helper function
def join_char(s):
str1 = ''
return(str1.join(s))
# function to perform n_grams on input string
def n_gram_extraction(n, token):
lst = []
n_grams = ngrams(list(str(token)), n)
for items in n_grams:
res = join_char(list(items))
lst.append(res)
return lst
# function to tokenize input url and extract values to form unigrams, bigrams & trigrams
def tokenizer(url):
# break url to domain, subdomain & suffix
# full url token - domain + subdomain + suffix
url_token = f'{url}-{xt.extract(url).subdomain}-{xt.extract(url).domain}-{xt.extract(url).suffix}'
# url to unigram level
domain_unigram = n_gram_extraction(1,xt.extract(url).domain)
subdomain_unigram = n_gram_extraction(1,xt.extract(url).subdomain)
# url to bigram level
domain_bigram = n_gram_extraction(2,xt.extract(url).domain)
subdomain_bigram = n_gram_extraction(2,xt.extract(url).subdomain)
# url to trigram level
domain_trigram = n_gram_extraction(3,xt.extract(url).domain)
subdomain_trigram = n_gram_extraction(3,xt.extract(url).subdomain)
token = url_token.split('-')
if '' in token:
token.remove('') # remove empty element in list
# append final exteacted tokens to list to form extracted features
for item in domain_unigram:
token.append(item)
for item in subdomain_unigram:
token.append(item)
for item in domain_bigram:
token.append(item)
for item in domain_trigram:
token.append(item)
for item in subdomain_bigram:
token.append(item)
for item in subdomain_trigram:
token.append(item)
# print(token)
return token
# predict model function
def predict(url):
url = str(url).lower()
# load train data to fit vectorizer
with open(config.X_TRAIN_SAVED, 'rb') as f:
Xtrain = pickle.load(f)
# preprocess & vectorize train set
tVec = TfidfVectorizer(tokenizer=tokenizer)
tf = tVec.fit_transform(Xtrain)
# preprocess and vectorize input url
input = [url]
tf = tVec.transform(input)
# load trained model
model = jl.load(config.TRAINED_MODEL, 'r')
# prediction
result = model.predict(tf)
res = {'0': 'maleware domain', '1': 'legit'}
# print(res[str(result[0])])
return res[str(result[0])]
if __name__ == '__main__':
# print(predict('GorddsogjowdhvoudhsidhsklE.Com'))
pass