Nilsparrow1920 commited on
Commit
b61471e
·
verified ·
1 Parent(s): 0570487

Upload 4 files

Browse files
app.py ADDED
@@ -0,0 +1,338 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Gradio web app for AMP prediction with the saved C ⊕ D ensemble
2
+ # - Mutually exclusive input modes: CSV | FASTA | Manual
3
+ # - Rebuilds raw features in the SAME order used in training:
4
+ # C: [kmer(2,3,4), ESM2 t6_8M_UR50D, modlAMP]
5
+ # D: [physchem(core), ESM2 t6_8M_UR50D, modlAMP]
6
+
7
+ import re
8
+ import io
9
+ import os
10
+ import joblib
11
+ import numpy as np
12
+ import pandas as pd
13
+ import gradio as gr
14
+ import matplotlib.pyplot as plt
15
+
16
+ import torch
17
+ from transformers import AutoTokenizer, AutoModel
18
+ from modlamp.descriptors import GlobalDescriptor
19
+ from collections import Counter
20
+ from itertools import product
21
+ from functools import lru_cache
22
+
23
+ # ----------------------
24
+ # Config
25
+ # ----------------------
26
+ ESM_MODEL_NAME = "facebook/esm2_t6_8M_UR50D"
27
+ AA_ALPHABET = 'ACDEFGHIKLMNPQRSTVWY'
28
+ AA_VALID = set(AA_ALPHABET)
29
+ # For Spaces, keep the model file in repo root or /models and use a relative path:
30
+ JOBLIB_PATH = os.getenv("JOBLIB_PATH", "best_ensemble_cd.joblib")
31
+
32
+ # ----------------------
33
+ # PeptideEnsembleCD (must match class used when saving joblib)
34
+ # ----------------------
35
+ class PeptideEnsembleCD:
36
+ def __init__(self,
37
+ modelC, scalerC_full, scalerC_keep, maskC, nzv_maskC,
38
+ modelD, scalerD_full, scalerD_keep, maskD, nzv_maskD,
39
+ alpha=0.65, thr=0.36):
40
+ self.modelC = modelC
41
+ self.scalerC_full = scalerC_full
42
+ self.scalerC_keep = scalerC_keep
43
+ self.maskC = maskC
44
+ self.nzv_maskC = nzv_maskC
45
+
46
+ self.modelD = modelD
47
+ self.scalerD_full = scalerD_full
48
+ self.scalerD_keep = scalerD_keep
49
+ self.maskD = maskD
50
+ self.nzv_maskD = nzv_maskD
51
+
52
+ self.alpha = alpha
53
+ self.thr = thr
54
+
55
+ def _prep_block(self, X_raw, nzv_mask, scaler_full, keep_mask, scaler_keep):
56
+ if nzv_mask is not None:
57
+ X_raw = X_raw[:, nzv_mask]
58
+ X = scaler_full.transform(X_raw)
59
+ X = X[:, keep_mask]
60
+ X = scaler_keep.transform(X)
61
+ return X
62
+
63
+ def predict_proba(self, X_C_raw, X_D_raw):
64
+ Xc = self._prep_block(X_C_raw, getattr(self, "nzv_maskC", None),
65
+ self.scalerC_full, self.maskC, self.scalerC_keep)
66
+ Xd = self._prep_block(X_D_raw, getattr(self, "nzv_maskD", None),
67
+ self.scalerD_full, self.maskD, self.scalerD_keep)
68
+ pC = self.modelC.predict_proba(Xc)[:, 1]
69
+ pD = self.modelD.predict_proba(Xd)[:, 1]
70
+ return self.alpha * pC + (1 - self.alpha) * pD
71
+
72
+ def predict(self, X_C_raw, X_D_raw):
73
+ probs = self.predict_proba(X_C_raw, X_D_raw)
74
+ return (probs > self.thr).astype(int)
75
+
76
+ # ----------------------
77
+ # Cached loaders (use lru_cache so Spaces won't re-download each run)
78
+ # ----------------------
79
+ @lru_cache(maxsize=1)
80
+ def load_ensemble(path=JOBLIB_PATH):
81
+ return joblib.load(path)
82
+
83
+ @lru_cache(maxsize=1)
84
+ def load_esm(model_name=ESM_MODEL_NAME):
85
+ tokenizer = AutoTokenizer.from_pretrained(model_name, do_lower_case=False)
86
+ model = AutoModel.from_pretrained(model_name)
87
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
88
+ model = model.to(device)
89
+ model.eval()
90
+ return tokenizer, model, device
91
+
92
+ # ----------------------
93
+ # Parsing helpers
94
+ # ----------------------
95
+ FASTA_HDR = re.compile(r"^>.*$")
96
+
97
+ def parse_fasta(text: str):
98
+ seqs, cur = [], []
99
+ for line in text.splitlines():
100
+ line = line.strip()
101
+ if not line:
102
+ continue
103
+ if FASTA_HDR.match(line):
104
+ if cur:
105
+ seqs.append(''.join(cur)); cur = []
106
+ else:
107
+ cur.append(re.sub(r"[^A-Za-z]", "", line))
108
+ if cur: seqs.append(''.join(cur))
109
+ return seqs
110
+
111
+ def parse_textbox(text: str):
112
+ if not text: return []
113
+ if ">" in text: # FASTA-like
114
+ return parse_fasta(text)
115
+ return [re.sub(r"[^A-Za-z]", "", s.strip())
116
+ for s in text.splitlines() if s.strip()]
117
+
118
+ def normalize_seq(s: str):
119
+ s = s.upper()
120
+ return ''.join([c for c in s if c in AA_VALID])
121
+
122
+ # ----------------------
123
+ # Feature builders (mirror training)
124
+ # ----------------------
125
+ def esm_embeddings(seqs, tokenizer, model, device, batch_size=16):
126
+ embs = []
127
+ with torch.no_grad():
128
+ for i in range(0, len(seqs), batch_size):
129
+ batch = seqs[i:i+batch_size]
130
+ toks = [" ".join(s) for s in batch]
131
+ inputs = tokenizer(toks, return_tensors="pt",
132
+ padding=True, truncation=True).to(device)
133
+ out = model(**inputs)
134
+ cls = out.last_hidden_state[:, 0, :].detach().cpu().numpy()
135
+ embs.append(cls)
136
+ return np.vstack(embs) if embs else np.zeros((0, model.config.hidden_size), dtype=np.float32)
137
+
138
+ def kmer_freqs(seqs, ks=[2,3,4]):
139
+ all_feats = []
140
+ for k in ks:
141
+ vocab = [''.join(p) for p in product(AA_ALPHABET, repeat=k)]
142
+ vidx = {kmer:i for i,kmer in enumerate(vocab)}
143
+ mat = np.zeros((len(seqs), len(vocab)), dtype=np.float32)
144
+ for i, s in enumerate(seqs):
145
+ kmers = [s[j:j+k] for j in range(len(s)-k+1)]
146
+ kmers = [kmer for kmer in kmers if all(ch in AA_VALID for ch in kmer)]
147
+ c = Counter(kmers)
148
+ total = float(sum(c.values()))
149
+ if total > 0:
150
+ for kmer, cnt in c.items():
151
+ mat[i, vidx[kmer]] = cnt/total
152
+ all_feats.append(mat)
153
+ return np.concatenate(all_feats, axis=1) if all_feats else np.zeros((len(seqs),0), dtype=np.float32)
154
+
155
+ hydro_scale = {
156
+ 'A': 1.8, 'C': 2.5, 'D': -3.5, 'E': -3.5, 'F': 2.8, 'G': -0.4,
157
+ 'H': -3.2, 'I': 4.5, 'K': -3.9, 'L': 3.8, 'M': 1.9, 'N': -3.5,
158
+ 'P': -1.6, 'Q': -3.5, 'R': -4.5, 'S': -0.8, 'T': -0.7, 'V': 4.2,
159
+ 'W': -0.9, 'Y': -1.3
160
+ }
161
+ pKa_basic = {'K': 10.5, 'R': 12.5, 'H': 6.0}
162
+ pKa_N = 9.69
163
+ helix_pref = set("AEHKLMQR")
164
+ sheet_pref = set("VIYFWTC")
165
+
166
+ def hydrophobic_moment(seq, radians_per_res):
167
+ if not seq: return 0.0
168
+ angles = np.arange(len(seq)) * radians_per_res
169
+ h = np.array([hydro_scale.get(a, 0.0) for a in seq], dtype=float)
170
+ x = np.sum(h * np.cos(angles)); y = np.sum(h * np.sin(angles))
171
+ return float(np.sqrt(x*x + y*y) / max(len(seq),1))
172
+
173
+ def positive_charge_at_pH(seq, pH=7.0, include_Nterm=True):
174
+ chg = 0.0
175
+ for aa, pKa in pKa_basic.items():
176
+ n = seq.count(aa)
177
+ chg += n * (1.0 / (1.0 + 10.0**(pH - pKa)))
178
+ if include_Nterm and seq:
179
+ chg += 1.0 / (1.0 + 10.0**(pH - pKa_N))
180
+ return float(chg)
181
+
182
+ def cleavage_density(seq, set_chars):
183
+ if not seq: return 0.0
184
+ L, sites = len(seq), 0
185
+ for i in range(L-1):
186
+ if seq[i] in set_chars and seq[i+1] != 'P':
187
+ sites += 1
188
+ if seq[-1] in set_chars:
189
+ sites += 1
190
+ return sites / L
191
+
192
+ def physchem_core(seqs, pH=7.0):
193
+ feats = []
194
+ for s in seqs:
195
+ L = len(s); Ls = max(L,1)
196
+ KD = [hydro_scale.get(a, 0.0) for a in s]
197
+ KD_mean = float(np.mean(KD)) if KD else 0.0
198
+ muH_helix = hydrophobic_moment(s, np.deg2rad(100.0))
199
+ muH_sheet = hydrophobic_moment(s, np.deg2rad(180.0))
200
+ pos_charge = positive_charge_at_pH(s, pH=pH, include_Nterm=True)
201
+ pos_charge_density = pos_charge / Ls
202
+ f_helix = sum(1 for a in s if a in helix_pref) / Ls
203
+ f_sheet = sum(1 for a in s if a in sheet_pref) / Ls
204
+ dens_trypsin = cleavage_density(s, set("KR"))
205
+ dens_chymo = cleavage_density(s, set("FYWL"))
206
+ dens_elastase = cleavage_density(s, set("AVIL"))
207
+ feats.append([float(L), KD_mean, muH_helix, muH_sheet,
208
+ pos_charge, pos_charge_density, f_helix, f_sheet,
209
+ dens_trypsin, dens_chymo, dens_elastase])
210
+ return np.array(feats, dtype=np.float32)
211
+
212
+ def modlamp_features(seqs):
213
+ desc = GlobalDescriptor(seqs)
214
+ desc.calculate_all()
215
+ return np.array(desc.descriptor, dtype=np.float32)
216
+
217
+ # Build raw matrices for C and D (order matters!)
218
+ def build_raw_C_D(seqs, tokenizer, model, device, batch_size=16):
219
+ seqs = [normalize_seq(s) for s in seqs]
220
+ X_kmer = kmer_freqs(seqs, ks=[2,3,4])
221
+ X_phys = physchem_core(seqs, pH=7.0)
222
+ X_modl = modlamp_features(seqs)
223
+ X_esm = esm_embeddings(seqs, tokenizer, model, device, batch_size=batch_size)
224
+ X_C_raw = np.concatenate([X_kmer, X_esm, X_modl], axis=1)
225
+ X_D_raw = np.concatenate([X_phys, X_esm, X_modl], axis=1)
226
+ return X_C_raw, X_D_raw
227
+
228
+ # ----------------------
229
+ # Core inference
230
+ # ----------------------
231
+ def run_predict(mode, text, csv_file, fasta_file, batch_size):
232
+ # Build sequence list from the active mode
233
+ seqs = []
234
+ if mode == "Manual":
235
+ seqs = parse_textbox(text)
236
+ elif mode == "CSV" and csv_file is not None:
237
+ try:
238
+ df = pd.read_csv(csv_file.name if hasattr(csv_file, "name") else csv_file)
239
+ if 'peptide_sequence' not in df.columns:
240
+ return None, None, None, "CSV must contain a 'peptide_sequence' column."
241
+ seqs = df['peptide_sequence'].astype(str).tolist()
242
+ except Exception as e:
243
+ return None, None, None, f"Error reading CSV: {e}"
244
+ elif mode == "FASTA" and fasta_file is not None:
245
+ try:
246
+ data = fasta_file.read() if hasattr(fasta_file, "read") else open(fasta_file.name, "rb").read()
247
+ text = data.decode('utf-8', errors='ignore')
248
+ seqs = parse_fasta(text)
249
+ except Exception as e:
250
+ return None, None, None, f"Error reading FASTA: {e}"
251
+
252
+ seqs = [s for s in [normalize_seq(s) for s in seqs] if len(s) > 0]
253
+ if not seqs:
254
+ return None, None, None, "No sequences found for the selected input."
255
+
256
+ try:
257
+ ensemble = load_ensemble(JOBLIB_PATH)
258
+ except Exception as e:
259
+ return None, None, None, f"Failed to load ensemble joblib: {e}"
260
+
261
+ try:
262
+ tokenizer, esm_model, device = load_esm(ESM_MODEL_NAME)
263
+ except Exception as e:
264
+ return None, None, None, f"Failed to load ESM model: {e}"
265
+
266
+ try:
267
+ X_C_raw, X_D_raw = build_raw_C_D(seqs, tokenizer, esm_model, device, batch_size=int(batch_size))
268
+ except Exception as e:
269
+ return None, None, None, f"Feature computation failed: {e}"
270
+
271
+ try:
272
+ probs = ensemble.predict_proba(X_C_raw, X_D_raw)
273
+ thr = getattr(ensemble, "thr", 0.36)
274
+ preds = (probs > thr).astype(int)
275
+ except Exception as e:
276
+ return None, None, None, f"Prediction failed: {e}"
277
+
278
+ df_out = pd.DataFrame({
279
+ "peptide_sequence": seqs,
280
+ "probability": probs,
281
+ "prediction": preds
282
+ })
283
+
284
+ # Prepare downloadable CSV
285
+ csv_bytes = df_out.to_csv(index=False).encode("utf-8")
286
+ csv_path = "predictions_ensemble_cd.csv"
287
+ with open(csv_path, "wb") as f:
288
+ f.write(csv_bytes)
289
+
290
+ # Pie chart only for CSV/FASTA
291
+ fig = None
292
+ if mode in ("CSV", "FASTA"):
293
+ counts = df_out["prediction"].value_counts().reindex([0,1], fill_value=0)
294
+ c0, c1 = int(counts.get(0,0)), int(counts.get(1,0))
295
+ fig, ax = plt.subplots()
296
+ ax.pie([c0, c1], labels=["0", "1"], autopct="%1.1f%%", startangle=90)
297
+ ax.axis("equal")
298
+ return df_out, csv_path, fig, f"Loaded {len(seqs)} sequences. Threshold={getattr(ensemble,'thr',0.36)}"
299
+
300
+ # ----------------------
301
+ # UI (Gradio Blocks)
302
+ # ----------------------
303
+ with gr.Blocks(title="KPhysicoPIP (Gradio)") as demo:
304
+ gr.Markdown("## 🧪 KPhysicoPIP — Pro-Inflammatory Peptide Predictor")
305
+
306
+ with gr.Row():
307
+ mode = gr.Radio(choices=["CSV","FASTA","Manual"], value="Manual", label="Choose ONE input mode")
308
+ batch_size = gr.Slider(4, 128, value=16, step=4, label="ESM batch size")
309
+
310
+ with gr.Row():
311
+ text = gr.Textbox(label="Manual input (FASTA or one-per-line)",
312
+ placeholder=">seq1\nKLAKLAK...\n>seq2\nGIGKFLHSAKKFGKAFVGEIMNS...",
313
+ lines=10)
314
+ with gr.Column():
315
+ csv_upl = gr.File(label="Upload CSV (must have column: peptide_sequence)", file_types=[".csv"])
316
+ fasta_upl = gr.File(label="Upload FASTA", file_types=[".fa",".fasta",".faa",".txt"])
317
+
318
+ run_btn = gr.Button("Predict", variant="primary")
319
+
320
+ with gr.Row():
321
+ df_out = gr.Dataframe(label="Predictions", interactive=False, wrap=True)
322
+ with gr.Row():
323
+ csv_dl = gr.File(label="Download predictions.csv")
324
+ fig_out = gr.Plot(label="Predicted label counts (CSV/FASTA only)")
325
+ status = gr.Markdown()
326
+
327
+ def clear_conflicts(m):
328
+ """Simple UX helper: when a mode is chosen, ignore the other inputs visually.
329
+ (No need to erase files; we just use the selected mode inside run_predict)."""
330
+ return f"Active input mode: **{m}** (other inputs are ignored)."
331
+
332
+ mode.change(fn=clear_conflicts, inputs=mode, outputs=status)
333
+ run_btn.click(fn=run_predict,
334
+ inputs=[mode, text, csv_upl, fasta_upl, batch_size],
335
+ outputs=[df_out, csv_dl, fig_out, status])
336
+
337
+ if __name__ == "__main__":
338
+ demo.launch()
best_ensemble_cd.joblib ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a6f6b9e1e603935fc30b44cfa93133d818fede36012068322639a71d7bad037e
3
+ size 2225457
predictions_ensemble_cd.csv ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ peptide_sequence,probability,prediction
2
+ SWK,0.006712601044863002,0
3
+ ACH,0.6495699989862738,1
4
+ FYS,0.17982166052450652,0
5
+ MIH,0.0014278786895917316,0
requirements.txt ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ streamlit
2
+ pandas
3
+ numpy
4
+ scikit-learn
5
+ torch
6
+ transformers
7
+ matplotlib
8
+ modlamp
9
+ joblib