Spaces:
Sleeping
Sleeping
Download app.py from NickyBZhangLab/fetosafe: direct link, hf CLI and curl.
- Browser
- Download file 2.05 kB
-
https://huggingface.co/spaces/NickyBZhangLab/fetosafe/resolve/main/app.py
- Command line
-
hf download hf://spaces/NickyBZhangLab/fetosafe/app.py
-
curl -L -o app.py https://huggingface.co/spaces/NickyBZhangLab/fetosafe/resolve/main/app.py
2.05 kB
| 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) | |
| def index(): | |
| return render_template("index.html") | |
| 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) | |