template5.py 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  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 ProductInfoTemplate(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.target_table = None # 第二个表格,存储产品信息
  18. def check_call_timing(self, preprocessed_data: Dict[str, Any]) -> bool:
  19. """检查是否符合模板调用条件"""
  20. if "表格列表" not in preprocessed_data:
  21. return False
  22. tables = preprocessed_data["表格列表"]
  23. if len(tables) < 1:
  24. print("表格数量不足,至少需要2个表格")
  25. return False
  26. try:
  27. self.target_table = tables[0]
  28. # 验证表格关键表头(按data.json第二个表格实际位置泛化匹配)
  29. header_patterns = [
  30. (0, 0, r'采购品目|品目'), # 第1行第1列
  31. (0, 2, r'品牌名称|品牌'), # 第1行第3列
  32. (1, 0, r'名称|产品名称'), # 第2行第1列
  33. (1, 2, r'产地及生产商|生产商|产地'), # 第2行第3列(用于验证表格结构)
  34. (2, 0, r'规格型号|规格|型号'), # 第3行第1列
  35. (2, 2, r'数量'), # 第3行第3列
  36. (3, 0, r'计量单位|单位'), # 第4行第1列
  37. (4, 0, r'单价'), # 第5行第1列
  38. (4, 2, r'总价|总金额'), # 第5行第3列
  39. ]
  40. # 验证表头
  41. for row, col, pattern in header_patterns:
  42. if row >= len(self.target_table) or col >= len(self.target_table[row]):
  43. return False
  44. header_text = self.target_table[row][col].strip()
  45. if not re.search(pattern, header_text, re.IGNORECASE):
  46. print(f"表头不匹配: {header_text} 不符合 {pattern}")
  47. return False
  48. return True
  49. except Exception as e:
  50. print(f"表格验证错误: {e}")
  51. return False
  52. def extract(self, preprocessed_data: Dict[str, Any]) -> Dict[str, Any]:
  53. """提取表格中的产品信息"""
  54. result = {"产品信息": []}
  55. # 提取产品信息
  56. product_info = self._extract_product_info()
  57. if product_info:
  58. result["产品信息"].append(product_info)
  59. return result
  60. def _get_value(self, table: list, row: int, col: int) -> str:
  61. """获取表格指定位置的值"""
  62. if row < len(table) and col < len(table[row]):
  63. return table[row][col].strip()
  64. return ""
  65. def _format_amount(self, value: str, header_row: int, header_col: int) -> str:
  66. """格式化金额,补充单位"""
  67. if not value:
  68. return ""
  69. # 检查值中是否已包含单位
  70. if re.search(r'[万亿美欧日]?元|¥|人民币', value):
  71. return value
  72. # 从表头获取单位补充
  73. header_text = self._get_value(self.target_table, header_row, header_col)
  74. if re.search(r'[万亿美欧日]?元|¥|人民币', header_text):
  75. unit = re.search(r'[万亿美欧日]?元|¥|人民币', header_text).group(0)
  76. return f"{value}{unit}"
  77. return value
  78. def _extract_product_info(self) -> Dict[str, Any]:
  79. """提取产品详细信息"""
  80. product = {
  81. "产品": self._get_value(self.target_table, 1, 1), # 产品名称
  82. "品目": self._get_value(self.target_table, 0, 1), # 采购品目
  83. "品牌": self._get_value(self.target_table, 0, 3), # 品牌名称
  84. "规格": self._get_value(self.target_table, 2, 1), # 规格型号
  85. "数量": self._get_value(self.target_table, 2, 3), # 数量
  86. "单位": self._get_value(self.target_table, 3, 1), # 计量单位
  87. "单价": self._format_amount(self._get_value(self.target_table, 4, 1), 4, 0), # 单价(补充单位)
  88. "总价": self._format_amount(self._get_value(self.target_table, 4, 3), 4, 2), # 总价(补充单位)
  89. }
  90. # 过滤空值字段
  91. return {k: v for k, v in product.items() if v}
  92. # 使用示例
  93. if __name__ == "__main__":
  94. with open("data.json", "r", encoding="utf8") as f:
  95. preprocessed_data = json.load(f)
  96. template = ProductInfoTemplate()
  97. if template.check_call_timing(preprocessed_data):
  98. result = template.extract(preprocessed_data)
  99. print("提取结果:", json.dumps(result, ensure_ascii=False, indent=2))
  100. else:
  101. print("当前数据不满足模板调用条件")