template2.py 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  1. # coding:utf8
  2. import re
  3. from typing import Dict, Any
  4. from BiddingKG.dl.template_extract.abstract_template import AbstractTemplate
  5. import os
  6. import json
  7. class CustomTransactionTemplate(AbstractTemplate):
  8. """
  9. 适配data.json表格结构(供应商/商品/货号/规格/单价/数量/总价)的成交信息提取模板
  10. 提取产品信息、中标信息,严格遵循返回格式要求
  11. """
  12. def __init__(self):
  13. super().__init__(
  14. template_id=os.path.abspath(__file__),
  15. priority=3
  16. )
  17. self.table_header = None # 表格表头
  18. self.table_data = None # 表格数据行
  19. def check_call_timing(self, preprocessed_data: Dict[str, Any]) -> bool:
  20. """
  21. 检查是否符合模板调用条件:匹配表格结构和核心表头(按data.json实际表头位置)
  22. :param preprocessed_data: 预处理后的输入数据(包含表格列表)
  23. :return: 是否符合调用条件
  24. """
  25. # 检查表格列表是否存在且有效
  26. if "表格列表" not in preprocessed_data:
  27. return False
  28. tables = preprocessed_data["表格列表"]
  29. if len(tables) < 1 or not isinstance(tables[0], list) or len(tables[0]) < 2:
  30. return False
  31. try:
  32. # 提取第一个表格的表头和数据
  33. target_table = tables[0]
  34. self.table_header = target_table[0]
  35. self.table_data = target_table[1:]
  36. # 定义核心表头的泛化正则匹配规则(按data.json实际表头位置)
  37. # 位置0:供应商 位置1:商品名称 位置2:货号 位置3:规格 位置4:单价 位置5:数量 位置6:总价
  38. header_patterns = [
  39. r'供应商|供应商名称|成交供应商|中标供应商|供货单位', # 第0列:供应商
  40. r'商品名称|产品名称|货品名称|物料名称|品名', # 第1列:商品名称
  41. r'货号|物料编码|产品编码|商品编号', # 第2列:货号
  42. r'规格|型号|规格型号|技术参数', # 第3列:规格
  43. r'单价|单价金额|单价(元)|单价(¥)', # 第4列:单价
  44. r'数量|数量值|采购数量|供货数量', # 第5列:数量
  45. r'总价|总金额|合计金额|金额总计' # 第6列:总价
  46. ]
  47. # 验证表头匹配(按位置校验,必须全部匹配)
  48. for idx, pattern in enumerate(header_patterns):
  49. if idx >= len(self.table_header):
  50. return False
  51. header_str = str(self.table_header[idx]).strip()
  52. if not re.fullmatch(pattern, header_str, re.IGNORECASE):
  53. print(f"表头位置{idx}匹配失败: 预期{pattern},实际{header_str}")
  54. return False
  55. return True
  56. except Exception as e:
  57. print(f"校验表格失败: {e}")
  58. return False
  59. def extract(self, preprocessed_data: Dict[str, Any]) -> Dict[str, Any]:
  60. """
  61. 提取表格数据,按指定格式返回(过滤空值、校验字段有效性)
  62. :param preprocessed_data: 预处理后的输入数据
  63. :return: 提取结果(符合指定JSON格式)
  64. """
  65. # 初始化返回结果结构
  66. extract_result = {
  67. "项目编号": "",
  68. "项目名称": "",
  69. "招标信息": [],
  70. "中标信息": [],
  71. "候选人信息": [],
  72. "产品信息": []
  73. }
  74. # 提取核心数据(按data.json表头位置)
  75. for row in self.table_data:
  76. if len(row) != len(self.table_header):
  77. continue # 跳过长度不匹配的行
  78. # 按表头位置提取字段(先做基础清洗)
  79. supplier_name = str(row[0]).strip() # 供应商(中标人)
  80. product_name = str(row[1]).strip() # 商品名称
  81. product_spec = str(row[3]).strip() # 规格
  82. unit_price = str(row[4]).strip() # 单价
  83. quantity = str(row[5]).strip() # 数量
  84. total_price = str(row[6]).strip() # 总价
  85. # ========== 1. 提取中标信息(必须包含中标人) ==========
  86. if supplier_name:
  87. # 处理单价/总价的单位补充(优先从表头提取,无则默认加"元")
  88. # 补充单价单位
  89. price_header = str(self.table_header[4]).strip()
  90. unit_match = re.search(r'([万亿美欧日]?元|¥)', price_header, re.IGNORECASE)
  91. if unit_match and unit_price and not re.search(unit_match.group(1), unit_price, re.IGNORECASE):
  92. unit_price += unit_match.group(1).replace("¥", "元")
  93. elif unit_price and not re.search(r'[万亿美欧日]?元|¥', unit_price, re.IGNORECASE):
  94. unit_price += "元"
  95. # 补充总价单位
  96. total_header = str(self.table_header[6]).strip()
  97. total_unit_match = re.search(r'([万亿美欧日]?元|¥)', total_header, re.IGNORECASE)
  98. if total_unit_match and total_price and not re.search(total_unit_match.group(1), total_price,
  99. re.IGNORECASE):
  100. total_price += total_unit_match.group(1).replace("¥", "元")
  101. elif total_price and not re.search(r'[万亿美欧日]?元|¥', total_price, re.IGNORECASE):
  102. total_price += "元"
  103. # 构建中标信息(中标价取总价,无总价则取单价*数量)
  104. bid_price = total_price if total_price else (f"{float(unit_price.replace('元', '')) * float(quantity)}元"
  105. if unit_price and quantity and unit_price.replace('元',
  106. '').replace(
  107. '.', '').isdigit() and quantity.replace('.', '').isdigit() else "")
  108. bid_info = {
  109. "标的": "",
  110. "标包": "",
  111. "包号": "",
  112. "中标人": supplier_name,
  113. "中标价": bid_price,
  114. "联系人": "",
  115. "电话": "",
  116. "服务时间": "",
  117. "地址": ""
  118. }
  119. # 过滤空值字段
  120. bid_info_filtered = {k: v for k, v in bid_info.items() if v}
  121. if bid_info_filtered: # 确保非空才添加
  122. extract_result["中标信息"].append(bid_info_filtered)
  123. # ========== 2. 提取产品信息(必须包含产品+至少一个其他要素) ==========
  124. if product_name:
  125. product_info = {
  126. "产品": product_name,
  127. "品目": "",
  128. "品牌": "",
  129. "规格": product_spec,
  130. "数量": quantity,
  131. "单位": "",
  132. "单价": unit_price,
  133. "总价": total_price
  134. }
  135. # 过滤空值字段
  136. product_info_filtered = {k: v for k, v in product_info.items() if v}
  137. # 验证:必须包含产品 + 至少一个其他要素
  138. if len(product_info_filtered) >= 2:
  139. extract_result["产品信息"].append(product_info_filtered)
  140. # ========== 3. 处理其他字段(无数据则置空) ==========
  141. # 招标信息:无招标人/预算,置空
  142. extract_result["招标信息"] = []
  143. # 候选人信息:无候选人+排名,置空
  144. extract_result["候选人信息"] = []
  145. # ========== 4. 过滤顶层空值字段 ==========
  146. extract_result = {k: v for k, v in extract_result.items() if v or isinstance(v, list)}
  147. return extract_result
  148. # 使用示例
  149. if __name__ == "__main__":
  150. # 读取data.json数据
  151. with open("data.json", "r", encoding="utf8") as f:
  152. preprocessed_data = json.load(f)
  153. # 初始化模板并执行提取
  154. template = CustomTransactionTemplate()
  155. if template.check_call_timing(preprocessed_data):
  156. result = template.extract(preprocessed_data)
  157. # 输出格式化JSON结果
  158. print("提取结果:")
  159. print(json.dumps(result, ensure_ascii=False, indent=4))
  160. else:
  161. print("当前数据不满足模板调用条件")