-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathflask_app.py
141 lines (110 loc) · 4.04 KB
/
flask_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
132
133
134
135
136
137
138
139
140
141
"""The app main."""
import json
import logging
from logging.config import dictConfig
import os
import traceback
from flask import Flask
from flask import render_template, request, Blueprint
import gin
from explain.logic import ExplainBot
from explain.sample_prompts_by_action import sample_prompt_for_action
# gunicorn doesn't have command line flags, using a gin file to pass command line args
@gin.configurable
class GlobalArgs:
def __init__(self, config, baseurl):
self.config = config
self.baseurl = baseurl
# Parse gin global config
gin.parse_config_file("global_config.gin")
# Get args
args = GlobalArgs()
bp = Blueprint('host', __name__, template_folder='templates')
dictConfig({
'version': 1,
'formatters': {'default': {
'format': '[%(asctime)s] %(levelname)s in %(module)s: %(message)s',
}},
'handlers': {'wsgi': {
'class': 'logging.StreamHandler',
'stream': 'ext://flask.logging.wsgi_errors_stream',
'formatter': 'default'
}},
'root': {
'level': 'INFO',
'handlers': ['wsgi']
}
})
os.environ["TOKENIZERS_PARALLELISM"] = "false"
# Parse application level configs
gin.parse_config_file(args.config)
# Setup the explainbot
BOT = ExplainBot()
@bp.route('/')
def home():
"""Load the explanation interface."""
app.logger.info("Loaded Login")
objective = BOT.conversation.describe.get_dataset_objective()
return render_template("index.html", currentUserId="user", datasetObjective=objective)
@bp.route("/log_feedback", methods=['POST'])
def log_feedback():
"""Logs feedback"""
feedback = request.data.decode("utf-8")
app.logger.info(feedback)
split_feedback = feedback.split(" || ")
message = f"Feedback formatted improperly. Got: {split_feedback}"
assert split_feedback[0].startswith("MessageID: "), message
assert split_feedback[1].startswith("Feedback: "), message
assert split_feedback[2].startswith("Username: "), message
message_id = split_feedback[0][len("MessageID: "):]
feedback_text = split_feedback[1][len("Feedback: "):]
username = split_feedback[2][len("Username: "):]
logging_info = {
"id": message_id,
"feedback_text": feedback_text,
"username": username
}
BOT.log(logging_info)
return ""
@bp.route("/sample_prompt", methods=["Post"])
def sample_prompt():
"""Samples a prompt"""
data = json.loads(request.data)
action = data["action"]
username = data["thisUserName"]
prompt = sample_prompt_for_action(action,
BOT.prompts.filename_to_prompt_id,
BOT.prompts.final_prompt_set,
real_ids=BOT.conversation.get_training_data_ids())
logging_info = {
"username": username,
"requested_action_generation": action,
"generated_prompt": prompt
}
BOT.log(logging_info)
return prompt
@bp.route("/get_response", methods=['POST'])
def get_bot_response():
"""Load the box response."""
if request.method == "POST":
app.logger.info("generating the bot response")
try:
data = json.loads(request.data)
user_text = data["userInput"]
conversation = BOT.conversation
response = BOT.update_state(user_text, conversation)
except Exception as ext:
app.logger.info(f"Traceback getting bot response: {traceback.format_exc()}")
app.logger.info(f"Exception getting bot response: {ext}")
response = "Sorry! I couldn't understand that. Could you please try to rephrase?"
return response
app = Flask(__name__)
app.register_blueprint(bp, url_prefix=args.baseurl)
if __name__ != '__main__':
gunicorn_logger = logging.getLogger('gunicorn.error')
app.logger.handlers = gunicorn_logger.handlers
app.logger.setLevel(gunicorn_logger.level)
if __name__ == "__main__":
# clean up storage file on restart
app.logger.info(f"Launching app from config: {args.config}")
app.run(debug=False, port=4455, host='0.0.0.0')