TillCyrill commited on
Commit
a3a5fc1
1 Parent(s): b55971a
Files changed (3) hide show
  1. Dockerfile +9 -7
  2. main.py +140 -20
  3. old_main.py +30 -0
Dockerfile CHANGED
@@ -51,16 +51,18 @@ ENV PYTHONPATH="$AMBERHOME/lib/python3.10/site-packages"
51
  #COPY --chown=user . $HOME/app
52
 
53
 
54
- #RUN adduser -u 5678 --disabled-password --gecos "" appuser && chown -R appuser .
55
- #USER appuser
56
- #CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "7860"]
57
 
58
- WORKDIR $HOME/app
59
 
60
- # Copy the current directory contents into the container at $HOME/app setting the owner to the user
61
- COPY --chown=user . $HOME/app
62
 
63
- CMD ["python", "app.py"]
 
 
 
 
 
64
 
65
 
66
 
 
51
  #COPY --chown=user . $HOME/app
52
 
53
 
54
+ RUN adduser -u 5678 --disabled-password --gecos "" appuser && chown -R appuser .
 
 
55
 
56
+ USER appuser
57
 
58
+ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "7860"]
 
59
 
60
+ #WORKDIR $HOME/app
61
+ #
62
+ ## Copy the current directory contents into the container at $HOME/app setting the owner to the user
63
+ #COPY --chown=user . $HOME/app
64
+ #
65
+ #CMD ["python", "app.py"]
66
 
67
 
68
 
main.py CHANGED
@@ -1,30 +1,150 @@
1
  import gradio as gr
 
 
 
 
 
 
 
 
2
  import torch
3
- import requests
4
- from torchvision import transforms
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
 
6
- model = torch.hub.load("pytorch/vision:v0.6.0", "resnet18", pretrained=True).eval()
7
- response = requests.get("https://git.io/JJkYN")
8
- labels = response.text.split("\n")
9
 
 
10
 
11
- def predict(inp):
12
- inp = transforms.ToTensor()(inp).unsqueeze(0)
13
- with torch.no_grad():
14
- prediction = torch.nn.functional.softmax(model(inp)[0], dim=0)
15
- confidences = {labels[i]: float(prediction[i]) for i in range(1000)}
16
- return confidences
17
 
18
 
19
- def run():
20
- demo = gr.Interface(
21
- fn=predict,
22
- inputs=gr.inputs.Image(type="pil"),
23
- outputs=gr.outputs.Label(num_top_classes=3),
24
- )
25
 
26
- demo.launch(server_name="0.0.0.0", server_port=7860)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
 
28
 
29
- if __name__ == "__main__":
30
- run()
 
1
  import gradio as gr
2
+
3
+ import py3Dmol
4
+
5
+ from Bio.PDB import *
6
+
7
+ import numpy as np
8
+ from Bio.PDB import PDBParser
9
+ import pandas as pd
10
  import torch
11
+ import os
12
+ from MDmodel import GNN_MD
13
+ import h5py
14
+ from transformMD import GNNTransformMD
15
+
16
+ # JavaScript functions
17
+ resid_hover = """function(atom,viewer) {{
18
+ if(!atom.label) {{
19
+ atom.label = viewer.addLabel('{0}:'+atom.atom+atom.serial,
20
+ {{position: atom, backgroundColor: 'mintcream', fontColor:'black'}});
21
+ }}
22
+ }}"""
23
+ hover_func = """
24
+ function(atom,viewer) {
25
+ if(!atom.label) {
26
+ atom.label = viewer.addLabel(atom.interaction,
27
+ {position: atom, backgroundColor: 'black', fontColor:'white'});
28
+ }
29
+ }"""
30
+ unhover_func = """
31
+ function(atom,viewer) {
32
+ if(atom.label) {
33
+ viewer.removeLabel(atom.label);
34
+ delete atom.label;
35
+ }
36
+ }"""
37
+ atom_mapping = {0:'H', 1:'C', 2:'N', 3:'O', 4:'F', 5:'P', 6:'S', 7:'CL', 8:'BR', 9:'I', 10: 'UNK'}
38
+
39
+ model = GNN_MD(11, 64)
40
+ state_dict = torch.load(
41
+ "best_weights_rep0.pt",
42
+ map_location=torch.device("cpu"),
43
+ )["model_state_dict"]
44
+ model.load_state_dict(state_dict)
45
+ model = model.to('cpu')
46
+ model.eval()
47
+
48
+
49
+
50
+ def get_pdb(pdb_code="", filepath=""):
51
+ try:
52
+ return filepath.name
53
+ except AttributeError as e:
54
+ if pdb_code is None or pdb_code == "":
55
+ return None
56
+ else:
57
+ os.system(f"wget -qnc https://files.rcsb.org/view/{pdb_code}.pdb")
58
+ return f"{pdb_code}.pdb"
59
+
60
+
61
+ def get_offset(pdb):
62
+ pdb_multiline = pdb.split("\n")
63
+ for line in pdb_multiline:
64
+ if line.startswith("ATOM"):
65
+ return int(line[22:27])
66
+
67
+
68
+ def predict(pdb_code, pdb_file):
69
+ #path_to_pdb = get_pdb(pdb_code=pdb_code, filepath=pdb_file)
70
+
71
+ #pdb = open(path_to_pdb, "r").read()
72
+ # switch to misato env if not running from container
73
+ mdh5_file = "inference_for_md.hdf5"
74
+ md_H5File = h5py.File(mdh5_file)
75
+
76
+ column_names = ["x", "y", "z", "element"]
77
+ atoms_protein = pd.DataFrame(columns = column_names)
78
+ cutoff = md_H5File["11GS"]["molecules_begin_atom_index"][:][-1] # cutoff defines protein atoms
79
+
80
+ atoms_protein["x"] = md_H5File["11GS"]["atoms_coordinates_ref"][:][:cutoff, 0]
81
+ atoms_protein["y"] = md_H5File["11GS"]["atoms_coordinates_ref"][:][:cutoff, 1]
82
+ atoms_protein["z"] = md_H5File["11GS"]["atoms_coordinates_ref"][:][:cutoff, 2]
83
+
84
+ atoms_protein["element"] = md_H5File["11GS"]["atoms_element"][:][:cutoff]
85
+
86
+ item = {}
87
+ item["scores"] = 0
88
+ item["id"] = "11GS"
89
+ item["atoms_protein"] = atoms_protein
90
+
91
+ transform = GNNTransformMD()
92
+ data_item = transform(item)
93
+ adaptability = model(data_item)
94
+ adaptability = adaptability.detach().numpy()
95
+
96
+ data = []
97
+
98
+
99
+ for i in range(adaptability.shape[0]):
100
+ data.append([i, atom_mapping(atoms_protein.iloc[i, atoms_protein.columns.get_loc("element")] - 1), atoms_protein.iloc[i, atoms_protein.columns.get_loc("x")],atoms_protein.iloc[i, atoms_protein.columns.get_loc("y")],atoms_protein.iloc[i, atoms_protein.columns.get_loc("z")],adaptability[i]])
101
+
102
+ topN = 100
103
+ topN_ind = np.argsort(adaptability)[::-1][:topN]
104
+
105
+ pdb = open(pdb_file.name, "r").read()
106
+
107
+ view = py3Dmol.view(width=600, height=400)
108
+ view.setBackgroundColor('black')
109
+ view.addModel(pdb, "pdb")
110
+ view.setStyle({'stick': {'colorscheme': {'prop': 'resi', 'C': 'turquoise'}}})
111
+
112
+ for i in range(topN):
113
+ view.addSphere({'center':{'x':atoms_protein.iloc[topN_ind[i], atoms_protein.columns.get_loc("x")], 'y':atoms_protein.iloc[topN_ind[i], atoms_protein.columns.get_loc("y")],'z':atoms_protein.iloc[topN_ind[i], atoms_protein.columns.get_loc("z")]},'radius':adaptability[topN_ind[i]]/1.5,'color':'orange','alpha':0.75})
114
 
115
+ view.zoomTo()
 
 
116
 
117
+ output = view._make_html().replace("'", '"')
118
 
119
+ x = f"""<!DOCTYPE html><html> {output} </html>""" # do not use ' in this input
120
+ return f"""<iframe style="width: 100%; height:420px" name="result" allow="midi; geolocation; microphone; camera;
121
+ display-capture; encrypted-media;" sandbox="allow-modals allow-forms
122
+ allow-scripts allow-same-origin allow-popups
123
+ allow-top-navigation-by-user-activation allow-downloads" allowfullscreen=""
124
+ allowpaymentrequest="" frameborder="0" srcdoc='{x}'></iframe>""", pd.DataFrame(data, columns=['index','element','x','y','z','Adaptability'])
125
 
126
 
127
+ callback = gr.CSVLogger()
 
 
 
 
 
128
 
129
+ with gr.Blocks() as demo:
130
+ gr.Markdown("# Protein Adaptability Prediction")
131
+
132
+ #text_input = gr.Textbox()
133
+ #text_output = gr.Textbox()
134
+ #text_button = gr.Button("Flip")
135
+ inp = gr.Textbox(placeholder="PDB Code or upload file below", label="Input structure")
136
+ pdb_file = gr.File(label="PDB File Upload")
137
+ #with gr.Row():
138
+ # helix = gr.ColorPicker(label="helix")
139
+ # sheet = gr.ColorPicker(label="sheet")
140
+ # loop = gr.ColorPicker(label="loop")
141
+ single_btn = gr.Button(label="Run")
142
+ with gr.Row():
143
+ html = gr.HTML()
144
+ with gr.Row():
145
+ dataframe = gr.Dataframe()
146
+
147
+ single_btn.click(fn=predict, inputs=[inp, pdb_file], outputs=[html, dataframe])
148
 
149
 
150
+ demo.launch(debug=True)
 
old_main.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import torch
3
+ import requests
4
+ from torchvision import transforms
5
+
6
+ model = torch.hub.load("pytorch/vision:v0.6.0", "resnet18", pretrained=True).eval()
7
+ response = requests.get("https://git.io/JJkYN")
8
+ labels = response.text.split("\n")
9
+
10
+
11
+ def predict(inp):
12
+ inp = transforms.ToTensor()(inp).unsqueeze(0)
13
+ with torch.no_grad():
14
+ prediction = torch.nn.functional.softmax(model(inp)[0], dim=0)
15
+ confidences = {labels[i]: float(prediction[i]) for i in range(1000)}
16
+ return confidences
17
+
18
+
19
+ def run():
20
+ demo = gr.Interface(
21
+ fn=predict,
22
+ inputs=gr.inputs.Image(type="pil"),
23
+ outputs=gr.outputs.Label(num_top_classes=3),
24
+ )
25
+
26
+ demo.launch(server_name="0.0.0.0", server_port=7860)
27
+
28
+
29
+ if __name__ == "__main__":
30
+ run()