Spaces:
Sleeping
Sleeping
Add text emotion classifier (config, tokenizer, app, Dockerfile)
Browse files- .gitignore +2 -0
- Dockerfile +15 -0
- app.py +99 -0
- config.json +47 -0
- requirements.txt +6 -0
- tokenizer.json +0 -0
- tokenizer_config.json +15 -0
.gitignore
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Text Emotion Model
|
| 2 |
+
model.safetensors
|
Dockerfile
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM python:3.11
|
| 2 |
+
|
| 3 |
+
RUN useradd -m -u 1000 user
|
| 4 |
+
USER user
|
| 5 |
+
ENV PATH="/home/user/.local/bin:$PATH"
|
| 6 |
+
ENV HOME="/home/user"
|
| 7 |
+
|
| 8 |
+
WORKDIR /app
|
| 9 |
+
|
| 10 |
+
COPY --chown=user ./requirements.txt requirements.txt
|
| 11 |
+
RUN pip install --no-cache-dir --upgrade -r requirements.txt
|
| 12 |
+
|
| 13 |
+
COPY --chown=user . /app
|
| 14 |
+
|
| 15 |
+
CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860"]
|
app.py
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import base64
|
| 2 |
+
import json
|
| 3 |
+
import os
|
| 4 |
+
|
| 5 |
+
import torch
|
| 6 |
+
import torch.nn.functional as F
|
| 7 |
+
from fastapi import FastAPI, HTTPException, Request
|
| 8 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 9 |
+
from transformers import (
|
| 10 |
+
AutoTokenizer,
|
| 11 |
+
AutoModelForSequenceClassification,
|
| 12 |
+
)
|
| 13 |
+
|
| 14 |
+
app = FastAPI(title="Text Emotion Recognition")
|
| 15 |
+
|
| 16 |
+
app.add_middleware(
|
| 17 |
+
CORSMiddleware,
|
| 18 |
+
allow_origins=["*"],
|
| 19 |
+
allow_credentials=True,
|
| 20 |
+
allow_methods=["*"],
|
| 21 |
+
allow_headers=["*"],
|
| 22 |
+
)
|
| 23 |
+
|
| 24 |
+
MODEL_LABELS = ["Anger", "Disgust", "Fear", "Happy", "Neutral", "Sad", "Surprise"]
|
| 25 |
+
|
| 26 |
+
_model = None
|
| 27 |
+
_tokenizer = None
|
| 28 |
+
_device = None
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def load_model():
|
| 32 |
+
global _model, _tokenizer, _device
|
| 33 |
+
_device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 34 |
+
model_path = os.path.dirname(os.path.abspath(__file__))
|
| 35 |
+
_tokenizer = AutoTokenizer.from_pretrained(model_path)
|
| 36 |
+
_model = AutoModelForSequenceClassification.from_pretrained(model_path).to(_device).eval()
|
| 37 |
+
print(f"[INFO] Model loaded on {_device}")
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
@app.on_event("startup")
|
| 41 |
+
async def startup():
|
| 42 |
+
load_model()
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
@app.get("/")
|
| 46 |
+
@app.get("/health")
|
| 47 |
+
async def health():
|
| 48 |
+
return {
|
| 49 |
+
"status": "ok",
|
| 50 |
+
"model_loaded": _model is not None,
|
| 51 |
+
"device": _device,
|
| 52 |
+
}
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
@app.post("/predict_b64")
|
| 56 |
+
async def predict_b64(request: Request):
|
| 57 |
+
try:
|
| 58 |
+
body = await request.body()
|
| 59 |
+
content_type = request.headers.get("content-type", "")
|
| 60 |
+
|
| 61 |
+
if "application/json" in content_type or body.startswith(b"{"):
|
| 62 |
+
payload = json.loads(body)
|
| 63 |
+
text_b64 = payload.get("text", "")
|
| 64 |
+
else:
|
| 65 |
+
import urllib.parse
|
| 66 |
+
parsed = urllib.parse.parse_qs(body.decode())
|
| 67 |
+
raw = parsed.get("data", [None])[0]
|
| 68 |
+
if raw is None:
|
| 69 |
+
raise HTTPException(status_code=400, detail="Missing 'data' field")
|
| 70 |
+
payload = json.loads(raw)
|
| 71 |
+
text_b64 = payload.get("text", "")
|
| 72 |
+
|
| 73 |
+
if not text_b64:
|
| 74 |
+
raise HTTPException(status_code=400, detail="No text data found")
|
| 75 |
+
|
| 76 |
+
try:
|
| 77 |
+
text = base64.b64decode(text_b64).decode("utf-8")
|
| 78 |
+
except Exception:
|
| 79 |
+
text = text_b64
|
| 80 |
+
|
| 81 |
+
inputs = _tokenizer(text, return_tensors="pt", truncation=True, max_length=512).to(_device)
|
| 82 |
+
with torch.no_grad():
|
| 83 |
+
outputs = _model(**inputs)
|
| 84 |
+
probs = F.softmax(outputs.logits, dim=-1).squeeze(0)
|
| 85 |
+
|
| 86 |
+
probs_np = probs.cpu().numpy()
|
| 87 |
+
pred_idx = int(probs_np.argmax())
|
| 88 |
+
emotion = MODEL_LABELS[pred_idx]
|
| 89 |
+
prob_map = {c: round(float(probs_np[i]), 4) for i, c in enumerate(MODEL_LABELS)}
|
| 90 |
+
|
| 91 |
+
return {
|
| 92 |
+
"emotion": emotion,
|
| 93 |
+
"confidence": round(float(probs_np[pred_idx]), 4),
|
| 94 |
+
"probabilities": prob_map,
|
| 95 |
+
}
|
| 96 |
+
except HTTPException:
|
| 97 |
+
raise
|
| 98 |
+
except Exception as e:
|
| 99 |
+
raise HTTPException(status_code=500, detail=str(e))
|
config.json
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"add_cross_attention": false,
|
| 3 |
+
"architectures": [
|
| 4 |
+
"CamembertForSequenceClassification"
|
| 5 |
+
],
|
| 6 |
+
"attention_probs_dropout_prob": 0.1,
|
| 7 |
+
"bos_token_id": 5,
|
| 8 |
+
"classifier_dropout": null,
|
| 9 |
+
"dtype": "float32",
|
| 10 |
+
"eos_token_id": 6,
|
| 11 |
+
"hidden_act": "gelu",
|
| 12 |
+
"hidden_dropout_prob": 0.1,
|
| 13 |
+
"hidden_size": 768,
|
| 14 |
+
"id2label": {
|
| 15 |
+
"0": "Anger",
|
| 16 |
+
"1": "Disgust",
|
| 17 |
+
"2": "Fear",
|
| 18 |
+
"3": "Happy",
|
| 19 |
+
"4": "Neutral",
|
| 20 |
+
"5": "Sad",
|
| 21 |
+
"6": "Surprise"
|
| 22 |
+
},
|
| 23 |
+
"initializer_range": 0.02,
|
| 24 |
+
"intermediate_size": 3072,
|
| 25 |
+
"is_decoder": false,
|
| 26 |
+
"label2id": {
|
| 27 |
+
"Anger": 0,
|
| 28 |
+
"Disgust": 1,
|
| 29 |
+
"Fear": 2,
|
| 30 |
+
"Happy": 3,
|
| 31 |
+
"Neutral": 4,
|
| 32 |
+
"Sad": 5,
|
| 33 |
+
"Surprise": 6
|
| 34 |
+
},
|
| 35 |
+
"layer_norm_eps": 1e-05,
|
| 36 |
+
"max_position_embeddings": 514,
|
| 37 |
+
"model_type": "camembert",
|
| 38 |
+
"num_attention_heads": 12,
|
| 39 |
+
"num_hidden_layers": 12,
|
| 40 |
+
"output_past": true,
|
| 41 |
+
"pad_token_id": 1,
|
| 42 |
+
"tie_word_embeddings": true,
|
| 43 |
+
"transformers_version": "5.12.1",
|
| 44 |
+
"type_vocab_size": 1,
|
| 45 |
+
"use_cache": false,
|
| 46 |
+
"vocab_size": 32005
|
| 47 |
+
}
|
requirements.txt
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
fastapi>=0.104.0
|
| 2 |
+
uvicorn[standard]>=0.24.0
|
| 3 |
+
python-multipart>=0.0.6
|
| 4 |
+
torch>=2.0.0
|
| 5 |
+
transformers>=4.30.0
|
| 6 |
+
safetensors>=0.3.0
|
tokenizer.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
tokenizer_config.json
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"add_prefix_space": true,
|
| 3 |
+
"backend": "tokenizers",
|
| 4 |
+
"bos_token": "<s>",
|
| 5 |
+
"cls_token": "<s>",
|
| 6 |
+
"eos_token": "</s>",
|
| 7 |
+
"is_local": false,
|
| 8 |
+
"local_files_only": false,
|
| 9 |
+
"mask_token": "<mask>",
|
| 10 |
+
"model_max_length": 512,
|
| 11 |
+
"pad_token": "<pad>",
|
| 12 |
+
"sep_token": "</s>",
|
| 13 |
+
"tokenizer_class": "CamembertTokenizer",
|
| 14 |
+
"unk_token": "<unk>"
|
| 15 |
+
}
|