app.py 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  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. # 按照模板匹配的方法
  38. result = process_query(query, template_dict, TEMPLATE_FOLDER)
  39. # # 按照自动机提取模板的方式进行匹配
  40. # extractor = EntityExtractor()
  41. # result = extractor.extract(query)
  42. # 如果没有该问题模板
  43. if result['play'] == '疑问':
  44. response = {
  45. # "content": final_content,
  46. "content_text": result["content"],
  47. # "raw_result": final_value,
  48. # "conditions": result["conditions"],
  49. "name": result["name"],
  50. "play": result["play"]
  51. }
  52. # return jsonify(response)
  53. return jsonify(success_response(data=response))
  54. # 查询类问题:
  55. if result['type'] == 'query':
  56. if result["flag"]:
  57. final_value = smart_find_value(DATA_FOLDER, result["dataJsonName"], result["conditions"], result["target"])
  58. final_value = final_value[0]
  59. else:
  60. final_value = smart_find_value(DATA_FOLDER, result["dataJsonName"], result["conditions"],
  61. result["target"])
  62. final_content = result["content"].replace("&", str(final_value))
  63. # final_content = fill_template_auto(result['content'], final_value)
  64. response = {
  65. "content": final_content,
  66. "content_text": result["content"],
  67. "raw_result": final_value,
  68. "conditions": result["conditions"],
  69. "name": result["name"],
  70. "play": result["play"],
  71. "unit": result["unit"],
  72. }
  73. # return jsonify(response)
  74. return jsonify(success_response(data=response))
  75. # 计算类问题
  76. elif result['type'] == 'calculate':
  77. conditions = result["conditions"]
  78. # 从条件中分离出开始时间和结束时间
  79. start_conditions = {('年' if 'year' in k else '月'): v for k, v in conditions.items() if
  80. k.startswith('start_')}
  81. end_conditions = {('年' if 'year' in k else '月'): v for k, v in conditions.items() if k.startswith('end_')}
  82. fileName = result["dataJsonName"] + ".json"
  83. final_value = calculate_sum_by_time_range(DATA_FOLDER, fileName, result["target"], start_conditions,
  84. end_conditions)
  85. response = {
  86. "content_text": result["content"],
  87. "raw_result": final_value,
  88. "conditions": result["conditions"],
  89. "name": result["name"],
  90. "play": result["play"],
  91. "unit": result["unit"],
  92. }
  93. # return jsonify(response)
  94. return jsonify(success_response(data=response))
  95. # 最值类问题
  96. elif result['type'] == 'compare_max_min':
  97. find_max = str(result['find_max']).lower() == 'true'
  98. final_value = find_max_or_min_value(folder_path=DATA_FOLDER,
  99. file_name=result["dataJsonName"],
  100. value_key=result['value_key'],
  101. name_key=result['name_key'],
  102. mapping_file=MAPPING_FILE,
  103. conditions=result["conditions"],
  104. find_max=find_max)
  105. keys = [result['name_key'], result['value_key']]
  106. final_content = fill_template_auto(result['content'], final_value, keys)
  107. response = {
  108. "content": final_content,
  109. "content_text": result["content"],
  110. "raw_result": final_value,
  111. "conditions": result["conditions"],
  112. "name": result["name"],
  113. "play": result["play"],
  114. "unit": result["unit"],
  115. }
  116. # return jsonify(response)
  117. return jsonify(success_response(data=response))
  118. # TopN
  119. elif result['type'] == 'topN':
  120. topN = result["conditions"]['rank']
  121. del result["conditions"]['rank']
  122. # print(topN)
  123. final_value = find_top_n_by_value(folder_path=DATA_FOLDER,
  124. file_name=result["dataJsonName"],
  125. value_key=result['value_key'],
  126. name_key=result['name_key'],
  127. mapping_file=MAPPING_FILE,
  128. conditions=result["conditions"],
  129. top_n=topN, # 查前3高
  130. descending=True
  131. )
  132. # keys = [result['name_key'], result['value_key']]
  133. final_content = fill_template_auto(result['content'], str(final_value))
  134. response = {
  135. "content": final_content,
  136. "content_text": result["content"],
  137. "raw_result": final_value,
  138. "conditions": result["conditions"],
  139. "name": result["name"],
  140. "play": result["play"],
  141. "unit": result["unit"],
  142. }
  143. # return jsonify(response)
  144. return jsonify(success_response(data=response))
  145. # TopN
  146. elif result['type'] == 'rank':
  147. rank = result["conditions"]['rank2']
  148. del result["conditions"]['rank2']
  149. # print(topN)
  150. final_value = find_top_n_by_value(folder_path=DATA_FOLDER,
  151. file_name=result["dataJsonName"],
  152. value_key=result['value_key'],
  153. name_key=result['name_key'],
  154. mapping_file=MAPPING_FILE,
  155. conditions=result["conditions"],
  156. top_n=rank, # 查前3高
  157. descending=True
  158. )
  159. # keys = [result['name_key'], result['value_key']]
  160. contentResult = final_value[rank - 1]
  161. # 构造需要填充的列表
  162. fillResult = [rank, contentResult[result['name_key']]]
  163. final_content = fill_template_auto(result['content'], fillResult)
  164. response = {
  165. "rank": rank,
  166. "content": final_content,
  167. "content_text": result["content"],
  168. "raw_result": final_value,
  169. "conditions": result["conditions"],
  170. "name": result["name"],
  171. "play": result["play"],
  172. "qcode": result["qcode"],
  173. "unit": result["unit"],
  174. }
  175. # return jsonify(response)
  176. return jsonify(success_response(data=response))
  177. except Exception as e:
  178. # return jsonify({"error": str(e)}), 500
  179. return jsonify(error_response(data=str(e)))
  180. if __name__ == "__main__":
  181. app.run(debug=True)