data_stardard.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  1. import os
  2. import time
  3. import asyncio
  4. import io
  5. import csv
  6. import datetime
  7. import httpx
  8. # --- LangChain Imports ---
  9. from langchain_openai import ChatOpenAI
  10. from langchain_core.prompts import ChatPromptTemplate
  11. from langchain_core.output_parsers import JsonOutputParser
  12. # --- 核心 Parser ---
  13. class TransactionParserAgent:
  14. def __init__(self, api_key: str, multimodal_api_url: str, base_url: str = "https://api.deepseek.com"):
  15. # 1. 初始化 LangChain ChatOpenAI 客户端
  16. # DeepSeek 完全兼容 OpenAI 接口,使用 ChatOpenAI 是标准做法
  17. self.llm = ChatOpenAI(
  18. model="deepseek-chat",
  19. api_key=api_key,
  20. base_url=base_url,
  21. temperature=0.1,
  22. max_retries=3, # LangChain 内置重试机制
  23. # 配置 httpx 客户端以优化超时和连接 (LangChain 允许透传 http_client)
  24. http_client=httpx.Client(
  25. timeout=httpx.Timeout(300.0, read=300.0, connect=60.0),
  26. limits=httpx.Limits(max_keepalive_connections=5, max_connections=10)
  27. )
  28. )
  29. self.multimodal_api_url = multimodal_api_url
  30. # 定义 JSON 解析器
  31. self.parser = JsonOutputParser()
  32. async def _invoke_miner_u(self, file_path: str) -> str:
  33. """调用 MinerU 并提取纯行数据 (保持 httpx 调用不变,因为这不是 LLM)"""
  34. miner_start_time = time.perf_counter()
  35. print("\n" + "=" * 40)
  36. print("📌 【步骤1 - 数据提取】 开始执行")
  37. dealRows = 0
  38. try:
  39. # MinerU 是独立服务,继续使用原生 httpx
  40. async with httpx.AsyncClient() as client:
  41. with open(file_path, 'rb') as f:
  42. files = {'file': (os.path.basename(file_path), f)}
  43. data = {'folderId': 'text'}
  44. print("🔄数据提取中...")
  45. response = await client.post(self.multimodal_api_url, files=files, data=data, timeout=120.0)
  46. if response.status_code == 200:
  47. res_json = response.json()
  48. full_md_list = []
  49. for element in res_json.get('convert_json', []):
  50. if 'md' in element:
  51. full_md_list.append(element['md'])
  52. if 'rows' in element:
  53. dealRows+=len(element['rows'])
  54. print(f"📊 提取结果:共提取 {dealRows-1} 条数据")
  55. return "\n\n".join(full_md_list)
  56. return ""
  57. except Exception as e:
  58. print(f"❌ MinerU 调用异常: {e}")
  59. return ""
  60. finally:
  61. print(f"✅ 【步骤1 - 数据提取】 执行完成")
  62. print(f"⏱️ 执行耗时:{ time.perf_counter() - miner_start_time:.2f} 秒")
  63. def _get_csv_prompt_template(self) -> ChatPromptTemplate:
  64. """
  65. 构造 LangChain 的 Prompt 模板
  66. """
  67. system_template = """
  68. # Role
  69. 你是一个高精度的银行账单转换工具。
  70. # Task
  71. 将输入的 Markdown 表格行转换为 JSON 数组。
  72. # Field Rules
  73. 1. txId: 如果输入数据中有交易流水号则直接使用,如果没有,从 T{start_id:04d} 开始递增生成。
  74. 2. txDate: 交易日期,格式为YYYY-MM-DD
  75. 3. txTime: 交易时间,格式为HH:mm:ss (未知填 00:00:00)
  76. 4. txAmount: 交易金额,绝对值数字
  77. 5. txBalance: 交易后余额。浮点数,移除千分位逗号。
  78. 6. txDirection: 交易方向。必须根据以下逻辑判断只输出“收入”或“支出”:
  79. - 若有“借/贷”列:“借”通常为支出,“贷”通常为收入(除非是信用卡,需结合表头)。
  80. - 若有“收入/支出”分列:按列归类。
  81. - 若金额带正负号:"+"为收入,"-"为支出。
  82. - 如果无符号,请结合表头判断。
  83. 7. txSummary: 摘要、用途、业务类型等备注。
  84. 8. txCounterparty: 交易对手方(名称及账号,如有)。
  85. # Constraints
  86. - **强制输出格式**:
  87. 1. 严格返回一个包含对象的 JSON 数组。
  88. 2. 每个对象必须包含上述 8 个字段名作为 Key。
  89. 3. 不要输出任何解释文字或 Markdown 代码块标签。
  90. # Anti-Hallucination Rules
  91. - 不得根据上下文推断任何未在原始数据中明确出现的字段
  92. - 不得计算或猜测余额
  93. - 不得根据常识补全对手方名称
  94. - 若字段缺失,必须返回空字符串 ""
  95. """
  96. user_template = """# Input Data
  97. {chunk_data}
  98. # Output
  99. JSON Array:
  100. """
  101. return ChatPromptTemplate.from_messages([
  102. ("system", system_template),
  103. ("user", user_template)
  104. ])
  105. async def parse_to_csv(self, file_path: str) -> str:
  106. # 1. 获取完整 Markdown 文本并按行切分
  107. md_text = await self._invoke_miner_u(file_path)
  108. if not md_text:
  109. return ""
  110. # 记录开始时间(使用time.perf_counter获取高精度时间)
  111. switch_start_time = time.perf_counter()
  112. print("\n" + "=" * 40)
  113. print("📌 【步骤2 - 标准化转换】 开始执行")
  114. # 初步切分
  115. raw_lines = md_text.splitlines()
  116. # 提取真正的第一行作为基准表头
  117. clean_lines = [l.strip() for l in raw_lines if l.strip()]
  118. if len(clean_lines) < 2: return ""
  119. # --- 【核心改进:动态寻找表头】 ---
  120. table_header = ""
  121. header_index = 0
  122. header_keywords = ["余额", "金额", "账号", "日期", "借/贷", "摘要"]
  123. for idx, line in enumerate(clean_lines):
  124. # 如果某一行包含 2 个以上关键词,且含有 Markdown 表格分隔符 '|'
  125. hit_count = sum(1 for kw in header_keywords if kw in line)
  126. if hit_count >= 2 and "|" in line:
  127. table_header = line
  128. header_index = idx
  129. break
  130. if not table_header:
  131. table_header = clean_lines[0]
  132. header_index = 0
  133. data_rows = []
  134. for line in clean_lines[header_index + 1:]:
  135. if all(c in '|- ' for c in line): continue
  136. if line == table_header: continue
  137. # 过滤掉一些 MinerU 可能在表格末尾产生的页码或无关文字
  138. if "|" not in line: continue
  139. data_rows.append(line)
  140. csv_header = "txId,txDate,txTime,txAmount,txDirection,txBalance,txSummary,txCounterparty,createdAt\n"
  141. csv_content = csv_header
  142. batch_size = 15
  143. global_tx_counter = 1
  144. # 构建 LCEL Chain: Prompt -> LLM -> Parser
  145. chain = self._get_csv_prompt_template() | self.llm | self.parser
  146. # 2. 分块处理
  147. for i in range(0, len(data_rows), batch_size):
  148. chunk = data_rows[i: i + batch_size]
  149. context_chunk = [table_header] + chunk
  150. chunk_str = "\n".join(context_chunk)
  151. # 1. 记录开始时间(使用time.perf_counter获取高精度时间)
  152. start_time = time.perf_counter()
  153. print(f"🔄 正在通过LLM转换批次 {i // batch_size + 1},包含 {len(chunk)} 条数据...")
  154. # print(f"待转换的数据块:\n{chunk_str}")
  155. try:
  156. # --- LangChain 调用 ---
  157. # 使用 ainvoke 异步调用链
  158. data_data = await chain.ainvoke({
  159. "start_id": global_tx_counter,
  160. "chunk_data": chunk_str
  161. })
  162. # print(f"💡 LLM 返回数据: {data_data}")
  163. # 兼容处理:LangChain Parser 通常会直接返回 List 或 Dict
  164. if isinstance(data_data, dict):
  165. # 尝试寻找 transactions 键,如果没有则假设整个 dict 就是我们要的对象(虽然罕见)
  166. batch_data = data_data.get("transactions", [data_data])
  167. # 如果取出来还是 dict (例如单条记录),包一层 list
  168. if isinstance(batch_data, dict):
  169. batch_data = [batch_data]
  170. elif isinstance(data_data, list):
  171. batch_data = data_data
  172. else:
  173. batch_data = []
  174. if batch_data:
  175. output = io.StringIO()
  176. createdAtStr = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
  177. writer = csv.writer(output, quoting=csv.QUOTE_MINIMAL, lineterminator='\n')
  178. print(f"✅ 批次转换成功,包含 {len(batch_data)} 条记录。")
  179. for item in batch_data:
  180. writer.writerow([
  181. item.get("txId", ""),
  182. item.get("txDate", ""),
  183. item.get("txTime", ""),
  184. item.get("txAmount", ""),
  185. item.get("txDirection", ""),
  186. item.get("txBalance", ""),
  187. item.get("txSummary", ""),
  188. item.get("txCounterparty", ""),
  189. createdAtStr
  190. ])
  191. batch_csv_string = output.getvalue()
  192. csv_content += batch_csv_string
  193. global_tx_counter += len(batch_data)
  194. except Exception as e:
  195. print(f"⚠️ 批次执行失败: {e}")
  196. finally:
  197. end_time = time.perf_counter()
  198. elapsed_time = end_time - start_time
  199. print(f"⏱️ 执行耗时: {elapsed_time:.2f} 秒")
  200. print(f"📊 转换结果:共转换 {global_tx_counter - 1} 条数据")
  201. print(f"✅ 【步骤2 - 标准化转换】 执行完成")
  202. return csv_content
  203. async def parse_and_save_to_file(self, file_path: str, output_dir: str = "output") -> str:
  204. """
  205. 供 Workflow 调用:解析并保存文件,返回全路径名
  206. """
  207. current_script_path = os.path.abspath(__file__)
  208. current_dir = os.path.dirname(current_script_path)
  209. file_full_name = os.path.basename(file_path)
  210. file_name = os.path.splitext(file_full_name)[0] # 不带后缀 11111
  211. output_dir = os.path.normpath(os.path.join(current_dir, "..", "..", output_dir))
  212. os.makedirs(output_dir, exist_ok=True)
  213. timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
  214. file_name = f"{file_name}_data_standard_{timestamp}.csv"
  215. full_path = os.path.join(output_dir, file_name)
  216. csv_result = await self.parse_to_csv(file_path)
  217. if csv_result:
  218. with open(full_path, "w", encoding="utf-8") as f:
  219. f.write(csv_result)
  220. return full_path
  221. else:
  222. raise Exception("数据解析失败,未生成有效内容")
  223. async def run_workflow_task(self, input_file_path: str) -> dict:
  224. """
  225. 标准 Workflow 入口方法
  226. """
  227. # 1. 记录开始时间(使用time.perf_counter获取高精度时间)
  228. start_time = time.perf_counter()
  229. print(f"BEGIN---数据标准化任务开始---")
  230. try:
  231. print(f"待执行标准化的文件:{input_file_path}")
  232. api_results_dir = "data_files"
  233. saved_path = await self.parse_and_save_to_file(input_file_path, api_results_dir)
  234. return {
  235. "status": "success",
  236. "file_path": saved_path,
  237. "file_name": os.path.basename(saved_path),
  238. "timestamp": datetime.datetime.now().isoformat()
  239. }
  240. except Exception as e:
  241. return {
  242. "status": "error",
  243. "message": str(e)
  244. }
  245. finally:
  246. end_time = time.perf_counter()
  247. elapsed_time = end_time - start_time
  248. print(f"⏱️ 执行总耗时: {elapsed_time:.2f} 秒")
  249. print(f"END---数据标准化任务结束")
  250. # --- 运行 ---
  251. async def main():
  252. agent = TransactionParserAgent(
  253. api_key="sk-8634dbc2866540c4b6003bb5733f23d8",
  254. multimodal_api_url="http://103.154.31.78:20012/api/file/read"
  255. )
  256. current_script_path = os.path.abspath(__file__)
  257. current_dir = os.path.dirname(current_script_path)
  258. # 模拟 Workflow 传入一个待处理文件
  259. input_pdf = "data_files/11111.png"
  260. filepath = os.path.normpath(os.path.join(current_dir, "..", "..", input_pdf))
  261. if not os.path.exists(filepath):
  262. print(f"{filepath}文件不存在")
  263. return
  264. result = await agent.run_workflow_task(filepath)
  265. if result["status"] == "success":
  266. print(f"🎯 【数据标准化】任务完成!")
  267. else:
  268. print(f"❌ 任务失败: {result['message']}")
  269. if __name__ == "__main__":
  270. asyncio.run(main())