"""Molecule rendering helpers.""" from __future__ import annotations from typing import Optional _CARD_BG = "#ffffff" _GRID_BG = "#f8fafc" _BORDER = "#e5e7eb" _TEXT_MUTED = "#6b7280" _TEXT_INK2 = "#374151" def _mol_to_svg(mol, size: tuple[int, int] = (300, 300)) -> str: """Render a single RDKit Mol to an SVG string (transparent background).""" import re from rdkit.Chem.Draw import rdMolDraw2D w, h = size drawer = rdMolDraw2D.MolDraw2DSVG(w, h) opts = drawer.drawOptions() opts.clearBackground = False opts.addStereoAnnotation = True rdMolDraw2D.PrepareAndDrawMolecule(drawer, mol) drawer.FinishDrawing() svg = drawer.GetDrawingText() # strip XML declaration svg = svg[svg.find(" str: """Return an HTML string of a responsive grid of molecule SVG cards.""" from rdkit import Chem mols, kept_legends = [], [] for i, smi in enumerate(smiles): mol = Chem.MolFromSmiles(smi) if smi else None if mol is None: continue mols.append(mol) if legends is not None: kept_legends.append(legends[i] if i < len(legends) else "") if not mols: return _empty_html("No valid molecules in this batch") cards_html = [] for i, mol in enumerate(mols): svg = _mol_to_svg(mol, size=(card_size, card_size)) legend = kept_legends[i] if kept_legends else "" legend_block = ( f'
{legend}
' if legend else "" ) cards_html.append( # card — min-width:0 prevents grid blowout f'
' # SVG wrapper: square aspect-ratio, fills card width f'
' f" {svg}" f"
" f" {legend_block}" f"
" ) card_max_px = 220 # max width per molecule card in px grid_max_px = cols * card_max_px grid = ( # outer wrapper — capped width so a single mol doesn't stretch full screen f'
' f'
' + "".join(cards_html) + "
" ) return grid def _empty_html(msg: str) -> str: return ( f'
{msg}
' )