import os import shutil import subprocess import zipfile from collections import Counter from pathlib import Path from typing import Dict, Tuple import pandas as pd from 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_path