Spaces:
Sleeping
Sleeping
Update app.py
Browse files16 unmodified lines17181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261273 unmodified lines13113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325416 unmodified linesst.set_page_config(page_title="Genome Annotation Workbench", layout="wide")# -----------------------------# Session state initialization# -----------------------------DEFAULT_SESSION_KEYS = {"job_dir": None,"zip_path": None,"summary_df": None,"stats_df": None,"features_df": None,"log_text": "","uploaded_name": None,"run_success": False,}for key, value in DEFAULT_SESSION_KEYS.items():if key not in st.session_state:st.session_state[key] = valuedef reset_results() -> None:"""Clear stored outputs from the current session."""st.session_state.job_dir = Nonest.session_state.zip_path = Nonest.session_state.summary_df = Nonest.session_state.stats_df = Nonest.session_state.features_df = Nonest.session_state.log_text = ""st.session_state.uploaded_name = Nonest.session_state.run_success = Falsedef sanitize_prefix(text: str) -> str:"""Create a filesystem-safe prefix."""safe = "".join(c if c.isalnum() or c in "-_" else "_" for c in text).strip("_")return safe or "sample_genome"def prepare_job_directory(prefix: str) -> Path:"""Create a persistent job directory under /tmp/space_jobs."""work_root = Path("/tmp/space_jobs")work_root.mkdir(parents=True, exist_ok=True)job_dir = work_root / prefixif job_dir.exists():shutil.rmtree(job_dir)job_dir.mkdir(parents=True, exist_ok=True)return job_dir# -----------------------------# Header# -----------------------------st.title("Bacterial Genome Annotation Workbench")st.write("Upload a bacterial genome FASTA file, run Prokka annotation, and review ""genome length, GC%, gene counts, CDS, rRNA, and tRNA summaries.")with st.expander("Accepted input and notes", expanded=False):st.markdown("""- Accepted formats: `.fasta`, `.fa`, `.fna`, `.fas`- Best input: assembled bacterial genome FASTA- This Space uses **Prokka** for annotation and also computes genome statistics directly from the uploaded FASTA- For best results, upload assembled contigs or a finished genome, not raw reads""")# -----------------------------# Input section# -----------------------------col1, col2 = st.columns([2, 1])with col1:uploaded = st.file_uploader("Upload bacterial genome FASTA",type=["fasta", "fa", "fna", "fas"],accept_multiple_files=False,help="Accepted formats: .fasta, .fa, .fna, .fas",)if uploaded is not None:st.success(f"File detected: {uploaded.name}")with col2:prefix = st.text_input("Sample name / prefix", value="sample_genome")genus = st.text_input("Genus", value="Escherichia")species = st.text_input("Species", value="coli")threads = st.number_input("Threads", min_value=1, max_value=8, value=2, step=1)btn_col1, btn_col2 = st.columns([1, 1])run_clicked = btn_col1.button("Run Annotation", type="primary", use_container_width=True)clear_clicked = btn_col2.button("Clear Results", use_container_width=True)# -----------------------------# Clear action# -----------------------------if clear_clicked:reset_results()st.success("Results cleared.")# -----------------------------# Run action# -----------------------------if run_clicked:reset_results()3 unmodified linesst.error("Unsupported file format. Upload .fasta, .fa, .fna, or .fas.")else:safe_prefix = sanitize_prefix(prefix)try:# Create persistent job directoryjob_dir = prepare_job_directory(safe_prefix)# Save uploaded FASTA directly into persistent directoryfasta_path = save_uploaded_file(uploaded, job_dir)# Validate FASTAok, validation_message = validate_fasta(fasta_path)if not ok:st.error(validation_message)else:st.info(validation_message)# Compute direct FASTA-based stats before annotationstats = compute_basic_genome_stats(fasta_path)with st.spinner("Running Prokka annotation. This may take a few minutes depending on genome size."):result = run_prokka_annotation(fasta_path=fasta_path,outdir=job_dir / "prokka_out",prefix=safe_prefix,genus=genus,species=species,cpus=int(threads),)st.session_state.log_text = result.get("log", "")st.session_state.uploaded_name = uploaded.nameif not result.get("success", False):st.error("Annotation failed. Review the log below.")else:summary = parse_prokka_summary(result["outdir"], safe_prefix)stats_df = pd.DataFrame([{"Metric": "Uploaded file", "Value": uploaded.name},{"Metric": "Genome length (bp)", "Value": stats["genome_length_bp"]},{"Metric": "GC content (%)", "Value": round(stats["gc_percent"], 3)},{"Metric": "Number of contigs", "Value": stats["num_contigs"]},{"Metric": "Longest contig (bp)", "Value": stats["longest_contig_bp"]},{"Metric": "N content (%)", "Value": round(stats["n_percent"], 3)},])summary_df = pd.DataFrame([{"Feature": "Genes", "Count": summary.get("genes", 0)},{"Feature": "CDS", "Count": summary.get("CDS", 0)},{"Feature": "rRNA", "Count": summary.get("rRNA", 0)},{"Feature": "tRNA", "Count": summary.get("tRNA", 0)},{"Feature": "tmRNA", "Count": summary.get("tmRNA", 0)},{"Feature": "Repeat regions", "Count": summary.get("repeat_region", 0)},])features_df = summary.get("feature_table", pd.DataFrame())zip_path = job_dir / f"{safe_prefix}_annotation_results.zip"make_download_zip(job_dir / "prokka_out", zip_path)st.session_state.job_dir = str(job_dir)st.session_state.zip_path = str(zip_path)st.session_state.summary_df = summary_dfst.session_state.stats_df = stats_dfst.session_state.features_df = features_dfst.session_state.run_success = Truest.success("Annotation completed successfully.")except Exception as exc:st.error(f"An unexpected error occurred: {exc}")# -----------------------------# Results display# -----------------------------if st.session_state.stats_df is not None:st.subheader("Genome Statistics")st.dataframe(st.session_state.stats_df, use_container_width=True, hide_index=True)if st.session_state.summary_df is not None:st.subheader("Annotation Summary")c1, c2, c3, c4 = st.columns(4)summary_map = {row["Feature"]: int(row["Count"])for _, row in st.session_state.summary_df.iterrows()}c1.metric("Genes", summary_map.get("Genes", 0))c2.metric("CDS", summary_map.get("CDS", 0))c3.metric("rRNA", summary_map.get("rRNA", 0))c4.metric("tRNA", summary_map.get("tRNA", 0))st.dataframe(st.session_state.summary_df, use_container_width=True, hide_index=True)if st.session_state.features_df is not None and not st.session_state.features_df.empty:st.subheader("Feature Counts by Type")st.dataframe(st.session_state.features_df, use_container_width=True, hide_index=True)# -----------------------------# Download section# -----------------------------if st.session_state.zip_path and os.path.exists(st.session_state.zip_path):with open(st.session_state.zip_path, "rb") as fh:st.download_button(label="Download annotation results (.zip)",data=fh.read(),file_name=Path(st.session_state.zip_path).name,mime="application/zip",use_container_width=True,)# -----------------------------# Log display# -----------------------------if st.session_state.log_text:with st.expander("View Prokka log", expanded=False):st.text(st.session_state.log_text)16 unmodified lines171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485863 unmodified lines9091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717816 unmodified linesst.set_page_config(page_title="Genome Annotation Workbench", layout="wide")if "job_dir" not in st.session_state:st.session_state.job_dir = Noneif "zip_path" not in st.session_state:st.session_state.zip_path = Noneif "summary_df" not in st.session_state:st.session_state.summary_df = Noneif "stats_df" not in st.session_state:st.session_state.stats_df = Noneif "features_df" not in st.session_state:st.session_state.features_df = Noneif "log_text" not in st.session_state:st.session_state.log_text = ""if "run_success" not in st.session_state:st.session_state.run_success = Falsedef reset_results():st.session_state.job_dir = Nonest.session_state.zip_path = Nonest.session_state.summary_df = Nonest.session_state.stats_df = Nonest.session_state.features_df = Nonest.session_state.log_text = ""st.session_state.run_success = Falsedef sanitize_prefix(text: str) -> str:safe = "".join(c if c.isalnum() or c in "-_" else "_" for c in text).strip("_")return safe or "sample_genome"st.title("Bacterial Genome Annotation Workbench")st.write("Upload a bacterial genome FASTA file, run Prokka annotation, and review genome statistics and annotation summary.")uploaded = st.file_uploader("Upload bacterial genome FASTA",type=["fasta", "fa", "fna", "fas"],accept_multiple_files=False,key="genome_uploader",)if uploaded is not None:st.success(f"File detected: {uploaded.name}")col1, col2, col3, col4 = st.columns(4)with col1:prefix = st.text_input("Sample name / prefix", value="sample_genome")with col2:genus = st.text_input("Genus", value="Escherichia")with col3:species = st.text_input("Species", value="coli")with col4:threads = st.number_input("Threads", min_value=1, max_value=8, value=2, step=1)b1, b2 = st.columns(2)run_clicked = b1.button("Run Annotation", type="primary", use_container_width=True)clear_clicked = b2.button("Clear Results", use_container_width=True)if clear_clicked:reset_results()st.success("Results cleared.")if run_clicked:reset_results()3 unmodified linesst.error("Unsupported file format. Upload .fasta, .fa, .fna, or .fas.")else:safe_prefix = sanitize_prefix(prefix)work_root = Path("/tmp/space_jobs")work_root.mkdir(parents=True, exist_ok=True)job_dir = work_root / safe_prefixif job_dir.exists():shutil.rmtree(job_dir)job_dir.mkdir(parents=True, exist_ok=True)fasta_path = save_uploaded_file(uploaded, job_dir)ok, validation_message = validate_fasta(fasta_path)if not ok:st.error(validation_message)else:st.info(validation_message)stats = compute_basic_genome_stats(fasta_path)with st.spinner("Running Prokka annotation..."):result = run_prokka_annotation(fasta_path=fasta_path,outdir=job_dir / "prokka_out",prefix=safe_prefix,genus=genus,species=species,cpus=int(threads),)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.stats_df = pd.DataFrame([{"Metric": "Genome length (bp)", "Value": stats["genome_length_bp"]},{"Metric": "GC content (%)", "Value": round(stats["gc_percent"], 3)},{"Metric": "Number of contigs", "Value": stats["num_contigs"]},{"Metric": "Longest contig (bp)", "Value": stats["longest_contig_bp"]},{"Metric": "N content (%)", "Value": round(stats["n_percent"], 3)},])st.session_state.summary_df = pd.DataFrame([{"Feature": "Genes", "Count": summary.get("genes", 0)},{"Feature": "CDS", "Count": summary.get("CDS", 0)},{"Feature": "rRNA", "Count": summary.get("rRNA", 0)},{"Feature": "tRNA", "Count": summary.get("tRNA", 0)},{"Feature": "tmRNA", "Count": summary.get("tmRNA", 0)},{"Feature": "Repeat regions", "Count": summary.get("repeat_region", 0)},])st.session_state.features_df = summary.get("feature_table", pd.DataFrame())zip_path = job_dir / f"{safe_prefix}_annotation_results.zip"make_download_zip(job_dir / "prokka_out", zip_path)st.session_state.job_dir = str(job_dir)st.session_state.zip_path = str(zip_path)st.session_state.run_success = Truest.success("Annotation completed successfully.")if st.session_state.stats_df is not None:st.subheader("Genome Statistics")st.dataframe(st.session_state.stats_df, use_container_width=True, hide_index=True)if st.session_state.summary_df is not None:st.subheader("Annotation Summary")st.dataframe(st.session_state.summary_df, use_container_width=True, hide_index=True)if st.session_state.features_df is not None and not st.session_state.features_df.empty:st.subheader("Feature Counts by Type")st.dataframe(st.session_state.features_df, use_container_width=True, hide_index=True)if st.session_state.zip_path and os.path.exists(st.session_state.zip_path):with open(st.session_state.zip_path, "rb") as fh:st.download_button("Download annotation results (.zip)",data=fh.read(),file_name=Path(st.session_state.zip_path).name,mime="application/zip",use_container_width=True,)if st.session_state.log_text:with st.expander("View Prokka log"):st.text(st.session_state.log_text)
app.py+96-172