strategy_parse.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. # -*- coding: utf-8 -*-
  2. """
  3. @author: yq
  4. @time: 2024/12/18
  5. @desc: 策略流节点解析
  6. """
  7. import json
  8. import re
  9. import time
  10. import pandas as pd
  11. from PIL import Image
  12. from openpyxl import load_workbook
  13. from commom import f_get_save_path, call_llm, f_file_upload, GeneralException
  14. from enums import ResultCodesEnum
  15. from prompt import f_get_prompt_parse_node, f_get_prompt_parse_flow
  16. def _f_parse_flow(ws):
  17. image = ws._images[0]
  18. img = Image.open(image.ref).convert("RGB")
  19. save_path = f_get_save_path("流程图.png")
  20. img.save(save_path)
  21. time.sleep(1)
  22. file_id = f_file_upload(save_path)
  23. prompt = f_get_prompt_parse_flow()
  24. prompt = [
  25. {
  26. "type": "text",
  27. "text": prompt
  28. },
  29. {
  30. "type": "image",
  31. "file_id": file_id
  32. }
  33. ]
  34. prompt = json.dumps(prompt, ensure_ascii=False)
  35. print(prompt)
  36. llm_answer = call_llm(prompt, "object_string")
  37. print(llm_answer)
  38. save_path = f_get_save_path("flow.py")
  39. with open(save_path, mode="w", encoding="utf8") as f:
  40. f.write(llm_answer)
  41. def _f_parse_node(df: pd.DataFrame, sheet_name):
  42. rules = ""
  43. for idx, row in df.iterrows():
  44. var_name = row["变量"]
  45. var_name = var_name.replace("\n", " ")
  46. rule_content = row["逻辑"]
  47. rule_out = row["输出"]
  48. rules = f"{rules}规则{idx + 1}: 变量:{var_name} 逻辑:{rule_content} 输出:{rule_out}\n"
  49. prompt = f_get_prompt_parse_node(sheet_name, rules)
  50. print(prompt)
  51. llm_answer = call_llm(prompt)
  52. llm_answer = re.findall(r"```python\n(.*)\n```", llm_answer, flags=re.DOTALL)[0]
  53. func_name = re.findall(r"def (.*)\(data", llm_answer)[0]
  54. save_path = f_get_save_path(f"{func_name}.py", "node")
  55. print(llm_answer)
  56. with open(save_path, mode="w", encoding="utf8") as f:
  57. f.write(llm_answer)
  58. def f_parse_strategy(file_path):
  59. wb = load_workbook(file_path)
  60. excel = pd.ExcelFile(file_path)
  61. sheet_names = excel.sheet_names
  62. if "流程图" not in sheet_names:
  63. GeneralException(ResultCodesEnum.NOT_FOUND, message=f"sheet【流程图】不存在")
  64. for sheet_name in sheet_names:
  65. if sheet_name == "流程图":
  66. _f_parse_flow(wb["流程图"])
  67. continue
  68. df = excel.parse(sheet_name=sheet_name)
  69. _f_parse_node(df, sheet_name)
  70. wb.close()
  71. excel.close()
  72. if __name__ == "__main__":
  73. f_parse_strategy("./cache/策略节点配置demo.xlsx")