JanetBackEnd/main_simple.py

99 lines
3.6 KiB
Python

from flask import Flask, request, jsonify
from flask_cors import CORS, cross_origin
import os
import shutil
import re
import requests
import time
from User import User
from DM import DM
import threading
app = Flask(__name__)
url = os.getenv("FRONTEND_URL_WITH_PORT")
version = os.getenv("FLASK_APP_VERSION_INFO")
#first 3 were url
cors = CORS(app, resources={r"/api/predict": {"origins": url},
r"/api/feedback": {"origins": url},
r"/api/dm": {"origins": url},
r"/health": {"origins": "*"}
})
users = {}
#check
alive = "alive"
def user_interest_decay(token):
while True:
try:
if token in users:
print("decaying interests after 3 minutes for " + users[token]['username'])
time.sleep(180)
users[token]['user'].decay_interests()
else:
break
except Exception as e:
alive = "dead_interest_decay"
@app.route("/health", methods=['GET'])
def health():
if alive=="alive":
return "Success \n" + "version number: " + version, 200
else:
return alive, 500
@app.route("/api/dm", methods=['POST'])
def init_dm():
try:
token = request.get_json().get("token")
status = request.get_json().get("stat")
if status == "start":
message = {"stat": "waiting", "err": ""}
elif status == "set":
headers = {"gcube-token": token, "Accept": "application/json"}
if token not in users:
url = 'https://api.d4science.org/rest/2/people/profile'
response = requests.get(url, headers=headers)
if response.status_code == 200:
username = response.json()['result']['username']
name = response.json()['result']['fullname']
users[token] = {'username': username, 'name': name, 'dm': DM(), 'activity': 0, 'user': User(username, token)}
threading.Thread(target=user_interest_decay, args=(token,), name='decayinterest_'+users[token]['username']).start()
message = {"stat": "done", "err": ""}
else:
message = {"stat": "rejected", "err": ""}
else:
message = {"stat": "done", "err": ""}
return message
except Exception as e:
message = {"stat": "init_dm_error", "err": str(e)}
return message
@app.route("/api/predict", methods=['POST'])
def predict():
time.sleep(10)
text = request.get_json().get("message")
message = {"answer": "https://api.d4science.org/rest/2/people/profile answer https://api.d4science.org/rest/2/people/profile answer https://api.d4science.org/rest/2/people/profile", "query": "text", "cand": "candidate", "history": "history", "modQuery": "modQuery"}
reply = jsonify(message)
return reply
@app.route('/api/feedback', methods = ['POST'])
def feedback():
data = request.get_json().get("feedback")
print(data)
reply = jsonify({"status": "done"})
return reply
if __name__ == "__main__":
"""
folder = '/app'
for filename in os.listdir(folder):
file_path = os.path.join(folder, filename)
try:
if os.path.isfile(file_path) or os.path.islink(file_path):
os.unlink(file_path)
elif os.path.isdir(file_path):
shutil.rmtree(file_path)
except Exception as e:
print('Failed to delete %s. Reason: %s' % (file_path, e))
"""
app.run(host='0.0.0.0')