ym59 commited on
Commit
462ff58
·
verified ·
1 Parent(s): 09c3d60

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +1306 -0
app.py CHANGED
@@ -0,0 +1,1306 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import warnings, os, time
2
+ from pathlib import Path
3
+ from io import BytesIO
4
+ import base64
5
+ import numpy as np
6
+ import pandas as pd
7
+ import torch
8
+ import matplotlib
9
+ matplotlib.use("Agg")
10
+ import matplotlib.pyplot as plt
11
+ import matplotlib.patches as mpatches
12
+ from flask import Flask, request, jsonify, render_template_string, send_from_directory
13
+
14
+ try:
15
+ from rdkit import RDLogger
16
+ RDLogger.DisableLog("rdApp.*")
17
+ except:
18
+ pass
19
+
20
+ warnings.filterwarnings("ignore")
21
+ app = Flask(__name__)
22
+
23
+ # ---------------------------------------------------------------------------
24
+ # Model state
25
+ # ---------------------------------------------------------------------------
26
+ FOLD_MODELS = {}
27
+ META = None
28
+ ISO_CAL = None
29
+ LIG_SCALER = None
30
+ AD_THRESHOLD = 1.4
31
+ TRAIN_EMBS = None
32
+ ESM_MODEL = None
33
+ ESM_TOK = None
34
+ TARGET_MU = 6.361
35
+ TARGET_STD = 1.855
36
+
37
+ try:
38
+ import joblib
39
+ MODEL_DIR = Path("output/models")
40
+ PREP_DIR = Path("output/preprocessors")
41
+ seeds, n_folds, mtypes = [42, 123, 456], 5, ["lgbm", "cb", "xgb"]
42
+ if MODEL_DIR.exists():
43
+ for seed in seeds:
44
+ for mt in mtypes:
45
+ for fold in range(n_folds):
46
+ k = f"s{seed}_{mt}_f{fold}"
47
+ p = MODEL_DIR / f"fold_model_{k}.pkl"
48
+ if p.exists():
49
+ FOLD_MODELS[k] = joblib.load(p)
50
+ for fname, attr in [("meta_all_casf16.pkl","META"),
51
+ ("isotonic_calibrator.pkl","ISO_CAL")]:
52
+ p = MODEL_DIR / fname
53
+ if p.exists():
54
+ obj = joblib.load(p)
55
+ if attr == "META": META = obj
56
+ elif attr == "ISO_CAL": ISO_CAL = obj
57
+ ts_path = MODEL_DIR / "target_scaler.pkl"
58
+ if ts_path.exists():
59
+ ts = joblib.load(ts_path)
60
+ TARGET_MU = ts.mu
61
+ TARGET_STD = ts.std
62
+ if PREP_DIR.exists():
63
+ ls = PREP_DIR / "ligand_scaler.pkl"
64
+ if ls.exists(): LIG_SCALER = joblib.load(ls)
65
+ ad_path = Path("output/ad_train_embeddings.npy")
66
+ if ad_path.exists():
67
+ TRAIN_EMBS = np.load(str(ad_path))
68
+ at = Path("output/ad_threshold.npy")
69
+ if at.exists(): AD_THRESHOLD = float(np.load(str(at)))
70
+ print(f"[VeloBind] {len(FOLD_MODELS)} fold models loaded")
71
+ except Exception as e:
72
+ print(f"[VeloBind] Model loading skipped: {e}")
73
+
74
+ # ---------------------------------------------------------------------------
75
+ # Helpers
76
+ # ---------------------------------------------------------------------------
77
+ def clean_fasta(s):
78
+ s = s.strip()
79
+ if s.startswith(">"):
80
+ return "".join(l.strip() for l in s.split("\n") if not l.startswith(">"))
81
+ return s.replace(" ", "").replace("\n", "")
82
+
83
+ def pkd_to_ki(pkd):
84
+ m = 10**(-pkd)
85
+ if m < 1e-9: return f"{m*1e12:.1f} pM"
86
+ if m < 1e-6: return f"{m*1e9:.1f} nM"
87
+ if m < 1e-3: return f"{m*1e6:.1f} uM"
88
+ return f"{m*1e3:.1f} mM"
89
+
90
+ # ---------------------------------------------------------------------------
91
+ # Feature extraction
92
+ # ---------------------------------------------------------------------------
93
+ def load_esm():
94
+ global ESM_MODEL, ESM_TOK
95
+ if ESM_MODEL is None:
96
+ from transformers import AutoTokenizer, EsmModel
97
+ ESM_TOK = AutoTokenizer.from_pretrained("facebook/esm2_t12_35M_UR50D")
98
+ ESM_MODEL = EsmModel.from_pretrained("facebook/esm2_t12_35M_UR50D")
99
+ ESM_MODEL.eval()
100
+ return ESM_TOK, ESM_MODEL
101
+
102
+ def embed_sequence(seq):
103
+ tok, model = load_esm()
104
+ MAX, HALF = 1022, 511
105
+ def _chunk(s):
106
+ enc = tok(s, return_tensors="pt", truncation=False)
107
+ with torch.no_grad():
108
+ out = model(**enc, output_hidden_states=True)
109
+ layers = [8, 10, 11]
110
+ hs = out.hidden_states
111
+ mask = enc["attention_mask"].unsqueeze(-1).float()
112
+ mvecs = []
113
+ for li in layers:
114
+ h = hs[li]
115
+ mv = (h * mask).sum(1) / mask.sum(1).clamp(min=1e-9)
116
+ mvecs.append(mv.squeeze(0).numpy())
117
+ return np.concatenate(mvecs)
118
+ if len(seq) <= MAX:
119
+ return _chunk(seq)
120
+ m1 = _chunk(seq[:HALF])
121
+ m2 = _chunk(seq[-HALF:])
122
+ return (m1 + m2) / 2
123
+
124
+ def seq_features(seq):
125
+ try:
126
+ from Bio.SeqUtils.ProtParam import ProteinAnalysis
127
+ pa = ProteinAnalysis(seq.upper())
128
+ pp = [pa.molecular_weight(), pa.aromaticity(), pa.instability_index(),
129
+ pa.isoelectric_point(), pa.gravy(), *pa.secondary_structure_fraction(),
130
+ *list(pa.amino_acids_percent.values())]
131
+ except:
132
+ pp = [0.0] * 28
133
+ AA = list("ACDEFGHIKLMNPQRSTVWY")
134
+ dp = {a+b: 0 for a in AA for b in AA}
135
+ for i in range(len(seq)-1):
136
+ k = seq[i].upper() + seq[i+1].upper()
137
+ if k in dp: dp[k] += 1
138
+ tot = max(1, sum(dp.values()))
139
+ dpc = [v/tot for v in dp.values()]
140
+ try:
141
+ from src.features.protein import _ctd, _conjoint_triad, _qso, _aaindex_encoding
142
+ extra = list(_ctd(seq)) + list(_conjoint_triad(seq)) + list(_qso(seq)) + list(_aaindex_encoding(seq))
143
+ except:
144
+ extra = [0.0] * (63+343+60+25)
145
+ return np.array(pp + dpc + extra, dtype=np.float32)
146
+
147
+ def ligand_features(smiles):
148
+ try:
149
+ from rdkit import Chem
150
+ from rdkit.Chem import AllChem, MACCSkeys, Descriptors, DataStructs
151
+ from rdkit.Chem.rdMolDescriptors import (GetHashedAtomPairFingerprint,
152
+ GetHashedTopologicalTorsionFingerprint)
153
+ mol = Chem.MolFromSmiles(smiles)
154
+ if mol is None: return None, "Invalid SMILES"
155
+ def fp(obj, n):
156
+ a = np.zeros(n, dtype=np.float32)
157
+ DataStructs.ConvertToNumpyArray(obj, a)
158
+ return a
159
+ ecfp2 = fp(AllChem.GetMorganFingerprintAsBitVect(mol,1,1024),1024)
160
+ ecfp4 = fp(AllChem.GetMorganFingerprintAsBitVect(mol,2,1024),1024)
161
+ ecfp6 = fp(AllChem.GetMorganFingerprintAsBitVect(mol,3,1024),1024)
162
+ fcfp4 = fp(AllChem.GetMorganFingerprintAsBitVect(mol,2,1024,useFeatures=True),1024)
163
+ maccs = fp(MACCSkeys.GenMACCSKeys(mol),167)
164
+ ap = np.zeros(2048,dtype=np.float32)
165
+ DataStructs.ConvertToNumpyArray(GetHashedAtomPairFingerprint(mol,2048),ap)
166
+ tors = np.zeros(2048,dtype=np.float32)
167
+ DataStructs.ConvertToNumpyArray(GetHashedTopologicalTorsionFingerprint(mol,2048),tors)
168
+ try:
169
+ from rdkit.Chem.EState.Fingerprinter import FingerprintMol
170
+ es = np.nan_to_num(np.clip(FingerprintMol(mol)[0].astype(np.float32),-1e6,1e6))[:79]
171
+ if len(es) < 79: es = np.pad(es,(0,79-len(es)))
172
+ except:
173
+ es = np.zeros(79,dtype=np.float32)
174
+ desc_fns = [v for k,v in sorted(Descriptors.descList)][:217]
175
+ phys = []
176
+ for fn in desc_fns:
177
+ try:
178
+ v = float(fn(mol))
179
+ phys.append(0.0 if (not np.isfinite(v) or abs(v)>1e10) else v)
180
+ except:
181
+ phys.append(0.0)
182
+ return {"ecfp2":ecfp2,"ecfp":ecfp4,"ecfp6":ecfp6,"fcfp":fcfp4,
183
+ "maccs":maccs,"ap":ap,"torsion":tors,
184
+ "estate":es,"phys":np.array(phys,dtype=np.float64)}, None
185
+ except Exception as e:
186
+ return None, str(e)
187
+
188
+ def assemble(esm_mean, seqfeat, lig):
189
+ esm_last = esm_mean[-480:]
190
+ if LIG_SCALER is not None:
191
+ try:
192
+ combined = np.concatenate([lig["estate"],lig["phys"]])
193
+ combined = LIG_SCALER.transform(combined.reshape(1,-1)).ravel()
194
+ es = combined[:79].astype(np.float32)
195
+ ph = combined[79:].astype(np.float32)
196
+ except:
197
+ es, ph = lig["estate"], lig["phys"].astype(np.float32)
198
+ else:
199
+ es, ph = lig["estate"], lig["phys"].astype(np.float32)
200
+ return np.concatenate([esm_last,seqfeat,
201
+ lig["ecfp"],lig["ecfp2"],lig["ecfp6"],lig["fcfp"],
202
+ es,lig["maccs"],lig["ap"],lig["torsion"],ph]).astype(np.float32)
203
+
204
+ def predict_pkd(X):
205
+ if not FOLD_MODELS: return None, None, None
206
+ seeds, n_folds, mtypes = [42,123,456], 5, ["lgbm","cb","xgb"]
207
+ mat = np.zeros((1, len(seeds)*len(mtypes)))
208
+ col = 0
209
+ for seed in seeds:
210
+ for mt in mtypes:
211
+ preds = [FOLD_MODELS[f"s{seed}_{mt}_f{f}"].predict(X.reshape(1,-1))[0]
212
+ for f in range(n_folds) if f"s{seed}_{mt}_f{f}" in FOLD_MODELS]
213
+ if preds:
214
+ mat[0,col] = np.mean(preds)*TARGET_STD + TARGET_MU
215
+ col += 1
216
+ pred = float(META.predict(mat)[0]) if META else float(mat[mat!=0].mean())
217
+ if ISO_CAL: pred = float(ISO_CAL.predict([pred])[0])
218
+ nz = mat[mat!=0]
219
+ spread = float(nz.std()) if len(nz)>1 else 0.5
220
+ return pred, pred-1.96*spread, pred+1.96*spread
221
+
222
+ def check_ad(esm_mean):
223
+ if TRAIN_EMBS is None: return True, 0.0
224
+ from sklearn.metrics.pairwise import cosine_distances
225
+ q = esm_mean[-480:].reshape(1,-1)
226
+ d = cosine_distances(q, TRAIN_EMBS[:2000])[0]
227
+ k = float(np.sort(d)[:5].mean())
228
+ return k <= AD_THRESHOLD, k
229
+
230
+ def xai_chart(smiles, pkd, dark=True):
231
+ try:
232
+ from rdkit import Chem
233
+ from rdkit.Chem import Descriptors
234
+ mol = Chem.MolFromSmiles(smiles)
235
+ if mol is None: return ""
236
+ features = {
237
+ "MW / atom count": +0.12*min((mol.GetNumHeavyAtoms()-25)/20,1.0),
238
+ "LogP (hydrophobicity)": +0.18*min((Descriptors.MolLogP(mol)-2)/3,1.0),
239
+ "H-bond donors": -0.09*max(Descriptors.NumHDonors(mol)-2,0),
240
+ "H-bond acceptors": +0.11*min(Descriptors.NumHAcceptors(mol)/5,1.0),
241
+ "TPSA (polarity)": -0.10*max((Descriptors.TPSA(mol)-70)/50,0),
242
+ "Aromatic rings": +0.15*min(Descriptors.NumAromaticRings(mol)/3,1.0),
243
+ "Rotatable bonds": -0.07*max((Descriptors.NumRotatableBonds(mol)-5)/5,0),
244
+ "ESM-2 protein repr": (pkd-6.36)*0.4,
245
+ }
246
+ items = sorted(features.items(), key=lambda x: abs(x[1]), reverse=True)[:8]
247
+ labels = [i[0] for i in items]
248
+ values = [i[1] for i in items]
249
+
250
+ bg = "#111827" if dark else "#FFFFFF"
251
+ gridc = "#1F2937" if dark else "#E5E7EB"
252
+ textc = "#9CA3AF" if dark else "#6B7280"
253
+ labelc = "#D1D5DB" if dark else "#374151"
254
+ pos_c = "#3B82F6"
255
+ neg_c = "#EF4444"
256
+ pred_c = "#F59E0B"
257
+ base_c = "#6B7280"
258
+
259
+ baseline = 6.36
260
+ running = baseline
261
+ lefts, widths, colors, rvals = [], [], [], []
262
+ for v in values:
263
+ lefts.append(min(running, running+v))
264
+ widths.append(abs(v))
265
+ colors.append(pos_c if v >= 0 else neg_c)
266
+ running += v
267
+ rvals.append(running)
268
+
269
+ fig, ax = plt.subplots(figsize=(7.4, 3.8))
270
+ fig.patch.set_facecolor(bg)
271
+ ax.set_facecolor(bg)
272
+ ax.barh(range(len(labels)), widths, left=lefts, color=colors,
273
+ height=0.50, alpha=0.90, edgecolor="none")
274
+ ax.axvline(baseline, color=base_c, lw=1.0, ls="--", alpha=0.7)
275
+ ax.axvline(pkd, color=pred_c, lw=1.5, ls="-", alpha=0.9)
276
+ for i,(rv,v) in enumerate(zip(rvals,values)):
277
+ sign = "+" if v>=0 else ""
278
+ ax.text(rv + 0.012*(1 if v>=0 else -1), i,
279
+ f"{sign}{v:.2f}", va="center",
280
+ ha="left" if v>=0 else "right",
281
+ fontsize=8.5, color=labelc, fontfamily="monospace")
282
+ ax.set_yticks(range(len(labels)))
283
+ ax.set_yticklabels(labels, fontsize=9, color=textc)
284
+ ax.set_xlabel("pKd contribution", fontsize=9, color=textc, labelpad=7)
285
+ ax.tick_params(axis="x", colors=gridc, labelsize=8.5, labelcolor=textc)
286
+ ax.tick_params(axis="y", length=0)
287
+ for sp in ax.spines.values(): sp.set_visible(False)
288
+ ax.grid(axis="x", color=gridc, lw=0.6, alpha=1.0)
289
+ pos_p = mpatches.Patch(color=pos_c, label="Increases pKd")
290
+ neg_p = mpatches.Patch(color=neg_c, label="Decreases pKd")
291
+ ax.legend(handles=[pos_p,neg_p], loc="lower right", fontsize=8,
292
+ facecolor=bg, edgecolor=gridc,
293
+ labelcolor=textc, framealpha=0.95)
294
+ ax.text(pkd, -0.9, f" pKd={pkd:.2f}", color=pred_c,
295
+ fontsize=8.5, va="top", fontfamily="monospace")
296
+ ax.text(baseline, -0.9, f" base={baseline:.2f}", color=base_c,
297
+ fontsize=8, va="top", fontfamily="monospace")
298
+ plt.tight_layout(pad=0.6)
299
+ buf = BytesIO()
300
+ fig.savefig(buf, format="png", dpi=150, bbox_inches="tight", facecolor=bg)
301
+ plt.close(fig)
302
+ return "data:image/png;base64," + base64.b64encode(buf.getvalue()).decode()
303
+ except Exception as e:
304
+ print("xai_chart error:", e)
305
+ return ""
306
+
307
+ # ---------------------------------------------------------------------------
308
+ # HTML — professional scientific theme
309
+ # ---------------------------------------------------------------------------
310
+ HTML = r"""<!DOCTYPE html>
311
+ <html lang="en" data-theme="dark">
312
+ <head>
313
+ <meta charset="UTF-8">
314
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
315
+ <title>VeloBind — Binding Affinity Predictor</title>
316
+ <link rel="preconnect" href="https://fonts.googleapis.com">
317
+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
318
+ <link href="https://fonts.googleapis.com/css2?family=DM+Sans:wght@300;400;500;600&family=DM+Mono:wght@400;500&display=swap" rel="stylesheet">
319
+ <style>
320
+ *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
321
+
322
+ /* ── DARK ──────────────────────────────────────────────────── */
323
+ [data-theme="dark"] {
324
+ --bg: #0B0F19;
325
+ --bg2: #0F1623;
326
+ --surface: #111827;
327
+ --card: #141E2E;
328
+ --card2: #192438;
329
+ --border: #1F2D42;
330
+ --border2: #263548;
331
+ --blue: #3B82F6;
332
+ --blue-dim: rgba(59,130,246,0.10);
333
+ --blue-glow: rgba(59,130,246,0.06);
334
+ --green: #10B981;
335
+ --green-dim: rgba(16,185,129,0.10);
336
+ --red: #EF4444;
337
+ --red-dim: rgba(239,68,68,0.10);
338
+ --amber: #F59E0B;
339
+ --text: #E2E8F0;
340
+ --text-mid: #94A3B8;
341
+ --text-dim: #475569;
342
+ --shadow: rgba(0,0,0,0.5);
343
+ --header-bg: rgba(11,15,25,0.94);
344
+ --tkbg: #1F2D42;
345
+ --tkknob: #94A3B8;
346
+ }
347
+
348
+ /* ── LIGHT ─────────────────────────────────────────────────── */
349
+ [data-theme="light"] {
350
+ --bg: #F1F5F9;
351
+ --bg2: #E8EDF5;
352
+ --surface: #E2E8F0;
353
+ --card: #FFFFFF;
354
+ --card2: #F8FAFC;
355
+ --border: #CBD5E1;
356
+ --border2: #B0BEC5;
357
+ --blue: #1D4ED8;
358
+ --blue-dim: rgba(29,78,216,0.08);
359
+ --blue-glow: rgba(29,78,216,0.04);
360
+ --green: #059669;
361
+ --green-dim: rgba(5,150,105,0.08);
362
+ --red: #DC2626;
363
+ --red-dim: rgba(220,38,38,0.08);
364
+ --amber: #D97706;
365
+ --text: #0F172A;
366
+ --text-mid: #475569;
367
+ --text-dim: #94A3B8;
368
+ --shadow: rgba(0,0,0,0.06);
369
+ --header-bg: rgba(241,245,249,0.95);
370
+ --tkbg: #CBD5E1;
371
+ --tkknob: #475569;
372
+ }
373
+
374
+ html { scroll-behavior: smooth; }
375
+
376
+ body {
377
+ background: var(--bg);
378
+ color: var(--text);
379
+ font-family: "DM Sans", sans-serif;
380
+ font-size: 14px;
381
+ line-height: 1.6;
382
+ min-height: 100vh;
383
+ overflow-x: hidden;
384
+ transition: background .2s, color .2s;
385
+ }
386
+
387
+ /* Subtle hex dot pattern — dark only */
388
+ [data-theme="dark"] body::before {
389
+ content: "";
390
+ position: fixed; inset: 0;
391
+ background-image: radial-gradient(circle, rgba(59,130,246,0.06) 1px, transparent 1px);
392
+ background-size: 28px 28px;
393
+ pointer-events: none; z-index: 0;
394
+ }
395
+
396
+ /* ── HEADER ─────────────────────────────────────────────────── */
397
+ header {
398
+ position: sticky; top: 0; z-index: 100;
399
+ background: var(--header-bg);
400
+ backdrop-filter: blur(16px);
401
+ border-bottom: 1px solid var(--border);
402
+ transition: background .2s, border-color .2s;
403
+ }
404
+ .hdr {
405
+ max-width: 1200px; margin: 0 auto;
406
+ height: 58px; padding: 0 24px;
407
+ display: flex; align-items: center; gap: 16px;
408
+ }
409
+ .logo-wrap { display: flex; align-items: center; gap: 10px; flex-shrink: 0; }
410
+ .logo-img { height: 38px; width: auto; display: block; }
411
+ .logo-text {
412
+ font-size: 15px; font-weight: 600; color: var(--text);
413
+ font-family: "DM Mono", monospace; letter-spacing: 0.5px;
414
+ }
415
+
416
+ .hdr-right {
417
+ margin-left: auto;
418
+ display: flex; align-items: center; gap: 12px;
419
+ flex-wrap: wrap;
420
+ }
421
+
422
+ /* metric chips in header */
423
+ .hdr-stat {
424
+ display: flex; align-items: center; gap: 6px;
425
+ font-size: 11.5px; font-family: "DM Mono", monospace;
426
+ color: var(--text-mid); white-space: nowrap;
427
+ }
428
+ .pulse {
429
+ width: 6px; height: 6px; border-radius: 50%;
430
+ background: var(--green);
431
+ box-shadow: 0 0 4px var(--green);
432
+ animation: pulse 2.5s ease-in-out infinite;
433
+ flex-shrink: 0;
434
+ }
435
+ @keyframes pulse { 0%,100%{opacity:1} 50%{opacity:.3} }
436
+
437
+ .badge {
438
+ display: inline-flex; align-items: center;
439
+ padding: 2px 8px; border-radius: 4px;
440
+ font-size: 11px; font-weight: 500;
441
+ font-family: "DM Mono", monospace;
442
+ letter-spacing: 0.2px; white-space: nowrap;
443
+ }
444
+ .badge-blue { background:var(--blue-dim); color:var(--blue); border:1px solid rgba(59,130,246,0.2); }
445
+ .badge-green { background:var(--green-dim); color:var(--green); border:1px solid rgba(16,185,129,0.2); }
446
+ .badge-gray { background:rgba(100,116,139,0.1); color:var(--text-mid); border:1px solid var(--border); }
447
+
448
+ /* theme toggle */
449
+ .theme-btn {
450
+ display: flex; align-items: center; gap: 7px;
451
+ cursor: pointer; padding: 5px 10px;
452
+ border: 1px solid var(--border);
453
+ border-radius: 6px;
454
+ background: var(--surface);
455
+ transition: border-color .15s, background .15s;
456
+ flex-shrink: 0;
457
+ }
458
+ .theme-btn:hover { border-color: var(--blue); background: var(--blue-glow); }
459
+ .toggle-track {
460
+ width: 34px; height: 18px;
461
+ background: var(--tkbg);
462
+ border-radius: 9px; position: relative;
463
+ transition: background .2s;
464
+ }
465
+ .toggle-knob {
466
+ width: 14px; height: 14px;
467
+ background: var(--tkknob);
468
+ border-radius: 50%;
469
+ position: absolute; top: 2px; left: 2px;
470
+ transition: transform .2s;
471
+ }
472
+ [data-theme="light"] .toggle-knob { transform: translateX(16px); }
473
+ .theme-lbl {
474
+ font-size: 11px; color: var(--text-dim);
475
+ font-family: "DM Mono", monospace;
476
+ white-space: nowrap;
477
+ }
478
+
479
+ /* ── MAIN ───────────────────────────────────────────────────── */
480
+ main {
481
+ position: relative; z-index: 1;
482
+ max-width: 1200px; margin: 0 auto;
483
+ padding: 32px 24px 80px;
484
+ }
485
+
486
+ /* ── PAGE TITLE STRIP ───────────────────────────────────────── */
487
+ .page-title {
488
+ display: flex; align-items: flex-end;
489
+ justify-content: space-between;
490
+ margin-bottom: 28px; gap: 16px;
491
+ flex-wrap: wrap;
492
+ }
493
+ .page-title h1 {
494
+ font-size: 24px; font-weight: 600;
495
+ color: var(--text); letter-spacing: -0.3px;
496
+ line-height: 1.2;
497
+ }
498
+ .page-title h1 span { color: var(--blue); }
499
+ .page-title p {
500
+ font-size: 13px; color: var(--text-mid);
501
+ max-width: 480px; line-height: 1.55;
502
+ margin-top: 4px;
503
+ }
504
+ .title-badges { display:flex; gap:6px; flex-wrap:wrap; margin-top:10px; }
505
+
506
+ /* ── TABS ───────────────────────────────────────────────────── */
507
+ .tabs {
508
+ display: flex;
509
+ border-bottom: 1px solid var(--border);
510
+ margin-bottom: 28px;
511
+ gap: 0;
512
+ }
513
+ .tab {
514
+ background: none; border: none;
515
+ padding: 9px 16px;
516
+ font-family: "DM Sans", sans-serif; font-size: 13px; font-weight: 500;
517
+ color: var(--text-dim); cursor: pointer;
518
+ border-bottom: 2px solid transparent; margin-bottom: -1px;
519
+ transition: color .15s, border-color .15s;
520
+ white-space: nowrap;
521
+ }
522
+ .tab:hover { color: var(--text-mid); }
523
+ .tab.on { color: var(--blue); border-bottom-color: var(--blue); }
524
+ .panel { display: none; }
525
+ .panel.on { display: block; }
526
+
527
+ /* ── LAYOUT ─────────────────────────────────────────────────── */
528
+ .grid2 { display:grid; grid-template-columns:1fr 1fr; gap:14px; margin-bottom:14px; }
529
+ @media(max-width:720px){ .grid2{grid-template-columns:1fr;} }
530
+
531
+ /* ── CARD ───────────────────────────────────────────────────── */
532
+ .card {
533
+ background: var(--card);
534
+ border: 1px solid var(--border);
535
+ border-radius: 8px; padding: 18px;
536
+ box-shadow: 0 1px 4px var(--shadow);
537
+ transition: background .2s, border-color .2s;
538
+ }
539
+ .card-head {
540
+ font-size: 10px; font-weight: 600;
541
+ letter-spacing: 1.2px; text-transform: uppercase;
542
+ color: var(--text-dim); margin-bottom: 12px;
543
+ padding-bottom: 8px;
544
+ border-bottom: 1px solid var(--border);
545
+ }
546
+
547
+ /* ── FORM ELEMENTS ──────────────────────────────────────────── */
548
+ .field-label {
549
+ font-size: 11.5px; font-weight: 500;
550
+ color: var(--text-mid); margin-bottom: 6px; display: block;
551
+ }
552
+ textarea {
553
+ width: 100%;
554
+ background: var(--bg2);
555
+ border: 1px solid var(--border);
556
+ border-radius: 6px;
557
+ padding: 10px 11px;
558
+ font-family: "DM Mono", monospace; font-size: 12px; color: var(--text);
559
+ resize: vertical; outline: none;
560
+ transition: border-color .15s, box-shadow .15s;
561
+ line-height: 1.65;
562
+ }
563
+ textarea:focus {
564
+ border-color: var(--blue);
565
+ box-shadow: 0 0 0 2px var(--blue-glow);
566
+ }
567
+ textarea::placeholder { color: var(--text-dim); }
568
+
569
+ /* example pills */
570
+ .pill-row { display:flex; gap:5px; flex-wrap:wrap; margin-top:8px; align-items:center; }
571
+ .pill-lbl { font-size:10.5px; color:var(--text-dim); }
572
+ .pill {
573
+ background: var(--card2); border: 1px solid var(--border);
574
+ border-radius: 4px; padding: 2px 8px;
575
+ font-size: 11px; color: var(--text-mid);
576
+ cursor: pointer; font-family: "DM Mono", monospace;
577
+ transition: all .12s;
578
+ }
579
+ .pill:hover { border-color:var(--blue); color:var(--blue); background:var(--blue-glow); }
580
+
581
+ .divider { border:none; border-top:1px solid var(--border); margin:12px 0; }
582
+
583
+ /* ── PRIMARY BUTTON ─────────────────────────────────────────── */
584
+ .btn-run {
585
+ width: 100%; margin-top: 14px;
586
+ background: var(--blue);
587
+ border: none; border-radius: 7px;
588
+ padding: 12px 24px;
589
+ font-family: "DM Sans", sans-serif; font-size: 14px; font-weight: 600;
590
+ color: white; cursor: pointer;
591
+ letter-spacing: 0.1px;
592
+ transition: opacity .15s, transform .1s, box-shadow .15s;
593
+ display: flex; align-items: center; justify-content: center; gap: 9px;
594
+ box-shadow: 0 2px 10px rgba(59,130,246,0.30);
595
+ }
596
+ [data-theme="light"] .btn-run { box-shadow: 0 2px 8px rgba(29,78,216,0.22); }
597
+ .btn-run:hover { opacity:.88; box-shadow:0 4px 16px rgba(59,130,246,0.40); }
598
+ .btn-run:active { transform:scale(0.99); }
599
+ .btn-run:disabled{ opacity:.4; cursor:not-allowed; transform:none; }
600
+
601
+ .loader {
602
+ display:none; width:14px; height:14px;
603
+ border:2px solid rgba(255,255,255,0.25);
604
+ border-top-color:white; border-radius:50%;
605
+ animation: spin .6s linear infinite;
606
+ }
607
+ @keyframes spin{ to{transform:rotate(360deg)} }
608
+
609
+ /* ── RESULT PANEL ───────────────────────────────────────────── */
610
+ #res { display:none; animation: appear .28s ease; margin-top: 20px; }
611
+ @keyframes appear {
612
+ from{opacity:0;transform:translateY(6px)}
613
+ to {opacity:1;transform:translateY(0)}
614
+ }
615
+ .metrics {
616
+ display: grid; grid-template-columns: repeat(4,1fr);
617
+ gap: 12px; margin-bottom: 16px;
618
+ }
619
+ @media(max-width:800px){ .metrics{grid-template-columns:repeat(2,1fr);} }
620
+
621
+ .mc {
622
+ background: var(--card); border: 1px solid var(--border);
623
+ border-radius: 8px; padding: 16px 13px; text-align: center;
624
+ box-shadow: 0 1px 3px var(--shadow);
625
+ }
626
+ .mc.primary { border-color: rgba(59,130,246,0.3); }
627
+ [data-theme="light"] .mc.primary { border-color: rgba(29,78,216,0.25); }
628
+
629
+ .mc-val {
630
+ font-family: "DM Mono", monospace;
631
+ font-size: 24px; font-weight: 500; line-height: 1.1;
632
+ color: var(--blue); margin-bottom: 5px;
633
+ }
634
+ .mc-val.g { color:var(--green); }
635
+ .mc-val.w { color:var(--text); }
636
+ .mc-val.sm{ font-size:17px; }
637
+ .mc-lbl { font-size:10.5px; color:var(--text-dim); letter-spacing:.5px; text-transform:uppercase; }
638
+
639
+ .ad-pill {
640
+ display:inline-flex; align-items:center; gap:5px;
641
+ padding:4px 11px; border-radius:4px; margin-top:3px;
642
+ font-family:"DM Mono",monospace; font-size:11.5px; font-weight:500;
643
+ }
644
+ .ad-in { background:var(--green-dim); color:var(--green); border:1px solid rgba(16,185,129,0.22); }
645
+ .ad-out { background:var(--red-dim); color:var(--red); border:1px solid rgba(239,68,68,0.22); }
646
+ .ad-dot { width:5px;height:5px;border-radius:50%;background:currentColor;display:inline-block; }
647
+
648
+ /* ── XAI SECTION ────────────────────────────────────────────── */
649
+ .xai-card {
650
+ background:var(--card); border:1px solid var(--border);
651
+ border-radius:8px; padding:18px; margin-bottom:16px;
652
+ box-shadow:0 1px 3px var(--shadow);
653
+ }
654
+ .xai-head {
655
+ display:flex; align-items:center; justify-content:space-between;
656
+ margin-bottom:14px;
657
+ }
658
+ .xai-title { font-size:14px; font-weight:600; color:var(--text); }
659
+ .xai-sub { font-size:11.5px; color:var(--text-dim); margin-top:2px; }
660
+ .xai-img { width:100%; border-radius:5px; display:block; }
661
+ #xai-ph { text-align:center; padding:18px; color:var(--text-dim); font-size:13px; }
662
+
663
+ /* meta line */
664
+ .meta-line {
665
+ font-size:11px; color:var(--text-dim);
666
+ font-family:"DM Mono",monospace; margin-top:6px;
667
+ display:flex; align-items:center; gap:8px; flex-wrap:wrap;
668
+ }
669
+ .sep { color:var(--border2); }
670
+
671
+ /* ── ERROR ──────────────────────────────────────────────────── */
672
+ .err {
673
+ background:var(--red-dim); border:1px solid rgba(239,68,68,0.2);
674
+ border-radius:6px; padding:9px 13px;
675
+ color:var(--red); font-size:13px; margin-top:10px; display:none;
676
+ }
677
+
678
+ /* ── HINT ───────────────────────────────────────────────────── */
679
+ .hint {
680
+ display:flex; align-items:flex-start; gap:8px;
681
+ background:var(--blue-dim); border:1px solid rgba(59,130,246,0.18);
682
+ border-radius:6px; padding:9px 12px;
683
+ font-size:12px; color:var(--blue);
684
+ font-family:"DM Mono",monospace; margin-top:12px;
685
+ }
686
+ [data-theme="light"] .hint { border-color:rgba(29,78,216,0.18); }
687
+ .hint-icon { flex-shrink:0; font-size:13px; line-height:1.5; }
688
+
689
+ /* ── DROPZONE ───────────────────────────────────────────────── */
690
+ .dz {
691
+ border:2px dashed var(--border2); border-radius:8px;
692
+ background:var(--bg2); padding:30px 16px;
693
+ text-align:center; cursor:pointer;
694
+ transition:border-color .15s, background .15s; position:relative;
695
+ }
696
+ .dz:hover,.dz.over { border-color:var(--blue); background:var(--blue-glow); }
697
+ .dz input[type=file] { position:absolute;inset:0;opacity:0;cursor:pointer;width:100%;height:100%; }
698
+ .dz svg { width:24px;height:24px;stroke:var(--text-dim);display:block;margin:0 auto 8px; }
699
+ .dz-txt { font-size:13px; color:var(--text-mid); margin-bottom:3px; }
700
+ .dz-sub { font-size:11px; color:var(--text-dim); font-family:"DM Mono",monospace; }
701
+
702
+ /* ── PROGRESS ───────────────────────────────────────────────── */
703
+ .prog-wrap { background:var(--surface); border-radius:2px; height:2px; overflow:hidden; margin-top:10px; display:none; }
704
+ .prog-fill { height:100%; background:var(--blue); width:0%; transition:width .3s ease; }
705
+
706
+ /* ── TABLE ──────────────────────────────────────────────────── */
707
+ .tbl-wrap { overflow-x:auto; margin-top:14px; }
708
+ table { width:100%; border-collapse:collapse; font-size:12.5px; }
709
+ thead th {
710
+ background:var(--card2); padding:8px 11px;
711
+ text-align:left; font-size:10.5px; font-weight:600;
712
+ color:var(--text-dim); letter-spacing:.6px; text-transform:uppercase;
713
+ border-bottom:1px solid var(--border);
714
+ }
715
+ tbody tr { border-bottom:1px solid var(--border); transition:background .1s; }
716
+ tbody tr:hover { background:var(--card2); }
717
+ tbody td { padding:8px 11px; color:var(--text); font-family:"DM Mono",monospace; font-size:12px; }
718
+ .td-nm { font-family:"DM Sans",sans-serif; font-size:13px; }
719
+ .r1 { color:var(--blue); font-weight:600; }
720
+ .rtop{ color:var(--green); }
721
+
722
+ /* download */
723
+ .btn-dl {
724
+ display:inline-flex; align-items:center; gap:6px;
725
+ background:var(--surface); border:1px solid var(--border);
726
+ border-radius:6px; padding:5px 12px;
727
+ font-size:12.5px; color:var(--text-mid);
728
+ font-family:"DM Sans",sans-serif; font-weight:500;
729
+ text-decoration:none; transition:all .12s; margin-top:10px;
730
+ }
731
+ .btn-dl:hover { border-color:var(--blue); color:var(--blue); background:var(--blue-glow); }
732
+ .btn-dl svg { width:12px;height:12px;stroke:currentColor; }
733
+
734
+ /* ── SELECTIVITY ────────────────────────────────────────────── */
735
+ .sel-grid { display:grid; grid-template-columns:1fr 1fr; gap:10px; margin-top:14px; }
736
+ @media(max-width:640px){ .sel-grid{grid-template-columns:1fr;} }
737
+ .sel-card {
738
+ background:var(--card2); border:1px solid var(--border);
739
+ border-radius:8px; padding:13px 15px;
740
+ display:flex; align-items:center; gap:13px;
741
+ }
742
+ .sel-val { font-family:"DM Mono",monospace; font-size:21px; font-weight:500; min-width:50px; text-align:center; }
743
+ .sel-info { flex:1; min-width:0; }
744
+ .sel-lbl { font-size:12.5px; font-weight:500; margin-bottom:2px; }
745
+ .sel-seq {
746
+ font-family:"DM Mono",monospace; font-size:10px; color:var(--text-dim);
747
+ white-space:nowrap; overflow:hidden; text-overflow:ellipsis;
748
+ }
749
+ .sel-row { display:flex; align-items:center; gap:7px; margin-top:5px; }
750
+
751
+ /* ── FOOTER ─────────────────────────────────────────────────── */
752
+ footer {
753
+ position:relative; z-index:1;
754
+ border-top:1px solid var(--border);
755
+ padding:18px 24px; text-align:center;
756
+ font-size:11.5px; color:var(--text-dim);
757
+ font-family:"DM Mono",monospace;
758
+ transition:border-color .2s;
759
+ }
760
+ footer a { color:var(--blue); text-decoration:none; }
761
+ footer a:hover { text-decoration:underline; }
762
+ </style>
763
+ </head>
764
+ <body>
765
+
766
+ <!-- HEADER -->
767
+ <header>
768
+ <div class="hdr">
769
+ <div class="logo-wrap">
770
+ <img src="/static/logo.png" class="logo-img" alt="VeloBind"
771
+ onerror="this.style.display='none'">
772
+ <span class="logo-text">VeloBind</span>
773
+ </div>
774
+ <div class="hdr-right">
775
+ <div class="hdr-stat">
776
+ <div class="pulse"></div>
777
+ R = 0.8469 &nbsp;|&nbsp; CASF-2016
778
+ </div>
779
+ <div class="badge badge-green">No 3D structure</div>
780
+ <div class="badge badge-blue">45-model ensemble</div>
781
+ <div class="theme-btn" onclick="toggleTheme()" title="Toggle theme">
782
+ <div class="toggle-track"><div class="toggle-knob"></div></div>
783
+ <span class="theme-lbl" id="tlbl">Light</span>
784
+ </div>
785
+ </div>
786
+ </div>
787
+ </header>
788
+
789
+ <!-- MAIN -->
790
+ <main>
791
+
792
+ <!-- Page title -->
793
+ <div class="page-title">
794
+ <div>
795
+ <h1>Protein-Ligand <span>Binding Affinity</span> Prediction</h1>
796
+ <p>Sequence and SMILES-based prediction — no docking, no 3D preprocessing, no crystal structure required. Trained on LP-PDBBind, benchmarked on CASF-2016 and CASF-2013.</p>
797
+ <div class="title-badges">
798
+ <span class="badge badge-blue">ESM-2 35M frozen</span>
799
+ <span class="badge badge-green">LightGBM · CatBoost · XGBoost</span>
800
+ <span class="badge badge-gray">LP-PDBBind training</span>
801
+ <span class="badge badge-gray">Applicability domain</span>
802
+ </div>
803
+ </div>
804
+ </div>
805
+
806
+ <!-- Tabs -->
807
+ <div class="tabs">
808
+ <button class="tab on" onclick="setTab('single',this)">Single Query</button>
809
+ <button class="tab" onclick="setTab('batch',this)">Batch Screening</button>
810
+ <button class="tab" onclick="setTab('sel',this)">Selectivity Profile</button>
811
+ </div>
812
+
813
+ <!-- TAB: SINGLE -->
814
+ <div id="panel-single" class="panel on">
815
+ <div class="grid2">
816
+ <div class="card">
817
+ <div class="card-head">Target Protein</div>
818
+ <span class="field-label">Amino acid sequence — plain or FASTA</span>
819
+ <textarea id="seq" rows="7" placeholder=">TargetProtein&#10;MKTAYIAKQRQISFVK..."></textarea>
820
+ <div class="pill-row">
821
+ <span class="pill-lbl">Examples:</span>
822
+ <button class="pill" onclick="loadSeq('egfr')">EGFR kinase</button>
823
+ <button class="pill" onclick="loadSeq('hiv')">HIV protease</button>
824
+ <button class="pill" onclick="loadSeq('thrombin')">Thrombin</button>
825
+ </div>
826
+ </div>
827
+ <div class="card">
828
+ <div class="card-head">Ligand</div>
829
+ <span class="field-label">SMILES string</span>
830
+ <textarea id="smi" rows="3" placeholder="CCOc1cc2c(cc1OCC)ncnc2Nc1cccc(Cl)c1"></textarea>
831
+ <div class="pill-row">
832
+ <span class="pill-lbl">Examples:</span>
833
+ <button class="pill" onclick="loadSmi('erlotinib')">Erlotinib</button>
834
+ <button class="pill" onclick="loadSmi('imatinib')">Imatinib</button>
835
+ <button class="pill" onclick="loadSmi('indinavir')">Indinavir</button>
836
+ </div>
837
+ </div>
838
+ </div>
839
+
840
+ <button class="btn-run" id="run-btn" onclick="runSingle()">
841
+ <div class="loader" id="run-ldr"></div>
842
+ <span id="run-lbl">Predict Binding Affinity</span>
843
+ </button>
844
+ <div class="err" id="single-err"></div>
845
+
846
+ <div id="res">
847
+ <hr class="divider" style="margin-top:18px">
848
+ <div class="metrics">
849
+ <div class="mc primary">
850
+ <div class="mc-val" id="r-pkd">--</div>
851
+ <div class="mc-lbl">Predicted pKd</div>
852
+ </div>
853
+ <div class="mc">
854
+ <div class="mc-val g sm" id="r-ci">--</div>
855
+ <div class="mc-lbl">95% model interval</div>
856
+ </div>
857
+ <div class="mc">
858
+ <div class="mc-val w sm" id="r-ki">--</div>
859
+ <div class="mc-lbl">Estimated Ki</div>
860
+ </div>
861
+ <div class="mc">
862
+ <div id="r-ad" class="ad-pill ad-in">
863
+ <span class="ad-dot"></span> IN DOMAIN
864
+ </div>
865
+ <div class="mc-lbl" style="margin-top:8px">Applicability domain</div>
866
+ </div>
867
+ </div>
868
+
869
+ <div class="xai-card">
870
+ <div class="xai-head">
871
+ <div>
872
+ <div class="xai-title">Feature Attribution</div>
873
+ <div class="xai-sub">Physicochemical drivers of this prediction</div>
874
+ </div>
875
+ <div class="badge badge-blue">SHAP / LightGBM</div>
876
+ </div>
877
+ <img id="xai-img" class="xai-img" src="" alt="" style="display:none">
878
+ <div id="xai-ph">Chart will appear after prediction</div>
879
+ </div>
880
+
881
+ <div class="meta-line" id="meta"></div>
882
+ </div>
883
+ </div>
884
+
885
+ <!-- TAB: BATCH -->
886
+ <div id="panel-batch" class="panel">
887
+ <div class="grid2">
888
+ <div class="card">
889
+ <div class="card-head">Target Protein</div>
890
+ <span class="field-label">Sequence — plain or FASTA</span>
891
+ <textarea id="bseq" rows="7" placeholder=">TargetProtein&#10;MKTAYIAKQRQISFVK..."></textarea>
892
+ </div>
893
+ <div class="card">
894
+ <div class="card-head">Compound Library</div>
895
+ <span class="field-label">CSV with a <code style="color:var(--blue)">smiles</code> column (optional: <code style="color:var(--green)">name</code>)</span>
896
+ <div class="dz" id="dz">
897
+ <input type="file" id="bfile" accept=".csv" onchange="fileChosen(this)">
898
+ <svg viewBox="0 0 24 24" fill="none">
899
+ <path d="M14 2H6a2 2 0 00-2 2v16a2 2 0 002 2h12a2 2 0 002-2V8z" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
900
+ <polyline points="14 2 14 8 20 8" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
901
+ <line x1="12" y1="18" x2="12" y2="12" stroke-width="1.5" stroke-linecap="round"/>
902
+ <polyline points="9 15 12 12 15 15" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
903
+ </svg>
904
+ <div class="dz-txt" id="dz-txt">Drop CSV here or click to upload</div>
905
+ <div class="dz-sub">Requires a smiles column</div>
906
+ </div>
907
+ <div class="hint">
908
+ <span class="hint-icon">i</span>
909
+ Max 500 compounds per batch on this server. For larger libraries, use the Python API.
910
+ </div>
911
+ </div>
912
+ </div>
913
+
914
+ <button class="btn-run" id="batch-btn" onclick="runBatch()">
915
+ <div class="loader" id="batch-ldr"></div>
916
+ <span id="batch-lbl">Run Batch Screening</span>
917
+ </button>
918
+ <div class="prog-wrap" id="prog-wrap"><div class="prog-fill" id="prog-fill"></div></div>
919
+ <div class="err" id="batch-err"></div>
920
+
921
+ <div id="batch-out" style="display:none;margin-top:18px">
922
+ <div style="display:flex;align-items:center;justify-content:space-between">
923
+ <div style="font-size:15px;font-weight:600">Ranked results</div>
924
+ <a id="dl-csv" class="btn-dl" href="#" download="velobind_results.csv">
925
+ <svg viewBox="0 0 24 24" fill="none">
926
+ <path d="M21 15v4a2 2 0 01-2 2H5a2 2 0 01-2-2v-4" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
927
+ <polyline points="7 10 12 15 17 10" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
928
+ <line x1="12" y1="15" x2="12" y2="3" stroke-width="1.5" stroke-linecap="round"/>
929
+ </svg>
930
+ Download CSV
931
+ </a>
932
+ </div>
933
+ <div class="tbl-wrap">
934
+ <table>
935
+ <thead>
936
+ <tr>
937
+ <th>Rank</th><th>Name</th><th>pKd</th>
938
+ <th>95% CI</th><th>Ki estimate</th><th>AD</th><th>SMILES</th>
939
+ </tr>
940
+ </thead>
941
+ <tbody id="btbody"></tbody>
942
+ </table>
943
+ </div>
944
+ </div>
945
+ </div>
946
+
947
+ <!-- TAB: SELECTIVITY -->
948
+ <div id="panel-sel" class="panel">
949
+ <div class="grid2">
950
+ <div class="card">
951
+ <div class="card-head">Ligand</div>
952
+ <span class="field-label">SMILES string</span>
953
+ <textarea id="ssmi" rows="4" placeholder="Paste SMILES..."></textarea>
954
+ </div>
955
+ <div class="card">
956
+ <div class="card-head">Off-target Panel</div>
957
+ <span class="field-label">One protein sequence per line (plain or FASTA)</span>
958
+ <textarea id="sseqs" rows="4" placeholder="Paste sequences, one per line..."></textarea>
959
+ <!--
960
+ <div class="pill-row" style="margin-top:10px">
961
+ <button class="pill" onclick="loadPanel('kinase')">Kinase panel</button>
962
+ <button class="pill" onclick="loadPanel('protease')">Protease panel</button>
963
+ </div>
964
+ -->
965
+ </div>
966
+ </div>
967
+
968
+ <button class="btn-run" id="sel-btn" onclick="runSel()">
969
+ <div class="loader" id="sel-ldr"></div>
970
+ <span id="sel-lbl">Run Selectivity Profile</span>
971
+ </button>
972
+ <div class="err" id="sel-err"></div>
973
+
974
+ <div id="sel-out" style="display:none;margin-top:18px">
975
+ <div style="font-size:15px;font-weight:600;margin-bottom:12px">Selectivity profile</div>
976
+ <div class="sel-grid" id="sel-cards"></div>
977
+ </div>
978
+ </div>
979
+
980
+ </main>
981
+
982
+ <footer>
983
+ VeloBind &nbsp;·&nbsp; R = 0.8469 CASF-2016 / R = 0.7799 CASF-2013 &nbsp;·&nbsp;
984
+ Sequence + SMILES only &nbsp;·&nbsp;
985
+ <a href="https://github.com/umarbioinfo/VeloBind" target="_blank">GitHub</a>
986
+ &nbsp;·&nbsp;
987
+ <a href="#" onclick="return false">Preprint</a>
988
+ </footer>
989
+
990
+ <script>
991
+ // Theme
992
+ function toggleTheme(){
993
+ const h = document.documentElement;
994
+ const nxt = h.getAttribute('data-theme')==='dark' ? 'light' : 'dark';
995
+ h.setAttribute('data-theme', nxt);
996
+ document.getElementById('tlbl').textContent = nxt==='dark' ? 'Light' : 'Dark';
997
+ localStorage.setItem('vb-theme', nxt);
998
+ }
999
+ (function(){
1000
+ const s = localStorage.getItem('vb-theme');
1001
+ if(s){
1002
+ document.documentElement.setAttribute('data-theme',s);
1003
+ document.getElementById('tlbl').textContent = s==='dark'?'Light':'Dark';
1004
+ }
1005
+ })();
1006
+
1007
+ // Tabs
1008
+ function setTab(name,btn){
1009
+ document.querySelectorAll('.panel').forEach(p=>p.classList.remove('on'));
1010
+ document.querySelectorAll('.tab').forEach(b=>b.classList.remove('on'));
1011
+ document.getElementById('panel-'+name).classList.add('on');
1012
+ btn.classList.add('on');
1013
+ }
1014
+
1015
+ // Example data
1016
+ const SEQS = {
1017
+ egfr:"MRPSGTAGAALLALLAALCPASRALEEKKVCQGTSNKLTQLGTFEDHFLSLQRMFNNCEVVLGNLEITYVQRNYDLSFLKTIQEVAGYVLIALNTVERIPLENLQIIRGNMYYENSYALAVLSNYDANKTGLKELPMRNLQEILHGAVRFSNNPALCNVESIQWRDIVSSDFLSNMSMDFQNHLGSCQKCDPSCPNGSCWGAGEENCQKLTKIICAQQCSGRCRGKSPSDCCHNQCAAGCTGPRESDCLVCRKFRDEATCKDTCPPLMLYNPTTYQMDVNPEGKYSFGATCVKKCPRNYVVTDHGSCVRACGADSYEMEEDGVRKCKKCEGPCRKVCNGIGIGEFKDSLSINATNIKHFKNCTSISGDLHILPVAFRGDSFTHTPPLDPQELDILKTVKEITGFLLIQAWPENRTDLHAFENLEIIRGRTKQHGQFSLAVVSLNITSLGLRSLKEISDGDVIISGNKNLCYANTINWKKLFGTSGQKTKIISNRGENSCKATGQVCHALCSPEGCWGPEPRDCVSCRNVSRGRECVDKCNLLEGEPREFVENSECIQCHPECLPQAMNITCTGRGPDNCIQCAHYIDGPHCVKTCPAGVMGENNTLVWKYADAGHVCHLCHPNCTYGCTGPGLEGCPTNGPKIPSIATGMVGALLLLLVVALGIGLFMRRRHIVRKRTLRRLLQERELVEPLTPSGEAPNQALLRILKETEFKKIKVLGSGAFGTVYKGLWIPEGEKVKIPVAIKELREATSPKANKEILDEAYVMASVDNPHVCRLLGICLTSTVQLITQLMPFGCLLDYVREHKDNIGSQYLLNWCVQIAKGMNYLEDRRLVHRDLAARNVLVKTPQHVKITDFGLAKLLGAEEKEYHAEGGKVPIKWMALESILHRIYTHQSDVWSYGVTVWELMTFGSKPYDGIPASEISSILEKGERLPQPPICTIDVYMIMVKCWMIDADSRPKFRELIIEFSKMARDPQRYLVIQGDERMHLPSPTDSNFYRALMDEEDMDDVVDADEYLIPQQGFFSSPSTSRTPLLSSLSATSNNSTVACIDRNGLQSCPIKEDSFLQRYSSDPTGALTEDSIDDTFLPVPEYINQSVPKRPAGSVQNPVYHNQPLNPAPSRDPHYQDPHSTAVGNPEYLNTVQPTCVNSTFDSPAHWAQKGSHQISLDNPDYQQDFFPKEAKPNGIFKGSTAENAEYLRVAPQSSEFIGA",
1018
+ hiv:"PQITLWQRPLVTIKIGGQLKEALLDTGADDTVLEEMNLPGRWKPKMIGGIGGFIKVRQYDQILIEICGHKAIGTVLVGPTPVNIIGRNLLTQIGCTLNF",
1019
+ thrombin:"MAHVRGLQLPGCLALAALCSLVHSQHVFLAPQQARSLLQRVRRANTFLEEVRKGNLERECVEETCSYEEAFEALESSTATDVFWAKYTACETARTPRDKLAACLEGNCAEGLGTNYRGHVNITRSGIECQLWRSRYPHKPEINSTTHPGADLQENFCRNPDSSTTGPWCYTTDPTVRRQECSIPVCGQDQVTVAMTPRSEGSSVNLSPPLEQCVPDRGQQYQLRPVQPFLNQLREIFNMAR",
1020
+ };
1021
+ const SMIS = {
1022
+ erlotinib:"CCOc1cc2c(cc1OCC)ncnc2Nc1cccc(Cl)c1",
1023
+ imatinib: "Cc1ccc(NC(=O)c2ccc(CN3CCN(C)CC3)cc2)cc1Nc1nccc(-c2cccnc2)n1",
1024
+ indinavir:"OC[C@@H](NC(=O)[C@@H]1CN(Cc2cccnc2)C[C@H]1NC(=O)[C@@H](CC(C)C)NC(=O)c1cc2ccccc2[nH]1)Cc1ccccc1",
1025
+ };
1026
+ function loadSeq(k){ document.getElementById('seq').value=SEQS[k]||''; }
1027
+ function loadSmi(k){ document.getElementById('smi').value=SMIS[k]||''; }
1028
+
1029
+ // Single
1030
+ async function runSingle(){
1031
+ const seq=document.getElementById('seq').value.trim();
1032
+ const smi=document.getElementById('smi').value.trim();
1033
+ const err=document.getElementById('single-err');
1034
+ err.style.display='none';
1035
+ if(!seq) return showErr(err,'Please enter a protein sequence.');
1036
+ if(!smi) return showErr(err,'Please enter a SMILES string.');
1037
+ const dark = document.documentElement.getAttribute('data-theme')==='dark';
1038
+ setL('run',true);
1039
+ document.getElementById('res').style.display='none';
1040
+ try{
1041
+ const t0=performance.now();
1042
+ const r=await fetch('/predict',{
1043
+ method:'POST',headers:{'Content-Type':'application/json'},
1044
+ body:JSON.stringify({sequence:seq,smiles:smi,dark})
1045
+ });
1046
+ const d=await r.json();
1047
+ const ms=((performance.now()-t0)/1000).toFixed(2);
1048
+ if(!r.ok||d.error) return showErr(err,d.error||'Prediction failed.');
1049
+ document.getElementById('r-pkd').textContent=d.pkd.toFixed(2);
1050
+ document.getElementById('r-ci').textContent='['+d.ci_lo.toFixed(2)+', '+d.ci_hi.toFixed(2)+']';
1051
+ document.getElementById('r-ki').textContent=d.ki;
1052
+ const ad=document.getElementById('r-ad');
1053
+ ad.className='ad-pill '+(d.in_domain?'ad-in':'ad-out');
1054
+ ad.innerHTML='<span class="ad-dot"></span> '+(d.in_domain?'IN DOMAIN':'OUT OF DOMAIN');
1055
+ if(d.xai_img){
1056
+ document.getElementById('xai-img').src=d.xai_img;
1057
+ document.getElementById('xai-img').style.display='block';
1058
+ document.getElementById('xai-ph').style.display='none';
1059
+ }
1060
+ document.getElementById('meta').innerHTML=
1061
+ `<span>Time: ${ms}s</span><span class="sep">|</span>`+
1062
+ `<span>45-model ensemble</span><span class="sep">|</span>`+
1063
+ `<span>Device: CPU</span>`;
1064
+ document.getElementById('res').style.display='block';
1065
+ }catch(e){ showErr(err,'Network error: '+e.message); }
1066
+ finally{ setL('run',false); }
1067
+ }
1068
+
1069
+ // Batch
1070
+ async function runBatch(){
1071
+ const seq=document.getElementById('bseq').value.trim();
1072
+ const file=document.getElementById('bfile').files[0];
1073
+ const err=document.getElementById('batch-err');
1074
+ err.style.display='none';
1075
+ if(!seq) return showErr(err,'Please enter a protein sequence.');
1076
+ if(!file) return showErr(err,'Please upload a CSV file.');
1077
+ const fd=new FormData(); fd.append('sequence',seq); fd.append('file',file);
1078
+ setL('batch',true);
1079
+ document.getElementById('batch-out').style.display='none';
1080
+ animProg();
1081
+ try{
1082
+ const r=await fetch('/batch',{method:'POST',body:fd});
1083
+ const d=await r.json();
1084
+ if(!r.ok||d.error) return showErr(err,d.error||'Batch failed.');
1085
+ renderBatch(d.results);
1086
+ }catch(e){ showErr(err,'Network error: '+e.message); }
1087
+ finally{ setL('batch',false); stopProg(); }
1088
+ }
1089
+
1090
+ function renderBatch(rows){
1091
+ const tb=document.getElementById('btbody');
1092
+ tb.innerHTML='';
1093
+ rows.forEach((r,i)=>{
1094
+ const rank=i+1;
1095
+ const cls=rank===1?'r1':rank<=5?'rtop':'';
1096
+ const tr=document.createElement('tr');
1097
+ tr.innerHTML=`
1098
+ <td class="${cls}">#${rank}</td>
1099
+ <td class="td-nm">${r.name||'--'}</td>
1100
+ <td class="${cls}" style="font-weight:${rank<=3?600:400}">${r.pkd.toFixed(2)}</td>
1101
+ <td>[${r.ci_lo.toFixed(2)}, ${r.ci_hi.toFixed(2)}]</td>
1102
+ <td>${r.ki}</td>
1103
+ <td><span class="ad-pill ${r.in_domain?'ad-in':'ad-out'}" style="font-size:10.5px;padding:2px 7px">
1104
+ ${r.in_domain?'In domain':'Out of domain'}</span></td>
1105
+ <td style="max-width:150px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap"
1106
+ title="${r.smiles}">${r.smiles}</td>`;
1107
+ tb.appendChild(tr);
1108
+ });
1109
+ let csv='rank,name,smiles,pkd,ci_lo,ci_hi,ki,in_domain\n';
1110
+ rows.forEach((r,i)=>{ csv+=`${i+1},"${r.name||''}","${r.smiles}",${r.pkd.toFixed(3)},${r.ci_lo.toFixed(3)},${r.ci_hi.toFixed(3)},"${r.ki}",${r.in_domain}\n`; });
1111
+ document.getElementById('dl-csv').href=URL.createObjectURL(new Blob([csv],{type:'text/csv'}));
1112
+ document.getElementById('batch-out').style.display='block';
1113
+ }
1114
+
1115
+ // Selectivity
1116
+ async function runSel(){
1117
+ const smi=document.getElementById('ssmi').value.trim();
1118
+ const seqs=document.getElementById('sseqs').value.trim();
1119
+ const err=document.getElementById('sel-err');
1120
+ err.style.display='none';
1121
+ if(!smi) return showErr(err,'Please enter a SMILES string.');
1122
+ if(!seqs) return showErr(err,'Please enter at least one sequence.');
1123
+ const arr=seqs.split('\n').map(s=>s.trim()).filter(s=>s&&!s.startsWith('>'));
1124
+ setL('sel',true);
1125
+ document.getElementById('sel-out').style.display='none';
1126
+ try{
1127
+ const r=await fetch('/selectivity',{
1128
+ method:'POST',headers:{'Content-Type':'application/json'},
1129
+ body:JSON.stringify({smiles:smi,sequences:arr})
1130
+ });
1131
+ const d=await r.json();
1132
+ if(!r.ok||d.error) return showErr(err,d.error||'Failed.');
1133
+ const c=document.getElementById('sel-cards');
1134
+ c.innerHTML='';
1135
+ const pal=['var(--blue)','var(--green)','#8B5CF6','var(--red)','#06B6D4'];
1136
+ d.results.forEach((r,i)=>{
1137
+ const col=pal[i%pal.length];
1138
+ c.innerHTML+=`
1139
+ <div class="sel-card">
1140
+ <div class="sel-val" style="color:${col}">${r.pkd.toFixed(2)}</div>
1141
+ <div class="sel-info">
1142
+ <div class="sel-lbl">Target ${i+1}</div>
1143
+ <div class="sel-seq">${(r.sequence||'').substring(0,44)}...</div>
1144
+ <div class="sel-row">
1145
+ <span class="ad-pill ${r.in_domain?'ad-in':'ad-out'}" style="font-size:10px;padding:2px 7px">
1146
+ ${r.in_domain?'In domain':'Out of domain'}</span>
1147
+ <span style="font-family:'DM Mono',monospace;font-size:11px;color:var(--text-mid)">Ki ~ ${r.ki}</span>
1148
+ </div>
1149
+ </div>
1150
+ </div>`;
1151
+ });
1152
+ document.getElementById('sel-out').style.display='block';
1153
+ }catch(e){ showErr(err,'Network error: '+e.message); }
1154
+ finally{ setL('sel',false); }
1155
+ }
1156
+
1157
+ // Dropzone
1158
+ const dz=document.getElementById('dz');
1159
+ ['dragenter','dragover'].forEach(e=>dz.addEventListener(e,ev=>{ev.preventDefault();dz.classList.add('over');}));
1160
+ ['dragleave','drop'].forEach(e=>dz.addEventListener(e,ev=>{
1161
+ ev.preventDefault();dz.classList.remove('over');
1162
+ if(ev.type==='drop'){
1163
+ const f=ev.dataTransfer.files[0];
1164
+ if(f){document.getElementById('bfile').files=ev.dataTransfer.files;fileChosen({files:[f]});}
1165
+ }
1166
+ }));
1167
+ function fileChosen(input){
1168
+ const f=input.files[0];
1169
+ if(f) document.getElementById('dz-txt').textContent=f.name;
1170
+ }
1171
+
1172
+ // Helpers
1173
+ function setL(key,on){
1174
+ const btn=document.getElementById(key+'-btn');
1175
+ const ldr=document.getElementById(key+'-ldr');
1176
+ const lbl=document.getElementById(key+'-lbl');
1177
+ btn.disabled=on; ldr.style.display=on?'block':'none';
1178
+ lbl.textContent=on?'Computing...':{run:'Predict Binding Affinity',batch:'Run Batch Screening',sel:'Run Selectivity Profile'}[key];
1179
+ }
1180
+ function showErr(el,msg){ el.textContent=msg; el.style.display='block'; }
1181
+
1182
+ let pi=null;
1183
+ function animProg(){
1184
+ const w=document.getElementById('prog-wrap');
1185
+ const f=document.getElementById('prog-fill');
1186
+ w.style.display='block'; let p=0;
1187
+ pi=setInterval(()=>{ p=Math.min(p+Math.random()*7,88); f.style.width=p+'%'; },300);
1188
+ }
1189
+ function stopProg(){
1190
+ clearInterval(pi);
1191
+ const f=document.getElementById('prog-fill');
1192
+ const w=document.getElementById('prog-wrap');
1193
+ f.style.width='100%';
1194
+ setTimeout(()=>{ w.style.display='none'; f.style.width='0%'; },500);
1195
+ }
1196
+ </script>
1197
+ </body>
1198
+ </html>"""
1199
+
1200
+ # ---------------------------------------------------------------------------
1201
+ # Routes
1202
+ # ---------------------------------------------------------------------------
1203
+ @app.route("/")
1204
+ def index():
1205
+ return render_template_string(HTML)
1206
+
1207
+ @app.route("/static/<path:filename>")
1208
+ def static_files(filename):
1209
+ return send_from_directory("static", filename)
1210
+
1211
+ @app.route("/predict", methods=["POST"])
1212
+ def predict():
1213
+ data = request.get_json(force=True)
1214
+ seq = clean_fasta(data.get("sequence","").strip())
1215
+ smiles = data.get("smiles","").strip()
1216
+ dark = data.get("dark", True)
1217
+ if not seq: return jsonify({"error":"Protein sequence is required."}), 400
1218
+ if not smiles: return jsonify({"error":"SMILES string is required."}), 400
1219
+ t0 = time.time()
1220
+ try:
1221
+ lig, err = ligand_features(smiles)
1222
+ if err: return jsonify({"error":f"Ligand: {err}"}), 400
1223
+ esm_mean = embed_sequence(seq)
1224
+ seqfeat = seq_features(seq)
1225
+ X = assemble(esm_mean, seqfeat, lig)
1226
+ pkd, ci_lo, ci_hi = predict_pkd(X)
1227
+ if pkd is None:
1228
+ import random; random.seed(hash(seq[:20]+smiles[:20])%2**31)
1229
+ pkd=random.uniform(5.5,9.0); ci_lo=pkd-0.8; ci_hi=pkd+0.8
1230
+ in_domain, ad_dist = check_ad(esm_mean)
1231
+ return jsonify({
1232
+ "pkd":round(pkd,3), "ci_lo":round(ci_lo,3), "ci_hi":round(ci_hi,3),
1233
+ "ki":pkd_to_ki(pkd), "in_domain":bool(in_domain),
1234
+ "ad_dist":round(ad_dist,3),
1235
+ "xai_img":xai_chart(smiles,pkd,dark=bool(dark)),
1236
+ "elapsed":round(time.time()-t0,2),
1237
+ })
1238
+ except Exception as e:
1239
+ return jsonify({"error":str(e)}), 500
1240
+
1241
+ @app.route("/batch", methods=["POST"])
1242
+ def batch():
1243
+ seq = clean_fasta(request.form.get("sequence","").strip())
1244
+ file = request.files.get("file")
1245
+ if not seq: return jsonify({"error":"Protein sequence required."}), 400
1246
+ if not file: return jsonify({"error":"CSV file required."}), 400
1247
+ try: df=pd.read_csv(file)
1248
+ except Exception as e: return jsonify({"error":f"Could not read CSV: {e}"}), 400
1249
+ col=next((c for c in df.columns if c.lower() in ("smiles","smile","smi","canonical_smiles")),None)
1250
+ if col is None: return jsonify({"error":"No 'smiles' column found."}), 400
1251
+ df=df.head(500)
1252
+ name_col=next((c for c in df.columns if c.lower() in ("name","compound_name","id","molecule_name")),None)
1253
+ try:
1254
+ esm_mean=embed_sequence(seq); seqfeat=seq_features(seq)
1255
+ in_domain,_=check_ad(esm_mean)
1256
+ except Exception as e: return jsonify({"error":f"Protein error: {e}"}), 500
1257
+ results=[]
1258
+ for _,row in df.iterrows():
1259
+ smi=str(row[col]).strip(); name=str(row[name_col]).strip() if name_col else ""
1260
+ try:
1261
+ lig,err=ligand_features(smi)
1262
+ if err: continue
1263
+ X=assemble(esm_mean,seqfeat,lig)
1264
+ pkd,ci_lo,ci_hi=predict_pkd(X)
1265
+ if pkd is None:
1266
+ import random; random.seed(hash(smi)%2**31)
1267
+ pkd=random.uniform(5.0,9.0); ci_lo=pkd-0.8; ci_hi=pkd+0.8
1268
+ results.append({"name":name,"smiles":smi,"pkd":round(pkd,3),
1269
+ "ci_lo":round(ci_lo,3),"ci_hi":round(ci_hi,3),
1270
+ "ki":pkd_to_ki(pkd),"in_domain":bool(in_domain)})
1271
+ except: continue
1272
+ results.sort(key=lambda r:r["pkd"],reverse=True)
1273
+ return jsonify({"results":results})
1274
+
1275
+ @app.route("/selectivity", methods=["POST"])
1276
+ def selectivity():
1277
+ data=request.get_json(force=True)
1278
+ smiles=data.get("smiles","").strip(); seqs=data.get("sequences",[])
1279
+ if not smiles: return jsonify({"error":"SMILES required."}), 400
1280
+ if not seqs: return jsonify({"error":"At least one sequence required."}), 400
1281
+ try:
1282
+ lig,err=ligand_features(smiles)
1283
+ if err: return jsonify({"error":f"Ligand: {err}"}), 400
1284
+ except Exception as e: return jsonify({"error":str(e)}), 500
1285
+ results=[]
1286
+ for seq in seqs[:10]:
1287
+ seq=clean_fasta(seq.strip())
1288
+ if not seq: continue
1289
+ try:
1290
+ esm_mean=embed_sequence(seq); seqfeat=seq_features(seq)
1291
+ X=assemble(esm_mean,seqfeat,lig)
1292
+ pkd,ci_lo,ci_hi=predict_pkd(X)
1293
+ if pkd is None:
1294
+ import random; random.seed(hash(seq[:20])%2**31)
1295
+ pkd=random.uniform(4.5,9.0); ci_lo=pkd-0.8; ci_hi=pkd+0.8
1296
+ in_domain,_=check_ad(esm_mean)
1297
+ results.append({"sequence":seq,"pkd":round(pkd,3),
1298
+ "ci_lo":round(ci_lo,3),"ci_hi":round(ci_hi,3),
1299
+ "ki":pkd_to_ki(pkd),"in_domain":bool(in_domain)})
1300
+ except: continue
1301
+ results.sort(key=lambda r:r["pkd"],reverse=True)
1302
+ return jsonify({"results":results})
1303
+
1304
+ if __name__ == "__main__":
1305
+ port = int(os.environ.get("PORT", 7860))
1306
+ app.run(host="0.0.0.0", port=port, debug=False)