app_uwsgi.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # time: 2023/3/27 16:29
  4. # file: app.py.py
  5. # author: David
  6. # company: shenyang JY
  7. import os
  8. import numpy as np
  9. np.random.seed(42)
  10. import pandas as pd
  11. from flask import Flask, request
  12. from startup import start_up
  13. from cache.clocking import Clock
  14. import threading
  15. import json, time
  16. from datetime import datetime
  17. app = Flask(__name__)
  18. with app.app_context():
  19. # import tensorflow as tf
  20. # global graph, sess
  21. # tf.compat.v1.set_random_seed(1234)
  22. # graph = tf.compat.v1.get_default_graph()
  23. # session_conf = tf.compat.v1.ConfigProto(intra_op_parallelism_threads=1, inter_op_parallelism_threads=1)
  24. # sess = tf.compat.v1.Session(graph=graph, config=session_conf)
  25. logger, va, args, req, process, features, fmi = start_up() # 程序初始化
  26. # model = fmi.fmi_model
  27. # 实例化定时任务类
  28. clock = Clock(logger=logger, args=args, process=process, features=features, fmi=fmi)
  29. logger.info("定时任务类初始化")
  30. # clock.calculate_coe(cluster=True) # 实际场站中要先修模
  31. clock.update_thread() # 定时任务开启
  32. result = {
  33. "errorCode": 1,
  34. "msg": "无异常",
  35. "res": []
  36. }
  37. @app.before_request
  38. def update_config():
  39. print("-----------------beofore_request------------------")
  40. global opt
  41. opt = args.parse_args_and_yaml()
  42. va.opt = opt
  43. process.opt = opt
  44. va.status = 0
  45. @app.route('/neu', methods=['post'])
  46. def cdq():
  47. try:
  48. start = time.time()
  49. # 初始化请求处理类
  50. nwp, dq, history_dq, history_rp, env = req.get_form_data(request)
  51. print("----进入预处理算法----")
  52. history_rp = va.validate_power(history_rp, env)
  53. history_rp.drop(['C_REAL_VALUE'], axis=1, inplace=True)
  54. history_rp.rename(columns={'NEW_RP': 'C_REAL_VALUE'}, inplace=True)
  55. s1 = time.time()
  56. logger.info(f"1解析数据验证-执行时间:{(s1 - start) * 1000}毫秒")
  57. nwp = pd.merge(nwp, dq, on='C_TIME')
  58. his = pd.merge(history_rp, history_dq, on='C_TIME')
  59. his = pd.merge(env, his, on='C_TIME')
  60. nwp = va.validate_nwp(nwp)
  61. his = va.validate_env(his)
  62. va.validate_authentic(dq, history_dq)
  63. start1 = time.time()
  64. logger.info(f"2解析数据验证-执行时间:{(start1 - s1) * 1000}毫秒")
  65. mean = [opt.mean.get(x) for x in opt.nwp_columns if x not in ['C_TIME']]
  66. std = [opt.std.get(x) for x in opt.nwp_columns if x not in ['C_TIME']]
  67. nwp = nwp[opt.nwp_columns]
  68. _, _, nwp_features = clock.normalize(nwp, mean=mean, std=std)
  69. mean = [opt.mean.get(x) for x in opt.env_columns if x not in ['C_TIME']]
  70. std = [opt.std.get(x) for x in opt.env_columns if x not in ['C_TIME']]
  71. his = his[opt.env_columns]
  72. _, _, env_features = clock.normalize(his, mean=mean, std=std)
  73. start2 = time.time()
  74. logger.info(f"归一化-执行时间:{(start2 - start1) * 1000}毫秒")
  75. data_test, env = process.get_test_data(nwp_features, env_features)
  76. test_X = features.get_realtime_data(data_test, env)
  77. start3 = time.time()
  78. logger.info(f"特征处理-执行时间:{(start3 - start2) * 1000}毫秒")
  79. logger.info("-----进入超短期预测算法-----")
  80. # with graph.as_default():
  81. # with sess.as_default():
  82. res = fmi.fmi_model.predict(test_X, batch_size=1)[0]
  83. start4 = time.time()
  84. logger.info(f"算法推理-执行时间:{(start4 - start3) * 1000}毫秒")
  85. # res = fmi.fmi_model.predict(opt, test_X)[0]
  86. res = np.array([r*opt.std['C_REAL_VALUE'] + opt.mean['C_REAL_VALUE'] for r in res])
  87. res = np.array([r*opt.calculate['coe'] + opt.calculate['abs'] for r in res])
  88. res[res < 0] = 0
  89. res[res > opt.cap] = opt.cap
  90. res = np.around(res, decimals=2)
  91. times = dq['C_TIME'].dt.strftime('%Y-%m-%d %H:%M:%S').values
  92. res = [{"C_TIME": times[i], "CDQ_VALUE": x} for i, x in enumerate(res)]
  93. end = time.time()
  94. logger.info(f"反归一化-执行时间:{(end - start4) * 1000}毫秒")
  95. print(f"总时间:{(end - start) * 1000}毫秒")
  96. logger.info("----{}".format(res))
  97. result["errorCode"] = 1
  98. result["res"] = res
  99. result["msg"] = "无异常"
  100. return json.dumps(result, ensure_ascii=False)
  101. except Exception as e:
  102. logger.error(e.args)
  103. result["errorCode"] = va.status if va.status != 1 else 0
  104. result["res"] = None
  105. result["msg"] = e.args
  106. return json.dumps(result, ensure_ascii=False)
  107. @app.route('/forecastVersion', methods=['get'])
  108. def forecast_version():
  109. opt = args.parse_args_and_yaml()
  110. return opt.version
  111. def date_diff(current_dt, repair_dt):
  112. format_pattern = '%Y-%m-%d'
  113. difference = (datetime.strptime(current_dt, format_pattern) - datetime.strptime(repair_dt, format_pattern))
  114. return difference.days
  115. @app.route('/last_model_update', methods=['get'])
  116. def last_model_update():
  117. dt = time.strftime('%Y-%m-%d', time.localtime(time.time()))
  118. repair, repair_dt = int(opt.repair_model_cycle), opt.authentication['repair']
  119. if repair_dt == 'null':
  120. return {"model_status": 0, "time": 'null', "msg": "未修模"}
  121. elif date_diff(dt, repair_dt) > repair*2:
  122. return {"model_status": 1, "time": repair_dt, "msg": "距上次修模已过{}天".format(date_diff(dt, repair_dt))}
  123. else:
  124. return {"model_status": 2, "time": repair_dt, "msg": "修模正常"}
  125. if __name__ == "__main__":
  126. opt = args.parse_args_and_yaml()
  127. current_path = os.path.dirname(__file__)
  128. gunicorn_config = {
  129. 'bind': '%s:%s' % ('0.0.0.0', str(opt.port)),
  130. 'certfile': current_path + '/ssl/server.pem',
  131. 'keyfile': current_path + '/ssl/server.key',
  132. "check_config": True,
  133. "worker_class": "gthread",
  134. "workers": 1,
  135. "threads": 1,
  136. 'timeout': 100,
  137. "loglevel": "info",
  138. "access_log_format": "gunicorn %(h)s - %(t)s - %(r)s - %(s)s - %(f)s",
  139. "backlog": 30,
  140. }
  141. threading.Thread(target=clock.calculate_coe, args=(True,)).start()
  142. # # 启动服务
  143. # app.run(host='0.0.0.0', port=9008, debug=False)
  144. init_file = './app.ini'
  145. os.system("uwsgi --init {}".format(init_file))