File size: 1,600 Bytes
84f95cd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Export the trained model to a compact JSON file that space/model.js runs in the browser.

Usage: python src/export_js.py --model outputs/model --out space/model.json
"""
import argparse
import json

from skops.io import get_untrusted_types, load

from urlflags import FLAG_IDS


def block(vec, coefs, digits):
    terms = sorted(vec.vocabulary_.items(), key=lambda kv: kv[1])
    idf = vec.idf_
    return {t: [round(float(idf[i]), 5), round(float(coefs[i]), digits)] for t, i in terms}


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--model", default="outputs/model")
    ap.add_argument("--out", default="space/model.json")
    args = ap.parse_args()
    f = f"{args.model}/model.skops"
    m = load(f, trusted=get_untrusted_types(file=f))
    char, toks, clf = m["char"], m["toks"], m["clf"]
    coef = clf.coef_[0]
    nc, nt = len(char.vocabulary_), len(toks.vocabulary_)
    out = {
        "format": "url-tfidf-logreg-v1",
        "labels": ["benign", "malicious"],
        "intercept": round(float(clf.intercept_[0]), 6),
        "threshold": m["threshold"],
        "char": {"ngram_range": list(char.ngram_range), "terms": block(char, coef[:nc], 5)},
        "toks": {"terms": block(toks, coef[nc:nc + nt], 5)},
        "flags": {"ids": FLAG_IDS, "scale": m["flag_scale"], "coef": [round(float(c), 5) for c in coef[nc + nt:]]},
    }
    with open(args.out, "w") as fh:
        json.dump(out, fh, ensure_ascii=False, separators=(",", ":"))
    print(f"wrote {args.out}: {nc} char + {nt} token terms + {len(FLAG_IDS)} flags")


if __name__ == "__main__":
    main()