DailyGlimpse

Visualize Proteins on Hugging Face Spaces with 3Dmol.js

AI
April 26, 2026 · 5:22 PM
Visualize Proteins on Hugging Face Spaces with 3Dmol.js

Proteins play a crucial role in our lives, from medicines to laundry detergents. Machine learning is transforming protein design, and visualizing these complex 3D structures is key to understanding their function. This guide shows you how to integrate protein visualization into a Hugging Face Space using 3Dmol.js and Gradio.

Motivation

Proteins are 3D objects made of amino acids. Machine learning models like AlphaFold2 predict their structures. With the rise of such models, being able to visualize predicted structures directly in the browser is invaluable.

See It for Yourself

3Dmol.js is a powerful tool for displaying molecular structures in the browser. Here’s how to set it up in a Hugging Face Space.

Prerequisites

  • Gradio installed (pip install gradio)
  • Basic knowledge of JavaScript/jQuery

Building the App

The app accepts a PDB code (e.g., 4-letter identifier) or a PDB file. It retrieves the structure and displays it in an iframe.

import gradio as gr

def update(inp, file):
    pdb_path = get_pdb(inp, file)
    return molecule(pdb_path)

demo = gr.Blocks()
with demo:
    gr.Markdown("# PDB viewer using 3Dmol.js")
    with gr.Row():
        with gr.Box():
            inp = gr.Textbox(placeholder="PDB Code or upload file below", label="Input structure")
            file = gr.File(file_count="single")
            btn = gr.Button("View structure")
        mol = gr.HTML()
    btn.click(fn=update, inputs=[inp, file], outputs=mol)
demo.launch()

The helper function get_pdb downloads the PDB file from RCSB if a code is provided, or uses the uploaded file.

import os
def get_pdb(pdb_code="", filepath=""):
    if pdb_code is None or len(pdb_code) != 4:
        try:
            return filepath.name
        except AttributeError:
            return None
    else:
        os.system(f"wget -qnc https://files.rcsb.org/view/{pdb_code}.pdb")
        return f"{pdb_code}.pdb"

The Molecule Viewer

The viewer is embedded as an iframe. The molecule function generates an HTML document containing 3Dmol.js.

First, include 3Dmol.js and jQuery in the <head>:

<head>
    <meta charset="UTF-8">
    <style>
    .mol-container {
        width: 100%;
        height: 700px;
        position: relative;
    }
    </style>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.3/jquery.min.js"></script>
    <script src="https://3Dmol.csb.pitt.edu/build/3Dmol-min.js"></script>
</head>

Then in the <body>, the PDB data is inserted and rendered:

<body>
    <div id="container" class="mol-container"></div>
    <script>
        let pdb = `{pdb_content}`;  // actual PDB data inserted via Python
        $(document).ready(function() {
            let element = $("#container");
            let viewer = $3Dmol.createViewer(element, {backgroundColor: "white"});
            viewer.addModel(pdb, "pdb");
            viewer.setStyle({}, {cartoon: {colorscheme: "whiteCarbon"}});
            viewer.zoomTo();
            viewer.render();
            viewer.zoom(0.8, 2000);
        });
    </script>
</body>

The Python function molecule returns an iframe containing this HTML.

Go Further

This setup can be extended to visualize custom structures from ML models. For instance, the ProteinMPNN Space uses inverse folding and AlphaFold2 to validate designs.

Check the source code for the full working example.

Update May 2024: You can now use the Molecule3D Gradio Custom Component for easier setup.