""" 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'(? 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)