Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,4 +1,5 @@
|
|
1 |
-
|
|
|
2 |
|
3 |
import os
|
4 |
import torch
|
@@ -10,17 +11,15 @@ import gradio as gr
|
|
10 |
from sklearn.cluster import KMeans
|
11 |
from tqdm import tqdm
|
12 |
import transformers
|
13 |
-
import argparse # We won't use argparse but might need it for compatibility if any function expects it
|
14 |
|
15 |
# Suppress verbose logging from transformers
|
16 |
transformers.logging.set_verbosity_error()
|
17 |
|
18 |
# --------------------------------------------------------------------------
|
19 |
# SECTION 1: CORE CLASS AND FUNCTION DEFINITIONS
|
20 |
-
# These definitions are now synchronized with your provided, working scripts.
|
21 |
# --------------------------------------------------------------------------
|
22 |
|
23 |
-
# --- Vocabulary Definition
|
24 |
AMINO_ACIDS = "ACDEFGHIKLMNPQRSTVWY"
|
25 |
token2id = {aa: i + 2 for i, aa in enumerate(AMINO_ACIDS)}
|
26 |
token2id["<PAD>"] = 0
|
@@ -28,62 +27,69 @@ token2id["<EOS>"] = 1
|
|
28 |
id2token = {i: t for t, i in token2id.items()}
|
29 |
VOCAB_SIZE = len(token2id)
|
30 |
|
31 |
-
# ---
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
32 |
class AntioxidantPredictor(nn.Module):
|
33 |
def __init__(self, input_dim, transformer_layers=3, transformer_heads=4, transformer_dropout=0.1):
|
34 |
super(AntioxidantPredictor, self).__init__()
|
35 |
self.prott5_dim = 1024
|
36 |
self.handcrafted_dim = input_dim - self.prott5_dim
|
37 |
self.seq_len = 16
|
38 |
-
self.prott5_feature_dim = 64
|
39 |
-
|
40 |
-
encoder_layer = nn.TransformerEncoderLayer(
|
41 |
-
d_model=self.prott5_feature_dim,
|
42 |
-
nhead=transformer_heads,
|
43 |
-
dropout=transformer_dropout,
|
44 |
-
batch_first=True
|
45 |
-
)
|
46 |
self.transformer_encoder = nn.TransformerEncoder(encoder_layer, num_layers=transformer_layers)
|
47 |
-
|
48 |
fused_dim = self.prott5_feature_dim + self.handcrafted_dim
|
49 |
-
self.fusion_fc = nn.Sequential(
|
50 |
-
|
51 |
-
nn.ReLU(),
|
52 |
-
nn.Dropout(0.3),
|
53 |
-
nn.Linear(1024, 512),
|
54 |
-
nn.ReLU(),
|
55 |
-
nn.Dropout(0.3)
|
56 |
-
)
|
57 |
-
|
58 |
-
self.classifier = nn.Sequential(
|
59 |
-
nn.Linear(512, 256),
|
60 |
-
nn.ReLU(),
|
61 |
-
nn.Dropout(0.3),
|
62 |
-
nn.Linear(256, 1)
|
63 |
-
)
|
64 |
self.temperature = nn.Parameter(torch.ones(1), requires_grad=False)
|
65 |
-
|
66 |
def forward(self, x, *args):
|
67 |
batch_size = x.size(0)
|
68 |
prot_t5_features = x[:, :self.prott5_dim]
|
69 |
handcrafted_features = x[:, self.prott5_dim:]
|
70 |
-
|
71 |
prot_t5_seq = prot_t5_features.view(batch_size, self.seq_len, self.prott5_feature_dim)
|
72 |
encoded_seq = self.transformer_encoder(prot_t5_seq)
|
73 |
refined_prott5 = encoded_seq.mean(dim=1)
|
74 |
-
|
75 |
fused_features = torch.cat([refined_prott5, handcrafted_features], dim=1)
|
76 |
fused_features = self.fusion_fc(fused_features)
|
77 |
-
|
78 |
logits = self.classifier(fused_features)
|
79 |
-
|
80 |
-
|
81 |
-
|
82 |
-
def set_temperature(self, temp_value, device):
|
83 |
-
self.temperature = nn.Parameter(torch.tensor([temp_value], device=device), requires_grad=False)
|
84 |
-
|
85 |
-
def get_temperature(self):
|
86 |
-
return self.temperature.item()
|
87 |
|
88 |
# --- Generator Model Architecture (Copied VERBATIM from your generator.py) ---
|
89 |
class ProtT5Generator(nn.Module):
|
|
|
1 |
+
|
2 |
+
# app.py - RLAnOxPeptide Gradio Web Application (FINAL CORRECTED VERSION - Robust Loading)
|
3 |
|
4 |
import os
|
5 |
import torch
|
|
|
11 |
from sklearn.cluster import KMeans
|
12 |
from tqdm import tqdm
|
13 |
import transformers
|
|
|
14 |
|
15 |
# Suppress verbose logging from transformers
|
16 |
transformers.logging.set_verbosity_error()
|
17 |
|
18 |
# --------------------------------------------------------------------------
|
19 |
# SECTION 1: CORE CLASS AND FUNCTION DEFINITIONS
|
|
|
20 |
# --------------------------------------------------------------------------
|
21 |
|
22 |
+
# --- Vocabulary Definition ---
|
23 |
AMINO_ACIDS = "ACDEFGHIKLMNPQRSTVWY"
|
24 |
token2id = {aa: i + 2 for i, aa in enumerate(AMINO_ACIDS)}
|
25 |
token2id["<PAD>"] = 0
|
|
|
27 |
id2token = {i: t for t, i in token2id.items()}
|
28 |
VOCAB_SIZE = len(token2id)
|
29 |
|
30 |
+
# --- ROBUST FeatureProtT5Model Class for Feature Extraction ---
|
31 |
+
class FeatureProtT5Model:
|
32 |
+
def __init__(self, model_dir_path, finetuned_weights_path=None):
|
33 |
+
self.device = "cuda" if torch.cuda.is_available() else "cpu"
|
34 |
+
print(f"Initializing ProtT5 from base directory: {model_dir_path}")
|
35 |
+
|
36 |
+
# Step 1: Load the base model architecture and tokenizer from the directory.
|
37 |
+
# This step requires the original pytorch_model.bin to be in the model_dir_path.
|
38 |
+
self.tokenizer = transformers.T5Tokenizer.from_pretrained(model_dir_path, do_lower_case=False)
|
39 |
+
self.model = transformers.T5EncoderModel.from_pretrained(model_dir_path)
|
40 |
+
|
41 |
+
# Step 2: If a separate fine-tuned weights file is provided, load it.
|
42 |
+
if finetuned_weights_path and os.path.exists(finetuned_weights_path):
|
43 |
+
print(f"Loading and applying fine-tuned weights from: {finetuned_weights_path}")
|
44 |
+
# Load the state_dict from your specific fine-tuned file
|
45 |
+
state_dict = torch.load(finetuned_weights_path, map_location=self.device)
|
46 |
+
# Use strict=False because the fine-tuned model may only contain encoder weights
|
47 |
+
self.model.load_state_dict(state_dict, strict=False)
|
48 |
+
print("Successfully applied fine-tuned weights to the model.")
|
49 |
+
else:
|
50 |
+
print("Warning: Fine-tuned weights file not provided or not found. Using the base ProtT5 model weights.")
|
51 |
+
|
52 |
+
self.model.to(self.device)
|
53 |
+
self.model.eval()
|
54 |
+
|
55 |
+
def encode(self, sequence):
|
56 |
+
if not sequence or not isinstance(sequence, str):
|
57 |
+
return np.zeros((1, 1024), dtype=np.float32)
|
58 |
+
seq_spaced = " ".join(list(sequence))
|
59 |
+
encoded_input = self.tokenizer(seq_spaced, return_tensors='pt', padding=True, truncation=True, max_length=1022)
|
60 |
+
encoded_input = {k: v.to(self.device) for k, v in encoded_input.items()}
|
61 |
+
with torch.no_grad():
|
62 |
+
embedding = self.model(**encoded_input).last_hidden_state
|
63 |
+
emb = embedding.squeeze(0).cpu().numpy()
|
64 |
+
return emb if emb.shape[0] > 0 else np.zeros((1, 1024), dtype=np.float32)
|
65 |
+
|
66 |
+
# --- Predictor Model Architecture ---
|
67 |
class AntioxidantPredictor(nn.Module):
|
68 |
def __init__(self, input_dim, transformer_layers=3, transformer_heads=4, transformer_dropout=0.1):
|
69 |
super(AntioxidantPredictor, self).__init__()
|
70 |
self.prott5_dim = 1024
|
71 |
self.handcrafted_dim = input_dim - self.prott5_dim
|
72 |
self.seq_len = 16
|
73 |
+
self.prott5_feature_dim = 64
|
74 |
+
encoder_layer = nn.TransformerEncoderLayer(d_model=self.prott5_feature_dim, nhead=transformer_heads, dropout=transformer_dropout, batch_first=.T.rue)
|
|
|
|
|
|
|
|
|
|
|
|
|
75 |
self.transformer_encoder = nn.TransformerEncoder(encoder_layer, num_layers=transformer_layers)
|
|
|
76 |
fused_dim = self.prott5_feature_dim + self.handcrafted_dim
|
77 |
+
self.fusion_fc = nn.Sequential(nn.Linear(fused_dim, 1024), nn.ReLU(), nn.Dropout(0.3), nn.Linear(1024, 512), nn.ReLU(), nn.Dropout(0.3))
|
78 |
+
self.classifier = nn.Sequential(nn.Linear(512, 256), nn.ReLU(), nn.Dropout(0.3), nn.Linear(256, 1))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
79 |
self.temperature = nn.Parameter(torch.ones(1), requires_grad=False)
|
|
|
80 |
def forward(self, x, *args):
|
81 |
batch_size = x.size(0)
|
82 |
prot_t5_features = x[:, :self.prott5_dim]
|
83 |
handcrafted_features = x[:, self.prott5_dim:]
|
|
|
84 |
prot_t5_seq = prot_t5_features.view(batch_size, self.seq_len, self.prott5_feature_dim)
|
85 |
encoded_seq = self.transformer_encoder(prot_t5_seq)
|
86 |
refined_prott5 = encoded_seq.mean(dim=1)
|
|
|
87 |
fused_features = torch.cat([refined_prott5, handcrafted_features], dim=1)
|
88 |
fused_features = self.fusion_fc(fused_features)
|
|
|
89 |
logits = self.classifier(fused_features)
|
90 |
+
return logits / self.temperature
|
91 |
+
def set_temperature(self, temp_value, device): self.temperature = nn.Parameter(torch.tensor([temp_value], device=device), requires_grad=False)
|
92 |
+
def get_temperature(self): return self.temperature.item()
|
|
|
|
|
|
|
|
|
|
|
93 |
|
94 |
# --- Generator Model Architecture (Copied VERBATIM from your generator.py) ---
|
95 |
class ProtT5Generator(nn.Module):
|