Spaces:
Running
Running
Update qsar_core_streamlit.py
Browse files1234567895 unmodified lines1516171819208 unmodified lines293031323334353637383940414243444546474849505111 unmodified lines63646566676869164 unmodified lines23423523623723823950 unmodified lines29029129229329429529629729829930030130230330430530630730830931031131213 unmodified lines32632732832933033115 unmodified lines3473483493503513527 unmodified lines36036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342419 unmodified lines4444454464474484498 unmodified lines45845946046146246340 unmodified lines5045055065075085091 unmodified line5115125135145155163 unmodified lines5205215225235245255261 unmodified line5285295305315325338 unmodified lines54254354454554654754854955055155226 unmodified lines57958058158258358458520 unmodified lines6066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736741 unmodified line67667767867968068168268368468568668768868969069169269369469569669769869970070170232 unmodified lines7357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957966 unmodified lines80380480580680780880912 unmodified lines82282382482582682782882983014 unmodified lines845846847848849850851852853854855856857858859860861862863import jsonimport mathimport reimport shutilimport subprocessimport tempfileimport zipfilefrom dataclasses import dataclassfrom pathlib import Path5 unmodified linesfrom rdkit.Chem import AllChem@dataclassclass AtomRecord:record: str8 unmodified linesline: strSUPPORTED_PROTEIN_EXTS = {".pdb", ".pdbqt"}SUPPORTED_LIGAND_EXTS = {".sdf", ".mol", ".mol2", ".pdb", ".pdbqt"}def ensure_command(cmd: str) -> bool:return shutil.which(cmd) is not Nonedef run_cmd(cmd: List[str], cwd: Optional[str] = None) -> subprocess.CompletedProcess:return subprocess.run(cmd, cwd=cwd, text=True, capture_output=True, check=False)def save_uploaded_file(uploaded_file, out_path: Path) -> Path:out_path.write_bytes(uploaded_file.getbuffer())return out_pathdef parse_pdb_like_atoms(file_path: Path) -> List[AtomRecord]:atoms: List[AtomRecord] = []with open(file_path, "r", errors="ignore") as f:11 unmodified linesy = float(line[38:46].strip())z = float(line[46:54].strip())atoms.append(AtomRecord(record, serial, atom_name, res_name, chain_id, res_seq, x, y, z, line))except Exception:continue164 unmodified linesfout.write("END\n")def infer_element_from_atom_name(atom_name: str) -> str:atom_name = (atom_name or "").strip()letters = "".join(ch for ch in atom_name if ch.isalpha())50 unmodified linesraise ValueError("No valid ATOM records remained after receptor cleaning.")def prepare_receptor_with_obabel(work_dir: Path, protein_file: Path) -> Tuple[Path, Path]:cleaned_pdb = work_dir / "receptor_cleaned_fallback.pdb"clean_receptor_pdb_for_meeko(protein_file, cleaned_pdb)out_pdbqt = work_dir / "receptor_fallback.pdbqt"result = run_cmd(["obabel", str(cleaned_pdb), "-O", str(out_pdbqt)],cwd=str(work_dir))if result.returncode != 0 or not out_pdbqt.exists():raise RuntimeError("Fallback receptor preparation with Open Babel failed.\n"f"STDOUT:\n{result.stdout}\nSTDERR:\n{result.stderr}")return out_pdbqt, cleaned_pdbdef ligand_mol_from_input(ligand_file: Optional[Path], smiles_text: str) -> Tuple[Chem.Mol, str]:13 unmodified linesassert ligand_file is not Nonesuffix = ligand_file.suffix.lower()if suffix == ".sdf":suppl = Chem.SDMolSupplier(str(ligand_file), removeHs=False)mol = next((m for m in suppl if m is not None), None)15 unmodified linesif status != 0:raise ValueError("Could not generate a 3D conformer for the ligand.")AllChem.UFFOptimizeMolecule(mol, maxIters=500)return mol, suffix.lstrip(".")7 unmodified linesif ligand_file is not None and ligand_file.suffix.lower() == ".pdbqt":dst = work_dir / "ligand_input.pdbqt"shutil.copy2(ligand_file, dst)return dstmol, _ = ligand_mol_from_input(ligand_file, smiles_text)sdf_path = work_dir / "ligand_prepared.sdf"write_ligand_sdf(mol, sdf_path)out_pdbqt = work_dir / "ligand.pdbqt"result = run_cmd(["obabel", str(sdf_path), "-O", str(out_pdbqt), "-xh"], cwd=str(work_dir))if result.returncode != 0 or not out_pdbqt.exists():raise RuntimeError(f"Ligand preparation failed.\nSTDOUT:\n{result.stdout}\nSTDERR:\n{result.stderr}")return out_pdbqtdef prepare_receptor_pdbqt(work_dir: Path,protein_file: Path,center: Tuple[float, float, float],size: Tuple[float, float, float],) -> Tuple[Path, Path]:protein_suffix = protein_file.suffix.lower()if protein_suffix == ".pdbqt":pdbqt_path = work_dir / "receptor.pdbqt"shutil.copy2(protein_file, pdbqt_path)return pdbqt_path, protein_fileif protein_suffix != ".pdb":raise ValueError("Protein must be PDB or PDBQT.")cleaned_pdb = work_dir / "receptor_cleaned.pdb"clean_receptor_pdb_for_meeko(protein_file, cleaned_pdb)if ensure_command("mk_prepare_receptor.py"):out_base = work_dir / "receptor"cmd = ["mk_prepare_receptor.py","--read_pdb", str(cleaned_pdb),"-o", str(out_base),"-p","--box_center", str(center[0]), str(center[1]), str(center[2]),"--box_size", str(size[0]), str(size[1]), str(size[2]),"--allow_bad_res",]result = run_cmd(cmd, cwd=str(work_dir))candidates = [work_dir / "receptor.pdbqt", work_dir / "receptor_rigid.pdbqt"]pdbqt_path = next((p for p in candidates if p.exists()), None)if pdbqt_path is None:generated = list(work_dir.glob("*.pdbqt"))pdbqt_path = generated[0] if generated else Noneif result.returncode == 0 and pdbqt_path is not None:return pdbqt_path, cleaned_pdbif ensure_command("obabel"):return prepare_receptor_with_obabel(work_dir, protein_file)raise RuntimeError("Receptor preparation failed with Meeko, and Open Babel fallback is unavailable.")VINA_TABLE_RE = re.compile(r"^\s*(\d+)\s+(-?\d+\.\d+)\s+([0-9.]+)\s+([0-9.]+)\s*$")19 unmodified lineslines = []in_first_model = Falsesaw_model = Falsewith open(pdbqt_path, "r", errors="ignore") as f:for line in f:if line.startswith("MODEL"):8 unmodified lineslines.append(line)else:lines.append(line)with open(out_path, "w") as out:out.writelines(lines)out.write("END\n")40 unmodified linesreturn pd.DataFrame(sorted(residues.values(), key=lambda x: x["min_distance_A"]))def make_zip(zip_path: Path, files: List[Path]) -> None:with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as zf:for fp in files:1 unmodified linezf.write(fp, arcname=fp.name)def run_docking(protein_file: Path,ligand_file: Optional[Path],3 unmodified linesexhaustiveness: int,num_modes: int,) -> Dict[str, Path]:with tempfile.TemporaryDirectory(prefix="dockapp_") as tmpdir:work_dir = Path(tmpdir)receptor_pdbqt, receptor_source = prepare_receptor_pdbqt(work_dir, protein_file, center, size)1 unmodified linedocked_pdbqt = work_dir / "docked_out.pdbqt"log_path = work_dir / "docking.log"cmd = ["vina","--receptor", str(receptor_pdbqt),8 unmodified lines"--num_modes", str(num_modes),"--out", str(docked_pdbqt),]result = run_cmd(cmd, cwd=str(work_dir))log_path.write_text((result.stdout or "") + "\n" + (result.stderr or ""))if result.returncode != 0 or not docked_pdbqt.exists():raise RuntimeError(f"Docking failed.\nSTDOUT:\n{result.stdout}\nSTDERR:\n{result.stderr}")scores_df = parse_vina_log(log_path)best_pose = work_dir / "best_pose_model1.pdbqt"26 unmodified lines}summary_json.write_text(json.dumps(payload, indent=2))export_dir = Path(tempfile.mkdtemp(prefix="dockapp_export_"))out_map = {"docked_pdbqt": export_dir / "docked_out.pdbqt","best_pose_pdbqt": export_dir / "best_pose_model1.pdbqt",20 unmodified linesreturn out_mapdef validate_extension(name: str, allowed: set[str], label: str) -> None:suffix = Path(name).suffix.lower()if suffix not in allowed:allowed_text = ", ".join(sorted(allowed))raise ValueError(f"{label} must be one of: {allowed_text}")def init_state() -> None:st.session_state.setdefault("run_outputs", None)def reset_all() -> None:for key in ["protein_uploader","ligand_uploader","smiles_text","residue_selection_text","run_outputs",]:if key in st.session_state:del st.session_state[key]st.rerun()def main() -> None:st.set_page_config(page_title="Protein-Ligand Docking Tool", layout="wide")init_state()st.title("Protein-Ligand Docking Tool")st.caption("Upload a protein and ligand, then run blind, residue-based, or manual docking.")with st.sidebar:st.header("Run settings")exhaustiveness = st.slider("Exhaustiveness", min_value=4, max_value=64, value=8, step=4)num_modes = st.slider("Number of poses", min_value=1, max_value=20, value=9, step=1)st.markdown("**Required container tools:** vina, obabel, mk_prepare_receptor.py")if st.button("Clear all inputs and results"):reset_all()missing_cmds = [cmd for cmd in ["vina", "obabel", "mk_prepare_receptor.py"] if not ensure_command(cmd)]if missing_cmds:st.warning("Missing container tools: " + ", ".join(missing_cmds) +". Upload may appear unstable until the Docker image is fixed.")st.subheader("Upload input files")protein_upload = st.file_uploader("Upload protein structure (PDB or PDBQT)",type=["pdb", "pdbqt"],accept_multiple_files=False,key="protein_uploader",help="Upload a receptor file in PDB or PDBQT format.",)ligand_upload = st.file_uploader("Upload ligand (SDF, MOL, MOL2, PDB, or PDBQT)",type=["sdf", "mol", "mol2", "pdb", "pdbqt"],accept_multiple_files=False,key="ligand_uploader",help="Upload a ligand file in SDF, MOL, MOL2, PDB, or PDBQT format.",)smiles_text = st.text_area("Or paste ligand SMILES",1 unmodified linekey="smiles_text",)if protein_upload is not None:try:validate_extension(protein_upload.name, SUPPORTED_PROTEIN_EXTS, "Protein file")st.success(f"Protein uploaded successfully: {protein_upload.name}")except Exception as e:st.error(str(e))else:st.info("No protein uploaded yet.")if ligand_upload is not None:try:validate_extension(ligand_upload.name, SUPPORTED_LIGAND_EXTS, "Ligand file")st.success(f"Ligand uploaded successfully: {ligand_upload.name}")except Exception as e:st.error(str(e))elif smiles_text.strip():st.success("Ligand SMILES provided.")else:st.info("No ligand uploaded yet.")st.subheader("Docking mode and box definition")docking_mode = st.radio("Choose docking mode",32 unmodified linessize_y = s2.number_input("Size Y", value=20.0, min_value=5.0, format="%.3f")size_z = s3.number_input("Size Z", value=20.0, min_value=5.0, format="%.3f")run_clicked = st.button("Run docking", type="primary", disabled=bool(missing_cmds))if run_clicked:try:if protein_upload is None:raise ValueError("Upload a protein file before running docking.")validate_extension(protein_upload.name, SUPPORTED_PROTEIN_EXTS, "Protein file")if ligand_upload is None and not smiles_text.strip():raise ValueError("Upload a ligand file or paste a SMILES string before running docking.")if ligand_upload is not None:validate_extension(ligand_upload.name, SUPPORTED_LIGAND_EXTS, "Ligand file")with st.spinner("Running docking..."):with tempfile.TemporaryDirectory(prefix="dock_ui_") as ui_tmp:tmpdir = Path(ui_tmp)protein_path = save_uploaded_file(protein_upload, tmpdir / protein_upload.name)ligand_path = Noneif ligand_upload is not None:ligand_path = save_uploaded_file(ligand_upload, tmpdir / ligand_upload.name)residue_match_df = Noneif docking_mode == "Blind docking":center, size = compute_blind_docking_box(protein_path,padding=padding,min_size=20.0,)elif docking_mode == "Residue-based docking":center, size, residue_match_df = compute_residue_based_box(protein_path,residue_selection_text=residue_selection_text,padding=padding,min_size=18.0,)else:center = (center_x, center_y, center_z)size = (size_x, size_y, size_z)outputs = run_docking(protein_file=protein_path,ligand_file=ligand_path,smiles_text=smiles_text,center=center,size=size,exhaustiveness=exhaustiveness,num_modes=num_modes,)st.session_state["run_outputs"] = {"files": {k: str(v) for k, v in outputs.items()},"center": center,"size": size,"mode": docking_mode,"matched_residues": residue_match_df.to_dict(orient="records") if residue_match_df is not None else None,}st.success("Docking completed successfully.")6 unmodified linesoutputs = {k: Path(v) for k, v in outputs_raw["files"].items()}center = tuple(outputs_raw["center"])size = tuple(outputs_raw["size"])docking_mode = outputs_raw["mode"]matched_residues = outputs_raw.get("matched_residues")scores_df = pd.read_csv(outputs["scores_csv"])12 unmodified linesst.metric("Center Z", center[2])st.metric("Size Z", size[2])st.info(f"Docking mode used: {docking_mode}")if docking_mode == "Residue-based docking" and matched_residues:st.subheader("Matched residues used to define the box")st.dataframe(pd.DataFrame(matched_residues), use_container_width=True)14 unmodified linesst.subheader("Downloads")with open(outputs["scores_csv"], "rb") as f:st.download_button("Download docking scores CSV", f.read(), file_name="docking_scores.csv", mime="text/csv")with open(outputs["residues_csv"], "rb") as f:st.download_button("Download active-site residues CSV", f.read(), file_name="active_site_residues.csv", mime="text/csv")with open(outputs["best_pose_pdbqt"], "rb") as f:st.download_button("Download best docked pose PDBQT", f.read(), file_name="best_pose_model1.pdbqt")if "active_site_pdb" in outputs and outputs["active_site_pdb"].exists():with open(outputs["active_site_pdb"], "rb") as f:st.download_button("Download active-site residues structure PDB", f.read(), file_name="active_site_residues.pdb")with open(outputs["zip"], "rb") as f:st.download_button("Download complete ZIP bundle", f.read(), file_name="docking_results_bundle.zip", mime="application/zip")except Exception as e:st.error(f"Saved results could not be displayed: {e}")if __name__ == "__main__":12345678910115 unmodified lines171819202122232425262728293031323334353637383940418 unmodified lines505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619711 unmodified lines209210211212213214215216217218219220221222223224225226164 unmodified lines39139239339439539639739839940050 unmodified lines45145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353413 unmodified lines54854955055155255355415 unmodified lines5705715725735745755767 unmodified lines58458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561619 unmodified lines6366376386396406416428 unmodified lines65165265365465565665740 unmodified lines6986997007017027037047057067071 unmodified line7097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437443 unmodified lines7487497507517527537541 unmodified line7567577587597607617628 unmodified lines77177277377477577677777877978078178278378478578678726 unmodified lines81481581681781881982082182220 unmodified lines8438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999001 unmodified line90290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296332 unmodified lines996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110526 unmodified lines105910601061106210631064106512 unmodified lines10781079108010811082108310841085108614 unmodified lines110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145import jsonimport mathimport osimport reimport shutilimport subprocessimport tempfileimport uuidimport zipfilefrom dataclasses import dataclassfrom pathlib import Path5 unmodified linesfrom rdkit.Chem import AllChem# ----------------------------# Constants and directories# ----------------------------SUPPORTED_PROTEIN_EXTS = {".pdb", ".pdbqt"}SUPPORTED_LIGAND_EXTS = {".sdf", ".mol", ".mol2", ".pdb", ".pdbqt"}APP_TMP_ROOT = Path("/tmp/docking_streamlit_app")UPLOAD_ROOT = APP_TMP_ROOT / "uploads"EXPORT_ROOT = APP_TMP_ROOT / "exports"UPLOAD_ROOT.mkdir(parents=True, exist_ok=True)EXPORT_ROOT.mkdir(parents=True, exist_ok=True)# ----------------------------# Data classes# ----------------------------@dataclassclass AtomRecord:record: str8 unmodified linesline: str# ----------------------------# Command helpers# ----------------------------def ensure_command(cmd: str) -> bool:return shutil.which(cmd) is not Nonedef run_cmd(cmd: List[str], cwd: Optional[str] = None) -> subprocess.CompletedProcess:return subprocess.run(cmd,cwd=cwd,text=True,capture_output=True,check=False,)# ----------------------------# Session helpers# ----------------------------def init_state() -> None:if "session_id" not in st.session_state:st.session_state["session_id"] = uuid.uuid4().hex[:12]if "run_outputs" not in st.session_state:st.session_state["run_outputs"] = Noneif "saved_protein_path" not in st.session_state:st.session_state["saved_protein_path"] = Noneif "saved_ligand_path" not in st.session_state:st.session_state["saved_ligand_path"] = Noneif "saved_protein_name" not in st.session_state:st.session_state["saved_protein_name"] = Noneif "saved_ligand_name" not in st.session_state:st.session_state["saved_ligand_name"] = Noneif "upload_notice" not in st.session_state:st.session_state["upload_notice"] = Nonedef get_session_dir() -> Path:session_dir = UPLOAD_ROOT / st.session_state["session_id"]session_dir.mkdir(parents=True, exist_ok=True)return session_dirdef get_export_dir() -> Path:export_dir = EXPORT_ROOT / st.session_state["session_id"]export_dir.mkdir(parents=True, exist_ok=True)return export_dirdef safe_filename(name: str) -> str:name = Path(name).namename = re.sub(r"[^A-Za-z0-9._-]+", "_", name)return name or "uploaded_file"def reset_all() -> None:session_dir = get_session_dir()export_dir = get_export_dir()shutil.rmtree(session_dir, ignore_errors=True)shutil.rmtree(export_dir, ignore_errors=True)for key in ["protein_uploader","ligand_uploader","smiles_text","residue_selection_text","run_outputs","saved_protein_path","saved_ligand_path","saved_protein_name","saved_ligand_name","upload_notice",]:if key in st.session_state:del st.session_state[key]st.rerun()# ----------------------------# Upload helpers# ----------------------------def file_size_mb(path: Path) -> float:return round(path.stat().st_size / (1024 * 1024), 3)def save_uploaded_file(uploaded_file, out_path: Path) -> Path:out_path.parent.mkdir(parents=True, exist_ok=True)uploaded_file.seek(0)with open(out_path, "wb") as fout:fout.write(uploaded_file.getbuffer())fout.flush()os.fsync(fout.fileno())return out_pathdef persist_uploads(protein_upload, ligand_upload) -> None:session_dir = get_session_dir()if protein_upload is not None:protein_name = safe_filename(protein_upload.name)protein_path = session_dir / f"protein_{protein_name}"save_uploaded_file(protein_upload, protein_path)st.session_state["saved_protein_path"] = str(protein_path)st.session_state["saved_protein_name"] = protein_upload.nameif ligand_upload is not None:ligand_name = safe_filename(ligand_upload.name)ligand_path = session_dir / f"ligand_{ligand_name}"save_uploaded_file(ligand_upload, ligand_path)st.session_state["saved_ligand_path"] = str(ligand_path)st.session_state["saved_ligand_name"] = ligand_upload.namedef get_saved_protein_path() -> Optional[Path]:p = st.session_state.get("saved_protein_path")if p and Path(p).exists():return Path(p)return Nonedef get_saved_ligand_path() -> Optional[Path]:p = st.session_state.get("saved_ligand_path")if p and Path(p).exists():return Path(p)return None# ----------------------------# PDB/PDBQT parsing helpers# ----------------------------def parse_pdb_like_atoms(file_path: Path) -> List[AtomRecord]:atoms: List[AtomRecord] = []with open(file_path, "r", errors="ignore") as f:11 unmodified linesy = float(line[38:46].strip())z = float(line[46:54].strip())atoms.append(AtomRecord(record=record,serial=serial,atom_name=atom_name,res_name=res_name,chain_id=chain_id,res_seq=res_seq,x=x,y=y,z=z,line=line,))except Exception:continue164 unmodified linesfout.write("END\n")# ----------------------------# Receptor preparation# ----------------------------def infer_element_from_atom_name(atom_name: str) -> str:atom_name = (atom_name or "").strip()letters = "".join(ch for ch in atom_name if ch.isalpha())50 unmodified linesraise ValueError("No valid ATOM records remained after receptor cleaning.")def validate_receptor_pdbqt(pdbqt_path: Path) -> None:bad_tags = ("ROOT", "BRANCH", "ENDBRANCH", "TORSDOF")text = pdbqt_path.read_text(errors="ignore")found = [tag for tag in bad_tags if tag in text]if found:raise RuntimeError(f"Invalid receptor PDBQT: found ligand-only tag(s): {', '.join(found)}")def prepare_receptor_pdbqt(work_dir: Path,protein_file: Path,center: Tuple[float, float, float],size: Tuple[float, float, float],) -> Tuple[Path, Path]:protein_suffix = protein_file.suffix.lower()if protein_suffix == ".pdbqt":pdbqt_path = work_dir / "receptor_input.pdbqt"shutil.copy2(protein_file, pdbqt_path)validate_receptor_pdbqt(pdbqt_path)return pdbqt_path, protein_fileif protein_suffix != ".pdb":raise ValueError("Protein must be PDB or PDBQT.")cleaned_pdb = work_dir / "receptor_cleaned.pdb"clean_receptor_pdb_for_meeko(protein_file, cleaned_pdb)if not ensure_command("mk_prepare_receptor.py"):raise RuntimeError("mk_prepare_receptor.py is required for receptor preparation but was not found. ""Please fix the Docker image instead of using Open Babel as a receptor fallback.")out_base = work_dir / "receptor"cmd = ["mk_prepare_receptor.py","--read_pdb", str(cleaned_pdb),"-o", str(out_base),"-p","--box_center", str(center[0]), str(center[1]), str(center[2]),"--box_size", str(size[0]), str(size[1]), str(size[2]),"--allow_bad_res",]result = run_cmd(cmd, cwd=str(work_dir))candidates = [work_dir / "receptor.pdbqt",work_dir / "receptor_rigid.pdbqt",work_dir / "receptor_rigid.pdbqt".replace(".pdbqt", "") if False else work_dir / "dummy"]real_candidates = [work_dir / "receptor.pdbqt", work_dir / "receptor_rigid.pdbqt"]pdbqt_path = next((p for p in real_candidates if p.exists()), None)if result.returncode != 0 or pdbqt_path is None:generated = [p.name for p in work_dir.glob("*.pdbqt")]raise RuntimeError("Receptor preparation with mk_prepare_receptor.py failed.\n"f"Generated PDBQT files: {generated}\n"f"STDOUT:\n{result.stdout}\n"f"STDERR:\n{result.stderr}")validate_receptor_pdbqt(pdbqt_path)return pdbqt_path, cleaned_pdb# ----------------------------# Ligand preparation# ----------------------------def validate_ligand_pdbqt(pdbqt_path: Path) -> None:text = pdbqt_path.read_text(errors="ignore")if "ROOT" not in text and "ATOM" not in text and "HETATM" not in text:raise RuntimeError("Ligand PDBQT appears to be invalid or empty.")def ligand_mol_from_input(ligand_file: Optional[Path], smiles_text: str) -> Tuple[Chem.Mol, str]:13 unmodified linesassert ligand_file is not Nonesuffix = ligand_file.suffix.lower()if suffix == ".sdf":suppl = Chem.SDMolSupplier(str(ligand_file), removeHs=False)mol = next((m for m in suppl if m is not None), None)15 unmodified linesif status != 0:raise ValueError("Could not generate a 3D conformer for the ligand.")AllChem.UFFOptimizeMolecule(mol, maxIters=500)return mol, suffix.lstrip(".")7 unmodified linesif ligand_file is not None and ligand_file.suffix.lower() == ".pdbqt":dst = work_dir / "ligand_input.pdbqt"shutil.copy2(ligand_file, dst)validate_ligand_pdbqt(dst)return dstif not ensure_command("obabel"):raise RuntimeError("obabel is required for ligand preparation but was not found.")mol, _ = ligand_mol_from_input(ligand_file, smiles_text)sdf_path = work_dir / "ligand_prepared.sdf"write_ligand_sdf(mol, sdf_path)out_pdbqt = work_dir / "ligand.pdbqt"result = run_cmd(["obabel", str(sdf_path), "-O", str(out_pdbqt), "-xh"], cwd=str(work_dir))if result.returncode != 0 or not out_pdbqt.exists():raise RuntimeError("Ligand preparation failed.\n"f"STDOUT:\n{result.stdout}\n"f"STDERR:\n{result.stderr}")validate_ligand_pdbqt(out_pdbqt)return out_pdbqt# ----------------------------# Docking result parsing# ----------------------------VINA_TABLE_RE = re.compile(r"^\s*(\d+)\s+(-?\d+\.\d+)\s+([0-9.]+)\s+([0-9.]+)\s*$")19 unmodified lineslines = []in_first_model = Falsesaw_model = Falsewith open(pdbqt_path, "r", errors="ignore") as f:for line in f:if line.startswith("MODEL"):8 unmodified lineslines.append(line)else:lines.append(line)with open(out_path, "w") as out:out.writelines(lines)out.write("END\n")40 unmodified linesreturn pd.DataFrame(sorted(residues.values(), key=lambda x: x["min_distance_A"]))# ----------------------------# Export helpers# ----------------------------def make_zip(zip_path: Path, files: List[Path]) -> None:with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as zf:for fp in files:1 unmodified linezf.write(fp, arcname=fp.name)# ----------------------------# Validation helpers# ----------------------------def validate_extension(name: str, allowed: set[str], label: str) -> None:suffix = Path(name).suffix.lower()if suffix not in allowed:allowed_text = ", ".join(sorted(allowed))raise ValueError(f"{label} must be one of: {allowed_text}")def validate_input_file_content(file_path: Path, label: str) -> None:if not file_path.exists():raise ValueError(f"{label} file was not saved correctly.")if file_path.stat().st_size == 0:raise ValueError(f"{label} file is empty.")suffix = file_path.suffix.lower()if suffix in {".pdb", ".pdbqt"}:text = file_path.read_text(errors="ignore")if "ATOM" not in text and "HETATM" not in text:raise ValueError(f"{label} file does not appear to contain valid atomic records.")# ----------------------------# Docking engine# ----------------------------def run_docking(protein_file: Path,ligand_file: Optional[Path],3 unmodified linesexhaustiveness: int,num_modes: int,) -> Dict[str, Path]:with tempfile.TemporaryDirectory(prefix="dockapp_job_") as tmpdir:work_dir = Path(tmpdir)receptor_pdbqt, receptor_source = prepare_receptor_pdbqt(work_dir, protein_file, center, size)1 unmodified linedocked_pdbqt = work_dir / "docked_out.pdbqt"log_path = work_dir / "docking.log"cmd = ["vina","--receptor", str(receptor_pdbqt),8 unmodified lines"--num_modes", str(num_modes),"--out", str(docked_pdbqt),]result = run_cmd(cmd, cwd=str(work_dir))log_path.write_text((result.stdout or "") + "\n" + (result.stderr or ""))if result.returncode != 0 or not docked_pdbqt.exists():raise RuntimeError("Docking failed.\n"f"Command: {' '.join(cmd)}\n"f"STDOUT:\n{result.stdout}\n"f"STDERR:\n{result.stderr}")scores_df = parse_vina_log(log_path)best_pose = work_dir / "best_pose_model1.pdbqt"26 unmodified lines}summary_json.write_text(json.dumps(payload, indent=2))export_dir = get_export_dir()export_dir.mkdir(parents=True, exist_ok=True)out_map = {"docked_pdbqt": export_dir / "docked_out.pdbqt","best_pose_pdbqt": export_dir / "best_pose_model1.pdbqt",20 unmodified linesreturn out_map# ----------------------------# UI# ----------------------------def main() -> None:st.set_page_config(page_title="Protein-Ligand Docking Tool", layout="wide")init_state()st.title("Protein-Ligand Docking Tool")st.caption("Upload a protein and ligand, save them to the session, then run blind, residue-based, or manual docking.")with st.sidebar:st.header("Run settings")exhaustiveness = st.slider("Exhaustiveness", min_value=4, max_value=64, value=8, step=4)num_modes = st.slider("Number of poses", min_value=1, max_value=20, value=9, step=1)st.markdown("**Required tools**")st.markdown("- vina")st.markdown("- obabel")st.markdown("- mk_prepare_receptor.py")if st.button("Clear all inputs and results"):reset_all()missing_cmds = [cmd for cmd in ["vina", "obabel", "mk_prepare_receptor.py"] if not ensure_command(cmd)]if missing_cmds:st.warning("Missing container tools: " + ", ".join(missing_cmds) + ". ""Docking will fail until the Docker image is fixed.")st.subheader("Step 1: Upload input files")col1, col2 = st.columns(2)with col1:protein_upload = st.file_uploader("Upload protein structure (PDB or PDBQT)",type=["pdb", "pdbqt"],accept_multiple_files=False,key="protein_uploader",help="Upload a receptor file in PDB or PDBQT format.",)with col2:ligand_upload = st.file_uploader("Upload ligand (SDF, MOL, MOL2, PDB, or PDBQT)",type=["sdf", "mol", "mol2", "pdb", "pdbqt"],accept_multiple_files=False,key="ligand_uploader",help="Upload a ligand file in SDF, MOL, MOL2, PDB, or PDBQT format.",)smiles_text = st.text_area("Or paste ligand SMILES",1 unmodified linekey="smiles_text",)save_uploads_clicked = st.button("Save uploaded files", type="secondary")if save_uploads_clicked:try:if protein_upload is None:raise ValueError("Upload a protein file before saving.")validate_extension(protein_upload.name, SUPPORTED_PROTEIN_EXTS, "Protein file")if ligand_upload is None and not smiles_text.strip():raise ValueError("Upload a ligand file or provide a SMILES string before saving.")if ligand_upload is not None:validate_extension(ligand_upload.name, SUPPORTED_LIGAND_EXTS, "Ligand file")persist_uploads(protein_upload, ligand_upload)protein_path = get_saved_protein_path()ligand_path = get_saved_ligand_path()if protein_path is not None:validate_input_file_content(protein_path, "Protein")if ligand_path is not None:validate_input_file_content(ligand_path, "Ligand")st.session_state["upload_notice"] = "Files saved successfully for this session."st.success(st.session_state["upload_notice"])except Exception as e:st.error(str(e))protein_path = get_saved_protein_path()ligand_path = get_saved_ligand_path()st.subheader("Saved session files")left, right = st.columns(2)with left:if protein_path is not None:st.success(f"Protein ready: {st.session_state.get('saved_protein_name', protein_path.name)} "f"({file_size_mb(protein_path)} MB)")else:st.info("No saved protein yet.")with right:if ligand_path is not None:st.success(f"Ligand ready: {st.session_state.get('saved_ligand_name', ligand_path.name)} "f"({file_size_mb(ligand_path)} MB)")elif smiles_text.strip():st.success("SMILES input ready.")else:st.info("No saved ligand yet.")st.subheader("Step 2: Docking mode and box definition")docking_mode = st.radio("Choose docking mode",32 unmodified linessize_y = s2.number_input("Size Y", value=20.0, min_value=5.0, format="%.3f")size_z = s3.number_input("Size Z", value=20.0, min_value=5.0, format="%.3f")run_disabled = bool(missing_cmds) or (protein_path is None) or ((ligand_path is None) and (not smiles_text.strip()))run_clicked = st.button("Run docking", type="primary", disabled=run_disabled)if run_clicked:try:if protein_path is None:raise ValueError("Save a protein file before running docking.")if ligand_path is None and not smiles_text.strip():raise ValueError("Save a ligand file or provide a SMILES string before running docking.")validate_input_file_content(protein_path, "Protein")if ligand_path is not None:validate_input_file_content(ligand_path, "Ligand")residue_match_df = Noneif docking_mode == "Blind docking":center, size = compute_blind_docking_box(protein_path,padding=padding,min_size=20.0,)elif docking_mode == "Residue-based docking":center, size, residue_match_df = compute_residue_based_box(protein_path,residue_selection_text=residue_selection_text,padding=padding,min_size=18.0,)else:center = (center_x, center_y, center_z)size = (size_x, size_y, size_z)with st.spinner("Running docking..."):outputs = run_docking(protein_file=protein_path,ligand_file=ligand_path,smiles_text=smiles_text,center=center,size=size,exhaustiveness=exhaustiveness,num_modes=num_modes,)st.session_state["run_outputs"] = {"files": {k: str(v) for k, v in outputs.items()},"center": center,"size": size,"mode": docking_mode,"matched_residues": residue_match_df.to_dict(orient="records") if residue_match_df is not None else None,}st.success("Docking completed successfully.")6 unmodified linesoutputs = {k: Path(v) for k, v in outputs_raw["files"].items()}center = tuple(outputs_raw["center"])size = tuple(outputs_raw["size"])docking_mode_used = outputs_raw["mode"]matched_residues = outputs_raw.get("matched_residues")scores_df = pd.read_csv(outputs["scores_csv"])12 unmodified linesst.metric("Center Z", center[2])st.metric("Size Z", size[2])st.info(f"Docking mode used: {docking_mode_used}")if docking_mode_used == "Residue-based docking" and matched_residues:st.subheader("Matched residues used to define the box")st.dataframe(pd.DataFrame(matched_residues), use_container_width=True)14 unmodified linesst.subheader("Downloads")with open(outputs["scores_csv"], "rb") as f:st.download_button("Download docking scores CSV",f.read(),file_name="docking_scores.csv",mime="text/csv",)with open(outputs["residues_csv"], "rb") as f:st.download_button("Download active-site residues CSV",f.read(),file_name="active_site_residues.csv",mime="text/csv",)with open(outputs["best_pose_pdbqt"], "rb") as f:st.download_button("Download best docked pose PDBQT",f.read(),file_name="best_pose_model1.pdbqt",)if "active_site_pdb" in outputs and outputs["active_site_pdb"].exists():with open(outputs["active_site_pdb"], "rb") as f:st.download_button("Download active-site residues structure PDB",f.read(),file_name="active_site_residues.pdb",)with open(outputs["zip"], "rb") as f:st.download_button("Download complete results ZIP",f.read(),file_name="docking_results_bundle.zip",mime="application/zip",)with st.expander("Show docking log"):st.code(outputs["log_txt"].read_text(errors="ignore"), language="text")except Exception as e:st.error(f"Could not display stored results: {e}")if __name__ == "__main__":
qsar_core_streamlit.py+466-184