Spaces:
Build error
Build error
Update app.py
Browse files1234567891011121314151617181920212223242549 unmodified lines7576777879808146 unmodified lines12812913013113213313413513613713813914014114214314414514614711 unmodified lines15916016116216316416570 unmodified lines236237238239from __future__ import annotationsimport osimport shutilimport tempfileimport zipfilefrom datetime import datetime, timezonefrom pathlib import Pathimport pandas as pdimport streamlit as stfrom woloji import __version__from woloji.io import auto_samples, samples_from_metadata, save_uploadsfrom woloji.pipeline import run_pipelinefrom woloji.tooling import database_rows, status_rowsfrom woloji.utils import safe_namest.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-oriented bacterial whole-genome analysis")with st.expander("Scope and interpretation", expanded=False):st.write(49 unmodified linesreference = 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(timezone.utc).strftime('%Y%m%d_%H%M%S')}")run = st.button("Run WOLOJI analysis", type="primary", use_container_width=True)if run:46 unmodified linesevents.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, "annotation": annotation, "composition": composition,"functional": functional, "amr": amr, "virulence": virulence,"secondary": secondary, "mobileome": mobileome, "mlst": mlst,"cgmlst": cgmlst, "pangenome": pangenome,"phylogenomics": phylogenomics, "population": population,}params = {"threads": threads, "memory_gb": memory_gb, "assembly_mode": assembly_mode,"annotation_engine": annotation_engine, "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,11 unmodified lineswith utilities_tab:from woloji.utilities import design_primers, local_blast, phyloforge, fasta_first_sequenceu1,u2,u3 = st.tabs(["Primer design", "GeneClean-BLAST", "PhyloForge"])with u1:st.markdown("#### Primer Design Tool")70 unmodified lines### 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.""")12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596649 unmodified lines101610171018101910201021102246 unmodified lines1069107010711072107310741075107610771078107910801081108211 unmodified lines10941095109610971098109970 unmodified lines1170117111721173"""WOLOJI Comprehensive Bacterial Genomics SuiteSingle-file build (merged from the woloji/ package + app.py) for deploymentsthat require one script. Generated from WOLOJI v2.0.1."""from __future__ import annotationsimport gzipimport hashlibimport jsonimport mathimport osimport reimport shutilimport subprocessimport tempfileimport zipfilefrom collections import Counter, defaultdictfrom collections.abc import Callable, Sequencefrom dataclasses import asdict, dataclassfrom datetime import UTC, datetimefrom pathlib import Pathimport matplotlibimport numpy as npimport pandas as pdimport streamlit as stfrom Bio import SeqIOmatplotlib.use("Agg")import matplotlib.pyplot as plt__version__ = "2.0.1"# =============================================================================# woloji/models.py -- data model# =============================================================================@dataclassclass Sample:sample_id: strread1: Path | None = Noneread2: Path | None = Nonelong_reads: Path | None = Noneassembly: Path | None = Nonegenus: str = ""species: str = ""@propertydef has_short_reads(self) -> bool:return self.read1 is not None@propertydef has_paired_reads(self) -> bool:return self.read1 is not None and self.read2 is not None@propertydef 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:breakh.update(chunk)return h.hexdigest()def command_exists(name: str) -> bool:return shutil.which(name) is not Nonedef 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 = 0seq_len = 0with open_text(path) as fh:cur = 0for raw in fh:line = raw.strip()if not line:continueif line.startswith(">"):if cur:lengths.append(cur)cur = 0continues = 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 + tgc = 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.0cum = 0n50 = l50 = 0for i, length in enumerate(ordered, start=1):cum += lengthif cum >= target:n50, l50 = length, ibreakreturn {"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: strcommand: list[str]returncode: intstarted_at: strfinished_at: strstdout_path: strstderr_path: strskipped: bool = Falsereason: 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_runself.timeout = timeoutself.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 recdef 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 recproc_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 recdef 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 / nametarget.write_bytes(uploaded.getvalue())mapping[name] = targetif name.lower().endswith(".zip"):with zipfile.ZipFile(target) as zf:for info in zf.infolist():if info.is_dir():continuebase = os.path.basename(info.filename)if not base:continueout = input_dir / baseout.write_bytes(zf.read(info.filename))mapping[base] = outreturn mappingdef _find_name(mapping: dict[str, Path], value: str | float | None):if value is None or (isinstance(value, float) and pd.isna(value)):return Nonevalue = str(value).strip()if not value:return Nonebase = 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 samplesdef _stem_without_ext(name: str) -> str:x = namefor 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).stemdef 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 = Falsefor 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 = pathelse: s.read2 = pathused.add(name); matched = True; breakif 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 = pathused.add(name)for name, path in fastas.items():sid = safe_name(_stem_without_ext(name))samples.setdefault(sid, Sample(sample_id=sid)).assembly = pathreturn 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"],"Bakta": ["bakta", "--version"],"Prokka": ["prokka", "--version"],"eggNOG-mapper": ["emapper.py", "--version"],"AMRFinderPlus": ["amrfinder", "--version"],"ABRicate": ["abricate", "--version"],"antiSMASH": ["antismash", "--version"],"MOB-suite": ["mob_recon", "--version"],"geNomad": ["genomad", "--version"],"IntegronFinder": ["integron_finder", "--version"],"MinCED": ["minced", "--version"],"mlst": ["mlst", "--version"],"chewBBACA": ["chewBBACA.py", "--version"],"Panaroo": ["panaroo", "--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 = {"Bakta": "BAKTA_DB","GTDB-Tk": "GTDBTK_DATA_PATH","CheckM2": "CHECKM2DB","eggNOG-mapper": "EGGNOG_DATA_DIR","geNomad": "GENOMAD_DB","MOB-suite": "MOB_SUITE_DB","VFDB/ABRicate": "ABRICATE_DB_DIR",}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 rowsdef 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 pltdef assembly_summary_plot(df: pd.DataFrame, out: Path):if df.empty: returnfig, 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: returnfig, 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/codon.py -- codon usage / RSCU / ENc analysis# =============================================================================matplotlib.use("Agg")import matplotlib.pyplot as pltfrom Bio import SeqIOGENETIC_CODE = {"TTT":"F","TTC":"F","TTA":"L","TTG":"L","TCT":"S","TCC":"S","TCA":"S","TCG":"S","TAT":"Y","TAC":"Y","TAA":"*","TAG":"*","TGT":"C","TGC":"C","TGA":"*","TGG":"W","CTT":"L","CTC":"L","CTA":"L","CTG":"L","CCT":"P","CCC":"P","CCA":"P","CCG":"P","CAT":"H","CAC":"H","CAA":"Q","CAG":"Q","CGT":"R","CGC":"R","CGA":"R","CGG":"R","ATT":"I","ATC":"I","ATA":"I","ATG":"M","ACT":"T","ACC":"T","ACA":"T","ACG":"T","AAT":"N","AAC":"N","AAA":"K","AAG":"K","AGT":"S","AGC":"S","AGA":"R","AGG":"R","GTT":"V","GTC":"V","GTA":"V","GTG":"V","GCT":"A","GCC":"A","GCA":"A","GCG":"A","GAT":"D","GAC":"D","GAA":"E","GAG":"E","GGT":"G","GGC":"G","GGA":"G","GGG":"G",}AA_TO_CODONS = defaultdict(list)for c,a in GENETIC_CODE.items():if a != "*": AA_TO_CODONS[a].append(c)def _enc(counts: Counter) -> float:family_f = defaultdict(list)for codons in AA_TO_CODONS.values():if len(codons) <= 1: continuetotal = sum(counts.get(c,0) for c in codons)if total <= 1: continuep2 = sum((counts.get(c,0)/total)**2 for c in codons)F = (total*p2 - 1)/(total-1)if F > 0: family_f[len(codons)].append(F)def mf(k):vals = family_f.get(k, [])return float(np.mean(vals)) if vals else np.nanvals = [mf(2),mf(3),mf(4),mf(6)]available = [x for x in vals if not np.isnan(x) and x > 0]if not available: return np.nanfallback = float(np.mean(available))F2,F3,F4,F6 = [x if not np.isnan(x) and x>0 else fallback for x in vals]return float(min(max(2 + 9/F2 + 1/F3 + 5/F4 + 3/F6,20),61))def analyse_ffn(ffn: Path, outdir: Path, min_codons: int = 30):outdir.mkdir(parents=True, exist_ok=True)global_counts = Counter(); gene_rows=[]for rec in SeqIO.parse(str(ffn), "fasta"):s = str(rec.seq).upper().replace("U","T")usable = len(s) - len(s)%3s = s[:usable]if usable < min_codons*3: continuecounts=Counter(); pos_gc=[0,0,0]; pos_n=[0,0,0]; ncod=0for i in range(0, usable, 3):codon=s[i:i+3]if len(codon)!=3 or any(b not in "ACGT" for b in codon): continueaa=GENETIC_CODE.get(codon)if aa is None: continuefor j,b in enumerate(codon):pos_n[j]+=1if b in "GC": pos_gc[j]+=1if aa != "*": counts[codon]+=1; global_counts[codon]+=1ncod+=1if ncod == 0: continuegc1=100*pos_gc[0]/pos_n[0] if pos_n[0] else np.nangc2=100*pos_gc[1]/pos_n[1] if pos_n[1] else np.nangc3=100*pos_gc[2]/pos_n[2] if pos_n[2] else np.nangene_rows.append({"gene_id":rec.id,"codons":ncod,"GC1_percent":gc1,"GC2_percent":gc2,"GC3_percent":gc3,"GC12_percent":np.nanmean([gc1,gc2]),"ENc":_enc(counts)})per_gene=pd.DataFrame(gene_rows)rscu=[]for aa,codons in sorted(AA_TO_CODONS.items()):total=sum(global_counts.get(c,0) for c in codons)expected=total/len(codons) if codons else 0for c in codons:rscu.append({"amino_acid":aa,"codon":c,"count":global_counts.get(c,0),"RSCU":global_counts.get(c,0)/expected if expected else 0})rscu_df=pd.DataFrame(rscu)per_gene.to_csv(outdir/"per_gene_codon_metrics.csv",index=False)rscu_df.to_csv(outdir/"rscu.csv",index=False)pd.DataFrame([{"CDS_analysed":len(per_gene),"genome_ENc":_enc(global_counts)}]).to_csv(outdir/"codon_summary.csv",index=False)if not per_gene.empty:fig,ax=plt.subplots(figsize=(6.5,5))ax.scatter(per_gene["GC3_percent"]/100,per_gene["ENc"],s=12,alpha=.55)x=np.linspace(0.001,.999,300); expected=2+x+29/(x*x+(1-x)*(1-x))ax.plot(x,expected,linestyle="--",linewidth=1.2)ax.set_xlabel("GC3 fraction");ax.set_ylabel("Effective number of codons (ENc)");ax.set_title("ENc plot")fig.tight_layout();fig.savefig(outdir/"enc_plot.png",dpi=600,bbox_inches="tight");plt.close(fig)valid=per_gene.dropna(subset=["GC3_percent","GC12_percent"])if len(valid)>=3:x=valid["GC3_percent"].to_numpy()/100;y=valid["GC12_percent"].to_numpy()/100slope,intercept=np.polyfit(x,y,1);pred=slope*x+interceptssr=np.sum((y-pred)**2);sst=np.sum((y-y.mean())**2);r2=1-ssr/sst if sst else np.nanfig,ax=plt.subplots(figsize=(6.5,5));ax.scatter(x,y,s=12,alpha=.55);order=np.argsort(x);ax.plot(x[order],pred[order],linestyle="--")ax.set_xlabel("GC3 fraction");ax.set_ylabel("GC12 fraction");ax.set_title(f"Neutrality plot: slope={slope:.3f}, R²={r2:.3f}")fig.tight_layout();fig.savefig(outdir/"neutrality_plot.png",dpi=600,bbox_inches="tight");plt.close(fig)return {"per_gene":per_gene,"rscu":rscu_df}# =============================================================================# 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 primer3seq=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","annotation_engine": "Auto","ani_min_fraction": 15,"vfdb_min_identity": 90,"vfdb_min_coverage": 80,"panaroo_clean_mode": "strict","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, Noneqc = out / "01_read_qc" / sample.sample_idqc.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 Nonecmd = ["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.read2reads = [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, r2def _polypolish(sample_id: str, draft: Path, r1: Path, r2: Path, out: Path, runner: Runner, threads: int):pol = out / "03_polishing" / sample_idpol.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 polisheddef _assemble(sample: Sample, r1: Path | None, r2: Path | None, out: Path, runner: Runner, p: dict):if sample.assembly:return sample.assemblyasm_root = out / "02_assembly" / sample.sample_idasm_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 draftif 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 Nonedef _quast(sample_id, assembly, out, runner, threads):qout = out / "04_assembly_qc" / "quast" / sample_idrunner.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_idindir = 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 _annotate(sample: Sample, assembly: Path, out: Path, runner: Runner, p: dict):root = out / "06_annotation" / sample.sample_idroot.mkdir(parents=True, exist_ok=True)engine = p["annotation_engine"]bakta_db = os.getenv("BAKTA_DB", "")if engine in {"Auto", "Bakta"} and command_exists("bakta") and bakta_db and Path(bakta_db).exists():cmd = ["bakta", "--db", bakta_db, "--output", root / "bakta", "--prefix", sample.sample_id,"--threads", p["threads"], assembly]runner.run(f"{sample.sample_id}_bakta", cmd)return {"engine": "Bakta", "gff": root/"bakta"/f"{sample.sample_id}.gff3", "faa": root/"bakta"/f"{sample.sample_id}.faa", "ffn": root/"bakta"/f"{sample.sample_id}.ffn"}cmd = ["prokka", "--outdir", root / "prokka", "--prefix", sample.sample_id, "--cpus", p["threads"],"--kingdom", "Bacteria"]if sample.genus: cmd += ["--genus", sample.genus]if sample.species: cmd += ["--species", sample.species]cmd += [assembly]runner.run(f"{sample.sample_id}_prokka", cmd)return {"engine": "Prokka", "gff": root/"prokka"/f"{sample.sample_id}.gff", "faa": root/"prokka"/f"{sample.sample_id}.faa", "ffn": root/"prokka"/f"{sample.sample_id}.ffn"}def _amr(sample_id, assembly, out, runner, threads):aout = out / "09_amr" / sample_id; aout.mkdir(parents=True, exist_ok=True)runner.run(f"{sample_id}_amrfinder", ["amrfinder", "-n", assembly, "--plus", "--threads", threads, "-o", aout/"amrfinder.tsv"])def _virulence(sample_id, assembly, out, runner, p):vout = out / "10_virulence" / sample_id; vout.mkdir(parents=True, exist_ok=True)cmd = ["abricate", "--db", "vfdb", "--minid", p["vfdb_min_identity"], "--mincov", p["vfdb_min_coverage"]]datadir = os.getenv("ABRICATE_DB_DIR", "")if datadir: cmd += ["--datadir", datadir]cmd += [assembly]runner.run(f"{sample_id}_vfdb", cmd, stdout_file=vout/"vfdb.tsv")def _antismash(sample_id, assembly, out, runner, threads):aout = out / "11_secondary_metabolites" / sample_idrunner.run(f"{sample_id}_antismash", ["antismash", assembly, "--output-dir", aout, "--cpus", threads, "--taxon", "bacteria"])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 _eggnog(sample_id, faa, out, runner, threads):if not faa: returnroot = out / "08_functional" / sample_id; root.mkdir(parents=True, exist_ok=True)data_dir = os.getenv("EGGNOG_DATA_DIR", "")cmd = ["emapper.py", "-i", faa, "--itype", "proteins", "-o", sample_id, "--output_dir", root,"--cpu", threads, "--override"]if data_dir: cmd += ["--data_dir", data_dir]runner.run(f"{sample_id}_eggnog", cmd)def _gtdbtk(assemblies: dict[str, Path], out: Path, runner: Runner, threads: int):if not assemblies: returnroot = 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")returnrunner.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: returnroot = 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 _panaroo(annotations: dict[str, dict], out: Path, runner: Runner, threads: int, clean_mode: str):gffs = [str(v["gff"]) for v in annotations.values() if v and Path(v["gff"]).exists()]if len(gffs) < 2:runner.skip("panaroo", ["panaroo"], "Panaroo requires at least two valid GFF annotations")returnroot = out / "14_pangenome" / "panaroo"runner.run("panaroo", ["panaroo", "-i", *gffs, "-o", root, "--clean-mode", clean_mode,"--remove-invalid-genes", "-a", "core", "--aligner", "mafft", "-t", threads])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")returnroot = 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")returnroot = out / "16_phylogenomics"; snippy_dirs = []for s in samples:asm = assemblies.get(s.sample_id)if asm is None: continueod = 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: returncore = 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 alniqdir = 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")returnroot = 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 targetdef 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] = {}; annotations: dict[str, dict] = {}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.read2if 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.assemblyif 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")continueassemblies[sample.sample_id] = asmif 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("annotation", True): annotations[sample.sample_id] = _annotate(sample, asm, run_dir, runner, p)if modules.get("composition", True) and annotations.get(sample.sample_id,{}).get("ffn"):ffn = Path(annotations[sample.sample_id]["ffn"])if ffn.exists() and not runner.dry_run: analyse_ffn(ffn, run_dir/"07_composition_codon"/sample.sample_id)if modules.get("functional", False): _eggnog(sample.sample_id, annotations.get(sample.sample_id,{}).get("faa"), run_dir, runner, p["threads"])if modules.get("amr", True): _amr(sample.sample_id, asm, run_dir, runner, p["threads"])if modules.get("virulence", True): _virulence(sample.sample_id, asm, run_dir, runner, p)if modules.get("secondary", False): _antismash(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("pangenome", True): _panaroo(annotations, run_dir, runner, p["threads"], p["panaroo_clean_mode"])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 ["BAKTA_DB","GTDBTK_DATA_PATH","CHECKM2DB","EGGNOG_DATA_DIR","GENOMAD_DB","MOB_SUITE_DB","ABRICATE_DB_DIR"]},"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# =============================================================================import osimport shutilimport tempfileimport zipfilefrom datetime import UTC, datetimefrom pathlib import Pathimport pandas as pdimport streamlit as stst.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(49 unmodified linesreference = 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:46 unmodified linesevents.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, "annotation": annotation, "composition": composition,"functional": functional, "amr": amr, "virulence": virulence, "secondary": secondary,"mobileome": mobileome, "mlst": mlst, "cgmlst": cgmlst, "pangenome": pangenome,"phylogenomics": phylogenomics, "population": population}params = {"threads": threads, "memory_gb": memory_gb, "assembly_mode": assembly_mode,"annotation_engine": annotation_engine, "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,11 unmodified lineswith utilities_tab:u1,u2,u3 = st.tabs(["Primer design", "GeneClean-BLAST", "PhyloForge"])with u1:st.markdown("#### Primer Design Tool")70 unmodified lines### 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.py+958-24