File size: 2,048 Bytes
9777d46
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
import pickle
import warnings

import numpy as np
from flask import Flask, jsonify, render_template, request
from rdkit import Chem, RDLogger
from rdkit.Chem import AllChem

warnings.filterwarnings("ignore")
RDLogger.DisableLog("rdApp.*")

HERE = os.path.dirname(os.path.abspath(__file__))
PROJECT_ROOT = os.path.dirname(HERE)
_LOCAL = os.path.join(HERE, "xgb_model.pkl")
_SIBLING = os.path.join(PROJECT_ROOT, "Placenta Drug Permeability", "xgb_model.pkl")
MODEL_PATH = _LOCAL if os.path.exists(_LOCAL) else _SIBLING

with open(MODEL_PATH, "rb") as f:
    MODEL = pickle.load(f)

N_BITS = 2048
RADIUS = 2
DEFAULT_THRESHOLD = 0.5

app = Flask(__name__)


def smiles_to_fingerprint(smiles: str):
    mol = Chem.MolFromSmiles(smiles)
    if mol is None:
        return None
    fp = AllChem.GetMorganFingerprintAsBitVect(mol, RADIUS, nBits=N_BITS)
    return np.array(fp, dtype=np.float32).reshape(1, -1)


@app.route("/")
def index():
    return render_template("index.html")


@app.route("/predict", methods=["POST"])
def predict():
    data = request.get_json(silent=True) or request.form
    smiles = (data.get("smiles") or "").strip()
    try:
        threshold = float(data.get("threshold", DEFAULT_THRESHOLD))
    except (TypeError, ValueError):
        threshold = DEFAULT_THRESHOLD

    if not smiles:
        return jsonify(error="Please enter a SMILES string."), 400

    fp = smiles_to_fingerprint(smiles)
    if fp is None:
        return jsonify(error=f"Invalid SMILES: {smiles!r}"), 400

    proba = MODEL.predict_proba(fp)[0]
    p_cross = float(proba[1])
    p_nocross = float(proba[0])
    label = "Crosses placenta" if p_cross >= threshold else "Does not cross"

    return jsonify(
        smiles=smiles,
        canonical_smiles=Chem.MolToSmiles(Chem.MolFromSmiles(smiles)),
        probability_cross=p_cross,
        probability_nocross=p_nocross,
        threshold=threshold,
        prediction=label,
    )


if __name__ == "__main__":
    app.run(host="0.0.0.0", port=int(os.environ.get("PORT", 5000)), debug=False)