Update app.py
Browse files123456781 unmodified line1011121314151645 unmodified lines626364656667686970713 unmodified lines75767778798081828384851 unmodified line878889909192939495969798991001011021031041051061071081091101111121131141151 unmodified line11711811912012112212312412512612712812913013113213367 unmodified lines2012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312 unmodified lines234235236237238239240import osimport zipfileimport loggingimport torchimport numpy as npfrom io import BytesIOfrom PIL import Image1 unmodified lineimport gradio as grfrom torch_geometric.data import Data as PyGDataimport matplotlibmatplotlib.use('Agg') # fix backend threading issuefrom rdkit import Chemfrom rdkit.Chem import Draw, AllChem, MolFromSmiles45 unmodified lines# Model Loading# ----------------------------def load_models():import numpy.core.multiarrayfrom torch.serialization import add_safe_globals# 显式允许加载某些 numpy 序列化类型(仅当你信任模型来源)add_safe_globals([numpy.core.multiarray.scalar])specs = {3 unmodified lines}models = {}for name, (path, out_dim) in specs.items():if not os.path.exists(path):if os.path.exists("models.zip"):logging.info("Unzipping models.zip...")with zipfile.ZipFile("models.zip", 'r') as z:z.extractall(".")else:1 unmodified linemodel = EnhancedGAT(input_dim=12, hidden_dim=512, output_dim=out_dim, num_heads=8)# 🔧 明确禁用 weights_only 以兼容新 PyTorch 版本try:state = torch.load(path, map_location=device, weights_only=False)except TypeError:# 兼容旧版本 PyTorch(无 weights_only 参数)state = torch.load(path, map_location=device)state_dict = state.get("model_state_dict", state)model.load_state_dict(state_dict)model.eval().to(device)models[name] = modellogging.info(f"{name} model loaded successfully.")return modelsmodels = load_models()# ----------------------------# Prediction Function# ----------------------------def predict_all(smiles: str):"""Run Elastic, Plastic, Brittle predictions; return text & PIL images."""atom_feats, (rows, cols, edge_attr), _ = smiles_to_graph(smiles)x = torch.tensor(atom_feats, dtype=torch.float)edge_index = torch.tensor(np.vstack((rows, cols)), dtype=torch.long)1 unmodified linedata = PyGData(x=x, edge_index=edge_index, edge_attr=edge_attr,smiles=[smiles], batch=torch.zeros(x.size(0), dtype=torch.long))results = []for name in ["Elastic", "Plastic", "Brittle"]:buf, pred = visualize_single_molecule(models[name], data, device, name)if buf:buf.seek(0)img = Image.open(buf)text = f"{name}: {int(pred)}"results.append((text, img))else:results.append((f"{name} prediction failed", None))return (*results[0], *results[1], *results[2])# ----------------------------# Molecule Builder Utilities67 unmodified lines# ----------------------------with gr.Blocks(title="CrystalGAT", css=""".gradio-container {max-width:800px; margin:auto}.block {padding:1em}.gr-button {margin:0.2em}""") as demo:gr.Markdown("## CrystalGAT \nEnter a SMILES string or build a molecule to predict Elastic, Plastic, and Brittle classes with attention visualization.")with gr.Tab("SMILES Input"):smi_in = gr.Textbox(label="SMILES", placeholder="e.g. CCO")predict1 = gr.Button("Predict")with gr.Tab("Manual Molecules Construction"):state = gr.State(init_molecule())status = gr.Textbox(label="Status", interactive=False, value="Start by adding atoms")with gr.Row():with gr.Column(scale=1):atom_type = gr.Dropdown(label="Atom Type", choices=ATOM_TYPES, value="C")add_a = gr.Button("Add Atom")atom_tbl = gr.Dataframe(headers=["ID","Type"], datatype=["number","str"], interactive=False)with gr.Column(scale=1):a1 = gr.Dropdown(label="Atom 1", choices=[], value=None)a2 = gr.Dropdown(label="Atom 2", choices=[], value=None)bond_type = gr.Dropdown(label="Bond Type", choices=BOND_TYPES, value="Single")add_b = gr.Button("Add Bond")bond_tbl = gr.Dataframe(headers=["Atom1","Atom2","Type"], datatype=["str","str","str"], interactive=False)with gr.Row():clear = gr.Button("Clear All")make = gr.Button("Generate SMILES")2 unmodified linespredict2 = gr.Button("Predict on Built Molecule")# Prediction Outputswith gr.Row():e_txt = gr.Text(label="Elastic")e_img = gr.Image(type="pil", label="Elastic Attention")123456781 unmodified line1011121314151645 unmodified lines626364656667686970713 unmodified lines757677787980818283841 unmodified line86878889909192939495969798991001011021031041051061071081091101111121131141151 unmodified line11711811912012112212312412512612712812913013113213313413513613713813914014114267 unmodified lines2102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402 unmodified lines243244245246247248249import osimport zipfileimport loggingimport torchimport torch.nn.functional as Fimport numpy as npfrom io import BytesIOfrom PIL import Image1 unmodified lineimport gradio as grfrom torch_geometric.data import Data as PyGDataimport matplotlibmatplotlib.use('Agg')from rdkit import Chemfrom rdkit.Chem import Draw, AllChem, MolFromSmiles45 unmodified lines# Model Loading# ----------------------------def load_models():from torch.serialization import add_safe_globalsimport numpy.core.multiarray# allow safe numpy objects if neededadd_safe_globals([numpy.core.multiarray.scalar])specs = {3 unmodified lines}models = {}for name, (path, out_dim) in specs.items():if not os.path.exists(path):if os.path.exists("models.zip"):logger.info("Extracting models.zip...")with zipfile.ZipFile("models.zip", 'r') as z:z.extractall(".")else:1 unmodified linemodel = EnhancedGAT(input_dim=12, hidden_dim=512, output_dim=out_dim, num_heads=8)try:state = torch.load(path, map_location=device, weights_only=False)except TypeError:state = torch.load(path, map_location=device)state_dict = state.get("model_state_dict", state)model.load_state_dict(state_dict)model.eval().to(device)models[name] = modellogger.info(f"{name} model loaded successfully.")return modelsmodels = load_models()# ----------------------------# Prediction Function# ----------------------------def predict_all(smiles: str):"""Run predictions for Elastic, Plastic, Brittle.Use threshold 0.5 for Elastic/Brittle, 0.3 for Plastic.Return (text, PIL image) for each."""atom_feats, (rows, cols, edge_attr), _ = smiles_to_graph(smiles)x = torch.tensor(atom_feats, dtype=torch.float)edge_index = torch.tensor(np.vstack((rows, cols)), dtype=torch.long)1 unmodified linedata = PyGData(x=x, edge_index=edge_index, edge_attr=edge_attr,smiles=[smiles], batch=torch.zeros(x.size(0), dtype=torch.long))outputs = []thresholds = {"Elastic": 0.5, "Plastic": 0.3, "Brittle": 0.5}for name in ["Elastic", "Plastic", "Brittle"]:model = models[name]with torch.no_grad():logits = model(data)# assume binary classification: two outputsif logits.dim() == 1 or logits.size(1) == 1:prob = torch.sigmoid(logits).item()else:prob = F.softmax(logits, dim=1)[0, 1].item()label = int(prob >= thresholds[name])# get visualization bufferbuf, _ = visualize_single_molecule(model, data, device, name)img = Image.open(buf) if buf else Noneoutputs.append((f"{name}: {label} (p={prob:.2f})", img))# flatten to 6 outputsreturn (*outputs[0], *outputs[1], *outputs[2])# ----------------------------# Molecule Builder Utilities67 unmodified lines# ----------------------------with gr.Blocks(title="CrystalGAT", css=""".gradio-container {max-width:800px; margin:auto}.gr-button {margin:0.2em}""") as demo:gr.Markdown("## CrystalGAT \nEnter a SMILES string or build a molecule to predict Elastic, Plastic, and Brittle classes with attention visualization.")with gr.Tab("SMILES Input"):smi_in = gr.Textbox(label="SMILES", placeholder="e.g. CCO")predict1 = gr.Button("Predict")with gr.Tab("Manual Molecule Construction"):state = gr.State(init_molecule())status = gr.Textbox(label="Status", interactive=False, value="Start by adding atoms")with gr.Row():with gr.Column():atom_type = gr.Dropdown(label="Atom Type", choices=ATOM_TYPES, value="C")add_a = gr.Button("Add Atom")atom_tbl = gr.Dataframe(headers=["ID","Type"], datatype=["number","str"], interactive=False)with gr.Column():a1 = gr.Dropdown(label="Atom 1", choices=[], value=None)a2 = gr.Dropdown(label="Atom 2", choices=[], value=None)bond_type = gr.Dropdown(label="Bond Type", choices=BOND_TYPES, value="Single")add_b = gr.Button("Add Bond")bond_tbl = gr.Dataframe(headers=["Atom1","Atom2","Type"], datatype=["str","str","str"], interactive=False)with gr.Row():clear = gr.Button("Clear All")make = gr.Button("Generate SMILES")2 unmodified linespredict2 = gr.Button("Predict on Built Molecule")# Outputswith gr.Row():e_txt = gr.Text(label="Elastic")e_img = gr.Image(type="pil", label="Elastic Attention")
app.py+38-29