-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
52 lines (41 loc) · 1.33 KB
/
main.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
from flask import Flask, request, jsonify
import tensorflow as tf
import numpy as np
keras = tf.keras
Tokenizer = keras.preprocessing.text.Tokenizer
import json
app = Flask(__name__)
MAX_LEN = 60
TRUNC_TYPE='post'
PAD_TYPE='pre'
PRED_CLASSES = ['hate_speech','offensive_language','ok']
try:
model = keras.models.load_model('model/hate_comment_detection_with_nlp.h5')
except Exception as e:
print(e)
try:
with open('hate_comment_detection_with_nlp_word_index.json', 'r') as file:
data = json.load(file)
# Convert the JSON data to a dictionary
word_index = dict(data)
oov_token = '<oov>'
tokenizer = Tokenizer(oov_token=oov_token)
tokenizer.word_index = word_index
except Exception as e:
print(e)
@app.route('/preds',methods=['POST'])
def predictHateComments():
try:
# get json data
req_body = request.json
text = req_body['comment']
# tokenize
encoded = tokenizer.texts_to_sequences([text])
encoded = keras.utils.pad_sequences(encoded,MAX_LEN,padding=PAD_TYPE,truncating=TRUNC_TYPE)
preds = model.predict(encoded)
pred = PRED_CLASSES[np.argmax(preds[0])]
return jsonify({'pred':pred}),200
except:
return jsonify({'pred':None, "err": "Some error"}),500
if __name__ == "__main__":
app.run(debug=True)