updated app.py
Browse files
app.py
CHANGED
|
@@ -10,6 +10,7 @@ from transformers import T5Tokenizer, T5EncoderModel
|
|
| 10 |
import os
|
| 11 |
from dotenv import load_dotenv
|
| 12 |
import google.generativeai as genai
|
|
|
|
| 13 |
|
| 14 |
load_dotenv()
|
| 15 |
GEMINI_API_KEY = os.getenv("GEMINI_API_KEY")
|
|
@@ -39,112 +40,6 @@ st.set_page_config(
|
|
| 39 |
initial_sidebar_state="expanded"
|
| 40 |
)
|
| 41 |
|
| 42 |
-
class BioCLIP(nn.Module):
|
| 43 |
-
def __init__(self, seq_dim=1024, text_dim=768, shared_dim=512):
|
| 44 |
-
super().__init__()
|
| 45 |
-
self.seq_projector = nn.Sequential(
|
| 46 |
-
nn.Linear(seq_dim, shared_dim),
|
| 47 |
-
nn.GELU(),
|
| 48 |
-
nn.Dropout(0.1),
|
| 49 |
-
nn.Linear(shared_dim, shared_dim)
|
| 50 |
-
)
|
| 51 |
-
self.text_projector = nn.Sequential(
|
| 52 |
-
nn.Linear(text_dim, shared_dim),
|
| 53 |
-
nn.GELU(),
|
| 54 |
-
nn.Dropout(0.1),
|
| 55 |
-
nn.Linear(shared_dim, shared_dim)
|
| 56 |
-
)
|
| 57 |
-
|
| 58 |
-
def forward(self, seq_emb, text_emb):
|
| 59 |
-
z_seq = F.normalize(self.seq_projector(seq_emb), p=2, dim=-1)
|
| 60 |
-
z_text = F.normalize(self.text_projector(text_emb), p=2, dim=-1)
|
| 61 |
-
return z_seq, z_text
|
| 62 |
-
|
| 63 |
-
class ProteinEmbedder:
|
| 64 |
-
def __init__(self, device="cpu"):
|
| 65 |
-
self.device = device
|
| 66 |
-
self.tokenizer = T5Tokenizer.from_pretrained("Rostlab/prot_t5_xl_uniref50", do_lower_case=False)
|
| 67 |
-
self.model = T5EncoderModel.from_pretrained("Rostlab/prot_t5_xl_uniref50").to(self.device)
|
| 68 |
-
self.model.eval()
|
| 69 |
-
|
| 70 |
-
def embed_raw_sequence(self, sequence: str):
|
| 71 |
-
seq = re.sub(r"[UZOB]", "X", sequence.upper())
|
| 72 |
-
seq_spaced = " ".join(list(seq))
|
| 73 |
-
|
| 74 |
-
with torch.no_grad():
|
| 75 |
-
ids = self.tokenizer([seq_spaced], add_special_tokens=True, padding=True, return_tensors="pt")
|
| 76 |
-
input_ids = ids['input_ids'].to(self.device)
|
| 77 |
-
attention_mask = ids['attention_mask'].to(self.device)
|
| 78 |
-
|
| 79 |
-
embedding = self.model(input_ids=input_ids, attention_mask=attention_mask)
|
| 80 |
-
seq_len = (attention_mask[0] == 1).sum()
|
| 81 |
-
protein_emb = embedding.last_hidden_state[0, :seq_len-1].mean(dim=0)
|
| 82 |
-
|
| 83 |
-
return protein_emb.cpu().numpy()
|
| 84 |
-
|
| 85 |
-
class ProtocolRecommender:
|
| 86 |
-
def __init__(self, device="cpu"):
|
| 87 |
-
self.device = device
|
| 88 |
-
self.steps = ['lysis', 'elution', 'desalting']
|
| 89 |
-
self.models = {}
|
| 90 |
-
self.databases = {}
|
| 91 |
-
|
| 92 |
-
for step in self.steps:
|
| 93 |
-
model = BioCLIP().to(self.device)
|
| 94 |
-
model.load_state_dict(torch.load(f"bioclip_weights_{step}.pth", map_location=self.device, weights_only=True), strict=False)
|
| 95 |
-
model.eval()
|
| 96 |
-
self.models[step] = model
|
| 97 |
-
|
| 98 |
-
with open(f"aligned_spaces_{step}.pkl", "rb") as f:
|
| 99 |
-
db = pickle.load(f)
|
| 100 |
-
|
| 101 |
-
text_vectors_np = np.array(db["aligned_text"])
|
| 102 |
-
kmeans = KMeans(n_clusters=15, random_state=42, n_init=10)
|
| 103 |
-
cluster_labels = kmeans.fit_predict(text_vectors_np)
|
| 104 |
-
|
| 105 |
-
self.databases[step] = {
|
| 106 |
-
"text_vectors": torch.tensor(db["aligned_text"]).float().to(self.device),
|
| 107 |
-
"raw_texts": db["raw_texts"],
|
| 108 |
-
"cluster_labels": cluster_labels
|
| 109 |
-
}
|
| 110 |
-
|
| 111 |
-
def search(self, protein_sequence_1024d, top_k=3):
|
| 112 |
-
results = {}
|
| 113 |
-
seq_tensor = torch.tensor(protein_sequence_1024d).float().unsqueeze(0).to(self.device)
|
| 114 |
-
|
| 115 |
-
with torch.no_grad():
|
| 116 |
-
for step in self.steps:
|
| 117 |
-
model = self.models[step]
|
| 118 |
-
db = self.databases[step]
|
| 119 |
-
|
| 120 |
-
z_query = F.normalize(model.seq_projector(seq_tensor), p=2, dim=-1)
|
| 121 |
-
|
| 122 |
-
similarities = (z_query @ db["text_vectors"].T).squeeze().cpu().numpy()
|
| 123 |
-
|
| 124 |
-
sorted_indices = np.argsort(similarities)[::-1]
|
| 125 |
-
|
| 126 |
-
diverse_indices = []
|
| 127 |
-
seen_clusters = set()
|
| 128 |
-
|
| 129 |
-
for idx in sorted_indices:
|
| 130 |
-
cluster_id = db["cluster_labels"][idx]
|
| 131 |
-
|
| 132 |
-
if cluster_id not in seen_clusters:
|
| 133 |
-
seen_clusters.add(cluster_id)
|
| 134 |
-
diverse_indices.append(idx)
|
| 135 |
-
|
| 136 |
-
if len(diverse_indices) == top_k:
|
| 137 |
-
break
|
| 138 |
-
|
| 139 |
-
step_results = []
|
| 140 |
-
for idx in diverse_indices:
|
| 141 |
-
step_results.append({
|
| 142 |
-
"confidence": float(similarities[idx]),
|
| 143 |
-
"text": db["raw_texts"][idx]
|
| 144 |
-
})
|
| 145 |
-
results[step] = step_results
|
| 146 |
-
return results
|
| 147 |
-
|
| 148 |
@st.cache_resource(show_spinner=False)
|
| 149 |
def load_ai_engines():
|
| 150 |
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
|
|
|
| 10 |
import os
|
| 11 |
from dotenv import load_dotenv
|
| 12 |
import google.generativeai as genai
|
| 13 |
+
from bio_clip_recommender import BioCLIP, ProteinEmbedder, ProtocolRecommender
|
| 14 |
|
| 15 |
load_dotenv()
|
| 16 |
GEMINI_API_KEY = os.getenv("GEMINI_API_KEY")
|
|
|
|
| 40 |
initial_sidebar_state="expanded"
|
| 41 |
)
|
| 42 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 43 |
@st.cache_resource(show_spinner=False)
|
| 44 |
def load_ai_engines():
|
| 45 |
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|