Spaces:
Runtime error

File size: 26,649 Bytes
ef8903e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
"""
AI Source Classifier β€” FastAPI Backend
Hybrid inference: TF-IDF + Random Forest (always)
               + DeBERTa (if model files are present)

Realigned to match Jupyter Notebook's inference logic (no preprocessing, identical model inputs).
Deploy on HuggingFace Spaces (Docker SDK).
"""

from __future__ import annotations

import logging
import os
import re
from typing import Any

import joblib
import numpy as np
from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel, Field

# ── Logging ───────────────────────────────────────────────────────────────────

logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s | %(levelname)-8s | %(message)s",
)
log = logging.getLogger(__name__)

# ── Config and Auto-detection of Model Paths ─────────────────────────────────

BASE_DIR = os.path.dirname(os.path.abspath(__file__))

MODEL_DIR = os.getenv("MODEL_DIR", "")
if not MODEL_DIR:
    for p in ["saved_hybrid_model", "models"]:
        path = os.path.join(BASE_DIR, p)
        if os.path.exists(path):
            MODEL_DIR = path
            break
    if not MODEL_DIR:
        MODEL_DIR = os.path.join(BASE_DIR, "saved_hybrid_model")

MODEL_FILE  = os.getenv("MODEL_FILE",  "model_compressed.joblib")  # FORMAT A filename

DEBERTA_DIR = os.getenv("DEBERTA_DIR", "")
if not DEBERTA_DIR:
    for p in ["deberta_model", "deberta"]:
        path = os.path.join(BASE_DIR, p)
        if os.path.exists(path):
            DEBERTA_DIR = path
            break
    if not DEBERTA_DIR:
        DEBERTA_DIR = os.path.join(BASE_DIR, "deberta_model")

CHAR_LIMIT  = int(os.getenv("CHAR_LIMIT",  "5000"))
TOKEN_LIMIT = int(os.getenv("TOKEN_LIMIT", "512"))
W_DEBERTA   = float(os.getenv("W_DEBERTA", "0.75"))
W_RF        = float(os.getenv("W_RF",      "0.25"))
BATCH_SIZE  = 8   # DeBERTa internal batch size

# ── Source label map (legacy numeric β†’ display name) ─────────────────────────
# Used when the label encoder stores raw integers (FORMAT B / old notebooks).

SOURCE_NAMES: dict[str, str] = {
    "0": "ChatGPT",
    "1": "Copilot",
    "2": "Gemini",
    "3": "Qwen",
    "4": "Claude",
    "5": "Human-written",
    "6": "AI-generated + Human-written",
    "7": "AI-generated + AI-refined",
    "8": "Human-written + AI-refined",
    "9": "AI-generated + AI-refined + Human-written",
}

AI_SOURCES = {"ChatGPT", "Copilot", "Gemini", "Qwen", "Claude"}

_PALETTE = [
    "#fde68a", "#bfdbfe", "#bbf7d0", "#fbcfe8", "#ddd6fe",
    "#fed7aa", "#a5f3fc", "#fca5a5", "#d9f99d", "#99f6e4",
]

# ── Model globals ─────────────────────────────────────────────────────────────

tfidf:      Any = None
rf:         Any = None
le:         Any = None
deberta:    Any = None
tokenizer_: Any = None
TORCH_OK      = False
USE_DEBERTA   = False
DEVICE        = "cpu"
N_CLASSES     = 0
ENCODED:       list[int]      = []
SOURCE_LABELS: dict[int, str] = {}
RF_INDEX:      list[int]      = []
SOURCE_COLORS: dict[str, str] = {}
MODEL_FORMAT  = "unknown"   # "single-file" | "three-file"


# ── Startup: load models ──────────────────────────────────────────────────────

def _load_models() -> None:
    global tfidf, rf, le, deberta, tokenizer_, TORCH_OK, USE_DEBERTA
    global DEVICE, N_CLASSES, ENCODED, SOURCE_LABELS, RF_INDEX, SOURCE_COLORS
    global MODEL_FORMAT

    # Check for PyTorch availability
    try:
        import torch
        import torch.nn.functional as F  # noqa: F401
        TORCH_OK = True
        DEVICE   = "cuda" if torch.cuda.is_available() else "cpu"
    except Exception as exc:
        log.warning("torch/transformers not available β€” RF-only mode. (%s)", exc)

    bundle_path = os.path.join(MODEL_DIR, MODEL_FILE)

    # ------------------------------------------------------------------ #
    # FORMAT A β€” single bundled .joblib (new notebook output)             #
    # ------------------------------------------------------------------ #
    if os.path.exists(bundle_path):
        log.info("Loading FORMAT A model bundle: %s", bundle_path)
        data = joblib.load(bundle_path)

        tfidf = data["vectorizer"]
        rf    = data["classifier"]
        le    = data["label_encoder"]

        # The bundle may supply a pre-built class list; fall back to le.classes_
        raw_classes = data.get("classes", le.classes_)

        MODEL_FORMAT = "single-file"
        log.info("FORMAT A loaded β€” %d classes", len(raw_classes))

    # ------------------------------------------------------------------ #
    # FORMAT B β€” three separate .pkl files (legacy / previous deployment) #
    # ------------------------------------------------------------------ #
    else:
        rf_path    = os.path.join(MODEL_DIR, "rf_model.pkl")
        tfidf_path = os.path.join(MODEL_DIR, "tfidf_vectorizer.pkl")
        le_path    = os.path.join(MODEL_DIR, "label_encoder.pkl")

        missing = [p for p in (rf_path, tfidf_path, le_path) if not os.path.exists(p)]
        if missing:
            raise FileNotFoundError(
                f"No model found.\n"
                f"  FORMAT A: place '{MODEL_FILE}' in {MODEL_DIR}\n"
                f"  FORMAT B: place rf_model.pkl + tfidf_vectorizer.pkl + label_encoder.pkl in {MODEL_DIR}\n"
                f"  Missing: {missing}"
            )

        log.info("Loading FORMAT B (3-file): %s", MODEL_DIR)
        tfidf = joblib.load(tfidf_path)
        rf    = joblib.load(rf_path)
        le    = joblib.load(le_path)
        raw_classes = le.classes_

        MODEL_FORMAT = "three-file"
        log.info("FORMAT B loaded β€” %d classes", len(raw_classes))

    # ------------------------------------------------------------------ #
    # Build shared runtime tables (same for both formats)                 #
    # ------------------------------------------------------------------ #
    N_CLASSES = len(raw_classes)
    ENCODED   = list(range(N_CLASSES))

    SOURCE_LABELS = {}
    for i, name in enumerate(raw_classes):
        # If le stores integers, map through SOURCE_NAMES; else use string as-is
        display = SOURCE_NAMES.get(str(name), str(name))
        SOURCE_LABELS[i] = display

    # RF's internal class ordering may differ from 0…N-1
    rf_classes = list(rf.classes_)
    RF_INDEX   = [rf_classes.index(c) for c in ENCODED]

    SOURCE_COLORS = {
        SOURCE_LABELS[i]: _PALETTE[i % len(_PALETTE)]
        for i in range(N_CLASSES)
    }

    log.info("Classes: %s", list(SOURCE_LABELS.values()))

    # ------------------------------------------------------------------ #
    # Optional: DeBERTa                                                   #
    # ------------------------------------------------------------------ #
    if TORCH_OK and DEBERTA_DIR and os.path.isdir(DEBERTA_DIR):
        cfg = os.path.join(DEBERTA_DIR, "config.json")
        if os.path.exists(cfg):
            from transformers import AutoModelForSequenceClassification, AutoTokenizer
            log.info("Loading DeBERTa from %s on %s …", DEBERTA_DIR, DEVICE)
            tokenizer_ = AutoTokenizer.from_pretrained(DEBERTA_DIR)
            deberta = (
                AutoModelForSequenceClassification
                .from_pretrained(DEBERTA_DIR)
                .to(DEVICE)
                .eval()
            )
            USE_DEBERTA = True
            log.info(
                "Mode: HYBRID (DeBERTa %.2f + RF %.2f) on %s",
                W_DEBERTA, W_RF, DEVICE,
            )
        else:
            log.warning("DEBERTA_DIR set but config.json missing β€” RF-only.")
    else:
        log.info("DeBERTa not configured β€” Mode: RF-only.")


# ── FastAPI app ───────────────────────────────────────────────────────────────

app = FastAPI(
    title="AI Source Classifier API",
    description=(
        "Identifies whether text was written by ChatGPT, Copilot, Gemini, Qwen, "
        "Claude, or a human β€” using a TF-IDF + Random Forest model (optionally "
        "ensembled with DeBERTa). Exposes single-text, batch, sentence-level, "
        "and sentence-attribution endpoints."
    ),
    version="3.0.0",
)

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_methods=["*"],
    allow_headers=["*"],
)


@app.on_event("startup")
def startup_event() -> None:
    _load_models()


# ── Guards ────────────────────────────────────────────────────────────────────

def _require_model() -> None:
    if rf is None:
        raise HTTPException(
            status_code=503,
            detail="Model not loaded. Check server logs.",
        )


# ── Core inference helpers (Aligned with Jupyter Notebook) ───────────────────

def _rf_probs(text: str) -> np.ndarray:
    # Match notebook's raw text ingestion without preprocess regex
    raw = rf.predict_proba(tfidf.transform([text]))[0]
    return raw[RF_INDEX]


def _deberta_probs_single(text: str) -> np.ndarray:
    """Single-text DeBERTa inference β€” identical to the notebook's deberta_probs().
    No padding, single text passed directly, matching notebook behaviour exactly."""
    import torch
    import torch.nn.functional as F

    enc = tokenizer_(
        text,
        truncation=True,
        max_length=TOKEN_LIMIT,
        return_tensors="pt",
    ).to(DEVICE)
    with torch.no_grad():
        logits = deberta(**enc).logits
    return F.softmax(logits, dim=-1).cpu().numpy()[0]


def _deberta_probs_batch(texts: list[str]) -> np.ndarray:
    """Batched DeBERTa inference β€” used for the leave-one-out attribution passes.
    Uses padding=True so the batch can be collated into a single tensor."""
    import torch
    import torch.nn.functional as F

    out = []
    for i in range(0, len(texts), BATCH_SIZE):
        batch = texts[i : i + BATCH_SIZE]
        enc = tokenizer_(
            batch,
            truncation=True,
            max_length=TOKEN_LIMIT,
            padding=True,
            return_tensors="pt",
        ).to(DEVICE)
        with torch.no_grad():
            logits = deberta(**enc).logits
        out.append(F.softmax(logits, dim=-1).cpu().numpy())
    return np.vstack(out)


def _ensemble_probs_batch(texts: list[str]) -> np.ndarray:
    """Vectorised ensemble: W_DEBERTA*DeBERTa + W_RF*RF, normalised."""
    # Match notebook's raw text list ingestion without preprocess regex
    P_rf = np.asarray(rf.predict_proba(tfidf.transform(texts)))[:, RF_INDEX]
    if USE_DEBERTA:
        P = W_DEBERTA * _deberta_probs_batch(texts) + W_RF * P_rf
    else:
        P = P_rf
    return P / P.sum(axis=1, keepdims=True)


def _predict_one(text: str) -> dict:
    """Full prediction for a single text string."""
    text = (text or "").strip()[:CHAR_LIMIT]
    if not text:
        raise ValueError("Text is empty.")

    p_rf = _rf_probs(text)

    if USE_DEBERTA:
        # Use single-text helper β€” matches notebook's deberta_probs() exactly
        # (no padding=True, no batching artefacts)
        p_deb    = _deberta_probs_single(text)
        p        = W_DEBERTA * p_deb + W_RF * p_rf
        deb_pick = SOURCE_LABELS[int(np.argmax(p_deb))]
    else:
        p        = p_rf
        deb_pick = None

    p     = p / p.sum()
    order = np.argsort(p)[::-1]

    return {
        "ranked":       [(SOURCE_LABELS[int(i)], float(p[i])) for i in order],
        "confidence":   float(p[int(order[0])]),
        "rf_pick":      SOURCE_LABELS[int(np.argmax(p_rf))],
        "deberta_pick": deb_pick,
        "mode":         "Hybrid" if USE_DEBERTA else "RF-only",
    }


def _merge_ai_sources(result: dict | None) -> dict | None:
    """Fold minor AI-source probabilities into the top AI label (Matches Notebook)."""
    if result is None:
        return None
    ranked    = result["ranked"]
    top_label = ranked[0][0]
    if top_label not in AI_SOURCES and top_label != "Human-written":
        return result

    ai_total = sum(p for lbl, p in ranked if lbl in AI_SOURCES)
    merged   = []
    for lbl, p in ranked:
        if lbl in AI_SOURCES and lbl != top_label:
            continue
        if lbl == top_label:
            p = (p + ai_total) if top_label == "Human-written" else ai_total
        merged.append((lbl, p))
    merged.sort(key=lambda x: x[1], reverse=True)

    return {**result, "ranked": merged, "confidence": float(merged[0][1])}


def _format_predictions(result: dict, top_n: int = 5) -> list[dict]:
    return [
        {"source": lbl, "probability": round(prob * 100, 2)}
        for lbl, prob in result["ranked"][:top_n]
    ]


# ── Sentence splitting helpers ────────────────────────────────────────────────

_SPLIT_RE = re.compile(
    r'(?:(?<=[.!?])|(?<=[.!?]["\'\)\]]))'
    r'(?<!\bMr\.)(?<!\bMrs\.)(?<!\bMs\.)(?<!\bDr\.)(?<!\bSt\.)(?<!\bvs\.)'
    r'(?<!\b[Ee]\.g\.)(?<!\b[Ii]\.e\.)(?<!\bNo\.)(?<!\bFig\.)'
    r'\s+(?=[A-Z0-9"\'\(\[])'
)


def _split_sentences(text: str) -> list[tuple]:
    """Return list of ('sent', text) and ('break',) tuples."""
    items: list[tuple] = []
    lines = text.split("\n")
    for i, line in enumerate(lines):
        line = line.strip()
        if line:
            parts = _SPLIT_RE.split(line)
            items.extend(("sent", p.strip()) for p in parts if p.strip())
        if i < len(lines) - 1:
            items.append(("break",))
    return items


def _rebuild(items: list[tuple], skip: int | None = None) -> str:
    parts = []
    for k, it in enumerate(items):
        if it[0] == "break":
            parts.append("\n")
        elif k != skip:
            parts.append(it[1] + " ")
    return "".join(parts).strip()


# ── Sentence attribution ──────────────────────────────────────────────────────

def _display_groups(p_full: np.ndarray) -> tuple[list[str], list[list[int]]]:
    top_label = SOURCE_LABELS[int(np.argmax(p_full))]
    ai_idx    = [i for i in range(N_CLASSES) if SOURCE_LABELS[i] in AI_SOURCES]
    labels, groups = [], []
    if top_label in AI_SOURCES or top_label == "Human-written":
        fold_into = top_label if top_label in AI_SOURCES else "Human-written"
        for i in range(N_CLASSES):
            name = SOURCE_LABELS[i]
            if name == fold_into:
                labels.append(name)
                groups.append(sorted(set(ai_idx + [i])))
            elif name in AI_SOURCES:
                continue
            else:
                labels.append(name)
                groups.append([i])
    else:
        for i in range(N_CLASSES):
            labels.append(SOURCE_LABELS[i])
            groups.append([i])
    return labels, groups


def _shares(probs: np.ndarray, n: int) -> np.ndarray:
    raw  = probs * n
    base = np.floor(raw).astype(int)
    for g in np.argsort(-(raw - base))[: n - base.sum()]:
        base[g] += 1
    return base


def _attribute_sentences(text: str) -> list[dict] | None:
    text  = (text or "").strip()[:CHAR_LIMIT]
    if not text:
        return None
    items    = _split_sentences(text)
    sent_pos = [k for k, it in enumerate(items) if it[0] == "sent"]
    if not sent_pos:
        return None
    n = len(sent_pos)

    p_full          = _ensemble_probs_batch([_rebuild(items)])[0]
    glabels, groups = _display_groups(p_full)
    G               = len(groups)
    Pg              = np.array([p_full[g].sum() for g in groups])
    quota           = _shares(Pg, n)

    if n == 1:
        Cg               = np.zeros((1, G))
        Cg[0, int(np.argmax(Pg))] = Pg.max()
    else:
        variants = [_rebuild(items, skip=k) for k in sent_pos]
        P_minus  = _ensemble_probs_batch(variants)
        C        = p_full[None, :] - P_minus
        Cg       = np.stack([C[:, g].sum(axis=1) for g in groups], axis=1)

    pairs  = sorted(
        ((Cg[i, g], i, g) for i in range(n) for g in range(G)),
        key=lambda t: -t[0],
    )
    left   = quota.copy()
    chosen: dict[int, tuple[int, float]] = {}
    for pull, i, g in pairs:
        if i in chosen or left[g] == 0:
            continue
        chosen[i] = (g, pull)
        left[g]  -= 1

    results, row = [], 0
    for it in items:
        if it[0] == "break":
            results.append({"type": "break"})
            continue
        g, pull = chosen[row]
        name    = glabels[g]
        share   = Pg[g] * 100
        results.append({
            "type":      "sent",
            "text":      it[1],
            "label":     name,
            "color":     SOURCE_COLORS.get(name, "#e5e7eb"),
            "share_pct": round(share, 2),
            "pull_pp":   round(float(pull) * 100, 4),
            "tooltip":   (
                f"{name} ({share:.1f}% of full-text prediction) "
                f"β€” sentence pull: {float(pull)*100:+.2f} pp"
            ),
        })
        row += 1
    return results


# ── Pydantic schemas ──────────────────────────────────────────────────────────

class TextInput(BaseModel):
    text:  str  = Field(..., min_length=1, example="Artificial intelligence is transforming the world.")
    top_n: int  = Field(5, ge=1, le=22, description="How many top predictions to return.")
    merge: bool = Field(True, description="Fold minor AI-source probabilities into the top AI label.")


class BatchInput(BaseModel):
    texts: list[str] = Field(..., min_length=1, example=["Deep learning uses neural networks.", "The quick brown fox jumps."])
    top_n: int       = Field(5, ge=1, le=22)
    merge: bool      = Field(True)


class SentenceInput(BaseModel):
    text:          str  = Field(..., min_length=1, example="Machine learning is a subset of AI. It enables systems to learn from data.")
    max_sentences: int  = Field(50, ge=1, le=50000)
    top_n:         int  = Field(5, ge=1, le=22)
    merge:         bool = Field(True)


class AttributeInput(BaseModel):
    text: str = Field(..., min_length=1)


class OAIInput(BaseModel):
    text: str


# ── Routes β€” Info ─────────────────────────────────────────────────────────────

@app.get("/", tags=["Info"])
def root():
    """Health check and service info."""
    return {
        "status":        "ok",
        "model_loaded":  rf is not None,
        "model_format":  MODEL_FORMAT,
        "mode":          "Hybrid" if USE_DEBERTA else "RF-only",
        "num_classes":   N_CLASSES,
        "classes":       list(SOURCE_LABELS.values()),
        "docs":          "/docs",
    }


@app.get("/health", tags=["Info"])
def health():
    """Lightweight liveness probe for Docker / HF Spaces."""
    return {"status": "ok", "model_loaded": rf is not None}


@app.get("/classes", tags=["Info"])
def list_classes():
    """All source labels the model can predict."""
    _require_model()
    return {"classes": list(SOURCE_LABELS.values()), "count": N_CLASSES}


@app.get("/model/info", tags=["Info"])
def model_info():
    """Metadata about the loaded model stack."""
    _require_model()
    return {
        "rf_type":           type(rf).__name__,
        "model_format":      MODEL_FORMAT,
        "deberta_active":    USE_DEBERTA,
        "mode":              "Hybrid" if USE_DEBERTA else "RF-only",
        "ensemble_weights":  {"deberta": W_DEBERTA, "rf": W_RF} if USE_DEBERTA else None,
        "num_classes":       N_CLASSES,
        "classes":           list(SOURCE_LABELS.values()),
        "char_limit":        CHAR_LIMIT,
        "device":            DEVICE if USE_DEBERTA else "cpu",
    }


# ── Routes β€” Prediction ───────────────────────────────────────────────────────

@app.post("/predict", tags=["Prediction"])
def predict(body: TextInput):
    """
    Classify a single text block.

    Returns the most-likely AI/human source with confidence and ranked
    probability scores for the top-N candidates.
    """
    _require_model()
    try:
        result = _predict_one(body.text)
    except ValueError as exc:
        raise HTTPException(status_code=422, detail=str(exc))

    if body.merge:
        result = _merge_ai_sources(result)

    return {
        "top_prediction": result["ranked"][0][0],
        "confidence":     round(result["confidence"] * 100, 2),
        "mode":           result["mode"],
        "rf_pick":        result["rf_pick"],
        "deberta_pick":   result["deberta_pick"],
        "predictions":    _format_predictions(result, body.top_n),
        "input_preview":  body.text[:120] + ("…" if len(body.text) > 120 else ""),
    }


@app.post("/predict/batch", tags=["Prediction"])
def predict_batch(body: BatchInput):
    """
    Classify multiple texts in one request.

    Returns a prediction entry for each text in input order.
    Failed items carry ``status: "error"`` instead of crashing the whole batch.
    """
    _require_model()
    results = []
    for idx, text in enumerate(body.texts):
        try:
            res = _predict_one(text)
            if body.merge:
                res = _merge_ai_sources(res)
            results.append({
                "index":          idx,
                "status":         "ok",
                "top_prediction": res["ranked"][0][0],
                "confidence":     round(res["confidence"] * 100, 2),
                "mode":           res["mode"],
                "predictions":    _format_predictions(res, body.top_n),
            })
        except Exception as exc:
            results.append({"index": idx, "status": "error", "detail": str(exc)})

    return {"count": len(results), "results": results}


@app.post("/predict/sentences", tags=["Prediction"])
def predict_sentences(body: SentenceInput):
    """
    Split the text into sentences and classify each one individually.

    Sentences shorter than 10 characters are skipped.
    """
    _require_model()
    items      = _split_sentences(body.text)
    sent_items = [(k, it) for k, it in enumerate(items) if it[0] == "sent"]

    truncated  = len(sent_items) > body.max_sentences
    sent_items = sent_items[: body.max_sentences]

    output = []
    for seq_n, (_, it) in enumerate(sent_items, start=1):
        sent = it[1]
        if len(sent.strip()) < 10:
            continue
        try:
            res = _predict_one(sent)
            if body.merge:
                res = _merge_ai_sources(res)
            output.append({
                "sentence_number": seq_n,
                "text":            sent[:120] + ("…" if len(sent) > 120 else ""),
                "top_prediction":  res["ranked"][0][0],
                "confidence":      round(res["confidence"] * 100, 2),
                "predictions":     _format_predictions(res, body.top_n),
            })
        except Exception:
            continue

    return {
        "total_sentences": len(output),
        "truncated":       truncated,
        "mode":            "Hybrid" if USE_DEBERTA else "RF-only",
        "results":         output,
    }


@app.post("/predict/attribute", tags=["Prediction"])
def attribute(body: AttributeInput):
    """
    Sentence-level source attribution that mirrors the full-text prediction.

    Each sentence's source share is allocated via leave-one-out pull so the
    per-source ratios match the card prediction above. Returns a list of
    sentence objects with label, color, share_pct, pull_pp, and a hover
    tooltip β€” ready for frontend highlighting.
    """
    _require_model()
    try:
        sent_results = _attribute_sentences(body.text)
    except Exception as exc:
        raise HTTPException(status_code=500, detail=str(exc))

    if sent_results is None:
        raise HTTPException(status_code=422, detail="No usable sentences found in the input text.")

    sentences = [s for s in sent_results if s["type"] == "sent"]

    seen: dict[str, str] = {}
    for s in sentences:
        seen.setdefault(s["label"], s["color"])

    return {
        "mode":            "Hybrid" if USE_DEBERTA else "RF-only",
        "total_sentences": len(sentences),
        "legend":          [{"label": lbl, "color": col} for lbl, col in seen.items()],
        "results":         sent_results,
    }


# ── Routes β€” OpenAI-compatible ────────────────────────────────────────────────

@app.post("/v1/completions", tags=["OpenAI-Compatible"])
def oai_completions(data: OAIInput):
    """
    Drop-in OpenAI-style completions endpoint.

    Accepts {"text": "..."} and returns a choices array whose
    text field is the predicted source label.
    """
    _require_model()
    try:
        res = _predict_one(data.text)
        res = _merge_ai_sources(res)
    except ValueError as exc:
        raise HTTPException(status_code=422, detail=str(exc))

    return {
        "id":     "ai-source-classifier",
        "object": "text_completion",
        "model":  "ai-source-classifier-hybrid" if USE_DEBERTA else "ai-source-classifier-rf",
        "choices": [
            {
                "text":          res["ranked"][0][0],
                "index":         0,
                "finish_reason": "stop",
                "probabilities": _format_predictions(res, top_n=5),
            }
        ],
    }


# ── Entrypoint ────────────────────────────────────────────────────────────────

if __name__ == "__main__":
    import uvicorn
    uvicorn.run("main:app", host="0.0.0.0", port=int(os.getenv("PORT", "7860")), reload=False)