Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,7 +1,29 @@
|
|
| 1 |
from fastapi import FastAPI
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
|
| 3 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4 |
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
from fastapi import FastAPI
|
| 2 |
+
from pydantic import BaseModel
|
| 3 |
+
from transformers import pipeline
|
| 4 |
+
import os
|
| 5 |
+
import asyncio
|
| 6 |
+
from contextlib import asynccontextmanager
|
| 7 |
|
| 8 |
+
@asynccontextmanager
|
| 9 |
+
async def lifespan(app: FastAPI):
|
| 10 |
+
global classifier
|
| 11 |
+
classifier = pipeline("sentiment-analysis")
|
| 12 |
+
yield
|
| 13 |
|
| 14 |
+
app = FastAPI(lifespan=lifespan)
|
| 15 |
+
|
| 16 |
+
class TextRequest(BaseModel):
|
| 17 |
+
text: str
|
| 18 |
+
|
| 19 |
+
@app.post("/analyze")
|
| 20 |
+
async def analyze(request: TextRequest):
|
| 21 |
+
try:
|
| 22 |
+
result = classifier(request.text)[0]
|
| 23 |
+
return {
|
| 24 |
+
"text": request.text,
|
| 25 |
+
"sentiment": result['label'],
|
| 26 |
+
"confidence": round(result['score'], 4)
|
| 27 |
+
}
|
| 28 |
+
except Exception as e:
|
| 29 |
+
return {"error": str(e)}
|