Update app.py
Browse files22 unmodified lines23242526272829303132331 unmodified line3536373839404142434445464748495051525354552 unmodified lines5859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161172 unmodified lines12012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429522 unmodified lineslogging.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"logger.info("设置GPU内存优化参数: PYTORCH_CUDA_ALLOC_CONF=max_split_size_mb:128")# 解压模型文件if not os.path.exists("best_model-B-6000-185.pth"):logger.info("开始解压模型文件...")try:1 unmodified linezip_ref.extractall(".")logger.info("模型文件解压完成!")except Exception as e:logger.error(f"解压模型文件失败: {str(e)}")raise# 导入模型工具try:from model_utils import EnhancedGAT, smiles_to_graph, visualize_single_moleculelogger.info("成功导入 model_utils 模块")except ImportError as e:logger.error(f"导入 model_utils 失败: {str(e)}")raisedevice = torch.device("cuda" if torch.cuda.is_available() else "cpu")logger.info(f"使用设备: {device}")if torch.cuda.is_available():logger.info(f"GPU 信息: {torch.cuda.get_device_name(0)}")def load_models():model_info = {2 unmodified lines"Brittle": ("models/best_model-B-6000-185.pth", 2)}models = {}for name, (pth_path, output_dim) in model_info.items():logger.info(f"正在加载 {name} 模型: {pth_path}")if not os.path.exists(pth_path):logger.error(f"模型文件不存在: {pth_path}")possible_files = [pth_path,pth_path.lower(),pth_path.upper(),pth_path.replace("-", "_"),pth_path.replace("_", "-")]found = Falsefor file in possible_files:if os.path.exists(file):logger.warning(f"使用替代文件: {file}")pth_path = filefound = Truebreakif not found:raise FileNotFoundError(f"模型文件 {pth_path} 不存在")try:model = EnhancedGAT(input_dim=12, hidden_dim=512, output_dim=output_dim, num_heads=8)logger.info(f"加载模型权重: {pth_path}")try:state = torch.load(pth_path, map_location=device, weights_only=False)except Exception as e:logger.warning(f"weights_only=False 加载失败: {str(e)}")try:import numpy as np, torch.serializationtorch.serialization.add_safe_globals([getattr(np, '_core', np).multiarray.scalar])state = torch.load(pth_path, map_location=device, weights_only=True)except:state = torch.load(pth_path, map_location=device)if "model_state_dict" in state:state_dict = state["model_state_dict"]else:state_dict = statemodel.load_state_dict(state_dict)model.eval().to(device)models[name] = modellogger.info(f"{name} 模型加载成功!")except Exception as e:logger.error(f"加载 {name} 模型失败: {str(e)}")raisereturn modelslogger.info("开始加载所有模型...")models = load_models()logger.info("所有模型加载完成!")def predict_all(smiles):logger.info(f"收到预测请求: SMILES = {smiles}")try:atom_features, (rows, cols, edge_attr), mol = smiles_to_graph(smiles)x = torch.tensor(atom_features, dtype=torch.float)edge_index = torch.tensor(np.column_stack((rows, cols)).T, dtype=torch.long)edge_attr = torch.tensor(edge_attr, dtype=torch.float).unsqueeze(1)2 unmodified linesedge_attr=edge_attr,smiles=[smiles],batch=torch.zeros(x.size(0), dtype=torch.long))results = []for name in ["Elastic", "Plastic", "Brittle"]:logger.info(f"使用 {name} 模型进行预测...")try:buf, pred = visualize_single_molecule(models[name], data, device, name)if buf:buf.seek(0)img = Image.open(buf)pred_text = f"{name} Result: {'1' if pred == 1 else '0'}"results.append((pred_text, img))else:results.append((f"{name} 预测失败: 未生成图像", None))except Exception as e:results.append((f"{name} 预测过程中发生错误: {str(e)}", None))return (results[0][0], results[0][1],results[1][0], results[1][1],results[2][0], results[2][1])except Exception as e:logger.error(f"预测过程中发生严重错误: {str(e)}")return ("预测失败", None, "预测失败", None, "预测失败", None)# 原子和键类型选项ATOM_TYPES = ["C", "N", "O", "S", "P", "F", "Cl", "Br", "I", "H"]BOND_TYPES = ["单键", "双键", "三键"]# 初始化分子结构def init_molecule():return {"atoms": [], "bonds": []}# 添加原子def add_atom(molecule, atom_type):molecule["atoms"].append({"id": len(molecule["atoms"]), "type": atom_type})return molecule# 添加键def add_bond(molecule, atom1_id, atom2_id, bond_type):if atom1_id >= len(molecule["atoms"]) or atom2_id >= len(molecule["atoms"]):return moleculefor bond in molecule["bonds"]:if {bond["atom1"], bond["atom2"]} == {atom1_id, atom2_id}:return moleculemolecule["bonds"].append({"atom1": atom1_id, "atom2": atom2_id, "type": bond_type})return molecule# 从 JSON 构建 SMILESdef generate_smiles(molecule_json):try:mol = Chem.RWMol()atom_map = {}for atom in molecule_json["atoms"]:idx = mol.AddAtom(Chem.Atom(atom["type"]))atom_map[atom["id"]] = idxfor bond in molecule_json["bonds"]:t = {"单键": Chem.BondType.SINGLE,"双键": Chem.BondType.DOUBLE,"三键": Chem.BondType.TRIPLE}[bond["type"]]mol.AddBond(atom_map[bond["atom1"]], atom_map[bond["atom2"]], t)mol.UpdatePropertyCache()Chem.SanitizeMol(mol)return Chem.MolToSmiles(mol)except Exception as e:logger.error(f"生成SMILES失败: {e}")return None# 可视化分子def visualize_molecule(molecule_json):smiles = generate_smiles(molecule_json)if not smiles:return Nonemol = MolFromSmiles(smiles)if mol is None:return NoneAllChem.Compute2DCoords(mol)img = Draw.MolToImage(mol, size=(300, 300))buf = BytesIO()img.save(buf, format="PNG")buf.seek(0)return buf# 更新下拉菜单选项(改为 gr.update)def update_atom_dropdowns(molecule):choices = [f"{a['id']}: {a['type']}" for a in molecule["atoms"]]return gr.update(choices=choices, value=None), gr.update(choices=choices, value=None)# 更新原子列表def update_atoms_list(molecule):return [[a["id"], a["type"]] for a in molecule["atoms"]]# 更新键列表def update_bonds_list(molecule):out = []for b in molecule["bonds"]:t1 = next(a["type"] for a in molecule["atoms"] if a["id"]==b["atom1"])t2 = next(a["type"] for a in molecule["atoms"] if a["id"]==b["atom2"])out.append([f"{b['atom1']}: {t1}", f"{b['atom2']}: {t2}", b["type"]])return outwith gr.Blocks(title="CrystalGAT") as demo:gr.Markdown("# CrystalGAT")gr.Markdown("输入SMILES或构建分子,预测弹性/塑性/脆性并可视化")with gr.Tab("SMILES输入"):smiles_input = gr.Textbox(label="SMILES", placeholder="例如: CCO")submit_btn1 = gr.Button("预测", variant="primary")with gr.Tab("构建分子"):molecule_state = gr.State(init_molecule())status_msg = gr.Textbox(label="状态", interactive=False, value="请添加原子开始")with gr.Row():atom_select = gr.Dropdown(label="选择原子类型", choices=ATOM_TYPES, value="C")add_atom_btn = gr.Button("添加原子")atoms_list = gr.Dataframe(headers=["ID","原子类型"], datatype=["number","str"], interactive=False)with gr.Row():atom1_select = gr.Dropdown(label="第一个原子", choices=[], value=None)atom2_select = gr.Dropdown(label="第二个原子", choices=[], value=None)bond_select = gr.Dropdown(label="键类型", choices=BOND_TYPES, value="单键")add_bond_btn = gr.Button("添加键")bonds_list = gr.Dataframe(headers=["原子1","原子2","键类型"], datatype=["str","str","str"], interactive=False)clear_btn = gr.Button("清除所有")generate_btn = gr.Button("生成分子")molecule_smiles = gr.Textbox(label="SMILES结果", interactive=False)molecule_img = gr.Image(label="分子预览", interactive=False)submit_btn2 = gr.Button("使用此分子预测", variant="primary")# 绑定事件add_atom_btn.click(fn=lambda at, mol: add_atom(mol, at),inputs=[atom_select, molecule_state],outputs=molecule_state) \.then(fn=update_atoms_list, inputs=molecule_state, outputs=atoms_list) \.then(fn=update_atom_dropdowns, inputs=molecule_state, outputs=[atom1_select, atom2_select]) \.then(fn=lambda: "原子添加成功", outputs=status_msg)add_bond_btn.click(fn=lambda a1, a2, b, mol: (add_bond(mol,int(a1.split(":")[0]),int(a2.split(":")[0]), b)) if a1 and a2 else mol,inputs=[atom1_select, atom2_select, bond_select, molecule_state],outputs=molecule_state) \.then(fn=update_bonds_list, inputs=molecule_state, outputs=bonds_list) \.then(fn=lambda: "键添加/更新成功", outputs=status_msg)clear_btn.click(fn=init_molecule, outputs=molecule_state) \.then(fn=lambda: ([], []), outputs=[atoms_list, bonds_list]) \.then(fn=lambda: (gr.update(choices=[], value=None), gr.update(choices=[], value=None)),outputs=[atom1_select, atom2_select]) \.then(fn=lambda: "已清除所有", outputs=status_msg)generate_btn.click(fn=generate_smiles, inputs=molecule_state, outputs=molecule_smiles) \.then(fn=visualize_molecule, inputs=molecule_state, outputs=molecule_img) \.then(fn=lambda: "分子生成完成", outputs=status_msg)# 输出区域with gr.Row():elastic_text = gr.Text(label="Elastic")elastic_img = gr.Image(type="pil", label="Elastic 可视化")with gr.Row():plastic_text = gr.Text(label="Plastic")plastic_img = gr.Image(type="pil", label="Plastic 可视化")with gr.Row():brittle_text = gr.Text(label="Brittle")brittle_img = gr.Image(type="pil", label="Brittle 可视化")submit_btn1.click(fn=predict_all,inputs=smiles_input,outputs=[elastic_text, elastic_img, plastic_text, plastic_img, brittle_text, brittle_img])submit_btn2.click(fn=lambda s: predict_all(s) if s else ("请输入SMILES", None, "", None, "", None),inputs=molecule_smiles,outputs=[elastic_text, elastic_img, plastic_text, plastic_img, brittle_text, brittle_img])if __name__ == "__main__":demo.launch(server_name="0.0.0.0", server_port=7860)22 unmodified lines23242526272829303132331 unmodified line3536373839404142434445464748495051525354552 unmodified lines5859606162636465666768697071727374757677787980812 unmodified lines8485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325422 unmodified lineslogging.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"logger.info("设置 GPU 内存优化参数")# 解压模型if not os.path.exists("best_model-B-6000-185.pth"):logger.info("开始解压模型文件...")try:1 unmodified linezip_ref.extractall(".")logger.info("模型文件解压完成!")except Exception as e:logger.error(f"解压失败: {e}")raise# 导入工具try:from model_utils import EnhancedGAT, smiles_to_graph, visualize_single_moleculelogger.info("导入 model_utils 成功")except ImportError as e:logger.error(f"导入 model_utils 失败: {e}")raisedevice = torch.device("cuda" if torch.cuda.is_available() else "cpu")logger.info(f"使用设备: {device}")if torch.cuda.is_available():logger.info(f"GPU: {torch.cuda.get_device_name(0)}")def load_models():model_info = {2 unmodified lines"Brittle": ("models/best_model-B-6000-185.pth", 2)}models = {}for name, (pth, od) in model_info.items():if not os.path.exists(pth):raise FileNotFoundError(f"{pth} 不存在")model = EnhancedGAT(input_dim=12, hidden_dim=512, output_dim=od, num_heads=8)# 加载state = torch.load(pth, 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} 模型加载完成")return modelsmodels = load_models()def predict_all(smiles):try:atom_features, (rows, cols, edge_attr), _ = smiles_to_graph(smiles)x = torch.tensor(atom_features, dtype=torch.float)edge_index = torch.tensor(np.column_stack((rows, cols)).T, dtype=torch.long)edge_attr = torch.tensor(edge_attr, dtype=torch.float).unsqueeze(1)2 unmodified linesedge_attr=edge_attr,smiles=[smiles],batch=torch.zeros(x.size(0), dtype=torch.long))out = []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)else:img = Image.new('RGB', (300,300), (255,255,255))text = f"{name} Result: {int(pred)}"out.extend([text, img])return tuple(out)except Exception as e:logger.error(f"预测失败: {e}")# 出错时统一返回提示和空图blank = Image.new('RGB', (300,300), (255,255,255))return ("Error", blank, "Error", blank, "Error", blank)# 分子构建相关ATOM_TYPES = ["C","N","O","S","P","F","Cl","Br","I","H"]BOND_TYPES = ["单键","双键","三键"]def init_molecule():return {"atoms": [], "bonds": []}def add_atom(mol, t):mol["atoms"].append({"id": len(mol["atoms"]), "type": t})return moldef add_bond(mol, a1, a2, b):if a1 < len(mol["atoms"]) and a2 < len(mol["atoms"]):if not any({bd["atom1"],bd["atom2"]}=={a1,a2} for bd in mol["bonds"]):mol["bonds"].append({"atom1":a1,"atom2":a2,"type":b})return moldef generate_smiles(mol):try:rw = Chem.RWMol()amap = {}for atom in mol["atoms"]:idx = rw.AddAtom(Chem.Atom(atom["type"]))amap[atom["id"]] = idxfor bd in mol["bonds"]:t = {"单键":Chem.BondType.SINGLE,"双键":Chem.BondType.DOUBLE,"三键":Chem.BondType.TRIPLE}[bd["type"]]rw.AddBond(amap[bd["atom1"]], amap[bd["atom2"]], t)rw.UpdatePropertyCache()Chem.SanitizeMol(rw)return Chem.MolToSmiles(rw)except Exception as e:logger.error(f"SMILES 生成失败: {e}")return ""def visualize_molecule_safe(mol):"""调用 visualize_molecule,出错时返回一张空白占位图"""try:# 复用上面 generate_smiles + RDKit 绘图逻辑smiles = generate_smiles(mol)m = MolFromSmiles(smiles)AllChem.Compute2DCoords(m)img = Draw.MolToImage(m, size=(300,300))buf = BytesIO()img.save(buf, format="PNG")buf.seek(0)return bufexcept Exception as e:logger.error(f"可视化失败: {e}")blank = Image.new('RGB',(300,300),(255,255,255))buf = BytesIO()blank.save(buf,'PNG')buf.seek(0)return bufdef update_atom_dropdowns(mol):ch = [f"{a['id']}: {a['type']}" for a in mol["atoms"]]return gr.update(choices=ch, value=None), gr.update(choices=ch, value=None)def update_atoms_list(mol):return [[a["id"],a["type"]] for a in mol["atoms"]]def update_bonds_list(mol):out = []for bd in mol["bonds"]:t1 = next(a["type"] for a in mol["atoms"] if a["id"]==bd["atom1"])t2 = next(a["type"] for a in mol["atoms"] if a["id"]==bd["atom2"])out.append([f"{bd['atom1']}: {t1}", f"{bd['atom2']}: {t2}", bd["type"]])return outwith gr.Blocks(title="CrystalGAT") as demo:gr.Markdown("# CrystalGAT")gr.Markdown("输入 SMILES 或 构建分子,预测弹性/塑性/脆性并可视化")# Tab1: SMILESwith gr.Tab("SMILES 输入"):smiles_in = gr.Textbox(label="SMILES", placeholder="如 CCO")btn1 = gr.Button("预测", variant="primary")# Tab2: 构建分子with gr.Tab("构建分子"):state = gr.State(init_molecule())status = gr.Textbox(label="状态", interactive=False, value="请添加原子开始")with gr.Row():atom_select = gr.Dropdown(ATOM_TYPES, label="原子类型", value="C")add_atom_btn = gr.Button("添加原子")atoms_df = gr.Dataframe(headers=["ID","类型"], datatype=["number","str"], interactive=False)with gr.Row():atom1_dd = gr.Dropdown([], label="第一个原子")atom2_dd = gr.Dropdown([], label="第二个原子")bond_dd = gr.Dropdown(BOND_TYPES, label="键类型", value="单键")add_bond_btn = gr.Button("添加键")bonds_df = gr.Dataframe(headers=["原子1","原子2","键"], datatype=["str","str","str"], interactive=False)clear_btn = gr.Button("清除所有")gen_btn = gr.Button("生成分子")smiles_out = gr.Textbox(label="生成 SMILES", interactive=False)img_out = gr.Image(label="分子预览")predict_btn2 = gr.Button("使用此分子预测", variant="primary")# 事件绑定add_atom_btn.click(fn=lambda t,m: add_atom(m,t),inputs=[atom_select, state],outputs=state) \.then(fn=update_atoms_list, inputs=state, outputs=atoms_df) \.then(fn=update_atom_dropdowns, inputs=state, outputs=[atom1_dd, atom2_dd]) \.then(fn=lambda: "原子添加成功", outputs=status)add_bond_btn.click(fn=lambda a1,a2,b,m: add_bond(m,int(a1.split(":")[0]) if a1 else -1,int(a2.split(":")[0]) if a2 else -1,b),inputs=[atom1_dd, atom2_dd, bond_dd, state],outputs=state) \.then(fn=update_bonds_list, inputs=state, outputs=bonds_df) \.then(fn=lambda: "键添加成功", outputs=status)clear_btn.click(fn=init_molecule, outputs=state) \.then(fn=lambda: ([],[]), outputs=[atoms_df, bonds_df]) \.then(fn=lambda: (gr.update(choices=[], value=None),gr.update(choices=[], value=None)),outputs=[atom1_dd, atom2_dd]) \.then(fn=lambda: "已清除所有", outputs=status)gen_btn.click(fn=lambda m: generate_smiles(m),inputs=state, outputs=smiles_out) \.then(fn=visualize_molecule_safe, inputs=state, outputs=img_out) \.then(fn=lambda: "分子生成完成", outputs=status)# 预测输出区with gr.Row():e_txt, e_img = gr.Text(label="Elastic"), gr.Image(type="pil", label="Elastic 可视化")with gr.Row():p_txt, p_img = gr.Text(label="Plastic"), gr.Image(type="pil", label="Plastic 可视化")with gr.Row():b_txt, b_img = gr.Text(label="Brittle"), gr.Image(type="pil", label="Brittle 可视化")btn1.click(fn=predict_all,inputs=smiles_in,outputs=[e_txt,e_img,p_txt,p_img,b_txt,b_img])predict_btn2.click(fn=lambda s: predict_all(s) if s else ("请先生成 SMILES",None,"","", "",""),inputs=smiles_out,outputs=[e_txt,e_img,p_txt,p_img,b_txt,b_img])if __name__ == "__main__":demo.launch(server_name="0.0.0.0", server_port=7860)
app.py+145-186