Spaces:
Runtime error
Runtime error
Update app.py
Browse files12 unmodified lines13141516171819202122317 unmodified lines3403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806 unmodified lines68768868969069169269369469569669769816 unmodified lines7157167177187197207217227237247251 unmodified line72772872973073173273373473573673773812 unmodified linesimport base64from rdkit import Chemfrom rdkit.Chem import Draw, BondType, rdDepictor# 配置日志logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')logger = logging.getLogger(__name__)# GPU内存优化os.environ["PYTORCH_CUDA_ALLOC_CONF"] = "max_split_size_mb:128"317 unmodified linesreturn "Invalid Molecule"# ==================== Gradio界面 ====================# 创建带有分子编辑器的Gradio界面with gr.Blocks(title="CrystalGAT: Crystal Mechanical Property Predictor") as demo:gr.Markdown("# CrystalGAT: Crystal Mechanical Property Predictor")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")gr.Markdown("1. Click on the canvas to add atoms")gr.Markdown("2. Drag from one atom to another to add bonds")gr.Markdown("3. Right-click on atoms or bonds to delete")gr.Markdown("4. Use 'Update from SMILES' to load a new molecule")with gr.Column(scale=2):# 分子编辑器画布canvas = gr.HTML("""<canvas id="moleculeCanvas" width="800" height="400" style="border:1px solid #000; background-color: white;"></canvas><script>// Canvas and contextconst canvas = document.getElementById('moleculeCanvas');const ctx = canvas.getContext('2d');// Molecule data structurelet moleculeData = { atoms: [], bonds: [] };let selectedAtom = null;let drawingBond = false;let atomRadius = 15;// Color mappingconst atomColors = {"C": "#CCCCCC", "N": "#6666FF", "O": "#FF6666","F": "#66FF66", "Cl": "#66FF66", "Br": "#FF8000","I": "#FF9999", "S": "#FFFF66", "P": "#FF9933"};// Initialize canvasfunction initCanvas() {ctx.clearRect(0, 0, canvas.width, canvas.height);drawMolecule();}// Draw moleculefunction drawMolecule() {ctx.clearRect(0, 0, canvas.width, canvas.height);// Draw bondsfor (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);ctx.strokeStyle = "black";ctx.lineWidth = 2;ctx.stroke();}}// Draw atomsfor (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();// Draw atom symbolctx.fillStyle = "black";ctx.font = "12px Arial";ctx.textAlign = "center";ctx.textBaseline = "middle";ctx.fillText(atom.symbol, atom.x, atom.y);}}// Add atomfunction 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"});drawMolecule();return id;}// Add bondfunction addBond(startId, endId, type) {// Check if bond already existsconst 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});drawMolecule();}}// Delete atomfunction deleteAtom(atomId) {// Remove atommoleculeData.atoms = moleculeData.atoms.filter(a => a.id !== atomId);// Remove related bondsmoleculeData.bonds = moleculeData.bonds.filter(b =>b.start !== atomId && b.end !== atomId);drawMolecule();}// Delete bondfunction deleteBond(startId, endId) {moleculeData.bonds = moleculeData.bonds.filter(b =>!((b.start === startId && b.end === endId) ||(b.start === endId && b.end === startId)));drawMolecule();}// Get atom at positionfunction 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;}// Get bond at positionfunction 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) {// Calculate distance to line segmentconst 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;}// Event listenerscanvas.addEventListener('click', (e) => {const rect = canvas.getBoundingClientRect();const x = e.clientX - rect.left;const y = e.clientY - rect.top;// Get selected atom typeconst atomType = document.querySelector('input[name="atom_type"]:checked').value;// Add new atomaddAtom(x, y, atomType);});canvas.addEventListener('mousedown', (e) => {if (e.button === 0) { // Left buttonconst 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;// Draw temporary bonddrawMolecule();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) {// Get selected bond typeconst bondType = document.querySelector('input[name="bond_type"]:checked').value;addBond(selectedAtom.id, endAtom.id, bondType);}drawingBond = 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;// Try to delete atom or bondconst atom = getAtomAt(x, y);if (atom) {deleteAtom(atom.id);return;}const bond = getBondAt(x, y);if (bond) {deleteBond(bond.start, bond.end);}});// Load molecule data from Pythonwindow.loadMoleculeData = function(data) {moleculeData = JSON.parse(data);drawMolecule();};// Get molecule datawindow.getMoleculeData = function() {return JSON.stringify(moleculeData);};// Initialize canvasinitCanvas();<script>window.addEventListener("message", async (event) => {const message = event.data;if (typeof message !== "string") return;if (!message.startsWith("{")) return;try {const cmd = JSON.parse(message);if (cmd.type === "load" && cmd.data && window.loadMoleculeData) {window.loadMoleculeData(cmd.data);} else if (cmd.type === "clear" && window.initCanvas) {window.initCanvas();} else if (cmd.type === "get" && window.getMoleculeData) {const molData = window.getMoleculeData();const event = new CustomEvent("send_mol_data", { detail: molData });window.dispatchEvent(event);}} catch (e) {console.error("Invalid command:", message);}});window.addEventListener("send_mol_data", (event) => {const input = document.querySelector("textarea[aria-label='mol_data']");if (input) {input.value = event.detail;input.dispatchEvent(new Event("input", { bubbles: true }));}});</script></script>""")# 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():with gr.Column():6 unmodified lineswith gr.Column():brittle_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)# 所有事件绑定都必须放在 with gr.Blocks() 内部update_btn.click(update_molecule_editor,inputs=[smiles_input],16 unmodified linesoutputs=[js_command])mol_data.change(convert_to_smiles,inputs=[mol_data],outputs=[smiles_input])predict_btn.click(predict_all,1 unmodified lineoutputs=[elastic_pred, elastic_img, plastic_pred, plastic_img, brittle_pred, brittle_img])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)}")raise12 unmodified lines131415161718192021222324317 unmodified lines3423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284296 unmodified lines43643743843944044144244344444516 unmodified lines4624634644654664674681 unmodified line47047147247347447512 unmodified linesimport base64from rdkit import Chemfrom rdkit.Chem import Draw, BondType, rdDepictorfrom utils import update_molecule_editor, convert_to_smiles, predict_all # 假设这些函数在 utils.py 中定义# 配置日志logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')logger = logging.getLogger(__name__)logger = logging.getLogger("CrystalGAT")# GPU内存优化os.environ["PYTORCH_CUDA_ALLOC_CONF"] = "max_split_size_mb:128"317 unmodified linesreturn "Invalid Molecule"# ==================== 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")atom_type = gr.Dropdown(["C", "N", "O", "F", "Cl", "Br", "I", "S", "P"], value="C", label="Atom Type")bond_type = gr.Dropdown(["SINGLE", "DOUBLE", "TRIPLE"], value="SINGLE", label="Bond Type")update_btn = gr.Button("Update from SMILES")gr.Markdown("### Instructions")gr.Markdown("1. Click on the canvas to add atoms\n2. Drag from one atom to another to add bonds\n3. Right-click on atoms or bonds to delete\n4. Use 'Update from SMILES' to load a new molecule")with gr.Column(scale=2):canvas_html = gr.HTML("""<canvas id='moleculeCanvas' width='800' height='400' style='border:1px solid black; background-color:white'></canvas><script>let moleculeData = { atoms: [], bonds: [] };let selectedAtom = null;let drawingBond = false;const canvas = document.getElementById("moleculeCanvas");const ctx = canvas.getContext("2d");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);for (const bond of moleculeData.bonds) {const a = moleculeData.atoms.find(x => x.id === bond.start);const b = moleculeData.atoms.find(x => x.id === bond.end);if (a && b) {ctx.beginPath();ctx.moveTo(a.x, a.y);ctx.lineTo(b.x, b.y);ctx.strokeStyle = "black";ctx.lineWidth = 2;ctx.stroke();}}for (const atom of moleculeData.atoms) {ctx.beginPath();ctx.arc(atom.x, atom.y, atomRadius, 0, Math.PI * 2);ctx.fillStyle = atomColors[atom.symbol] || "#FFFFFF";ctx.fill();ctx.strokeStyle = "black";ctx.stroke();ctx.fillStyle = "black";ctx.font = "12px Arial";ctx.textAlign = "center";ctx.textBaseline = "middle";ctx.fillText(atom.symbol, atom.x, atom.y);}}canvas.addEventListener("click", function(e) {const rect = canvas.getBoundingClientRect();const x = e.clientX - rect.left;const y = e.clientY - rect.top;const symbol = document.querySelector("select[label='Atom Type']")?.value || "C";const id = moleculeData.atoms.length > 0 ? Math.max(...moleculeData.atoms.map(a => a.id)) + 1 : 0;moleculeData.atoms.push({ id, symbol, x, y });drawMolecule();});window.getMolData = () => JSON.stringify(moleculeData);window.loadMolData = (data) => { moleculeData = JSON.parse(data); drawMolecule(); };window.clearMolData = () => { moleculeData = { atoms: [], bonds: [] }; drawMolecule(); };</script>""")preview = gr.Image(label="Molecule Preview", interactive=False)with 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():with gr.Column():6 unmodified lineswith gr.Column():brittle_pred = gr.Text(label="Brittle Prediction")brittle_img = gr.Image(label="Brittle Attention Visualization")mol_data = gr.Text(visible=False)js_command = gr.Textbox(visible=False)update_btn.click(update_molecule_editor,inputs=[smiles_input],16 unmodified linesoutputs=[js_command])mol_data.change(convert_to_smiles, inputs=[mol_data], outputs=[smiles_input])predict_btn.click(predict_all,1 unmodified lineoutputs=[elastic_pred, elastic_img, plastic_pred, plastic_img, brittle_pred, brittle_img])if __name__ == "__main__":logger.info("启动Gradio应用...")demo.launch(server_name="0.0.0.0", server_port=7860, share=True)
app.py+73-336