data_stardard.py 13 KB

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