Spaces:
Sleeping
Sleeping
Download main.py from XDR-SAM/ai-source-classifier: direct link, hf CLI and curl.
- Browser
- Download file 11 kB
-
https://huggingface.co/spaces/XDR-SAM/ai-source-classifier/resolve/main/main.py
- Command line
-
hf download hf://spaces/XDR-SAM/ai-source-classifier/main.py
-
curl -L -o main.py https://huggingface.co/spaces/XDR-SAM/ai-source-classifier/resolve/main/main.py
11 kB
| """ | |
| 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 βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| 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", | |
| } | |
| 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)} | |
| 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 ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| 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, | |
| } | |
| 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, | |
| } | |
| 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} | |
| 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"], | |
| } | |
| ], | |
| } |