Spaces:
Sleeping
Sleeping
File size: 11,008 Bytes
eacc8dd 476eb29 eacc8dd 476eb29 eacc8dd 476eb29 eacc8dd 38cfd11 | 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 | """
AI Source Classifier - FastAPI Application
Integrates the trained Random Forest model from the notebook
to expose prediction endpoints via REST API.
Run with:
uvicorn main:app --reload
"""
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel, Field
from typing import Optional
import joblib
import numpy as np
import re
import os
# ββ App setup ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
app = FastAPI(
title="AI Source Classifier API",
description=(
"Classifies text to identify which AI model (ChatGPT, Claude, Gemini, etc.) "
"or human wrote it. Supports single-text prediction, sentence-by-sentence "
"analysis, and batch prediction."
),
version="1.0.0",
)
# ββ Model loading ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
MODEL_PATH = os.getenv("MODEL_PATH", "model_compressed.joblib")
try:
_model_data = joblib.load(MODEL_PATH)
vectorizer = _model_data["vectorizer"]
classifier = _model_data["classifier"]
label_encoder = _model_data["label_encoder"]
CLASSES = _model_data["classes"].tolist()
print(f"[startup] Model loaded β {len(CLASSES)} classes.")
except FileNotFoundError:
vectorizer = classifier = label_encoder = None
CLASSES = []
print(f"[startup] WARNING: model file '{MODEL_PATH}' not found. Train the model first.")
# ββ Helpers ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def _preprocess(text: str) -> str:
"""Lowercase, strip extra whitespace, remove special characters."""
if not text:
return ""
text = str(text).lower()
text = re.sub(r"\s+", " ", text)
text = re.sub(r"[^\w\s.,!?;:]", " ", text)
return text.strip()
def _split_sentences(text: str) -> list:
"""Split text into sentences using NLTK, falling back to regex."""
try:
from nltk.tokenize import sent_tokenize
return sent_tokenize(text)
except Exception:
return [s.strip() for s in re.split(r"(?<=[.!?])\s+", text) if s.strip()]
def _predict_text(text: str, top_n: int = 3) -> dict:
"""Core prediction logic. Returns top_n predictions with probabilities."""
processed = _preprocess(text)
if not processed:
raise ValueError("Text is empty after preprocessing.")
tfidf_vec = vectorizer.transform([processed])
probs = classifier.predict_proba(tfidf_vec)[0]
top_indices = np.argsort(probs)[-top_n:][::-1]
pred_idx = classifier.predict(tfidf_vec)[0]
top_label = label_encoder.inverse_transform([pred_idx])[0]
predictions = [
{
"source": label_encoder.inverse_transform([i])[0],
"probability": round(float(probs[i]) * 100, 2),
}
for i in top_indices
]
return {"top_prediction": top_label, "predictions": predictions}
def _check_model():
"""Raise 503 if the model is not loaded."""
if classifier is None:
raise HTTPException(
status_code=503,
detail=(
f"Model not loaded. Place '{MODEL_PATH}' next to main.py "
"and restart the server."
),
)
# ββ Pydantic schemas βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
class TextInput(BaseModel):
text: str = Field(
...,
min_length=10,
description="Text to classify (minimum 10 characters).",
example="Artificial intelligence is transforming the world at an unprecedented pace.",
)
top_n: int = Field(
3,
ge=1,
le=22,
description="Number of top predictions to return (1β10).",
)
class SentenceInput(BaseModel):
text: str = Field(
...,
min_length=10,
description="Text to analyse sentence by sentence.",
example=(
"Machine learning is a subset of AI. "
"It enables systems to learn from data."
),
)
max_sentences: int = Field(
20,
ge=1,
le=50000,
description="Maximum number of sentences to analyse (1β50000).",
)
top_n: int = Field(
22,
ge=1,
le=22,
description="Top predictions per sentence (1β22).",
)
class BatchInput(BaseModel):
texts: list = Field(
...,
description="List of texts to classify (at least one).",
example=[
"Deep learning uses neural networks.",
"The quick brown fox jumps over the lazy dog.",
],
)
top_n: int = Field(
22,
ge=1,
le=22,
description="Number of top predictions per text (1β22).",
)
# OpenAI-compatible schema (accepts raw text instead of raw feature vectors)
class OAIInput(BaseModel):
text: str = Field(
...,
description="Raw text to classify.",
example="Recursion is a technique where a function calls itself.",
)
# ββ GET routes βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
@app.get("/", summary="Health check", tags=["Info"])
def root():
"""Returns service status and model information."""
return {
"message": "AI Source Classifier API is running π",
"status": "ok",
"model_loaded": classifier is not None,
"num_classes": len(CLASSES),
"docs": "/docs",
}
@app.get("/classes", summary="List all supported source classes", tags=["Info"])
def list_classes():
"""
Returns the full list of AI/human source labels the model can predict,
e.g. ChatGPT, Claude, Gemini, Human written, etc.
"""
_check_model()
return {"classes": CLASSES, "count": len(CLASSES)}
@app.get("/model/info", summary="Model metadata", tags=["Info"])
def model_info():
"""Returns metadata about the loaded classifier."""
_check_model()
return {
"model_type": type(classifier).__name__,
"num_classes": len(CLASSES),
"classes": CLASSES,
"num_features": vectorizer.max_features,
"ngram_range": list(vectorizer.ngram_range),
"model_path": MODEL_PATH,
}
# ββ POST routes ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
@app.post("/predict", summary="Predict source for a single text", tags=["Prediction"])
def predict(body: TextInput):
"""
Classify a single block of text and return the most likely AI/human source
together with probability scores for the top-N candidates.
- **text**: The text to classify.
- **top_n**: How many ranked predictions to include in the response.
"""
_check_model()
try:
result = _predict_text(body.text, top_n=body.top_n)
except ValueError as exc:
raise HTTPException(status_code=422, detail=str(exc))
return {
"input_preview": body.text[:120] + ("..." if len(body.text) > 120 else ""),
**result,
}
@app.post(
"/predict/sentences",
summary="Sentence-by-sentence analysis",
tags=["Prediction"],
)
def predict_sentences(body: SentenceInput):
"""
Split the input text into sentences and predict the AI/human source
for each sentence individually. Sentences shorter than 10 characters are skipped.
- **text**: The full text to split and analyse.
- **max_sentences**: Cap on how many sentences are processed.
- **top_n**: Top predictions to return per sentence.
"""
_check_model()
sentences = _split_sentences(body.text)
truncated = len(sentences) > body.max_sentences
sentences = sentences[: body.max_sentences]
results = []
for i, sent in enumerate(sentences, start=1):
if len(sent.strip()) < 10:
continue
try:
pred = _predict_text(sent, top_n=body.top_n)
except ValueError:
continue
results.append(
{
"sentence_number": i,
"text": sent[:100] + ("..." if len(sent) > 100 else ""),
**pred,
}
)
return {
"total_sentences_analysed": len(results),
"truncated": truncated,
"results": results,
}
@app.post(
"/predict/batch",
summary="Batch prediction for multiple texts",
tags=["Prediction"],
)
def predict_batch(body: BatchInput):
"""
Classify multiple texts in a single request.
Returns a prediction for each text in the same order as the input list.
- **texts**: A list of text strings to classify.
- **top_n**: Number of top predictions to return for each text.
"""
_check_model()
if not body.texts:
raise HTTPException(status_code=422, detail="texts list must not be empty.")
results = []
for idx, text in enumerate(body.texts):
try:
pred = _predict_text(text, top_n=body.top_n)
results.append({"index": idx, "status": "ok", **pred})
except ValueError as exc:
results.append({"index": idx, "status": "error", "detail": str(exc)})
return {"count": len(results), "results": results}
@app.post(
"/v1/completions",
summary="OpenAI-compatible completions endpoint",
tags=["OpenAI-Compatible"],
)
def oai_completions(data: OAIInput):
"""
OpenAI-style completions endpoint for drop-in compatibility.
Accepts `{ "text": "..." }` and returns a `choices` array whose `text`
field contains the predicted source label.
**Note:** The original notebook used raw feature vectors; this endpoint
now accepts plain text and runs the full preprocessing + TF-IDF pipeline.
"""
_check_model()
try:
result = _predict_text(data.text, top_n=3)
except ValueError as exc:
raise HTTPException(status_code=422, detail=str(exc))
return {
"id": "model-prediction",
"object": "text_completion",
"model": "ai-source-classifier-rf",
"choices": [
{
"text": result["top_prediction"],
"index": 0,
"finish_reason": "stop",
"probabilities": result["predictions"],
}
],
} |