|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | +# |
| 3 | +# Copyright (C) 2024 CERN. |
| 4 | +# |
| 5 | +# ZenodoRDM is free software; you can redistribute it and/or modify |
| 6 | +# it under the terms of the MIT License; see LICENSE file for more details. |
| 7 | +"""Model definitions.""" |
| 8 | + |
| 9 | + |
| 10 | +import json |
| 11 | +import string |
| 12 | + |
| 13 | +import requests |
| 14 | +from bs4 import BeautifulSoup |
| 15 | +from flask import current_app |
| 16 | + |
| 17 | +from .base import MLModel |
| 18 | + |
| 19 | + |
| 20 | +class SpamDetectorScikit(MLModel): |
| 21 | + """Spam detection model based on Sklearn.""" |
| 22 | + |
| 23 | + MODEL_NAME = "sklearn-spam" |
| 24 | + MAX_WORDS = 4000 |
| 25 | + |
| 26 | + def __init__(self, version, **kwargs): |
| 27 | + """Constructor. Makes version required.""" |
| 28 | + super().__init__(version, **kwargs) |
| 29 | + |
| 30 | + def preprocess(self, data): |
| 31 | + """Preprocess data. |
| 32 | +
|
| 33 | + Parse HTML, remove punctuation and truncate to max chars. |
| 34 | + """ |
| 35 | + text = BeautifulSoup(data, "html.parser").get_text() |
| 36 | + trans_table = str.maketrans(string.punctuation, " " * len(string.punctuation)) |
| 37 | + parts = text.translate(trans_table).lower().strip().split(" ") |
| 38 | + if len(parts) >= self.MAX_WORDS: |
| 39 | + parts = parts[: self.MAX_WORDS] |
| 40 | + return " ".join(parts) |
| 41 | + |
| 42 | + def postprocess(self, data): |
| 43 | + """Postprocess data. |
| 44 | +
|
| 45 | + Gives spam and ham probability. |
| 46 | + """ |
| 47 | + result = { |
| 48 | + "spam": data["outputs"][0]["data"][0], |
| 49 | + "ham": data["outputs"][0]["data"][1], |
| 50 | + } |
| 51 | + return result |
| 52 | + |
| 53 | + def _send_request_kubeflow(self, data): |
| 54 | + """Send predict request to Kubeflow.""" |
| 55 | + payload = { |
| 56 | + "inputs": [ |
| 57 | + { |
| 58 | + "name": "input-0", |
| 59 | + "shape": [1], |
| 60 | + "datatype": "BYTES", |
| 61 | + "data": [f"{data}"], |
| 62 | + } |
| 63 | + ] |
| 64 | + } |
| 65 | + model_ref = self.MODEL_NAME + "-" + self.version |
| 66 | + url = current_app.config.get("ML_KUBEFLOW_MODEL_URL").format(model_ref) |
| 67 | + host = current_app.config.get("ML_KUBEFLOW_MODEL_HOST").format(model_ref) |
| 68 | + access_token = current_app.config.get("ML_KUBEFLOW_TOKEN") |
| 69 | + r = requests.post( |
| 70 | + url, |
| 71 | + headers={ |
| 72 | + "Authorization": f"Bearer {access_token}", |
| 73 | + "Content-Type": "application/json", |
| 74 | + "Host": host, |
| 75 | + }, |
| 76 | + json=payload, |
| 77 | + ) |
| 78 | + if r.status_code != 200: |
| 79 | + raise requests.RequestException("Prediction was not successful.", request=r) |
| 80 | + return json.loads(r.text) |
| 81 | + |
| 82 | + def predict(self, data): |
| 83 | + """Get prediction from model.""" |
| 84 | + prediction = self._send_request_kubeflow(data) |
| 85 | + return prediction |
0 commit comments