serengil / deepface

A Lightweight Face Recognition and Facial Attribute Analysis (Age, Gender, Emotion and Race) Library for Python
https://bit.ly/deepface-py
MIT License
14.62k stars 2.22k forks source link

How do I preload retinaFace and other models? #540

Closed martinenkoEduard closed 2 years ago

martinenkoEduard commented 2 years ago

I want to build a simple REST API for face recognition. Is there a way to preload retinaFace and other models beforehand (before first request).

martinenkoEduard commented 2 years ago

What is the best way to use deepface with flask?

serengil commented 2 years ago

yes you can. load the pre-trained model in the following file and pass to analyze or verify funciton.

https://github.com/serengil/deepface/blob/master/api/api.py#L104

serengil commented 2 years ago

i am using flask with gunicorn

martinenkoEduard commented 2 years ago

I mean - that in this case the first call of analyze on this particular gunicorn worker will take a long time, because it will be loading model into memory.

How do I load model when the flask application is starting. So even the first request is fast.

serengil commented 2 years ago

i mean that you can move loading pre-trained model logic in start up

if you change the line 104 as:

models = {}
models['emotion'] = build_model('Emotion')
models['age'] = build_model('Age')
models['gender'] = build_model('Gender')
models['race'] = build_model('Race')
resp_obj = DeepFace.analyze(instances, actions = ["age", "gender", "emotion", "race"], models = models)

this will spend time on app start up and your first request will be fast.

if you do not pass models to analyze function, then the library spend time to build models in the first request.

martinenkoEduard commented 2 years ago

What models should I use for DeepFace.represent and detect_faces?

serengil commented 2 years ago

facenet and retinaface

martinenkoEduard commented 2 years ago

I mean how do I define it?

models = {} models['emotion'] = build_model('Emotion') models['age'] = build_model('Age') models['gender'] = build_model('Gender') models['race'] = build_model('Race')

models['represent'] = build_model('facenet512 ')?

serengil commented 2 years ago

this code snippet is for facial analysis. facenet is face recognition model. they are different.

you can find how to use it in the code docs: https://github.com/serengil/deepface/blob/master/deepface/DeepFace.py#L271

models = {}

models['emotion'] = build_model('Emotion')
models['age'] = build_model('Age')
models['gender'] = build_model('Gender')
models['race'] = build_model('Race')

resp_obj = DeepFace.analyze("img1.jpg", 
                        actions = ["age", "gender", "emotion", "race"], 
                        models = models, 
                        detector_backend = "retinaface"
)