template1.py 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  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. # 验证表头匹配(按位置严格校验,使用fullmatch)
  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. # 提取核心数据(产品信息+中标信息)
  75. for row in self.table_data:
  76. if len(row) != len(self.table_header):
  77. continue # 跳过长度不匹配的行
  78. # 按表头位置提取字段(严格对应data.json的列)
  79. payee = str(row[0]).strip() # 收款方(中标人)
  80. product_name = str(row[1]).strip() # 商品名称
  81. spec = str(row[2]).strip() # 规格
  82. unit = str(row[3]).strip() # 最小单位
  83. unit_price = str(row[4]).strip() # 单价
  84. quantity = str(row[5]).strip() # 数量
  85. total_price = str(row[6]).strip() # 总价
  86. # ========== 提取产品信息(必须包含产品+至少一个其他要素) ==========
  87. if product_name: # 产品名称为必填
  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)
  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, re.IGNORECASE):
  99. total_price += total_unit_match.group(1)
  100. elif total_price and not re.search(r'[万亿美欧日]?元', total_price, re.IGNORECASE):
  101. total_price += "元"
  102. # 构建产品信息字典
  103. product_info = {
  104. "产品": product_name,
  105. "品目": "",
  106. "品牌": "",
  107. "规格": spec,
  108. "数量": quantity,
  109. "单位": unit,
  110. "单价": unit_price,
  111. "总价": total_price
  112. }
  113. # 过滤空值字段
  114. product_info_filtered = {k: v for k, v in product_info.items() if v}
  115. # 产品信息必须包含产品+至少一个其他要素
  116. if len(product_info_filtered) > 1:
  117. extract_result["产品信息"].append(product_info_filtered)
  118. # ========== 按规则处理其他字段 ==========
  119. # 招标信息:无招标人/预算,置空(符合要求)
  120. extract_result["招标信息"] = []
  121. # 候选人信息:无候选人+排名,置空(符合要求)
  122. extract_result["候选人信息"] = []
  123. # 过滤顶层空值字段(项目编号/名称为空则移除)
  124. extract_result = {k: v for k, v in extract_result.items() if v or isinstance(v, list)}
  125. return extract_result
  126. # 使用示例
  127. if __name__ == "__main__":
  128. # 读取data.json数据
  129. with open("data.json", "r", encoding="utf8") as f:
  130. preprocessed_data = json.load(f)
  131. # 初始化模板并执行提取
  132. template = CustomTransactionTemplate()
  133. if template.check_call_timing(preprocessed_data):
  134. result = template.extract(preprocessed_data)
  135. # 输出格式化JSON结果
  136. print("提取结果:")
  137. print(json.dumps(result, ensure_ascii=False, indent=4))
  138. else:
  139. print("当前数据不满足模板调用条件")