hnsw_app.py 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. from gevent import monkey; monkey.patch_all()
  2. import os
  3. from flask import Flask, request, jsonify
  4. from flask_apscheduler import APScheduler
  5. from gevent.pywsgi import WSGIServer
  6. import config
  7. from hnsw_model import HNSW
  8. from hnsw_model_train import HNSW_Model_Train
  9. from restart_server import restart_retrieval_app
  10. from log_config import LogConfig
  11. app = Flask(__name__)
  12. class APS_Config(object):
  13. SCHEDULER_API_ENABLED = True
  14. scheduler = APScheduler()
  15. # 定时重启retrieval_app服务, 防止内存累加
  16. @scheduler.task('cron', id='restart_retrieval_app', day='*', hour='02', minute='00', second='00', timezone='Asia/Shanghai')
  17. def retrieval_app_schedule():
  18. # 重启retrieval_app服务
  19. restart_retrieval_app()
  20. # 定时训练HNSW模型并重启服务(0-'mon',...2-'wed',...,6-'sun')
  21. @scheduler.task('cron', id='hm_train', week='*', day_of_week='0', hour='02', minute='30', second='00', timezone='Asia/Shanghai')
  22. def hm_train_schedule():
  23. hm_train = HNSW_Model_Train(hm_logger)
  24. hm_train()
  25. os.popen("nohup python restart_server.py 1 > logs/temp_app.log 2>&1 &")
  26. # 每周定时刷新日志
  27. @scheduler.task('cron', id='log_reset', week='*', day_of_week='sun', hour='05', minute='00', second='00', timezone='Asia/Shanghai')
  28. def log_reset_schedule():
  29. hm_LogConfig.log_reset()
  30. os.popen("nohup python restart_server.py > logs/temp_app.log 2>&1 &")
  31. # hnsw模型数据检索
  32. @app.route('/retrieve', methods=['GET', 'POST'])
  33. def retrieve():
  34. if request.method == 'POST':
  35. # 获取post数据
  36. query_vec = request.get_json()
  37. # HNSW检索
  38. query_labels = hnsw.retrieve(query_vec)
  39. return jsonify(query_labels)
  40. if __name__ == '__main__':
  41. # 日志采集初始化
  42. hm_LogConfig = LogConfig(config.retrieval_path, "hnsw_model")
  43. hm_logger = hm_LogConfig.get_log()
  44. # HNSW模型初始化
  45. hnsw = HNSW(hm_logger)
  46. # 定时更新HNSW模型增/改/删变化
  47. app.config.from_object(APS_Config())
  48. scheduler.init_app(app)
  49. scheduler.start()
  50. # app.run(host='0.0.0.0',port='8836')
  51. server = WSGIServer(('0.0.0.0', 8836), app)
  52. server.serve_forever()