utils.py 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  1. # -*- coding: utf-8 -*-
  2. """
  3. @author: yq
  4. @time: 2024/12/5
  5. @desc:
  6. """
  7. import json
  8. import os
  9. import shutil
  10. import time
  11. from typing import List
  12. import gradio as gr
  13. import pandas as pd
  14. from commom import f_read_file
  15. from config import BaseConfig
  16. from .manager import engine
  17. DATA_SUB_DIR = "data"
  18. UPLOAD_DATA_PREFIX = "prefix_upload_data_"
  19. def _clean_base_dir(data):
  20. base_dir = _get_base_dir(data)
  21. file_name_list: List[str] = os.listdir(base_dir)
  22. for file_name in file_name_list:
  23. if file_name in [DATA_SUB_DIR]:
  24. continue
  25. file_path = os.path.join(base_dir, file_name)
  26. if os.path.isdir(file_path):
  27. shutil.rmtree(file_path)
  28. else:
  29. os.remove(file_path)
  30. def _check_save_dir(data):
  31. project_name = engine.get(data, "project_name")
  32. if project_name is None or len(project_name) == 0:
  33. raise gr.Error(message='项目名称不能为空', duration=5)
  34. return True
  35. def _get_prefix_file(save_path, prefix):
  36. file_name_list: List[str] = os.listdir(save_path)
  37. for file_name in file_name_list:
  38. if prefix in file_name:
  39. return os.path.join(save_path, file_name)
  40. def _get_base_dir(data):
  41. project_name = engine.get(data, "project_name")
  42. base_dir = os.path.join(BaseConfig.base_dir, project_name)
  43. return base_dir
  44. def _get_upload_data(data) -> pd.ExcelFile:
  45. base_dir = _get_base_dir(data)
  46. save_path = os.path.join(base_dir, DATA_SUB_DIR)
  47. file_path = _get_prefix_file(save_path, UPLOAD_DATA_PREFIX)
  48. excel = pd.ExcelFile(file_path)
  49. return excel
  50. def _get_node_func_dict(data) -> dict:
  51. node_func_dict_path = _get_save_path(data, BaseConfig.node_map_name)
  52. if not os.path.exists(node_func_dict_path):
  53. return None
  54. with open(node_func_dict_path, mode="r", encoding="utf8") as f:
  55. node_func_dict = f.read()
  56. node_func_dict = json.loads(node_func_dict)
  57. return node_func_dict
  58. def f_project_is_exist(data):
  59. project_name = engine.get(data, "project_name")
  60. if project_name is None or len(project_name) == 0:
  61. gr.Warning(message='项目名称不能为空', duration=5)
  62. elif os.path.exists(_get_base_dir(data)):
  63. gr.Warning(message='项目名称已被使用', duration=5)
  64. def _get_save_path(data, file_name: str, sub_dir="", name_prefix=""):
  65. base_dir = _get_base_dir(data)
  66. save_path = os.path.join(base_dir, sub_dir)
  67. os.makedirs(save_path, exist_ok=True)
  68. # 有前缀标示的先删除
  69. if name_prefix:
  70. file = _get_prefix_file(save_path, name_prefix)
  71. if file:
  72. os.remove(file)
  73. save_path = os.path.join(save_path, name_prefix + os.path.basename(file_name))
  74. return save_path
  75. def f_data_upload(data):
  76. if not _check_save_dir(data):
  77. return
  78. file_data = engine.get(data, "file_data")
  79. data_path = _get_save_path(data, file_data.name, DATA_SUB_DIR, UPLOAD_DATA_PREFIX)
  80. shutil.copy(file_data.name, data_path)
  81. excel = _get_upload_data(data)
  82. df = excel.parse(sheet_name=BaseConfig.flow_sheet_name)
  83. columns = excel.sheet_names
  84. excel.close()
  85. return {
  86. engine.get_elem_by_id("data_upload"): gr.update(value=df, visible=True),
  87. engine.get_elem_by_id("sheet_name"): gr.update(choices=columns),
  88. }
  89. def f_get_sheet_data(data):
  90. sheet_name = engine.get(data, "sheet_name")
  91. excel = _get_upload_data(data)
  92. df = excel.parse(sheet_name=sheet_name)
  93. excel.close()
  94. node_func_dict = _get_node_func_dict(data)
  95. if node_func_dict is not None:
  96. code = f_read_file(_get_save_path(data, node_func_dict[sheet_name]))
  97. return {
  98. engine.get_elem_by_id("data_upload"): gr.update(value=df),
  99. engine.get_elem_by_id("code_view"): gr.update(value=code),
  100. }
  101. return {
  102. engine.get_elem_by_id("data_upload"): gr.update(value=df)
  103. }
  104. def f_download_code(data):
  105. file_path = _get_save_path(data, BaseConfig.code_zip_name)
  106. if os.path.exists(file_path):
  107. return {engine.get_elem_by_id("download_code"): gr.update(value=file_path)}
  108. else:
  109. raise FileNotFoundError(f"{file_path} not found.")
  110. def f_verify_param(data):
  111. excel = _get_upload_data(data)
  112. columns = excel.sheet_names
  113. excel.close()
  114. if BaseConfig.flow_sheet_name not in columns:
  115. raise gr.Error(message=f'【{BaseConfig.flow_sheet_name}】sheet不能为空', duration=5)
  116. return True
  117. def f_code_generate(data, progress=gr.Progress(track_tqdm=True)):
  118. def _reset_component_state():
  119. return {engine.get_elem_by_id("download_code"): gr.update(visible=False),
  120. engine.get_elem_by_id("code_view"): gr.update(visible=False)
  121. }
  122. progress(0, desc="Starting")
  123. all_param = engine.get_all(data)
  124. # 清空储存目录
  125. # _clean_base_dir(data)
  126. # 校验参数
  127. if not f_verify_param(data):
  128. yield _reset_component_state()
  129. yield _reset_component_state()
  130. progress(0.01)
  131. time.sleep(2)
  132. excel = None
  133. try:
  134. excel = _get_upload_data(data)
  135. # strategy_parse = StrategyParse(**all_param)
  136. # strategy_parse.f_parse_strategy(excel, progress)
  137. excel.close()
  138. except Exception as msg:
  139. if excel is not None:
  140. excel.close()
  141. yield _reset_component_state()
  142. raise gr.Error(message=f"系统错误【{msg}】", duration=5)
  143. code_zip_file_path = _get_save_path(data, BaseConfig.code_zip_name)
  144. node_func_dict = _get_node_func_dict(data)
  145. flow_code = f_read_file(_get_save_path(data, node_func_dict[BaseConfig.flow_sheet_name]))
  146. progress(1)
  147. yield {engine.get_elem_by_id("generate_progress"): gr.update(value="生成完成"),
  148. engine.get_elem_by_id("download_code"): gr.update(value=code_zip_file_path, visible=True),
  149. engine.get_elem_by_id("code_view"): gr.update(value=flow_code, visible=True),
  150. }