- minor addition to the web demo writeup
[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 import base64
18
19 def generate_image_df(path_image="", bin_stream=b""):
20     # munge stream and mimetype into input sample
21     if path_image and os.path.exists(path_image):
22         bin_stream = open(path_image, 'rb').read()
23     bin_stream = base64.b64encode(bin_stream)
24     if type(bin_stream)==bytes:
25         bin_stream = bin_stream.decode()
26     return pd.DataFrame([['image/jpeg', bin_stream]], columns=[FaceDetectTransform.COL_IMAGE_MIME, FaceDetectTransform.COL_IMAGE_DATA])
27
28 def transform(mime_type, base64_data):
29     app = current_app
30     time_start = time.clock()
31     image_read = base64_data.stream.read()
32     X = generate_image_df(bin_stream=image_read)
33     print(X)
34
35     if app.model_detect is not None:
36         pred_out = app.model_detect.transform.from_native(X)
37     if app.model_proc is not None:
38         pred_prior = pred_out
39         #pred_out = app.model_proc.transform.from_msg(pred_prior.as_msg())
40         pred_out = app.model_proc.transform.from_native(pred_prior.as_native())
41     time_stop = time.clock()
42
43     retStr = json.dumps(pred_out.as_native().to_dict(orient='records'), indent=4)
44
45     # formulate response
46     resp = make_response((retStr, 200, { } ))
47     # allow 'localhost' from 'file' or other;
48     # NOTE: DO NOT USE IN PRODUCTION!!!
49     resp.headers['Access-Control-Allow-Origin'] = '*'
50     print(retStr[:min(200, len(retStr))])
51     #print(pred)
52     return resp
53
54
55 if __name__ == '__main__':
56     parser = argparse.ArgumentParser()
57     parser.add_argument('-p', "--port", type=int, default=8884, help='port to launch the simple web server')
58     parser.add_argument('-d', "--modeldir_detect", type=str, default='../model_detect', help='model directory for detection')
59     parser.add_argument('-a', "--modeldir_analyze", type=str, default='../model_pix', help='model directory for detection')
60     pargs = parser.parse_args()
61
62     print("Configuring local application... {:}".format(__name__))
63     logging.basicConfig(level=logging.INFO)
64     app = connexion.App(__name__)
65     app.add_api('swagger.yaml')
66     # example usage:
67     #     curl -F image_binary=@test.jpg -F mime_type="image/jpeg" "http://localhost:8885/transform"
68
69     app.app.model_detect = None
70     if pargs.modeldir_detect:
71         if not os.path.exists(pargs.modeldir_detect):
72             print("Failed loading of detect model '{:}' even though it was specified...".format(pargs.modeldir_detect))
73         else:
74             print("Loading detect model... {:}".format(pargs.modeldir_detect))
75             app.app.model_detect = load_model(pargs.modeldir_detect)
76
77     app.app.model_proc = None
78     if pargs.modeldir_analyze:
79         if not os.path.exists(pargs.modeldir_analyze):
80             print("Failed loading of processing model '{:}' even though it was specified...".format(
81                 pargs.modeldir_analyze))
82         else:
83             print("Loading processing model... {:}".format(pargs.modeldir_analyze))
84             app.app.model_proc = load_model(pargs.modeldir_analyze)
85
86     # run our standalone gevent server
87     app.run(port=pargs.port) #, server='gevent')