Spaces:
Running on Zero
Running on Zero
Add the Virtual OpenCell tab: browse CELL-FM's virtual staining of 1,276 OpenCell proteins
Browse files- README.md +30 -0
- app.py +109 -1
- assets/virtual_opencell_proteins.csv +0 -0
- cell_fm/apps/virtual_opencell/__init__.py +7 -0
- cell_fm/apps/virtual_opencell/viewer.py +294 -0
README.md
CHANGED
|
@@ -71,6 +71,36 @@ is the quickest way to see the model respond to sequence grammar.
|
|
| 71 |
|
| 72 |
---
|
| 73 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 74 |
## Hardware
|
| 75 |
|
| 76 |
**A GPU is required in practice.** The code itself runs on CPU — `flash-attn` is
|
|
|
|
| 71 |
|
| 72 |
---
|
| 73 |
|
| 74 |
+
## Virtual OpenCell
|
| 75 |
+
|
| 76 |
+
Browse CELL-FM's virtual staining of 1,276 OpenCell proteins, laid out like an
|
| 77 |
+
[OpenCell](https://opencell.sf.czbiohub.org/) target page. Search for a protein:
|
| 78 |
+
|
| 79 |
+
- **Left** is OpenCell's annotation of the *real* cell line: localization grades
|
| 80 |
+
(bar height is the grade, 3 the most prominent), UniProt and Ensembl IDs, sequence
|
| 81 |
+
length, HEK293 abundance, and a link to the real images on OpenCell. None of it is
|
| 82 |
+
predicted.
|
| 83 |
+
- **Right** are CELL-FM's images, in OpenCell's colours: the nucleus blue and the
|
| 84 |
+
generated protein (the *target*) gray. OpenCell's channel switch and per-channel
|
| 85 |
+
intensity range and gamma adjust the view; the strip below holds every sample of
|
| 86 |
+
the protein, and **Download TIFF** saves the selected one as the raw 2-channel image.
|
| 87 |
+
|
| 88 |
+
Every image is generated from the protein sequence in **one shared cell**: the nucleus
|
| 89 |
+
channel is the same real nucleus (ATG7, crop 1) for every protein, so differences
|
| 90 |
+
between proteins come from the sequence, and a protein's samples are independent
|
| 91 |
+
draws for that cell.
|
| 92 |
+
|
| 93 |
+
The images are the dataset
|
| 94 |
+
[`BoHuangLab/CELL-FM`](https://huggingface.co/datasets/BoHuangLab/CELL-FM):
|
| 95 |
+
`OpenCell/virtual_staining/<GENE>/<NNNN>.tif`, 93,510 samples, each (2, 256, 256)
|
| 96 |
+
uint16 with the nucleus first. A protein's samples are fetched the first time it is
|
| 97 |
+
viewed (`VIRTUAL_OPENCELL_LOCAL_DIR` reads a local copy instead); while that repo is
|
| 98 |
+
private, the Space needs an `HF_TOKEN` secret that can read it. The protein table,
|
| 99 |
+
`assets/virtual_opencell_proteins.csv`, is built by
|
| 100 |
+
`notebooks/tools/build_virtual_opencell_assets.py`. This section runs on CPU.
|
| 101 |
+
|
| 102 |
+
---
|
| 103 |
+
|
| 104 |
## Hardware
|
| 105 |
|
| 106 |
**A GPU is required in practice.** The code itself runs on CPU — `flash-attn` is
|
app.py
CHANGED
|
@@ -7,6 +7,8 @@ titration curve, and integrates it into AUC (condensation propensity) and AAC
|
|
| 7 |
"""
|
| 8 |
|
| 9 |
import os
|
|
|
|
|
|
|
| 10 |
|
| 11 |
import gradio as gr
|
| 12 |
import matplotlib
|
|
@@ -16,6 +18,7 @@ import numpy as np
|
|
| 16 |
import pandas as pd
|
| 17 |
|
| 18 |
from cell_fm.apps.condenseq import metrics, pipeline
|
|
|
|
| 19 |
|
| 20 |
# gradio_client walks component API schemas to build /gradio_api/info. JSON Schema
|
| 21 |
# allows `additionalProperties: true`, but the walker recurses into that bool as if
|
|
@@ -66,6 +69,9 @@ def load_default_sequence() -> str:
|
|
| 66 |
|
| 67 |
DEFAULT_SEQUENCE = load_default_sequence()
|
| 68 |
|
|
|
|
|
|
|
|
|
|
| 69 |
|
| 70 |
def plot_curve(result: pipeline.Result):
|
| 71 |
"""The titration curve, with the two integrated areas drawn as the areas they are."""
|
|
@@ -240,7 +246,107 @@ def build_condensate_titration_section():
|
|
| 240 |
)
|
| 241 |
|
| 242 |
|
| 243 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 244 |
gr.Markdown(
|
| 245 |
"""
|
| 246 |
# CELL-FM
|
|
@@ -252,6 +358,8 @@ with gr.Blocks(title="CELL-FM", theme=gr.themes.Soft()) as demo:
|
|
| 252 |
with gr.Tabs():
|
| 253 |
with gr.Tab("Condensate Titration"):
|
| 254 |
build_condensate_titration_section()
|
|
|
|
|
|
|
| 255 |
|
| 256 |
|
| 257 |
# Download weights and build the models at startup, on CPU. Under ZeroGPU the GPU
|
|
|
|
| 7 |
"""
|
| 8 |
|
| 9 |
import os
|
| 10 |
+
import shutil
|
| 11 |
+
import tempfile
|
| 12 |
|
| 13 |
import gradio as gr
|
| 14 |
import matplotlib
|
|
|
|
| 18 |
import pandas as pd
|
| 19 |
|
| 20 |
from cell_fm.apps.condenseq import metrics, pipeline
|
| 21 |
+
from cell_fm.apps.virtual_opencell import viewer
|
| 22 |
|
| 23 |
# gradio_client walks component API schemas to build /gradio_api/info. JSON Schema
|
| 24 |
# allows `additionalProperties: true`, but the walker recurses into that bool as if
|
|
|
|
| 69 |
|
| 70 |
DEFAULT_SEQUENCE = load_default_sequence()
|
| 71 |
|
| 72 |
+
# The proteins with virtual staining, and OpenCell's annotations of their real cell lines
|
| 73 |
+
PROTEINS = viewer.load_catalog(os.path.join(HERE, "assets", "virtual_opencell_proteins.csv"))
|
| 74 |
+
|
| 75 |
|
| 76 |
def plot_curve(result: pipeline.Result):
|
| 77 |
"""The titration curve, with the two integrated areas drawn as the areas they are."""
|
|
|
|
| 246 |
)
|
| 247 |
|
| 248 |
|
| 249 |
+
def build_virtual_opencell_section():
|
| 250 |
+
"""Pick an OpenCell protein and browse CELL-FM's virtual staining of it, laid out like an
|
| 251 |
+
OpenCell target page: the real cell line's annotations on the left, the images on the right."""
|
| 252 |
+
|
| 253 |
+
def load(gene):
|
| 254 |
+
row = PROTEINS.loc[gene]
|
| 255 |
+
stack, paths = viewer.load_samples(gene, int(row["n_samples"]))
|
| 256 |
+
return row, stack, paths
|
| 257 |
+
|
| 258 |
+
def show(gene, index, channel, n_min, n_max, n_gamma, t_min, t_max, t_gamma):
|
| 259 |
+
_, stack, _ = load(gene)
|
| 260 |
+
return viewer.render(stack[index], channel, (n_min, n_max, n_gamma), (t_min, t_max, t_gamma))
|
| 261 |
+
|
| 262 |
+
def sample_file(gene, index):
|
| 263 |
+
"""The raw sample under a readable name, copied where Gradio is allowed to serve it."""
|
| 264 |
+
_, _, paths = load(gene)
|
| 265 |
+
path = os.path.join(tempfile.gettempdir(), f"virtual_opencell_{gene}_{index + 1:04d}.tif")
|
| 266 |
+
shutil.copyfile(paths[index], path)
|
| 267 |
+
return path
|
| 268 |
+
|
| 269 |
+
def protein_view(gene, *settings):
|
| 270 |
+
"""Panel, thumbnails, first sample and its file for one protein."""
|
| 271 |
+
row, stack, _ = load(gene)
|
| 272 |
+
image = show(gene, 0, *settings)
|
| 273 |
+
return viewer.target_html(gene, row), viewer.thumbnails(stack), image, sample_file(gene, 0)
|
| 274 |
+
|
| 275 |
+
def select_protein(gene, channel, n_min, n_max, n_gamma, t_min, t_max, t_gamma):
|
| 276 |
+
try:
|
| 277 |
+
info, thumbs, image, path = protein_view(gene, channel, n_min, n_max, n_gamma, t_min, t_max, t_gamma)
|
| 278 |
+
except Exception as exc:
|
| 279 |
+
raise gr.Error(f"Could not load the images for {gene}: {viewer.load_error(exc)}") from exc
|
| 280 |
+
return info, gr.Gallery(value=thumbs, selected_index=0), image, 0, path
|
| 281 |
+
|
| 282 |
+
def select_sample(gene, channel, n_min, n_max, n_gamma, t_min, t_max, t_gamma, evt: gr.SelectData):
|
| 283 |
+
image = show(gene, evt.index, channel, n_min, n_max, n_gamma, t_min, t_max, t_gamma)
|
| 284 |
+
return image, evt.index, sample_file(gene, evt.index)
|
| 285 |
+
|
| 286 |
+
# Shown on first load: the default protein, unless its images cannot be fetched
|
| 287 |
+
defaults = ("Both", 0, 100, 1.0, 0, 100, 1.0)
|
| 288 |
+
try:
|
| 289 |
+
info0, thumbs0, image0, file0 = protein_view(viewer.DEFAULT_GENE, *defaults)
|
| 290 |
+
except Exception as exc: # e.g. no access to the dataset; the error is shown in the panel
|
| 291 |
+
print(f"[startup] virtual OpenCell preload failed: {exc}")
|
| 292 |
+
info0, thumbs0, image0, file0 = viewer.error_html(viewer.DEFAULT_GENE, exc), None, None, None
|
| 293 |
+
|
| 294 |
+
with gr.Column(elem_id="virtual-opencell"):
|
| 295 |
+
with gr.Row(elem_classes="vo-navbar", equal_height=True):
|
| 296 |
+
gr.HTML(viewer.NAVBAR_HTML)
|
| 297 |
+
protein = gr.Dropdown(
|
| 298 |
+
choices=list(PROTEINS.index), value=viewer.DEFAULT_GENE, filterable=True,
|
| 299 |
+
show_label=False, container=False, scale=0, min_width=220, elem_classes="vo-search",
|
| 300 |
+
)
|
| 301 |
+
|
| 302 |
+
with gr.Row():
|
| 303 |
+
with gr.Column(scale=4):
|
| 304 |
+
info = gr.HTML(info0)
|
| 305 |
+
|
| 306 |
+
with gr.Column(scale=6):
|
| 307 |
+
with gr.Row():
|
| 308 |
+
channel = gr.Radio(viewer.CHANNELS, value=defaults[0], label="Channel",
|
| 309 |
+
elem_classes="vo-buttons")
|
| 310 |
+
download = gr.DownloadButton("Download TIFF", value=file0, size="sm", variant="secondary",
|
| 311 |
+
scale=0, min_width=140, elem_classes="vo-download")
|
| 312 |
+
image = gr.Image(
|
| 313 |
+
value=image0, show_label=False, interactive=False, height=600,
|
| 314 |
+
show_download_button=True, elem_classes="vo-viewer",
|
| 315 |
+
)
|
| 316 |
+
gr.HTML('<div class="vo-settings-label">Samples</div>', padding=False)
|
| 317 |
+
samples = gr.Gallery(
|
| 318 |
+
value=thumbs0, selected_index=0 if thumbs0 else None, show_label=False,
|
| 319 |
+
columns=8, height=230, allow_preview=False, object_fit="contain",
|
| 320 |
+
show_share_button=False, show_download_button=False, elem_classes="vo-thumbnails",
|
| 321 |
+
)
|
| 322 |
+
with gr.Row(elem_classes="vo-settings"):
|
| 323 |
+
with gr.Column():
|
| 324 |
+
gr.HTML('<div class="vo-settings-label">Nucleus image settings</div>', padding=False)
|
| 325 |
+
n_min = gr.Slider(0, 100, value=defaults[1], step=1, label="Intensity min (%)")
|
| 326 |
+
n_max = gr.Slider(1, 150, value=defaults[2], step=1, label="Intensity max (%)")
|
| 327 |
+
n_gamma = gr.Slider(0.5, 1.5, value=defaults[3], step=0.05, label="Gamma")
|
| 328 |
+
with gr.Column():
|
| 329 |
+
gr.HTML('<div class="vo-settings-label">Target image settings</div>', padding=False)
|
| 330 |
+
t_min = gr.Slider(0, 100, value=defaults[4], step=1, label="Intensity min (%)")
|
| 331 |
+
t_max = gr.Slider(1, 150, value=defaults[5], step=1, label="Intensity max (%)")
|
| 332 |
+
t_gamma = gr.Slider(0.5, 1.5, value=defaults[6], step=0.05, label="Gamma")
|
| 333 |
+
|
| 334 |
+
gr.HTML(viewer.FOOTER_HTML)
|
| 335 |
+
|
| 336 |
+
index = gr.State(0)
|
| 337 |
+
settings = [channel, n_min, n_max, n_gamma, t_min, t_max, t_gamma]
|
| 338 |
+
|
| 339 |
+
protein.change(select_protein, inputs=[protein] + settings,
|
| 340 |
+
outputs=[info, samples, image, index, download])
|
| 341 |
+
# Redraws take milliseconds: no progress overlay, and a dragged slider only renders its latest value
|
| 342 |
+
samples.select(select_sample, inputs=[protein] + settings, outputs=[image, index, download],
|
| 343 |
+
show_progress="hidden")
|
| 344 |
+
for control in settings:
|
| 345 |
+
control.change(show, inputs=[protein, index] + settings, outputs=image,
|
| 346 |
+
show_progress="hidden", trigger_mode="always_last")
|
| 347 |
+
|
| 348 |
+
|
| 349 |
+
with gr.Blocks(title="CELL-FM", theme=gr.themes.Soft(), css=viewer.CSS, head=viewer.HEAD) as demo:
|
| 350 |
gr.Markdown(
|
| 351 |
"""
|
| 352 |
# CELL-FM
|
|
|
|
| 358 |
with gr.Tabs():
|
| 359 |
with gr.Tab("Condensate Titration"):
|
| 360 |
build_condensate_titration_section()
|
| 361 |
+
with gr.Tab("Virtual OpenCell"):
|
| 362 |
+
build_virtual_opencell_section()
|
| 363 |
|
| 364 |
|
| 365 |
# Download weights and build the models at startup, on CPU. Under ZeroGPU the GPU
|
assets/virtual_opencell_proteins.csv
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
cell_fm/apps/virtual_opencell/__init__.py
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""The Virtual OpenCell app: browse CELL-FM's virtual staining of the OpenCell proteins.
|
| 2 |
+
|
| 3 |
+
Kept in the tracked package, like the CondenSeq app, so the logic behind the Space is on
|
| 4 |
+
GitHub; the Space imports the same module from its vendored copy of cell_fm.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from . import viewer # noqa: F401
|
cell_fm/apps/virtual_opencell/viewer.py
ADDED
|
@@ -0,0 +1,294 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Virtual OpenCell: CELL-FM's virtual staining of the OpenCell proteins, browsed like OpenCell.
|
| 2 |
+
|
| 3 |
+
The images are the dataset repo BoHuangLab/CELL-FM, one folder per protein:
|
| 4 |
+
|
| 5 |
+
OpenCell/virtual_staining/<GENE>/<NNNN>.tif (2, 256, 256) uint16
|
| 6 |
+
|
| 7 |
+
Channel 0 is the nucleus every sample was conditioned on: one real cell (ATG7, crop 1),
|
| 8 |
+
shared by all 1276 proteins, so differences between proteins are the model's and not the
|
| 9 |
+
cell's. Channel 1 is the protein CELL-FM generated from the sequence; a protein's samples
|
| 10 |
+
are independent draws for that same cell. They are fetched the first time a protein is
|
| 11 |
+
viewed and kept in memory.
|
| 12 |
+
|
| 13 |
+
The annotations shown beside the images (the catalog CSV, built by
|
| 14 |
+
notebooks/tools/build_virtual_opencell_assets.py) are OpenCell's measurements of the *real*
|
| 15 |
+
cell line -- localization grades, identifiers, abundance -- shown for comparison, not
|
| 16 |
+
predicted.
|
| 17 |
+
|
| 18 |
+
Images come from the Hub by default (HF_TOKEN is used if the repo is private). Set
|
| 19 |
+
VIRTUAL_OPENCELL_LOCAL_DIR to a local copy of the dataset, the folder holding OpenCell/, to
|
| 20 |
+
read them from disk instead.
|
| 21 |
+
"""
|
| 22 |
+
|
| 23 |
+
import html
|
| 24 |
+
import os
|
| 25 |
+
from concurrent.futures import ThreadPoolExecutor
|
| 26 |
+
from functools import lru_cache
|
| 27 |
+
|
| 28 |
+
import numpy as np
|
| 29 |
+
import pandas as pd
|
| 30 |
+
import tifffile
|
| 31 |
+
|
| 32 |
+
DATASET_REPO = os.environ.get("VIRTUAL_OPENCELL_REPO", "BoHuangLab/CELL-FM")
|
| 33 |
+
LOCAL_DIR = os.environ.get("VIRTUAL_OPENCELL_LOCAL_DIR", "")
|
| 34 |
+
IMAGE_DIR = "OpenCell/virtual_staining"
|
| 35 |
+
|
| 36 |
+
DEFAULT_GENE = "TOMM20"
|
| 37 |
+
CHANNELS = ["Nucleus", "Target", "Both"] # OpenCell's names for the 405 and 488 channels
|
| 38 |
+
|
| 39 |
+
# OpenCell draws the nucleus in blue and the tagged target in gray; colours add in "Both"
|
| 40 |
+
NUCLEUS_RGB = np.array([0.0, 0.45, 1.0], dtype=np.float32)
|
| 41 |
+
TARGET_RGB = np.array([1.0, 1.0, 1.0], dtype=np.float32)
|
| 42 |
+
# Auto-contrast: 0-100% of the intensity range maps this percentile window to black-white
|
| 43 |
+
AUTO_PERCENTILES = (0.1, 99.9)
|
| 44 |
+
|
| 45 |
+
THUMBNAIL_SIZE = 128
|
| 46 |
+
OPENCELL_URL = "https://opencell.sf.czbiohub.org"
|
| 47 |
+
|
| 48 |
+
# OpenCell's localization categories, as its pages print them
|
| 49 |
+
LOCALIZATION_NAMES = {
|
| 50 |
+
"er": "ER",
|
| 51 |
+
"golgi": "Golgi",
|
| 52 |
+
"nucleolus_gc": "nucleolus GC",
|
| 53 |
+
"nucleolus_fc_dfc": "nucleolus FC/DFC",
|
| 54 |
+
}
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def load_catalog(path: str) -> pd.DataFrame:
|
| 58 |
+
"""The protein table, indexed by gene name."""
|
| 59 |
+
return pd.read_csv(path, keep_default_na=False, na_values=[""]).set_index("gene_name")
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def _sample_files(gene: str, n_samples: int) -> list:
|
| 63 |
+
"""Local paths of a protein's samples, downloading them first unless reading from disk.
|
| 64 |
+
|
| 65 |
+
Files are numbered 0001.tif .. NNNN.tif without gaps, so they are requested by name;
|
| 66 |
+
listing the 93k-file repo on every selection would be far slower.
|
| 67 |
+
"""
|
| 68 |
+
names = [f"{IMAGE_DIR}/{gene}/{i:04d}.tif" for i in range(1, n_samples + 1)]
|
| 69 |
+
if LOCAL_DIR:
|
| 70 |
+
return [os.path.join(LOCAL_DIR, name) for name in names]
|
| 71 |
+
|
| 72 |
+
from huggingface_hub import hf_hub_download
|
| 73 |
+
|
| 74 |
+
def fetch(name):
|
| 75 |
+
return hf_hub_download(repo_id=DATASET_REPO, filename=name, repo_type="dataset")
|
| 76 |
+
|
| 77 |
+
with ThreadPoolExecutor(max_workers=16) as pool:
|
| 78 |
+
return list(pool.map(fetch, names))
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
@lru_cache(maxsize=16)
|
| 82 |
+
def load_samples(gene: str, n_samples: int):
|
| 83 |
+
"""(stack, paths): stack is (N, 2, H, W) uint16, nucleus first."""
|
| 84 |
+
paths = _sample_files(gene, n_samples)
|
| 85 |
+
return np.stack([tifffile.imread(p) for p in paths]), tuple(paths)
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def _scale(channel: np.ndarray, low: float, high: float, gamma: float) -> np.ndarray:
|
| 89 |
+
"""One channel to [0, 1]: auto-contrast, then OpenCell's intensity range (%) and gamma."""
|
| 90 |
+
lo, hi = np.percentile(channel, AUTO_PERCENTILES)
|
| 91 |
+
x = (channel.astype(np.float32) - lo) / max(hi - lo, 1.0)
|
| 92 |
+
low, high = low / 100.0, max(high, low + 1.0) / 100.0
|
| 93 |
+
return np.clip((x - low) / (high - low), 0.0, 1.0) ** gamma
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def render(sample: np.ndarray, channel: str = "Both",
|
| 97 |
+
nucleus=(0, 100, 1.0), target=(0, 100, 1.0)) -> np.ndarray:
|
| 98 |
+
"""A (2, H, W) sample as an (H, W, 3) uint8 image; nucleus/target are (min %, max %, gamma)."""
|
| 99 |
+
rgb = np.zeros(sample.shape[1:] + (3,), dtype=np.float32)
|
| 100 |
+
if channel in ("Nucleus", "Both"):
|
| 101 |
+
rgb += _scale(sample[0], *nucleus)[..., None] * NUCLEUS_RGB
|
| 102 |
+
if channel in ("Target", "Both"):
|
| 103 |
+
rgb += _scale(sample[1], *target)[..., None] * TARGET_RGB
|
| 104 |
+
return (np.clip(rgb, 0.0, 1.0) * 255).astype(np.uint8)
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def thumbnails(stack: np.ndarray) -> list:
|
| 108 |
+
"""Both channels at default settings, downsized for the sample strip."""
|
| 109 |
+
step = max(stack.shape[-1] // THUMBNAIL_SIZE, 1)
|
| 110 |
+
return [render(sample)[::step, ::step] for sample in stack]
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def _localization_name(category: str) -> str:
|
| 114 |
+
return LOCALIZATION_NAMES.get(category, category.replace("_", " "))
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def _metadata_item(label: str, value: str) -> str:
|
| 118 |
+
return (f'<div class="vo-metadata-item"><div class="vo-metadata-label">{label}</div>'
|
| 119 |
+
f'<div class="vo-metadata-value">{value}</div></div>')
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def target_html(gene: str, row: pd.Series) -> str:
|
| 123 |
+
"""The left-hand panel of an OpenCell target page: name, identifiers, localization."""
|
| 124 |
+
esc = html.escape
|
| 125 |
+
uniprot, ensg, cid = row["uniprot_id"], row["ensg_id"], row["opencell_cid"]
|
| 126 |
+
|
| 127 |
+
items = [
|
| 128 |
+
_metadata_item("UniProt ID", f'<a href="https://www.uniprot.org/uniprotkb/{esc(uniprot)}" '
|
| 129 |
+
f'target="_blank">{esc(uniprot)}</a>'),
|
| 130 |
+
_metadata_item("Ensembl ID", f'<a href="https://www.ensembl.org/Homo_sapiens/Gene/Summary?g={esc(ensg)}" '
|
| 131 |
+
f'target="_blank">{esc(ensg)}</a>'),
|
| 132 |
+
_metadata_item("Sequence length", f"{int(row['sequence_length'])} aa"),
|
| 133 |
+
]
|
| 134 |
+
if pd.notna(row["hek_protein_conc_nm"]):
|
| 135 |
+
items.append(_metadata_item("HEK293 abundance", f"{row['hek_protein_conc_nm']:,.0f} nM"))
|
| 136 |
+
|
| 137 |
+
rows = []
|
| 138 |
+
for grade in (3, 2, 1):
|
| 139 |
+
value = row[f"grade_{grade}"]
|
| 140 |
+
for category in ([] if pd.isna(value) else value.split(";")):
|
| 141 |
+
rows.append(
|
| 142 |
+
f'<div class="vo-localization-row"><div class="vo-grade-container">'
|
| 143 |
+
f'<div class="vo-grade vo-grade-{grade}"></div></div>'
|
| 144 |
+
f'<div>{esc(_localization_name(category))}</div></div>'
|
| 145 |
+
)
|
| 146 |
+
localization = "".join(rows) or '<div class="vo-muted">Not annotated by OpenCell</div>'
|
| 147 |
+
|
| 148 |
+
name = row["protein_name"] if pd.notna(row["protein_name"]) else ""
|
| 149 |
+
return f"""
|
| 150 |
+
<div class="vo-target">
|
| 151 |
+
<div class="vo-target-name">{esc(gene)}</div>
|
| 152 |
+
<div class="vo-protein-description">{esc(name)}</div>
|
| 153 |
+
<div class="vo-status">CELL-FM virtual staining · {int(row['n_samples'])} samples</div>
|
| 154 |
+
<div class="vo-metadata">{''.join(items)}</div>
|
| 155 |
+
<div class="vo-section-header">Protein localization</div>
|
| 156 |
+
<div class="vo-section-caption">OpenCell's annotation of the real cell line; bar height is the grade</div>
|
| 157 |
+
{localization}
|
| 158 |
+
<div class="vo-external-links">
|
| 159 |
+
<a href="{OPENCELL_URL}/target/{esc(cid)}" target="_blank">Real images on OpenCell</a>
|
| 160 |
+
<a href="https://www.uniprot.org/uniprotkb/{esc(uniprot)}" target="_blank">UniProt</a>
|
| 161 |
+
<a href="https://www.ensembl.org/Homo_sapiens/Gene/Summary?g={esc(ensg)}" target="_blank">Ensembl</a>
|
| 162 |
+
</div>
|
| 163 |
+
</div>
|
| 164 |
+
"""
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
def load_error(exc: Exception) -> str:
|
| 168 |
+
"""Why a protein's images could not be loaded, in words a visitor can act on."""
|
| 169 |
+
# A private repo answers 404 to anyone without access, so "not found" means "no access" here
|
| 170 |
+
if type(exc).__name__ in ("RepositoryNotFoundError", "GatedRepoError"):
|
| 171 |
+
return f"the image dataset {DATASET_REPO} is not readable here (private, with no token that can read it)."
|
| 172 |
+
return str(exc).splitlines()[0]
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
def error_html(gene: str, exc: Exception) -> str:
|
| 176 |
+
return (f'<div class="vo-target"><div class="vo-target-name">{html.escape(gene)}</div>'
|
| 177 |
+
f'<div class="vo-muted">Could not load the images: {html.escape(load_error(exc))}</div></div>')
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
NAVBAR_HTML = """
|
| 181 |
+
<div class="vo-navbar-brand">
|
| 182 |
+
<span class="vo-navbar-title">Virtual OpenCell</span>
|
| 183 |
+
<span class="vo-navbar-menu">CELL-FM virtual staining of 1,276 OpenCell proteins</span>
|
| 184 |
+
</div>
|
| 185 |
+
"""
|
| 186 |
+
|
| 187 |
+
FOOTER_HTML = f"""
|
| 188 |
+
<div class="vo-footer">
|
| 189 |
+
Each image is CELL-FM's prediction from the protein sequence alone, drawn in one shared cell:
|
| 190 |
+
the nucleus channel is the same real nucleus for every protein, so differences between
|
| 191 |
+
proteins come from the sequence. Localization grades, identifiers and abundance are
|
| 192 |
+
OpenCell's measurements of the real cell lines
|
| 193 |
+
(<a href="{OPENCELL_URL}" target="_blank">OpenCell</a>; Cho et al., <i>Science</i> 2022).
|
| 194 |
+
</div>
|
| 195 |
+
"""
|
| 196 |
+
|
| 197 |
+
# Fonts OpenCell uses: Lato for names and titles, Nunito Sans for metadata labels
|
| 198 |
+
HEAD = """
|
| 199 |
+
<link rel="preconnect" href="https://fonts.googleapis.com">
|
| 200 |
+
<link href="https://fonts.googleapis.com/css2?family=Lato:wght@300;400;600;700&family=Nunito+Sans:wght@300;400;700&display=swap" rel="stylesheet">
|
| 201 |
+
"""
|
| 202 |
+
|
| 203 |
+
# OpenCell's look (its stylesheet: navbar, clm-*, metadata-*, localization-grade-*,
|
| 204 |
+
# slice-viewer-*, roi-thumbnail-*), scoped to the tab so the other sections keep the theme
|
| 205 |
+
CSS = """
|
| 206 |
+
#virtual-opencell {
|
| 207 |
+
--vo-blue: #01a1dd;
|
| 208 |
+
--color-accent: #137cbd;
|
| 209 |
+
--color-accent-soft: #e8f2fa;
|
| 210 |
+
--slider-color: #137cbd;
|
| 211 |
+
/* OpenCell is flat: no cards, small grey labels instead of the theme's badges */
|
| 212 |
+
--block-background-fill: transparent;
|
| 213 |
+
--block-border-width: 0px;
|
| 214 |
+
--block-shadow: none;
|
| 215 |
+
--block-title-background-fill: none;
|
| 216 |
+
--block-title-border-width: 0px;
|
| 217 |
+
--block-title-text-color: #999;
|
| 218 |
+
--block-title-text-size: 12px;
|
| 219 |
+
--block-title-text-weight: 400;
|
| 220 |
+
--block-title-padding: 0;
|
| 221 |
+
--block-label-background-fill: none;
|
| 222 |
+
--block-label-text-color: #999;
|
| 223 |
+
--panel-background-fill: transparent;
|
| 224 |
+
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
|
| 225 |
+
color: #182026;
|
| 226 |
+
}
|
| 227 |
+
#virtual-opencell a { color: #333; text-decoration: underline; }
|
| 228 |
+
#virtual-opencell a:hover { color: #999; }
|
| 229 |
+
|
| 230 |
+
/* navbar: grey band, cyan Lato title, small-caps menu, bold uppercase search */
|
| 231 |
+
#virtual-opencell .vo-navbar {
|
| 232 |
+
background: #eee; border-radius: 6px; padding: 8px 16px; align-items: center; margin-bottom: 8px;
|
| 233 |
+
}
|
| 234 |
+
#virtual-opencell .vo-navbar-title {
|
| 235 |
+
color: var(--vo-blue); font-family: "Lato", sans-serif; font-size: 30px; font-weight: 600;
|
| 236 |
+
letter-spacing: 1px; margin-right: 24px;
|
| 237 |
+
}
|
| 238 |
+
#virtual-opencell .vo-navbar-menu {
|
| 239 |
+
color: #333; font-size: 20px; font-variant: all-small-caps;
|
| 240 |
+
}
|
| 241 |
+
#virtual-opencell .vo-search input {
|
| 242 |
+
font-size: 22px !important; font-weight: bold; text-transform: uppercase; background: #fff;
|
| 243 |
+
}
|
| 244 |
+
|
| 245 |
+
/* target panel (OpenCell's clm-*) */
|
| 246 |
+
#virtual-opencell .vo-target { font-family: "Lato", sans-serif; padding-right: 12px; }
|
| 247 |
+
#virtual-opencell .vo-target-name { font-size: 60px; font-weight: 400; line-height: 1.1; }
|
| 248 |
+
#virtual-opencell .vo-protein-description { font-size: 20px; font-weight: 300; margin-top: 4px; }
|
| 249 |
+
#virtual-opencell .vo-status { font-size: 16px; font-weight: 300; font-style: italic; margin-top: 6px; color: #555; }
|
| 250 |
+
#virtual-opencell .vo-metadata { display: flex; flex-wrap: wrap; margin: 18px 0 8px 0; }
|
| 251 |
+
#virtual-opencell .vo-metadata-item { margin: 0 25px 12px 0; max-width: 200px; color: #333; font-size: 15px; }
|
| 252 |
+
#virtual-opencell .vo-metadata-label { color: #aaa; font-family: "Nunito Sans", sans-serif; font-size: 13px; }
|
| 253 |
+
#virtual-opencell .vo-section-header { font-size: 20px; font-weight: 400; margin-top: 14px; border-bottom: 1px solid #eee; }
|
| 254 |
+
#virtual-opencell .vo-section-caption { color: #999; font-size: 12px; margin: 4px 0 6px 0; }
|
| 255 |
+
#virtual-opencell .vo-localization-row { display: flex; align-items: center; padding: 3px 0; font-size: 16px; }
|
| 256 |
+
#virtual-opencell .vo-grade-container { width: 32px; height: 22px; padding: 0 3px; margin-right: 8px; display: flex; align-items: flex-end; }
|
| 257 |
+
#virtual-opencell .vo-grade { width: 100%; border-radius: 5px; }
|
| 258 |
+
#virtual-opencell .vo-grade-1 { height: 10px; background-color: #ccdeef; }
|
| 259 |
+
#virtual-opencell .vo-grade-2 { height: 14px; background-color: #51ade1cc; }
|
| 260 |
+
#virtual-opencell .vo-grade-3 { height: 18px; background-color: #00477bcc; }
|
| 261 |
+
#virtual-opencell .vo-external-links { margin-top: 18px; font-size: 14px; }
|
| 262 |
+
#virtual-opencell .vo-external-links a { margin-right: 16px; }
|
| 263 |
+
#virtual-opencell .vo-muted { color: #999; font-size: 14px; }
|
| 264 |
+
|
| 265 |
+
/* Gradio groups inputs in a grey .form box; OpenCell lays them straight on the page */
|
| 266 |
+
#virtual-opencell .form { background: transparent !important; border: none !important; box-shadow: none !important; }
|
| 267 |
+
|
| 268 |
+
/* viewer: black, rounded, the image filling it (slice-viewer-canvas-container) */
|
| 269 |
+
#virtual-opencell .vo-viewer { background: #000 !important; border-radius: 10px !important; overflow: hidden; }
|
| 270 |
+
#virtual-opencell .vo-viewer .image-container,
|
| 271 |
+
#virtual-opencell .vo-viewer .image-frame { width: 100%; height: 100%; }
|
| 272 |
+
#virtual-opencell .vo-viewer img { width: 100%; height: 100%; object-fit: contain; }
|
| 273 |
+
|
| 274 |
+
/* OpenCell's button groups: grey label, rounded simple buttons, bold when active */
|
| 275 |
+
#virtual-opencell .vo-buttons input[type="radio"] { display: none; }
|
| 276 |
+
#virtual-opencell .vo-buttons label {
|
| 277 |
+
background: transparent !important; border: none !important; box-shadow: none !important;
|
| 278 |
+
padding: 4px 10px; border-radius: 5px; color: #333; font-size: 15px;
|
| 279 |
+
}
|
| 280 |
+
#virtual-opencell .vo-buttons label:hover { background: #d2d2d2 !important; }
|
| 281 |
+
#virtual-opencell .vo-buttons label.selected { font-weight: bold; background: #d1d4d64d !important; }
|
| 282 |
+
#virtual-opencell .vo-download button { font-size: 13px; font-weight: 400; }
|
| 283 |
+
#virtual-opencell .vo-settings-label { font-size: 16px; color: #182026; margin: 6px 0 -6px 0; }
|
| 284 |
+
|
| 285 |
+
/* sample strip: white frame, cyan when active (roi-thumbnail-*) */
|
| 286 |
+
#virtual-opencell .vo-thumbnails .grid-container { grid-template-columns: repeat(var(--grid-cols), minmax(0, 1fr)) !important; }
|
| 287 |
+
#virtual-opencell .vo-thumbnails .thumbnail-item { border: 3px solid #fff; border-radius: 5px; box-shadow: none; }
|
| 288 |
+
#virtual-opencell .vo-thumbnails .thumbnail-item:hover { opacity: 0.7; }
|
| 289 |
+
#virtual-opencell .vo-thumbnails .thumbnail-item.selected { border-color: var(--vo-blue); box-shadow: none; }
|
| 290 |
+
|
| 291 |
+
#virtual-opencell .vo-footer {
|
| 292 |
+
background: #eee; border-radius: 6px; padding: 10px 16px; margin-top: 10px; font-size: 13px; color: #333;
|
| 293 |
+
}
|
| 294 |
+
"""
|