pswap commited on
Commit
ef9616f
·
verified ·
1 Parent(s): 7ca1a38
Files changed (3) hide show
  1. README.md +51 -7
  2. app.py +176 -0
  3. requirements.txt +5 -0
README.md CHANGED
@@ -1,15 +1,59 @@
1
  ---
2
  title: Foldy
3
- emoji: 😻
4
- colorFrom: yellow
5
- colorTo: gray
6
  sdk: gradio
7
- sdk_version: 6.27.0
8
- python_version: '3.12'
9
  app_file: app.py
10
  pinned: false
11
  license: mit
12
- short_description: 'ESMfold2 '
 
 
 
 
 
 
 
13
  ---
14
 
15
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
  title: Foldy
3
+ emoji: 🧬
4
+ colorFrom: blue
5
+ colorTo: purple
6
  sdk: gradio
 
 
7
  app_file: app.py
8
  pinned: false
9
  license: mit
10
+ short_description: Protein structure prediction with ESMFold2 (ZeroGPU)
11
+ suggested_hardware: zero-a10g
12
+ tags:
13
+ - biology
14
+ - protein
15
+ - structure-prediction
16
+ - esmfold2
17
+ - zerogpu
18
  ---
19
 
20
+ # Foldy
21
+
22
+ Predicts 3D protein structure from amino acid sequences using
23
+ [ESMFold2](https://huggingface.co/biohub/ESMFold2-Fast) (Biohub), a 7B-parameter
24
+ diffusion-based structure predictor. Runs on Hugging Face's ZeroGPU.
25
+
26
+ ## Input
27
+
28
+ - A single raw amino acid sequence
29
+ - A multi-record FASTA (each `>` record becomes a chain — folds a complex)
30
+ - `/`-separated chains, e.g. `SEQ1/SEQ2`
31
+
32
+ Total length is capped (see `MAX_TOTAL_RESIDUES` in [app.py](app.py)) to keep inference
33
+ within the ZeroGPU time budget.
34
+
35
+ ## Output
36
+
37
+ - An interactive 3D viewer (py3Dmol), colored by predicted confidence (pLDDT)
38
+ - Mean pLDDT, pTM, and (for complexes) ipTM
39
+ - A downloadable mmCIF file
40
+
41
+ ## Notes
42
+
43
+ - Uses the `ESMFold2-Fast` checkpoint (single-sequence, no MSA) for speed. Swap
44
+ `MODEL_NAME` in [app.py](app.py) for `biohub/ESMFold2` if you want MSA-conditioned
45
+ predictions (slower, and you'll need to supply an MSA yourself).
46
+ - Model weights load once at startup in bfloat16 and are moved to the GPU inside the
47
+ `@spaces.GPU`-decorated function, per the ZeroGPU pattern.
48
+ - "Recycling loops" and "diffusion sampling steps" trade accuracy for speed — raise
49
+ them for harder targets, lower them for a faster demo.
50
+
51
+ ## Local development
52
+
53
+ ```bash
54
+ pip install -r requirements.txt
55
+ python app.py
56
+ ```
57
+
58
+ Folding requires a CUDA GPU; on Spaces, ZeroGPU provides this on demand via the
59
+ `spaces` package. Locally, you need your own GPU for `model.to("cuda")` to work.
app.py ADDED
@@ -0,0 +1,176 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Foldy — protein structure prediction with ESMFold2, on HF ZeroGPU."""
2
+
3
+ import os
4
+ import re
5
+ import string
6
+ import tempfile
7
+ import time
8
+
9
+ import gradio as gr
10
+ import py3Dmol
11
+ import spaces
12
+ import torch
13
+ from esm.models.esmfold2 import (
14
+ ESMFold2InputBuilder,
15
+ EsmFold2Model,
16
+ ProteinInput,
17
+ StructurePredictionInput,
18
+ )
19
+
20
+ # The -Fast checkpoint is single-sequence (no MSA), which keeps inference time
21
+ # reasonable on a shared ZeroGPU slot. Swap for "biohub/ESMFold2" for MSA-conditioned
22
+ # accuracy on hard targets (slower, needs an MSA pipeline this app doesn't provide).
23
+ MODEL_NAME = "biohub/ESMFold2-Fast"
24
+ MAX_TOTAL_RESIDUES = 600 # keeps inference within the ZeroGPU time/memory budget
25
+ VALID_AMINO_ACIDS = set("ACDEFGHIKLMNPQRSTVWYXBZUO")
26
+ CHAIN_IDS = string.ascii_uppercase
27
+
28
+ EXAMPLES = [
29
+ ["MQIFVKTLTGKTITLEVEPSDTIENVKAKIQDKEGIPPDQQRLIFAGKQLEDGRTLSDYNIQKESTLHLVLRLRGG"],
30
+ [">A\nMKTVRQERLKSIVRILERSKEPVSGAQLAEELSVSRQVIVQDIAYLRSLGYNIVATPRGYVLAGG"],
31
+ ]
32
+
33
+ print(f"Loading {MODEL_NAME} (this happens once at startup)...")
34
+ model = EsmFold2Model.from_pretrained(MODEL_NAME, device="cpu", dtype=torch.bfloat16).eval()
35
+ builder = ESMFold2InputBuilder()
36
+ print("Model loaded.")
37
+
38
+
39
+ def parse_chains(raw_text: str) -> list[tuple[str, str]]:
40
+ """Parse a raw sequence, multi-record FASTA, or '/'-separated chains into (chain_id, sequence) pairs."""
41
+ text = raw_text.strip()
42
+ if not text:
43
+ return []
44
+
45
+ records: list[str] = []
46
+ if text.startswith(">"):
47
+ buf: list[str] = []
48
+ for line in text.splitlines():
49
+ line = line.strip()
50
+ if not line:
51
+ continue
52
+ if line.startswith(">"):
53
+ if buf:
54
+ records.append("".join(buf))
55
+ buf = []
56
+ else:
57
+ buf.append(line)
58
+ if buf:
59
+ records.append("".join(buf))
60
+ else:
61
+ records = [chunk for chunk in re.split(r"[/\n]+", text) if chunk.strip()]
62
+
63
+ chains = []
64
+ for i, record in enumerate(records):
65
+ sequence = re.sub(r"[^A-Za-z]", "", record).upper()
66
+ if sequence:
67
+ chains.append((CHAIN_IDS[i % len(CHAIN_IDS)], sequence))
68
+ return chains
69
+
70
+
71
+ def render_structure(cif_str: str) -> str:
72
+ view = py3Dmol.view(width=600, height=500)
73
+ view.addModel(cif_str, "cif")
74
+ view.setStyle({"cartoon": {"colorscheme": {"prop": "b", "gradient": "roygb", "min": 50, "max": 90}}})
75
+ view.zoomTo()
76
+ raw_html = view._make_html()
77
+ escaped = raw_html.replace('"', """)
78
+ return f'<iframe style="width: 100%; height: 500px; border: none;" srcdoc="{escaped}"></iframe>'
79
+
80
+
81
+ @spaces.GPU(duration=300)
82
+ def fold_sequences(raw_text: str, num_loops: int, num_sampling_steps: int, progress=gr.Progress()):
83
+ chains = parse_chains(raw_text)
84
+ if not chains:
85
+ raise gr.Error("Please enter at least one protein sequence.")
86
+
87
+ for chain_id, sequence in chains:
88
+ invalid_chars = set(sequence) - VALID_AMINO_ACIDS
89
+ if invalid_chars:
90
+ raise gr.Error(f"Chain {chain_id}: invalid characters {', '.join(sorted(invalid_chars))}")
91
+
92
+ total_residues = sum(len(sequence) for _, sequence in chains)
93
+ if total_residues > MAX_TOTAL_RESIDUES:
94
+ raise gr.Error(
95
+ f"Total length is {total_residues} residues across {len(chains)} chain(s); this Space "
96
+ f"is limited to {MAX_TOTAL_RESIDUES} residues to keep inference within the ZeroGPU time budget."
97
+ )
98
+
99
+ progress(0.1, desc="Moving model to GPU...")
100
+ model.to("cuda")
101
+
102
+ progress(0.3, desc=f"Folding {len(chains)} chain(s), {total_residues} residues total...")
103
+ structure_input = StructurePredictionInput(
104
+ sequences=[ProteinInput(id=chain_id, sequence=sequence) for chain_id, sequence in chains]
105
+ )
106
+
107
+ start = time.time()
108
+ result = builder.fold(
109
+ model,
110
+ structure_input,
111
+ num_loops=num_loops,
112
+ num_sampling_steps=num_sampling_steps,
113
+ num_diffusion_samples=1,
114
+ seed=0,
115
+ )
116
+ elapsed = time.time() - start
117
+
118
+ progress(0.9, desc="Building structure file...")
119
+ cif_str = result.complex.to_mmcif()
120
+
121
+ cif_path = os.path.join(tempfile.gettempdir(), f"foldy_{int(time.time())}.cif")
122
+ with open(cif_path, "w") as f:
123
+ f.write(cif_str)
124
+
125
+ viewer_html = render_structure(cif_str)
126
+ mean_plddt = float(result.plddt.mean())
127
+ summary_lines = [
128
+ f"**Chains:** {len(chains)} ({', '.join(c for c, _ in chains)})",
129
+ f"**Total length:** {total_residues} residues",
130
+ f"**Mean pLDDT:** {mean_plddt:.1f} / 100",
131
+ f"**pTM:** {float(result.ptm):.3f}",
132
+ ]
133
+ if len(chains) > 1:
134
+ summary_lines.append(f"**ipTM:** {float(result.iptm):.3f}")
135
+ summary_lines.append(f"**Inference time:** {elapsed:.1f}s")
136
+
137
+ return viewer_html, " \n".join(summary_lines), cif_path
138
+
139
+
140
+ with gr.Blocks(title="Foldy — ESMFold2 Protein Structure Prediction", theme=gr.themes.Soft()) as demo:
141
+ gr.Markdown(
142
+ f"""
143
+ # 🧬 Foldy
144
+ Predict 3D protein structure from amino acid sequences using
145
+ [ESMFold2](https://huggingface.co/biohub/ESMFold2-Fast) (Biohub).
146
+ Paste a raw sequence, a multi-record FASTA, or `/`-separated chains to fold a complex
147
+ (max {MAX_TOTAL_RESIDUES} total residues). Structure is colored by predicted confidence
148
+ (pLDDT): blue = high, red = low.
149
+ """
150
+ )
151
+ with gr.Row():
152
+ with gr.Column(scale=1):
153
+ sequence_input = gr.Textbox(
154
+ label="Protein sequence(s)",
155
+ placeholder="Paste one sequence, a multi-record FASTA, or chains separated by '/'...",
156
+ lines=8,
157
+ )
158
+ with gr.Accordion("Advanced settings", open=False):
159
+ num_loops = gr.Slider(1, 3, value=1, step=1, label="Recycling loops")
160
+ num_sampling_steps = gr.Slider(10, 50, value=20, step=5, label="Diffusion sampling steps")
161
+ gr.Markdown("Higher values improve accuracy but increase inference time.")
162
+ fold_btn = gr.Button("Fold", variant="primary")
163
+ gr.Examples(examples=EXAMPLES, inputs=sequence_input, label="Example sequences")
164
+ summary_output = gr.Markdown(label="Summary")
165
+ cif_output = gr.File(label="Download mmCIF")
166
+ with gr.Column(scale=2):
167
+ structure_output = gr.HTML(label="Predicted structure")
168
+
169
+ fold_btn.click(
170
+ fn=fold_sequences,
171
+ inputs=[sequence_input, num_loops, num_sampling_steps],
172
+ outputs=[structure_output, summary_output, cif_output],
173
+ )
174
+
175
+ if __name__ == "__main__":
176
+ demo.queue(max_size=20).launch()
requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ gradio>=5.0
2
+ spaces
3
+ torch
4
+ esm>=3.4.1
5
+ py3Dmol