Updated try and catch code
Browse files
app.py
CHANGED
|
@@ -31,8 +31,12 @@ def load_model():
|
|
| 31 |
@asynccontextmanager
|
| 32 |
async def lifespan(app: FastAPI):
|
| 33 |
global model, tokenizer
|
| 34 |
-
|
| 35 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 36 |
|
| 37 |
# Attach startup loader
|
| 38 |
app = FastAPI(lifespan=lifespan)
|
|
@@ -43,23 +47,26 @@ class TextInput(BaseModel):
|
|
| 43 |
|
| 44 |
# Sync text classification
|
| 45 |
def classify_text(sentence: str):
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
|
|
|
|
|
|
|
|
|
| 63 |
|
| 64 |
# POST route to analyze text
|
| 65 |
@app.post("/analyze")
|
|
@@ -68,13 +75,14 @@ async def analyze_text(data: TextInput):
|
|
| 68 |
if not user_input:
|
| 69 |
raise HTTPException(status_code=400, detail="Text cannot be empty")
|
| 70 |
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
|
|
|
| 78 |
|
| 79 |
# Health check route
|
| 80 |
@app.get("/health")
|
|
|
|
| 31 |
@asynccontextmanager
|
| 32 |
async def lifespan(app: FastAPI):
|
| 33 |
global model, tokenizer
|
| 34 |
+
try:
|
| 35 |
+
model, tokenizer = load_model()
|
| 36 |
+
yield
|
| 37 |
+
except Exception as e:
|
| 38 |
+
print(f"Startup error: {str(e)}")
|
| 39 |
+
raise RuntimeError(f"Failed to start application: {str(e)}")
|
| 40 |
|
| 41 |
# Attach startup loader
|
| 42 |
app = FastAPI(lifespan=lifespan)
|
|
|
|
| 47 |
|
| 48 |
# Sync text classification
|
| 49 |
def classify_text(sentence: str):
|
| 50 |
+
try:
|
| 51 |
+
inputs = tokenizer(sentence, return_tensors="pt", truncation=True, padding=True)
|
| 52 |
+
input_ids = inputs["input_ids"]
|
| 53 |
+
attention_mask = inputs["attention_mask"]
|
| 54 |
+
|
| 55 |
+
with torch.no_grad():
|
| 56 |
+
outputs = model(input_ids, attention_mask=attention_mask, labels=input_ids)
|
| 57 |
+
loss = outputs.loss
|
| 58 |
+
perplexity = torch.exp(loss).item()
|
| 59 |
+
|
| 60 |
+
if perplexity < 60:
|
| 61 |
+
result = "AI-generated"
|
| 62 |
+
elif perplexity < 80:
|
| 63 |
+
result = "Probably AI-generated"
|
| 64 |
+
else:
|
| 65 |
+
result = "Human-written"
|
| 66 |
+
|
| 67 |
+
return result, perplexity
|
| 68 |
+
except Exception as e:
|
| 69 |
+
raise RuntimeError(f"Error during text classification: {str(e)}")
|
| 70 |
|
| 71 |
# POST route to analyze text
|
| 72 |
@app.post("/analyze")
|
|
|
|
| 75 |
if not user_input:
|
| 76 |
raise HTTPException(status_code=400, detail="Text cannot be empty")
|
| 77 |
|
| 78 |
+
try:
|
| 79 |
+
result, perplexity = await asyncio.to_thread(classify_text, user_input)
|
| 80 |
+
return {
|
| 81 |
+
"result": result,
|
| 82 |
+
"perplexity": round(perplexity, 2),
|
| 83 |
+
}
|
| 84 |
+
except Exception as e:
|
| 85 |
+
raise HTTPException(status_code=500, detail=f"Analysis failed: {str(e)}")
|
| 86 |
|
| 87 |
# Health check route
|
| 88 |
@app.get("/health")
|