Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 15 additions & 2 deletions model-lab/app/main.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,25 @@
from fastapi import FastAPI, File, UploadFile
from contextlib import asynccontextmanager
from PIL import Image
import io
from app.model import predict_emotion
from app.model import predict_emotion, load_model, is_model_ready

app = FastAPI(title="Face Sentiment API")
@asynccontextmanager
async def lifespan(app: FastAPI):
load_model()
yield

app = FastAPI(title="Face Sentiment API", lifespan=lifespan)

@app.post("/predict")
async def predict(file: UploadFile = File(...)):
image = Image.open(io.BytesIO(await file.read()))
emotion = predict_emotion(image)
return {"emotion": emotion}

@app.get("/health")
def get_health():
if is_model_ready():
return {"status" : "ok"}
else:
return {"status" : "unavailable"}
13 changes: 11 additions & 2 deletions model-lab/app/model.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,20 @@
from typing import Optional
from transformers import AutoFeatureExtractor, AutoModelForImageClassification
from PIL import Image
import torch

MODEL_NAME = "trpakov/vit-face-expression"

extractor = AutoFeatureExtractor.from_pretrained(MODEL_NAME)
model = AutoModelForImageClassification.from_pretrained(MODEL_NAME)
extractor = None
model = None

def load_model():
global extractor, model
extractor = AutoFeatureExtractor.from_pretrained(MODEL_NAME)
model = AutoModelForImageClassification.from_pretrained(MODEL_NAME)

def is_model_ready() -> bool:
return extractor is not None and model is not None

def predict_emotion(image: Image.Image):
inputs = extractor(images=image, return_tensors="pt")
Expand Down