Spaces:
Sleeping
Sleeping
File size: 8,296 Bytes
3e3ee14 0b0dafb 3e3ee14 0b0dafb 3e3ee14 0b0dafb 1adadbe 3e3ee14 0b0dafb 3e3ee14 0b0dafb 3e3ee14 0b0dafb 3e3ee14 0b0dafb 3e3ee14 0b0dafb 3e3ee14 0b0dafb 3e3ee14 0b0dafb 3e3ee14 1adadbe 0b0dafb 1adadbe 3e3ee14 0b0dafb 3e3ee14 0b0dafb 3e3ee14 0b0dafb 3e3ee14 0b0dafb 6e09236 0b0dafb 6e09236 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 | """Morph's public Gradio interface, with ZeroGPU generation."""
import json
from pathlib import Path
import spaces # Initialize ZeroGPU before importing torch through backend.
import gradio as gr
import pandas as pd
import py3Dmol
import html
from trajectory_view import trajectory_viewer
ROOT = Path(__file__).resolve().parent
REGISTRY = json.loads((ROOT / "models.json").read_text())
def description(key):
spec = REGISTRY[key]
return (
spec["description"]
+ f" [Model details](https://huggingface.co/maltefranke/morph/tree/main/{spec['checkpoint'].rsplit('/', 1)[0]})."
)
def change_model(key):
return (
gr.update(visible=REGISTRY[key]["kind"] == "logp"),
gr.update(visible=REGISTRY[key]["kind"] == "count"),
description(key),
)
def viewer(records, sample):
item = next((r for r in records if r["index"] == int(sample or 0)), None)
if item is None:
return "<p style='color:#65758b;padding:24px'>Generate molecules to explore their 3D structures.</p>"
view = py3Dmol.view(width="100%", height=410)
if item.get("molblock"):
view.addModel(item["molblock"], "sdf")
else:
view.addModel()
view.getModel().addAtoms(item["frames"][-1]["atoms"])
view.setStyle({"stick": {"radius": 0.15}, "sphere": {"scale": 0.23}})
view.setBackgroundColor("#f7f9fc")
view.zoomTo()
document = view._make_html()
return (
'<iframe title="Interactive molecule" sandbox="allow-scripts allow-same-origin" style="width:100%;height:425px;border:0;border-radius:12px" srcdoc="'
+ html.escape(document, quote=True)
+ '"></iframe>'
)
@spaces.GPU(duration=45)
def sample_on_gpu(key, target_logp, target_n, count, seed):
# Some scientific dependencies probe CUDA while importing. Import them
# only after ZeroGPU attaches the real device, keeping its parent clean.
from backend import MODELS, generate_graphs, load_models, present
if key not in MODELS:
load_models("cuda", keys=[key])
result = generate_graphs(
key, target_logp, target_n, count, seed, trajectory=True, require_gpu=True
)
return present(
result["graphs"],
key,
target_logp,
target_n,
seed,
trajectories=result["trajectories"],
times=result["times"],
runtime=result["runtime"],
)
def generate(key, target_logp, target_n, count, seed):
gallery, rows, records, sdf, csv, status, archive, runtime = sample_on_gpu(
key, target_logp, target_n, count, seed
)
choices = [str(record["index"]) for record in records]
selected = choices[0] if choices else None
table = pd.DataFrame(rows)[
["sample", "valid", "atoms", "logP", "target_logP", "target_N", "smiles"]
]
return (
gallery,
table,
records,
gr.update(choices=choices, value=selected),
viewer(records, selected),
sdf,
csv,
status,
gr.update(choices=choices, value=selected),
trajectory_viewer(records, selected),
archive,
runtime,
)
CSS = """
.gradio-container {max-width: 1250px !important; margin: auto;}
#hero {padding: 16px 4px 22px;}
#hero h1 {font-size: 40px; letter-spacing: -1.5px; margin-bottom: 6px;}
#hero p {font-size: 17px; color: #62738b;}
footer {display: none !important;}
"""
with gr.Blocks(
title="Morph 路 Molecular playground",
theme=gr.themes.Soft(primary_hue="blue", neutral_hue="slate"),
css=CSS,
delete_cache=(3600, 3600),
) as demo:
gr.Markdown("# Morph\nExplore molecular generation in 3D.", elem_id="hero")
records = gr.State([])
with gr.Row():
with gr.Column(scale=1, min_width=300):
model = gr.Dropdown(
[
(REGISTRY[key]["label"], key)
for key in ["geom", *[k for k in REGISTRY if k != "geom"]]
],
value="geom",
label="Model",
interactive=True,
)
note = gr.Markdown(description("geom"))
target_logp = gr.Slider(
-8, 9, value=2, step=0.1, label="Target logP", visible=False
)
target_n = gr.Slider(
3,
120,
value=40,
step=1,
label="Target atoms, including H",
visible=False,
)
count = gr.Slider(
1,
8,
value=4,
step=1,
label="Molecules",
)
seed = gr.Number(
value=42,
minimum=0,
maximum=2147483647,
precision=0,
label="Random seed",
)
button = gr.Button("Generate molecules", variant="primary", size="lg")
gr.Markdown(
"Shared GPU 路 You may need to sign in to Hugging Face and wait in the queue. Changing the seed gives new samples."
)
gr.Markdown(
"[Checkpoints & evaluation](https://huggingface.co/maltefranke/morph) 路 [Source](https://huggingface.co/spaces/maltefranke/morph-playground/tree/main)"
)
with gr.Column(scale=2, min_width=420):
status = gr.Markdown("Choose a model and generate your first molecules.")
with gr.Tabs():
with gr.Tab("Molecules"):
gallery = gr.Gallery(
label="Generated molecules",
columns=2,
height=600,
object_fit="contain",
show_label=False,
)
with gr.Tab("3D view"):
selected = gr.Dropdown(
choices=[], label="Molecule", interactive=True
)
structure = gr.HTML(viewer([], None))
gr.Markdown("Drag to rotate 路 Scroll to zoom")
with gr.Tab("Trajectory"):
trajectory_selected = gr.Dropdown(
choices=[], label="Molecule", interactive=True
)
trajectory_player = gr.HTML(trajectory_viewer([], None))
trajectory_file = gr.File(
label="Download trajectories (JSON + XYZ)"
)
with gr.Tab("Properties"):
table = gr.Dataframe(
interactive=False, wrap=True, label="Every generation attempt"
)
with gr.Row():
sdf = gr.File(label="Download 3D structures (SDF)")
csv = gr.File(label="Download properties (CSV)")
gr.Markdown(
"Generated targets are approximate. Chemical validity checks sanitization, connectedness and radicals (plus neutrality for QM9); it does not assess 3D geometry. Samples are shown without filtering or retrying. N includes hydrogens except for the ChEMBL3D heavy-atom model."
)
model.change(change_model, model, [target_logp, target_n, note], queue=False)
selected.change(viewer, [records, selected], structure, queue=False)
trajectory_selected.change(
trajectory_viewer,
[records, trajectory_selected],
trajectory_player,
queue=False,
)
runtime_info = gr.JSON(visible=False)
button.click(
generate,
[model, target_logp, target_n, count, seed],
[
gallery,
table,
records,
selected,
structure,
sdf,
csv,
status,
trajectory_selected,
trajectory_player,
trajectory_file,
runtime_info,
],
api_name="generate",
concurrency_limit=1,
)
if __name__ == "__main__":
from huggingface_hub import hf_hub_download
# Download once at startup; model construction runs in the GPU worker.
for spec in REGISTRY.values():
hf_hub_download(
"maltefranke/morph", spec["checkpoint"], revision=spec["revision"]
)
demo.queue(max_size=24).launch(ssr_mode=False)
|