Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,14 +1,16 @@
|
|
| 1 |
-
|
|
|
|
| 2 |
from pydantic import BaseModel
|
| 3 |
from transformers import AutoTokenizer, AutoModelForSequenceClassification
|
| 4 |
import torch
|
| 5 |
-
import os
|
| 6 |
|
| 7 |
-
# Fix Hugging Face
|
| 8 |
os.environ["TRANSFORMERS_CACHE"] = "/tmp"
|
|
|
|
| 9 |
|
| 10 |
MODEL_NAME = "roberta-base-openai-detector"
|
| 11 |
|
|
|
|
| 12 |
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
|
| 13 |
model = AutoModelForSequenceClassification.from_pretrained(MODEL_NAME)
|
| 14 |
|
|
@@ -18,15 +20,15 @@ class InputText(BaseModel):
|
|
| 18 |
text: str
|
| 19 |
|
| 20 |
@app.get("/")
|
| 21 |
-
def
|
| 22 |
-
return {"
|
| 23 |
|
| 24 |
@app.post("/analyze")
|
| 25 |
-
async def
|
| 26 |
inputs = tokenizer(data.text, return_tensors="pt", truncation=True, padding=True)
|
| 27 |
with torch.no_grad():
|
| 28 |
logits = model(**inputs).logits
|
| 29 |
-
probs = torch.softmax(logits, dim=1).tolist()
|
| 30 |
|
| 31 |
results = [
|
| 32 |
{"label": model.config.id2label[i], "score": round(probs[i], 4)}
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
from fastapi import FastAPI
|
| 3 |
from pydantic import BaseModel
|
| 4 |
from transformers import AutoTokenizer, AutoModelForSequenceClassification
|
| 5 |
import torch
|
|
|
|
| 6 |
|
| 7 |
+
# ✅ Fix cache permission errors on Hugging Face Spaces
|
| 8 |
os.environ["TRANSFORMERS_CACHE"] = "/tmp"
|
| 9 |
+
os.environ["HF_HOME"] = "/tmp"
|
| 10 |
|
| 11 |
MODEL_NAME = "roberta-base-openai-detector"
|
| 12 |
|
| 13 |
+
# Load model safely inside /tmp
|
| 14 |
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
|
| 15 |
model = AutoModelForSequenceClassification.from_pretrained(MODEL_NAME)
|
| 16 |
|
|
|
|
| 20 |
text: str
|
| 21 |
|
| 22 |
@app.get("/")
|
| 23 |
+
def root():
|
| 24 |
+
return {"message": "AI Text Detector is running", "usage": "POST /analyze with {'text': 'your text'}"}
|
| 25 |
|
| 26 |
@app.post("/analyze")
|
| 27 |
+
async def analyze(data: InputText):
|
| 28 |
inputs = tokenizer(data.text, return_tensors="pt", truncation=True, padding=True)
|
| 29 |
with torch.no_grad():
|
| 30 |
logits = model(**inputs).logits
|
| 31 |
+
probs = torch.softmax(logits, dim=1)[0].tolist()
|
| 32 |
|
| 33 |
results = [
|
| 34 |
{"label": model.config.id2label[i], "score": round(probs[i], 4)}
|