app.py 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  1. import sys
  2. from flask import Flask, request, jsonify
  3. from commonUtil import fill_template, fill_template_auto
  4. from responseUtil import *
  5. from similarity_answer_json import *
  6. from util import *
  7. import os
  8. app = Flask(__name__)
  9. # TEMPLATE_FOLDER = "templatesJson"
  10. # DATA_FOLDER = "..\Json\json_data"
  11. # def resource_path(relative_path):
  12. # """适配开发环境 + PyInstaller,支持从项目根目录查找资源"""
  13. # if getattr(sys, 'frozen', False):
  14. # base_path = sys._MEIPASS
  15. # else:
  16. # # 向上两层回退到项目根目录:适配 ByRules 子目录结构
  17. # base_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", ".."))
  18. # return os.path.join(base_path, relative_path)
  19. #
  20. # MAPPING_FILE = resource_path("final/Json/sjgxys.json")
  21. # TEMPLATE_FOLDER = resource_path("final/ByRules/templatesJson")
  22. # DATA_FOLDER = resource_path("final/Json/json_data")
  23. BASE_DIR = os.path.dirname(os.path.abspath(__file__))
  24. TEMPLATE_FOLDER = os.path.join(BASE_DIR, "templatesJson")
  25. DATA_FOLDER = os.path.join(BASE_DIR, "..", "Json", "json_data")
  26. MAPPING_FOLDER = os.path.join(BASE_DIR, "..", "Json", "sjgxys")
  27. MAPPING_FILE = os.path.join(MAPPING_FOLDER, "sjgxys.json")
  28. @app.route('/process_query', methods=['POST'])
  29. def process_query_route():
  30. data = request.get_json()
  31. query = data.get("query")
  32. if not query:
  33. # return jsonify({"error": "Query cannot be empty"}), 400
  34. # return jsonify({"error": "Query cannot be empty"}), 400
  35. return jsonify(error_response("Query cannot be empty"))
  36. try:
  37. result = process_query(query, template_dict, TEMPLATE_FOLDER)
  38. # 如果没有该问题模板
  39. if result['play'] == '疑问':
  40. response = {
  41. # "content": final_content,
  42. "content_text": result["content"],
  43. # "raw_result": final_value,
  44. # "conditions": result["conditions"],
  45. "name": result["name"],
  46. "play": result["play"]
  47. }
  48. # return jsonify(response)
  49. return jsonify(success_response(data=response))
  50. # 查询类问题:
  51. if result['type'] == 'query':
  52. if result["flag"]:
  53. final_value = smart_find_value(DATA_FOLDER, result["dataJsonName"], result["conditions"], result["target"])
  54. final_value = final_value[0]
  55. else:
  56. final_value = smart_find_value(DATA_FOLDER, result["dataJsonName"], result["conditions"],
  57. result["target"])
  58. final_content = result["content"].replace("&", str(final_value))
  59. # final_content = fill_template_auto(result['content'], final_value)
  60. response = {
  61. "content": final_content,
  62. "content_text": result["content"],
  63. "raw_result": final_value,
  64. "conditions": result["conditions"],
  65. "name": result["name"],
  66. "play": result["play"],
  67. "unit": result["unit"],
  68. }
  69. # return jsonify(response)
  70. return jsonify(success_response(data=response))
  71. # 计算类问题
  72. elif result['type'] == 'calculate':
  73. conditions = result["conditions"]
  74. # 从条件中分离出开始时间和结束时间
  75. start_conditions = {('年' if 'year' in k else '月'): v for k, v in conditions.items() if
  76. k.startswith('start_')}
  77. end_conditions = {('年' if 'year' in k else '月'): v for k, v in conditions.items() if k.startswith('end_')}
  78. fileName = result["dataJsonName"] + ".json"
  79. final_value = calculate_sum_by_time_range(DATA_FOLDER, fileName, result["target"], start_conditions,
  80. end_conditions)
  81. response = {
  82. "content_text": result["content"],
  83. "raw_result": final_value,
  84. "conditions": result["conditions"],
  85. "name": result["name"],
  86. "play": result["play"],
  87. "unit": result["unit"],
  88. }
  89. # return jsonify(response)
  90. return jsonify(success_response(data=response))
  91. # 最值类问题
  92. elif result['type'] == 'compare_max_min':
  93. find_max = str(result['find_max']).lower() == 'true'
  94. final_value = find_max_or_min_value(folder_path=DATA_FOLDER,
  95. file_name=result["dataJsonName"],
  96. value_key=result['value_key'],
  97. name_key=result['name_key'],
  98. mapping_file=MAPPING_FILE,
  99. conditions=result["conditions"],
  100. find_max=find_max)
  101. keys = [result['name_key'], result['value_key']]
  102. final_content = fill_template_auto(result['content'], final_value, keys)
  103. response = {
  104. "content": final_content,
  105. "content_text": result["content"],
  106. "raw_result": final_value,
  107. "conditions": result["conditions"],
  108. "name": result["name"],
  109. "play": result["play"],
  110. "unit": result["unit"],
  111. }
  112. # return jsonify(response)
  113. return jsonify(success_response(data=response))
  114. # TopN
  115. elif result['type'] == 'topN':
  116. topN = result["conditions"]['rank']
  117. del result["conditions"]['rank']
  118. # print(topN)
  119. final_value = find_top_n_by_value(folder_path=DATA_FOLDER,
  120. file_name=result["dataJsonName"],
  121. value_key=result['value_key'],
  122. name_key=result['name_key'],
  123. mapping_file=MAPPING_FILE,
  124. conditions=result["conditions"],
  125. top_n=topN, # 查前3高
  126. descending=True
  127. )
  128. # keys = [result['name_key'], result['value_key']]
  129. final_content = fill_template_auto(result['content'], str(final_value))
  130. response = {
  131. "content": final_content,
  132. "content_text": result["content"],
  133. "raw_result": final_value,
  134. "conditions": result["conditions"],
  135. "name": result["name"],
  136. "play": result["play"],
  137. "unit": result["unit"],
  138. }
  139. # return jsonify(response)
  140. return jsonify(success_response(data=response))
  141. # TopN
  142. elif result['type'] == 'rank':
  143. rank = result["conditions"]['rank2']
  144. del result["conditions"]['rank2']
  145. # print(topN)
  146. final_value = find_top_n_by_value(folder_path=DATA_FOLDER,
  147. file_name=result["dataJsonName"],
  148. value_key=result['value_key'],
  149. name_key=result['name_key'],
  150. mapping_file=MAPPING_FILE,
  151. conditions=result["conditions"],
  152. top_n=rank, # 查前3高
  153. descending=True
  154. )
  155. # keys = [result['name_key'], result['value_key']]
  156. contentResult = final_value[rank - 1]
  157. # 构造需要填充的列表
  158. fillResult = [rank, contentResult[result['name_key']]]
  159. final_content = fill_template_auto(result['content'], fillResult)
  160. response = {
  161. "rank": rank,
  162. "content": final_content,
  163. "content_text": result["content"],
  164. "raw_result": final_value,
  165. "conditions": result["conditions"],
  166. "name": result["name"],
  167. "play": result["play"],
  168. "qcode": result["qcode"],
  169. "unit": result["unit"],
  170. }
  171. # return jsonify(response)
  172. return jsonify(success_response(data=response))
  173. except Exception as e:
  174. # return jsonify({"error": str(e)}), 500
  175. return jsonify(error_response(data=str(e)))
  176. if __name__ == "__main__":
  177. app.run(debug=True)