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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
|
| 3 |
+
# --- 1. CRITICAL SETUP FOR LEGACY KERAS ---
|
| 4 |
+
os.environ["TF_USE_LEGACY_KERAS"] = "1"
|
| 5 |
+
os.environ["TF_XLA_FLAGS"] = "--tf_xla_enable_xla_devices=false"
|
| 6 |
+
os.environ["TF_FORCE_GPU_ALLOW_GROWTH"] = "true"
|
| 7 |
+
|
| 8 |
+
import gradio as gr
|
| 9 |
+
import tensorflow as tf
|
| 10 |
+
import tf_keras as keras
|
| 11 |
+
import numpy as np
|
| 12 |
+
import pandas as pd
|
| 13 |
+
import pickle
|
| 14 |
+
import torch
|
| 15 |
+
from transformers import BertModel, BertTokenizer
|
| 16 |
+
from model import PredictModel
|
| 17 |
+
|
| 18 |
+
# Import your local helper files
|
| 19 |
+
# (These must be uploaded to the same folder as app.py)
|
| 20 |
+
from dataset import Graph_Classification_Dataset
|
| 21 |
+
from encoding import one_hot_padding, position_encoding, blosum62_padding, zscale_padding
|
| 22 |
+
|
| 23 |
+
# --- 2. CONFIGURATION ---
|
| 24 |
+
SEEDS = [2023, 2024, 2025]
|
| 25 |
+
TASK = 'PDC'
|
| 26 |
+
|
| 27 |
+
# --- 3. LOAD PROTBERT (The "Brain" for Peptides) ---
|
| 28 |
+
print("📦 Downloading/Loading ProtBERT Model... (This runs once)")
|
| 29 |
+
tokenizer = BertTokenizer.from_pretrained("Rostlab/prot_bert", do_lower_case=False)
|
| 30 |
+
bert_model = BertModel.from_pretrained("Rostlab/prot_bert")
|
| 31 |
+
|
| 32 |
+
# Move to CPU (Hugging Face Free Tier is CPU-only usually)
|
| 33 |
+
bert_model.eval()
|
| 34 |
+
|
| 35 |
+
# --- 4. HELPER FUNCTIONS ---
|
| 36 |
+
|
| 37 |
+
def get_protbert_embedding(sequence):
|
| 38 |
+
"""
|
| 39 |
+
Generates the t1 tensor dynamically for ANY peptide sequence using ProtBERT.
|
| 40 |
+
Replaces Peptide.pkl lookup.
|
| 41 |
+
"""
|
| 42 |
+
# ProtBERT expects spaces between amino acids: "A C D E"
|
| 43 |
+
spaced_sequence = " ".join(list(sequence))
|
| 44 |
+
|
| 45 |
+
# Clean sequence (remove weird chars if any)
|
| 46 |
+
spaced_sequence = re.sub(r"[UZOB]", "X", spaced_sequence)
|
| 47 |
+
|
| 48 |
+
# Tokenize
|
| 49 |
+
encoded_input = tokenizer(spaced_sequence, return_tensors='pt')
|
| 50 |
+
|
| 51 |
+
# Run Model (No Gradient needed for inference)
|
| 52 |
+
with torch.no_grad():
|
| 53 |
+
output = bert_model(**encoded_input)
|
| 54 |
+
|
| 55 |
+
# Get the Last Hidden State [1, Seq_Len, 1024]
|
| 56 |
+
# We remove the [CLS] and [SEP] tokens (first and last)
|
| 57 |
+
embedding = output.last_hidden_state
|
| 58 |
+
embedding = embedding[:, 1:-1, :]
|
| 59 |
+
|
| 60 |
+
# Convert to TensorFlow Tensor
|
| 61 |
+
tf_embedding = tf.convert_to_tensor(embedding.numpy(), dtype=tf.float32)
|
| 62 |
+
|
| 63 |
+
# Ensure shape matches [1, Seq_Len, 1024]
|
| 64 |
+
return tf_embedding
|
| 65 |
+
|
| 66 |
+
def get_t2_features(sequence, padding=71):
|
| 67 |
+
"""Replicates the logic from extract_t2 in class.py"""
|
| 68 |
+
selected_sequences = [sequence]
|
| 69 |
+
|
| 70 |
+
one_hot = one_hot_padding(selected_sequences, padding)
|
| 71 |
+
pos = position_encoding(padding)
|
| 72 |
+
blosum = blosum62_padding(selected_sequences, padding)
|
| 73 |
+
zscale = zscale_padding(selected_sequences, padding)
|
| 74 |
+
|
| 75 |
+
pos_expanded = np.expand_dims(pos, axis=0).repeat(len(selected_sequences), axis=0)
|
| 76 |
+
|
| 77 |
+
combined = np.concatenate((one_hot, pos_expanded, blosum, zscale), axis=2)
|
| 78 |
+
return tf.constant(combined, dtype=tf.float32)
|
| 79 |
+
|
| 80 |
+
def preprocess_input(payload_smiles, linker_smiles, peptide_seq):
|
| 81 |
+
# 1. Create dummy input for Graph Dataset
|
| 82 |
+
df = pd.DataFrame({
|
| 83 |
+
'Payload SMILES': [payload_smiles],
|
| 84 |
+
'Linker SMILES': [linker_smiles],
|
| 85 |
+
'label': [0],
|
| 86 |
+
'index': [0]
|
| 87 |
+
})
|
| 88 |
+
df.to_excel('temp_input.xlsx', index=False)
|
| 89 |
+
|
| 90 |
+
# 2. Get Graph Features
|
| 91 |
+
dataset_gen = Graph_Classification_Dataset(
|
| 92 |
+
'temp_input.xlsx',
|
| 93 |
+
smiles_field1='Payload SMILES',
|
| 94 |
+
smiles_field2='Linker SMILES',
|
| 95 |
+
label_field=['label'],
|
| 96 |
+
index_field=['index'],
|
| 97 |
+
seed=2023,
|
| 98 |
+
batch_size=1,
|
| 99 |
+
a=1,
|
| 100 |
+
addH=True
|
| 101 |
+
).get_data()
|
| 102 |
+
|
| 103 |
+
_, _, val_dataset = dataset_gen
|
| 104 |
+
x1, adjoin1, _, x2, adjoin2, _ = next(iter(val_dataset))
|
| 105 |
+
|
| 106 |
+
# Masks
|
| 107 |
+
seq1 = tf.cast(tf.math.equal(x1, 0), tf.float32)
|
| 108 |
+
mask1 = seq1[:, tf.newaxis, tf.newaxis, :]
|
| 109 |
+
seq2 = tf.cast(tf.math.equal(x2, 0), tf.float32)
|
| 110 |
+
mask2 = seq2[:, tf.newaxis, tf.newaxis, :]
|
| 111 |
+
|
| 112 |
+
# 3. Get Peptide Features
|
| 113 |
+
t2 = get_t2_features(peptide_seq)
|
| 114 |
+
|
| 115 |
+
# DYNAMIC GENERATION (The Fix)
|
| 116 |
+
t1 = get_protbert_embedding(peptide_seq)
|
| 117 |
+
|
| 118 |
+
return x1, mask1, adjoin1, x2, mask2, adjoin2, t1, t2
|
| 119 |
+
|
| 120 |
+
def predict_ensemble(payload, linker, peptide):
|
| 121 |
+
if not payload or not linker or not peptide:
|
| 122 |
+
return "⚠️ Please fill in all fields."
|
| 123 |
+
|
| 124 |
+
try:
|
| 125 |
+
x1, mask1, adj1, x2, mask2, adj2, t1, t2 = preprocess_input(payload, linker, peptide)
|
| 126 |
+
|
| 127 |
+
total_prob = 0.0
|
| 128 |
+
models_ran = 0
|
| 129 |
+
|
| 130 |
+
for seed in SEEDS:
|
| 131 |
+
weight_file = f'PDC_{seed}.h5'
|
| 132 |
+
if not os.path.exists(weight_file):
|
| 133 |
+
continue
|
| 134 |
+
|
| 135 |
+
keras.backend.clear_session()
|
| 136 |
+
model = PredictModel(num_layers=6, d_model=256, dff=512, num_heads=8, vocab_size=18, a=1, dense_dropout=0.4)
|
| 137 |
+
|
| 138 |
+
# Init weights
|
| 139 |
+
_ = model(x1=x1, mask1=mask1, training=False, adjoin_matrix1=adj1,
|
| 140 |
+
x2=x2, mask2=mask2, adjoin_matrix2=adj2, t1=t1, t2=t2)
|
| 141 |
+
|
| 142 |
+
model.load_weights(weight_file)
|
| 143 |
+
|
| 144 |
+
logits = model(x1=x1, mask1=mask1, training=False, adjoin_matrix1=adj1,
|
| 145 |
+
x2=x2, mask2=mask2, adjoin_matrix2=adj2, t1=t1, t2=t2)
|
| 146 |
+
|
| 147 |
+
prob = tf.sigmoid(logits).numpy()[0][0]
|
| 148 |
+
total_prob += prob
|
| 149 |
+
models_ran += 1
|
| 150 |
+
del model
|
| 151 |
+
|
| 152 |
+
if models_ran == 0:
|
| 153 |
+
return "Error: No model weights found on server."
|
| 154 |
+
|
| 155 |
+
avg_score = total_prob / models_ran
|
| 156 |
+
label = "Active PDC ✅" if avg_score > 0.5 else "Inactive ❌"
|
| 157 |
+
return f"{label}\nConfidence: {avg_score:.2%}"
|
| 158 |
+
|
| 159 |
+
except Exception as e:
|
| 160 |
+
return f"Error: {str(e)}"
|
| 161 |
+
|
| 162 |
+
# --- 5. GRADIO INTERFACE ---
|
| 163 |
+
import re # Needed for regex in protbert cleaning
|
| 164 |
+
|
| 165 |
+
with gr.Blocks(title="PDCNet Ensemble Demo") as demo:
|
| 166 |
+
gr.Markdown("# 💊 PDCNet Ensemble Predictor")
|
| 167 |
+
gr.Markdown("Predict the activity of Peptide-Drug Conjugates. Supports **Any Peptide Sequence** via live ProtBERT embedding.")
|
| 168 |
+
|
| 169 |
+
with gr.Row():
|
| 170 |
+
with gr.Column():
|
| 171 |
+
in_payload = gr.Textbox(label="Payload SMILES", placeholder="e.g. COc1cc2c...", lines=2)
|
| 172 |
+
in_linker = gr.Textbox(label="Linker SMILES", placeholder="e.g. C(=O)CCCC(=O)O", lines=2)
|
| 173 |
+
in_peptide = gr.Textbox(label="Peptide Sequence", placeholder="e.g. ACDEFGH", lines=2)
|
| 174 |
+
btn_predict = gr.Button("Predict Activity", variant="primary")
|
| 175 |
+
|
| 176 |
+
with gr.Column():
|
| 177 |
+
out_result = gr.Textbox(label="Prediction Result", lines=4)
|
| 178 |
+
|
| 179 |
+
btn_predict.click(predict_ensemble, inputs=[in_payload, in_linker, in_peptide], outputs=out_result)
|
| 180 |
+
|
| 181 |
+
demo.launch()
|