Spaces:
Sleeping
Sleeping
top n model 22 update
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336"""AI Source Classifier - FastAPI ApplicationIntegrates the trained Random Forest model from the notebookto expose prediction endpoints via REST API.Run with:uvicorn main:app --reload"""from fastapi import FastAPI, HTTPExceptionfrom pydantic import BaseModel, Fieldfrom typing import Optionalimport joblibimport numpy as npimport reimport 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 = NoneCLASSES = []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_tokenizereturn 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=10,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=50,description="Maximum number of sentences to analyse (1β50).",)top_n: int = Field(3,ge=1,le=10,description="Top predictions per sentence (1β10).",)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(3,ge=1,le=10,description="Number of top predictions per text (1β10).",)# 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 sourcetogether 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 sourcefor 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_sentencessentences = sentences[: body.max_sentences]results = []for i, sent in enumerate(sentences, start=1):if len(sent.strip()) < 10:continuetry:pred = _predict_text(sent, top_n=body.top_n)except ValueError:continueresults.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 endpointnow 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"],}],}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336"""AI Source Classifier - FastAPI ApplicationIntegrates the trained Random Forest model from the notebookto expose prediction endpoints via REST API.Run with:uvicorn main:app --reload"""from fastapi import FastAPI, HTTPExceptionfrom pydantic import BaseModel, Fieldfrom typing import Optionalimport joblibimport numpy as npimport reimport 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 = NoneCLASSES = []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_tokenizereturn 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=50,description="Maximum number of sentences to analyse (1β50).",)top_n: int = Field(3,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(3,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 sourcetogether 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 sourcefor 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_sentencessentences = sentences[: body.max_sentences]results = []for i, sent in enumerate(sentences, start=1):if len(sent.strip()) < 10:continuetry:pred = _predict_text(sent, top_n=body.top_n)except ValueError:continueresults.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 endpointnow 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"],}],}
main.py+335-335