Spaces:
Running
Running
ThorbenFroehlking
commited on
Commit
·
2460e63
1
Parent(s):
06bab06
Updated
Browse files- .ipynb_checkpoints/app-checkpoint.py +2 -3
- .ipynb_checkpoints/requirements-checkpoint.txt +2 -1
- app-Copy1.py +537 -0
- app.py +2 -3
- requirements.txt +2 -1
.ipynb_checkpoints/app-checkpoint.py
CHANGED
@@ -7,7 +7,7 @@ from Bio.SeqUtils import seq1
|
|
7 |
from typing import Optional, Tuple
|
8 |
import numpy as np
|
9 |
import os
|
10 |
-
from gradio_molecule3d import Molecule3D
|
11 |
|
12 |
from model_loader import load_model
|
13 |
|
@@ -533,5 +533,4 @@ with gr.Blocks(css="""
|
|
533 |
outputs=[predictions_output, molecule_output, download_output]
|
534 |
)
|
535 |
|
536 |
-
|
537 |
-
demo.launch()
|
|
|
7 |
from typing import Optional, Tuple
|
8 |
import numpy as np
|
9 |
import os
|
10 |
+
#from gradio_molecule3d import Molecule3D
|
11 |
|
12 |
from model_loader import load_model
|
13 |
|
|
|
533 |
outputs=[predictions_output, molecule_output, download_output]
|
534 |
)
|
535 |
|
536 |
+
demo.launch(share=True)
|
|
.ipynb_checkpoints/requirements-checkpoint.txt
CHANGED
@@ -10,4 +10,5 @@ sentencepiece
|
|
10 |
huggingface_hub>=0.15.0
|
11 |
requests
|
12 |
gradio_molecule3d
|
13 |
-
biopython>=1.81
|
|
|
|
10 |
huggingface_hub>=0.15.0
|
11 |
requests
|
12 |
gradio_molecule3d
|
13 |
+
biopython>=1.81
|
14 |
+
pydantic==1.10.13
|
app-Copy1.py
ADDED
@@ -0,0 +1,537 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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B.Polypeptide import is_aa
|
6 |
+
from Bio.SeqUtils import seq1
|
7 |
+
from typing import Optional, Tuple
|
8 |
+
import numpy as np
|
9 |
+
import os
|
10 |
+
from gradio_molecule3d import Molecule3D
|
11 |
+
|
12 |
+
from model_loader import load_model
|
13 |
+
|
14 |
+
import torch
|
15 |
+
import torch.nn as nn
|
16 |
+
import torch.nn.functional as F
|
17 |
+
from torch.utils.data import DataLoader
|
18 |
+
|
19 |
+
import re
|
20 |
+
import pandas as pd
|
21 |
+
import copy
|
22 |
+
|
23 |
+
import transformers
|
24 |
+
from transformers import AutoTokenizer, DataCollatorForTokenClassification
|
25 |
+
|
26 |
+
from datasets import Dataset
|
27 |
+
|
28 |
+
from scipy.special import expit
|
29 |
+
|
30 |
+
|
31 |
+
# Load model and move to device
|
32 |
+
#checkpoint = 'ThorbenF/prot_t5_xl_uniref50'
|
33 |
+
#checkpoint = 'ThorbenF/prot_t5_xl_uniref50_cryptic'
|
34 |
+
checkpoint = 'ThorbenF/prot_t5_xl_uniref50_database'
|
35 |
+
max_length = 1500
|
36 |
+
model, tokenizer = load_model(checkpoint, max_length)
|
37 |
+
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
|
38 |
+
model.to(device)
|
39 |
+
model.eval()
|
40 |
+
|
41 |
+
def normalize_scores(scores):
|
42 |
+
min_score = np.min(scores)
|
43 |
+
max_score = np.max(scores)
|
44 |
+
return (scores - min_score) / (max_score - min_score) if max_score > min_score else scores
|
45 |
+
|
46 |
+
def read_mol(pdb_path):
|
47 |
+
"""Read PDB file and return its content as a string"""
|
48 |
+
with open(pdb_path, 'r') as f:
|
49 |
+
return f.read()
|
50 |
+
|
51 |
+
def fetch_structure(pdb_id: str, output_dir: str = ".") -> Optional[str]:
|
52 |
+
"""
|
53 |
+
Fetch the structure file for a given PDB ID. Prioritizes CIF files.
|
54 |
+
If a structure file already exists locally, it uses that.
|
55 |
+
"""
|
56 |
+
file_path = download_structure(pdb_id, output_dir)
|
57 |
+
if file_path:
|
58 |
+
return file_path
|
59 |
+
else:
|
60 |
+
return None
|
61 |
+
|
62 |
+
def download_structure(pdb_id: str, output_dir: str) -> Optional[str]:
|
63 |
+
"""
|
64 |
+
Attempt to download the structure file in CIF or PDB format.
|
65 |
+
Returns the path to the downloaded file, or None if download fails.
|
66 |
+
"""
|
67 |
+
for ext in ['.cif', '.pdb']:
|
68 |
+
file_path = os.path.join(output_dir, f"{pdb_id}{ext}")
|
69 |
+
if os.path.exists(file_path):
|
70 |
+
return file_path
|
71 |
+
url = f"https://files.rcsb.org/download/{pdb_id}{ext}"
|
72 |
+
try:
|
73 |
+
response = requests.get(url, timeout=10)
|
74 |
+
if response.status_code == 200:
|
75 |
+
with open(file_path, 'wb') as f:
|
76 |
+
f.write(response.content)
|
77 |
+
return file_path
|
78 |
+
except Exception as e:
|
79 |
+
print(f"Download error for {pdb_id}{ext}: {e}")
|
80 |
+
return None
|
81 |
+
|
82 |
+
def convert_cif_to_pdb(cif_path: str, output_dir: str = ".") -> str:
|
83 |
+
"""
|
84 |
+
Convert a CIF file to PDB format using BioPython and return the PDB file path.
|
85 |
+
"""
|
86 |
+
pdb_path = os.path.join(output_dir, os.path.basename(cif_path).replace('.cif', '.pdb'))
|
87 |
+
parser = MMCIFParser(QUIET=True)
|
88 |
+
structure = parser.get_structure('protein', cif_path)
|
89 |
+
io = PDBIO()
|
90 |
+
io.set_structure(structure)
|
91 |
+
io.save(pdb_path)
|
92 |
+
return pdb_path
|
93 |
+
|
94 |
+
def fetch_pdb(pdb_id):
|
95 |
+
pdb_path = fetch_structure(pdb_id)
|
96 |
+
if not pdb_path:
|
97 |
+
return None
|
98 |
+
_, ext = os.path.splitext(pdb_path)
|
99 |
+
if ext == '.cif':
|
100 |
+
pdb_path = convert_cif_to_pdb(pdb_path)
|
101 |
+
return pdb_path
|
102 |
+
|
103 |
+
def create_chain_specific_pdb(input_pdb: str, chain_id: str, residue_scores: list, protein_residues: list) -> str:
|
104 |
+
"""
|
105 |
+
Create a PDB file with only the selected chain and residues, replacing B-factor with prediction scores
|
106 |
+
"""
|
107 |
+
# Read the original PDB file
|
108 |
+
parser = PDBParser(QUIET=True)
|
109 |
+
structure = parser.get_structure('protein', input_pdb)
|
110 |
+
|
111 |
+
# Prepare a new structure with only the specified chain and selected residues
|
112 |
+
output_pdb = f"{os.path.splitext(input_pdb)[0]}_{chain_id}_predictions_scores.pdb"
|
113 |
+
|
114 |
+
# Create scores dictionary for easy lookup
|
115 |
+
scores_dict = {resi: score for resi, score in residue_scores}
|
116 |
+
|
117 |
+
# Create a custom Select class
|
118 |
+
class ResidueSelector(Select):
|
119 |
+
def __init__(self, chain_id, selected_residues, scores_dict):
|
120 |
+
self.chain_id = chain_id
|
121 |
+
self.selected_residues = selected_residues
|
122 |
+
self.scores_dict = scores_dict
|
123 |
+
|
124 |
+
def accept_chain(self, chain):
|
125 |
+
return chain.id == self.chain_id
|
126 |
+
|
127 |
+
def accept_residue(self, residue):
|
128 |
+
return residue.id[1] in self.selected_residues
|
129 |
+
|
130 |
+
def accept_atom(self, atom):
|
131 |
+
if atom.parent.id[1] in self.scores_dict:
|
132 |
+
atom.bfactor = np.absolute(1-self.scores_dict[atom.parent.id[1]]) * 100
|
133 |
+
return True
|
134 |
+
|
135 |
+
# Prepare output PDB with selected chain and residues, modified B-factors
|
136 |
+
io = PDBIO()
|
137 |
+
selector = ResidueSelector(chain_id, [res.id[1] for res in protein_residues], scores_dict)
|
138 |
+
|
139 |
+
io.set_structure(structure[0])
|
140 |
+
io.save(output_pdb, selector)
|
141 |
+
|
142 |
+
return output_pdb
|
143 |
+
|
144 |
+
def process_pdb(pdb_id_or_file, segment):
|
145 |
+
# Determine if input is a PDB ID or file path
|
146 |
+
if pdb_id_or_file.endswith('.pdb'):
|
147 |
+
pdb_path = pdb_id_or_file
|
148 |
+
pdb_id = os.path.splitext(os.path.basename(pdb_path))[0]
|
149 |
+
else:
|
150 |
+
pdb_id = pdb_id_or_file
|
151 |
+
pdb_path = fetch_pdb(pdb_id)
|
152 |
+
|
153 |
+
if not pdb_path:
|
154 |
+
return "Failed to fetch PDB file", None, None
|
155 |
+
|
156 |
+
# Determine the file format and choose the appropriate parser
|
157 |
+
_, ext = os.path.splitext(pdb_path)
|
158 |
+
parser = MMCIFParser(QUIET=True) if ext == '.cif' else PDBParser(QUIET=True)
|
159 |
+
|
160 |
+
try:
|
161 |
+
# Parse the structure file
|
162 |
+
structure = parser.get_structure('protein', pdb_path)
|
163 |
+
except Exception as e:
|
164 |
+
return f"Error parsing structure file: {e}", None, None
|
165 |
+
|
166 |
+
# Extract the specified chain
|
167 |
+
try:
|
168 |
+
chain = structure[0][segment]
|
169 |
+
except KeyError:
|
170 |
+
return "Invalid Chain ID", None, None
|
171 |
+
|
172 |
+
protein_residues = [res for res in chain if is_aa(res)]
|
173 |
+
sequence = "".join(seq1(res.resname) for res in protein_residues)
|
174 |
+
sequence_id = [res.id[1] for res in protein_residues]
|
175 |
+
|
176 |
+
visualized_sequence = "".join(seq1(res.resname) for res in protein_residues)
|
177 |
+
if sequence != visualized_sequence:
|
178 |
+
raise ValueError("The visualized sequence does not match the prediction sequence")
|
179 |
+
|
180 |
+
input_ids = tokenizer(" ".join(sequence), return_tensors="pt").input_ids.to(device)
|
181 |
+
with torch.no_grad():
|
182 |
+
outputs = model(input_ids).logits.detach().cpu().numpy().squeeze()
|
183 |
+
|
184 |
+
# Calculate scores and normalize them
|
185 |
+
scores = expit(outputs[:, 1] - outputs[:, 0])
|
186 |
+
|
187 |
+
normalized_scores = normalize_scores(scores)
|
188 |
+
|
189 |
+
# Zip residues with scores to track the residue ID and score
|
190 |
+
residue_scores = [(resi, score) for resi, score in zip(sequence_id, normalized_scores)]
|
191 |
+
|
192 |
+
|
193 |
+
# Define the score brackets
|
194 |
+
score_brackets = {
|
195 |
+
"0.0-0.2": (0.0, 0.2),
|
196 |
+
"0.2-0.4": (0.2, 0.4),
|
197 |
+
"0.4-0.6": (0.4, 0.6),
|
198 |
+
"0.6-0.8": (0.6, 0.8),
|
199 |
+
"0.8-1.0": (0.8, 1.0)
|
200 |
+
}
|
201 |
+
|
202 |
+
# Initialize a dictionary to store residues by bracket
|
203 |
+
residues_by_bracket = {bracket: [] for bracket in score_brackets}
|
204 |
+
|
205 |
+
# Categorize residues into brackets
|
206 |
+
for resi, score in residue_scores:
|
207 |
+
for bracket, (lower, upper) in score_brackets.items():
|
208 |
+
if lower <= score < upper:
|
209 |
+
residues_by_bracket[bracket].append(resi)
|
210 |
+
break
|
211 |
+
|
212 |
+
# Preparing the result string
|
213 |
+
current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
214 |
+
result_str = f"Prediction for PDB: {pdb_id}, Chain: {segment}\nDate: {current_time}\n\n"
|
215 |
+
result_str += "Residues by Score Brackets:\n\n"
|
216 |
+
|
217 |
+
# Add residues for each bracket
|
218 |
+
for bracket, residues in residues_by_bracket.items():
|
219 |
+
result_str += f"Bracket {bracket}:\n"
|
220 |
+
result_str += "Columns: Residue Name, Residue Number, One-letter Code, Normalized Score\n"
|
221 |
+
result_str += "\n".join([
|
222 |
+
f"{res.resname} {res.id[1]} {sequence[i]} {normalized_scores[i]:.2f}"
|
223 |
+
for i, res in enumerate(protein_residues) if res.id[1] in residues
|
224 |
+
])
|
225 |
+
result_str += "\n\n"
|
226 |
+
|
227 |
+
# Create chain-specific PDB with scores in B-factor
|
228 |
+
scored_pdb = create_chain_specific_pdb(pdb_path, segment, residue_scores, protein_residues)
|
229 |
+
|
230 |
+
# Molecule visualization with updated script with color mapping
|
231 |
+
mol_vis = molecule(pdb_path, residue_scores, segment)#, color_map)
|
232 |
+
|
233 |
+
# Improved PyMOL command suggestions
|
234 |
+
current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
235 |
+
pymol_commands = f"Prediction for PDB: {pdb_id}, Chain: {segment}\nDate: {current_time}\n\n"
|
236 |
+
|
237 |
+
pymol_commands += f"""
|
238 |
+
# PyMOL Visualization Commands
|
239 |
+
load {os.path.abspath(pdb_path)}, protein
|
240 |
+
hide everything, all
|
241 |
+
show cartoon, chain {segment}
|
242 |
+
color white, chain {segment}
|
243 |
+
"""
|
244 |
+
|
245 |
+
# Define colors for each score bracket
|
246 |
+
bracket_colors = {
|
247 |
+
"0.0-0.2": "white",
|
248 |
+
"0.2-0.4": "lightorange",
|
249 |
+
"0.4-0.6": "orange",
|
250 |
+
"0.6-0.8": "orangered",
|
251 |
+
"0.8-1.0": "red"
|
252 |
+
}
|
253 |
+
|
254 |
+
# Add PyMOL commands for each score bracket
|
255 |
+
for bracket, residues in residues_by_bracket.items():
|
256 |
+
if residues: # Only add commands if there are residues in this bracket
|
257 |
+
color = bracket_colors[bracket]
|
258 |
+
resi_list = '+'.join(map(str, residues))
|
259 |
+
pymol_commands += f"""
|
260 |
+
select bracket_{bracket.replace('.', '').replace('-', '_')}, resi {resi_list} and chain {segment}
|
261 |
+
show sticks, bracket_{bracket.replace('.', '').replace('-', '_')}
|
262 |
+
color {color}, bracket_{bracket.replace('.', '').replace('-', '_')}
|
263 |
+
"""
|
264 |
+
# Create prediction and scored PDB files
|
265 |
+
prediction_file = f"{pdb_id}_binding_site_residues.txt"
|
266 |
+
with open(prediction_file, "w") as f:
|
267 |
+
f.write(result_str)
|
268 |
+
|
269 |
+
return pymol_commands, mol_vis, [prediction_file,scored_pdb]
|
270 |
+
|
271 |
+
def molecule(input_pdb, residue_scores=None, segment='A'):
|
272 |
+
# More granular scoring for visualization
|
273 |
+
mol = read_mol(input_pdb) # Read PDB file content
|
274 |
+
|
275 |
+
# Prepare high-scoring residues script if scores are provided
|
276 |
+
high_score_script = ""
|
277 |
+
if residue_scores is not None:
|
278 |
+
# Filter residues based on their scores
|
279 |
+
class1_score_residues = [resi for resi, score in residue_scores if 0.0 < score <= 0.2]
|
280 |
+
class2_score_residues = [resi for resi, score in residue_scores if 0.2 < score <= 0.4]
|
281 |
+
class3_score_residues = [resi for resi, score in residue_scores if 0.4 < score <= 0.6]
|
282 |
+
class4_score_residues = [resi for resi, score in residue_scores if 0.6 < score <= 0.8]
|
283 |
+
class5_score_residues = [resi for resi, score in residue_scores if 0.8 < score <= 1.0]
|
284 |
+
|
285 |
+
high_score_script = """
|
286 |
+
// Load the original model and apply white cartoon style
|
287 |
+
let chainModel = viewer.addModel(pdb, "pdb");
|
288 |
+
chainModel.setStyle({}, {});
|
289 |
+
chainModel.setStyle(
|
290 |
+
{"chain": "%s"},
|
291 |
+
{"cartoon": {"color": "white"}}
|
292 |
+
);
|
293 |
+
|
294 |
+
// Create a new model for high-scoring residues and apply red sticks style
|
295 |
+
let class1Model = viewer.addModel(pdb, "pdb");
|
296 |
+
class1Model.setStyle({}, {});
|
297 |
+
class1Model.setStyle(
|
298 |
+
{"chain": "%s", "resi": [%s]},
|
299 |
+
{"stick": {"color": "0xFFFFFF", "opacity": 0.5}}
|
300 |
+
);
|
301 |
+
|
302 |
+
// Create a new model for high-scoring residues and apply red sticks style
|
303 |
+
let class2Model = viewer.addModel(pdb, "pdb");
|
304 |
+
class2Model.setStyle({}, {});
|
305 |
+
class2Model.setStyle(
|
306 |
+
{"chain": "%s", "resi": [%s]},
|
307 |
+
{"stick": {"color": "0xFFD580", "opacity": 0.7}}
|
308 |
+
);
|
309 |
+
|
310 |
+
// Create a new model for high-scoring residues and apply red sticks style
|
311 |
+
let class3Model = viewer.addModel(pdb, "pdb");
|
312 |
+
class3Model.setStyle({}, {});
|
313 |
+
class3Model.setStyle(
|
314 |
+
{"chain": "%s", "resi": [%s]},
|
315 |
+
{"stick": {"color": "0xFFA500", "opacity": 1}}
|
316 |
+
);
|
317 |
+
|
318 |
+
// Create a new model for high-scoring residues and apply red sticks style
|
319 |
+
let class4Model = viewer.addModel(pdb, "pdb");
|
320 |
+
class4Model.setStyle({}, {});
|
321 |
+
class4Model.setStyle(
|
322 |
+
{"chain": "%s", "resi": [%s]},
|
323 |
+
{"stick": {"color": "0xFF4500", "opacity": 1}}
|
324 |
+
);
|
325 |
+
|
326 |
+
// Create a new model for high-scoring residues and apply red sticks style
|
327 |
+
let class5Model = viewer.addModel(pdb, "pdb");
|
328 |
+
class5Model.setStyle({}, {});
|
329 |
+
class5Model.setStyle(
|
330 |
+
{"chain": "%s", "resi": [%s]},
|
331 |
+
{"stick": {"color": "0xFF0000", "alpha": 1}}
|
332 |
+
);
|
333 |
+
|
334 |
+
""" % (
|
335 |
+
segment,
|
336 |
+
segment,
|
337 |
+
", ".join(str(resi) for resi in class1_score_residues),
|
338 |
+
segment,
|
339 |
+
", ".join(str(resi) for resi in class2_score_residues),
|
340 |
+
segment,
|
341 |
+
", ".join(str(resi) for resi in class3_score_residues),
|
342 |
+
segment,
|
343 |
+
", ".join(str(resi) for resi in class4_score_residues),
|
344 |
+
segment,
|
345 |
+
", ".join(str(resi) for resi in class5_score_residues)
|
346 |
+
)
|
347 |
+
|
348 |
+
# Generate the full HTML content
|
349 |
+
html_content = f"""
|
350 |
+
<!DOCTYPE html>
|
351 |
+
<html>
|
352 |
+
<head>
|
353 |
+
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
|
354 |
+
<style>
|
355 |
+
.mol-container {{
|
356 |
+
width: 100%;
|
357 |
+
height: 700px;
|
358 |
+
position: relative;
|
359 |
+
}}
|
360 |
+
</style>
|
361 |
+
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.3/jquery.min.js"></script>
|
362 |
+
<script src="https://3Dmol.csb.pitt.edu/build/3Dmol-min.js"></script>
|
363 |
+
</head>
|
364 |
+
<body>
|
365 |
+
<div id="container" class="mol-container"></div>
|
366 |
+
<script>
|
367 |
+
let pdb = `{mol}`; // Use template literal to properly escape PDB content
|
368 |
+
$(document).ready(function () {{
|
369 |
+
let element = $("#container");
|
370 |
+
let config = {{ backgroundColor: "white" }};
|
371 |
+
let viewer = $3Dmol.createViewer(element, config);
|
372 |
+
|
373 |
+
{high_score_script}
|
374 |
+
|
375 |
+
// Add hover functionality
|
376 |
+
viewer.setHoverable(
|
377 |
+
{{}},
|
378 |
+
true,
|
379 |
+
function(atom, viewer, event, container) {{
|
380 |
+
if (!atom.label) {{
|
381 |
+
atom.label = viewer.addLabel(
|
382 |
+
atom.resn + ":" +atom.resi + ":" + atom.atom,
|
383 |
+
{{
|
384 |
+
position: atom,
|
385 |
+
backgroundColor: 'mintcream',
|
386 |
+
fontColor: 'black',
|
387 |
+
fontSize: 18,
|
388 |
+
padding: 4
|
389 |
+
}}
|
390 |
+
);
|
391 |
+
}}
|
392 |
+
}},
|
393 |
+
function(atom, viewer) {{
|
394 |
+
if (atom.label) {{
|
395 |
+
viewer.removeLabel(atom.label);
|
396 |
+
delete atom.label;
|
397 |
+
}}
|
398 |
+
}}
|
399 |
+
);
|
400 |
+
|
401 |
+
viewer.zoomTo();
|
402 |
+
viewer.render();
|
403 |
+
viewer.zoom(0.8, 2000);
|
404 |
+
}});
|
405 |
+
</script>
|
406 |
+
</body>
|
407 |
+
</html>
|
408 |
+
"""
|
409 |
+
|
410 |
+
# Return the HTML content within an iframe safely encoded for special characters
|
411 |
+
return f'<iframe width="100%" height="700" srcdoc="{html_content.replace(chr(34), """).replace(chr(39), "'")}"></iframe>'
|
412 |
+
|
413 |
+
# Gradio UI
|
414 |
+
with gr.Blocks(css="""
|
415 |
+
/* Customize Gradio button colors */
|
416 |
+
#visualize-btn, #predict-btn {
|
417 |
+
background-color: #FF7300; /* Deep orange */
|
418 |
+
color: white;
|
419 |
+
border-radius: 5px;
|
420 |
+
padding: 10px;
|
421 |
+
font-weight: bold;
|
422 |
+
}
|
423 |
+
#visualize-btn:hover, #predict-btn:hover {
|
424 |
+
background-color: #CC5C00; /* Darkened orange on hover */
|
425 |
+
}
|
426 |
+
""") as demo:
|
427 |
+
gr.Markdown("# Protein Binding Site Prediction")
|
428 |
+
|
429 |
+
# Mode selection
|
430 |
+
mode = gr.Radio(
|
431 |
+
choices=["PDB ID", "Upload File"],
|
432 |
+
value="PDB ID",
|
433 |
+
label="Input Mode",
|
434 |
+
info="Choose whether to input a PDB ID or upload a PDB/CIF file."
|
435 |
+
)
|
436 |
+
|
437 |
+
# Input components based on mode
|
438 |
+
pdb_input = gr.Textbox(value="2F6V", label="PDB ID", placeholder="Enter PDB ID here...")
|
439 |
+
pdb_file = gr.File(label="Upload PDB/CIF File", visible=False)
|
440 |
+
visualize_btn = gr.Button("Visualize Structure", elem_id="visualize-btn")
|
441 |
+
|
442 |
+
molecule_output2 = Molecule3D(label="Protein Structure", reps=[
|
443 |
+
{
|
444 |
+
"model": 0,
|
445 |
+
"style": "cartoon",
|
446 |
+
"color": "whiteCarbon",
|
447 |
+
"residue_range": "",
|
448 |
+
"around": 0,
|
449 |
+
"byres": False,
|
450 |
+
}
|
451 |
+
])
|
452 |
+
|
453 |
+
with gr.Row():
|
454 |
+
segment_input = gr.Textbox(value="A", label="Chain ID (protein)", placeholder="Enter Chain ID here...",
|
455 |
+
info="Choose in which chain to predict binding sites.")
|
456 |
+
prediction_btn = gr.Button("Predict Binding Site", elem_id="predict-btn")
|
457 |
+
|
458 |
+
molecule_output = gr.HTML(label="Protein Structure")
|
459 |
+
explanation_vis = gr.Markdown("""
|
460 |
+
Score dependent colorcoding:
|
461 |
+
- 0.0-0.2: white
|
462 |
+
- 0.2–0.4: light orange
|
463 |
+
- 0.4–0.6: orange
|
464 |
+
- 0.6–0.8: orangered
|
465 |
+
- 0.8–1.0: red
|
466 |
+
""")
|
467 |
+
predictions_output = gr.Textbox(label="Visualize Prediction with PyMol")
|
468 |
+
gr.Markdown("### Download:\n- List of predicted binding site residues\n- PDB with score in beta factor column")
|
469 |
+
download_output = gr.File(label="Download Files", file_count="multiple")
|
470 |
+
|
471 |
+
def process_interface(mode, pdb_id, pdb_file, chain_id):
|
472 |
+
if mode == "PDB ID":
|
473 |
+
return process_pdb(pdb_id, chain_id)
|
474 |
+
elif mode == "Upload File":
|
475 |
+
_, ext = os.path.splitext(pdb_file.name)
|
476 |
+
file_path = os.path.join('./', f"{_}{ext}")
|
477 |
+
if ext == '.cif':
|
478 |
+
pdb_path = convert_cif_to_pdb(file_path)
|
479 |
+
else:
|
480 |
+
pdb_path= file_path
|
481 |
+
return process_pdb(pdb_path, chain_id)
|
482 |
+
else:
|
483 |
+
return "Error: Invalid mode selected", None, None
|
484 |
+
|
485 |
+
def fetch_interface(mode, pdb_id, pdb_file):
|
486 |
+
if mode == "PDB ID":
|
487 |
+
return fetch_pdb(pdb_id)
|
488 |
+
elif mode == "Upload File":
|
489 |
+
_, ext = os.path.splitext(pdb_file.name)
|
490 |
+
file_path = os.path.join('./', f"{_}{ext}")
|
491 |
+
#print(ext)
|
492 |
+
if ext == '.cif':
|
493 |
+
pdb_path = convert_cif_to_pdb(file_path)
|
494 |
+
else:
|
495 |
+
pdb_path= file_path
|
496 |
+
#print(pdb_path)
|
497 |
+
return pdb_path
|
498 |
+
else:
|
499 |
+
return "Error: Invalid mode selected"
|
500 |
+
|
501 |
+
def toggle_mode(selected_mode):
|
502 |
+
if selected_mode == "PDB ID":
|
503 |
+
return gr.update(visible=True), gr.update(visible=False)
|
504 |
+
else:
|
505 |
+
return gr.update(visible=False), gr.update(visible=True)
|
506 |
+
|
507 |
+
mode.change(
|
508 |
+
toggle_mode,
|
509 |
+
inputs=[mode],
|
510 |
+
outputs=[pdb_input, pdb_file]
|
511 |
+
)
|
512 |
+
|
513 |
+
prediction_btn.click(
|
514 |
+
process_interface,
|
515 |
+
inputs=[mode, pdb_input, pdb_file, segment_input],
|
516 |
+
outputs=[predictions_output, molecule_output, download_output]
|
517 |
+
)
|
518 |
+
|
519 |
+
visualize_btn.click(
|
520 |
+
fetch_interface,
|
521 |
+
inputs=[mode, pdb_input, pdb_file],
|
522 |
+
outputs=molecule_output2
|
523 |
+
)
|
524 |
+
|
525 |
+
gr.Markdown("## Examples")
|
526 |
+
gr.Examples(
|
527 |
+
examples=[
|
528 |
+
["7RPZ", "A"],
|
529 |
+
["2IWI", "B"],
|
530 |
+
["7LCJ", "R"]
|
531 |
+
],
|
532 |
+
inputs=[pdb_input, segment_input],
|
533 |
+
outputs=[predictions_output, molecule_output, download_output]
|
534 |
+
)
|
535 |
+
|
536 |
+
#demo.launch(share=True)
|
537 |
+
demo.launch()
|
app.py
CHANGED
@@ -7,7 +7,7 @@ from Bio.SeqUtils import seq1
|
|
7 |
from typing import Optional, Tuple
|
8 |
import numpy as np
|
9 |
import os
|
10 |
-
from gradio_molecule3d import Molecule3D
|
11 |
|
12 |
from model_loader import load_model
|
13 |
|
@@ -533,5 +533,4 @@ with gr.Blocks(css="""
|
|
533 |
outputs=[predictions_output, molecule_output, download_output]
|
534 |
)
|
535 |
|
536 |
-
|
537 |
-
demo.launch()
|
|
|
7 |
from typing import Optional, Tuple
|
8 |
import numpy as np
|
9 |
import os
|
10 |
+
#from gradio_molecule3d import Molecule3D
|
11 |
|
12 |
from model_loader import load_model
|
13 |
|
|
|
533 |
outputs=[predictions_output, molecule_output, download_output]
|
534 |
)
|
535 |
|
536 |
+
demo.launch(share=True)
|
|
requirements.txt
CHANGED
@@ -10,4 +10,5 @@ sentencepiece
|
|
10 |
huggingface_hub>=0.15.0
|
11 |
requests
|
12 |
gradio_molecule3d
|
13 |
-
biopython>=1.81
|
|
|
|
10 |
huggingface_hub>=0.15.0
|
11 |
requests
|
12 |
gradio_molecule3d
|
13 |
+
biopython>=1.81
|
14 |
+
pydantic==1.10.13
|