Spaces:
Runtime error
Runtime error
Update app.py
Browse files7 unmodified lines891011121314327 unmodified lines34234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769820 unmodified lines71972072172272372472572672772872973073173220 unmodified lines75375475575675775875976076114 unmodified lines77677777877978078178278378425 unmodified lines8108118128138148158168178188197 unmodified linesimport gradio as grfrom torch_geometric.data import Data as PyGDataimport matplotlibmatplotlib.use('Agg') # 修复后台线程问题import ioimport jsonimport base64327 unmodified lines# ==================== Gradio界面 ====================# 创建带有分子编辑器的Gradio界面with gr.Blocks(title="CrystalGAT", head='''<script>// 全局变量let moleculeData = { atoms: [], bonds: [] };let selectedAtom = null;let drawingBond = false;const atomRadius = 15;// 原子颜色映射const atomColors = {"C": "#CCCCCC", "N": "#6666FF", "O": "#FF6666","F": "#66FF66", "Cl": "#66FF66", "Br": "#FF8000","I": "#FF9999", "S": "#FFFF66", "P": "#FF9933"};// 初始化画布function initCanvas() {const canvas = document.getElementById('moleculeCanvas');if (!canvas) return;const ctx = canvas.getContext('2d');ctx.clearRect(0, 0, canvas.width, canvas.height);drawMolecule(ctx);}// 绘制分子function drawMolecule(ctx) {if (!ctx) return;ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);// 绘制键for (const bond of moleculeData.bonds) {const startAtom = moleculeData.atoms.find(a => a.id === bond.start);const endAtom = moleculeData.atoms.find(a => a.id === bond.end);if (startAtom && endAtom) {ctx.beginPath();ctx.moveTo(startAtom.x, startAtom.y);ctx.lineTo(endAtom.x, endAtom.y);// 根据键类型设置线宽if (bond.type === "SINGLE") {ctx.lineWidth = 2;} else if (bond.type === "DOUBLE") {ctx.lineWidth = 4;} else if (bond.type === "TRIPLE") {ctx.lineWidth = 6;}ctx.strokeStyle = "black";ctx.stroke();}}// 绘制原子for (const atom of moleculeData.atoms) {ctx.beginPath();ctx.arc(atom.x, atom.y, atomRadius, 0, Math.PI * 2);ctx.fillStyle = atom.color;ctx.fill();ctx.strokeStyle = "black";ctx.lineWidth = 1;ctx.stroke();// 绘制原子符号ctx.fillStyle = "black";ctx.font = "bold 14px Arial";ctx.textAlign = "center";ctx.textBaseline = "middle";ctx.fillText(atom.symbol, atom.x, atom.y);}}// 添加原子function addAtom(x, y, symbol) {const id = moleculeData.atoms.length > 0? Math.max(...moleculeData.atoms.map(a => a.id)) + 1: 0;moleculeData.atoms.push({id: id,symbol: symbol,x: x,y: y,color: atomColors[symbol] || "#FFFFFF"});const canvas = document.getElementById('moleculeCanvas');if (canvas) {const ctx = canvas.getContext('2d');drawMolecule(ctx);}updateMolData();return id;}// 添加键function addBond(startId, endId, type) {// 检查键是否已存在const bondExists = moleculeData.bonds.some(b =>(b.start === startId && b.end === endId) ||(b.start === endId && b.end === startId));if (!bondExists) {moleculeData.bonds.push({start: startId,end: endId,type: type,order: type === "SINGLE" ? 1 : type === "DOUBLE" ? 2 : 3});const canvas = document.getElementById('moleculeCanvas');if (canvas) {const ctx = canvas.getContext('2d');drawMolecule(ctx);}updateMolData();}}// 删除原子function deleteAtom(atomId) {// 移除原子moleculeData.atoms = moleculeData.atoms.filter(a => a.id !== atomId);// 移除相关键moleculeData.bonds = moleculeData.bonds.filter(b =>b.start !== atomId && b.end !== atomId);const canvas = document.getElementById('moleculeCanvas');if (canvas) {const ctx = canvas.getContext('2d');drawMolecule(ctx);}updateMolData();}// 删除键function deleteBond(startId, endId) {moleculeData.bonds = moleculeData.bonds.filter(b =>!((b.start === startId && b.end === endId) ||(b.start === endId && b.end === startId)));const canvas = document.getElementById('moleculeCanvas');if (canvas) {const ctx = canvas.getContext('2d');drawMolecule(ctx);}updateMolData();}// 获取位置上的原子function getAtomAt(x, y) {for (const atom of moleculeData.atoms) {const dx = atom.x - x;const dy = atom.y - y;const distance = Math.sqrt(dx * dx + dy * dy);if (distance < atomRadius) {return atom;}}return null;}// 获取位置上的键function getBondAt(x, y) {for (const bond of moleculeData.bonds) {const startAtom = moleculeData.atoms.find(a => a.id === bond.start);const endAtom = moleculeData.atoms.find(a => a.id === bond.end);if (startAtom && endAtom) {// 计算到线段的距离const A = { x: startAtom.x, y: startAtom.y };const B = { x: endAtom.x, y: endAtom.y };const P = { x: x, y: y };const AB = { x: B.x - A.x, y: B.y - A.y };const AP = { x: P.x - A.x, y: P.y - A.y };const dot = AP.x * AB.x + AP.y * AB.y;const lenSq = AB.x * AB.x + AB.y * AB.y;const t = Math.min(1, Math.max(0, dot / lenSq));const projection = {x: A.x + t * AB.x,y: A.y + t * AB.y};const dx = P.x - projection.x;const dy = P.y - projection.y;const distance = Math.sqrt(dx * dx + dy * dy);if (distance < 10) {return bond;}}}return null;}// 更新分子数据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: [] };}const canvas = document.getElementById('moleculeCanvas');if (canvas) {const ctx = canvas.getContext('2d');drawMolecule(ctx);}} catch (e) {console.error("Error loading molecule data:", e);}}// 初始化编辑器function setupMoleculeEditor() {const canvas = document.getElementById('moleculeCanvas');if (!canvas) return;const ctx = canvas.getContext('2d');initCanvas();// 事件监听器canvas.addEventListener('click', (e) => {const rect = canvas.getBoundingClientRect();const x = e.clientX - rect.left;const y = e.clientY - rect.top;// 获取选中的原子类型const atomRadios = 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);});canvas.addEventListener('mousedown', (e) => {if (e.button === 0) { // 左键const rect = canvas.getBoundingClientRect();const x = e.clientX - rect.left;const y = e.clientY - rect.top;selectedAtom = getAtomAt(x, y);drawingBond = selectedAtom !== null;}});canvas.addEventListener('mousemove', (e) => {if (drawingBond && selectedAtom) {const rect = canvas.getBoundingClientRect();const x = e.clientX - rect.left;const y = e.clientY - rect.top;// 绘制临时键drawMolecule(ctx);ctx.beginPath();ctx.moveTo(selectedAtom.x, selectedAtom.y);ctx.lineTo(x, y);ctx.strokeStyle = "blue";ctx.lineWidth = 2;ctx.stroke();}});canvas.addEventListener('mouseup', (e) => {if (drawingBond && selectedAtom) {const rect = canvas.getBoundingClientRect();const x = e.clientX - rect.left;const y = e.clientY - rect.top;const endAtom = getAtomAt(x, y);if (endAtom && endAtom !== selectedAtom) {// 获取选中的键类型const bondRadios = 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);}drawingBond = false;selectedAtom = null;drawMolecule(ctx);}});canvas.addEventListener('contextmenu', (e) => {e.preventDefault();const rect = canvas.getBoundingClientRect();const x = e.clientX - rect.left;const y = e.clientY - rect.top;// 尝试删除原子或键const atom = getAtomAt(x, y);if (atom) {deleteAtom(atom.id);return;}const bond = getBondAt(x, y);if (bond) {deleteBond(bond.start, bond.end);}});// 监听更新事件window.addEventListener('update_mol_data', (e) => {const molDataElement = document.getElementById('mol-data');if (molDataElement) {molDataElement.value = e.detail;}});}// 页面加载完成后初始化编辑器document.addEventListener('DOMContentLoaded', setupMoleculeEditor);</script>''') 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.")20 unmodified linesgr.Markdown("4. Use 'Update from SMILES' to load a new molecule")with gr.Column(scale=2):# 分子编辑器画布canvas_html = """<div style="border: 1px solid #000; background-color: white; cursor: pointer;"><canvas id="moleculeCanvas" width="800" height="400"></canvas></div>"""canvas = gr.HTML(canvas_html, label="Molecule Editor")# Molecule previewpreview = gr.Image(label="Molecule Preview", interactive=False)20 unmodified linesmol_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:14 unmodified lines# 清除按钮事件clear_btn.click(lambda: ["", None, ""],inputs=None,outputs=[smiles_input, preview, mol_data])# 获取SMILES按钮事件25 unmodified linesif __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)}")raise7 unmodified lines891011121314327 unmodified lines34234334434534634734820 unmodified lines36937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664720 unmodified lines66866967067167267367467567667767867968068168268368468568668714 unmodified lines70270370470570670770870971071171271371425 unmodified lines7407417427437447457467477487497507517527537547557567577587597607617627637647657 unmodified linesimport gradio as grfrom torch_geometric.data import Data as PyGDataimport matplotlibmatplotlib.use('Agg')import ioimport jsonimport base64327 unmodified lines# ==================== 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.")20 unmodified linesgr.Markdown("4. Use 'Update from SMILES' to load a new molecule")with gr.Column(scale=2):# 分子编辑器画布 - 使用更简单的实现canvas_html = """<div id="molecule-editor-container" style="position: relative; width: 800px; height: 400px; border: 1px solid #ccc; background-color: white;"><canvas id="molecule-canvas" width="800" height="400"></canvas></div>"""canvas = gr.HTML(canvas_html, label="Molecule Editor")# 注入安全的JavaScriptcanvas.js = """// 创建安全的编辑器实现function initMoleculeEditor() {const canvas = document.getElementById('molecule-canvas');if (!canvas) return;const ctx = canvas.getContext('2d');let atoms = [];let bonds = [];let selectedAtom = null;let isDrawingBond = false;const atomRadius = 15;// 原子颜色映射const atomColors = {"C": "#CCCCCC", "N": "#6666FF", "O": "#FF6666","F": "#66FF66", "Cl": "#66FF66", "Br": "#FF8000","I": "#FF9999", "S": "#FFFF66", "P": "#FF9933"};// 绘制分子function drawMolecule() {ctx.clearRect(0, 0, canvas.width, canvas.height);// 绘制键bonds.forEach(bond => {const startAtom = atoms.find(a => a.id === bond.start);const endAtom = atoms.find(a => a.id === bond.end);if (startAtom && endAtom) {ctx.beginPath();ctx.moveTo(startAtom.x, startAtom.y);ctx.lineTo(endAtom.x, endAtom.y);ctx.strokeStyle = "black";// 设置线宽基于键类型if (bond.type === "SINGLE") ctx.lineWidth = 2;else if (bond.type === "DOUBLE") ctx.lineWidth = 4;else if (bond.type === "TRIPLE") ctx.lineWidth = 6;ctx.stroke();}});// 绘制原子atoms.forEach(atom => {ctx.beginPath();ctx.arc(atom.x, atom.y, atomRadius, 0, Math.PI * 2);ctx.fillStyle = atom.color;ctx.fill();ctx.strokeStyle = "black";ctx.lineWidth = 1;ctx.stroke();// 绘制原子符号ctx.fillStyle = "black";ctx.font = "bold 14px Arial";ctx.textAlign = "center";ctx.textBaseline = "middle";ctx.fillText(atom.symbol, atom.x, atom.y);});}// 添加原子function addAtom(x, y, symbol) {const id = atoms.length > 0 ? Math.max(...atoms.map(a => a.id)) + 1 : 0;atoms.push({id: id,symbol: symbol,x: x,y: y,color: atomColors[symbol] || "#FFFFFF"});drawMolecule();updateMolData();return id;}// 添加键function addBond(startId, endId, type) {// 检查键是否已存在const bondExists = bonds.some(b =>(b.start === startId && b.end === endId) ||(b.start === endId && b.end === startId));if (!bondExists) {bonds.push({start: startId,end: endId,type: type,order: type === "SINGLE" ? 1 : type === "DOUBLE" ? 2 : 3});drawMolecule();updateMolData();}}// 删除原子function deleteAtom(atomId) {atoms = atoms.filter(a => a.id !== atomId);bonds = bonds.filter(b => b.start !== atomId && b.end !== atomId);drawMolecule();updateMolData();}// 删除键function deleteBond(startId, endId) {bonds = bonds.filter(b =>!((b.start === startId && b.end === endId) ||(b.start === endId && b.end === startId)));drawMolecule();updateMolData();}// 获取位置上的原子function getAtomAt(x, y) {return atoms.find(atom => {const dx = atom.x - x;const dy = atom.y - y;return Math.sqrt(dx * dx + dy * dy) < atomRadius;});}// 获取位置上的键function getBondAt(x, y) {return bonds.find(bond => {const startAtom = atoms.find(a => a.id === bond.start);const endAtom = atoms.find(a => a.id === bond.end);if (!startAtom || !endAtom) return false;// 计算点到线段的距离const A = { x: startAtom.x, y: startAtom.y };const B = { x: endAtom.x, y: endAtom.y };const P = { x: x, y: y };const AB = { x: B.x - A.x, y: B.y - A.y };const AP = { x: P.x - A.x, y: P.y - A.y };const dot = AP.x * AB.x + AP.y * AB.y;const lenSq = AB.x * AB.x + AB.y * AB.y;const t = Math.min(1, Math.max(0, dot / lenSq));const projection = {x: A.x + t * AB.x,y: A.y + t * AB.y};const dx = P.x - projection.x;const dy = P.y - projection.y;return Math.sqrt(dx * dx + dy * dy) < 10;});}// 更新分子数据function updateMolData() {const molData = {atoms: atoms,bonds: bonds,width: canvas.width,height: canvas.height};const event = new CustomEvent('update_mol_data', {detail: JSON.stringify(molData)});window.dispatchEvent(event);}// 事件监听器canvas.addEventListener('click', (e) => {const rect = canvas.getBoundingClientRect();const x = e.clientX - rect.left;const y = e.clientY - rect.top;// 获取选中的原子类型const atomType = document.querySelector('input[name="atom_type"]:checked').value;addAtom(x, y, atomType);});canvas.addEventListener('mousedown', (e) => {if (e.button === 0) { // 左键const rect = canvas.getBoundingClientRect();const x = e.clientX - rect.left;const y = e.clientY - rect.top;selectedAtom = getAtomAt(x, y);isDrawingBond = selectedAtom !== null;}});canvas.addEventListener('mousemove', (e) => {if (isDrawingBond && selectedAtom) {const rect = canvas.getBoundingClientRect();const x = e.clientX - rect.left;const y = e.clientY - rect.top;// 绘制临时键drawMolecule();ctx.beginPath();ctx.moveTo(selectedAtom.x, selectedAtom.y);ctx.lineTo(x, y);ctx.strokeStyle = "blue";ctx.lineWidth = 2;ctx.stroke();}});canvas.addEventListener('mouseup', (e) => {if (isDrawingBond && selectedAtom) {const rect = canvas.getBoundingClientRect();const x = e.clientX - rect.left;const y = e.clientY - rect.top;const endAtom = getAtomAt(x, y);if (endAtom && endAtom !== selectedAtom) {// 获取选中的键类型const bondType = document.querySelector('input[name="bond_type"]:checked').value;addBond(selectedAtom.id, endAtom.id, bondType);}isDrawingBond = false;selectedAtom = null;drawMolecule();}});canvas.addEventListener('contextmenu', (e) => {e.preventDefault();const rect = canvas.getBoundingClientRect();const x = e.clientX - rect.left;const y = e.clientY - rect.top;// 尝试删除原子或键const atom = getAtomAt(x, y);if (atom) {deleteAtom(atom.id);return;}const bond = getBondAt(x, y);if (bond) {deleteBond(bond.start, bond.end);}});// 初始化画布drawMolecule();// 监听更新事件window.addEventListener('update_mol_data', (e) => {const molDataElement = document.getElementById('mol-data');if (molDataElement) {molDataElement.value = e.detail;}});}// 初始化编辑器document.addEventListener('DOMContentLoaded', initMoleculeEditor);"""# Molecule previewpreview = gr.Image(label="Molecule Preview", interactive=False)20 unmodified linesmol_data = gr.Text(value="", visible=False, elem_id="mol-data")# 事件绑定def clear_editor():# 通过JavaScript重置编辑器return gr.update(js="""(() => {const canvas = document.getElementById('molecule-canvas');if (canvas) {const ctx = canvas.getContext('2d');ctx.clearRect(0, 0, canvas.width, canvas.height);}window.dispatchEvent(new CustomEvent('update_mol_data', {detail: JSON.stringify({atoms: [], bonds: []})}));return '';})()""")def update_preview(smiles):img = generate_molecule_image(smiles)if img is None:14 unmodified lines# 清除按钮事件clear_btn.click(clear_editor,inputs=None,outputs=[mol_data]).then(lambda: ["", None],inputs=None,outputs=[smiles_input, preview])# 获取SMILES按钮事件25 unmodified linesif __name__ == "__main__":logger.info("启动Gradio应用...")try:demo.launch(server_name="0.0.0.0",server_port=7860,# 禁用安全策略以允许编辑器工作enable_queue=True,share=False,auth=None,favicon_path=None,ssl_verify=True,ssl_keyfile=None,ssl_certfile=None,ssl_keyfile_password=None,quiet=False,show_error=True,debug=True)except Exception as e:logger.error(f"启动Gradio应用失败: {str(e)}")raise
app.py+307-361