Spaces:
Runtime error
Runtime error
Update app.py
Browse files190 unmodified lines1911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293301 unmodified line3323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923 unmodified lines3963973983994004014025 unmodified lines40840941041141241341441541641741841942042142242342479 unmodified lines50450550650750850951013 unmodified lines5245255265275285295308 unmodified lines5395405415425435445453 unmodified lines54955055155255355455546 unmodified lines6026036046056066076086096106116126136146156166176186196206216226236246256266276286296306311 unmodified line63363463563663763863964064164233 unmodified lines67667767867968068168268312 unmodified lines6966976986997007017027037047057067077087097107117127137147156 unmodified lines7227237247257267277287297307317327337348 unmodified lines7437447457467477487497507517527537547557567577587597607617627637647657667677687697702 unmodified lines7737747757767777787795 unmodified lines785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852190 unmodified lineslogger.error(error_msg)return error_msg, None, error_msg, None, error_msg, None# ==================== 分子编辑器功能 (修复版) ====================def generate_molecule_image(smiles, width=400, height=400):"""从SMILES生成分子图像"""try:mol = Chem.MolFromSmiles(smiles)if mol is None:return None# 生成2D坐标rdDepictor.Compute2DCoords(mol)drawer = Draw.MolDraw2DCairo(width, height)opts = drawer.drawOptions()opts.updateAtomPalette({k: matplotlib.colors.to_rgb(v) for k, v in get_atom_color_dict().items()})drawer.DrawMolecule(mol)drawer.FinishDrawing()# 转换为PIL图像img = Image.open(io.BytesIO(drawer.GetDrawingText()))return imgexcept Exception as e:logger.error(f"生成分子图像失败: {str(e)}")return Nonedef get_atom_color_dict():"""获取原子颜色字典"""return {"C": "#CCCCCC", "N": "#6666FF", "O": "#FF6666","F": "#66FF66", "Cl": "#66FF66", "Br": "#FF8000","I": "#FF9999", "S": "#FFFF66", "P": "#FF9933"}def smiles_to_mol_data(smiles):"""将SMILES转换为分子数据(用于编辑器)"""try:mol = Chem.MolFromSmiles(smiles)if not mol:return None# 生成2D坐标rdDepictor.Compute2DCoords(mol)# 获取原子和键信息atoms = []bonds = []# 原子信息for atom in mol.GetAtoms():pos = mol.GetConformer().GetAtomPosition(atom.GetIdx())atoms.append({"id": atom.GetIdx(),"symbol": atom.GetSymbol(),"x": pos.x,"y": pos.y,"color": get_atom_color_dict().get(atom.GetSymbol(), "#FFFFFF")})# 键信息for bond in mol.GetBonds():bonds.append({"start": bond.GetBeginAtomIdx(),"end": bond.GetEndAtomIdx(),"type": bond.GetBondType().name,"order": bond.GetBondTypeAsDouble()})# 计算边界min_x = min(atom["x"] for atom in atoms)max_x = max(atom["x"] for atom in atoms)min_y = min(atom["y"] for atom in atoms)max_y = max(atom["y"] for atom in atoms)# 计算缩放比例canvas_width, canvas_height = 800, 400mol_width = max_x - min_xmol_height = max_y - min_yscale = min(canvas_width / (mol_width + 1e-5),canvas_height / (mol_height + 1e-5)) * 0.8 # 保留边距# 计算中心偏移center_x = (min_x + max_x) / 2center_y = (min_y + max_y) / 2offset_x = canvas_width / 2 - center_x * scaleoffset_y = canvas_height / 2 - center_y * scale# 应用缩放和偏移for atom in atoms:atom["x"] = atom["x"] * scale + offset_xatom["y"] = atom["y"] * scale + offset_yreturn {"atoms": atoms,"bonds": bonds,"width": canvas_width,"height": canvas_height}except Exception as e:logger.error(f"转换SMILES为分子数据失败: {str(e)}")return Nonedef update_molecule_editor(smiles):"""更新分子编辑器"""try:mol_data = smiles_to_mol_data(smiles)if mol_data is None:return None, "Invalid SMILES"# 生成预览图像img = generate_molecule_image(smiles)if img is None:return None, "无法生成分子图像"# 转换为Base64编码buffered = io.BytesIO()img.save(buffered, format="PNG")img_str = "data:image/png;base64," + base64.b64encode(buffered.getvalue()).decode()return img_str, json.dumps(mol_data)except Exception as e:logger.error(f"更新分子编辑器失败: {str(e)}")return None, f"错误: {str(e)}"def convert_to_smiles(mol_data):"""将分子数据转换为SMILES字符串"""try:if not mol_data:return ""mol_data = json.loads(mol_data)atoms = mol_data.get("atoms", [])bonds = mol_data.get("bonds", [])# 创建分子对象mol = Chem.RWMol()1 unmodified line# 添加原子for atom_data in atoms:try:atom = Chem.Atom(atom_data["symbol"])idx = mol.AddAtom(atom)atom_map[atom_data["id"]] = idxexcept Exception as e:logger.warning(f"添加原子失败: {str(e)}")# 添加键for bond_data in bonds:try:start_idx = atom_map.get(bond_data["start"])end_idx = atom_map.get(bond_data["end"])if start_idx is not None and end_idx is not None:bond_type_str = bond_data.get("type", "SINGLE")bond_type = getattr(BondType, bond_type_str, BondType.SINGLE)mol.AddBond(start_idx, end_idx, bond_type)except Exception as e:logger.warning(f"添加键失败: {str(e)}")# 清理和规范化分子try:Chem.SanitizeMol(mol)return Chem.MolToSmiles(mol)except:# 如果无法规范化,尝试直接输出try:return Chem.MolToSmiles(mol, kekuleSmiles=True)except:return "Invalid Molecule"except Exception as e:logger.error(f"转换分子为SMILES时出错: {str(e)}")return "Invalid Molecule"# ==================== Gradio界面 (完全修复版) ====================# 创建带有分子编辑器的Gradio界面with gr.Blocks(title="CrystalGAT", css=".gradio-container {max-width: 1200px !important}") as demo:gr.Markdown("# CrystalGAT")gr.Markdown("Input the SMILES string or use the molecular editor to create a molecular structure.")with gr.Tab("Molecular Editor"):with gr.Row():with gr.Column(scale=1):smiles_input = gr.Textbox(label="SMILES", placeholder="Enter SMILES string, e.g.: CCO", elem_id="smiles_input")update_btn = gr.Button("Update from SMILES")with gr.Row():atom_type = gr.Radio(["C", "N", "O", "F", "Cl", "Br", "I", "S", "P"],label="Atom Type", value="C", elem_id="atom_type_radio")bond_type = gr.Radio(["SINGLE", "DOUBLE", "TRIPLE"],label="Bond Type", value="SINGLE", elem_id="bond_type_radio")gr.Markdown("### Instructions")3 unmodified linesgr.Markdown("4. Use 'Update from SMILES' to load a new molecule")with gr.Column(scale=2):# 分子编辑器画布 - 完全修复的实现canvas_html = """<!DOCTYPE html><html>5 unmodified linesborder: 1px solid #000;background-color: white;cursor: pointer;margin-bottom: 10px;}.canvas-container {position: relative;}</style></head><body><div class="canvas-container"><canvas id="moleculeCanvas" width="800" height="400"></canvas></div><script>// 全局变量79 unmodified lines});drawMolecule();updateMolData();return id;}13 unmodified linesorder: type === "SINGLE" ? 1 : type === "DOUBLE" ? 2 : 3});drawMolecule();updateMolData();}}8 unmodified lines);drawMolecule();updateMolData();}// 删除键3 unmodified lines(b.start === endId && b.end === startId)));drawMolecule();updateMolData();}// 获取位置上的原子46 unmodified linesreturn null;}// 更新分子数据function updateMolData() {const molData = JSON.stringify(moleculeData);// 发送消息给父窗口(Gradio)window.parent.postMessage({type: "molDataUpdate",data: molData}, "*");}// 加载分子数据function loadMoleculeData(data) {try {if (data) {moleculeData = JSON.parse(data);} else {moleculeData = { atoms: [], bonds: [] };}drawMolecule();} catch (e) {console.error("加载分子数据错误:", e);}}// 事件监听器canvas.addEventListener('click', (e) => {const rect = canvas.getBoundingClientRect();1 unmodified lineconst y = e.clientY - rect.top;// 获取选中的原子类型const atomType = document.querySelector('input[name="atom_type"]:checked').value;// 添加新原子addAtom(x, y, atomType);});canvas.addEventListener('mousedown', (e) => {33 unmodified linesconst endAtom = getAtomAt(x, y);if (endAtom && endAtom !== selectedAtom) {// 获取选中的键类型const bondType = document.querySelector('input[name="bond_type"]:checked').value;addBond(selectedAtom.id, endAtom.id, bondType);}drawingBond = false;12 unmodified linesconst atom = getAtomAt(x, y);if (atom) {deleteAtom(atom.id);return;}const bond = getBondAt(x, y);if (bond) {deleteBond(bond.start, bond.end);}});// 监听来自Gradio的消息window.addEventListener('message', (event) => {if (event.data.type === 'loadMolecule') {loadMoleculeData(event.data.data);}});// 初始化画布6 unmodified linescanvas = gr.HTML(canvas_html, label="Molecule Editor")# Molecule previewpreview = gr.Image(label="Molecule Preview", interactive=False, elem_id="molecule_preview")# Action buttonswith gr.Row():clear_btn = gr.Button("Clear Canvas", elem_id="clear_btn")get_smiles_btn = gr.Button("Get SMILES", elem_id="get_smiles_btn")predict_btn = gr.Button("Predict Properties", elem_id="predict_btn")with gr.Tab("Prediction Results"):with gr.Row():8 unmodified linesbrittle_pred = gr.Text(label="Brittle Prediction")brittle_img = gr.Image(label="Brittle Attention Visualization")# Hidden component for storing molecule datamol_data = gr.Text(value="{}", visible=False, elem_id="mol_data")# 自定义JavaScript通信js_comm = gr.Text(value="", visible=False, elem_id="js_comm")# 更新按钮事件update_btn.click(update_molecule_editor,inputs=[smiles_input],outputs=[preview, mol_data]).then(lambda data: f"loadMolecule:{data}",inputs=[mol_data],outputs=[js_comm])# 清除按钮事件clear_btn.click(lambda: ("", "", "", "clearCanvas"),inputs=None,outputs=[smiles_input, preview, mol_data, js_comm])# 获取SMILES按钮事件2 unmodified linesinputs=[mol_data],outputs=[smiles_input]).then(update_molecule_editor,inputs=[smiles_input],outputs=[preview, mol_data])5 unmodified linesoutputs=[elastic_pred, elastic_img, plastic_pred, plastic_img, brittle_pred, brittle_img])# JavaScript通信处理js_comm.change(fn=your_python_function,inputs=[your_input_components],outputs=[your_output_components]).then(None, # 没有 Python 函数_js="""(command) => {if (!command) return;// 处理不同类型的命令if (command.startsWith("loadMolecule:")) {const data = command.replace("loadMolecule:", "");const canvasFrame = document.querySelector("#moleculeEditor iframe");if (canvasFrame && canvasFrame.contentWindow) {canvasFrame.contentWindow.postMessage({type: 'loadMolecule',data: data}, '*');}}else if (command === "clearCanvas") {const canvasFrame = document.querySelector("#moleculeEditor iframe");if (canvasFrame && canvasFrame.contentWindow) {canvasFrame.contentWindow.postMessage({type: 'loadMolecule',data: '{"atoms":[],"bonds":[]}'}, '*');}}}""")# 分子数据变化监听demo.load(_js="""() => {// 监听来自分子编辑器的消息window.addEventListener('message', (event) => {if (event.data.type === 'molDataUpdate') {// 更新隐藏的分子数据字段const molDataInput = document.getElementById("mol_data");if (molDataInput) {molDataInput.value = event.data.data;molDataInput.dispatchEvent(new Event('input', { bubbles: true }));}}});}""")if __name__ == "__main__":logger.info("启动Gradio应用...")try:demo.launch(server_name="0.0.0.0",server_port=7860,share=False,debug=True)except Exception as e:logger.error(f"启动Gradio应用失败: {str(e)}")raise190 unmodified lines1911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153161 unmodified line3183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643 unmodified lines3683693703713723733745 unmodified lines38038138238338438538638738838939079 unmodified lines47047147247347447513 unmodified lines4894904914924934948 unmodified lines5035045055065075083 unmodified lines51251351451551651746 unmodified lines5645655665675685691 unmodified line57157257357457557657757857958058158258358458558658758833 unmodified lines62262362462562662762862963063163263363463563663763812 unmodified lines6516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966 unmodified lines7037047057067077087097107117127137147158 unmodified lines7247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627632 unmodified lines7667677687697707717725 unmodified lines778779780781782783784785786787788789790791792793794795190 unmodified lineslogger.error(error_msg)return error_msg, None, error_msg, None, error_msg, None# ==================== 分子编辑器功能 ====================def generate_molecule_image(smiles, width=400, height=400):"""从SMILES生成分子图像"""mol = Chem.MolFromSmiles(smiles)if mol is None:return None# 生成2D坐标rdDepictor.Compute2DCoords(mol)drawer = Draw.MolDraw2DCairo(width, height)drawer.DrawMolecule(mol)drawer.FinishDrawing()# 转换为PIL图像img = Image.open(io.BytesIO(drawer.GetDrawingText()))return imgdef smiles_to_mol_data(smiles):"""将SMILES转换为分子数据(用于编辑器)"""mol = Chem.MolFromSmiles(smiles)if not mol:return None# 生成2D坐标rdDepictor.Compute2DCoords(mol)# 获取原子和键信息atoms = []bonds = []# 原子信息for atom in mol.GetAtoms():pos = mol.GetConformer().GetAtomPosition(atom.GetIdx())atoms.append({"id": atom.GetIdx(),"symbol": atom.GetSymbol(),"x": pos.x,"y": pos.y,"color": get_atom_color(atom.GetSymbol())})# 键信息for bond in mol.GetBonds():bonds.append({"start": bond.GetBeginAtomIdx(),"end": bond.GetEndAtomIdx(),"type": bond.GetBondType().name,"order": bond.GetBondTypeAsDouble()})# 计算边界min_x = min(atom["x"] for atom in atoms)max_x = max(atom["x"] for atom in atoms)min_y = min(atom["y"] for atom in atoms)max_y = max(atom["y"] for atom in atoms)# 计算缩放比例canvas_width, canvas_height = 800, 400mol_width = max_x - min_xmol_height = max_y - min_yscale = min(canvas_width / (mol_width + 1e-5),canvas_height / (mol_height + 1e-5)) * 0.8 # 保留边距# 计算中心偏移center_x = (min_x + max_x) / 2center_y = (min_y + max_y) / 2offset_x = canvas_width / 2 - center_x * scaleoffset_y = canvas_height / 2 - center_y * scale# 应用缩放和偏移for atom in atoms:atom["x"] = atom["x"] * scale + offset_xatom["y"] = atom["y"] * scale + offset_yreturn {"atoms": atoms,"bonds": bonds,"width": canvas_width,"height": canvas_height,"scale": scale,"offset_x": offset_x,"offset_y": offset_y}def get_atom_color(symbol):"""获取原子颜色"""atom_colors = {"C": "#CCCCCC", "N": "#6666FF", "O": "#FF6666","F": "#66FF66", "Cl": "#66FF66", "Br": "#FF8000","I": "#FF9999", "S": "#FFFF66", "P": "#FF9933"}return atom_colors.get(symbol, "#FFFFFF")def update_molecule_editor(smiles):"""更新分子编辑器"""mol_data = smiles_to_mol_data(smiles)if mol_data is None:return None, "Invalid SMILES"# 生成预览图像img = generate_molecule_image(smiles)if img is None:return None, "无法生成分子图像"# 转换为Base64编码buffered = io.BytesIO()img.save(buffered, format="PNG")img_str = "data:image/png;base64," + base64.b64encode(buffered.getvalue()).decode()return img_str, json.dumps(mol_data)def convert_to_smiles(mol_data):"""将分子数据转换为SMILES字符串"""try:mol_data = json.loads(mol_data)atoms = mol_data["atoms"]bonds = mol_data["bonds"]# 创建分子对象mol = Chem.RWMol()1 unmodified line# 添加原子for atom_data in atoms:atom = Chem.Atom(atom_data["symbol"])idx = mol.AddAtom(atom)atom_map[atom_data["id"]] = idx# 添加键for bond_data in bonds:start_idx = atom_map.get(bond_data["start"])end_idx = atom_map.get(bond_data["end"])if start_idx is not None and end_idx is not None:bond_type = getattr(BondType, bond_data["type"])mol.AddBond(start_idx, end_idx, bond_type)# 清理和规范化分子Chem.SanitizeMol(mol)return Chem.MolToSmiles(mol)except Exception as e:logger.error(f"转换分子为SMILES时出错: {str(e)}")return "Invalid Molecule"# ==================== Gradio界面 ====================# 创建带有分子编辑器的Gradio界面with gr.Blocks(title="CrystalGAT") as demo:gr.Markdown("# CrystalGAT")gr.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.")with gr.Tab("Molecular Editor"):with gr.Row():with gr.Column(scale=1):smiles_input = gr.Textbox(label="SMILES", placeholder="Enter SMILES string, e.g.: CCO")update_btn = gr.Button("Update from SMILES")with gr.Row():atom_type = gr.Radio(["C", "N", "O", "F", "Cl", "Br", "I", "S", "P"],label="Atom Type", value="C")bond_type = gr.Radio(["SINGLE", "DOUBLE", "TRIPLE"],label="Bond Type", value="SINGLE")gr.Markdown("### Instructions")3 unmodified linesgr.Markdown("4. Use 'Update from SMILES' to load a new molecule")with gr.Column(scale=2):# 分子编辑器画布canvas_html = """<!DOCTYPE html><html>5 unmodified linesborder: 1px solid #000;background-color: white;cursor: pointer;}</style></head><body><canvas id="moleculeCanvas" width="800" height="400"></canvas><script>// 全局变量79 unmodified lines});drawMolecule();return id;}13 unmodified linesorder: type === "SINGLE" ? 1 : type === "DOUBLE" ? 2 : 3});drawMolecule();}}8 unmodified lines);drawMolecule();}// 删除键3 unmodified lines(b.start === endId && b.end === startId)));drawMolecule();}// 获取位置上的原子46 unmodified linesreturn null;}// 事件监听器canvas.addEventListener('click', (e) => {const rect = canvas.getBoundingClientRect();1 unmodified lineconst y = e.clientY - rect.top;// 获取选中的原子类型const atomRadios = parent.document.querySelectorAll('input[name="atom_type"]');let atomType = "C";for (const radio of atomRadios) {if (radio.checked) {atomType = radio.value;break;}}// 添加新原子addAtom(x, y, atomType);updateMolData();});canvas.addEventListener('mousedown', (e) => {33 unmodified linesconst endAtom = getAtomAt(x, y);if (endAtom && endAtom !== selectedAtom) {// 获取选中的键类型const bondRadios = parent.document.querySelectorAll('input[name="bond_type"]');let bondType = "SINGLE";for (const radio of bondRadios) {if (radio.checked) {bondType = radio.value;break;}}addBond(selectedAtom.id, endAtom.id, bondType);updateMolData();}drawingBond = false;12 unmodified linesconst atom = getAtomAt(x, y);if (atom) {deleteAtom(atom.id);updateMolData();return;}const bond = getBondAt(x, y);if (bond) {deleteBond(bond.start, bond.end);updateMolData();}});// 更新分子数据function updateMolData() {const event = new CustomEvent('update_mol_data', {detail: JSON.stringify(moleculeData)});window.dispatchEvent(event);}// 加载分子数据function loadMoleculeData(data) {try {if (data) {moleculeData = JSON.parse(data);} else {moleculeData = { atoms: [], bonds: [] };}drawMolecule();} catch (e) {console.error("Error loading molecule data:", e);}}// 暴露全局函数window.loadMoleculeData = loadMoleculeData;window.initCanvas = initCanvas;// 监听更新事件window.addEventListener('update_mol_data', (e) => {document.getElementById('mol-data').value = e.detail;});// 初始化画布6 unmodified linescanvas = gr.HTML(canvas_html, label="Molecule Editor")# Molecule previewpreview = gr.Image(label="Molecule Preview", interactive=False)# Action buttonswith gr.Row():clear_btn = gr.Button("Clear Canvas")get_smiles_btn = gr.Button("Get SMILES")predict_btn = gr.Button("Predict Properties")with gr.Tab("Prediction Results"):with gr.Row():8 unmodified linesbrittle_pred = gr.Text(label="Brittle Prediction")brittle_img = gr.Image(label="Brittle Attention Visualization")# Hidden component for storing molecule datamol_data = gr.Text(value="", visible=False)js_command = gr.Textbox(value="", visible=False, label=None, interactive=False)# Hidden component for storing molecule datamol_data = gr.Text(value="", visible=False, elem_id="mol-data")# 事件绑定def clear_all():return "", "", ""def update_preview(smiles):img = generate_molecule_image(smiles)if img is None:return None, "Invalid SMILES"buffered = io.BytesIO()img.save(buffered, format="PNG")img_str = "data:image/png;base64," + base64.b64encode(buffered.getvalue()).decode()return img_str, smiles_to_mol_data(smiles) or ""# 更新按钮事件update_btn.click(update_preview,inputs=[smiles_input],outputs=[preview, mol_data])# 清除按钮事件clear_btn.click(clear_all,inputs=None,outputs=[smiles_input, preview, mol_data])# 获取SMILES按钮事件2 unmodified linesinputs=[mol_data],outputs=[smiles_input]).then(update_preview,inputs=[smiles_input],outputs=[preview, mol_data])5 unmodified linesoutputs=[elastic_pred, elastic_img, plastic_pred, plastic_img, brittle_pred, brittle_img])# 分子数据变化时更新预览mol_data.change(lambda data: update_preview(convert_to_smiles(data))[0],inputs=[mol_data],outputs=[preview])if __name__ == "__main__":logger.info("启动Gradio应用...")try:demo.launch(server_name="0.0.0.0", server_port=7860)except Exception as e:logger.error(f"启动Gradio应用失败: {str(e)}")raise
app.py+206-263