File size: 4,958 Bytes
c73c351
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
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