import sys sys.path.append('.') from flask import Flask, request, jsonify import os import json import cv2 import numpy as np from tensorflow.keras.preprocessing import image from keras_facenet import FaceNet from sklearn.svm import OneClassSVM import pickle # create a facenet model embedding_model = FaceNet(key = '20180402-114759', use_prebuilt=True, cache_folder= os.path.abspath(os.path.dirname(__file__)) + '/facenet_weights').model clf_model = pickle.load(open(os.path.abspath(os.path.dirname(__file__)) + '/model/clf_mode.sav', 'rb')) target_shape = (160, 160) app = Flask(__name__) app.config['SITE'] = "http://0.0.0.0:8000/" app.config['DEBUG'] = False @app.route('/api/detect_human_face', methods=['POST']) def detect_human_face(): file1 = request.files['image1'] image1 = cv2.imdecode(np.fromstring(file1.read(), np.uint8), cv2.IMREAD_COLOR) if image1 is None: result = "image1: is null!" status = "ok" response = jsonify({"status": status, "data": {"result": result}}) response.status_code = 200 response.headers["Content-Type"] = "application/json; charset=utf-8" return response X = np.float32([(np.float32(image1) - 127.5) / 127.5]) X_ft = embedding_model.predict(X, batch_size=1) anomaly_score = clf_model.decision_function(X_ft) * -1 if anomaly_score > 1: result = "Not Human" else: result = "Human" status = "ok" response = jsonify( { "status": status, "data": { "result": result, "anomaly_score": float(anomaly_score) } }) response.status_code = 200 response.headers["Content-Type"] = "application/json; charset=utf-8" return response if __name__ == '__main__': port = int(os.environ.get("PORT", 8000)) app.run(host='0.0.0.0', port=port)