Spaces:
Sleeping
Sleeping
Upload 4 files
Browse filesFiles changed (4)
- DockerfileAdded+29
- annotation_core.pyAdded+179
- app.pyAdded+182
- requirements.txtAdded+3
1234567891011121314151617181920212223242526272829FROM python:3.11-slim
ENV DEBIAN_FRONTEND=noninteractive \ PYTHONDONTWRITEBYTECODE=1 \ PYTHONUNBUFFERED=1 \ PIP_NO_CACHE_DIR=1
WORKDIR /app
RUN apt-get update && apt-get install -y --no-install-recommends \ prokka \ default-jre \ libdatetime-perl \ libxml-simple-perl \ libdigest-md5-perl \ libfile-slurp-perl \ libbio-perl-perl \ wget \ ca-certificates \ && rm -rf /var/lib/apt/lists/*
COPY requirements.txt ./RUN pip install --upgrade pip && pip install -r requirements.txt
COPY . /app
EXPOSE 7860
CMD ["streamlit", "run", "app.py", "--server.port=7860", "--server.address=0.0.0.0", "--server.maxUploadSize=200"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179import osimport shutilimport subprocessimport zipfilefrom collections import Counterfrom pathlib import Pathfrom typing import Dict, Tuple
import pandas as pdfrom Bio import SeqIO
ALLOWED_EXTENSIONS = {".fasta", ".fa", ".fna", ".fas"}
def allowed_fasta(filename: str) -> bool: return Path(filename).suffix.lower() in ALLOWED_EXTENSIONS
def save_uploaded_file(uploaded_file, target_dir: Path) -> Path: target_dir.mkdir(parents=True, exist_ok=True) out_path = target_dir / uploaded_file.name out_path.write_bytes(uploaded_file.getbuffer()) return out_path
def validate_fasta(fasta_path: Path) -> Tuple[bool, str]: try: records = list(SeqIO.parse(str(fasta_path), "fasta")) except Exception as exc: return False, f"Unable to parse FASTA file: {exc}"
if not records: return False, "The uploaded FASTA file contains no sequences."
valid_chars = set("ACGTURYKMSWBDHVNacgturykmswbdhvn") for record in records: seq = str(record.seq) if not seq: return False, f"Sequence '{record.id}' is empty." if any(base not in valid_chars for base in seq): return False, f"Sequence '{record.id}' contains unsupported characters for nucleotide FASTA."
return True, "FASTA validated successfully."
def compute_basic_genome_stats(fasta_path: Path) -> Dict[str, float]: lengths = [] gc = 0 total = 0 n_count = 0
for record in SeqIO.parse(str(fasta_path), "fasta"): seq = str(record.seq).upper() lengths.append(len(seq)) gc += seq.count("G") + seq.count("C") n_count += seq.count("N") total += len(seq)
gc_percent = (gc / total * 100.0) if total else 0.0 n_percent = (n_count / total * 100.0) if total else 0.0
return { "genome_length_bp": total, "gc_percent": gc_percent, "num_contigs": len(lengths), "longest_contig_bp": max(lengths) if lengths else 0, "n_percent": n_percent, }
def run_prokka_annotation( fasta_path: Path, outdir: Path, prefix: str, genus: str, species: str, cpus: int = 2,) -> Dict[str, str]: outdir = Path(outdir) if outdir.exists(): shutil.rmtree(outdir) outdir.mkdir(parents=True, exist_ok=True)
cmd = [ "prokka", "--outdir", str(outdir), "--prefix", prefix, "--force", "--cpus", str(cpus), "--genus", genus, "--species", species, str(fasta_path), ]
try: proc = subprocess.run( cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, check=False, ) except FileNotFoundError: return { "success": False, "log": "Prokka is not installed or not available in PATH. Build the Space with the provided Dockerfile.", "outdir": str(outdir), }
log_text = f"COMMAND:\n{' '.join(cmd)}\n\nSTDOUT:\n{proc.stdout}\n\nSTDERR:\n{proc.stderr}" success = proc.returncode == 0
return { "success": success, "log": log_text, "outdir": str(outdir), }
def parse_prokka_summary(prokka_outdir: str, prefix: str) -> Dict[str, object]: prokka_outdir = Path(prokka_outdir) gff_path = prokka_outdir / f"{prefix}.gff" tsv_path = prokka_outdir / f"{prefix}.tsv"
counts = Counter() feature_rows = []
if gff_path.exists(): with open(gff_path, "r", encoding="utf-8") as fh: for line in fh: if line.startswith("#"): continue parts = line.rstrip("\n").split("\t") if len(parts) < 9: continue feature_type = parts[2] counts[feature_type] += 1
genes = counts.get("gene", 0) cds = counts.get("CDS", 0) rrna = counts.get("rRNA", 0) trna = counts.get("tRNA", 0) tmrna = counts.get("tmRNA", 0) repeat_region = counts.get("repeat_region", 0)
for k, v in sorted(counts.items()): feature_rows.append({"Feature type": k, "Count": v})
feature_df = pd.DataFrame(feature_rows) if feature_rows else pd.DataFrame(columns=["Feature type", "Count"])
return { "genes": genes, "CDS": cds, "rRNA": rrna, "tRNA": trna, "tmRNA": tmrna, "repeat_region": repeat_region, "feature_table": feature_df, "tsv_exists": tsv_path.exists(), }
def make_download_zip(source_dir: Path, zip_path: Path) -> Path: source_dir = Path(source_dir) zip_path = Path(zip_path) if zip_path.exists(): zip_path.unlink()
with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as zf: for file_path in source_dir.rglob("*"): if file_path.is_file(): zf.write(file_path, arcname=file_path.relative_to(source_dir)) return zip_path123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182import osimport tempfileimport zipfilefrom pathlib import Path
import pandas as pdimport streamlit as st
from annotation_core import ( allowed_fasta, compute_basic_genome_stats, parse_prokka_summary, run_prokka_annotation, save_uploaded_file, validate_fasta, make_download_zip,)
st.set_page_config(page_title="Genome Annotation Workbench", layout="wide")
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 """ )
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 = ""
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, )
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)
if clear_clicked: 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.success("Results cleared.")
if run_clicked: if uploaded is None: st.error("Please upload a FASTA file first.") elif not allowed_fasta(uploaded.name): st.error("Unsupported file format. Upload .fasta, .fa, .fna, or .fas.") else: with tempfile.TemporaryDirectory(prefix="genome_annot_") as tmpdir: tmpdir_path = Path(tmpdir) fasta_path = save_uploaded_file(uploaded, tmpdir_path)
ok, validation_message = validate_fasta(fasta_path) if not ok: st.error(validation_message) else: stats = compute_basic_genome_stats(fasta_path)
work_root = Path("/tmp/space_jobs") work_root.mkdir(parents=True, exist_ok=True) safe_prefix = "".join(c if c.isalnum() or c in "-_" else "_" for c in prefix).strip("_") or "sample_genome" job_dir = work_root / safe_prefix if job_dir.exists(): import shutil shutil.rmtree(job_dir) job_dir.mkdir(parents=True, exist_ok=True)
fasta_copy = job_dir / fasta_path.name fasta_copy.write_bytes(fasta_path.read_bytes())
with st.spinner("Running Prokka annotation. This may take a few minutes depending on genome size."): result = run_prokka_annotation( fasta_path=fasta_copy, outdir=job_dir / "prokka_out", prefix=safe_prefix, genus=genus, species=species, cpus=int(threads), )
st.session_state.log_text = result["log"]
if not result["success"]: st.error("Annotation failed. Review the log below.") else: summary = parse_prokka_summary(result["outdir"], safe_prefix)
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)}, ])
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
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)
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, )
if st.session_state.log_text: with st.expander("View Prokka log", expanded=False): st.text(st.session_state.log_text)123streamlit==1.43.2pandas==2.2.3biopython==1.84DockerfileAdded+29
annotation_core.pyAdded+179
app.pyAdded+182
requirements.txtAdded+3