File size: 18,266 Bytes
7967808 7c65163 54b7526 618a405 8a681a9 7967808 8a681a9 7e5fff1 8a681a9 618a405 8a681a9 296bce3 8a681a9 296bce3 7967808 8a681a9 54b7526 296bce3 54b7526 296bce3 b4a3218 296bce3 304a3ae 54b7526 8a681a9 54b7526 8a681a9 296bce3 8a681a9 296bce3 8a681a9 54b7526 7967808 54b7526 7967808 54b7526 8a681a9 d32c681 8a681a9 54b7526 8a681a9 618a405 8a681a9 296bce3 54b7526 296bce3 54b7526 8a681a9 618a405 8a681a9 54b7526 8a681a9 54b7526 618a405 54b7526 618a405 54b7526 b4a3218 54b7526 7967808 54b7526 296bce3 8963da2 296bce3 54b7526 8a681a9 54b7526 618a405 54b7526 fb2e9c0 8a681a9 54b7526 8a681a9 54b7526 618a405 54b7526 5c3b44c 618a405 54b7526 7967808 54b7526 618a405 54b7526 7967808 618a405 54b7526 8963da2 618a405 296bce3 618a405 5c3b44c 296bce3 618a405 54b7526 5c3b44c 7967808 54b7526 34ff790 7967808 54b7526 |
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 |
# app.py: AI Detection and Plagiarism Check API
from fastapi import FastAPI, UploadFile, File, HTTPException, BackgroundTasks
from fastapi.responses import JSONResponse
from sentence_transformers import SentenceTransformer
from transformers import AutoModelForSequenceClassification, AutoTokenizer
from PyPDF2 import PdfReader
from sklearn.metrics.pairwise import cosine_similarity
import torch
import os
import numpy as np
import shutil
import uuid
import tempfile
import logging
import time
from typing import Dict, Any
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)
app = FastAPI(
title="Essay Analysis API",
version="1.0.0",
docs_url="/docs",
redoc_url=None
)
# Configuration
CACHE_DIR = "/tmp/cache"
PLAGIARISM_THRESHOLD = 0.82
MAX_TEXT_LENGTH = 512
MODEL_NAME = "Essay-Grader/roberta-ai-detector-20250401_232702"
SENTENCE_MODEL = "sentence-transformers/all-roberta-large-v1"
# Global State
model_status = {
"model_loaded": False,
"last_error": None
}
# Model References
embedder = None
ai_tokenizer = None
ai_model = None
def initialize_models():
global embedder, ai_tokenizer, ai_model
try:
# Cleanup existing models
if embedder or ai_model:
del embedder, ai_tokenizer, ai_model
torch.cuda.empty_cache()
# Load models
logger.info("Loading models...")
embedder = SentenceTransformer(SENTENCE_MODEL)
ai_tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
ai_model = AutoModelForSequenceClassification.from_pretrained(
MODEL_NAME,
device_map="auto",
torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32
).eval()
# Warmup
test_text = "Model initialization text. " * 50
inputs = ai_tokenizer(test_text, return_tensors="pt", truncation=True)
with torch.no_grad():
ai_model(**inputs.to(ai_model.device))
model_status.update({"model_loaded": True, "last_error": None})
return True
except Exception as e:
error_msg = f"Model load failed: {str(e)}"
logger.error(error_msg)
model_status.update({"model_loaded": False, "last_error": error_msg})
return False
@app.on_event("startup")
async def startup_event():
for _ in range(3):
if initialize_models():
return
time.sleep(5)
logger.error("Failed to initialize models")
def extract_text_from_pdf(pdf_path: str) -> str:
try:
return " ".join(page.extract_text() for page in PdfReader(pdf_path).pages)
except Exception as e:
logger.error(f"PDF error: {str(e)}")
raise HTTPException(400, "Invalid PDF file")
def chunk_text(text: str) -> list:
sentences = [s.strip() for s in text.split('.') if s.strip()]
return ['. '.join(sentences[i:i+5]) + '.' for i in range(0, len(sentences), 5)]
def analyze_content(text: str) -> Dict[str, float]:
try:
inputs = ai_tokenizer(
text,
truncation=True,
padding='max_length',
max_length=MAX_TEXT_LENGTH,
return_tensors="pt"
).to(ai_model.device)
with torch.no_grad():
outputs = ai_model(**inputs)
probs = torch.softmax(outputs.logits, dim=1).squeeze()
return {
"Human_Written": round(probs[0].item() * 100, 2),
"AI_Generated": round(probs[1].item() * 100, 2)
}
except Exception as e:
logger.error(f"AI analysis failed: {str(e)}")
raise
def calculate_plagiarism(chunks: list) -> float:
if len(chunks) < 2:
return 0.0
embeddings = embedder.encode(chunks, batch_size=32)
similarity_matrix = cosine_similarity(embeddings)
np.fill_diagonal(similarity_matrix, 0)
similar_pairs = np.sum(similarity_matrix > PLAGIARISM_THRESHOLD)
total_possible = len(chunks) * (len(chunks) - 1) // 2
return round((similar_pairs / total_possible) * 100, 2) if total_possible else 0.0
@app.post("/analyze")
async def analyze_essay(file: UploadFile = File(...)) -> Dict[str, Any]:
if not model_status["model_loaded"]:
raise HTTPException(503, "Service unavailable")
if not file.filename.lower().endswith(".pdf"):
raise HTTPException(400, "PDF files only")
try:
with tempfile.TemporaryDirectory() as tmp_dir:
# Save file
file_path = f"{tmp_dir}/{uuid.uuid4()}.pdf"
with open(file_path, "wb") as f:
shutil.copyfileobj(file.file, f)
# Process
text = extract_text_from_pdf(file_path)
if not text.strip():
raise HTTPException(400, "Empty PDF content")
return {
"analysis": {
**analyze_content(text),
"Plagiarism_Score": calculate_plagiarism(chunk_text(text))
},
"status": "success"
}
except HTTPException:
raise
except Exception as e:
logger.error(f"Processing failed: {str(e)}")
raise HTTPException(500, "Analysis error")
@app.get("/health")
async def health_check() -> Dict[str, Any]:
return {"status": "operational" if model_status["model_loaded"] else "degraded"}
@app.get("/")
async def root():
return {"message": "Essay Analysis API - POST PDFs to /analyze"}
# from fastapi import FastAPI, UploadFile, File, HTTPException, BackgroundTasks
# from fastapi.responses import JSONResponse
# from sentence_transformers import SentenceTransformer
# from transformers import AutoModelForSequenceClassification, AutoTokenizer
# from PyPDF2 import PdfReader
# from sklearn.metrics.pairwise import cosine_similarity
# import torch
# import os
# import numpy as np
# import shutil
# import uuid
# import tempfile
# import logging
# import time
# from typing import Dict, Any
# # Configure logging
# logging.basicConfig(
# level=logging.INFO,
# format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
# )
# logger = logging.getLogger(__name__)
# app = FastAPI(
# title="Essay Analysis API",
# description="API for AI Content Detection and Plagiarism Checking",
# version="1.0.0",
# docs_url="/docs",
# redoc_url=None
# )
# # Configuration Constants
# CACHE_DIR = "/tmp/cache"
# PLAGIARISM_THRESHOLD = 0.82 # Adjusted threshold for better differentiation
# MAX_TEXT_LENGTH = 512
# MODEL_NAME = "Essay-Grader/roberta-ai-detector-20250401_232702"
# SENTENCE_MODEL = "sentence-transformers/all-roberta-large-v1"
# # Global State Management
# model_status = {
# "model_loaded": False,
# "last_error": None,
# "last_reload_attempt": None,
# "retry_count": 0
# }
# # Model References
# embedder = None
# ai_tokenizer = None
# ai_model = None
# def initialize_models():
# """Initialize ML models with enhanced error handling"""
# global embedder, ai_tokenizer, ai_model
# try:
# # Clear previous models and cache
# if embedder or ai_model:
# del embedder, ai_tokenizer, ai_model
# torch.cuda.empty_cache()
# logger.info("Loading sentence transformer model...")
# embedder = SentenceTransformer(
# SENTENCE_MODEL,
# cache_folder=CACHE_DIR,
# device='cuda' if torch.cuda.is_available() else 'cpu'
# )
# logger.info(f"Loading AI detection model: {MODEL_NAME}")
# ai_tokenizer = AutoTokenizer.from_pretrained(
# MODEL_NAME,
# cache_dir=CACHE_DIR,
# use_fast=True,
# padding_side='left'
# )
# ai_model = AutoModelForSequenceClassification.from_pretrained(
# MODEL_NAME,
# cache_dir=CACHE_DIR,
# use_safetensors=True,
# device_map="auto",
# trust_remote_code=True,
# torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32
# ).eval()
# # Warmup with varied inputs
# warmup_texts = [
# "The quick brown fox jumps over the lazy dog.",
# "Artificial intelligence is transforming modern society.",
# "Climate change remains one of humanity's greatest challenges."
# ]
# device = ai_model.device
# for text in warmup_texts:
# inputs = ai_tokenizer(
# text,
# truncation=True,
# padding='max_length',
# max_length=MAX_TEXT_LENGTH,
# return_tensors="pt"
# ).to(device)
# with torch.no_grad(), torch.cuda.amp.autocast(enabled=torch.cuda.is_available()):
# outputs = ai_model(**inputs)
# probs = torch.softmax(outputs.logits, dim=1)
# logger.debug(f"Warmup prob: {probs.cpu().numpy()}")
# model_status.update({
# "model_loaded": True,
# "last_error": None
# })
# return True
# except Exception as e:
# error_msg = f"Model initialization failed: {str(e)}"
# logger.error(error_msg, exc_info=True)
# model_status.update({
# "model_loaded": False,
# "last_error": error_msg
# })
# return False
# @app.on_event("startup")
# async def startup_event():
# """Enhanced startup with better resource management"""
# os.makedirs(CACHE_DIR, exist_ok=True)
# max_retries = 3
# while model_status["retry_count"] < max_retries:
# if initialize_models():
# model_status.update({"retry_count": 0})
# return
# model_status["retry_count"] += 1
# logger.warning(f"Retry attempt {model_status['retry_count']}/{max_retries}")
# time.sleep(10)
# torch.cuda.empty_cache()
# logger.critical("Failed to initialize models after multiple attempts")
# def extract_text_from_pdf(pdf_path: str) -> str:
# """Robust PDF text extraction"""
# try:
# reader = PdfReader(pdf_path)
# text = []
# for page in reader.pages:
# page_text = page.extract_text()
# if page_text:
# text.append(page_text.strip())
# return "\n".join(text)
# except Exception as e:
# logger.error(f"PDF extraction failed: {str(e)}")
# raise RuntimeError("Failed to extract text from PDF")
# def chunk_text(text: str, chunk_size: int = 5) -> list:
# """Improved text chunking with overlap"""
# sentences = [s.strip() for s in text.split('.') if s.strip()]
# chunks = []
# for i in range(0, len(sentences), chunk_size):
# start = max(0, i - 1) # Add overlap
# end = i + chunk_size
# chunk = '. '.join(sentences[start:end]) + '.'
# chunks.append(chunk)
# return chunks
# def analyze_ai_content(text: str) -> Dict[str, float]:
# """Enhanced AI analysis with dynamic batching"""
# try:
# if len(text) < 100:
# logger.warning("Text too short for reliable analysis")
# return {"human_written": 50.0, "ai_generated": 50.0}
# device = ai_model.device
# inputs = ai_tokenizer(
# text,
# truncation=True,
# padding='max_length',
# max_length=MAX_TEXT_LENGTH,
# return_tensors="pt"
# ).to(device)
# # Handle long texts with sliding window
# if inputs.input_ids.shape[1] > MAX_TEXT_LENGTH:
# window_size = MAX_TEXT_LENGTH - 128 # 128 token overlap
# all_probs = []
# for i in range(0, inputs.input_ids.shape[1], window_size):
# chunk = inputs.input_ids[:, i:i+MAX_TEXT_LENGTH]
# with torch.no_grad(), torch.cuda.amp.autocast(enabled=torch.cuda.is_available()):
# outputs = ai_model(input_ids=chunk)
# probs = torch.softmax(outputs.logits, dim=1)
# all_probs.append(probs.cpu())
# avg_probs = torch.mean(torch.cat(all_probs), dim=0)
# else:
# with torch.no_grad(), torch.cuda.amp.autocast(enabled=torch.cuda.is_available()):
# outputs = ai_model(**inputs)
# avg_probs = torch.softmax(outputs.logits, dim=1).squeeze()
# human = avg_probs[0].item() * 100
# ai = avg_probs[1].item() * 100
# logger.info(f"AI detection results - Human: {human:.2f}%, AI: {ai:.2f}%")
# return {
# "human_written": round(human, 2),
# "ai_generated": round(ai, 2)
# }
# except Exception as e:
# logger.error(f"AI analysis error: {str(e)}", exc_info=True)
# raise RuntimeError("Failed to analyze text content")
# def calculate_plagiarism_score(chunks: list) -> float:
# """Improved plagiarism detection with adaptive thresholds"""
# if len(chunks) < 2:
# return 0.0
# try:
# # Dynamic batch sizing
# batch_size = 32 if torch.cuda.is_available() else 8
# embeddings = []
# for i in range(0, len(chunks), batch_size):
# batch = chunks[i:i+batch_size]
# batch_embeddings = embedder.encode(
# batch,
# convert_to_tensor=True,
# show_progress_bar=False,
# normalize_embeddings=True
# )
# embeddings.append(batch_embeddings.cpu().numpy())
# embeddings = np.concatenate(embeddings)
# similarity_matrix = cosine_similarity(embeddings)
# np.fill_diagonal(similarity_matrix, -1) # Ignore self-similarity
# # Adaptive threshold calculation
# avg_sim = np.mean(similarity_matrix)
# std_dev = np.std(similarity_matrix)
# dynamic_threshold = min(
# PLAGIARISM_THRESHOLD,
# avg_sim + std_dev * 0.5
# )
# logger.info(f"Using dynamic plagiarism threshold: {dynamic_threshold:.3f}")
# similar_pairs = np.sum(similarity_matrix > dynamic_threshold)
# total_possible = len(chunks) * (len(chunks) - 1) // 2
# score = round((similar_pairs / total_possible) * 100, 2) if total_possible else 0.0
# logger.info(f"Plagiarism score: {score}%")
# return score
# except Exception as e:
# logger.error(f"Plagiarism calculation error: {str(e)}", exc_info=True)
# raise RuntimeError("Failed to calculate plagiarism score")
# @app.post("/analyze")
# async def analyze_document(file: UploadFile = File(...)) -> Dict[str, Any]:
# """Enhanced analysis endpoint with detailed processing"""
# start_time = time.time()
# if not model_status["model_loaded"]:
# raise HTTPException(503, "Service unavailable - models not loaded")
# if not file.filename.lower().endswith(".pdf"):
# raise HTTPException(400, "Only PDF files are supported")
# try:
# with tempfile.TemporaryDirectory() as tmp_dir:
# # File handling
# file_path = os.path.join(tmp_dir, f"{uuid.uuid4()}.pdf")
# with open(file_path, "wb") as buffer:
# shutil.copyfileobj(file.file, buffer)
# logger.info(f"Processing file: {file.filename}")
# text = extract_text_from_pdf(file_path)
# if not text.strip():
# raise HTTPException(400, "No text found in document")
# text_length = len(text)
# logger.info(f"Extracted {text_length} characters")
# if text_length < 200:
# raise HTTPException(400, "Insufficient text for analysis")
# # Core analysis
# ai_result = analyze_ai_content(text)
# chunks = chunk_text(text)
# logger.info(f"Analyzing {len(chunks)} text chunks")
# plagiarism_score = calculate_plagiarism_score(chunks)
# # Result compilation
# processing_time = time.time() - start_time
# logger.info(f"Analysis completed in {processing_time:.2f}s")
# return {
# "analysis": {
# "ai_detection": ai_result,
# "plagiarism_score": plagiarism_score,
# "text_metrics": {
# "characters": text_length,
# "chunks_analyzed": len(chunks)
# },
# "processing_time": round(processing_time, 2)
# },
# "status": "success"
# }
# except HTTPException:
# raise
# except Exception as e:
# logger.error(f"Analysis pipeline failed: {str(e)}", exc_info=True)
# raise HTTPException(500, f"Analysis failed: {str(e)}")
# @app.get("/health")
# async def health_check() -> Dict[str, Any]:
# """Enhanced health check with resource info"""
# return {
# "status": "operational" if model_status["model_loaded"] else "degraded",
# "model_loaded": model_status["model_loaded"],
# "last_error": model_status["last_error"],
# "system": {
# "device": str(ai_model.device) if ai_model else "unknown",
# "torch_version": torch.__version__,
# "cuda_available": torch.cuda.is_available()
# }
# }
# @app.post("/reload-models")
# async def reload_models(background_tasks: BackgroundTasks):
# """Model reload endpoint with resource cleanup"""
# background_tasks.add_task(initialize_models)
# return {"status": "reload-initiated", "message": "Model reload in progress"}
# @app.get("/")
# async def root():
# """Root endpoint with documentation"""
# return {
# "service": "Essay Analysis API",
# "version": "1.0.0",
# "endpoints": {
# "/analyze": "POST - Analyze PDF document",
# "/health": "GET - System health check",
# "/reload-models": "POST - Reload AI models"
# }
# } |