malicious-url-classifier / src /export_js.py
DaveyD347's picture
Add malicious URL classifier
84f95cd verified
Raw History Blame Contribute Delete
1.6 kB
"""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()