from __future__ import annotations import gzip import hashlib import json import os import platform import re import shutil import subprocess import sys import time import traceback import uuid import zipfile from dataclasses import asdict, dataclass from datetime import datetime, timezone from pathlib import Path from typing import Dict, List, Optional, Sequence, Tuple import gradio as gr import numpy as np import pandas as pd import psutil import yaml APP_TITLE = os.getenv("APP_TITLE", "Gulumba Metagenomics Tool 1") APP_VERSION = "2.0.0" WORK_ROOT = Path(os.getenv("WORK_ROOT", "/tmp/metagenome_runs")).resolve() WORK_ROOT.mkdir(parents=True, exist_ok=True) MAX_UPLOAD_GB = float(os.getenv("MAX_UPLOAD_GB", "20")) DEFAULT_THREADS = max(1, min(int(os.getenv("DEFAULT_THREADS", "4")), os.cpu_count() or 2)) DB_ENV = { "Kraken2 / Bracken": "KRAKEN2_DB", "CheckM2": "CHECKM2DB", "GTDB-Tk": "GTDBTK_DATA_PATH", "eggNOG-mapper": "EGGNOG_DATA_DIR", "geNomad": "GENOMAD_DB", } SPECIAL_ENVS = { "checkm2": "checkm2", "gtdbtk": "gtdbtk", "genomad": "genomad", "emapper.py": "eggnog", "amrfinder": "amrfinder", } CORE_TOOLS = [ "fastp", "fastqc", "multiqc", "bowtie2", "bowtie2-build", "samtools", "kraken2", "bracken", "megahit", "quast.py", "metabat2", "jgi_summarize_bam_contig_depths", "prodigal", "dRep", "seqkit", ] OPTIONAL_TOOLS = ["checkm2", "gtdbtk", "genomad", "emapper.py", "amrfinder"] @dataclass class Sample: sample_id: str read1: Path read2: Optional[Path] = None group: str = "NA" condition: str = "NA" location: str = "NA" time_point: str = "NA" replicate: str = "NA" sequencing_platform: str = "Illumina" library_type: str = "Shotgun" class PipelineError(RuntimeError): pass def now_iso() -> str: return datetime.now(timezone.utc).isoformat() def safe_name(value: str) -> str: value = re.sub(r"[^A-Za-z0-9._-]+", "_", str(value).strip()) return value[:120] or "sample" def human_bytes(n: int) -> str: units = ["B", "KB", "MB", "GB", "TB"] value = float(n) for unit in units: if value < 1024 or unit == units[-1]: return f"{value:.2f} {unit}" value /= 1024 return f"{value:.2f} TB" def sha256sum(path: Path, chunk_size: int = 1024 * 1024) -> str: h = hashlib.sha256() with path.open("rb") as fh: while True: chunk = fh.read(chunk_size) if not chunk: break h.update(chunk) return h.hexdigest() def tool_cmd(tool: str, *args: str) -> List[str]: env_name = SPECIAL_ENVS.get(tool) if env_name: return ["micromamba", "run", "-n", env_name, tool, *map(str, args)] return [tool, *map(str, args)] def tool_available(tool: str) -> bool: if shutil.which(tool): return True env_name = SPECIAL_ENVS.get(tool) if env_name and shutil.which("micromamba"): proc = subprocess.run( ["micromamba", "run", "-n", env_name, tool, "--help"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=20, ) return proc.returncode in (0, 1, 2) return False def tool_version(tool: str) -> str: candidates = [ tool_cmd(tool, "--version"), tool_cmd(tool, "-version"), tool_cmd(tool, "-v"), ] for cmd in candidates: try: p = subprocess.run(cmd, capture_output=True, text=True, timeout=15) text = (p.stdout + "\n" + p.stderr).strip() if text: return text.splitlines()[0][:250] except Exception: pass return "available" if tool_available(tool) else "not available" def run_command( cmd: Sequence[str], log_path: Path, cwd: Optional[Path] = None, env: Optional[dict] = None, dry_run: bool = False, ) -> None: command_string = " ".join(map(str, cmd)) with log_path.open("a", encoding="utf-8") as log: log.write(f"\n[{now_iso()}] COMMAND: {command_string}\n") log.flush() if dry_run: log.write("DRY RUN: command not executed.\n") return proc = subprocess.Popen( list(map(str, cmd)), cwd=str(cwd) if cwd else None, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, bufsize=1, ) assert proc.stdout is not None for line in proc.stdout: log.write(line) rc = proc.wait() if rc != 0: raise PipelineError(f"Command failed with exit code {rc}: {command_string}") def copy_upload(src: str | Path, dst_dir: Path) -> Path: src = Path(src) dst = dst_dir / safe_name(src.name) shutil.copy2(src, dst) return dst def parse_metadata(metadata_path: Path, upload_map: Dict[str, Path]) -> List[Sample]: sep = "\t" if metadata_path.suffix.lower() in {".tsv", ".txt"} else "," df = pd.read_csv(metadata_path, sep=sep, dtype=str).fillna("") normalized = {c.lower().strip(): c for c in df.columns} required = ["sample_id", "read_1"] missing = [x for x in required if x not in normalized] if missing: raise PipelineError( "Metadata must contain Sample_ID and Read_1 columns. " f"Missing: {', '.join(missing)}" ) if df[normalized["sample_id"]].duplicated().any(): dups = df.loc[df[normalized["sample_id"]].duplicated(), normalized["sample_id"]].tolist() raise PipelineError(f"Duplicate Sample_ID values detected: {dups[:10]}") def field(row, name: str, default: str = "NA") -> str: col = normalized.get(name) value = str(row[col]).strip() if col else "" return value or default def resolve_read(name: str) -> Path: base = Path(name).name if base in upload_map: return upload_map[base] if name in upload_map: return upload_map[name] raise PipelineError( f"Metadata references '{name}', but that FASTQ file was not uploaded. " "Use matching file names in Read_1 and Read_2." ) samples: List[Sample] = [] for _, row in df.iterrows(): sid = safe_name(field(row, "sample_id", "sample")) r1 = resolve_read(field(row, "read_1", "")) r2_name = field(row, "read_2", "") if "read_2" in normalized else "" r2 = resolve_read(r2_name) if r2_name and r2_name != "NA" else None samples.append( Sample( sample_id=sid, read1=r1, read2=r2, group=field(row, "group"), condition=field(row, "condition"), location=field(row, "location"), time_point=field(row, "time_point"), replicate=field(row, "replicate"), sequencing_platform=field(row, "sequencing_platform", "Illumina"), library_type=field(row, "library_type", "Shotgun"), ) ) return samples def infer_samples(uploaded: List[Path]) -> List[Sample]: if len(uploaded) == 1: return [Sample(sample_id=safe_name(uploaded[0].name.split(".")[0]), read1=uploaded[0])] if len(uploaded) == 2: names = [p.name.lower() for p in uploaded] r1_idx = next((i for i, n in enumerate(names) if any(t in n for t in ["_r1", "_1.", "-r1"])), 0) r2_idx = 1 - r1_idx sid = re.sub(r"([._-]r?1).*", "", uploaded[r1_idx].name, flags=re.I) return [Sample(sample_id=safe_name(sid), read1=uploaded[r1_idx], read2=uploaded[r2_idx])] raise PipelineError("For more than two FASTQ files, upload a metadata CSV/TSV describing each sample.") def validate_inputs(samples: List[Sample]) -> List[str]: warnings: List[str] = [] ids = [s.sample_id for s in samples] if len(ids) != len(set(ids)): raise PipelineError("Sample IDs must be unique.") for s in samples: for read in [s.read1, s.read2]: if read is None: continue if not read.exists() or read.stat().st_size == 0: raise PipelineError(f"Missing or empty FASTQ: {read}") n = read.name.lower() if not any(n.endswith(ext) for ext in (".fastq", ".fq", ".fastq.gz", ".fq.gz")): warnings.append(f"{read.name}: extension is not a standard FASTQ extension.") return warnings def fastq_open(path: Path): return gzip.open(path, "rt", encoding="utf-8", errors="replace") if path.suffix == ".gz" else path.open("r", encoding="utf-8", errors="replace") def estimate_read_length(path: Path, max_reads: int = 1000) -> int: lengths = [] try: with fastq_open(path) as fh: i = 0 while i < max_reads: header = fh.readline() seq = fh.readline().strip() plus = fh.readline() qual = fh.readline() if not header or not seq or not plus or not qual: break lengths.append(len(seq)) i += 1 except Exception: return 150 return int(round(float(np.median(lengths)))) if lengths else 150 def module_status_dataframe() -> pd.DataFrame: rows = [] for tool in CORE_TOOLS + OPTIONAL_TOOLS: rows.append({"Tool": tool, "Available": "Yes" if tool_available(tool) else "No", "Version": tool_version(tool)}) for label, env_name in DB_ENV.items(): path = os.getenv(env_name, "") rows.append({"Tool": f"Database: {label}", "Available": "Yes" if path and Path(path).exists() else "No", "Version": path or f"Set {env_name}"}) return pd.DataFrame(rows) def make_manifest(run_dir: Path, samples: List[Sample], params: dict, input_files: List[Path]) -> dict: manifest = { "application": APP_TITLE, "application_version": APP_VERSION, "run_id": run_dir.name, "created_utc": now_iso(), "platform": platform.platform(), "python": sys.version, "cpu_count": os.cpu_count(), "memory_total_gb": round(psutil.virtual_memory().total / (1024 ** 3), 2), "parameters": params, "samples": [ { **asdict(s), "read1": s.read1.name, "read2": s.read2.name if s.read2 else None, } for s in samples ], "inputs": [], "databases": {env: os.getenv(env, "") for env in DB_ENV.values()}, } for p in input_files: manifest["inputs"].append({ "file": p.name, "size_bytes": p.stat().st_size, "sha256": sha256sum(p), }) (run_dir / "run_manifest.json").write_text(json.dumps(manifest, indent=2), encoding="utf-8") return manifest def write_versions(run_dir: Path) -> None: rows = [] for tool in CORE_TOOLS + OPTIONAL_TOOLS: rows.append({"software": tool, "version": tool_version(tool)}) pd.DataFrame(rows).to_csv(run_dir / "software_versions.tsv", sep="\t", index=False) db_rows = [] for label, env_name in DB_ENV.items(): db_rows.append({"database": label, "environment_variable": env_name, "path": os.getenv(env_name, "")}) pd.DataFrame(db_rows).to_csv(run_dir / "database_versions.tsv", sep="\t", index=False) def fastp_step(sample: Sample, out_dir: Path, log: Path, threads: int, min_q: int, min_len: int, max_n_bases: int, trim_poly_g: bool, dry_run: bool) -> Tuple[Path, Optional[Path]]: """Run fastp with an absolute N-base limit. fastp --n_base_limit is a count, not a proportion.""" out_dir.mkdir(parents=True, exist_ok=True) r1 = out_dir / f"{sample.sample_id}_clean_R1.fastq.gz" r2 = out_dir / f"{sample.sample_id}_clean_R2.fastq.gz" if sample.read2 else None json_out = out_dir / f"{sample.sample_id}_fastp.json" html_out = out_dir / f"{sample.sample_id}_fastp.html" if not tool_available("fastp"): raise PipelineError("fastp is not installed in the container.") cmd = [ "fastp", "-i", str(sample.read1), "-o", str(r1), "-q", str(min_q), "-l", str(min_len), "--n_base_limit", str(max(0, int(max_n_bases))), "-w", str(threads), "-j", str(json_out), "-h", str(html_out) ] if trim_poly_g: cmd.append("--trim_poly_g") if sample.read2: cmd.extend(["-I", str(sample.read2), "-O", str(r2), "--detect_adapter_for_pe"]) run_command(cmd, log, dry_run=dry_run) if dry_run: return sample.read1, sample.read2 return r1, r2 def fastqc_multiqc_step(reads: List[Path], out_dir: Path, log: Path, threads: int, dry_run: bool) -> None: if not tool_available("fastqc") or not tool_available("multiqc"): return fq_dir = out_dir / "fastqc" fq_dir.mkdir(parents=True, exist_ok=True) run_command(["fastqc", "-t", str(threads), "-o", str(fq_dir), *map(str, reads)], log, dry_run=dry_run) run_command(["multiqc", str(out_dir), "-o", str(out_dir / "multiqc"), "--force"], log, dry_run=dry_run) def host_remove_step(sample_id: str, r1: Path, r2: Optional[Path], host_fasta: Path, out_dir: Path, log: Path, threads: int, dry_run: bool) -> Tuple[Path, Optional[Path]]: out_dir.mkdir(parents=True, exist_ok=True) if not tool_available("bowtie2") or not tool_available("bowtie2-build"): raise PipelineError("Bowtie2 is required for host removal.") index_prefix = out_dir / "host_index" run_command(["bowtie2-build", str(host_fasta), str(index_prefix)], log, dry_run=dry_run) if r2: prefix = out_dir / f"{sample_id}_nonhost_R%.fastq.gz" cmd = ["bowtie2", "-x", str(index_prefix), "-1", str(r1), "-2", str(r2), "--very-sensitive", "-p", str(threads), "--un-conc-gz", str(prefix), "-S", "/dev/null"] run_command(cmd, log, dry_run=dry_run) if dry_run: return r1, r2 return out_dir / f"{sample_id}_nonhost_R1.fastq.gz", out_dir / f"{sample_id}_nonhost_R2.fastq.gz" out_single = out_dir / f"{sample_id}_nonhost.fastq.gz" cmd = ["bowtie2", "-x", str(index_prefix), "-U", str(r1), "--very-sensitive", "-p", str(threads), "--un-gz", str(out_single), "-S", "/dev/null"] run_command(cmd, log, dry_run=dry_run) return (r1 if dry_run else out_single), None def kraken_step(sample_id: str, r1: Path, r2: Optional[Path], out_dir: Path, log: Path, threads: int, confidence: float, bracken_level: str, min_reads: int, dry_run: bool) -> Optional[Path]: db = os.getenv("KRAKEN2_DB", "") if not db or not Path(db).exists() or not tool_available("kraken2"): with log.open("a", encoding="utf-8") as fh: fh.write(f"\nSKIP taxonomy for {sample_id}: set KRAKEN2_DB to a valid database path.\n") return None out_dir.mkdir(parents=True, exist_ok=True) report = out_dir / f"{sample_id}_kraken_report.tsv" classified = out_dir / f"{sample_id}_kraken_output.tsv" cmd = ["kraken2", "--db", db, "--threads", str(threads), "--confidence", str(confidence), "--use-names", "--report", str(report), "--output", str(classified)] if r2: cmd.extend(["--paired", str(r1), str(r2)]) else: cmd.append(str(r1)) run_command(cmd, log, dry_run=dry_run) if dry_run or not tool_available("bracken"): return report if not dry_run else None read_len = estimate_read_length(r1) bracken = out_dir / f"{sample_id}_bracken_{bracken_level}.tsv" run_command(["bracken", "-d", db, "-i", str(report), "-o", str(bracken), "-r", str(read_len), "-l", bracken_level, "-t", str(min_reads)], log, dry_run=dry_run) return bracken def megahit_step(sample_id: str, r1: Path, r2: Optional[Path], out_dir: Path, log: Path, threads: int, min_contig: int, dry_run: bool) -> Optional[Path]: if not tool_available("megahit"): with log.open("a", encoding="utf-8") as fh: fh.write("\nSKIP assembly: MEGAHIT is not installed.\n") return None sample_out = out_dir / sample_id cmd = ["megahit", "-o", str(sample_out), "-t", str(threads), "--min-contig-len", str(min_contig)] if r2: cmd.extend(["-1", str(r1), "-2", str(r2)]) else: cmd.extend(["-r", str(r1)]) run_command(cmd, log, dry_run=dry_run) return sample_out / "final.contigs.fa" def quast_step(sample_id: str, contigs: Path, out_dir: Path, log: Path, threads: int, min_contig: int, dry_run: bool) -> None: if not tool_available("quast.py"): return run_command(["quast.py", str(contigs), "-o", str(out_dir / sample_id), "-t", str(threads), "--min-contig", str(min_contig)], log, dry_run=dry_run) def mapping_binning_step(sample_id: str, contigs: Path, r1: Path, r2: Optional[Path], out_dir: Path, log: Path, threads: int, dry_run: bool) -> Optional[Path]: needed = ["bowtie2", "bowtie2-build", "samtools", "metabat2", "jgi_summarize_bam_contig_depths"] if not all(tool_available(x) for x in needed): with log.open("a", encoding="utf-8") as fh: fh.write("\nSKIP binning: required mapping/MetaBAT2 tools are not installed.\n") return None sdir = out_dir / sample_id sdir.mkdir(parents=True, exist_ok=True) idx = sdir / "assembly_index" sam = sdir / "mapping.sam" bam = sdir / "mapping.sorted.bam" depth = sdir / "depth.tsv" bins = sdir / "bins" bins.mkdir(exist_ok=True) run_command(["bowtie2-build", str(contigs), str(idx)], log, dry_run=dry_run) mapcmd = ["bowtie2", "-x", str(idx), "-p", str(threads)] if r2: mapcmd.extend(["-1", str(r1), "-2", str(r2)]) else: mapcmd.extend(["-U", str(r1)]) mapcmd.extend(["-S", str(sam)]) run_command(mapcmd, log, dry_run=dry_run) run_command(["samtools", "sort", "-@", str(threads), "-o", str(bam), str(sam)], log, dry_run=dry_run) if not dry_run and sam.exists(): sam.unlink(missing_ok=True) run_command(["samtools", "index", str(bam)], log, dry_run=dry_run) run_command(["jgi_summarize_bam_contig_depths", "--outputDepth", str(depth), str(bam)], log, dry_run=dry_run) run_command(["metabat2", "-i", str(contigs), "-a", str(depth), "-o", str(bins / "bin"), "-m", "1500", "-t", str(threads)], log, dry_run=dry_run) return bins def checkm2_step(bins: Path, out_dir: Path, log: Path, threads: int, dry_run: bool) -> None: db = os.getenv("CHECKM2DB", "") if not tool_available("checkm2") or not db or not Path(db).exists(): with log.open("a", encoding="utf-8") as fh: fh.write("\nSKIP CheckM2: install tool and set CHECKM2DB.\n") return cmd = tool_cmd("checkm2", "predict", "--threads", str(threads), "--input", str(bins), "--output-directory", str(out_dir), "--database_path", db) run_command(cmd, log, dry_run=dry_run) def gtdbtk_step(bins: Path, out_dir: Path, log: Path, threads: int, dry_run: bool) -> None: db = os.getenv("GTDBTK_DATA_PATH", "") if not tool_available("gtdbtk") or not db or not Path(db).exists(): with log.open("a", encoding="utf-8") as fh: fh.write("\nSKIP GTDB-Tk: install tool and set GTDBTK_DATA_PATH.\n") return env = os.environ.copy() env["GTDBTK_DATA_PATH"] = db cmd = tool_cmd("gtdbtk", "classify_wf", "--genome_dir", str(bins), "--out_dir", str(out_dir), "--cpus", str(threads), "-x", "fa") run_command(cmd, log, env=env, dry_run=dry_run) def prodigal_step(sample_id: str, contigs: Path, out_dir: Path, log: Path, dry_run: bool) -> Optional[Path]: if not tool_available("prodigal"): return None sdir = out_dir / sample_id sdir.mkdir(parents=True, exist_ok=True) proteins = sdir / "proteins.faa" genes = sdir / "genes.fna" gff = sdir / "genes.gff" run_command(["prodigal", "-i", str(contigs), "-a", str(proteins), "-d", str(genes), "-o", str(gff), "-p", "meta", "-f", "gff", "-q"], log, dry_run=dry_run) return proteins def eggnog_step(sample_id: str, proteins: Path, out_dir: Path, log: Path, threads: int, dry_run: bool) -> None: db = os.getenv("EGGNOG_DATA_DIR", "") if not tool_available("emapper.py") or not db or not Path(db).exists(): with log.open("a", encoding="utf-8") as fh: fh.write(f"\nSKIP eggNOG for {sample_id}: set EGGNOG_DATA_DIR.\n") return cmd = tool_cmd("emapper.py", "-i", str(proteins), "--itype", "proteins", "-o", sample_id, "--output_dir", str(out_dir / sample_id), "--cpu", str(threads), "--data_dir", db, "--override") run_command(cmd, log, dry_run=dry_run) def amrfinder_step(sample_id: str, contigs: Path, out_dir: Path, log: Path, dry_run: bool) -> None: if not tool_available("amrfinder"): with log.open("a", encoding="utf-8") as fh: fh.write("\nSKIP AMRFinderPlus: tool is not installed.\n") return out_dir.mkdir(parents=True, exist_ok=True) out = out_dir / f"{sample_id}_amrfinder.tsv" cmd = tool_cmd("amrfinder", "-n", str(contigs), "--plus", "-o", str(out)) run_command(cmd, log, dry_run=dry_run) def genomad_step(sample_id: str, contigs: Path, out_dir: Path, log: Path, threads: int, dry_run: bool) -> None: db = os.getenv("GENOMAD_DB", "") if not tool_available("genomad") or not db or not Path(db).exists(): with log.open("a", encoding="utf-8") as fh: fh.write(f"\nSKIP geNomad for {sample_id}: set GENOMAD_DB.\n") return splits = max(1, min(threads, 8)) cmd = tool_cmd("genomad", "end-to-end", "--cleanup", "--splits", str(splits), str(contigs), str(out_dir / sample_id), db) run_command(cmd, log, dry_run=dry_run) def parse_bracken(path: Path) -> pd.Series: df = pd.read_csv(path, sep="\t") name_col = next((c for c in ["name", "taxonomy_name"] if c in df.columns), None) value_col = next((c for c in ["fraction_total_reads", "new_est_reads", "estimated_reads"] if c in df.columns), None) if name_col is None or value_col is None: raise PipelineError(f"Unexpected Bracken columns in {path.name}") s = pd.Series(pd.to_numeric(df[value_col], errors="coerce").fillna(0).values, index=df[name_col].astype(str)) if value_col != "fraction_total_reads": total = s.sum() if total > 0: s = s / total return s.groupby(level=0).sum() def parse_bracken_counts(path: Path) -> pd.Series: """Return estimated read counts from a Bracken table.""" df = pd.read_csv(path, sep="\t") name_col = next((c for c in ["name", "taxonomy_name"] if c in df.columns), None) value_col = next((c for c in ["new_est_reads", "estimated_reads", "kraken_assigned_reads"] if c in df.columns), None) if name_col is None or value_col is None: raise PipelineError(f"Bracken count columns were not found in {path.name}") s = pd.Series(pd.to_numeric(df[value_col], errors="coerce").fillna(0).values, index=df[name_col].astype(str)) return s.groupby(level=0).sum() def _normalise_rows(matrix: pd.DataFrame) -> pd.DataFrame: x = matrix.astype(float).clip(lower=0) return x.div(x.sum(axis=1).replace(0, np.nan), axis=0).fillna(0.0) def build_abundance_matrix(bracken_files: Dict[str, Path], out_dir: Path) -> Optional[pd.DataFrame]: """Build both estimated read count and relative abundance matrices. This is the hand off point to Tool 2. species_relative_abundance.tsv and species_estimated_reads.tsv, together with samplesheet_resolved.csv, are the files that Tool 2 (statistics and reporting) expects as input. """ if not bracken_files: return None rel_series, count_series = [], [] for sid, path in bracken_files.items(): if not path.exists(): continue s_rel = parse_bracken(path) s_rel.name = sid rel_series.append(s_rel) try: s_count = parse_bracken_counts(path) s_count.name = sid count_series.append(s_count) except Exception: pass if not rel_series: return None rel = pd.concat(rel_series, axis=1).fillna(0).T rel = _normalise_rows(rel) rel.index.name = "Sample_ID" rel.to_csv(out_dir / "species_relative_abundance.tsv", sep="\t") if count_series: counts = pd.concat(count_series, axis=1).fillna(0).T counts.index.name = "Sample_ID" counts.to_csv(out_dir / "species_estimated_reads.tsv", sep="\t") return rel def metadata_dataframe(samples: List[Sample]) -> pd.DataFrame: return pd.DataFrame([ { "Sample_ID": s.sample_id, "Group": s.group, "Condition": s.condition, "Location": s.location, "Time_point": s.time_point, "Replicate": s.replicate, "Sequencing_platform": s.sequencing_platform, "Library_type": s.library_type, } for s in samples ]) def write_methods(run_dir: Path, params: dict, completed: List[str], skipped: List[str]) -> None: db_text = "; ".join(f"{k}={os.getenv(v, 'not configured')}" for k, v in DB_ENV.items()) text = f"""# Automated methods record, Tool 1: sequence processing Analysis was performed with {APP_TITLE} v{APP_VERSION}. The workflow was executed in {params['analysis_mode']} mode using {params['threads']} CPU threads. Raw shotgun metagenomic reads were quality filtered with fastp using a minimum Phred score of {params['min_quality']}, a minimum retained read length of {params['min_read_length']} bp, and an absolute maximum of {params['max_n_bases']} ambiguous N bases per read. Poly-G trimming was {'enabled' if params['trim_poly_g'] else 'disabled'}. FastQC and MultiQC were used when available. Host read removal was {'enabled' if params['host_removal'] else 'not requested'}. Read based taxonomic profiling used Kraken2 with confidence {params['kraken_confidence']} and Bracken at taxonomic level {params['bracken_level']} when a Kraken2 database was configured. Assembly used MEGAHIT with a minimum contig length of {params['min_contig_length']} bp. QUAST was used for assembly quality assessment when available. Genome resolved analysis mapped cleaned reads back to contigs with Bowtie2 and SAMtools and performed MetaBAT2 binning. CheckM2 and GTDB-Tk were executed only when their external databases were configured. Gene prediction used Prodigal in metagenomic mode. eggNOG-mapper, AMRFinderPlus, and geNomad were executed when their software and databases were available. Database configuration: {db_text}. Completed modules: {', '.join(completed) if completed else 'None'}. Skipped modules: {', '.join(skipped) if skipped else 'None'}. All software versions, input checksums, parameter values, and database paths are stored with the run outputs. The files species_relative_abundance.tsv, species_estimated_reads.tsv, and samplesheet_resolved.csv in this package are the direct input to Tool 2 (statistics and reporting). """ (run_dir / "methods.txt").write_text(text, encoding="utf-8") def make_zip(run_dir: Path) -> Path: zip_path = run_dir.parent / f"{run_dir.name}_results.zip" with zipfile.ZipFile(zip_path, "w", compression=zipfile.ZIP_DEFLATED, compresslevel=6) as zf: for path in run_dir.rglob("*"): if path.is_file(): zf.write(path, path.relative_to(run_dir.parent)) return zip_path def tail_log(log: Path, max_chars: int = 18000) -> str: if not log.exists(): return "" text = log.read_text(encoding="utf-8", errors="replace") return text[-max_chars:] def run_pipeline( fastq_files, metadata_file, host_file, analysis_mode, threads, min_quality, min_read_length, max_n_bases, trim_poly_g, kraken_confidence, bracken_level, min_bracken_reads, min_contig_length, host_removal, dry_run, ): started = time.time() run_id = f"run_{datetime.now().strftime('%Y%m%d_%H%M%S')}_{uuid.uuid4().hex[:8]}" run_dir = WORK_ROOT / run_id input_dir = run_dir / "00_Input" input_dir.mkdir(parents=True, exist_ok=True) log = run_dir / "pipeline.log" completed: List[str] = [] skipped: List[str] = [] try: if not fastq_files: raise PipelineError("Upload at least one FASTQ or FASTQ.GZ file.") fastq_files = fastq_files if isinstance(fastq_files, list) else [fastq_files] total_upload = sum(Path(f).stat().st_size for f in fastq_files) if total_upload > MAX_UPLOAD_GB * (1024 ** 3): raise PipelineError(f"Uploaded FASTQ files total {human_bytes(total_upload)}, above the configured {MAX_UPLOAD_GB:g} GB limit.") copied_reads = [copy_upload(f, input_dir) for f in fastq_files] upload_map = {p.name: p for p in copied_reads} copied_metadata = copy_upload(metadata_file, input_dir) if metadata_file else None copied_host = copy_upload(host_file, input_dir) if host_file else None samples = parse_metadata(copied_metadata, upload_map) if copied_metadata else infer_samples(copied_reads) warnings = validate_inputs(samples) params = { "analysis_mode": analysis_mode, "threads": int(threads), "min_quality": int(min_quality), "min_read_length": int(min_read_length), "max_n_bases": int(max_n_bases), "trim_poly_g": bool(trim_poly_g), "kraken_confidence": float(kraken_confidence), "bracken_level": bracken_level, "min_bracken_reads": int(min_bracken_reads), "min_contig_length": int(min_contig_length), "host_removal": bool(host_removal), "dry_run": bool(dry_run), } (run_dir / "parameters.yaml").write_text(yaml.safe_dump(params, sort_keys=False), encoding="utf-8") metadata_df = metadata_dataframe(samples) metadata_df.to_csv(run_dir / "samplesheet_resolved.csv", index=False) input_files = copied_reads + ([copied_metadata] if copied_metadata else []) + ([copied_host] if copied_host else []) make_manifest(run_dir, samples, params, [p for p in input_files if p]) write_versions(run_dir) cleaned: Dict[str, Tuple[Path, Optional[Path]]] = {} qc_dir = run_dir / "01_QC" all_clean_reads: List[Path] = [] for sample in samples: r1, r2 = fastp_step(sample, qc_dir / "fastp", log, int(threads), int(min_quality), int(min_read_length), int(max_n_bases), bool(trim_poly_g), bool(dry_run)) cleaned[sample.sample_id] = (r1, r2) all_clean_reads.append(r1) if r2: all_clean_reads.append(r2) completed.append("quality trimming") fastqc_multiqc_step(all_clean_reads, qc_dir, log, int(threads), bool(dry_run)) completed.append("FastQC/MultiQC") if host_removal: if not copied_host: warnings.append("Host removal was requested but no host reference FASTA was uploaded. The step was skipped.") skipped.append("host removal") else: host_out = run_dir / "02_Host_Removal" for sid, (r1, r2) in list(cleaned.items()): cleaned[sid] = host_remove_step(sid, r1, r2, copied_host, host_out / sid, log, int(threads), bool(dry_run)) completed.append("host removal") mode = str(analysis_mode).lower() do_taxonomy = any(k in mode for k in ["basic", "comprehensive", "complete"]) do_assembly = any(k in mode for k in ["comprehensive", "genome", "complete"]) do_genome = any(k in mode for k in ["genome", "complete"]) do_function = any(k in mode for k in ["comprehensive", "complete"]) bracken_files: Dict[str, Path] = {} if do_taxonomy: tax_dir = run_dir / "03_Taxonomy" for sid, (r1, r2) in cleaned.items(): b = kraken_step(sid, r1, r2, tax_dir, log, int(threads), float(kraken_confidence), bracken_level, int(min_bracken_reads), bool(dry_run)) if b: bracken_files[sid] = b if bracken_files: completed.append("Kraken2/Bracken taxonomy") else: skipped.append("Kraken2/Bracken taxonomy") assemblies: Dict[str, Path] = {} if do_assembly: assembly_dir = run_dir / "04_Assembly" quast_dir = run_dir / "05_Assembly_QC" for sid, (r1, r2) in cleaned.items(): contigs = megahit_step(sid, r1, r2, assembly_dir, log, int(threads), int(min_contig_length), bool(dry_run)) if contigs and (contigs.exists() or dry_run): assemblies[sid] = contigs quast_step(sid, contigs, quast_dir, log, int(threads), int(min_contig_length), bool(dry_run)) if assemblies or dry_run: completed.append("MEGAHIT assembly") else: skipped.append("assembly") bins_by_sample: Dict[str, Path] = {} if do_genome and assemblies: bin_dir = run_dir / "06_MAGs" for sid, contigs in assemblies.items(): r1, r2 = cleaned[sid] bins = mapping_binning_step(sid, contigs, r1, r2, bin_dir, log, int(threads), bool(dry_run)) if bins and (dry_run or any(bins.glob("*.fa"))): bins_by_sample[sid] = bins checkm2_step(bins, bin_dir / sid / "checkm2", log, int(threads), bool(dry_run)) gtdbtk_step(bins, bin_dir / sid / "gtdbtk", log, int(threads), bool(dry_run)) if bins_by_sample: completed.append("MAG binning and genome quality/taxonomy") else: skipped.append("MAG quality/taxonomy") if (do_function or do_genome) and assemblies: gene_dir = run_dir / "07_Genes_Function" amr_dir = run_dir / "08_Resistome_Virulome" mobile_dir = run_dir / "09_Viruses_Plasmids" for sid, contigs in assemblies.items(): proteins = prodigal_step(sid, contigs, gene_dir, log, bool(dry_run)) if proteins and (proteins.exists() or dry_run): eggnog_step(sid, proteins, gene_dir / "eggnog", log, int(threads), bool(dry_run)) amrfinder_step(sid, contigs, amr_dir, log, bool(dry_run)) genomad_step(sid, contigs, mobile_dir, log, int(threads), bool(dry_run)) completed.append("gene prediction and optional functional/resistance/mobile element analysis") abundance_dir = run_dir / "10_Abundance_Matrix" abundance_dir.mkdir(exist_ok=True) if bracken_files and not dry_run: abundance = build_abundance_matrix(bracken_files, abundance_dir) if abundance is not None: completed.append("species abundance matrix for Tool 2") elif bracken_files: skipped.append("abundance matrix construction (dry run)") else: skipped.append("abundance matrix because no Kraken2/Bracken output was produced") write_methods(run_dir, params, completed, skipped) summary = { "run_id": run_id, "status": "completed", "elapsed_seconds": round(time.time() - started, 2), "sample_count": len(samples), "completed_modules": completed, "skipped_modules": skipped, "warnings": warnings, "next_step": "Feed species_relative_abundance.tsv (or species_estimated_reads.tsv) from 10_Abundance_Matrix, together with samplesheet_resolved.csv, into Tool 2 (statistics and reporting).", } (run_dir / "analysis_summary.json").write_text(json.dumps(summary, indent=2), encoding="utf-8") zip_path = make_zip(run_dir) status_df = pd.DataFrame([ {"Category": "Run", "Item": "Run ID", "Value": run_id}, {"Category": "Run", "Item": "Samples", "Value": len(samples)}, {"Category": "Run", "Item": "Mode", "Value": analysis_mode}, {"Category": "Run", "Item": "Elapsed", "Value": f"{summary['elapsed_seconds']} s"}, {"Category": "Modules", "Item": "Completed", "Value": "; ".join(completed)}, {"Category": "Modules", "Item": "Skipped", "Value": "; ".join(skipped) or "None"}, {"Category": "Warnings", "Item": "Input/analysis warnings", "Value": "; ".join(warnings) or "None"}, {"Category": "Next step", "Item": "Tool 2 input files", "Value": "10_Abundance_Matrix/species_relative_abundance.tsv + samplesheet_resolved.csv"}, ]) md = f"### Sequence processing completed\n**Run:** `{run_id}` \n**Samples:** {len(samples)} \n**Mode:** {analysis_mode} \n**Results:** complete run directory packaged as ZIP. Use `10_Abundance_Matrix/species_relative_abundance.tsv` and `samplesheet_resolved.csv` as input to Tool 2." return md, status_df, tail_log(log), str(zip_path) except Exception as exc: with log.open("a", encoding="utf-8") as fh: fh.write("\nERROR\n") fh.write(traceback.format_exc()) try: zip_path = make_zip(run_dir) zip_value = str(zip_path) except Exception: zip_value = None status_df = pd.DataFrame([{"Category": "Error", "Item": type(exc).__name__, "Value": str(exc)}]) return f"### Analysis stopped\n{type(exc).__name__}: {exc}", status_df, tail_log(log), zip_value def refresh_status(): return module_status_dataframe() DESCRIPTION = """ **Tool 1 of 2.** Upload shotgun metagenomic FASTQ files and optional metadata. The application executes a modular read based, assembly based, genome resolved, and functional workflow according to the selected analysis mode, and finishes by building a species abundance matrix. For multiple samples, upload a CSV or TSV containing at least `Sample_ID`, `Read_1`, and optionally `Read_2`, `Group`, `Condition`, `Location`, `Time_point`, `Replicate`, `Sequencing_platform`, and `Library_type`. The FASTQ file names in the metadata must match the uploaded file names. Database dependent modules are run only when their Space environment variables point to valid mounted database directories. The app never silently downloads large scientific databases during an analysis run. **Hand off to Tool 2:** the results ZIP contains `10_Abundance_Matrix/species_relative_abundance.tsv`, `10_Abundance_Matrix/species_estimated_reads.tsv`, and `samplesheet_resolved.csv`. Upload these into Tool 2 (statistics and reporting) to get diversity statistics, exploratory differential abundance, exploratory machine learning, and a publication ready output package. """ with gr.Blocks(title=APP_TITLE) as demo: gr.Markdown(f"# {APP_TITLE}\n**Version {APP_VERSION}**\n\n{DESCRIPTION}") with gr.Tab("Run sequence processing"): with gr.Row(): with gr.Column(scale=2): fastq_files = gr.File(label="FASTQ / FASTQ.GZ files", file_count="multiple", file_types=[".fastq", ".fq", ".gz"], type="filepath") metadata_file = gr.File(label="Metadata CSV/TSV (recommended for multiple samples)", file_types=[".csv", ".tsv", ".txt"], type="filepath") host_file = gr.File(label="Optional host reference FASTA", file_types=[".fa", ".fasta", ".fna", ".gz"], type="filepath") with gr.Column(scale=1): analysis_mode = gr.Dropdown( choices=["Basic", "Comprehensive", "Genome resolved", "Complete"], value="Complete", label="Analysis mode", ) threads = gr.Slider(1, max(2, min(16, os.cpu_count() or 2)), value=DEFAULT_THREADS, step=1, label="CPU threads") host_removal = gr.Checkbox(value=False, label="Remove host reads") dry_run = gr.Checkbox(value=False, label="Dry run: write commands without executing") with gr.Accordion("Scientific parameters", open=False): with gr.Row(): min_quality = gr.Slider(10, 35, value=20, step=1, label="Minimum base quality (fastp)") min_read_length = gr.Slider(30, 150, value=50, step=5, label="Minimum retained read length, bp") max_n_bases = gr.Slider(0, 20, value=5, step=1, label="Maximum N bases per read (absolute count)") trim_poly_g = gr.Checkbox(value=True, label="Trim poly-G") kraken_confidence = gr.Slider(0.0, 1.0, value=0.10, step=0.01, label="Kraken2 confidence") with gr.Row(): bracken_level = gr.Dropdown(choices=["P", "C", "O", "F", "G", "S"], value="S", label="Bracken taxonomic level") min_bracken_reads = gr.Slider(1, 100, value=10, step=1, label="Minimum Bracken reads") min_contig_length = gr.Slider(500, 5000, value=1000, step=100, label="Minimum assembly contig length, bp") run_button = gr.Button("Run sequence processing workflow", variant="primary") summary_output = gr.Markdown() status_output = gr.Dataframe(label="Run summary", interactive=False) log_output = gr.Textbox(label="Pipeline log", lines=18, max_lines=30) download_output = gr.File(label="Download complete results ZIP") run_button.click( fn=run_pipeline, inputs=[ fastq_files, metadata_file, host_file, analysis_mode, threads, min_quality, min_read_length, max_n_bases, trim_poly_g, kraken_confidence, bracken_level, min_bracken_reads, min_contig_length, host_removal, dry_run, ], outputs=[summary_output, status_output, log_output, download_output], ) with gr.Tab("System and database status"): gr.Markdown("This table shows which executables and external databases are available inside the running Space.") status_table = gr.Dataframe(value=module_status_dataframe(), interactive=False, label="Module status") refresh_button = gr.Button("Refresh status") refresh_button.click(fn=refresh_status, outputs=status_table) with gr.Tab("Output structure"): gr.Markdown(""" ``` run__/ ├── 00_Input/ ├── 01_QC/ ├── 02_Host_Removal/ ├── 03_Taxonomy/ ├── 04_Assembly/ ├── 05_Assembly_QC/ ├── 06_MAGs/ ├── 07_Genes_Function/ ├── 08_Resistome_Virulome/ ├── 09_Viruses_Plasmids/ ├── 10_Abundance_Matrix/ │ ├── species_relative_abundance.tsv <- Tool 2 input │ └── species_estimated_reads.tsv <- Tool 2 input (optional, enables Chao1) ├── run_manifest.json ├── parameters.yaml ├── software_versions.tsv ├── database_versions.tsv ├── samplesheet_resolved.csv <- Tool 2 input ├── methods.txt ├── analysis_summary.json └── pipeline.log ``` """) if __name__ == "__main__": demo.queue(default_concurrency_limit=1, max_size=8).launch( server_name="0.0.0.0", server_port=int(os.getenv("PORT", "7860")), show_error=True, )