File size: 1,976 Bytes
caeec0f ffd6688 fa46345 ffd6688 caeec0f ffd6688 fa46345 caeec0f fa46345 ffd6688 fa46345 ffd6688 caeec0f fa46345 caeec0f fa46345 caeec0f fa46345 ffd6688 fa46345 caeec0f fa46345 ffd6688 |
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 |
from datetime import datetime
from flask import Flask, request, jsonify, make_response
from flask_cors import CORS
from datetime import datetime
import openai
import os
import random
import therapist
### VARIABLES
INITIAL_MESSAGE = "Hi! I'm Brainy, a virtual assistant who can guide you through the mental health screening process. Can you start by telling me a bit about the problems you are experiencing?"
HASH_LENGTH = 12
#### SET UP ENVIRONMENT
openai.api_key = os.getenv("OPENAI_API_KEY")
app = Flask(__name__)
CORS(app)
users = {}
message_history = {}
### UTILITY FUNCTIONS
def clean_users(users=users, message_history=message_history):
#TODO: Write a function that looks through the connection times in
# users, and then removes all records older than a day from both
# users and message_history
pass
### INIT WEB APP
@app.route("/")
def index():
return app.send_static_file("index.html")
@app.route('/get_initial', methods=['GET'])
def get_initial():
response = therapist.initial_message
connect_time = datetime.now()
user_id = str("%030x" % random.randrange(16 ** HASH_LENGTH))[-HASH_LENGTH:]
users[user_id] = {
"user_id": user_id,
"connect_time": connect_time,
"state": ["initial"],
"message_history": [therapist.initial_message]}
clean_users() # Remove old user IDs and messages from our system
return jsonify({"response": response, "user_id":user_id})
@app.route('/get_response', methods=['GET'])
def get_response():
message = request.args.get("message")
user_id = request.args.get("user_id")
user = users[user_id]
if not message.strip():
response = "Please enter a message."
else:
state, response = therapist.generate_response(user, message)
user["state"] = state
user["message_history"].extend([message, response])
return jsonify({"response": response})
if __name__ == '__main__':
app.run()
|