""" common.py Shared helper functions used across Woloji Genomic Suite v1.0 tools. Kept framework agnostic so it can be imported without Streamlit side effects. """ import re import shutil import subprocess import zipfile from pathlib import Path from typing import Iterable, Optional def safe_filename(name: str) -> str: """Turn a user supplied filename into a filesystem safe stem.""" base = Path(name).stem cleaned = re.sub(r"[^A-Za-z0-9._-]+", "_", base.strip()) return cleaned or "output" def ensure_directories(paths: Iterable[Path]) -> None: for path in paths: Path(path).mkdir(parents=True, exist_ok=True) def run_command(cmd, cwd: Optional[Path] = None, stdin_text: Optional[str] = None): """Run a subprocess command as a list, never as a shell string. Returns a dict with returncode, stdout, stderr, and the joined command for logging. Never raises, so callers can decide how to report failure. """ try: result = subprocess.run( cmd, cwd=cwd, input=stdin_text, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, check=False, ) return { "cmd": " ".join(map(str, cmd)), "returncode": result.returncode, "stdout": result.stdout, "stderr": result.stderr, } except FileNotFoundError as exc: return { "cmd": " ".join(map(str, cmd)), "returncode": 127, "stdout": "", "stderr": f"Executable not found: {exc}", } except Exception as exc: return { "cmd": " ".join(map(str, cmd)), "returncode": 1, "stdout": "", "stderr": str(exc), } def which_first(names) -> Optional[str]: for n in names: path = shutil.which(n) if path: return path return None def zip_directory(folder_path: Path, zip_path: Path) -> Path: with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as zf: for file in Path(folder_path).rglob("*"): if file.is_file(): zf.write(file, arcname=file.relative_to(folder_path)) return zip_path def dataframe_to_csv_bytes(df) -> bytes: return df.to_csv(index=False).encode("utf-8") def dataframe_to_excel_bytes(df) -> bytes: import io import pandas as pd # noqa: F401 (kept local so common.py has no hard pandas dependency at import time) output = io.BytesIO() with pd.ExcelWriter(output, engine="openpyxl") as writer: df.to_excel(writer, sheet_name="Results", index=False) return output.getvalue()