Spaces:
Sleeping
Sleeping
Download app.py from cusanovichlab/seqtypeai: direct link, hf CLI and curl.
- Browser
- Download file 18.2 kB
-
https://huggingface.co/spaces/cusanovichlab/seqtypeai/resolve/main/app.py
- Command line
-
hf download hf://spaces/cusanovichlab/seqtypeai/app.py
-
curl -L -o app.py https://huggingface.co/spaces/cusanovichlab/seqtypeai/resolve/main/app.py
18.2 kB
| """ | |
| SeqTypeAI β FastAPI backend for HuggingFace Spaces deployment. | |
| Directory layout expected: | |
| app/ | |
| core/ | |
| feature_extractor.py <- your existing extractor | |
| models/ | |
| seqtype_classifier.joblib | |
| label_encoder.joblib | |
| feature_names.json | |
| model_meta.json | |
| quality_norm.json <- optional, for QC z-scores | |
| app.py <- this file | |
| static/ | |
| index.html <- built React frontend | |
| Run locally: | |
| uvicorn app:app --reload --port 7860 | |
| """ | |
| import io | |
| import gzip | |
| import json | |
| import tempfile | |
| import logging | |
| from pathlib import Path | |
| from typing import Optional | |
| import joblib | |
| import numpy as np | |
| import pandas as pd | |
| from fastapi import FastAPI, File, UploadFile, HTTPException | |
| from fastapi.responses import HTMLResponse, JSONResponse | |
| from fastapi.staticfiles import StaticFiles | |
| from pydantic import BaseModel | |
| # ββ paths βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| ROOT = Path(__file__).parent | |
| MODEL_DIR = ROOT / "app" / "models" | |
| STATIC_DIR = ROOT / "static" | |
| # ββ logging βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| logging.basicConfig(level=logging.INFO) | |
| log = logging.getLogger("seqtypeai") | |
| # ββ load model artifacts ββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| try: | |
| clf = joblib.load(MODEL_DIR / "seqtype_classifier.joblib") | |
| le = joblib.load(MODEL_DIR / "label_encoder.joblib") | |
| feature_names = json.loads((MODEL_DIR / "feature_names.json").read_text()) | |
| model_meta = json.loads((MODEL_DIR / "model_meta.json").read_text()) | |
| log.info("Model loaded β %d classes, %d features", | |
| len(le.classes_), len(feature_names)) | |
| except Exception as exc: | |
| log.error("Failed to load model artifacts: %s", exc) | |
| clf = le = feature_names = model_meta = None | |
| # optional: per-assay QC thresholds derived from training data | |
| try: | |
| quality_norm = json.loads((MODEL_DIR / "quality_norm.json").read_text()) | |
| except Exception: | |
| quality_norm = {} | |
| # ββ feature extractor βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # Import your existing extractor so browser and server use identical features. | |
| import sys | |
| sys.path.insert(0, str(ROOT / "app" / "core")) | |
| try: | |
| from feature_extractor import FeatureExtractor | |
| extractor = FeatureExtractor(max_reads=50_000) | |
| log.info("FeatureExtractor loaded from app/core/feature_extractor.py") | |
| except ImportError as exc: | |
| log.warning("FeatureExtractor not found (%s) β falling back to stub", exc) | |
| extractor = None | |
| # ββ assay metadata ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| ASSAY_LABELS = { | |
| "amplicon_16s": "16S Amplicon", | |
| "atac_seq": "Bulk ATAC-seq", | |
| "bisulfite": "Bisulfite-seq (WGBS)", | |
| "chip_seq": "ChIP-seq", | |
| "cut_and_run": "CUT&RUN", | |
| "cut_and_tag": "CUT&Tag", | |
| "rna_seq": "RNA-seq", | |
| "sc_atac_seq": "scATAC-seq", | |
| "sc_rna_seq": "scRNA-seq", | |
| "spatial": "Spatial transcriptomics", | |
| "wes": "Whole exome seq", | |
| "wgs": "Whole genome seq", | |
| } | |
| # ββ FastAPI app βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| app = FastAPI( | |
| title="SeqTypeAI", | |
| description="NGS assay type classifier β 12 library types from FASTQ features", | |
| version=model_meta.get("version", "1.0") if model_meta else "1.0", | |
| ) | |
| # serve React frontend | |
| if STATIC_DIR.exists(): | |
| app.mount("/static", StaticFiles(directory=str(STATIC_DIR)), name="static") | |
| # ββ response schemas ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| class PredictionItem(BaseModel): | |
| assay: str | |
| label: str | |
| confidence: float | |
| evidence: str = "" | |
| class QCCheck(BaseModel): | |
| label: str | |
| status: str # "good" | "warn" | "poor" | |
| value: float | |
| desc: str | |
| class ClassifyResponse(BaseModel): | |
| filename: str | |
| top_assay: str | |
| top_label: str | |
| confidence: float | |
| predictions: list[PredictionItem] | |
| features: dict | |
| qc_checks: list[QCCheck] | |
| qc_overall: str | |
| reasoning: str | |
| model_version: str | |
| warnings: list[str] = [] | |
| # ββ helpers βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def _is_interleaved(reads: list[dict], headers: list[str], n_check: int = 50) -> bool: | |
| """Return True if reads appear to be interleaved paired-end.""" | |
| import re | |
| pairs = 0 | |
| check = min(n_check * 2, len(headers)) | |
| prev = None | |
| for i in range(check): | |
| raw = headers[i].lstrip("@").split()[0] | |
| base = re.sub(r"[./][12]$", "", raw) | |
| if prev is not None and base == prev: | |
| pairs += 1 | |
| prev = base | |
| return pairs >= n_check * 0.8 | |
| def read_fastq_bytes(data: bytes, max_reads: int = 50_000) -> tuple[list[dict], list[str]]: | |
| """Parse FASTQ bytes (plain or gzip) β (reads, warnings). | |
| Detects interleaved paired-end files and extracts R1 only, returning | |
| a warning string so the caller can surface it to the user. | |
| """ | |
| if data[:2] == b"\x1f\x8b": | |
| data = gzip.decompress(data) | |
| text = data.decode("utf-8", errors="replace") | |
| lines = text.splitlines() | |
| reads = [] | |
| headers = [] | |
| for i in range(0, len(lines) - 3, 4): | |
| h, seq, _, qual = lines[i], lines[i+1], lines[i+2], lines[i+3] | |
| if h.startswith("@") and seq and qual: | |
| reads.append({"seq": seq.strip(), "qual": qual.strip()}) | |
| headers.append(h) | |
| if len(reads) >= max_reads * 2: # over-read to detect interleaving | |
| break | |
| warnings = [] | |
| if _is_interleaved(reads, headers): | |
| warnings.append( | |
| "Interleaved paired-end file detected (R1+R2 merged). " | |
| "Only R1 reads (every other read) were used for classification. " | |
| "For best results, submit R1 only using: " | |
| "seqtk seq -1 input.fastq.gz > R1.fastq.gz" | |
| ) | |
| reads = reads[::2] # keep every other read (R1 only) | |
| return reads[:max_reads], warnings | |
| def reads_to_tempfile(reads: list[dict]) -> str: | |
| """Write reads to a temporary FASTQ file for FeatureExtractor.""" | |
| with tempfile.NamedTemporaryFile( | |
| mode="w", suffix=".fastq", delete=False | |
| ) as fh: | |
| for i, r in enumerate(reads): | |
| fh.write(f"@read_{i}\n{r['seq']}\n+\n{r['qual']}\n") | |
| return fh.name | |
| def run_extractor(reads: list[dict]) -> dict: | |
| """Extract features using FeatureExtractor or a lightweight fallback.""" | |
| if extractor is not None: | |
| tmp = reads_to_tempfile(reads) | |
| try: | |
| return extractor.extract(tmp) | |
| finally: | |
| Path(tmp).unlink(missing_ok=True) | |
| # ββ lightweight fallback (matches browser-side extraction) ββ | |
| import re, math | |
| seqs = [r["seq"] for r in reads] | |
| rls = [len(s) for s in seqs] | |
| gcs = [(s.count("G") + s.count("C")) / len(s) if s else 0 for s in seqs] | |
| cfs = [s.count("C") / len(s) if s else 0 for s in seqs] | |
| def shannon(s): | |
| n = len(s) | |
| if not n: return 0 | |
| cnt = {c: s.count(c) for c in "ACGT"} | |
| return -sum((v/n)*math.log2(v/n) for v in cnt.values() if v) / 2 | |
| entropies = [shannon(s) for s in seqs] | |
| tn5 = [(s[:9].count("A") + s[:9].count("T")) / 9 if len(s) >= 9 else 0 for s in seqs] | |
| polya = [1 if re.search(r"A{6,}", s[-20:]) else 0 for s in seqs] | |
| repk = [] | |
| for s in seqs: | |
| if len(s) < 4: repk.append(0); continue | |
| km = {} | |
| for j in range(len(s)-1): k = s[j:j+2]; km[k] = km.get(k, 0) + 1 | |
| repk.append(max(km.values()) / (len(s)-1)) | |
| mean = lambda a: sum(a)/len(a) if a else 0 | |
| std = lambda a: math.sqrt(mean([(v - mean(a))**2 for v in a])) if a else 0 | |
| bc = sum(1 for l in rls if 24 <= l <= 28) / len(rls) if rls else 0 | |
| return { | |
| "n_reads": len(reads), | |
| "rl_mean": mean(rls), | |
| "rl_std": std(rls), | |
| "rl_min": min(rls) if rls else 0, | |
| "rl_max": max(rls) if rls else 0, | |
| "gc_mean": mean(gcs), | |
| "gc_std": std(gcs), | |
| "c_fraction": mean(cfs), | |
| "entropy_mean": mean(entropies), | |
| "tn5_start_approx": mean(tn5), | |
| "polya_signal": mean(polya), | |
| "repeat_kmer_frac": mean(repk), | |
| "gc_tail_low": sum(1 for v in gcs if v < 0.30) / len(gcs) if gcs else 0, | |
| "gc_tail_high": sum(1 for v in gcs if v > 0.70) / len(gcs) if gcs else 0, | |
| "is_barcode_length": 1 if bc > 0.80 else 0, | |
| } | |
| def model_predict(features: dict) -> list[PredictionItem]: | |
| """Run the trained sklearn model and return ranked predictions.""" | |
| if clf is None or le is None or feature_names is None: | |
| raise HTTPException(503, "Model not loaded β check server logs") | |
| row = pd.DataFrame([{f: features.get(f, 0.0) for f in feature_names}]) | |
| proba = clf.predict_proba(row)[0] | |
| items = [] | |
| for cls, prob in sorted( | |
| zip(le.classes_, proba), key=lambda x: -x[1] | |
| ): | |
| items.append(PredictionItem( | |
| assay=cls, | |
| label=ASSAY_LABELS.get(cls, cls), | |
| confidence=round(float(prob), 4), | |
| evidence="", | |
| )) | |
| return items | |
| def build_reasoning(preds: list[PredictionItem], features: dict) -> str: | |
| top = preds[0] | |
| runner_up = preds[1] if len(preds) > 1 else None | |
| parts = [ | |
| f"Top prediction is {top.label} ({top.confidence*100:.0f}% confidence)." | |
| ] | |
| # add a couple of the most discriminating feature observations | |
| if features.get("is_barcode_length") == 1: | |
| parts.append("R1 read length of 24β28 bp is consistent with a 10x-style barcode read.") | |
| if features.get("c_fraction", 1) < 0.06: | |
| parts.append(f"Very low C fraction ({features['c_fraction']*100:.1f}%) is a strong bisulfite conversion signal.") | |
| if features.get("tn5_start_approx", 0) > 0.52: | |
| parts.append(f"AT-rich read starts ({features['tn5_start_approx']*100:.0f}%) indicate Tn5 or MNase insertion bias.") | |
| if runner_up and runner_up.confidence > 0.15: | |
| parts.append(f"Runner-up: {runner_up.label} ({runner_up.confidence*100:.0f}%).") | |
| return " ".join(parts) | |
| # ββ QC assessment (mirrors browser-side logic) ββββββββββββββββββββββββββββββββ | |
| QC_THRESHOLDS = { | |
| "atac_seq": [ | |
| ("Tn5 insertion bias", "tn5_start_approx", | |
| lambda v: v > 0.52, lambda v: v > 0.48, | |
| "AT-rich read starts indicate Tn5 transposition"), | |
| ("GC content", "gc_mean", | |
| lambda v: 0.40 < v < 0.60, lambda v: 0.35 < v < 0.65, | |
| "Expected 40β60% for open chromatin"), | |
| ("Library complexity", "entropy_mean", | |
| lambda v: v > 0.85, lambda v: v > 0.75, | |
| "High entropy indicates library diversity"), | |
| ], | |
| "bisulfite": [ | |
| ("Conversion efficiency", "c_fraction", | |
| lambda v: v < 0.05, lambda v: v < 0.10, | |
| "C fraction < 5% = good bisulfite conversion"), | |
| ("Low-GC read fraction", "gc_tail_low", | |
| lambda v: v > 0.20, lambda v: v > 0.10, | |
| "CβT conversion produces GC-depleted reads"), | |
| ], | |
| "rna_seq": [ | |
| ("GC content", "gc_mean", | |
| lambda v: 0.42 < v < 0.58, lambda v: 0.38 < v < 0.62, | |
| "Human transcriptome: 48β52% GC"), | |
| ("Library complexity", "entropy_mean", | |
| lambda v: v > 0.85, lambda v: v > 0.75, | |
| "Diverse read sequences expected"), | |
| ("Read length", "rl_mean", | |
| lambda v: 75 <= v <= 200, lambda v: 50 <= v <= 300, | |
| "Standard RNA-seq: 75β150 bp"), | |
| ], | |
| "sc_rna_seq": [ | |
| ("Barcode read length", "is_barcode_length", | |
| lambda v: v == 1, lambda v: False, | |
| "28 bp R1 = 10x v3 barcode + UMI"), | |
| ], | |
| "sc_atac_seq": [ | |
| ("Barcode read length", "is_barcode_length", | |
| lambda v: v == 1, lambda v: False, | |
| "Short R1 indicates barcode read"), | |
| ], | |
| "wgs": [ | |
| ("GC content", "gc_mean", | |
| lambda v: 0.37 < v < 0.47, lambda v: 0.33 < v < 0.53, | |
| "Human genome ~41% GC"), | |
| ("Repeat k-mer content", "repeat_kmer_frac", | |
| lambda v: 0.003 < v < 0.07, lambda v: v < 0.10, | |
| "Moderate repeat fraction expected for WGS"), | |
| ], | |
| "wes": [ | |
| ("GC content", "gc_mean", | |
| lambda v: 0.44 < v < 0.56, lambda v: 0.40 < v < 0.60, | |
| "Exome regions are GC-enriched (~49%)"), | |
| ("Repeat depletion", "repeat_kmer_frac", | |
| lambda v: v < 0.04, lambda v: v < 0.07, | |
| "Exome capture depletes repetitive sequences"), | |
| ], | |
| "chip_seq": [ | |
| ("Library complexity", "entropy_mean", | |
| lambda v: v > 0.85, lambda v: v > 0.75, | |
| "Low complexity suggests over-amplification"), | |
| ], | |
| "cut_and_run": [ | |
| ("MNase start bias", "tn5_start_approx", | |
| lambda v: v > 0.50, lambda v: v > 0.46, | |
| "MNase cleaves AT-rich linker regions"), | |
| ], | |
| "cut_and_tag": [ | |
| ("Tn5 insertion bias", "tn5_start_approx", | |
| lambda v: v > 0.52, lambda v: v > 0.48, | |
| "pA-Tn5 shows AT bias similar to ATAC-seq"), | |
| ], | |
| "amplicon_16s": [ | |
| ("Amplicon read length", "rl_mean", | |
| lambda v: 200 <= v <= 500, lambda v: 150 <= v <= 600, | |
| "V4: ~253 bp, V3βV4: ~464 bp"), | |
| ("Community diversity", "entropy_mean", | |
| lambda v: v > 0.80, lambda v: v > 0.70, | |
| "Good microbial community diversity expected"), | |
| ], | |
| "spatial": [ | |
| ("Read length", "rl_mean", | |
| lambda v: v < 40, lambda v: v < 60, | |
| "Visium R1 = 28 bp"), | |
| ], | |
| } | |
| def assess_quality(features: dict, assay: str) -> tuple[list[QCCheck], str]: | |
| checks_def = QC_THRESHOLDS.get(assay, []) | |
| checks = [] | |
| for label, key, good, warn, desc in checks_def: | |
| val = features.get(key, 0.0) | |
| status = "good" if good(val) else ("warn" if warn(val) else "poor") | |
| checks.append(QCCheck(label=label, status=status, value=round(float(val), 4), desc=desc)) | |
| score_map = {"good": 2, "warn": 1, "poor": 0} | |
| if checks: | |
| score = sum(score_map[c.status] for c in checks) / (len(checks) * 2) | |
| else: | |
| score = 1.0 | |
| overall = "good" if score >= 0.75 else ("warn" if score >= 0.5 else "poor") | |
| return checks, overall | |
| # ββ routes ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| async def root(): | |
| idx = STATIC_DIR / "index.html" | |
| if idx.exists(): | |
| return HTMLResponse(idx.read_text()) | |
| return HTMLResponse("<h1>SeqTypeAI API</h1><p>Docs: <a href='/docs'>/docs</a></p>") | |
| async def health(): | |
| return { | |
| "status": "ok", | |
| "model_loaded": clf is not None, | |
| "model_version": model_meta.get("version", "unknown") if model_meta else "unknown", | |
| "n_features": len(feature_names) if feature_names else 0, | |
| "n_classes": len(le.classes_) if le else 0, | |
| } | |
| async def classify(file: UploadFile = File(...)): | |
| """ | |
| Upload a FASTQ file (.fastq or .fastq.gz) and receive: | |
| - ranked assay type predictions with confidence scores | |
| - extracted library features | |
| - assay-specific QC assessment | |
| """ | |
| if not file.filename: | |
| raise HTTPException(400, "No filename provided") | |
| allowed_ext = {".fastq", ".fq", ".fastq.gz", ".fq.gz"} | |
| fname = file.filename.lower() | |
| if not any(fname.endswith(e) for e in allowed_ext): | |
| raise HTTPException(400, f"File must be one of: {', '.join(allowed_ext)}") | |
| data = await file.read() | |
| if len(data) > 50 * 1024 * 1024: # 100 MB β plenty for 50k reads of any assay | |
| raise HTTPException(413, | |
| "File too large (maximum 50 MB). SeqTypeAI only needs the first " | |
| "50,000 reads to classify a library β please submit a subsample. " | |
| "See the /docs page or the error response for subsampling commands." | |
| ) | |
| reads, warnings = read_fastq_bytes(data, max_reads=50_000) | |
| if not reads: | |
| raise HTTPException(422, "No valid FASTQ records found in file") | |
| if warnings: | |
| for w in warnings: | |
| log.warning(" %s: %s", file.filename, w) | |
| features = run_extractor(reads) | |
| preds = model_predict(features) | |
| reasoning = build_reasoning(preds, features) | |
| qc_checks, qc_overall = assess_quality(features, preds[0].assay) | |
| return ClassifyResponse( | |
| filename = file.filename, | |
| top_assay = preds[0].assay, | |
| top_label = preds[0].label, | |
| confidence = preds[0].confidence, | |
| predictions = preds, | |
| features = {k: round(v, 6) if isinstance(v, float) else v | |
| for k, v in features.items()}, | |
| qc_checks = qc_checks, | |
| qc_overall = qc_overall, | |
| reasoning = reasoning, | |
| model_version = model_meta.get("version", "1.0") if model_meta else "1.0", | |
| warnings = warnings, | |
| ) | |