Update app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354551 unmodified line57585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105from fastapi import FastAPI, HTTPException, Dependsfrom fastapi.security import HTTPBearerfrom pydantic import BaseModelfrom transformers import GPT2LMHeadModel, GPT2TokenizerFast, GPT2Configimport torchimport asynciofrom contextlib import asynccontextmanager# FastAPI app instanceapp = FastAPI()# Global model and tokenizer variablesmodel, tokenizer = None, None# HTTPBearer instance for securitybearer_scheme = HTTPBearer()# Function to load model and tokenizerdef load_model():model_path = "./Ai-Text-Detector/model"weights_path = "./Ai-Text-Detector/model_weights.pth"try:tokenizer = GPT2TokenizerFast.from_pretrained(model_path)config = GPT2Config.from_pretrained(model_path)model = GPT2LMHeadModel(config)model.load_state_dict(torch.load(weights_path, map_location=torch.device("cpu")))model.eval() # Set model to evaluation modeexcept Exception as e:raise RuntimeError(f"Error loading model: {str(e)}")return model, tokenizer# Load model on app startup@asynccontextmanagerasync def lifespan(app: FastAPI):global model, tokenizermodel, tokenizer = load_model()yield# Attach startup loaderapp = FastAPI(lifespan=lifespan)# Input schemaclass TextInput(BaseModel):text: str# Sync text classificationdef classify_text(sentence: str):inputs = tokenizer(sentence, return_tensors="pt", truncation=True, padding=True)input_ids = inputs["input_ids"]attention_mask = inputs["attention_mask"]with torch.no_grad():outputs = model(input_ids, attention_mask=attention_mask, labels=input_ids)1 unmodified lineperplexity = torch.exp(loss).item()if perplexity < 60:result = "AI-generated"elif perplexity < 80:result = "Probably AI-generated"else:result = "Human-written"return result, perplexity# POST route to analyze text with Bearer token@app.post("/analyze")async def analyze_text(data: TextInput, token: str = Depends(bearer_scheme)):user_input = data.text.strip()if not user_input:raise HTTPException(status_code=400, detail="Text cannot be empty")# Check if there are at least two wordsword_count = len(user_input.split())if word_count < 2:raise HTTPException(status_code=400, detail="Text must contain at least two words")# The token is automatically extracted from the Authorization header# You can validate the token here if neededprint(f"Received Bearer Token: {token}")# Run classification asynchronously to prevent blockingresult, perplexity = await asyncio.to_thread(classify_text, user_input)return {"result": result,"perplexity": round(perplexity, 2),}# Health check route@app.get("/health")async def health_check():return {"status": "ok"}# Simple index route@app.get("/")def index():return {"message": "FastAPI API is up.","try": "/docs to test the API.","status": "OK"}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879801 unmodified line828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169from fastapi import FastAPI, HTTPException, Depends, UploadFile, Filefrom fastapi.security import HTTPBearerfrom pydantic import BaseModelfrom transformers import GPT2LMHeadModel, GPT2TokenizerFast, GPT2Configfrom dotenv import load_dotenvfrom contextlib import asynccontextmanagerimport torchimport asyncioimport mathimport osimport docximport fitz # PyMuPDFimport loggingfrom io import BytesIO# Setup logginglogging.basicConfig(level=logging.DEBUG)# Load environment variablesload_dotenv()SECRET_TOKEN = os.getenv("SECRET_TOKEN")# File PathsMODEL_PATH = "./AI-MODEL/model"WEIGHTS_PATH = "./AI-MODEL/model_weights.pth"# Global model and tokenizermodel = Nonetokenizer = Nonedevice = torch.device("cuda" if torch.cuda.is_available() else "cpu")# Securitybearer_scheme = HTTPBearer()# Text input schemaclass TextInput(BaseModel):text: str# Load model and tokenizerdef load_model():global model, tokenizertry:tokenizer = GPT2TokenizerFast.from_pretrained(MODEL_PATH)config = GPT2Config.from_pretrained(MODEL_PATH)model_instance = GPT2LMHeadModel(config)model_instance.load_state_dict(torch.load(WEIGHTS_PATH, map_location=device))model_instance.to(device)model_instance.eval()model = model_instanceexcept Exception as e:raise RuntimeError(f"Error loading model: {str(e)}")# Lifespan event to load model on startup@asynccontextmanagerasync def lifespan(app: FastAPI):load_model()yield# FastAPI app instanceapp = FastAPI(lifespan=lifespan)# Classification logicdef classify_text(text: str):if not model or not tokenizer:raise RuntimeError("Model or tokenizer not loaded.")inputs = tokenizer(text,return_tensors="pt",truncation=True,padding="max_length",max_length=512)input_ids = inputs["input_ids"].to(device)attention_mask = inputs["attention_mask"].to(device)with torch.no_grad():outputs = model(input_ids, attention_mask=attention_mask, labels=input_ids)1 unmodified lineperplexity = torch.exp(loss).item()if perplexity < 60:return "AI-generated", perplexityelif perplexity < 80:return "Probably AI-generated", perplexityelse:return "Human-written", perplexity# Score converter (optional utility)def Perplexity_Converter(perplexity):return max(0, min(100, 100 - math.log2(perplexity) * 10))# Analyze text directly@app.post("/analyze")async def analyze_text(data: TextInput, token: str = Depends(bearer_scheme)):if token.credentials != SECRET_TOKEN:raise HTTPException(status_code=401, detail="Invalid token")text = data.text.strip()if not text:raise HTTPException(status_code=400, detail="Text cannot be empty")if len(text.split()) < 2:raise HTTPException(status_code=400, detail="Text must contain at least two words")try:label, perplexity = await asyncio.to_thread(classify_text, text)return {"result": label, "perplexity": round(perplexity, 2)}except Exception as e:logging.error(f"Text analysis failed: {str(e)}")raise HTTPException(status_code=500, detail="Model processing error")# -------- File Upload and Parsing -------- #def parse_docx(file: BytesIO):doc = docx.Document(file)return "\n".join(para.text for para in doc.paragraphs)def parse_pdf(file: BytesIO):try:doc = fitz.open(stream=file, filetype="pdf")return "".join([doc.load_page(i).get_text() for i in range(doc.page_count)])except Exception as e:logging.error(f"PDF error: {str(e)}")raise HTTPException(status_code=500, detail="Error processing PDF")def parse_txt(file: BytesIO):return file.read().decode("utf-8")@app.post("/upload/")async def upload_file(file: UploadFile = File(...), token: str = Depends(bearer_scheme)):if token.credentials != SECRET_TOKEN:raise HTTPException(status_code=401, detail="Invalid token")try:content_type = file.content_typecontent = await file.read()if content_type == 'application/vnd.openxmlformats-officedocument.wordprocessingml.document':text = parse_docx(BytesIO(content))elif content_type == 'application/pdf':text = parse_pdf(BytesIO(content))elif content_type == 'text/plain':text = parse_txt(BytesIO(content))else:raise HTTPException(status_code=400, detail="Unsupported file type")if len(text) > 10000:return {"message": "File contains more than 10,000 characters."}cleaned_text = text.replace("\n", "").replace("\t", "")label, perplexity = await asyncio.to_thread(classify_text, cleaned_text)return {"result": label, "perplexity": round(perplexity, 2)}except Exception as e:logging.error(f"File processing error: {str(e)}")raise HTTPException(status_code=500, detail="Error processing file")# Health Check and Index@app.get("/health")def health_check():return {"status": "ok"}@app.get("/")def index():return {"message": "FastAPI AI Text Detector is running.","usage": "Use /docs or /analyze or /upload to test the API."}
app.py+124-60