Spaces:
Build error
Build error
Delete app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991"""WOLOJI Bacterial Genomics Suite (trimmed build)Single-file build merged from the woloji/ package + app.py.
Removed from this build (covered by separate dedicated tools): - Genome annotation (Bakta / Prokka) - Genome composition & codon usage (RSCU / ENc) - AMR detection (AMRFinderPlus) - Virulence screening (ABRicate / VFDB) - Secondary metabolites (antiSMASH)Also removed because they depend entirely on the annotation step above: - Functional annotation (eggNOG-mapper) -- needs the .faa file from annotation - Pan-genome analysis (Panaroo) -- needs the GFF files from annotation
Remaining pipeline: read QC, assembly/polishing, QUAST, CheckM2, taxonomy(GTDB-Tk, Mash, skani), mobileome (MOB-suite, geNomad, IntegronFinder, MinCED),MLST, cgMLST/wgMLST, core SNP phylogenomics, population genomics (PopPUNK),plus the standalone utilities tab (primer design, local BLAST, PhyloForge)."""from __future__ import annotations
import gzipimport hashlibimport jsonimport mathimport osimport reimport shutilimport subprocessimport tempfileimport zipfilefrom collections.abc import Callable, Sequencefrom dataclasses import asdict, dataclassfrom datetime import UTC, datetimefrom pathlib import Path
import matplotlibimport pandas as pdimport streamlit as stfrom Bio import SeqIO
matplotlib.use("Agg")import matplotlib.pyplot as plt
__version__ = "2.0.1"
# =============================================================================# woloji/models.py -- data model# =============================================================================@dataclassclass Sample: sample_id: str read1: Path | None = None read2: Path | None = None long_reads: Path | None = None assembly: Path | None = None genus: str = "" species: str = ""
@property def has_short_reads(self) -> bool: return self.read1 is not None
@property def has_paired_reads(self) -> bool: return self.read1 is not None and self.read2 is not None
@property def has_long_reads(self) -> bool: return self.long_reads is not None
# =============================================================================# woloji/utils.py -- filesystem, hashing, command execution helpers# =============================================================================def utc_now() -> str: return datetime.now(UTC).isoformat()
def safe_name(value: str) -> str: value = re.sub(r"[^A-Za-z0-9._-]+", "_", str(value)).strip("._") return value or "sample"
def sha256_file(path: Path, block: int = 1024 * 1024) -> str: h = hashlib.sha256() with open(path, "rb") as fh: while True: chunk = fh.read(block) if not chunk: break h.update(chunk) return h.hexdigest()
def command_exists(name: str) -> bool: return shutil.which(name) is not None
def get_version(command: Sequence[str]) -> str: try: cp = subprocess.run(command, capture_output=True, text=True, timeout=20, check=False) text = (cp.stdout or cp.stderr or "").strip().splitlines() return text[0][:300] if text else "unknown" except Exception as exc: return f"unavailable: {exc}"
def open_text(path: Path): if str(path).lower().endswith(".gz"): return gzip.open(path, "rt", encoding="utf-8", errors="ignore") return open(path, "rt", encoding="utf-8", errors="ignore")
def fasta_stats(path: Path) -> dict: lengths = [] a = c = g = t = n = 0 seq_len = 0 with open_text(path) as fh: cur = 0 for raw in fh: line = raw.strip() if not line: continue if line.startswith(">"): if cur: lengths.append(cur) cur = 0 continue s = line.upper() cur += len(s) a += s.count("A") c += s.count("C") g += s.count("G") t += s.count("T") n += len(s) - sum(s.count(x) for x in "ACGT") if cur: lengths.append(cur) seq_len = sum(lengths) canonical = a + c + g + t gc = 100.0 * (g + c) / canonical if canonical else float("nan") n_pct = 100.0 * n / seq_len if seq_len else float("nan") ordered = sorted(lengths, reverse=True) target = seq_len / 2.0 cum = 0 n50 = l50 = 0 for i, length in enumerate(ordered, start=1): cum += length if cum >= target: n50, l50 = length, i break return { "assembly": path.name, "total_length_bp": int(seq_len), "contigs": len(lengths), "largest_contig_bp": int(max(lengths) if lengths else 0), "N50_bp": int(n50), "L50": int(l50), "GC_percent": round(gc, 5) if not math.isnan(gc) else None, "ambiguous_percent": round(n_pct, 5) if not math.isnan(n_pct) else None, "A": a, "C": c, "G": g, "T": t, "ambiguous_bases": n, }
@dataclassclass CmdResult: name: str command: list[str] returncode: int started_at: str finished_at: str stdout_path: str stderr_path: str skipped: bool = False reason: str = ""
def to_dict(self): return asdict(self)
class Runner: def __init__(self, log_dir: Path, dry_run: bool = False, timeout: int = 14400): self.log_dir = Path(log_dir) self.log_dir.mkdir(parents=True, exist_ok=True) self.dry_run = dry_run self.timeout = timeout self.records: list[CmdResult] = []
def skip(self, name: str, command: Sequence[str], reason: str) -> CmdResult: now = utc_now() rec = CmdResult(name, list(map(str, command)), 0, now, now, "", "", True, reason) self.records.append(rec) return rec
def run(self, name: str, command: Sequence[str], cwd: Path | None = None, stdout_file: Path | None = None, env: dict | None = None, check: bool = False) -> CmdResult: command = [str(x) for x in command] exe = command[0] if not command_exists(exe): return self.skip(name, command, f"Executable not found on PATH: {exe}") started = utc_now() out_path = self.log_dir / f"{safe_name(name)}.stdout.txt" err_path = self.log_dir / f"{safe_name(name)}.stderr.txt" if self.dry_run: rec = CmdResult(name, command, 0, started, utc_now(), str(out_path), str(err_path), True, "dry run") self.records.append(rec) return rec proc_env = os.environ.copy() if env: proc_env.update({k: str(v) for k, v in env.items()}) with open(out_path, "w", encoding="utf-8") as out, open(err_path, "w", encoding="utf-8") as err: if stdout_file: stdout_file.parent.mkdir(parents=True, exist_ok=True) with open(stdout_file, "w", encoding="utf-8") as redirected: cp = subprocess.run(command, cwd=cwd, stdout=redirected, stderr=err, text=True, timeout=self.timeout, env=proc_env, check=False) else: cp = subprocess.run(command, cwd=cwd, stdout=out, stderr=err, text=True, timeout=self.timeout, env=proc_env, check=False) rec = CmdResult(name, command, int(cp.returncode), started, utc_now(), str(out_path), str(err_path)) self.records.append(rec) if check and cp.returncode != 0: raise RuntimeError(f"{name} failed. See {err_path}") return rec
def write_manifest(self, path: Path): path.write_text(json.dumps([r.to_dict() for r in self.records], indent=2), encoding="utf-8")
# =============================================================================# woloji/io.py -- sample discovery from uploads / metadata# =============================================================================FASTA_EXT = (".fa", ".fasta", ".fna", ".fas", ".fa.gz", ".fasta.gz", ".fna.gz")FASTQ_EXT = (".fastq", ".fq", ".fastq.gz", ".fq.gz")
def save_uploads(uploaded_files, input_dir: Path) -> dict[str, Path]: input_dir.mkdir(parents=True, exist_ok=True) mapping = {} for uploaded in uploaded_files or []: name = os.path.basename(uploaded.name) target = input_dir / name target.write_bytes(uploaded.getvalue()) mapping[name] = target if name.lower().endswith(".zip"): with zipfile.ZipFile(target) as zf: for info in zf.infolist(): if info.is_dir(): continue base = os.path.basename(info.filename) if not base: continue out = input_dir / base out.write_bytes(zf.read(info.filename)) mapping[base] = out return mapping
def _find_name(mapping: dict[str, Path], value: str | float | None): if value is None or (isinstance(value, float) and pd.isna(value)): return None value = str(value).strip() if not value: return None base = os.path.basename(value) return mapping.get(value) or mapping.get(base)
def samples_from_metadata(metadata_path: Path, mapping: dict[str, Path]) -> list[Sample]: df = pd.read_csv(metadata_path, sep=None, engine="python") required = {"Sample_ID"} if not required.issubset(df.columns): raise ValueError("Metadata must contain Sample_ID. Optional columns: Read_1, Read_2, Long_Reads, Assembly, Genus, Species") samples = [] for _, row in df.iterrows(): sid = safe_name(row["Sample_ID"]) samples.append(Sample( sample_id=sid, read1=_find_name(mapping, row.get("Read_1")), read2=_find_name(mapping, row.get("Read_2")), long_reads=_find_name(mapping, row.get("Long_Reads")), assembly=_find_name(mapping, row.get("Assembly")), genus=str(row.get("Genus", "") or ""), species=str(row.get("Species", "") or ""), )) return samples
def _stem_without_ext(name: str) -> str: x = name for ext in [".fastq.gz", ".fq.gz", ".fasta.gz", ".fna.gz", ".fa.gz", ".fastq", ".fq", ".fasta", ".fna", ".fa", ".fas"]: if x.lower().endswith(ext): return x[:-len(ext)] return Path(x).stem
def auto_samples(mapping: dict[str, Path]) -> list[Sample]: fastqs = {n: p for n, p in mapping.items() if n.lower().endswith(FASTQ_EXT)} fastas = {n: p for n, p in mapping.items() if n.lower().endswith(FASTA_EXT)} samples: dict[str, Sample] = {} used = set() patterns = [ (re.compile(r"(.+?)(?:_R?1)(?:_\d+)?$", re.IGNORECASE), "r1"), (re.compile(r"(.+?)(?:_R?2)(?:_\d+)?$", re.IGNORECASE), "r2"), ] for name, path in fastqs.items(): stem = _stem_without_ext(name) matched = False for pat, side in patterns: m = pat.match(stem) if m: sid = safe_name(m.group(1)) s = samples.setdefault(sid, Sample(sample_id=sid)) if side == "r1": s.read1 = path else: s.read2 = path used.add(name); matched = True; break if not matched: sid = safe_name(stem) s = samples.setdefault(sid, Sample(sample_id=sid)) # Unpaired FASTQ is interpreted as long-read input. s.long_reads = path used.add(name) for name, path in fastas.items(): sid = safe_name(_stem_without_ext(name)) samples.setdefault(sid, Sample(sample_id=sid)).assembly = path return sorted(samples.values(), key=lambda s: s.sample_id)
# =============================================================================# woloji/tooling.py -- external tool + database status# =============================================================================TOOLS = { "fastp": ["fastp", "--version"], "FastQC": ["fastqc", "--version"], "MultiQC": ["multiqc", "--version"], "SPAdes": ["spades.py", "--version"], "Flye": ["flye", "--version"], "Unicycler": ["unicycler", "--version"], "Polypolish": ["polypolish", "--version"], "QUAST": ["quast.py", "--version"], "CheckM2": ["checkm2", "--version"], "GTDB-Tk": ["gtdbtk", "--version"], "Mash": ["mash", "--version"], "skani": ["skani", "--version"], "MOB-suite": ["mob_recon", "--version"], "geNomad": ["genomad", "--version"], "IntegronFinder": ["integron_finder", "--version"], "MinCED": ["minced", "--version"], "mlst": ["mlst", "--version"], "chewBBACA": ["chewBBACA.py", "--version"], "Snippy": ["snippy", "--version"], "Gubbins": ["run_gubbins.py", "--version"], "MAFFT": ["mafft", "--version"], "IQ-TREE": ["iqtree2", "--version"], "PopPUNK": ["poppunk", "--version"], "BLAST+": ["blastn", "-version"], "Primer3": ["primer3_core", "--version"],}
DATABASES = { "GTDB-Tk": "GTDBTK_DATA_PATH", "CheckM2": "CHECKM2DB", "geNomad": "GENOMAD_DB", "MOB-suite": "MOB_SUITE_DB",}
def status_rows(): rows = [] for display, cmd in TOOLS.items(): exe = cmd[0] rows.append({ "tool": display, "executable": exe, "available": command_exists(exe), "version": get_version(cmd) if command_exists(exe) else "not installed", }) return rows
def database_rows(): rows = [] for name, envvar in DATABASES.items(): value = os.getenv(envvar, "") exists = bool(value) and Path(value).exists() rows.append({"database": name, "environment_variable": envvar, "path": value, "detected": exists}) return rows
# =============================================================================# woloji/figures.py -- publication figures# =============================================================================matplotlib.use("Agg")import matplotlib.pyplot as plt
def assembly_summary_plot(df: pd.DataFrame, out: Path): if df.empty: return fig, ax = plt.subplots(figsize=(8, 4.8)) x = range(len(df)) ax.bar(x, df["N50_bp"].astype(float)) ax.set_xticks(list(x)) ax.set_xticklabels(df["sample"], rotation=45, ha="right") ax.set_ylabel("N50 (bp)") ax.set_title("Assembly contiguity across isolates") fig.tight_layout() fig.savefig(out, dpi=600, bbox_inches="tight") plt.close(fig)
def gc_plot(df: pd.DataFrame, out: Path): if df.empty: return fig, ax = plt.subplots(figsize=(8, 4.8)) x = range(len(df)) ax.scatter(x, df["GC_percent"].astype(float), s=42) ax.set_xticks(list(x)) ax.set_xticklabels(df["sample"], rotation=45, ha="right") ax.set_ylabel("GC (%)") ax.set_title("Genome GC content") fig.tight_layout() fig.savefig(out, dpi=600, bbox_inches="tight") plt.close(fig)
# =============================================================================# woloji/utilities.py -- primer design, local BLAST, PhyloForge# =============================================================================def fasta_first_sequence(file_bytes: bytes, name: str = "input.fasta") -> tuple[str,str]: with tempfile.TemporaryDirectory() as td: p=Path(td)/name;p.write_bytes(file_bytes) rec=next(SeqIO.parse(str(p),"fasta")) return rec.id, str(rec.seq).upper()
def design_primers(sequence: str, target_start: int = 0, target_length: int = 0, product_min: int = 100, product_max: int = 600, num_return: int = 5): import primer3 seq=sequence.upper().replace(" ","").replace("\n","") args={"SEQUENCE_ID":"target","SEQUENCE_TEMPLATE":seq} if target_length>0: args["SEQUENCE_TARGET"]=[int(target_start),int(target_length)] global_args={ "PRIMER_OPT_SIZE":20,"PRIMER_MIN_SIZE":18,"PRIMER_MAX_SIZE":25, "PRIMER_OPT_TM":60.0,"PRIMER_MIN_TM":57.0,"PRIMER_MAX_TM":63.0, "PRIMER_MIN_GC":35.0,"PRIMER_MAX_GC":65.0, "PRIMER_PRODUCT_SIZE_RANGE":[[int(product_min),int(product_max)]], "PRIMER_NUM_RETURN":int(num_return), } res=primer3.bindings.design_primers(args,global_args) rows=[] for i in range(int(res.get("PRIMER_PAIR_NUM_RETURNED",0))): rows.append({ "pair":i+1, "left_primer":res.get(f"PRIMER_LEFT_{i}_SEQUENCE",""), "right_primer":res.get(f"PRIMER_RIGHT_{i}_SEQUENCE",""), "left_tm":res.get(f"PRIMER_LEFT_{i}_TM"), "right_tm":res.get(f"PRIMER_RIGHT_{i}_TM"), "left_gc":res.get(f"PRIMER_LEFT_{i}_GC_PERCENT"), "right_gc":res.get(f"PRIMER_RIGHT_{i}_GC_PERCENT"), "product_size":res.get(f"PRIMER_PAIR_{i}_PRODUCT_SIZE"), "pair_penalty":res.get(f"PRIMER_PAIR_{i}_PENALTY"), }) return pd.DataFrame(rows)
def local_blast(query_bytes: bytes, subject_bytes: bytes, task: str = "blastn", evalue: float = 1e-10, threads: int = 2): with tempfile.TemporaryDirectory() as td: td=Path(td);q=td/"query.fasta";s=td/"subject.fasta";q.write_bytes(query_bytes);s.write_bytes(subject_bytes) runner=Runner(td/"logs") runner.run("makeblastdb",["makeblastdb","-in",s,"-dbtype","nucl","-out",td/"db"],check=True) out=td/"blast.tsv" fields="qseqid sseqid pident length mismatch gapopen qstart qend sstart send evalue bitscore qcovs" runner.run("blastn",["blastn","-task",task,"-query",q,"-db",td/"db","-evalue",evalue,"-num_threads",threads,"-outfmt",f"6 {fields}","-out",out],check=True) cols=fields.split() return pd.read_csv(out,sep="\t",names=cols) if out.exists() and out.stat().st_size else pd.DataFrame(columns=cols)
def phyloforge(files, threads: int = 2, model: str = "MFP", bootstrap: int = 1000): with tempfile.TemporaryDirectory() as td: td=Path(td);inp=td/"input.fasta" with open(inp,"wb") as out: for f in files: out.write(f.getvalue());out.write(b"\n") runner=Runner(td/"logs") aln=td/"aligned.fasta" runner.run("mafft",["mafft","--auto","--thread",threads,inp],stdout_file=aln,check=True) prefix=td/"tree" runner.run("iqtree",["iqtree2","-s",aln,"-m",model,"-B",bootstrap,"-T",threads,"--prefix",prefix],check=True) tree=Path(str(prefix)+".treefile") return aln.read_text() if aln.exists() else "", tree.read_text() if tree.exists() else ""
# =============================================================================# woloji/pipeline.py -- end-to-end analysis pipeline# =============================================================================DEFAULTS = { "threads": 4, "memory_gb": 12, "fastp_quality": 20, "fastp_length": 50, "fastp_n_limit": 5, "assembly_mode": "Auto", "iqtree_model": "MFP", "iqtree_bootstrap": 1000, "dry_run": False,}
def _emit(cb: Callable[[str], None] | None, text: str): if cb: cb(text)
def _copy_or_link(src: Path, dst: Path): dst.parent.mkdir(parents=True, exist_ok=True) if dst.exists() or dst.is_symlink(): dst.unlink() try: dst.symlink_to(src.resolve()) except Exception: shutil.copy2(src, dst)
def _run_fastp(sample: Sample, out: Path, runner: Runner, p: dict): if not sample.read1: return None, None qc = out / "01_read_qc" / sample.sample_id qc.mkdir(parents=True, exist_ok=True) r1 = qc / f"{sample.sample_id}.clean_R1.fastq.gz" r2 = qc / f"{sample.sample_id}.clean_R2.fastq.gz" if sample.read2 else None cmd = ["fastp", "-i", sample.read1, "-o", r1, "--qualified_quality_phred", p["fastp_quality"], "--length_required", p["fastp_length"], "--n_base_limit", p["fastp_n_limit"], "--thread", p["threads"], "--json", qc / "fastp.json", "--html", qc / "fastp.html"] if sample.read2: cmd += ["-I", sample.read2, "-O", r2, "--detect_adapter_for_pe"] result = runner.run(f"{sample.sample_id}_fastp", cmd) if result.skipped or result.returncode != 0: return sample.read1, sample.read2 reads = [x for x in [r1, r2] if x] if command_exists("fastqc") and not runner.dry_run: runner.run(f"{sample.sample_id}_fastqc", ["fastqc", "-t", p["threads"], "-o", qc, *reads]) return r1, r2
def _polypolish(sample_id: str, draft: Path, r1: Path, r2: Path, out: Path, runner: Runner, threads: int): pol = out / "03_polishing" / sample_id pol.mkdir(parents=True, exist_ok=True) draft_copy = pol / "draft.fasta" shutil.copy2(draft, draft_copy) runner.run(f"{sample_id}_bwa_index", ["bwa", "index", draft_copy]) a1 = pol / "alignments_1.sam"; a2 = pol / "alignments_2.sam" runner.run(f"{sample_id}_bwa_r1", ["bwa", "mem", "-t", threads, "-a", draft_copy, r1], stdout_file=a1) runner.run(f"{sample_id}_bwa_r2", ["bwa", "mem", "-t", threads, "-a", draft_copy, r2], stdout_file=a2) f1 = pol / "filtered_1.sam"; f2 = pol / "filtered_2.sam" runner.run(f"{sample_id}_polypolish_filter", ["polypolish", "filter", "--in1", a1, "--in2", a2, "--out1", f1, "--out2", f2]) polished = pol / "polished.fasta" runner.run(f"{sample_id}_polypolish", ["polypolish", "polish", draft_copy, f1, f2], stdout_file=polished) return polished
def _assemble(sample: Sample, r1: Path | None, r2: Path | None, out: Path, runner: Runner, p: dict): if sample.assembly: return sample.assembly asm_root = out / "02_assembly" / sample.sample_id asm_root.mkdir(parents=True, exist_ok=True) threads = p["threads"] mem = p["memory_gb"] mode = p["assembly_mode"] if sample.long_reads and r1 and r2 and mode in {"Auto", "Hybrid: Unicycler"}: runner.run(f"{sample.sample_id}_unicycler", ["unicycler", "-1", r1, "-2", r2, "-l", sample.long_reads, "-o", asm_root, "-t", threads]) return asm_root / "assembly.fasta" if sample.long_reads: runner.run(f"{sample.sample_id}_flye", ["flye", "--nano-hq", sample.long_reads, "--out-dir", asm_root, "--threads", threads, "--genome-size", "5m"]) draft = asm_root / "assembly.fasta" if r1 and r2 and command_exists("polypolish") and command_exists("bwa"): return _polypolish(sample.sample_id, draft, r1, r2, out, runner, threads) return draft if r1: cmd = ["spades.py", "--isolate", "-1", r1, "-2", r2, "-o", asm_root, "-t", threads, "-m", mem] if r2 else \ ["spades.py", "--isolate", "-s", r1, "-o", asm_root, "-t", threads, "-m", mem] runner.run(f"{sample.sample_id}_spades", cmd) return asm_root / "contigs.fasta" return None
def _quast(sample_id, assembly, out, runner, threads): qout = out / "04_assembly_qc" / "quast" / sample_id runner.run(f"{sample_id}_quast", ["quast.py", assembly, "-o", qout, "-t", threads])
def _checkm2(sample_id, assembly, out, runner, threads): db = os.getenv("CHECKM2DB", "") qout = out / "04_assembly_qc" / "checkm2" / sample_id indir = qout / "input"; indir.mkdir(parents=True, exist_ok=True) _copy_or_link(assembly, indir / f"{sample_id}.fasta") cmd = ["checkm2", "predict", "--threads", threads, "--input", indir, "--output-directory", qout / "results", "--extension", "fasta"] if db: cmd += ["--database_path", db] runner.run(f"{sample_id}_checkm2", cmd)
def _mobileome(sample_id, assembly, out, runner, threads): root = out / "12_mobileome" / sample_id; root.mkdir(parents=True, exist_ok=True) mob_db = os.getenv("MOB_SUITE_DB", "") cmd = ["mob_recon", "--infile", assembly, "--outdir", root/"mob_suite", "--num_threads", threads] if mob_db: cmd += ["--database_directory", mob_db] runner.run(f"{sample_id}_mob_recon", cmd) gdb = os.getenv("GENOMAD_DB", "") if gdb and Path(gdb).exists(): runner.run(f"{sample_id}_genomad", ["genomad", "end-to-end", "--cleanup", "--splits", threads, assembly, root/"genomad", gdb]) else: runner.skip(f"{sample_id}_genomad", ["genomad", "end-to-end", assembly, root/"genomad", "$GENOMAD_DB"], "GENOMAD_DB is not configured") runner.run(f"{sample_id}_integronfinder", ["integron_finder", "--local-max", "--cpu", min(int(threads), 4), "--outdir", root/"integrons", assembly]) runner.run(f"{sample_id}_minced", ["minced", assembly, root/"crispr.txt", root/"crispr.gff"])
def _mlst(sample_id, assembly, out, runner): root = out / "13_typing" / "mlst"; root.mkdir(parents=True, exist_ok=True) runner.run(f"{sample_id}_mlst", ["mlst", "--full", assembly], stdout_file=root/f"{sample_id}.tsv")
def _gtdbtk(assemblies: dict[str, Path], out: Path, runner: Runner, threads: int): if not assemblies: return root = out / "05_taxonomy" / "gtdbtk"; inp = root / "input"; inp.mkdir(parents=True, exist_ok=True) for sid, asm in assemblies.items(): _copy_or_link(asm, inp/f"{sid}.fasta") db = os.getenv("GTDBTK_DATA_PATH", "") if not db or not Path(db).exists(): runner.skip("gtdbtk_classify", ["gtdbtk", "classify_wf", "--genome_dir", inp, "--out_dir", root/"results"], "GTDBTK_DATA_PATH is not configured") return runner.run("gtdbtk_classify", ["gtdbtk", "classify_wf", "--genome_dir", inp, "--out_dir", root/"results", "--extension", "fasta", "--cpus", threads])
def _mash_skani(assemblies: dict[str, Path], out: Path, runner: Runner, threads: int): if len(assemblies) < 2: return root = out / "05_taxonomy" / "comparative"; root.mkdir(parents=True, exist_ok=True) paths = list(assemblies.values()) runner.run("mash_sketch", ["mash", "sketch", "-o", root/"genomes", *paths]) runner.run("mash_dist", ["mash", "dist", root/"genomes.msh", root/"genomes.msh"], stdout_file=root/"mash_dist.tsv") runner.run("skani_triangle", ["skani", "triangle", "-s", "90", "-t", threads, "-E", *paths], stdout_file=root/"skani_triangle.tsv")
def _chewbbaca(assemblies: dict[str, Path], schema_dir: Path | None, out: Path, runner: Runner, threads: int): if len(assemblies) < 2 or not schema_dir: runner.skip("chewbbaca", ["chewBBACA.py", "AlleleCall"], "cgMLST/wgMLST requires at least two genomes and a schema directory") return root = out / "13_typing" / "chewbbaca"; inp = root/"genomes"; inp.mkdir(parents=True, exist_ok=True) for sid, asm in assemblies.items(): _copy_or_link(asm, inp/f"{sid}.fasta") runner.run("chewbbaca_allelecall", ["chewBBACA.py", "AlleleCall", "-i", inp, "-g", schema_dir, "-o", root/"allelecall", "--cpu", threads])
def _phylogenomics(samples: list[Sample], assemblies: dict[str, Path], reference: Path | None, out: Path, runner: Runner, p: dict): if len(assemblies) < 2 or reference is None: runner.skip("core_snp_phylogeny", ["snippy"], "Core SNP analysis requires at least two samples and a reference genome") return root = out / "16_phylogenomics"; snippy_dirs = [] for s in samples: asm = assemblies.get(s.sample_id) if asm is None: continue od = root/"snippy"/s.sample_id; snippy_dirs.append(od) if s.read1: cmd = ["snippy", "--cpus", p["threads"], "--outdir", od, "--ref", reference, "--R1", s.read1] if s.read2: cmd += ["--R2", s.read2] else: cmd = ["snippy", "--cpus", p["threads"], "--outdir", od, "--ref", reference, "--ctgs", asm] runner.run(f"{s.sample_id}_snippy", cmd) if len(snippy_dirs) < 2: return core = root/"core"; core.mkdir(parents=True, exist_ok=True) runner.run("snippy_core", ["snippy-core", "--ref", reference, "--prefix", core/"core", *snippy_dirs]) aln = core/"core.full.aln" gub = root/"gubbins"; gub.mkdir(parents=True, exist_ok=True) runner.run("gubbins", ["run_gubbins.py", "--prefix", gub/"gubbins", "--threads", p["threads"], aln]) filt = gub/"gubbins.filtered_polymorphic_sites.fasta" iq_input = filt if filt.exists() else aln iqdir = root/"iqtree"; iqdir.mkdir(parents=True, exist_ok=True) runner.run("iqtree", ["iqtree2", "-s", iq_input, "-m", p["iqtree_model"], "-B", p["iqtree_bootstrap"], "-T", p["threads"], "--prefix", iqdir/"tree"])
def _poppunk(assemblies: dict[str, Path], out: Path, runner: Runner, threads: int): if len(assemblies) < 3: runner.skip("poppunk", ["poppunk", "--create-db"], "PopPUNK model fitting is most useful with at least three genomes") return root = out / "17_population" / "poppunk"; root.mkdir(parents=True, exist_ok=True) rlist = root/"rlist.txt" rlist.write_text("\n".join(f"{sid}\t{path}" for sid, path in assemblies.items()) + "\n") runner.run("poppunk_create_db", ["poppunk", "--create-db", "--output", root/"database", "--r-files", rlist, "--threads", threads]) runner.run("poppunk_fit", ["poppunk", "--fit-model", "bgmm", "--K", "2", "--ref-db", root/"database", "--output", root/"database", "--threads", threads])
def _publication_report(run_dir: Path, samples: list[Sample], assemblies: dict[str, Path], runner: Runner, params: dict): tables = run_dir/"20_publication_report"/"tables"; figs = run_dir/"20_publication_report"/"figures" tables.mkdir(parents=True, exist_ok=True); figs.mkdir(parents=True, exist_ok=True) rows = [] for sid, asm in assemblies.items(): if asm.exists(): d = fasta_stats(asm); d["sample"] = sid; rows.append(d) df = pd.DataFrame(rows) if not df.empty: df.to_csv(tables/"assembly_summary.csv", index=False) assembly_summary_plot(df, figs/"assembly_n50.png") gc_plot(df, figs/"genome_gc.png") methods = [ "WOLOJI Comprehensive Bacterial Genomics Suite v2.0.1 was used to coordinate the selected bacterial whole-genome analyses.", "The exact commands, software availability, parameters, input checksums, and database paths are recorded in the run manifest and command manifest.", "Predicted AMR, virulence, mobile genetic elements, secondary metabolite clusters, taxonomic assignments, and epidemiological clusters should be interpreted in the context of genome quality and the relevant reference database version.", ] (run_dir/"20_publication_report"/"methods_note.txt").write_text("\n\n".join(methods)+"\n") summary = { "samples": len(samples), "assemblies_available": len(assemblies), "commands_total": len(runner.records), "commands_skipped": sum(r.skipped for r in runner.records), "commands_failed": sum((not r.skipped and r.returncode != 0) for r in runner.records), } (run_dir/"20_publication_report"/"run_summary.json").write_text(json.dumps(summary, indent=2))
def _zip_run(run_dir: Path) -> Path: target = run_dir.parent / f"{run_dir.name}.zip" with zipfile.ZipFile(target, "w", zipfile.ZIP_DEFLATED) as zf: for path in run_dir.rglob("*"): if path.is_file(): zf.write(path, path.relative_to(run_dir)) return target
def run_pipeline(samples: list[Sample], run_dir: Path, modules: dict, params: dict, reference: Path | None = None, schema_dir: Path | None = None, progress_cb: Callable[[str], None] | None = None): p = DEFAULTS.copy(); p.update(params or {}) run_dir.mkdir(parents=True, exist_ok=True) runner = Runner(run_dir/"logs", dry_run=bool(p.get("dry_run")), timeout=int(p.get("timeout", 14400))) assemblies: dict[str, Path] = {} input_manifest = [] for s in samples: for label, path in [("Read_1", s.read1), ("Read_2", s.read2), ("Long_Reads", s.long_reads), ("Assembly", s.assembly)]: if path and Path(path).exists(): input_manifest.append({"sample": s.sample_id, "type": label, "file": str(path), "sha256": sha256_file(Path(path))}) pd.DataFrame(input_manifest).to_csv(run_dir/"input_manifest.tsv", sep="\t", index=False)
for i, sample in enumerate(samples, start=1): _emit(progress_cb, f"[{i}/{len(samples)}] {sample.sample_id}: preparing reads and assembly") r1, r2 = sample.read1, sample.read2 if modules.get("read_qc", True) and sample.read1: r1, r2 = _run_fastp(sample, run_dir, runner, p) asm = _assemble(sample, r1, r2, run_dir, runner, p) if modules.get("assembly", True) else sample.assembly if asm: asm = Path(asm) if not runner.dry_run and not asm.exists(): runner.skip(f"{sample.sample_id}_downstream", [str(asm)], "Assembly was not produced; downstream modules skipped for this sample") continue assemblies[sample.sample_id] = asm if modules.get("quast", True): _quast(sample.sample_id, asm, run_dir, runner, p["threads"]) if modules.get("checkm2", False): _checkm2(sample.sample_id, asm, run_dir, runner, p["threads"]) if modules.get("mobileome", True): _mobileome(sample.sample_id, asm, run_dir, runner, p["threads"]) if modules.get("mlst", True): _mlst(sample.sample_id, asm, run_dir, runner)
if command_exists("multiqc") and modules.get("read_qc", True): runner.run("multiqc", ["multiqc", run_dir/"01_read_qc", "-o", run_dir/"01_read_qc"/"multiqc"]) if modules.get("taxonomy", True): _gtdbtk(assemblies, run_dir, runner, p["threads"]) _mash_skani(assemblies, run_dir, runner, p["threads"]) if modules.get("cgmlst", False): _chewbbaca(assemblies, schema_dir, run_dir, runner, p["threads"]) if modules.get("phylogenomics", False): _phylogenomics(samples, assemblies, reference, run_dir, runner, p) if modules.get("population", False): _poppunk(assemblies, run_dir, runner, p["threads"])
_publication_report(run_dir, samples, assemblies, runner, p) runner.write_manifest(run_dir/"command_manifest.json") run_manifest = { "suite": "WOLOJI Comprehensive Bacterial Genomics Suite", "version": "2.0.1", "created_at": utc_now(), "parameters": p, "modules": modules, "database_paths": {k: os.getenv(k, "") for k in ["GTDBTK_DATA_PATH","CHECKM2DB","GENOMAD_DB","MOB_SUITE_DB"]}, "samples": [s.sample_id for s in samples], "software_versions": status_rows(), } (run_dir/"run_manifest.json").write_text(json.dumps(run_manifest, indent=2)) zip_path = _zip_run(run_dir) return zip_path, run_manifest, runner.records
# =============================================================================# app.py -- Streamlit interface# =============================================================================st.set_page_config(page_title="WOLOJI Comprehensive Bacterial Genomics Suite", page_icon="🧬", layout="wide")
st.title("🧬 WOLOJI Comprehensive Bacterial Genomics Suite")st.caption(f"Version {__version__} | Raw reads to publication-ready bacterial whole-genome analysis")
with st.expander("Scope and interpretation", expanded=False): st.write( "WOLOJI is designed for bacterial isolate whole-genome analysis. It coordinates read quality control, assembly, " "assembly quality, taxonomy, mobile genetic elements, sequence typing, SNP phylogenomics, population genomics, " "and reproducibility reporting. Genome annotation, codon usage analysis, AMR detection, virulence screening, " "and secondary metabolite prediction are handled by separate dedicated tools and are out of scope here. " "Database-dependent modules run only when the corresponding database path is configured. Prediction-based outputs do not " "replace phenotypic or experimental validation." )
run_tab, utilities_tab, status_tab, help_tab = st.tabs(["Run complete analysis", "Woloji sequence utilities", "Tools & databases", "Deployment guide"])
with st.sidebar: st.header("Workflow modules") read_qc = st.checkbox("1. Raw read QC", True) assembly = st.checkbox("2. Genome assembly / polishing", True) quast = st.checkbox("3. QUAST assembly QC", True) checkm2 = st.checkbox("4. CheckM2 completeness", False) taxonomy = st.checkbox("5. Taxonomy + ANI", True) mobileome = st.checkbox("6. Mobileome / plasmids / prophages / CRISPR", True) mlst = st.checkbox("7. Classical MLST", True) cgmlst = st.checkbox("8. cgMLST / wgMLST", False) phylogenomics = st.checkbox("9. Core SNP phylogenomics", False) population = st.checkbox("10. Population genomics", False)
st.header("Core parameters") threads = st.slider("CPU threads", 1, max(1, os.cpu_count() or 2), min(4, max(1, os.cpu_count() or 2))) memory_gb = st.number_input("Assembly memory limit (GB)", 2, 256, 12, 1) assembly_mode = st.selectbox("Assembly strategy", ["Auto", "Hybrid: Unicycler", "Long-read: Flye", "Short-read: SPAdes"]) fastp_quality = st.slider("fastp minimum Phred", 10, 35, 20) fastp_length = st.number_input("fastp minimum read length", 20, 300, 50, 5) fastp_n_limit = st.number_input("fastp maximum N bases per read", 0, 50, 5, 1, help="fastp --n_base_limit is an absolute count, not a percentage.") dry_run = st.checkbox("Dry run: generate commands without executing", False)
with run_tab: st.subheader("1. Upload data") files = st.file_uploader( "Upload FASTQ/FASTQ.GZ, FASTA/FASTA.GZ, or a ZIP containing them", accept_multiple_files=True, type=["fastq","fq","gz","fa","fasta","fna","fas","zip"], ) meta = st.file_uploader("Optional metadata CSV/TSV", type=["csv","tsv","txt"], key="meta") st.caption("Recommended metadata columns: Sample_ID, Read_1, Read_2, Long_Reads, Assembly, Genus, Species") reference = st.file_uploader("Optional reference genome for core SNP analysis", type=["fa","fasta","fna","gbk","gbff"], key="ref") schema_zip = st.file_uploader("Optional chewBBACA cgMLST/wgMLST schema ZIP", type=["zip"], key="schema")
run_name = st.text_input("Run name", value=f"woloji_{datetime.now(UTC).strftime('%Y%m%d_%H%M%S')}") run = st.button("Run WOLOJI analysis", type="primary", use_container_width=True)
if run: if not files: st.error("Upload at least one sequencing or assembly file.") else: work_root = Path(tempfile.gettempdir()) / "woloji_runs" work_root.mkdir(parents=True, exist_ok=True) run_dir = work_root / safe_name(run_name) if run_dir.exists(): shutil.rmtree(run_dir) input_dir = run_dir / "00_input"; input_dir.mkdir(parents=True, exist_ok=True) mapping = save_uploads(files, input_dir) metadata_path = None if meta: metadata_path = input_dir / os.path.basename(meta.name) metadata_path.write_bytes(meta.getvalue()) try: samples = samples_from_metadata(metadata_path, mapping) if metadata_path else auto_samples(mapping) except Exception as exc: st.error(f"Input parsing failed: {exc}") samples = [] if not samples: st.error("No valid samples were detected. Use metadata if automatic filename pairing is ambiguous.") else: ref_path = None if reference: ref_path = input_dir / os.path.basename(reference.name) ref_path.write_bytes(reference.getvalue()) schema_dir = None if schema_zip: schema_file = input_dir / os.path.basename(schema_zip.name) schema_file.write_bytes(schema_zip.getvalue()) schema_dir = run_dir / "00_input" / "cgmlst_schema" schema_dir.mkdir(parents=True, exist_ok=True) with zipfile.ZipFile(schema_file) as zf: zf.extractall(schema_dir) children = [p for p in schema_dir.iterdir() if p.is_dir()] if len(children) == 1: schema_dir = children[0]
st.write("Detected samples") st.dataframe(pd.DataFrame([{ "Sample_ID": s.sample_id, "Read_1": s.read1.name if s.read1 else "", "Read_2": s.read2.name if s.read2 else "", "Long_Reads": s.long_reads.name if s.long_reads else "", "Assembly": s.assembly.name if s.assembly else "", } for s in samples]), use_container_width=True) status = st.empty(); progress = st.progress(0) events = [] def cb(msg): events.append(msg); status.info(msg) progress.progress(min(95, 5 + int(90 * len(events) / max(1, len(samples)*3))))
modules = {"read_qc": read_qc, "assembly": assembly, "quast": quast, "checkm2": checkm2, "taxonomy": taxonomy, "mobileome": mobileome, "mlst": mlst, "cgmlst": cgmlst, "phylogenomics": phylogenomics, "population": population} params = {"threads": threads, "memory_gb": memory_gb, "assembly_mode": assembly_mode, "fastp_quality": fastp_quality, "fastp_length": int(fastp_length), "fastp_n_limit": int(fastp_n_limit), "dry_run": dry_run} try: zip_path, manifest, records = run_pipeline(samples, run_dir, modules, params, reference=ref_path, schema_dir=schema_dir, progress_cb=cb) progress.progress(100); status.success("Analysis finished") command_df = pd.DataFrame([r.to_dict() for r in records]) st.subheader("Execution summary") if not command_df.empty: st.dataframe(command_df[["name","returncode","skipped","reason"]], use_container_width=True) st.json(manifest) st.download_button("Download complete WOLOJI result package", data=zip_path.read_bytes(), file_name=zip_path.name, mime="application/zip", use_container_width=True) except Exception as exc: progress.empty(); status.error(f"Pipeline failed: {exc}")
with utilities_tab: u1,u2,u3 = st.tabs(["Primer design", "GeneClean-BLAST", "PhyloForge"]) with u1: st.markdown("#### Primer Design Tool") primer_file=st.file_uploader("Target FASTA",type=["fa","fasta","fna"],key="primer_file") primer_text=st.text_area("Or paste target DNA sequence",height=120,key="primer_text") pc1,pc2=st.columns(2) prod_min=pc1.number_input("Minimum product size",50,5000,100,10) prod_max=pc2.number_input("Maximum product size",60,10000,600,10) if st.button("Design primers",key="design_primers"): seq=primer_text.strip().replace(" ","").replace("\n","") if primer_file: _,seq=fasta_first_sequence(primer_file.getvalue(),primer_file.name) if not seq: st.error("Provide a FASTA file or DNA sequence.") else: try: pdf=design_primers(seq,product_min=int(prod_min),product_max=int(prod_max)) st.dataframe(pdf,use_container_width=True,hide_index=True) st.download_button("Download primer table",pdf.to_csv(index=False).encode(),"woloji_primers.csv","text/csv") except Exception as exc: st.error(f"Primer design failed: {exc}") with u2: st.markdown("#### GeneClean-BLAST") q=st.file_uploader("Query FASTA",type=["fa","fasta","fna"],key="blast_q") subj=st.file_uploader("Subject/reference FASTA",type=["fa","fasta","fna"],key="blast_s") if st.button("Run local BLAST",key="run_blast"): if not q or not subj: st.error("Upload query and subject FASTA files.") else: try: bdf=local_blast(q.getvalue(),subj.getvalue(),threads=threads) st.dataframe(bdf,use_container_width=True,hide_index=True) st.download_button("Download BLAST table",bdf.to_csv(index=False).encode(),"woloji_blast.csv","text/csv") except Exception as exc: st.error(f"BLAST failed: {exc}") with u3: st.markdown("#### PhyloForge") pf=st.file_uploader("Upload homologous FASTA sequences",type=["fa","fasta","fna","fas"],accept_multiple_files=True,key="phylo_files") if st.button("Align and infer tree",key="run_phylo"): if not pf or len(pf)<2: st.error("Upload at least two homologous sequences or sequence sets.") else: try: aln,tree=phyloforge(pf,threads=threads) st.text_area("MAFFT alignment",aln,height=250) st.code(tree,language="text") st.download_button("Download alignment",aln.encode(),"woloji_alignment.fasta","text/plain") st.download_button("Download Newick tree",tree.encode(),"woloji_tree.nwk","text/plain") except Exception as exc: st.error(f"PhyloForge failed: {exc}")
with status_tab: st.subheader("Installed command-line tools") if st.button("Refresh tool status"): st.session_state["tool_status"] = status_rows() st.session_state["db_status"] = database_rows() if "tool_status" not in st.session_state: st.session_state["tool_status"] = status_rows() st.session_state["db_status"] = database_rows() st.dataframe(pd.DataFrame(st.session_state["tool_status"]), use_container_width=True, hide_index=True) st.subheader("Reference database configuration") st.dataframe(pd.DataFrame(st.session_state["db_status"]), use_container_width=True, hide_index=True) st.info("Large reference databases should be mounted on persistent storage and exposed through the environment variables shown above.")
with help_tab: st.markdown("""### Input namingFor paired Illumina files without metadata, use names such as `Sample01_R1.fastq.gz` and `Sample01_R2.fastq.gz`.Unpaired FASTQ files are interpreted as long-read data. For mixed or non-standard names, use the metadata table.
### Recommended analysis modes**Routine isolate WGS:** read QC, assembly, QUAST, taxonomy/ANI, mobileome, MLST and report.
**Comparative genomics:** analyse multiple assemblies and enable cgMLST/wgMLST and population genomics.
**Outbreak/phylogenomic analysis:** provide a reference genome and enable core SNP phylogenomics. WOLOJI calls Snippy, Gubbins and IQ-TREE when available.
### Out of scopeGenome annotation, codon usage / composition analysis, AMR detection, virulence screening, and secondary metaboliteprediction are performed with separate dedicated tools and are not part of this build.
### Important database variables`GTDBTK_DATA_PATH`, `CHECKM2DB`, `GENOMAD_DB`, `MOB_SUITE_DB`.
### Publication outputsEvery run records input SHA256 hashes, selected parameters, database paths, exact command lines, command logs, software outputs, assembly summary tables, publication figures, and a reproducibility manifest.""")app.pyDeleted-991