ZhaohanM commited on
Commit
91a8b2f
1 Parent(s): 791eac9

Update space

Browse files
Files changed (2) hide show
  1. app.py +218 -131
  2. requirements.txt +2 -4
app.py CHANGED
@@ -1,146 +1,233 @@
1
- import gradio as gr
2
- import numpy as np
3
- import random
4
- from diffusers import DiffusionPipeline
5
  import torch
 
 
 
 
 
 
 
6
 
7
- device = "cuda" if torch.cuda.is_available() else "cpu"
 
8
 
9
- if torch.cuda.is_available():
10
- torch.cuda.max_memory_allocated(device=device)
11
- pipe = DiffusionPipeline.from_pretrained("stabilityai/sdxl-turbo", torch_dtype=torch.float16, variant="fp16", use_safetensors=True)
12
- pipe.enable_xformers_memory_efficient_attention()
13
- pipe = pipe.to(device)
14
- else:
15
- pipe = DiffusionPipeline.from_pretrained("stabilityai/sdxl-turbo", use_safetensors=True)
16
- pipe = pipe.to(device)
17
 
18
- MAX_SEED = np.iinfo(np.int32).max
19
- MAX_IMAGE_SIZE = 1024
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
 
21
- def infer(prompt, negative_prompt, seed, randomize_seed, width, height, guidance_scale, num_inference_steps):
 
22
 
23
- if randomize_seed:
24
- seed = random.randint(0, MAX_SEED)
25
-
26
- generator = torch.Generator().manual_seed(seed)
27
-
28
- image = pipe(
29
- prompt = prompt,
30
- negative_prompt = negative_prompt,
31
- guidance_scale = guidance_scale,
32
- num_inference_steps = num_inference_steps,
33
- width = width,
34
- height = height,
35
- generator = generator
36
- ).images[0]
37
-
38
- return image
39
-
40
- examples = [
41
- "Astronaut in a jungle, cold color palette, muted colors, detailed, 8k",
42
- "An astronaut riding a green horse",
43
- "A delicious ceviche cheesecake slice",
44
- ]
45
-
46
- css="""
47
- #col-container {
48
- margin: 0 auto;
49
- max-width: 520px;
50
- }
51
- """
52
-
53
- if torch.cuda.is_available():
54
- power_device = "GPU"
55
- else:
56
- power_device = "CPU"
57
-
58
- with gr.Blocks(css=css) as demo:
59
-
60
- with gr.Column(elem_id="col-container"):
61
- gr.Markdown(f"""
62
- # Text-to-Image Gradio Template
63
- Currently running on {power_device}.
64
- """)
65
-
66
- with gr.Row():
67
-
68
- prompt = gr.Text(
69
- label="Prompt",
70
- show_label=False,
71
- max_lines=1,
72
- placeholder="Enter your prompt",
73
- container=False,
74
- )
75
 
76
- run_button = gr.Button("Run", scale=0)
77
-
78
- result = gr.Image(label="Result", show_label=False)
79
 
80
- with gr.Accordion("Advanced Settings", open=False):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81
 
82
- negative_prompt = gr.Text(
83
- label="Negative prompt",
84
- max_lines=1,
85
- placeholder="Enter a negative prompt",
86
- visible=False,
87
- )
88
 
89
- seed = gr.Slider(
90
- label="Seed",
91
- minimum=0,
92
- maximum=MAX_SEED,
93
- step=1,
94
- value=0,
95
- )
96
 
97
- randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
 
98
 
99
- with gr.Row():
100
-
101
- width = gr.Slider(
102
- label="Width",
103
- minimum=256,
104
- maximum=MAX_IMAGE_SIZE,
105
- step=32,
106
- value=512,
107
- )
108
-
109
- height = gr.Slider(
110
- label="Height",
111
- minimum=256,
112
- maximum=MAX_IMAGE_SIZE,
113
- step=32,
114
- value=512,
115
- )
116
 
117
- with gr.Row():
118
-
119
- guidance_scale = gr.Slider(
120
- label="Guidance scale",
121
- minimum=0.0,
122
- maximum=10.0,
123
- step=0.1,
124
- value=0.0,
125
- )
126
-
127
- num_inference_steps = gr.Slider(
128
- label="Number of inference steps",
129
- minimum=1,
130
- maximum=12,
131
- step=1,
132
- value=2,
133
- )
134
-
135
- gr.Examples(
136
- examples = examples,
137
- inputs = [prompt]
138
- )
139
-
140
- run_button.click(
141
- fn = infer,
142
- inputs = [prompt, negative_prompt, seed, randomize_seed, width, height, guidance_scale, num_inference_steps],
143
- outputs = [result]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
144
  )
 
 
 
 
 
 
145
 
146
- demo.queue().launch()
 
 
1
+ import os
2
+ import sys
3
+ import argparse
 
4
  import torch
5
+ from torch.utils.data import DataLoader
6
+ from transformers import EsmForMaskedLM, AutoModel, EsmTokenizer
7
+ from utils.drug_tokenizer import DrugTokenizer
8
+ from utils.metric_learning_models_att_maps import Pre_encoded, FusionDTI
9
+ from bertviz import head_view
10
+ import tempfile
11
+ from flask import Flask, request, render_template_string
12
 
13
+ os.environ["TOKENIZERS_PARALLELISM"] = "false"
14
+ sys.path.append("../")
15
 
16
+ app = Flask(__name__)
 
 
 
 
 
 
 
17
 
18
+ def parse_config():
19
+ parser = argparse.ArgumentParser()
20
+ parser.add_argument('-f')
21
+ parser.add_argument("--prot_encoder_path", type=str, default="westlake-repl/SaProt_650M_AF2", help="path/name of protein encoder model located")
22
+ parser.add_argument("--drug_encoder_path", type=str, default="HUBioDataLab/SELFormer", help="path/name of SMILE pre-trained language model")
23
+ parser.add_argument("--agg_mode", default="mean_all_tok", type=str, help="{cls|mean|mean_all_tok}")
24
+ parser.add_argument("--fusion", default="CAN", type=str, help="{CAN|BAN}")
25
+ parser.add_argument("--batch_size", type=int, default=64)
26
+ parser.add_argument("--group_size", type=int, default=1)
27
+ parser.add_argument("--lr", type=float, default=1e-4)
28
+ parser.add_argument("--dropout", type=float, default=0.1)
29
+ parser.add_argument("--test", type=int, default=0)
30
+ parser.add_argument("--use_pooled", action="store_true", default=True)
31
+ parser.add_argument("--device", type=str, default="cuda" if torch.cuda.is_available() else "cpu")
32
+ parser.add_argument("--save_path_prefix", type=str, default="save_model_ckp/", help="save the result in which directory")
33
+ parser.add_argument("--save_name", default="fine_tune", type=str, help="the name of the saved file")
34
+ parser.add_argument("--dataset", type=str, default="Human", help="Name of the dataset to use (e.g., 'BindingDB', 'Human', 'Biosnap')")
35
+ return parser.parse_args()
36
 
37
+ args = parse_config()
38
+ device = args.device
39
 
40
+ prot_tokenizer = EsmTokenizer.from_pretrained(args.prot_encoder_path)
41
+ drug_tokenizer = DrugTokenizer()
42
+
43
+ prot_model = EsmForMaskedLM.from_pretrained(args.prot_encoder_path)
44
+ drug_model = AutoModel.from_pretrained(args.drug_encoder_path)
45
+
46
+ encoding = Pre_encoded(prot_model, drug_model, args).to(device)
47
+
48
+ def get_case_feature(model, dataloader, device):
49
+ with torch.no_grad():
50
+ for step, batch in enumerate(dataloader):
51
+ prot_input_ids, prot_attention_mask, drug_input_ids, drug_attention_mask, label = batch
52
+ prot_input_ids, prot_attention_mask, drug_input_ids, drug_attention_mask = \
53
+ prot_input_ids.to(device), prot_attention_mask.to(device), drug_input_ids.to(device), drug_attention_mask.to(device)
54
+
55
+ prot_embed, drug_embed = model.encoding(prot_input_ids, prot_attention_mask, drug_input_ids, drug_attention_mask)
56
+ prot_embed, drug_embed = prot_embed.cpu(), drug_embed.cpu()
57
+ prot_input_ids, drug_input_ids = prot_input_ids.cpu(), drug_input_ids.cpu()
58
+ prot_attention_mask, drug_attention_mask = prot_attention_mask.cpu(), drug_attention_mask.cpu()
59
+ label = label.cpu()
60
+
61
+ return [(prot_embed, drug_embed, prot_input_ids, drug_input_ids, prot_attention_mask, drug_attention_mask, label)]
62
+
63
+ def visualize_attention(model, case_features, device, prot_tokenizer, drug_tokenizer):
64
+ model.eval()
65
+ with torch.no_grad():
66
+ for batch in case_features:
67
+ prot, drug, prot_ids, drug_ids, prot_mask, drug_mask, label = batch
68
+ prot, drug = prot.to(device), drug.to(device)
69
+ prot_mask, drug_mask = prot_mask.to(device), drug_mask.to(device)
70
+
71
+ output, attention_weights = model(prot, drug, prot_mask, drug_mask)
72
+ prot_tokens = [prot_tokenizer.decode([pid.item()], skip_special_tokens=True) for pid in prot_ids.squeeze()]
73
+ drug_tokens = [drug_tokenizer.decode([did.item()], skip_special_tokens=True) for did in drug_ids.squeeze()]
74
+ tokens = prot_tokens + drug_tokens
75
+
76
+ attention_weights = attention_weights.unsqueeze(1)
77
+
78
+ # Generate HTML content using head_view with html_action='return'
79
+ html_head_view = head_view(attention_weights, tokens, sentence_b_start=512, html_action='return')
80
+
81
+ # Parse the HTML and modify it to replace sentence labels
82
+ html_content = html_head_view.data
83
+ html_content = html_content.replace("Sentence A -> Sentence A", "Protein -> Protein")
84
+ html_content = html_content.replace("Sentence B -> Sentence B", "Drug -> Drug")
85
+ html_content = html_content.replace("Sentence A -> Sentence B", "Protein -> Drug")
86
+ html_content = html_content.replace("Sentence B -> Sentence A", "Drug -> Protein")
87
+
88
+ # Save the modified HTML content to a temporary file
89
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".html") as f:
90
+ f.write(html_content.encode('utf-8'))
91
+ temp_file_path = f.name
92
 
93
+ return temp_file_path
 
 
94
 
95
+ @app.route('/', methods=['GET', 'POST'])
96
+ def index():
97
+ protein_sequence = ""
98
+ drug_sequence = ""
99
+ result = None
100
+
101
+ if request.method == 'POST':
102
+ if 'clear' in request.form:
103
+ protein_sequence = ""
104
+ drug_sequence = ""
105
+ else:
106
+ protein_sequence = request.form['protein_sequence']
107
+ drug_sequence = request.form['drug_sequence']
108
+
109
+ dataset = [(protein_sequence, drug_sequence, 1)]
110
+ dataloader = DataLoader(dataset, batch_size=1, collate_fn=collate_fn_batch_encoding)
111
 
112
+ case_features = get_case_feature(encoding, dataloader, device)
113
+ model = FusionDTI(446, 768, args).to(device)
 
 
 
 
114
 
115
+ best_model_dir = f"{args.save_path_prefix}{args.dataset}_{args.fusion}"
116
+ checkpoint_path = os.path.join(best_model_dir, 'best_model.ckpt')
 
 
 
 
 
117
 
118
+ if os.path.exists(checkpoint_path):
119
+ model.load_state_dict(torch.load(checkpoint_path, map_location=device))
120
 
121
+ html_file_path = visualize_attention(model, case_features, device, prot_tokenizer, drug_tokenizer)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
122
 
123
+ with open(html_file_path, 'r') as f:
124
+ result = f.read()
125
+
126
+ return render_template_string('''
127
+ <html>
128
+ <head>
129
+ <title>Drug Target Interaction Visualization</title>
130
+ <style>
131
+ body { font-family: 'Times New Roman', Times, serif; margin: 40px; }
132
+ h2 { color: #333; }
133
+ .container { display: flex; }
134
+ .left { flex: 1; padding-right: 20px; }
135
+ .right { flex: 1; }
136
+ textarea {
137
+ width: 100%;
138
+ padding: 12px 20px;
139
+ margin: 8px 0;
140
+ display: inline-block;
141
+ border: 1px solid #ccc;
142
+ border-radius: 4px;
143
+ box-sizing: border-box;
144
+ font-size: 16px;
145
+ font-family: 'Times New Roman', Times, serif;
146
+ }
147
+ .button-container {
148
+ display: flex;
149
+ justify-content: space-between;
150
+ }
151
+ input[type="submit"], .button {
152
+ width: 48%;
153
+ color: white;
154
+ padding: 14px 20px;
155
+ margin: 8px 0;
156
+ border: none;
157
+ border-radius: 4px;
158
+ cursor: pointer;
159
+ font-size: 16px;
160
+ font-family: 'Times New Roman', Times, serif;
161
+ }
162
+ .submit {
163
+ background-color: #FFA500;
164
+ }
165
+ .submit:hover {
166
+ background-color: #FF8C00;
167
+ }
168
+ .clear {
169
+ background-color: #D3D3D3;
170
+ }
171
+ .clear:hover {
172
+ background-color: #A9A9A9;
173
+ }
174
+ .result {
175
+ font-size: 18px;
176
+ }
177
+ </style>
178
+ </head>
179
+ <body>
180
+ <h2 style="text-align: center;">Drug Target Interaction Visualization</h2>
181
+ <div class="container">
182
+ <div class="left">
183
+ <form method="post">
184
+ <label for="protein_sequence">Protein Sequence:</label>
185
+ <textarea id="protein_sequence" name="protein_sequence" rows="4" placeholder="Enter protein sequence here..." required>{{ protein_sequence }}</textarea><br>
186
+ <label for="drug_sequence">Drug Sequence:</label>
187
+ <textarea id="drug_sequence" name="drug_sequence" rows="4" placeholder="Enter drug sequence here..." required>{{ drug_sequence }}</textarea><br>
188
+ <div class="button-container">
189
+ <input type="submit" name="submit" class="button submit" value="Submit">
190
+ <input type="submit" name="clear" class="button clear" value="Clear">
191
+ </div>
192
+ </form>
193
+ </div>
194
+ <div class="right" style="display: flex; justify-content: center; align-items: center;">
195
+ {% if result %}
196
+ <div class="result">
197
+ {{ result|safe }}
198
+ </div>
199
+ {% endif %}
200
+ </div>
201
+ </div>
202
+ </body>
203
+ </html>
204
+ ''', protein_sequence=protein_sequence, drug_sequence=drug_sequence, result=result)
205
+
206
+ def collate_fn_batch_encoding(batch):
207
+ query1, query2, scores = zip(*batch)
208
+
209
+ query_encodings1 = prot_tokenizer.batch_encode_plus(
210
+ list(query1),
211
+ max_length=512,
212
+ padding="max_length",
213
+ truncation=True,
214
+ add_special_tokens=True,
215
+ return_tensors="pt",
216
+ )
217
+ query_encodings2 = drug_tokenizer.batch_encode_plus(
218
+ list(query2),
219
+ max_length=512,
220
+ padding="max_length",
221
+ truncation=True,
222
+ add_special_tokens=True,
223
+ return_tensors="pt",
224
  )
225
+ scores = torch.tensor(list(scores))
226
+
227
+ attention_mask1 = query_encodings1["attention_mask"].bool()
228
+ attention_mask2 = query_encodings2["attention_mask"].bool()
229
+
230
+ return query_encodings1["input_ids"], attention_mask1, query_encodings2["input_ids"], attention_mask2, scores
231
 
232
+ if __name__ == '__main__':
233
+ app.run(debug=True, host='127.0.0.1', port=7860)
requirements.txt CHANGED
@@ -1,6 +1,4 @@
1
- accelerate
2
- diffusers
3
- invisible_watermark
4
  torch
5
  transformers
6
- xformers
 
1
+ Flask
 
 
2
  torch
3
  transformers
4
+ bertviz