Spaces:
Runtime error
Runtime error
''' | |
Build Project | |
''' | |
# imported necessary libraries | |
import gradio as gr | |
import tensorflow as tf | |
import numpy as np | |
import os | |
import yaml | |
import cv2 | |
from PIL import Image | |
import io | |
import json | |
# read config file | |
def read_config(): | |
config = {} | |
print(os.path.curdir) | |
with open('models_config.yaml', 'r') as cf: | |
config = yaml.safe_load(cf) | |
for var in config: | |
config[var] = config[var].replace(';', os.sep) | |
return config | |
config = read_config() | |
# loading the models | |
age_model = tf.keras.models.load_model(config['A_M_PATH']) | |
gender_model = tf.keras.models.load_model(config['G_M_PATH']) | |
face_cascade = cv2.CascadeClassifier(config['FD_M_PATH']) | |
def main_pipeline(image): | |
#file = request.form() | |
#im_b64 = file['img'] | |
#image = im_b64.file.read() | |
#image = Image.open(image) | |
#image = image.convert("RGB") | |
image = np.asarray(image) | |
gray_img = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY) | |
faces = face_cascade.detectMultiScale(gray_img, 1.1, 4) | |
if len(faces) == 0: | |
return "NO FACE DETECTED" | |
x, y, w, h = faces[0] | |
#cv2.rectangle(image, (x, y), (x+w, y+h), (255, 0, 0), 2) | |
image = Image.fromarray(image) | |
image = image.crop((x, y, x + w, y + h)) | |
#cv2.imshow('image', np.asarray(image)) | |
#cv2.waitKey() | |
image = image.resize((224,224)) | |
#image = tf.image.resize(image, [224,224]) | |
image = tf.keras.preprocessing.image.img_to_array(image) | |
image = image / 255.0 | |
image = tf.expand_dims(image, axis=0) | |
age_prds = age_model.predict(image) | |
gender_prds = gender_model.predict(image) | |
age_prds = np.around(age_prds) | |
gender_prds = np.around(gender_prds) | |
gender = "" | |
if gender_prds[0][0] == 0: | |
gender = 'male' | |
else: | |
gender = 'female' | |
data = {} | |
data['age'] = str(age_prds[0][0]) | |
data['gender'] = gender | |
b_box_arr = [(x, y, w, h) for (x, y, w, h) in faces] | |
data['left'] = str(b_box_arr[0][0]) | |
data['top'] = str(b_box_arr[0][1]) | |
data['width'] = str(b_box_arr[0][2]) | |
data['height'] = str(b_box_arr[0][3]) | |
predictions_json = json.dumps(data) | |
return predictions_json | |
# initializing the input component | |
image = gr.inputs.Image(shape = (224, 224)) | |
# initializing the output component | |
labels = gr.outputs.Label() | |
# launching the interface | |
gr.Interface(fn = main_pipeline, inputs = image, | |
outputs = labels, capture_session = True).launch() |