Spaces:
Sleeping
Sleeping
Update app.py
Browse files16 unmodified lines1718192021222324252627282930313233343536373839402021222324252627282930313233343536373839404142474344454652474849505758596061626364656667686970717251527576535455798081828384858687888990919293949596979899100565758596061621021036364656610567686970717273747511111211376777879115116117808182831221231248485863 unmodified lines9091921341351361371381391401411421431441459394959697989910010110210310410510610710810911011111211311411511611711811912012112212312414714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021112512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815921821922022122222322422522622722822916016116216316416523623723816616716824216917017117217317417524925025117625317717816 unmodified lines
st.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] = value
def reset_results() -> None: """Clear stored outputs from the current session."""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 = False
def reset_results(): st.session_state.job_dir = None st.session_state.zip_path = None st.session_state.summary_df = None st.session_state.stats_df = None st.session_state.features_df = None st.session_state.log_text = "" st.session_state.uploaded_name = None st.session_state.run_success = False
def 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 / prefix if 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." "Upload a bacterial genome FASTA file, run Prokka annotation, and review genome statistics and annotation summary.")
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", )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}")if uploaded is not None: st.success(f"File detected: {uploaded.name}")
col1, col2, col3, col4 = st.columns(4)with col2: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)
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)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)
# -----------------------------# Clear action# -----------------------------if clear_clicked: reset_results() st.success("Results cleared.")
# -----------------------------# Run action# -----------------------------if run_clicked: reset_results()
3 unmodified lines st.error("Unsupported file format. Upload .fasta, .fa, .fna, or .fas.") else: safe_prefix = sanitize_prefix(prefix)
try: # Create persistent job directory job_dir = prepare_job_directory(safe_prefix)
# Save uploaded FASTA directly into persistent directory fasta_path = save_uploaded_file(uploaded, job_dir)
# Validate FASTA ok, validation_message = validate_fasta(fasta_path) if not ok: st.error(validation_message) work_root = Path("/tmp/space_jobs") work_root.mkdir(parents=True, exist_ok=True)
job_dir = work_root / safe_prefix if 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: st.info(validation_message)
# Compute direct FASTA-based stats before annotation stats = 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.name
if 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_df st.session_state.stats_df = stats_df st.session_state.features_df = features_df st.session_state.run_success = True
st.success("Annotation completed successfully.")
except Exception as exc: st.error(f"An unexpected error occurred: {exc}")
# -----------------------------# Results display# ----------------------------- 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 = True st.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")
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)", "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): with st.expander("View Prokka log"): st.text(st.session_state.log_text)app.py+96-172