- first pass at app endpoint simulation
[face-privacy-filter.git] / testing / app.py
1 #!/usr/bin/env python3
2 import connexion
3 import logging
4
5 import argparse
6 import json
7 import time
8 import os
9
10 from flask import Flask, request, current_app, make_response
11
12 import pandas as pd
13 import requests
14
15 from cognita_client.wrap.load import load_model
16 from face_privacy_filter.transform_detect import FaceDetectTransform
17
18 def generate_image_df(path_image="", bin_stream=b""):
19     # munge stream and mimetype into input sample
20     if path_image and os.path.exists(path_image):
21         bin_stream = open(path_image, 'rb').read()
22     return pd.DataFrame([['image/jpeg', bin_stream]],
23                         columns=[FaceDetectTransform.COL_IMAGE_MIME, FaceDetectTransform.COL_IMAGE_DATA])
24
25 def transform(mime_type, image_binary):
26     app = current_app
27     time_start = time.clock()
28     image_read = image_binary.stream.read()
29     X = generate_image_df(bin_stream=image_read)
30     print(X)
31
32     if app.model_detect is not None:
33         dfPred = app.model_detect.transform.from_native(X).as_native()
34     if app.model_proc is not None:
35         dfRegions = dfPred
36         dfPred = app.model_proc.transform.from_native(dfRegions).as_native()
37     time_stop = time.clock()
38
39     retStr = json.dumps(dfPred.to_dict(orient='records'), indent=4)
40
41     # formulate response
42     resp = make_response((retStr, 200, { } ))
43     # allow 'localhost' from 'file' or other;
44     # NOTE: DO NOT USE IN PRODUCTION!!!
45     resp.headers['Access-Control-Allow-Origin'] = '*'
46     print(type(dfPred))
47     print(retStr[:min(200, len(retStr))])
48     #print(pred)
49     return resp
50
51
52 if __name__ == '__main__':
53     parser = argparse.ArgumentParser()
54     parser.add_argument('-p', "--port", type=int, default=8884, help='port to launch the simple web server')
55     parser.add_argument('-d', "--modeldir_detect", type=str, default='../model_detect', help='model directory for detection')
56     parser.add_argument('-a', "--modeldir_analyze", type=str, default='../model_pix', help='model directory for detection')
57     pargs = parser.parse_args()
58
59     print("Configuring local application... {:}".format(__name__))
60     logging.basicConfig(level=logging.INFO)
61     app = connexion.App(__name__)
62     app.add_api('swagger.yaml')
63     # example usage:
64     #     curl -F image_binary=@test.jpg -F mime_type="image/jpeg" "http://localhost:8885/transform"
65
66     app.app.model_detect = None
67     if pargs.modeldir_detect:
68         if not os.path.exists(pargs.modeldir_detect):
69             print("Failed loading of detect model '{:}' even though it was specified...".format(pargs.modeldir_detect))
70         else:
71             print("Loading detect model... {:}".format(pargs.modeldir_detect))
72             app.app.model_detect = load_model(pargs.modeldir_detect)
73
74     app.app.model_proc = None
75     if pargs.modeldir_analyze:
76         if not os.path.exists(pargs.modeldir_analyze):
77             print("Failed loading of processing model '{:}' even though it was specified...".format(
78                 pargs.modeldir_analyze))
79         else:
80             print("Loading processing model... {:}".format(pargs.modeldir_analyze))
81             app.app.model_proc = load_model(pargs.modeldir_analyze)
82
83     # run our standalone gevent server
84     app.run(port=pargs.port) #, server='gevent')