Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,145 +1,96 @@
|
|
| 1 |
import os
|
| 2 |
-
import
|
|
|
|
|
|
|
| 3 |
import torch
|
| 4 |
-
from
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
os.environ["
|
| 13 |
-
os.environ["
|
| 14 |
-
os.environ["
|
| 15 |
-
os.
|
| 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 |
-
39: 'text-davinci-002', 40: 'text-davinci-003'
|
| 51 |
-
}
|
| 52 |
-
|
| 53 |
-
# β
Text cleaning and normalization
|
| 54 |
-
def clean_text(text: str) -> str:
|
| 55 |
-
text = re.sub(r'\s{2,}', ' ', text)
|
| 56 |
-
text = re.sub(r'\s+([,.;:?!])', r'\1', text)
|
| 57 |
-
return text
|
| 58 |
-
|
| 59 |
-
newline_to_space = Replace(Regex(r'\s*\n\s*'), " ")
|
| 60 |
-
join_hyphen_break = Replace(Regex(r'(\w+)[--]\s*\n\s*(\w+)'), r"\1\2")
|
| 61 |
-
|
| 62 |
-
tokenizer.backend_tokenizer.normalizer = Sequence([
|
| 63 |
-
tokenizer.backend_tokenizer.normalizer,
|
| 64 |
-
join_hyphen_break,
|
| 65 |
-
newline_to_space,
|
| 66 |
-
Strip()
|
| 67 |
-
])
|
| 68 |
-
|
| 69 |
-
# β
FastAPI app
|
| 70 |
-
app = FastAPI(title="ModernBERT AI Text Detector")
|
| 71 |
-
|
| 72 |
-
class InputText(BaseModel):
|
| 73 |
-
text: str
|
| 74 |
-
|
| 75 |
-
def classify_text_ensemble(text: str):
|
| 76 |
-
"""Run ensemble classification and return percentages + identified model"""
|
| 77 |
-
cleaned_text = clean_text(text)
|
| 78 |
-
if not cleaned_text.strip():
|
| 79 |
-
return None
|
| 80 |
-
|
| 81 |
-
inputs = tokenizer(cleaned_text, return_tensors="pt", truncation=True, padding=True).to(device)
|
| 82 |
-
|
| 83 |
-
with torch.no_grad():
|
| 84 |
-
logits_1 = model_1(**inputs).logits
|
| 85 |
-
logits_2 = model_2(**inputs).logits
|
| 86 |
-
logits_3 = model_3(**inputs).logits
|
| 87 |
-
|
| 88 |
-
softmax_1 = torch.softmax(logits_1, dim=1)
|
| 89 |
-
softmax_2 = torch.softmax(logits_2, dim=1)
|
| 90 |
-
softmax_3 = torch.softmax(logits_3, dim=1)
|
| 91 |
-
|
| 92 |
-
averaged_probabilities = (softmax_1 + softmax_2 + softmax_3) / 3
|
| 93 |
-
probabilities = averaged_probabilities[0]
|
| 94 |
-
|
| 95 |
-
human_prob = probabilities[24].item()
|
| 96 |
-
ai_probs_clone = probabilities.clone()
|
| 97 |
-
ai_probs_clone[24] = 0
|
| 98 |
-
ai_total_prob = ai_probs_clone.sum().item()
|
| 99 |
-
|
| 100 |
-
total = human_prob + ai_total_prob
|
| 101 |
-
human_percentage = (human_prob / total) * 100
|
| 102 |
-
ai_percentage = (ai_total_prob / total) * 100
|
| 103 |
-
|
| 104 |
-
ai_argmax_index = torch.argmax(ai_probs_clone).item()
|
| 105 |
-
ai_model_name = label_mapping[ai_argmax_index]
|
| 106 |
-
|
| 107 |
-
return {
|
| 108 |
-
"ai_percentage": round(ai_percentage, 2),
|
| 109 |
-
"human_percentage": round(human_percentage, 2),
|
| 110 |
-
"identified_model": ai_model_name,
|
| 111 |
-
"is_ai": ai_percentage > human_percentage
|
| 112 |
-
}
|
| 113 |
-
|
| 114 |
-
@app.get("/")
|
| 115 |
-
def root():
|
| 116 |
-
return {"message": "ModernBERT AI Text Detector API is running. Use POST /analyze"}
|
| 117 |
-
|
| 118 |
@app.post("/analyze")
|
| 119 |
-
async def
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
return {"
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import os
|
| 2 |
+
from fastapi import FastAPI, WebSocket, UploadFile, File
|
| 3 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 4 |
+
from fastapi.responses import JSONResponse
|
| 5 |
import torch
|
| 6 |
+
from transformers import AutoTokenizer, AutoModelForSequenceClassification, pipeline
|
| 7 |
+
import asyncio
|
| 8 |
+
|
| 9 |
+
# =====================================================
|
| 10 |
+
# β
Fix Hugging Face Cache Permission Errors
|
| 11 |
+
# =====================================================
|
| 12 |
+
CACHE_DIR = "/tmp/hf_cache"
|
| 13 |
+
os.environ["HF_HOME"] = CACHE_DIR
|
| 14 |
+
os.environ["TRANSFORMERS_CACHE"] = CACHE_DIR
|
| 15 |
+
os.environ["HF_DATASETS_CACHE"] = CACHE_DIR
|
| 16 |
+
os.environ["HF_HUB_CACHE"] = CACHE_DIR
|
| 17 |
+
os.makedirs(CACHE_DIR, exist_ok=True)
|
| 18 |
+
|
| 19 |
+
# =====================================================
|
| 20 |
+
# β
Initialize Model and Tokenizer
|
| 21 |
+
# =====================================================
|
| 22 |
+
MODEL_NAME = "answerdotai/ModernBERT-base"
|
| 23 |
+
|
| 24 |
+
print("Loading model and tokenizer...")
|
| 25 |
+
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
|
| 26 |
+
model = AutoModelForSequenceClassification.from_pretrained(MODEL_NAME)
|
| 27 |
+
|
| 28 |
+
classifier = pipeline(
|
| 29 |
+
"text-classification",
|
| 30 |
+
model=model,
|
| 31 |
+
tokenizer=tokenizer,
|
| 32 |
+
device=0 if torch.cuda.is_available() else -1
|
| 33 |
+
)
|
| 34 |
+
|
| 35 |
+
# =====================================================
|
| 36 |
+
# β
FastAPI App Setup
|
| 37 |
+
# =====================================================
|
| 38 |
+
app = FastAPI(title="ModernBERT FastAPI Server")
|
| 39 |
+
|
| 40 |
+
# Allow all origins (for testing)
|
| 41 |
+
app.add_middleware(
|
| 42 |
+
CORSMiddleware,
|
| 43 |
+
allow_origins=["*"],
|
| 44 |
+
allow_credentials=True,
|
| 45 |
+
allow_methods=["*"],
|
| 46 |
+
allow_headers=["*"],
|
| 47 |
+
)
|
| 48 |
+
|
| 49 |
+
# =====================================================
|
| 50 |
+
# β
REST Endpoint Example
|
| 51 |
+
# =====================================================
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 52 |
@app.post("/analyze")
|
| 53 |
+
async def analyze_text(data: dict):
|
| 54 |
+
try:
|
| 55 |
+
text = data.get("text", "")
|
| 56 |
+
if not text.strip():
|
| 57 |
+
return JSONResponse({"error": "Empty text provided"}, status_code=400)
|
| 58 |
+
|
| 59 |
+
result = classifier(text)
|
| 60 |
+
return {"result": result}
|
| 61 |
+
except Exception as e:
|
| 62 |
+
return JSONResponse({"error": str(e)}, status_code=500)
|
| 63 |
+
|
| 64 |
+
# =====================================================
|
| 65 |
+
# β
WebSocket Endpoint (real-time classification)
|
| 66 |
+
# =====================================================
|
| 67 |
+
@app.websocket("/ws")
|
| 68 |
+
async def websocket_endpoint(ws: WebSocket):
|
| 69 |
+
await ws.accept()
|
| 70 |
+
idle_timeout = 60 # seconds
|
| 71 |
+
|
| 72 |
+
async def close_if_idle():
|
| 73 |
+
while True:
|
| 74 |
+
await asyncio.sleep(idle_timeout)
|
| 75 |
+
await ws.close(code=1000)
|
| 76 |
+
break
|
| 77 |
+
|
| 78 |
+
asyncio.create_task(close_if_idle())
|
| 79 |
+
|
| 80 |
+
try:
|
| 81 |
+
while True:
|
| 82 |
+
message = await ws.receive_text()
|
| 83 |
+
if message.lower() in ["exit", "quit"]:
|
| 84 |
+
await ws.close(code=1000)
|
| 85 |
+
break
|
| 86 |
+
result = classifier(message)
|
| 87 |
+
await ws.send_json(result)
|
| 88 |
+
except Exception:
|
| 89 |
+
await ws.close()
|
| 90 |
+
|
| 91 |
+
# =====================================================
|
| 92 |
+
# β
Root Endpoint
|
| 93 |
+
# =====================================================
|
| 94 |
+
@app.get("/")
|
| 95 |
+
def home():
|
| 96 |
+
return {"status": "ok", "model": MODEL_NAME, "device": "cuda" if torch.cuda.is_available() else "cpu"}
|