Spaces:
Sleeping
Sleeping
| from fastapi import FastAPI, Request | |
| from transformers import AutoTokenizer, AutoModelForSequenceClassification | |
| import torch | |
| import uvicorn | |
| import os | |
| # ✅ Fix permission issue on Hugging Face Spaces | |
| os.environ["TRANSFORMERS_CACHE"] = "/tmp/huggingface" | |
| app = FastAPI(title="AI Detector API") | |
| MODEL_NAME = "roberta-base-openai-detector" | |
| tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME) | |
| model = AutoModelForSequenceClassification.from_pretrained(MODEL_NAME) | |
| model.eval() | |
| def get_ai_probability(text: str) -> float: | |
| inputs = tokenizer(text, return_tensors="pt", truncation=True, max_length=512) | |
| with torch.no_grad(): | |
| logits = model(**inputs).logits | |
| probs = torch.softmax(logits, dim=1) | |
| ai_score = probs[0][1].item() * 100 | |
| return round(ai_score, 2) | |
| async def analyze_text(request: Request): | |
| data = await request.json() | |
| text = data.get("text", "").strip() | |
| if not text: | |
| return {"error": "No text provided"} | |
| paragraphs = [p.strip() for p in text.split("\n") if p.strip()] | |
| results = [] | |
| for i, para in enumerate(paragraphs, start=1): | |
| ai_score = get_ai_probability(para) | |
| results.append({ | |