import os import urllib.parse import warnings import numpy as np import requests import torch import torch.nn as nn from flask import Flask, jsonify, render_template, request from rdkit import Chem, RDLogger from rdkit.Chem import AllChem from transformers import AutoModel, AutoTokenizer warnings.filterwarnings("ignore") RDLogger.DisableLog("rdApp.*") HERE = os.path.dirname(os.path.abspath(__file__)) # Prefer the snapshot baked into the Docker image; fall back to the Hub name # for local dev (cluster has the model already cached under HF_HOME). _LOCAL_CHEMBERTA = os.path.join(HERE, "chemberta_local") MODEL_NAME = _LOCAL_CHEMBERTA if os.path.isdir(_LOCAL_CHEMBERTA) else "DeepChem/ChemBERTa-77M-MLM" TRANSFORMER_PT = os.path.join(HERE, "models", "transformer.pt") DISCRIMINATOR_PT = os.path.join(HERE, "models", "discriminator.pt") ACTIVE_FPS_NPY = os.path.join(HERE, "models", "active_fps.npy") MAX_SEQ_LEN = 512 DEFAULT_THRESHOLD = 0.5 FP_RADIUS = 2 FP_NBITS = 2048 PUBCHEM_TIMEOUT = 6 MAX_BATCH = 200 class Discriminator(nn.Module): """Vendored from tnik_experiment/models/ganbert.py — keeps the deploy self-contained.""" def __init__(self, input_size=384, hidden_sizes=(384,), num_labels=2, dropout_rate=0.5): super().__init__() self.input_dropout = nn.Dropout(p=dropout_rate) layers = [] hs = [input_size] + list(hidden_sizes) for i in range(len(hs) - 1): layers += [ nn.Linear(hs[i], hs[i + 1]), nn.LeakyReLU(0.2, inplace=True), nn.Dropout(dropout_rate), ] self.layers = nn.Sequential(*layers) self.logit = nn.Linear(hs[-1], num_labels + 1) # +1 for the GAN "fake" class def forward(self, rep): rep = self.input_dropout(rep) h = self.layers(rep) return self.logit(h) device = torch.device("cpu") print("[boot] loading tokenizer + transformer …", flush=True) tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME) transformer = AutoModel.from_pretrained(MODEL_NAME, use_safetensors=True).to(device) transformer.load_state_dict( torch.load(TRANSFORMER_PT, map_location=device, weights_only=True) ) transformer.eval() print("[boot] loading discriminator …", flush=True) discriminator = Discriminator().to(device) discriminator.load_state_dict( torch.load(DISCRIMINATOR_PT, map_location=device, weights_only=True) ) discriminator.eval() print("[boot] loading train-active fingerprints …", flush=True) ACTIVE_FPS = np.load(ACTIVE_FPS_NPY).astype(np.uint8) ACTIVE_POPCOUNT = ACTIVE_FPS.sum(axis=1) print(f"[boot] {ACTIVE_FPS.shape[0]} active fingerprints loaded.", flush=True) print("[boot] ready.", flush=True) def nearest_active_tanimoto(mol): """Return max Tanimoto similarity between query mol and any train active.""" fp = AllChem.GetMorganFingerprintAsBitVect(mol, FP_RADIUS, nBits=FP_NBITS) q = np.array(fp, dtype=np.uint8) intersect = ACTIVE_FPS @ q union = ACTIVE_POPCOUNT + q.sum() - intersect tanimoto = np.where(union > 0, intersect / union, 0.0) idx = int(tanimoto.argmax()) return float(tanimoto[idx]), idx def applicability_verdict(t): if t >= 0.6: return "in-distribution", "Score is reliable — query is similar to known TNIK actives." if t >= 0.4: return "borderline", "Query is moderately similar to train actives — interpret with caution." return "out-of-distribution", "Query is unlike anything the model trained on — score may be unreliable." def _pubchem_name_to_smiles(name: str): """Resolve a compound name via PubChem PUG REST. Returns SMILES or None.""" enc = urllib.parse.quote(name, safe="") # PubChem's PUG REST accepts legacy names in the URL path but returns the # SMILES under the `SMILES` key as of 2025. Try modern then legacy names. for path_prop in ("SMILES", "IsomericSMILES", "CanonicalSMILES"): url = f"https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/name/{enc}/property/{path_prop}/JSON" try: r = requests.get(url, timeout=PUBCHEM_TIMEOUT) if r.status_code != 200: continue props = r.json().get("PropertyTable", {}).get("Properties", []) if not props: continue for k in ("SMILES", "IsomericSMILES", "CanonicalSMILES"): if props[0].get(k): return props[0][k] except requests.RequestException: continue return None def resolve_to_mol(query: str): """Return (mol, resolved_smiles, source, error). Tries SMILES first, then PubChem name lookup.""" q = query.strip() if not q: return None, None, None, "Empty input" mol = Chem.MolFromSmiles(q) if mol is not None: return mol, q, "smiles", None smi = _pubchem_name_to_smiles(q) if smi is None: return None, None, None, f"Could not parse as SMILES or find compound named {q!r} on PubChem" mol = Chem.MolFromSmiles(smi) if mol is None: return None, None, None, f"PubChem returned an unparseable SMILES for {q!r}" return mol, smi, "pubchem", None def _score_one(query: str, threshold: float): mol, resolved_smi, source, err = resolve_to_mol(query) if err: return {"input": query, "error": err} canonical = Chem.MolToSmiles(mol) p = predict(canonical) nn_t, _ = nearest_active_tanimoto(mol) ad_class, ad_message = applicability_verdict(nn_t) label = "Likely active on TNIK" if p["p_active"] >= threshold else "Likely inactive" return { "input": query, "source": source, "resolved_smiles": resolved_smi, "canonical_smiles": canonical, "probability_active": p["p_active"], "probability_inactive": p["p_inactive"], "threshold": threshold, "prediction": label, "nearest_active_tanimoto": nn_t, "applicability": ad_class, "applicability_message": ad_message, } def _encode(smiles: str) -> torch.Tensor: enc = tokenizer( smiles, max_length=MAX_SEQ_LEN, padding="max_length", truncation=True, return_tensors="pt", ) enc = {k: v.to(device) for k, v in enc.items()} out = transformer(**enc, return_dict=True) rep = out.pooler_output if rep is None: rep = out.last_hidden_state[:, 0, :] return rep @torch.no_grad() def predict(smiles: str): rep = _encode(smiles) logits = discriminator(rep) real = logits[:, 0:2] # drop the +1 fake class probs = torch.softmax(real, dim=-1)[0].tolist() return {"p_inactive": probs[0], "p_active": probs[1]} app = Flask(__name__) @app.route("/") def index(): return render_template("index.html") def _parse_threshold(data): try: return float(data.get("threshold", DEFAULT_THRESHOLD)) except (TypeError, ValueError): return DEFAULT_THRESHOLD @app.route("/predict_batch", methods=["POST"]) def predict_batch_route(): data = request.get_json(silent=True) or {} queries = data.get("queries") or [] if isinstance(queries, str): queries = [queries] queries = [q.strip() for q in queries if isinstance(q, str) and q.strip()] if not queries: return jsonify(error="Please enter at least one SMILES or compound name."), 400 if len(queries) > MAX_BATCH: return jsonify(error=f"Batch too large ({len(queries)}). Max {MAX_BATCH}."), 400 threshold = _parse_threshold(data) results = [_score_one(q, threshold) for q in queries] return jsonify(threshold=threshold, results=results) if __name__ == "__main__": app.run(host="0.0.0.0", port=int(os.environ.get("PORT", 7860)), debug=False)