Spaces:
Sleeping
Sleeping
Update app.py
Browse files7 unmodified lines8910111213148 unmodified lines2324252627282930315 unmodified lines37383940414214 unmodified lines57585960616245 unmodified lines10810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415530 unmodified lines186187188189190191130 unmodified lines32232332432532632732832933033133246 unmodified lines379380381382383384385386387102 unmodified lines4904914924937 unmodified linesbundles all results into a single downloadable archive suitable for amethodological paper.It keeps the existing annotation_core workflow and adds a genome_analysis layer."""import os8 unmodified linesfrom annotation_core import (allowed_fasta,compute_basic_genome_stats,parse_prokka_summary,run_prokka_annotation,save_uploaded_file,validate_fasta,)5 unmodified linesga.set_publication_style()# ----------------------------------------------------------------------------# Session state# ----------------------------------------------------------------------------14 unmodified lines"figure_paths": {},"log_text": "","run_success": False,"fasta_path": None,}45 unmodified linesreturn df.to_csv(index=False).encode("utf-8")def build_results_bundle(job_dir, figure_dir):"""Zip all tables, figures, and the methods text into one archive."""buffer = io.BytesIO()with zipfile.ZipFile(buffer, "w", zipfile.ZIP_DEFLATED) as zf:# Tablestable_map = {"tables/assembly_statistics.csv": st.session_state.assembly_table,"tables/per_contig_statistics.csv": st.session_state.per_contig,"tables/annotation_summary.csv": st.session_state.summary_df,"tables/feature_counts.csv": st.session_state.feature_counts,"tables/codon_usage.csv": st.session_state.codon_table,"tables/amino_acid_composition.csv": st.session_state.aa_table,}for name, df in table_map.items():if df is not None and not df.empty:zf.writestr(name, df.to_csv(index=False))# Figures (PNG and PDF)fig_dir = Path(figure_dir)if fig_dir.exists():for f in fig_dir.glob("*.png"):zf.write(f, f"figures/{f.name}")for f in fig_dir.glob("*.pdf"):zf.write(f, f"figures/{f.name}")# Methods textzf.writestr("methods_summary.txt", build_methods_text())buffer.seek(0)return buffer.read()def build_methods_text():s = st.session_state.stats or {}cd = st.session_state.coding_density or 0.0hyp = st.session_state.hypotheticalstrand = st.session_state.strand or {"+": 0, "-": 0}lines = ["Genome annotation and analysis methods summary","=" * 50,"","The genome was annotated with Prokka using default settings.","Assembly metrics, base composition, coding density, codon usage,","and amino acid composition were computed with the Genome Annotation","and Analysis Workbench.",30 unmodified linesreturn "\n".join(lines)def run_full_analysis(fasta_path, prokka_outdir, prefix, figure_dir):"""Run all genome analyses and generate figures. Stores results in session."""Path(figure_dir).mkdir(parents=True, exist_ok=True)130 unmodified lines)st.session_state.log_text = result.get("log", "")if not result.get("success", False):st.error("Annotation failed. Review the log below.")else:summary = parse_prokka_summary(result["outdir"], safe_prefix)st.session_state.summary_df = pd.DataFrame([{"Feature": "Genes", "Count": summary.get("genes", 0)},{"Feature": "CDS", "Count": summary.get("CDS", 0)},46 unmodified linesm5, m6, m7, m8 = st.columns(4)m5.metric("Coding density", f"{cd:.1f}%")if st.session_state.summary_df is not None:cds_n = int(st.session_state.summary_df.set_index("Feature").loc["CDS", "Count"])m6.metric("CDS", f"{cds_n:,}")if st.session_state.hypothetical:m7.metric("Hypothetical CDS", f"{st.session_state.hypothetical[0]:.1f}%")m8.metric("Largest contig (bp)", f"{s['largest_contig_bp']:,}")102 unmodified linesif st.session_state.log_text:with st.expander("View Prokka log"):st.text(st.session_state.log_text)7 unmodified lines891011121314151617181920212223248 unmodified lines333435363738395 unmodified lines4546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114 unmodified lines15615715815916016116245 unmodified lines20820921021121221321421521621721821922022122222322422522622722822923030 unmodified lines261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295130 unmodified lines42642742842943043143243343443543643743843944044144244344444544644744846 unmodified lines495496497498499500501502503504505506102 unmodified lines6096106116127 unmodified linesbundles all results into a single downloadable archive suitable for amethodological paper.The Prokka step is robust. It tries a full annotation first. If the productsearch step fails (the common "Could not run command ... parallel ... blastp"error), it retries once with --noanno so gene prediction still completes and theoutput files are written. The analysis layer then runs in either case.Files needed on the Space:app.py (this file)genome_analysis.py (analysis and figures module)annotation_core.py (your existing helpers)requirements.txtpackages.txt or a Docker image that provides Prokka"""import os8 unmodified linesfrom annotation_core import (allowed_fasta,parse_prokka_summary,save_uploaded_file,validate_fasta,)5 unmodified linesga.set_publication_style()# ----------------------------------------------------------------------------# Robust Prokka runner (full annotation, then --noanno fallback)# ----------------------------------------------------------------------------def _build_prokka_command(fasta_path, outdir, prefix, genus, species, cpus, noanno):cmd = ["prokka","--outdir", str(outdir),"--prefix", str(prefix),"--force","--cpus", str(cpus),]if genus:cmd += ["--genus", str(genus)]if species:cmd += ["--species", str(species)]if noanno:cmd += ["--noanno"]cmd += [str(fasta_path)]return cmddef _prokka_outputs_present(outdir, prefix):"""Check that the core files the analysis needs were written."""outdir = Path(outdir)for ext in ["gff", "ffn", "faa"]:if (outdir / f"{prefix}.{ext}").exists():continueif list(outdir.glob(f"*.{ext}")):continuereturn Falsereturn Truedef _run_prokka_once(fasta_path, outdir, prefix, genus, species, cpus, noanno):cmd = _build_prokka_command(fasta_path, outdir, prefix, genus, species, cpus, noanno)proc = subprocess.run(cmd, capture_output=True, text=True, check=False)log = ("COMMAND:\n" + " ".join(cmd) + "\n\n""STDOUT:\n" + (proc.stdout or "") + "\n\n""STDERR:\n" + (proc.stderr or ""))ok = proc.returncode == 0 and _prokka_outputs_present(outdir, prefix)return ok, logdef run_prokka_annotation(fasta_path, outdir, prefix, genus="", species="", cpus=2):"""Run Prokka with a safe fallback. Always tries to leave usable output.Returns {"success": bool, "outdir": str, "log": str, "mode": str}where mode is 'full', 'noanno', or 'failed'."""outdir = Path(outdir)outdir.mkdir(parents=True, exist_ok=True)# Attempt 1: full annotationok, log_full = _run_prokka_once(fasta_path, outdir, prefix, genus, species,cpus, noanno=False)if ok:return {"success": True, "outdir": str(outdir),"log": log_full, "mode": "full"}# Clean the directory before the retry so --force has a clean slateif outdir.exists():shutil.rmtree(outdir)outdir.mkdir(parents=True, exist_ok=True)# Attempt 2: gene prediction only, no BLAST product search, single cpuok2, log_noanno = _run_prokka_once(fasta_path, outdir, prefix, genus, species,cpus=1, noanno=True)combined_log = ("FIRST ATTEMPT (full annotation) FAILED.\n""The product search step did not complete. Common causes are a GNU ""parallel version mismatch, low memory, or a missing BLAST database.\n""Retried with --noanno so gene prediction still completes.\n"+ "=" * 70 + "\n"+ log_full+ "\n" + "=" * 70 + "\n"+ "SECOND ATTEMPT (--noanno):\n"+ log_noanno)if ok2:return {"success": True, "outdir": str(outdir),"log": combined_log, "mode": "noanno"}return {"success": False, "outdir": str(outdir),"log": combined_log, "mode": "failed"}# ----------------------------------------------------------------------------# Session state# ----------------------------------------------------------------------------14 unmodified lines"figure_paths": {},"log_text": "","run_success": False,"run_mode": None,"fasta_path": None,}45 unmodified linesreturn df.to_csv(index=False).encode("utf-8")def build_methods_text():s = st.session_state.stats or {}cd = st.session_state.coding_density or 0.0hyp = st.session_state.hypotheticalstrand = st.session_state.strand or {"+": 0, "-": 0}mode = st.session_state.run_mode or "full"lines = ["Genome annotation and analysis methods summary","=" * 50,"","The genome was annotated with Prokka.",]if mode == "noanno":lines.append("Note: product search did not complete on the host, so ""Prokka ran in --noanno mode. Gene prediction is intact, ""but CDS product names are not available.")lines += ["Assembly metrics, base composition, coding density, codon usage,","and amino acid composition were computed with the Genome Annotation","and Analysis Workbench.",30 unmodified linesreturn "\n".join(lines)def build_results_bundle(job_dir, figure_dir):"""Zip all tables, figures, and the methods text into one archive."""buffer = io.BytesIO()with zipfile.ZipFile(buffer, "w", zipfile.ZIP_DEFLATED) as zf:table_map = {"tables/assembly_statistics.csv": st.session_state.assembly_table,"tables/per_contig_statistics.csv": st.session_state.per_contig,"tables/annotation_summary.csv": st.session_state.summary_df,"tables/feature_counts.csv": st.session_state.feature_counts,"tables/codon_usage.csv": st.session_state.codon_table,"tables/amino_acid_composition.csv": st.session_state.aa_table,}for name, df in table_map.items():if df is not None and not df.empty:zf.writestr(name, df.to_csv(index=False))fig_dir = Path(figure_dir)if fig_dir.exists():for f in fig_dir.glob("*.png"):zf.write(f, f"figures/{f.name}")for f in fig_dir.glob("*.pdf"):zf.write(f, f"figures/{f.name}")zf.writestr("methods_summary.txt", build_methods_text())buffer.seek(0)return buffer.read()def run_full_analysis(fasta_path, prokka_outdir, prefix, figure_dir):"""Run all genome analyses and generate figures. Stores results in session."""Path(figure_dir).mkdir(parents=True, exist_ok=True)130 unmodified lines)st.session_state.log_text = result.get("log", "")st.session_state.run_mode = result.get("mode")if not result.get("success", False):st.error("Annotation failed in both full and fallback modes. ""Review the log below.")else:if result.get("mode") == "noanno":st.warning("The full product search did not complete on the ""host, so Prokka ran in fallback mode (--noanno). ""Gene prediction, assembly metrics, codon usage, ""and composition are all valid. CDS product names ""are not available. See the log for the cause.")try:summary = parse_prokka_summary(result["outdir"], safe_prefix)except Exception:summary = {}st.session_state.summary_df = pd.DataFrame([{"Feature": "Genes", "Count": summary.get("genes", 0)},{"Feature": "CDS", "Count": summary.get("CDS", 0)},46 unmodified linesm5, m6, m7, m8 = st.columns(4)m5.metric("Coding density", f"{cd:.1f}%")if st.session_state.summary_df is not None:try:cds_n = int(st.session_state.summary_df.set_index("Feature").loc["CDS", "Count"])m6.metric("CDS", f"{cds_n:,}")except Exception:passif st.session_state.hypothetical:m7.metric("Hypothetical CDS", f"{st.session_state.hypothetical[0]:.1f}%")m8.metric("Largest contig (bp)", f"{s['largest_contig_bp']:,}")102 unmodified linesif st.session_state.log_text:with st.expander("View Prokka log"):st.text(st.session_state.log_text)
app.py+161-42