Update app_new.py
Browse files- app_new.py +117 -0
app_new.py
CHANGED
@@ -0,0 +1,117 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
import pandas as pd
|
3 |
+
import torch
|
4 |
+
from transformers import AutoTokenizer, AutoModelForMaskedLM
|
5 |
+
import logging
|
6 |
+
import numpy as np
|
7 |
+
import matplotlib.pyplot as plt
|
8 |
+
import seaborn as sns
|
9 |
+
from io import BytesIO
|
10 |
+
from PIL import Image
|
11 |
+
|
12 |
+
logging.getLogger("transformers.modeling_utils").setLevel(logging.ERROR)
|
13 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
14 |
+
print(f"Using device: {device}")
|
15 |
+
|
16 |
+
# Load the tokenizer and model
|
17 |
+
model_name = "ChatterjeeLab/FusOn-pLM"
|
18 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
|
19 |
+
model = AutoModelForMaskedLM.from_pretrained(model_name, trust_remote_code=True)
|
20 |
+
model.to(device)
|
21 |
+
model.eval()
|
22 |
+
|
23 |
+
def process_sequence(sequence, domain_bounds, n):
|
24 |
+
start_index = int(domain_bounds['start'][0]) - 1
|
25 |
+
end_index = int(domain_bounds['end'][0])
|
26 |
+
|
27 |
+
top_n_mutations = {}
|
28 |
+
all_logits = []
|
29 |
+
|
30 |
+
for i in range(len(sequence)):
|
31 |
+
if start_index <= i <= end_index:
|
32 |
+
masked_seq = sequence[:i] + '<mask>' + sequence[i+1:]
|
33 |
+
inputs = tokenizer(masked_seq, return_tensors="pt", padding=True, truncation=True, max_length=2000)
|
34 |
+
inputs = {k: v.to(device) for k, v in inputs.items()}
|
35 |
+
with torch.no_grad():
|
36 |
+
logits = model(**inputs).logits
|
37 |
+
mask_token_index = torch.where(inputs["input_ids"] == tokenizer.mask_token_id)[1]
|
38 |
+
mask_token_logits = logits[0, mask_token_index, :]
|
39 |
+
# Decode top n tokens
|
40 |
+
top_n_tokens = torch.topk(mask_token_logits, n, dim=1).indices[0].tolist()
|
41 |
+
mutation = [tokenizer.decode([token]) for token in top_n_tokens]
|
42 |
+
top_n_mutations[(sequence[i], i)] = mutation
|
43 |
+
|
44 |
+
logits_array = mask_token_logits.cpu().numpy()
|
45 |
+
# filter out non-amino acid tokens
|
46 |
+
filtered_indices = list(range(4, 23 + 1))
|
47 |
+
filtered_logits = logits_array[:, filtered_indices]
|
48 |
+
all_logits.append(filtered_logits)
|
49 |
+
|
50 |
+
token_indices = torch.arange(logits.size(-1))
|
51 |
+
tokens = [tokenizer.decode([idx]) for idx in token_indices]
|
52 |
+
filtered_tokens = [tokens[i] for i in filtered_indices]
|
53 |
+
|
54 |
+
all_logits_array = np.vstack(all_logits)
|
55 |
+
normalized_logits_array = (all_logits_array - all_logits_array.min()) / (all_logits_array.max() - all_logits_array.min())
|
56 |
+
transposed_logits_array = normalized_logits_array.T
|
57 |
+
|
58 |
+
# Plotting the heatmap
|
59 |
+
step = 50
|
60 |
+
y_tick_positions = np.arange(0, len(sequence), step)
|
61 |
+
y_tick_labels = [str(pos) for pos in y_tick_positions]
|
62 |
+
|
63 |
+
plt.figure(figsize=(15, 8))
|
64 |
+
sns.heatmap(transposed_logits_array, cmap='plasma', xticklabels=y_tick_labels, yticklabels=filtered_tokens)
|
65 |
+
plt.title('Logits for masked per residue tokens')
|
66 |
+
plt.ylabel('Token')
|
67 |
+
plt.xlabel('Residue Index')
|
68 |
+
plt.yticks(rotation=0)
|
69 |
+
plt.xticks(y_tick_positions, y_tick_labels, rotation = 0)
|
70 |
+
|
71 |
+
# Save the figure to a BytesIO object
|
72 |
+
buf = BytesIO()
|
73 |
+
plt.savefig(buf, format='png')
|
74 |
+
buf.seek(0)
|
75 |
+
plt.close()
|
76 |
+
|
77 |
+
# Convert BytesIO object to an image
|
78 |
+
img = Image.open(buf)
|
79 |
+
|
80 |
+
original_residues = []
|
81 |
+
mutations = []
|
82 |
+
positions = []
|
83 |
+
|
84 |
+
for key, value in top_n_mutations.items():
|
85 |
+
original_residue, position = key
|
86 |
+
original_residues.append(original_residue)
|
87 |
+
mutations.append(value)
|
88 |
+
positions.append(position + 1)
|
89 |
+
|
90 |
+
df = pd.DataFrame({
|
91 |
+
'Original Residue': original_residues,
|
92 |
+
'Predicted Residues (in order of decreasing likelihood)': mutations,
|
93 |
+
'Position': positions
|
94 |
+
})
|
95 |
+
|
96 |
+
df = df[start_index:end_index]
|
97 |
+
|
98 |
+
return df, img
|
99 |
+
|
100 |
+
demo = gr.Interface(
|
101 |
+
fn=process_sequence,
|
102 |
+
inputs=[
|
103 |
+
"text",
|
104 |
+
gr.Dataframe(
|
105 |
+
headers=["start", "end"],
|
106 |
+
datatype=["number", "number"],
|
107 |
+
row_count=(1, "fixed"),
|
108 |
+
col_count=(2, "fixed"),
|
109 |
+
),
|
110 |
+
gr.Dropdown([i for i in range(1, 21)]), # Dropdown with numbers from 1 to 20 as integers
|
111 |
+
],
|
112 |
+
outputs=["dataframe", "image"],
|
113 |
+
description="Choose a number between 1-20 to predict n tokens for each position. Choose the start and end index of the domain of interest (indexing starts at 1).",
|
114 |
+
)
|
115 |
+
|
116 |
+
if __name__ == "__main__":
|
117 |
+
demo.launch()
|