Accelernate commited on
Commit
e8fdfbc
·
verified ·
1 Parent(s): c3a875f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +84 -57
app.py CHANGED
@@ -1,77 +1,104 @@
1
  import streamlit as st
2
- import random
3
- import hashlib
4
  import py3Dmol
5
  import requests
6
- import io
7
- from Bio import PDB
 
 
 
 
 
 
 
 
8
 
 
9
  def generate_sequence_from_words(words, length):
10
  seed = ' '.join(words).encode('utf-8')
11
  random.seed(hashlib.md5(seed).hexdigest())
12
  amino_acids = "ACDEFGHIKLMNPQRSTVWY"
13
  return ''.join(random.choice(amino_acids) for _ in range(length))
14
 
15
- def predict_structure(sequence):
16
- url = "https://api.esmatlas.com/foldSequence/v1/pdb/"
17
- headers = {"Content-Type": "application/x-www-form-urlencoded"}
18
- data = {"sequence": sequence}
19
-
20
- response = requests.post(url, headers=headers, data=data, timeout=300)
21
- if response.status_code == 200:
22
- return response.text
23
- else:
24
- st.error(f"Error in structure prediction: {response.status_code} - {response.text}")
25
- return None
26
-
27
- def visualize_protein(pdb_string):
28
- view = py3Dmol.view(width=800, height=400)
29
- view.addModel(pdb_string, 'pdb')
30
- view.setStyle({'cartoon': {'color': 'spectrum'}})
31
- view.zoomTo()
32
- return view
33
 
34
- st.title("Protein Sequence Generator and Structure Predictor")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35
 
36
- st.write("Enter three random words to seed your protein sequence:")
37
- word1 = st.text_input("Word 1")
38
- word2 = st.text_input("Word 2")
39
- word3 = st.text_input("Word 3")
40
 
41
- sequence_length = st.number_input("Enter desired sequence length",
42
- min_value=50,
43
- max_value=400,
44
- value=100,
45
- step=10)
 
46
 
47
- if st.button("Generate Sequence and Predict Structure"):
 
48
  if word1 and word2 and word3:
49
- words = [word1, word2, word3]
50
- sequence = generate_sequence_from_words(words, sequence_length)
51
- st.write(f"Generated sequence inspired by '{word1}', '{word2}', and '{word3}' with length '{sequence_length}':")
52
- st.code(sequence)
53
-
54
- st.header("Protein Structure Prediction")
55
  with st.spinner("Predicting protein structure... This may take a few minutes."):
56
- pdb_string = predict_structure(sequence)
57
- if pdb_string:
58
- view = visualize_protein(pdb_string)
59
-
60
- st_py3dmol = py3Dmol.show3d(view, width=800, height=400)
61
- st.components.v1.html(st_py3dmol.startjs, height=400)
62
-
63
- st.success("Structure prediction complete!")
64
- st.write("Note: This is a computational prediction and may not represent the actual biological structure.")
65
- else:
66
- st.error("Failed to predict structure. Please try again.")
67
  else:
68
- st.error("Please enter all three words.")
69
 
70
- st.markdown("""
 
71
  ## What to do next:
72
- 1. Experiment with different seed words and sequence lengths.
73
- 2. Learn about how protein sequences relate to their predicted structures.
74
- 3. Remember that these are computational predictions and may not represent the actual biological structure.
75
- 4. For real protein structures, visit the [Protein Data Bank (PDB)](https://www.rcsb.org/).
76
- Enjoy exploring the world of protein sequences and predicted structures!
 
77
  """)
 
1
  import streamlit as st
2
+ from stmol import showmol
 
3
  import py3Dmol
4
  import requests
5
+ import biotite.structure.io as bsio
6
+ import random
7
+ import hashlib
8
+ import urllib3
9
+
10
+ urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
11
+
12
+ st.set_page_config(layout='wide')
13
+ st.sidebar.title('🎈 ESMFold Protein Structure Predictor')
14
+ st.sidebar.write('[*ESMFold*](https://esmatlas.com/about) is an end-to-end single sequence protein structure predictor based on the ESM-2 language model. For more information, read the [research article](https://www.biorxiv.org/content/10.1101/2022.07.20.500902v2) and the [news article](https://www.nature.com/articles/d41586-022-03539-1) published in *Nature*.')
15
 
16
+ # Function to generate protein sequence from words
17
  def generate_sequence_from_words(words, length):
18
  seed = ' '.join(words).encode('utf-8')
19
  random.seed(hashlib.md5(seed).hexdigest())
20
  amino_acids = "ACDEFGHIKLMNPQRSTVWY"
21
  return ''.join(random.choice(amino_acids) for _ in range(length))
22
 
23
+ # stmol
24
+ def render_mol(pdb):
25
+ pdbview = py3Dmol.view()
26
+ pdbview.addModel(pdb,'pdb')
27
+ pdbview.setStyle({'cartoon':{'color':'spectrum'}})
28
+ pdbview.setBackgroundColor('white')
29
+ pdbview.zoomTo()
30
+ pdbview.zoom(2, 800)
31
+ pdbview.spin(True)
32
+ showmol(pdbview, height = 500,width=800)
 
 
 
 
 
 
 
 
33
 
34
+ # ESMfold
35
+ def update(sequence, word1, word2, word3, sequence_length):
36
+ headers = {
37
+ 'Content-Type': 'application/x-www-form-urlencoded',
38
+ }
39
+ try:
40
+ response = requests.post('https://api.esmatlas.com/foldSequence/v1/pdb/',
41
+ headers=headers,
42
+ data=sequence,
43
+ verify=False, # Disable SSL verification
44
+ timeout=300) # Set a longer timeout
45
+ response.raise_for_status() # Raise an exception for bad status codes
46
+ pdb_string = response.content.decode('utf-8')
47
+
48
+ with open('predicted.pdb', 'w') as f:
49
+ f.write(pdb_string)
50
+
51
+ struct = bsio.load_structure('predicted.pdb', extra_fields=["b_factor"])
52
+ b_value = round(struct.b_factor.mean(), 2)
53
+
54
+ # Display protein structure
55
+ st.subheader(f'Predicted protein structure using seed: {word1}, {word2}, and {word3} + length ({sequence_length})')
56
+ render_mol(pdb_string)
57
+
58
+ # plDDT value is stored in the B-factor field
59
+ st.subheader('plDDT Score')
60
+ st.write('plDDT is a per-residue estimate of the confidence in prediction on a scale from 0-100.')
61
+ st.info(f'Average plDDT: {b_value}%')
62
+
63
+ st.download_button(
64
+ label="Download PDB",
65
+ data=pdb_string,
66
+ file_name='predicted.pdb',
67
+ mime='text/plain',
68
+ )
69
+ except requests.exceptions.RequestException as e:
70
+ st.error(f"An error occurred while calling the API: {str(e)}")
71
+ st.write("Please try again later or contact support if the issue persists.")
72
 
73
+ # Streamlit app
74
+ st.title("Word-Seeded Protein Sequence Generator and Structure Predictor")
 
 
75
 
76
+ # Input for word-seeded sequence generation
77
+ st.sidebar.subheader("Generate Sequence from Words")
78
+ word1 = st.sidebar.text_input("Word 1")
79
+ word2 = st.sidebar.text_input("Word 2")
80
+ word3 = st.sidebar.text_input("Word 3")
81
+ sequence_length = st.sidebar.number_input("Sequence Length", min_value=50, max_value=400, value=100, step=10)
82
 
83
+ # Generate and predict button
84
+ if st.sidebar.button('Generate and Predict'):
85
  if word1 and word2 and word3:
86
+ sequence = generate_sequence_from_words([word1, word2, word3], sequence_length)
87
+ st.sidebar.text_area("Generated Sequence", sequence, height=100)
88
+ st.sidebar.info("Note: The same words and length will always produce the same sequence.")
89
+
 
 
90
  with st.spinner("Predicting protein structure... This may take a few minutes."):
91
+ update(sequence, word1, word2, word3, sequence_length)
 
 
 
 
 
 
 
 
 
 
92
  else:
93
+ st.sidebar.warning("Please enter all three words to generate a sequence.")
94
 
95
+ # Information display
96
+ st.sidebar.markdown("""
97
  ## What to do next:
98
+ 1. Enter three words and a sequence length.
99
+ 2. Click 'Generate and Predict' to generate the sequence, visualize the protein, and get its plDDT score.
100
+ 3. Explore the 3D structure and download the PDB file if desired.
101
+ 4. Experiment with different words or sequence lengths to see how they affect the predicted structure.
102
+
103
+ Remember, these predictions are based on AI models and should be interpreted with caution.
104
  """)