Update app.py
Browse files9 unmodified lines10111213141516265 unmodified lines2822832842852862872882892902912922936 unmodified lines300301302303304305180 unmodified lines4864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325333 unmodified lines537538539540541542543127 unmodified lines6716726736746756766776786796806812 unmodified lines6846856866876886894 unmodified lines6946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427 unmodified lines7507517527537547557569 unmodified linesimport torchimport numpy as npimport loggingfrom PIL import Imageimport gradio as grfrom torch_geometric.data import Data as PyGDataimport matplotlib265 unmodified lines# 添加坐标信息if self.mol.GetNumConformers() == 0:conf = Chem.Conformer()self.mol.AddConformer(conf)conf = self.mol.GetConformer()conf.SetAtomPosition(atom_idx, Chem.rdGeometry.Point3D(x/50, y/50, 0))self.atoms[atom_idx] = (x, y, symbol)return atom_idxdef add_bond(self, start_idx, end_idx, bond_type):6 unmodified linesself.mol.AddBond(int(start_idx), int(end_idx), bond_type.value)bond_id = len(self.bonds)self.bonds[bond_id] = (start_idx, end_idx, bond_type)return Truereturn False180 unmodified linesreturn BondType.SINGLEdef render_molecule(self, width=600, height=400):"""渲染分子图像"""if not self.atoms:# 创建空白图像img = Image.new('RGB', (width, height), (255, 255, 255))return img# 创建临时分子用于渲染temp_mol = Chem.RWMol()atom_map = {}# 添加原子for atom_idx, (x, y, symbol) in self.atoms.items():atom = Chem.Atom(symbol)new_idx = temp_mol.AddAtom(atom)atom_map[atom_idx] = new_idx# 添加化学键for _, (start_idx, end_idx, bond_type) in self.bonds.items():if start_idx in atom_map and end_idx in atom_map:temp_mol.AddBond(atom_map[start_idx], atom_map[end_idx], bond_type.value)# 添加坐标conf = Chem.Conformer()for atom_idx, (x, y, _) in self.atoms.items():if atom_idx in atom_map:conf.SetAtomPosition(atom_map[atom_idx], Chem.rdGeometry.Point3D(x/50, y/50, 0))temp_mol.AddConformer(conf)# 设置高亮原子highlight_atoms = []if self.selected_atom is not None and self.selected_atom in atom_map:highlight_atoms.append(atom_map[self.selected_atom])if self.bond_start_atom is not None and self.bond_start_atom in atom_map:highlight_atoms.append(atom_map[self.bond_start_atom])# 生成2D坐标rdDepictor.Compute2DCoords(temp_mol)# 绘制分子img = Draw.MolToImage(temp_mol, size=(width, height),highlightAtoms=highlight_atoms,highlightColor=(1, 0, 0))return img# ==================== Gradio界面 ====================3 unmodified linesgr.Markdown("Input the SMILES string of a molecule or use the molecular editor to create a molecular structure. The model will predict its elasticity, plasticity and brittleness classification and visualize the attention weights.")# 存储分子状态editor = gr.State(MoleculeEditor())with gr.Tab("Molecular Editor"):with gr.Row():127 unmodified lines# 选择已有原子editor.selected_atom = nearest_atomeditor.bond_start_atom = None # 清除化学键选择else:# 在空白处添加新原子new_atom = editor.add_atom(x, y, atom_type_val)editor.selected_atom = new_atomeditor.bond_start_atom = Noneelif mode == "bond":# 化学键模式:选择两个原子添加键2 unmodified lines# 选择第一个原子editor.bond_start_atom = nearest_atomeditor.selected_atom = nearest_atomelse:# 选择第二个原子,添加化学键if editor.bond_start_atom != nearest_atom:4 unmodified lines}.get(bond_type_val, BondType.SINGLE)editor.add_bond(editor.bond_start_atom, nearest_atom, bond_type)editor.bond_start_atom = Noneeditor.selected_atom = nearest_atomelse:# 点击空白处,清除选择editor.bond_start_atom = Noneeditor.selected_atom = Nonereturn x, y, editor, update_display(editor)# 事件绑定molecule_display.select(handle_canvas_click,inputs=[molecule_display, editor, atom_type, bond_type, mode_select],outputs=[click_x, click_y, editor, molecule_display])delete_btn.click(delete_handler,inputs=[editor],outputs=[editor, molecule_display])clear_bond_selection.click(clear_bond_selection_handler,inputs=[editor],outputs=[editor, molecule_display])clear_btn.click(init_display,inputs=[],outputs=[editor, molecule_display])update_btn.click(update_from_smiles,inputs=[smiles_input, editor],outputs=[editor, molecule_display])get_smiles_btn.click(get_smiles,inputs=[editor],outputs=[smiles_input])7 unmodified linesdemo.load(init_display,inputs=[],outputs=[editor, molecule_display])if __name__ == "__main__":9 unmodified lines10111213141516265 unmodified lines2822832842852862872882892902912922932942952962976 unmodified lines304305306307308309310180 unmodified lines4914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305313 unmodified lines535536537538539540541127 unmodified lines6696706716726736746756766776786796806812 unmodified lines6846856866876886896904 unmodified lines6956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457 unmodified lines7537547557567577587599 unmodified linesimport torchimport numpy as npimport loggingfrom PIL import Image, ImageDrawimport gradio as grfrom torch_geometric.data import Data as PyGDataimport matplotlib265 unmodified lines# 添加坐标信息if self.mol.GetNumConformers() == 0:conf = Chem.Conformer()conf_id = self.mol.AddConformer(conf)logger.info(f"添加新构象,ID: {conf_id}")else:conf_id = 0conf = self.mol.GetConformer(conf_id)conf.SetAtomPosition(atom_idx, Chem.rdGeometry.Point3D(x/50, y/50, 0))self.atoms[atom_idx] = (x, y, symbol)logger.info(f"添加原子 {symbol} 在位置 ({x}, {y}),索引: {atom_idx}")return atom_idxdef add_bond(self, start_idx, end_idx, bond_type):6 unmodified linesself.mol.AddBond(int(start_idx), int(end_idx), bond_type.value)bond_id = len(self.bonds)self.bonds[bond_id] = (start_idx, end_idx, bond_type)logger.info(f"添加键: {start_idx}-{end_idx} 类型: {bond_type}")return Truereturn False180 unmodified linesreturn BondType.SINGLEdef render_molecule(self, width=600, height=400):"""渲染分子图像 - 使用自定义渲染避免RDKit自动添加氢原子"""if not self.atoms:# 创建空白图像img = Image.new('RGB', (width, height), (255, 255, 255))return img# 创建空白图像img = Image.new('RGB', (width, height), (255, 255, 255))draw = ImageDraw.Draw(img)# 绘制化学键for _, (start_idx, end_idx, bond_type) in self.bonds.items():if start_idx in self.atoms and end_idx in self.atoms:x1, y1, _ = self.atoms[start_idx]x2, y2, _ = self.atoms[end_idx]# 绘制键line_width = 2 if bond_type == BondType.SINGLE else 4 if bond_type == BondType.DOUBLE else 6draw.line([(x1, y1), (x2, y2)], fill=(0, 0, 0), width=line_width)# 绘制原子for atom_idx, (x, y, symbol) in self.atoms.items():# 绘制原子radius = 15fill_color = self.atom_colors.get(symbol, "#CCCCCC")outline_color = (255, 0, 0) if atom_idx == self.selected_atom or atom_idx == self.bond_start_atom else (0, 0, 0)# 绘制原子圆圈draw.ellipse([(x - radius, y - radius), (x + radius, y + radius)],fill=fill_color, outline=outline_color, width=2)# 绘制原子符号text_width, text_height = draw.textsize(symbol)draw.text((x - text_width/2, y - text_height/2), symbol, fill=(0, 0, 0))return img# ==================== Gradio界面 ====================3 unmodified linesgr.Markdown("Input the SMILES string of a molecule or use the molecular editor to create a molecular structure. The model will predict its elasticity, plasticity and brittleness classification and visualize the attention weights.")# 存储分子状态editor_state = gr.State(MoleculeEditor())with gr.Tab("Molecular Editor"):with gr.Row():127 unmodified lines# 选择已有原子editor.selected_atom = nearest_atomeditor.bond_start_atom = None # 清除化学键选择logger.info(f"选择原子: {nearest_atom}")else:# 在空白处添加新原子new_atom = editor.add_atom(x, y, atom_type_val)editor.selected_atom = new_atomeditor.bond_start_atom = Nonelogger.info(f"添加新原子: {new_atom}")elif mode == "bond":# 化学键模式:选择两个原子添加键2 unmodified lines# 选择第一个原子editor.bond_start_atom = nearest_atomeditor.selected_atom = nearest_atomlogger.info(f"选择起始原子: {nearest_atom}")else:# 选择第二个原子,添加化学键if editor.bond_start_atom != nearest_atom:4 unmodified lines}.get(bond_type_val, BondType.SINGLE)editor.add_bond(editor.bond_start_atom, nearest_atom, bond_type)logger.info(f"添加键: {editor.bond_start_atom}-{nearest_atom} 类型: {bond_type}")editor.bond_start_atom = Noneeditor.selected_atom = nearest_atomelse:# 点击空白处,清除选择editor.bond_start_atom = Noneeditor.selected_atom = Nonelogger.info("清除键选择")return x, y, editor, update_display(editor)# 事件绑定molecule_display.select(handle_canvas_click,inputs=[molecule_display, editor_state, atom_type, bond_type, mode_select],outputs=[click_x, click_y, editor_state, molecule_display])delete_btn.click(delete_handler,inputs=[editor_state],outputs=[editor_state, molecule_display])clear_bond_selection.click(clear_bond_selection_handler,inputs=[editor_state],outputs=[editor_state, molecule_display])clear_btn.click(init_display,inputs=[],outputs=[editor_state, molecule_display])update_btn.click(update_from_smiles,inputs=[smiles_input, editor_state],outputs=[editor_state, molecule_display])get_smiles_btn.click(get_smiles,inputs=[editor_state],outputs=[smiles_input])7 unmodified linesdemo.load(init_display,inputs=[],outputs=[editor_state, molecule_display])if __name__ == "__main__":
app.py+51-48