Spaces:
Runtime error
Runtime error
Update app.py
Browse files16 unmodified lines171819202122250 unmodified lines27327427527627727874 unmodified lines3533543553563573583595 unmodified lines36536636736836937037137237337437537637749 unmodified lines42742842943043143243343443543643712 unmodified lines4504514524534544554564574584594604614624634644654664 unmodified lines4714724734744754764774784794804814824834843 unmodified lines4884894904914924934944954964974984995005015025035045055065075085091 unmodified line51151251351451551651713 unmodified lines5315325335345355365378 unmodified lines5465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016022 unmodified lines6056066076086096106116126136146156166176186196206216224 unmodified lines62762862963063163263316 unmodified linesfrom rdkit.Chem.Draw import rdMolDraw2Dimport tempfileimport math# 配置日志logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')250 unmodified lines"""添加原子到分子"""atom = Chem.Atom(atom_type)idx = mol.AddAtom(atom)return mol, idxdef add_bond(mol, start_idx, end_idx, bond_type):74 unmodified lines# ==================== 化学键绘制功能修复 ====================def find_nearest_atom(mol, x, y, threshold=20):"""在分子中找到距离点击位置最近的原子"""if mol.GetNumAtoms() == 0:return None# 获取分子中所有原子的坐标5 unmodified linesatom_idx = atom.GetIdx()pos = conf.GetAtomPosition(atom_idx)# 计算点击位置与原子位置的距离distance = math.sqrt((x - pos.x)**2 + (y - pos.y)**2)# 转换为像素距离(假设1坐标单位≈50像素)pixel_distance = distance * 50if pixel_distance < threshold and pixel_distance < min_distance:min_distance = pixel_distancenearest_atom = atom_idxreturn nearest_atom49 unmodified lineswith gr.Column(scale=2):# 分子编辑器画布molecule_display = gr.Image(label="Molecule Editor", interactive=True, width=600, height=400)# 原子和键选择with gr.Row():atom_list = gr.Dropdown([], label="Atoms", interactive=True)bond_list = gr.Dropdown([], label="Bonds", interactive=True)with gr.Tab("Prediction Results"):with gr.Row():12 unmodified linesdef update_molecule_display(mol, selected_atom=None, selected_bond=None):"""更新分子显示"""img = draw_molecule_with_highlights(mol, selected_atom, selected_bond, 600, 400)# 更新原子和键列表atoms = []for atom in mol.GetAtoms():atoms.append(f"Atom {atom.GetIdx()}: {atom.GetSymbol()}")bonds = []for bond in mol.GetBonds():bonds.append(f"Bond {bond.GetIdx()}: {bond.GetBeginAtomIdx()}-{bond.GetEndAtomIdx()} ({bond.GetBondType()})")return img, atoms, bonds# 初始化显示def init_display():4 unmodified linesdef add_atom_handler(mol, atom_type, x, y):"""处理添加原子"""# 在点击位置添加原子mol, idx = add_atom(mol, atom_type, x, y)return mol, *update_molecule_display(mol)# 添加键def add_bond_handler(mol, atom1, atom2, bond_type_str):"""处理添加键"""if atom1 is None or atom2 is None:return mol, *update_molecule_display(mol)# 获取键类型bond_type = {3 unmodified lines}.get(bond_type_str, Chem.BondType.SINGLE)mol = add_bond(mol, atom1, atom2, bond_type)return mol, *update_molecule_display(mol)# 删除选中的原子或键def delete_handler(mol, selected_atom, selected_bond):"""处理删除操作"""if selected_atom is not None:mol = delete_atom(mol, selected_atom)elif selected_bond is not None:# 获取键的原子索引bond = mol.GetBondWithIdx(int(selected_bond))if bond:start_idx = bond.GetBeginAtomIdx()end_idx = bond.GetEndAtomIdx()mol = delete_bond(mol, start_idx, end_idx)return mol, *update_molecule_display(mol)# 从SMILES更新def update_from_smiles(smiles):1 unmodified linemol = Chem.RWMol(Chem.MolFromSmiles(smiles))if mol is None:mol = create_empty_molecule()return mol, *update_molecule_display(mol)# 获取SMILESdef get_smiles(mol):13 unmodified lines# 如果有上次点击的原子,并且不是同一个原子,则添加键if last_clicked is not None and last_clicked != nearest_atom:# 获取键类型bond_type_str = "SINGLE" # 默认单键# 添加键mol = add_bond(mol, last_clicked, nearest_atom,{"SINGLE": Chem.BondType.SINGLE,8 unmodified lines# 没有点击到原子,重置last_clicked = Nonereturn x, y, mol, last_clicked, *update_molecule_display(mol, last_clicked, None)# 选择原子def select_atom(atom_str):"""选择原子"""if atom_str:return int(atom_str.split(":")[0].split()[1])return None# 选择键def select_bond(bond_str):"""选择键"""if bond_str:return int(bond_str.split(":")[0].split()[1])return None# 事件绑定molecule_display.select(handle_canvas_click,inputs=[molecule_display, current_mol, last_clicked_atom],outputs=[click_x, click_y, current_mol, last_clicked_atom, molecule_display, atom_list, bond_list])add_atom_btn.click(add_atom_handler,inputs=[current_mol, atom_type, click_x, click_y],outputs=[current_mol, molecule_display, atom_list, bond_list])add_bond_btn.click(add_bond_handler,inputs=[current_mol, selected_atom, selected_atom, bond_type],outputs=[current_mol, molecule_display, atom_list, bond_list])delete_btn.click(delete_handler,inputs=[current_mol, selected_atom, selected_bond],outputs=[current_mol, molecule_display, atom_list, bond_list])clear_btn.click(init_display,inputs=[],outputs=[current_mol, molecule_display, atom_list, bond_list])update_btn.click(update_from_smiles,inputs=[smiles_input],outputs=[current_mol, molecule_display, atom_list, bond_list])get_smiles_btn.click(2 unmodified linesoutputs=[smiles_input])atom_list.change(select_atom,inputs=[atom_list],outputs=[selected_atom])bond_list.change(select_bond,inputs=[bond_list],outputs=[selected_bond])predict_btn.click(predict_all,inputs=[smiles_input],4 unmodified linesdemo.load(init_display,inputs=[],outputs=[molecule_display, atom_list, bond_list])if __name__ == "__main__":16 unmodified lines17181920212223250 unmodified lines27427527627727827928028128228328428528628728874 unmodified lines3633643653663673683695 unmodified lines37537637737837938038138238338438538638738849 unmodified lines43843944044144244312 unmodified lines4564574584594604614624 unmodified lines4674684694704714724734744754764774784794804813 unmodified lines4854864874884894904914924934944954964974981 unmodified line50050150250350450550650750850913 unmodified lines5235245255265275285298 unmodified lines5385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795802 unmodified lines5835845855865875884 unmodified lines59359459559659759859916 unmodified linesfrom rdkit.Chem.Draw import rdMolDraw2Dimport tempfileimport mathimport re# 配置日志logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')250 unmodified lines"""添加原子到分子"""atom = Chem.Atom(atom_type)idx = mol.AddAtom(atom)# 添加坐标信息if mol.GetNumConformers() == 0:conf = Chem.Conformer()mol.AddConformer(conf)conf = mol.GetConformer()conf.SetAtomPosition(idx, Chem.rdGeometry.Point3D(x/50, y/50, 0)) # 缩放坐标return mol, idxdef add_bond(mol, start_idx, end_idx, bond_type):74 unmodified lines# ==================== 化学键绘制功能修复 ====================def find_nearest_atom(mol, x, y, threshold=20):"""在分子中找到距离点击位置最近的原子"""if mol is None or mol.GetNumAtoms() == 0:return None# 获取分子中所有原子的坐标5 unmodified linesatom_idx = atom.GetIdx()pos = conf.GetAtomPosition(atom_idx)# 计算点击位置与原子位置的距离# 注意:RDKit坐标系统与像素坐标不同,需要转换pixel_x = pos.x * 50 # 假设1坐标单位≈50像素pixel_y = pos.y * 50distance = math.sqrt((x - pixel_x)**2 + (y - pixel_y)**2)if distance < threshold and distance < min_distance:min_distance = distancenearest_atom = atom_idxreturn nearest_atom49 unmodified lineswith gr.Column(scale=2):# 分子编辑器画布molecule_display = gr.Image(label="Molecule Editor", interactive=True, width=600, height=400)with gr.Tab("Prediction Results"):with gr.Row():12 unmodified linesdef update_molecule_display(mol, selected_atom=None, selected_bond=None):"""更新分子显示"""img = draw_molecule_with_highlights(mol, selected_atom, selected_bond, 600, 400)return img# 初始化显示def init_display():4 unmodified linesdef add_atom_handler(mol, atom_type, x, y):"""处理添加原子"""# 在点击位置添加原子if x > 0 and y > 0: # 确保有有效的坐标mol, idx = add_atom(mol, atom_type, x, y)return mol, update_molecule_display(mol)# 添加键def add_bond_handler(mol, atom1, atom2, bond_type_str):"""处理添加键"""if atom1 is None or atom2 is None:return mol, update_molecule_display(mol)# 获取键类型bond_type = {3 unmodified lines}.get(bond_type_str, Chem.BondType.SINGLE)mol = add_bond(mol, atom1, atom2, bond_type)return mol, update_molecule_display(mol)# 删除选中的原子或键def delete_handler(mol, selected_atom):"""处理删除操作"""if selected_atom is not None:mol = delete_atom(mol, selected_atom)return mol, update_molecule_display(mol)# 从SMILES更新def update_from_smiles(smiles):1 unmodified linemol = Chem.RWMol(Chem.MolFromSmiles(smiles))if mol is None:mol = create_empty_molecule()else:# 添加默认坐标rdDepictor.Compute2DCoords(mol)return mol, update_molecule_display(mol)# 获取SMILESdef get_smiles(mol):13 unmodified lines# 如果有上次点击的原子,并且不是同一个原子,则添加键if last_clicked is not None and last_clicked != nearest_atom:# 获取键类型bond_type_str = bond_type.value # 使用当前选择的键类型# 添加键mol = add_bond(mol, last_clicked, nearest_atom,{"SINGLE": Chem.BondType.SINGLE,8 unmodified lines# 没有点击到原子,重置last_clicked = Nonereturn x, y, mol, last_clicked, update_molecule_display(mol, last_clicked, None)# 事件绑定molecule_display.select(handle_canvas_click,inputs=[molecule_display, current_mol, last_clicked_atom],outputs=[click_x, click_y, current_mol, last_clicked_atom, molecule_display])add_atom_btn.click(add_atom_handler,inputs=[current_mol, atom_type, click_x, click_y],outputs=[current_mol, molecule_display])add_bond_btn.click(add_bond_handler,inputs=[current_mol, last_clicked_atom, last_clicked_atom, bond_type],outputs=[current_mol, molecule_display])delete_btn.click(delete_handler,inputs=[current_mol, last_clicked_atom],outputs=[current_mol, molecule_display])clear_btn.click(init_display,inputs=[],outputs=[current_mol, molecule_display])update_btn.click(update_from_smiles,inputs=[smiles_input],outputs=[current_mol, molecule_display])get_smiles_btn.click(2 unmodified linesoutputs=[smiles_input])predict_btn.click(predict_all,inputs=[smiles_input],4 unmodified linesdemo.load(init_display,inputs=[],outputs=[molecule_display])if __name__ == "__main__":
app.py+40-74