app.py 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  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, g
  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, fix = start_up(graph, sess) # 程序初始化
  26. # model = fmi.fmi_model
  27. # 实例化定时任务类
  28. clock = Clock(logger=logger, args=args, process=process, features=features, fmi=fmi, fix=fix)
  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. opt = args.parse_args_and_yaml()
  41. g.opt = opt
  42. va.opt = opt
  43. process.opt = opt
  44. features.opt = opt
  45. fix.opt = opt
  46. # va.status = 0
  47. # class StandaloneApplication(gunicorn.app.base.BaseApplication):
  48. # def __init__(self, app, options=None):
  49. # self.options = options or {}
  50. # self.application = app
  51. # super().__init__()
  52. #
  53. # def load_config(self):
  54. # config = {key: value for key, value in self.options.items()
  55. # if key in self.cfg.settings and value is not None}
  56. # for key, value in config.items():
  57. # self.cfg.set(key.lower(), value)
  58. #
  59. # def load(self):
  60. # return self.application
  61. integral = 0
  62. @app.route('/neu', methods=['post'])
  63. def cdq():
  64. try:
  65. opt = g.opt
  66. start = time.time()
  67. # 初始化请求处理类
  68. history_dq, history_rp, env, nwp, dq = req.get_form_data(request)
  69. his = va.validate_his_data(history_rp, env, history_dq).reset_index(drop=True)
  70. print("----进入预处理算法----")
  71. history_rp = va.validate_power(his)
  72. history_rp.rename(columns={'NEW_RP': 'C_REAL_VALUE'}, inplace=True)
  73. his.drop(columns=['C_REAL_VALUE'], axis=1, inplace=True)
  74. his = pd.merge(his, history_rp, on='C_TIME')
  75. s1 = time.time()
  76. logger.info(f"测光-信号限电处理-执行时间:{(s1 - start) * 1000:.2f}毫秒")
  77. nwp = pd.merge(nwp, dq, on='C_TIME')
  78. nwp = va.validate_nwp(nwp)
  79. nwp = process.get_predict_data(nwp, dq)
  80. va.status = 0
  81. va.validate_authentic(dq, history_dq)
  82. start1 = time.time()
  83. logger.info(f"数据验证-执行时间:{(start1 - s1) * 1000:.2f}毫秒")
  84. mean = [opt.mean.get(x) for x in opt.nwp_columns if x not in ['C_TIME']]
  85. std = [opt.std.get(x) for x in opt.nwp_columns if x not in ['C_TIME']]
  86. nwp = nwp[opt.nwp_columns]
  87. _, _, nwp_features = clock.normalize(nwp, mean=mean, std=std)
  88. if len(nwp_features) > opt.Model["output_size"]:
  89. nwp_features = nwp_features.head(opt.Model["output_size"])
  90. dq = dq.head(opt.Model["output_size"])
  91. mean = [opt.mean.get(x) for x in opt.env_columns if x not in ['C_TIME']]
  92. std = [opt.std.get(x) for x in opt.env_columns if x not in ['C_TIME']]
  93. his = his[opt.env_columns]
  94. _, _, env_features = clock.normalize(his, mean=mean, std=std)
  95. start2 = time.time()
  96. logger.info(f"归一化-执行时间:{(start2 - start1) * 1000:.2f}毫秒")
  97. test_X = features.get_realtime_data([nwp_features], env_features)
  98. start3 = time.time()
  99. logger.info(f"预处理及特征处理-执行时间:{(start3 - start2) * 1000:.2f}毫秒")
  100. logger.info("-----进入超短期预测算法-----")
  101. res = fmi.predict(test_X)[0]
  102. res = np.array([r * opt.std['C_REAL_VALUE'] + opt.mean['C_REAL_VALUE'] for r in res])
  103. res[res < 0] = 0 # 如果出现负数,置为0
  104. res[res > opt.cap] = opt.cap # 出现大于实际装机量的数,置为实际装机量
  105. res = np.around(res, decimals=2)
  106. start4 = time.time()
  107. logger.info(f"算法推理-执行时间:{(start4 - start3) * 1000:.2f}毫秒")
  108. dq_res = fix.history_error(history_dq, history_rp, dq)
  109. dq_res['dq_fix'] = res
  110. res = fix.cdq(dq_res)
  111. end = time.time()
  112. logger.info(f"生成超短期-执行时间:{(end - start4) * 1000:.2f}毫秒")
  113. logger.info(f"总时间:{(end - start) * 1000:.2f}毫秒")
  114. logger.info("----{}".format(res))
  115. va.status = 1
  116. result["errorCode"] = 1
  117. result["res"] = res
  118. result["msg"] = "无异常"
  119. return json.dumps(result, ensure_ascii=False)
  120. except Exception as e:
  121. global integral
  122. logger.error(e.args)
  123. if va.status == 2 and integral > 60:
  124. va.status = 3
  125. integral = 0
  126. result["errorCode"] = va.status if va.status != 1 else 0
  127. result["res"] = None
  128. result["msg"] = e.args
  129. return json.dumps(result, ensure_ascii=False)
  130. @app.route('/forecastVersion', methods=['get'])
  131. def forecast_version():
  132. return g.opt.version
  133. def date_diff(current_dt, repair_dt):
  134. format_pattern = '%Y-%m-%d'
  135. difference = (datetime.strptime(current_dt, format_pattern) - datetime.strptime(repair_dt, format_pattern))
  136. return difference.days
  137. @app.route('/last_model_update', methods=['get'])
  138. def last_model_update():
  139. dt = time.strftime('%Y-%m-%d', time.localtime(time.time()))
  140. repair, repair_dt = int(g.opt.repair_model_cycle), g.opt.authentication['repair']
  141. if repair_dt == 'null':
  142. return {"model_status": 0, "time": 'null', "msg": "neu算法:未修模"}
  143. elif date_diff(dt, repair_dt) > repair*2:
  144. return {"model_status": 1, "time": repair_dt, "msg": "neu算法:距上次修模{}天".format(date_diff(dt, repair_dt))}
  145. elif va.status != 1:
  146. status_msg = {2: "环境数据缺失", 3: "重载环境数据"}
  147. global integral
  148. if va.status == 2 and integral <= 60:
  149. integral += 1
  150. return {"model_status": 1, "time": repair_dt, "msg": "neu算法:接口状态{}".format(status_msg.get(va.status, '检查'))}
  151. else:
  152. return {"model_status": 2, "time": repair_dt, "msg": "neu算法:修模正常"}
  153. if __name__ == "__main__":
  154. opt = args.parse_args_and_yaml()
  155. current_path = os.path.dirname(__file__)
  156. # gunicorn_config = {
  157. # 'bind': '%s:%s' % ('0.0.0.0', str(opt.port)),
  158. # 'certfile': current_path + '/ssl/server.pem',
  159. # 'keyfile': current_path + '/ssl/server.key',
  160. # "check_config": True,
  161. # "worker_class": "gthread",
  162. # "workers": 1,
  163. # "threads": 1,
  164. # 'timeout': 100,
  165. # "loglevel": "info",
  166. # "access_log_format": "gunicorn %(h)s - %(t)s - %(r)s - %(s)s - %(f)s",
  167. # "backlog": 30,
  168. # }
  169. if opt.algorithm_platform['switch']:
  170. clock.calculate_coe(True)
  171. else:
  172. threading.Thread(target=clock.calculate_coe, args=(True,)).start()
  173. # # 启动服务
  174. # StandaloneApplication(app, options=gunicorn_config).run()
  175. app.run(host='0.0.0.0', port=opt.port, debug=False,
  176. ssl_context=(current_path + '/ssl/server.pem', current_path + '/ssl/server.key'))