Spaces:
Sleeping
Sleeping
Upload main.py
Browse files
main.py
CHANGED
@@ -1,44 +1,50 @@
|
|
1 |
-
from fastapi import FastAPI, Request
|
2 |
-
from transformers import AutoModelForSequenceClassification,
|
3 |
-
from scipy.special import softmax
|
4 |
-
import numpy as np
|
5 |
-
import
|
6 |
-
|
7 |
-
app = FastAPI()
|
8 |
-
|
9 |
-
#
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
|
14 |
-
|
15 |
-
|
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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from fastapi import FastAPI, Request
|
2 |
+
from transformers import AutoModelForSequenceClassification, AutoConfig, RobertaTokenizer
|
3 |
+
from scipy.special import softmax
|
4 |
+
import numpy as np
|
5 |
+
import os
|
6 |
+
|
7 |
+
app = FastAPI()
|
8 |
+
|
9 |
+
# Set HF cache and home directory to writable path
|
10 |
+
os.environ["TRANSFORMERS_CACHE"] = "/tmp/hf-cache"
|
11 |
+
os.environ["HF_HOME"] = "/tmp/hf-home"
|
12 |
+
|
13 |
+
# Model and tokenizer setup
|
14 |
+
MODEL = "cardiffnlp/twitter-roberta-base-sentiment-latest"
|
15 |
+
TOKENIZER_MODEL = "cardiffnlp/twitter-roberta-base-sentiment"
|
16 |
+
|
17 |
+
tokenizer = RobertaTokenizer.from_pretrained(TOKENIZER_MODEL)
|
18 |
+
config = AutoConfig.from_pretrained(MODEL)
|
19 |
+
model = AutoModelForSequenceClassification.from_pretrained(MODEL)
|
20 |
+
|
21 |
+
# Preprocessing
|
22 |
+
def preprocess(text):
|
23 |
+
tokens = []
|
24 |
+
for t in text.split():
|
25 |
+
if t.startswith("@") and len(t) > 1:
|
26 |
+
t = "@user"
|
27 |
+
elif t.startswith("http"):
|
28 |
+
t = "http"
|
29 |
+
tokens.append(t)
|
30 |
+
return " ".join(tokens)
|
31 |
+
|
32 |
+
# Endpoint
|
33 |
+
@app.post("/analyze")
|
34 |
+
async def analyze(request: Request):
|
35 |
+
data = await request.json()
|
36 |
+
text = preprocess(data.get("text", ""))
|
37 |
+
|
38 |
+
encoded_input = tokenizer(text, return_tensors='pt')
|
39 |
+
output = model(**encoded_input)
|
40 |
+
scores = output[0][0].detach().numpy()
|
41 |
+
scores = softmax(scores)
|
42 |
+
|
43 |
+
ranking = np.argsort(scores)[::-1]
|
44 |
+
result = []
|
45 |
+
for i in ranking:
|
46 |
+
label = config.id2label[i]
|
47 |
+
score = round(float(scores[i]), 4)
|
48 |
+
result.append({"label": label, "score": score})
|
49 |
+
|
50 |
+
return {"result": result}
|