Spaces:
Runtime error
Runtime error
Upload 2 files
Browse files- app.py +54 -0
- requirements.txt +4 -0
app.py
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import FastAPI
|
| 2 |
+
from pydantic import BaseModel
|
| 3 |
+
import tensorflow as tf
|
| 4 |
+
import sentencepiece as spm
|
| 5 |
+
import numpy as np
|
| 6 |
+
|
| 7 |
+
app = FastAPI()
|
| 8 |
+
|
| 9 |
+
# Load tokenizer and model
|
| 10 |
+
sp = spm.SentencePieceProcessor()
|
| 11 |
+
sp.load('sentencepiece.bpe.model')
|
| 12 |
+
|
| 13 |
+
interpreter = tf.lite.Interpreter(model_path="toxic_xlmr.tflite")
|
| 14 |
+
interpreter.allocate_tensors()
|
| 15 |
+
|
| 16 |
+
input_details = interpreter.get_input_details()
|
| 17 |
+
output_details = interpreter.get_output_details()
|
| 18 |
+
max_len = input_details[0]['shape'][1]
|
| 19 |
+
|
| 20 |
+
class TextRequest(BaseModel):
|
| 21 |
+
text: str
|
| 22 |
+
|
| 23 |
+
@app.post("/predict")
|
| 24 |
+
def predict(request: TextRequest):
|
| 25 |
+
# Tokenize text
|
| 26 |
+
# XLM-R uses 0 for <s> and 2 for </s>
|
| 27 |
+
tokens = [0] + sp.encode_as_ids(request.text) + [2]
|
| 28 |
+
|
| 29 |
+
if len(tokens) > max_len:
|
| 30 |
+
tokens = tokens[:max_len]
|
| 31 |
+
tokens[-1] = 2
|
| 32 |
+
else:
|
| 33 |
+
# pad with 1
|
| 34 |
+
tokens = tokens + [1] * (max_len - len(tokens))
|
| 35 |
+
|
| 36 |
+
input_data = np.array([tokens], dtype=np.int32)
|
| 37 |
+
|
| 38 |
+
interpreter.set_tensor(input_details[0]['index'], input_data)
|
| 39 |
+
interpreter.invoke()
|
| 40 |
+
|
| 41 |
+
output_data = interpreter.get_tensor(output_details[0]['index'])
|
| 42 |
+
|
| 43 |
+
# Assuming output shape [1, 2] where index 1 is toxic class
|
| 44 |
+
# or shape [1, 1] where 0 is toxic class.
|
| 45 |
+
if output_data.shape[-1] == 2:
|
| 46 |
+
is_toxic = bool(output_data[0][1] > 0.5)
|
| 47 |
+
else:
|
| 48 |
+
is_toxic = bool(output_data[0][0] > 0.5)
|
| 49 |
+
|
| 50 |
+
return {"is_toxic": is_toxic}
|
| 51 |
+
|
| 52 |
+
@app.get("/")
|
| 53 |
+
def read_root():
|
| 54 |
+
return {"status": "Toxic API is running!"}
|
requirements.txt
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
fastapi
|
| 2 |
+
uvicorn
|
| 3 |
+
tensorflow-cpu
|
| 4 |
+
sentencepiece
|