-
Notifications
You must be signed in to change notification settings - Fork 575
/
app.py
131 lines (112 loc) · 5.03 KB
/
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
"""REST API server for analyzer."""
import json
import logging
import os
from logging.config import fileConfig
from pathlib import Path
from typing import Tuple
from flask import Flask, request, jsonify, Response
from werkzeug.exceptions import HTTPException
from presidio_analyzer.analyzer_engine import AnalyzerEngine
from presidio_analyzer.analyzer_request import AnalyzerRequest
DEFAULT_PORT = "3000"
LOGGING_CONF_FILE = "logging.ini"
WELCOME_MESSAGE = r"""
_______ _______ _______ _______ _________ ______ _________ _______
( ____ )( ____ )( ____ \( ____ \\__ __/( __ \ \__ __/( ___ )
| ( )|| ( )|| ( \/| ( \/ ) ( | ( \ ) ) ( | ( ) |
| (____)|| (____)|| (__ | (_____ | | | | ) | | | | | | |
| _____)| __)| __) (_____ ) | | | | | | | | | | | |
| ( | (\ ( | ( ) | | | | | ) | | | | | | |
| ) | ) \ \__| (____/\/\____) |___) (___| (__/ )___) (___| (___) |
|/ |/ \__/(_______/\_______)\_______/(______/ \_______/(_______)
"""
class Server:
"""HTTP Server for calling Presidio Analyzer."""
def __init__(self):
fileConfig(Path(Path(__file__).parent, LOGGING_CONF_FILE))
self.logger = logging.getLogger("presidio-analyzer")
self.logger.setLevel(os.environ.get("LOG_LEVEL", self.logger.level))
self.app = Flask(__name__)
self.logger.info("Starting analyzer engine")
self.engine = AnalyzerEngine()
self.logger.info(WELCOME_MESSAGE)
@self.app.route("/health")
def health() -> str:
"""Return basic health probe result."""
return "Presidio Analyzer service is up"
@self.app.route("/analyze", methods=["POST"])
def analyze() -> Tuple[str, int]:
"""Execute the analyzer function."""
# Parse the request params
try:
req_data = AnalyzerRequest(request.get_json())
if not req_data.text:
raise Exception("No text provided")
if not req_data.language:
raise Exception("No language provided")
recognizer_result_list = self.engine.analyze(
text=req_data.text,
language=req_data.language,
correlation_id=req_data.correlation_id,
score_threshold=req_data.score_threshold,
entities=req_data.entities,
return_decision_process=req_data.return_decision_process,
ad_hoc_recognizers=req_data.ad_hoc_recognizers,
context=req_data.context,
)
return Response(
json.dumps(
recognizer_result_list,
default=lambda o: o.to_dict(),
sort_keys=True,
),
content_type="application/json",
)
except TypeError as te:
error_msg = (
f"Failed to parse /analyze request "
f"for AnalyzerEngine.analyze(). {te.args[0]}"
)
self.logger.error(error_msg)
return jsonify(error=error_msg), 400
except Exception as e:
self.logger.error(
f"A fatal error occurred during execution of "
f"AnalyzerEngine.analyze(). {e}"
)
return jsonify(error=e.args[0]), 500
@self.app.route("/recognizers", methods=["GET"])
def recognizers() -> Tuple[str, int]:
"""Return a list of supported recognizers."""
language = request.args.get("language")
try:
recognizers_list = self.engine.get_recognizers(language)
names = [o.name for o in recognizers_list]
return jsonify(names), 200
except Exception as e:
self.logger.error(
f"A fatal error occurred during execution of "
f"AnalyzerEngine.get_recognizers(). {e}"
)
return jsonify(error=e.args[0]), 500
@self.app.route("/supportedentities", methods=["GET"])
def supported_entities() -> Tuple[str, int]:
"""Return a list of supported entities."""
language = request.args.get("language")
try:
entities_list = self.engine.get_supported_entities(language)
return jsonify(entities_list), 200
except Exception as e:
self.logger.error(
f"A fatal error occurred during execution of "
f"AnalyzerEngine.supported_entities(). {e}"
)
return jsonify(error=e.args[0]), 500
@self.app.errorhandler(HTTPException)
def http_exception(e):
return jsonify(error=e.description), e.code
if __name__ == "__main__":
port = int(os.environ.get("PORT", DEFAULT_PORT))
server = Server()
server.app.run(host="0.0.0.0", port=port)