A newer version of the Gradio SDK is available:
5.24.0
Here's a sample code to show an H2 molecule and a water molecule in a py3Dmol flow inside a Gradio display:
Explanation: Molecule Creation: The molecule_viewer function takes a molecule_type parameter to determine which molecule to visualize. It uses RDKit to create the molecule from SMILES strings, add hydrogens, and embed the molecule in 3D space. Visualization: The molecule is then converted to a MolBlock format, which py3Dmol can read. The view object is created with the molecule data, and styles are applied to show the molecule in stick and sphere representations. Gradio Interface: The Gradio interface allows users to select between H2 and H2O molecules using a radio button. The selected molecule is then visualized in the HTML output. Launch: The Gradio app is launched, providing an interactive web interface where users can view the 3D models of the selected molecules. This code provides a simple yet effective way to visualize H2 and H2O molecules in 3D within a Gradio interface. Users can rotate, zoom, and interact with the molecules to explore their structures.
import gradio as gr from rdkit import Chem from rdkit.Chem import AllChem import py3Dmol
def molecule_viewer(molecule_type): if molecule_type == "H2": # Create an H2 molecule h2 = Chem.MolFromSmiles("H[H]") h2 = AllChem.AddHs(h2) AllChem.EmbedMolecule(h2) mol_block = Chem.MolToMolBlock(h2) elif molecule_type == "H2O": # Create a water molecule water = Chem.MolFromSmiles("O") water = AllChem.AddHs(water) AllChem.EmbedMolecule(water) mol_block = Chem.MolToMolBlock(water) else: return "Invalid molecule type"
# Create the 3Dmol view
view = py3Dmol.view(data=mol_block, style={"stick": {}, "sphere": {"scale": 0.3}})
view.zoomTo()
return view
Define the Gradio interface
demo = gr.Interface( fn=molecule_viewer, inputs=gr.Radio(choices=["H2", "H2O"], label="Select Molecule"), outputs=gr.HTML(label="3D Molecule Viewer") )
Launch the Gradio app
demo.launch()