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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
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
"""
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 ────────────────────────────────────────────────────────────────────
@app.get("/", response_class=HTMLResponse)
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>")


@app.get("/health")
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,
    }


@app.post("/classify", response_model=ClassifyResponse)
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,
    )