6
6
import datetime
7
7
from detoxify import Detoxify
8
8
import logging
9
+ from flask_caching import Cache
9
10
10
11
load_dotenv ()
11
12
15
16
LISTEN_HOST = os .getenv ("LISTEN_HOST" , "0.0.0.0" )
16
17
LISTEN_PORT = os .getenv ("LISTEN_PORT" , "7860" )
17
18
DETOXIFY_MODEL = os .getenv ("DETOXIFY_MODEL" , "unbiased-small" )
19
+ CACHE_DURATION_SECONDS = int (os .getenv ("CACHE_DURATION_SECONDS" , 60 ))
20
+ ENABLE_CACHE = os .getenv ("ENABLE_CACHE" , "false" ) == "true"
21
+
18
22
APP_VERSION = "0.1.0"
19
23
20
24
# Setup logging configuration
40
44
41
45
app = Flask (__name__ )
42
46
47
+ cache_config = {
48
+ "DEBUG" : True if APP_ENV != "production" else False ,
49
+ "CACHE_TYPE" : "SimpleCache" if ENABLE_CACHE else "NullCache" ,
50
+ "CACHE_DEFAULT_TIMEOUT" : CACHE_DURATION_SECONDS , # Cache duration in seconds
51
+ }
52
+ cache = Cache (config = cache_config )
53
+ cache .init_app (app )
54
+
43
55
44
56
def is_valid_api_key (api_key ):
45
57
if api_key == API_TOKEN :
@@ -67,6 +79,16 @@ def decorator(*args, **kwargs):
67
79
return decorator
68
80
69
81
82
+ def make_key_fn ():
83
+ """A function which is called to derive the key for a computed value.
84
+ The key in this case is the concat value of all the json request
85
+ parameters. Other strategy could to use any hashing function.
86
+ :returns: unique string for which the value should be cached.
87
+ """
88
+ user_data = request .get_json ()
89
+ return "," .join ([f"{ key } ={ value } " for key , value in user_data .items ()])
90
+
91
+
70
92
def perform_hate_speech_analysis (query ):
71
93
result = {}
72
94
df = pd .DataFrame (model .predict (query ), index = [0 ])
@@ -86,6 +108,7 @@ def handle_exception(error):
86
108
87
109
@app .route ("/predict" , methods = ["POST" ])
88
110
@api_required
111
+ @cache .cached (make_cache_key = make_key_fn )
89
112
def predict ():
90
113
data = request .json
91
114
q = data ["q" ]
@@ -99,9 +122,7 @@ def predict():
99
122
100
123
@app .route ("/" , methods = ["GET" ])
101
124
def index ():
102
- response = {
103
- "message" : "Use /predict route to get prediction result"
104
- }
125
+ response = {"message" : "Use /predict route to get prediction result" }
105
126
return jsonify (response )
106
127
107
128
0 commit comments