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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import spaces
|
| 2 |
+
import gradio as gr
|
| 3 |
+
from gradio_molecule3d import Molecule3D
|
| 4 |
+
import os
|
| 5 |
+
import numpy as np
|
| 6 |
+
import torch
|
| 7 |
+
from rdkit import Chem
|
| 8 |
+
import argparse
|
| 9 |
+
import random
|
| 10 |
+
from tqdm import tqdm
|
| 11 |
+
from vina import Vina
|
| 12 |
+
import esm
|
| 13 |
+
from utils.relax import openmm_relax, relax_sdf
|
| 14 |
+
from utils.protein_ligand import PDBProtein, parse_sdf_file
|
| 15 |
+
from utils.data import torchify_dict
|
| 16 |
+
from torch_geometric.transforms import Compose
|
| 17 |
+
from utils.datasets import *
|
| 18 |
+
from utils.transforms import *
|
| 19 |
+
from utils.misc import *
|
| 20 |
+
from utils.data import *
|
| 21 |
+
from torch.utils.data import DataLoader
|
| 22 |
+
from models.PD import Pocket_Design_new
|
| 23 |
+
from functools import partial
|
| 24 |
+
import pickle
|
| 25 |
+
import yaml
|
| 26 |
+
from easydict import EasyDict
|
| 27 |
+
import uuid
|
| 28 |
+
from datetime import datetime
|
| 29 |
+
import tempfile
|
| 30 |
+
import shutil
|
| 31 |
+
from Bio import PDB
|
| 32 |
+
from Bio.PDB import MMCIFParser, PDBIO
|
| 33 |
+
import logging
|
| 34 |
+
import zipfile
|
| 35 |
+
|
| 36 |
+
# 配置日志
|
| 37 |
+
logger = logging.getLogger(__name__)
|
| 38 |
+
LOG_FORMAT = "%(asctime)s,%(msecs)-3d %(levelname)-8s [%(filename)s:%(lineno)s %(funcName)s] %(message)s"
|
| 39 |
+
logging.basicConfig(
|
| 40 |
+
format=LOG_FORMAT,
|
| 41 |
+
level=logging.INFO,
|
| 42 |
+
datefmt="%Y-%m-%d %H:%M:%S",
|
| 43 |
+
filemode="w",
|
| 44 |
+
)
|
| 45 |
+
|
| 46 |
+
# 确保目录存在
|
| 47 |
+
os.makedirs("./generate/upload", exist_ok=True)
|
| 48 |
+
os.makedirs("./tmp", exist_ok=True)
|
| 49 |
+
|
| 50 |
+
# 自定义CSS样式
|
| 51 |
+
custom_css = """
|
| 52 |
+
.title {
|
| 53 |
+
font-size: 32px;
|
| 54 |
+
font-weight: bold;
|
| 55 |
+
color: #4CAF50;
|
| 56 |
+
display: flex;
|
| 57 |
+
align-items: center;
|
| 58 |
+
}
|
| 59 |
+
.subtitle {
|
| 60 |
+
font-size: 20px;
|
| 61 |
+
color: #666;
|
| 62 |
+
margin-bottom: 20px;
|
| 63 |
+
}
|
| 64 |
+
.footer {
|
| 65 |
+
margin-top: 20px;
|
| 66 |
+
text-align: center;
|
| 67 |
+
color: #666;
|
| 68 |
+
}
|
| 69 |
+
"""
|
| 70 |
+
|
| 71 |
+
# 3D显示表示设置 - 默认配置
|
| 72 |
+
default_reps = [
|
| 73 |
+
{
|
| 74 |
+
"model": 0,
|
| 75 |
+
"chain": "",
|
| 76 |
+
"resname": "",
|
| 77 |
+
"style": "cartoon",
|
| 78 |
+
"color": "whiteCarbon",
|
| 79 |
+
"residue_range": "",
|
| 80 |
+
"around": 0,
|
| 81 |
+
"byres": False,
|
| 82 |
+
"visible": True,
|
| 83 |
+
"opacity": 1.0
|
| 84 |
+
},
|
| 85 |
+
{
|
| 86 |
+
"model": 0,
|
| 87 |
+
"chain": "",
|
| 88 |
+
"resname": "",
|
| 89 |
+
"style": "stick",
|
| 90 |
+
"color": "greenCarbon",
|
| 91 |
+
"around": 5, # 显示配体周围5Å的残基
|
| 92 |
+
"byres": True,
|
| 93 |
+
"visible": True,
|
| 94 |
+
"opacity": 0.8
|
| 95 |
+
}
|
| 96 |
+
]
|
| 97 |
+
|
| 98 |
+
def create_zip_file(directory_path, zip_filename):
|
| 99 |
+
"""将指定目录压缩为zip文件"""
|
| 100 |
+
try:
|
| 101 |
+
with zipfile.ZipFile(zip_filename, 'w', zipfile.ZIP_DEFLATED) as zipf:
|
| 102 |
+
for root, dirs, files in os.walk(directory_path):
|
| 103 |
+
for file in files:
|
| 104 |
+
file_path = os.path.join(root, file)
|
| 105 |
+
arcname = os.path.relpath(file_path, directory_path)
|
| 106 |
+
zipf.write(file_path, arcname)
|
| 107 |
+
|
| 108 |
+
logger.info(f"成功创建压缩文件: {zip_filename}")
|
| 109 |
+
return zip_filename
|
| 110 |
+
except Exception as e:
|
| 111 |
+
logger.error(f"创建压缩文件时出错: {str(e)}")
|
| 112 |
+
return None
|
| 113 |
+
|
| 114 |
+
def load_config(config_path):
|
| 115 |
+
"""加载配置文件"""
|
| 116 |
+
with open(config_path, 'r') as f:
|
| 117 |
+
config_dict = yaml.load(f, Loader=yaml.FullLoader)
|
| 118 |
+
return EasyDict(config_dict)
|
| 119 |
+
|
| 120 |
+
# 删除了Vina相关的计算函数,因为只需要RMSD结果
|
| 121 |
+
|
| 122 |
+
def from_protein_ligand_dicts(protein_dict=None, ligand_dict=None, residue_dict=None, seq=None, full_seq_idx=None,
|
| 123 |
+
r10_idx=None):
|
| 124 |
+
"""从蛋白质和配体字典创建数据实例"""
|
| 125 |
+
instance = {}
|
| 126 |
+
|
| 127 |
+
if protein_dict is not None:
|
| 128 |
+
for key, item in protein_dict.items():
|
| 129 |
+
instance['protein_' + key] = item
|
| 130 |
+
|
| 131 |
+
if ligand_dict is not None:
|
| 132 |
+
for key, item in ligand_dict.items():
|
| 133 |
+
instance['ligand_' + key] = item
|
| 134 |
+
|
| 135 |
+
if residue_dict is not None:
|
| 136 |
+
for key, item in residue_dict.items():
|
| 137 |
+
instance[key] = item
|
| 138 |
+
|
| 139 |
+
if seq is not None:
|
| 140 |
+
instance['seq'] = seq
|
| 141 |
+
|
| 142 |
+
if full_seq_idx is not None:
|
| 143 |
+
instance['full_seq_idx'] = full_seq_idx
|
| 144 |
+
|
| 145 |
+
if r10_idx is not None:
|
| 146 |
+
instance['r10_idx'] = r10_idx
|
| 147 |
+
|
| 148 |
+
return instance
|
| 149 |
+
|
| 150 |
+
def ith_true_index(tensor, i):
|
| 151 |
+
"""找到张量中第i个为真的元素的索引"""
|
| 152 |
+
true_indices = torch.nonzero(tensor).squeeze()
|
| 153 |
+
return true_indices[i].item()
|
| 154 |
+
|
| 155 |
+
def name2data(pdb_path, lig_path):
|
| 156 |
+
"""从PDB和SDF文件生成数据"""
|
| 157 |
+
name = os.path.basename(pdb_path).split('.')[0]
|
| 158 |
+
dir_name = os.path.dirname(pdb_path)
|
| 159 |
+
pocket_path = os.path.join(dir_name, f"{name}_pocket.pdb")
|
| 160 |
+
|
| 161 |
+
try:
|
| 162 |
+
with open(pdb_path, 'r') as f:
|
| 163 |
+
pdb_block = f.read()
|
| 164 |
+
protein = PDBProtein(pdb_block)
|
| 165 |
+
seq = ''.join(protein.to_dict_residue()['seq'])
|
| 166 |
+
|
| 167 |
+
ligand = parse_sdf_file(lig_path, feat=False)
|
| 168 |
+
if ligand is None:
|
| 169 |
+
raise ValueError(f"无法从{lig_path}解析配体")
|
| 170 |
+
|
| 171 |
+
r10_idx, r10_residues = protein.query_residues_ligand(ligand, radius=10, selected_residue=None, return_mask=False)
|
| 172 |
+
full_seq_idx, _ = protein.query_residues_ligand(ligand, radius=3.5, selected_residue=r10_residues, return_mask=False)
|
| 173 |
+
|
| 174 |
+
if not r10_residues:
|
| 175 |
+
raise ValueError("在配体10Å范围内未找到任何残基")
|
| 176 |
+
|
| 177 |
+
assert len(r10_idx) == len(r10_residues)
|
| 178 |
+
|
| 179 |
+
pdb_block_pocket = protein.residues_to_pdb_block(r10_residues)
|
| 180 |
+
with open(pocket_path, 'w') as f:
|
| 181 |
+
f.write(pdb_block_pocket)
|
| 182 |
+
|
| 183 |
+
with open(pocket_path, 'r') as f:
|
| 184 |
+
pdb_block = f.read()
|
| 185 |
+
pocket = PDBProtein(pdb_block)
|
| 186 |
+
|
| 187 |
+
pocket_dict = pocket.to_dict_atom()
|
| 188 |
+
residue_dict = pocket.to_dict_residue()
|
| 189 |
+
|
| 190 |
+
_, residue_dict['protein_edit_residue'] = pocket.query_residues_ligand(ligand)
|
| 191 |
+
if residue_dict['protein_edit_residue'].sum() == 0:
|
| 192 |
+
raise ValueError("在口袋内未找到可编辑残基")
|
| 193 |
+
|
| 194 |
+
assert residue_dict['protein_edit_residue'].sum() > 0 and residue_dict['protein_edit_residue'].sum() == len(full_seq_idx)
|
| 195 |
+
assert len(residue_dict['protein_edit_residue']) == len(r10_idx)
|
| 196 |
+
full_seq_idx.sort()
|
| 197 |
+
r10_idx.sort()
|
| 198 |
+
|
| 199 |
+
data = from_protein_ligand_dicts(
|
| 200 |
+
protein_dict=torchify_dict(pocket_dict),
|
| 201 |
+
ligand_dict=torchify_dict(ligand),
|
| 202 |
+
residue_dict=torchify_dict(residue_dict),
|
| 203 |
+
seq=seq,
|
| 204 |
+
full_seq_idx=torch.tensor(full_seq_idx),
|
| 205 |
+
r10_idx=torch.tensor(r10_idx)
|
| 206 |
+
)
|
| 207 |
+
data['protein_filename'] = pocket_path
|
| 208 |
+
data['ligand_filename'] = lig_path
|
| 209 |
+
data['whole_protein_name'] = pdb_path
|
| 210 |
+
|
| 211 |
+
return transform(data)
|
| 212 |
+
|
| 213 |
+
except Exception as e:
|
| 214 |
+
logger.error(f"name2data中出错: {str(e)}")
|
| 215 |
+
raise
|
| 216 |
+
|
| 217 |
+
def convert_cif_to_pdb(cif_path):
|
| 218 |
+
"""将CIF文件转换为PDB文件并保存为临时文件"""
|
| 219 |
+
try:
|
| 220 |
+
parser = MMCIFParser()
|
| 221 |
+
structure = parser.get_structure("protein", cif_path)
|
| 222 |
+
|
| 223 |
+
with tempfile.NamedTemporaryFile(suffix=".pdb", delete=False) as temp_file:
|
| 224 |
+
temp_pdb_path = temp_file.name
|
| 225 |
+
|
| 226 |
+
io = PDBIO()
|
| 227 |
+
io.set_structure(structure)
|
| 228 |
+
io.save(temp_pdb_path)
|
| 229 |
+
|
| 230 |
+
return temp_pdb_path
|
| 231 |
+
|
| 232 |
+
except Exception as e:
|
| 233 |
+
logger.error(f"将CIF转换为PDB时出错: {str(e)}")
|
| 234 |
+
raise
|
| 235 |
+
|
| 236 |
+
def align_pdb_files(pdb_file_1, pdb_file_2):
|
| 237 |
+
"""将两个PDB文件对齐,将第二个结构对齐到第一个结构上"""
|
| 238 |
+
try:
|
| 239 |
+
parser = PDB.PPBuilder()
|
| 240 |
+
io = PDB.PDBIO()
|
| 241 |
+
structure_1 = PDB.PDBParser(QUIET=True).get_structure('Structure_1', pdb_file_1)
|
| 242 |
+
structure_2 = PDB.PDBParser(QUIET=True).get_structure('Structure_2', pdb_file_2)
|
| 243 |
+
|
| 244 |
+
super_imposer = PDB.Superimposer()
|
| 245 |
+
model_1 = structure_1[0]
|
| 246 |
+
model_2 = structure_2[0]
|
| 247 |
+
|
| 248 |
+
atoms_1 = [atom for atom in model_1.get_atoms() if atom.get_name() == "CA"]
|
| 249 |
+
atoms_2 = [atom for atom in model_2.get_atoms() if atom.get_name() == "CA"]
|
| 250 |
+
|
| 251 |
+
if not atoms_1 or not atoms_2:
|
| 252 |
+
logger.warning("未找到用于对齐的CA原子")
|
| 253 |
+
return
|
| 254 |
+
|
| 255 |
+
min_length = min(len(atoms_1), len(atoms_2))
|
| 256 |
+
if min_length == 0:
|
| 257 |
+
logger.warning("没有可用于对齐的原子")
|
| 258 |
+
return
|
| 259 |
+
|
| 260 |
+
super_imposer.set_atoms(atoms_1[:min_length], atoms_2[:min_length])
|
| 261 |
+
super_imposer.apply(model_2)
|
| 262 |
+
|
| 263 |
+
io.set_structure(structure_2)
|
| 264 |
+
io.save(pdb_file_2)
|
| 265 |
+
|
| 266 |
+
except Exception as e:
|
| 267 |
+
logger.error(f"对齐PDB文件时出错: {str(e)}")
|
| 268 |
+
raise
|
| 269 |
+
|
| 270 |
+
def create_combined_structure(protein_path, ligand_path, output_path):
|
| 271 |
+
"""将蛋白质和配体合并为一个PDB文件以便可视化"""
|
| 272 |
+
try:
|
| 273 |
+
# 读取蛋白质PDB文件
|
| 274 |
+
with open(protein_path, 'r') as f:
|
| 275 |
+
protein_content = f.read()
|
| 276 |
+
|
| 277 |
+
# 读取配体SDF文件并转换为PDB格式的字符串
|
| 278 |
+
mol = Chem.MolFromMolFile(ligand_path)
|
| 279 |
+
if mol is None:
|
| 280 |
+
logger.error(f"无法读取配体文件: {ligand_path}")
|
| 281 |
+
return protein_path
|
| 282 |
+
|
| 283 |
+
# 将配体转换为PDB格式
|
| 284 |
+
ligand_pdb_block = Chem.MolToPDBBlock(mol)
|
| 285 |
+
|
| 286 |
+
# 合并蛋白质和配体
|
| 287 |
+
combined_content = protein_content.rstrip() + "\n" + ligand_pdb_block
|
| 288 |
+
|
| 289 |
+
# 保存合并后的文件
|
| 290 |
+
with open(output_path, 'w') as f:
|
| 291 |
+
f.write(combined_content)
|
| 292 |
+
|
| 293 |
+
return output_path
|
| 294 |
+
|
| 295 |
+
except Exception as e:
|
| 296 |
+
logger.error(f"创建合并结构时出错: {str(e)}")
|
| 297 |
+
return protein_path # 如果失败,返回原始蛋白质文件
|
| 298 |
+
|
| 299 |
+
@spaces.GPU(duration=500)
|
| 300 |
+
def process_files(pdb_file, sdf_file, config_path):
|
| 301 |
+
"""处理上传的PDB和SDF文件"""
|
| 302 |
+
|
| 303 |
+
try:
|
| 304 |
+
unique_id = f"{datetime.now().strftime('%Y%m%d_%H%M%S')}_{uuid.uuid4().hex[:8]}"
|
| 305 |
+
upload_dir = os.path.join("./generate/upload", unique_id)
|
| 306 |
+
os.makedirs(upload_dir, exist_ok=True)
|
| 307 |
+
|
| 308 |
+
logger.info(f"使用ID处理文件: {unique_id}")
|
| 309 |
+
|
| 310 |
+
config = load_config(config_path)
|
| 311 |
+
|
| 312 |
+
pdb_save_path = os.path.join(upload_dir, "protein.pdb")
|
| 313 |
+
sdf_save_path = os.path.join(upload_dir, "ligand.sdf")
|
| 314 |
+
|
| 315 |
+
shutil.copy(pdb_file, pdb_save_path)
|
| 316 |
+
shutil.copy(sdf_file, sdf_save_path)
|
| 317 |
+
|
| 318 |
+
logger.info(f"文件已保存到 {upload_dir}")
|
| 319 |
+
|
| 320 |
+
device = "cuda:0" if torch.cuda.is_available() else "cpu"
|
| 321 |
+
logger.info(f"使用设备: {device}")
|
| 322 |
+
|
| 323 |
+
protein_featurizer = FeaturizeProteinAtom()
|
| 324 |
+
ligand_featurizer = FeaturizeLigandAtom()
|
| 325 |
+
global transform
|
| 326 |
+
transform = Compose([
|
| 327 |
+
protein_featurizer,
|
| 328 |
+
ligand_featurizer,
|
| 329 |
+
])
|
| 330 |
+
|
| 331 |
+
logger.info("加载ESM模型...")
|
| 332 |
+
name = 'esm2_t33_650M_UR50D'
|
| 333 |
+
pretrained_model, alphabet = esm.pretrained.load_model_and_alphabet_hub(name)
|
| 334 |
+
batch_converter = alphabet.get_batch_converter()
|
| 335 |
+
|
| 336 |
+
checkpoint_path = config.model.checkpoint
|
| 337 |
+
logger.info(f"从{checkpoint_path}加载检查点")
|
| 338 |
+
ckpt = torch.load(checkpoint_path, map_location=device, weights_only=False)
|
| 339 |
+
del pretrained_model
|
| 340 |
+
|
| 341 |
+
logger.info("初始化模型...")
|
| 342 |
+
model = Pocket_Design_new(
|
| 343 |
+
config.model,
|
| 344 |
+
protein_atom_feature_dim=protein_featurizer.feature_dim,
|
| 345 |
+
ligand_atom_feature_dim=ligand_featurizer.feature_dim,
|
| 346 |
+
device=device
|
| 347 |
+
).to(device)
|
| 348 |
+
model.load_state_dict(ckpt['model'])
|
| 349 |
+
|
| 350 |
+
logger.info("处理输入数据...")
|
| 351 |
+
data = name2data(pdb_save_path, sdf_save_path)
|
| 352 |
+
|
| 353 |
+
batch_size = 2
|
| 354 |
+
datalist = [data for _ in range(batch_size)]
|
| 355 |
+
protein_filename = data['protein_filename']
|
| 356 |
+
ligand_filename = data['ligand_filename']
|
| 357 |
+
whole_protein_name = data['whole_protein_name']
|
| 358 |
+
|
| 359 |
+
dir_name = os.path.dirname(protein_filename)
|
| 360 |
+
|
| 361 |
+
model.generate_id = 0
|
| 362 |
+
model.generate_id1 = 0
|
| 363 |
+
|
| 364 |
+
test_loader = DataLoader(
|
| 365 |
+
datalist,
|
| 366 |
+
batch_size=batch_size,
|
| 367 |
+
shuffle=False,
|
| 368 |
+
num_workers=0,
|
| 369 |
+
collate_fn=partial(collate_mols_block, batch_converter=batch_converter)
|
| 370 |
+
)
|
| 371 |
+
|
| 372 |
+
logger.info("生成结构...")
|
| 373 |
+
with torch.no_grad():
|
| 374 |
+
model.eval()
|
| 375 |
+
for batch in tqdm(test_loader, desc='Test'):
|
| 376 |
+
for key in batch:
|
| 377 |
+
if torch.is_tensor(batch[key]):
|
| 378 |
+
batch[key] = batch[key].to(device)
|
| 379 |
+
|
| 380 |
+
aar, rmsd, attend_logits = model.generate(batch, dir_name)
|
| 381 |
+
logger.info(f'RMSD: {rmsd}')
|
| 382 |
+
|
| 383 |
+
# 创建结果文件
|
| 384 |
+
result_path = os.path.join(dir_name, "0_whole.pdb")
|
| 385 |
+
relaxed_path = os.path.join(dir_name, "0_relaxed.pdb")
|
| 386 |
+
if os.path.exists(relaxed_path):
|
| 387 |
+
shutil.copy(relaxed_path, result_path)
|
| 388 |
+
else:
|
| 389 |
+
shutil.copy(pdb_save_path, result_path)
|
| 390 |
+
|
| 391 |
+
# 创建包含蛋白质和配体的合并文件用于可视化
|
| 392 |
+
combined_path = os.path.join(dir_name, "combined_structure.pdb")
|
| 393 |
+
visualization_path = create_combined_structure(result_path, sdf_save_path, combined_path)
|
| 394 |
+
|
| 395 |
+
# 创建压缩文件
|
| 396 |
+
zip_filename = os.path.join("./generate/upload", f"{unique_id}_results.zip")
|
| 397 |
+
zip_path = create_zip_file(upload_dir, zip_filename)
|
| 398 |
+
|
| 399 |
+
logger.info(f"结果已保存到 {result_path}")
|
| 400 |
+
logger.info(f"压缩文件已创建: {zip_path}")
|
| 401 |
+
|
| 402 |
+
summary = f"""
|
| 403 |
+
处理完成!
|
| 404 |
+
|
| 405 |
+
结果摘要:
|
| 406 |
+
- 均方根偏差 (RMSD): {rmsd}
|
| 407 |
+
|
| 408 |
+
文件说明:
|
| 409 |
+
- 所有结果文件已打包为ZIP文件供下载
|
| 410 |
+
- 包含原始输入、处理结果等
|
| 411 |
+
- 任务ID: {unique_id}
|
| 412 |
+
"""
|
| 413 |
+
|
| 414 |
+
return visualization_path, zip_path, summary
|
| 415 |
+
|
| 416 |
+
except Exception as e:
|
| 417 |
+
import traceback
|
| 418 |
+
error_trace = traceback.format_exc()
|
| 419 |
+
logger.error(f"处理过程中出错: {error_trace}")
|
| 420 |
+
return None, None, f"处理过程中出错: {str(e)}"
|
| 421 |
+
|
| 422 |
+
def gradio_interface(pdb_file, sdf_file, config_path):
|
| 423 |
+
"""Gradio接口函数"""
|
| 424 |
+
|
| 425 |
+
if pdb_file is None or sdf_file is None:
|
| 426 |
+
return None, None, "请上传PDB和SDF文件。"
|
| 427 |
+
|
| 428 |
+
logger.info(f"开始处理{pdb_file}和{sdf_file}")
|
| 429 |
+
pdb_viewer, zip_path, message = process_files(pdb_file, sdf_file, config_path)
|
| 430 |
+
|
| 431 |
+
if pdb_viewer and os.path.exists(pdb_viewer):
|
| 432 |
+
return pdb_viewer, zip_path, message
|
| 433 |
+
else:
|
| 434 |
+
return None, None, message if message else "处理失败,未知错误。"
|
| 435 |
+
|
| 436 |
+
# 创建Gradio接口
|
| 437 |
+
with gr.Blocks(title="蛋白质-配体处理", css=custom_css) as demo:
|
| 438 |
+
gr.Markdown("# 蛋白质-配体结构处理", elem_classes=["title"])
|
| 439 |
+
gr.Markdown("上传PDB和SDF文件进行蛋白质口袋设计和配体对接分析", elem_classes=["subtitle"])
|
| 440 |
+
|
| 441 |
+
with gr.Row():
|
| 442 |
+
with gr.Column(scale=1):
|
| 443 |
+
pdb_input = gr.File(label="上传PDB文件", file_types=[".pdb"])
|
| 444 |
+
sdf_input = gr.File(label="上传SDF文件", file_types=[".sdf"])
|
| 445 |
+
config_input = gr.Textbox(label="配置文件路径", value="./configs/train_model_moad.yml")
|
| 446 |
+
submit_btn = gr.Button("处理文件", variant="primary")
|
| 447 |
+
|
| 448 |
+
with gr.Column(scale=2):
|
| 449 |
+
# 使用Molecule3D组件,固定为默认样式
|
| 450 |
+
view3d = Molecule3D(
|
| 451 |
+
label="3D结构可视化 (蛋白质卡通 + 配体周围残基棒状)",
|
| 452 |
+
reps=default_reps
|
| 453 |
+
)
|
| 454 |
+
output_message = gr.Textbox(label="处理状态和结果摘要", lines=8)
|
| 455 |
+
output_file = gr.File(label="下载完整结果包 (ZIP)")
|
| 456 |
+
|
| 457 |
+
# 处理文件的点击事件
|
| 458 |
+
submit_btn.click(
|
| 459 |
+
fn=gradio_interface,
|
| 460 |
+
inputs=[pdb_input, sdf_input, config_input],
|
| 461 |
+
outputs=[view3d, output_file, output_message]
|
| 462 |
+
)
|
| 463 |
+
|
| 464 |
+
gr.Markdown("""
|
| 465 |
+
## 使用说明
|
| 466 |
+
|
| 467 |
+
1. **上传文件**: 上传蛋白质PDB文件和配体SDF文件
|
| 468 |
+
2. **配置设置**: 保持默认配置路径或调整为您的配置文件位置
|
| 469 |
+
3. **处理文件**: 点击"处理文件"按钮开始处理
|
| 470 |
+
4. **结果查看**:
|
| 471 |
+
- 在3D查看器中交互式查看优化后的蛋白质-配体复合物结构
|
| 472 |
+
- 查看详细的处理结果摘要
|
| 473 |
+
- 下载包含所有结果文件的ZIP压缩包
|
| 474 |
+
|
| 475 |
+
## 3D可视化功能
|
| 476 |
+
|
| 477 |
+
- **旋转**: 鼠标左键拖拽
|
| 478 |
+
- **缩放**: 鼠标滚轮或双指缩放
|
| 479 |
+
- **平移**: 鼠标右键拖拽
|
| 480 |
+
- **重置视图**: 双击重置到初始视角
|
| 481 |
+
|
| 482 |
+
可视化样式说明:
|
| 483 |
+
- 蛋白质以卡通形式显示(白色碳骨架)
|
| 484 |
+
- 配体周围5Å内的残基以棒状形式显示(绿色碳骨架)
|
| 485 |
+
|
| 486 |
+
## 下载文件说明
|
| 487 |
+
|
| 488 |
+
ZIP压缩包包含以下文件:
|
| 489 |
+
- **protein.pdb**: 原始输入蛋白质文件
|
| 490 |
+
- **ligand.sdf**: 原始输入配体文件
|
| 491 |
+
- **protein_pocket.pdb**: 提取的蛋白质口袋文件
|
| 492 |
+
- **0_whole.pdb**: 优化后的完整蛋白质结构
|
| 493 |
+
- **0_relaxed.pdb**: 松弛优化后的蛋白质结构
|
| 494 |
+
- **combined_structure.pdb**: 用于可视化的蛋白质-配体复合物
|
| 495 |
+
|
| 496 |
+
## 技术说明
|
| 497 |
+
|
| 498 |
+
该应用程序使用深度学习方法优化蛋白质口袋结构,提高与特定配体的结合能力。主要功能包括:
|
| 499 |
+
|
| 500 |
+
- **蛋白质口袋识别**: 自动识别并提取配体结合口袋
|
| 501 |
+
- **结构优化设计**: 使用AI模型优化口袋残基构象
|
| 502 |
+
- **分子对接评分**: 使用Vina进行结合能评估
|
| 503 |
+
- **交互式3D可视化**: 清晰展示蛋白质-配体相互作用
|
| 504 |
+
- **完整结果打包**: 所有中间和最终结果文件统一打包下载
|
| 505 |
+
|
| 506 |
+
处理可能需要几分钟时间,请耐心等待。
|
| 507 |
+
""")
|
| 508 |
+
|
| 509 |
+
gr.Markdown("© 2025 zaixi", elem_classes=["footer"])
|
| 510 |
+
|
| 511 |
+
if __name__ == "__main__":
|
| 512 |
+
demo.launch(share=True)
|