investment_parser.py 57 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289
  1. # Copyright (c) Opendatalab. All rights reserved.
  2. """
  3. 投资估算表格解析模块
  4. 支持四种类型:
  5. 1. 可研批复投资估算
  6. 2. 可研评审投资估算
  7. 3. 初设批复概算投资
  8. 4. 安评可研批复投资估算
  9. """
  10. from typing import List, Optional
  11. import re
  12. from ..utils.logging_config import get_logger
  13. from ..models.data_models import (
  14. FeasibilityApprovalInvestment,
  15. FeasibilityReviewInvestment,
  16. PreliminaryApprovalInvestment,
  17. InvestmentItem,
  18. FinalAccountRecord,
  19. FinalAccountItem
  20. )
  21. from .table_parser import extract_table_with_rowspan_colspan
  22. logger = get_logger("pdf_converter_v2.parser.investment")
  23. def detect_investment_type(markdown_content: str) -> Optional[str]:
  24. """
  25. 检测投资估算表格类型
  26. Returns:
  27. str: 类型名称
  28. - "fsApproval" - 可研批复
  29. - "fsReview" - 可研评审
  30. - "pdApproval" - 初设批复
  31. - "safetyFsApproval" - 安评可研批复
  32. - None - 无法识别
  33. """
  34. # 安评可研批复(先于可研批复判断,结构同可研批复)
  35. if "安评可研批复" in markdown_content or ("安全评价" in markdown_content and "可行性研究报告的批复" in markdown_content):
  36. if "架空线" in markdown_content or "间隔" in markdown_content:
  37. logger.info("[投资估算] 检测到类型: 安评可研批复投资估算")
  38. return "safetyFsApproval"
  39. # 检查标题关键词
  40. if "可研批复" in markdown_content or "可行性研究报告的批复" in markdown_content:
  41. # 检查是否有建设规模相关列(可研批复特有)
  42. if "架空线" in markdown_content or "间隔" in markdown_content:
  43. logger.info("[投资估算] 检测到类型: 可研批复投资估算")
  44. return "fsApproval"
  45. if "可研评审" in markdown_content or "可行性研究报告的评审意见" in markdown_content:
  46. logger.info("[投资估算] 检测到类型: 可研评审投资估算")
  47. return "fsReview"
  48. if "初设批复" in markdown_content or "初步设计的批复" in markdown_content:
  49. logger.info("[投资估算] 检测到类型: 初设批复概算投资")
  50. return "pdApproval"
  51. logger.warning("[投资估算] 无法识别投资估算表格类型")
  52. return None
  53. def determine_level(text: str, name: str = "", strict_mode: bool = True) -> str:
  54. """
  55. 判断明细等级
  56. 规则:
  57. - 大写中文数字(一、二、三等) -> 第一级(顶级大类)
  58. - strict_mode=True: 需要名称包含电压等级+输变电工程才是一级,否则降为二级
  59. - strict_mode=False: 中文数字直接判断为一级(用于 fsReview、pdApproval)
  60. - 小写阿拉伯数字(1、2、3等) -> 第二级
  61. - 带括号的数字(1)、2)等) -> 第三级
  62. - 合计 -> 0
  63. Args:
  64. text: 序号或名称文本
  65. name: 可选,名称文本,用于辅助判断(区分顶级大类和子项)
  66. strict_mode: 是否使用严格模式(默认True,用于 fsApproval 区分顶级大类)
  67. Returns:
  68. str: "0"(合计), "1"(一级), "2"(二级), "3"(三级), ""(无法判断)
  69. """
  70. if not text:
  71. return ""
  72. text = text.strip()
  73. # 合计行(包含"合 计"这种带空格的情况)
  74. text_no_space = text.replace(" ", "")
  75. if "合计" in text_no_space or "小计" in text_no_space:
  76. return "0"
  77. # 第一级: 大写中文数字
  78. # 匹配: "一、", "一,", "一.", "一 ", "一" (后面可以跟任意字符或结束)
  79. # 注意:需要排除"十一"、"十二"等多位数字,只匹配单个中文数字
  80. is_chinese_numeral = False
  81. if re.match(r'^[一二三四五六七八九十]+[、,,.\s]', text):
  82. is_chinese_numeral = True
  83. # 如果序号后面直接跟汉字(没有标点),也可能是第一级
  84. # 例如: "一变电工程", "二线路工程"
  85. elif re.match(r'^[一二三四五六七八九十]+[\u4e00-\u9fa5]', text):
  86. is_chinese_numeral = True
  87. # 如果只是单独的中文数字(没有后续字符),也可能是第一级
  88. # 例如: "一", "二", "三"
  89. elif re.match(r'^[一二三四五六七八九十]+$', text):
  90. is_chinese_numeral = True
  91. if is_chinese_numeral:
  92. # 非严格模式:中文数字直接判断为一级(用于 fsReview、pdApproval)
  93. if not strict_mode:
  94. return "1"
  95. # 严格模式:进一步判断,区分顶级大类和子项目(用于 fsApproval)
  96. # 顶级大类特征:名称包含电压等级(如"220千伏"、"500kV")+ 输变电工程
  97. # 子项目特征:简单的工程类型名称(变电工程、线路工程、配套通信工程)
  98. name_to_check = name if name else text
  99. # 1. 检查是否是顶级大类(包含电压等级 + 输变电工程)
  100. # 电压等级模式:220千伏、500kV、110kv、35千伏等
  101. has_voltage = bool(re.search(r'\d+\s*(千伏|kV|KV|kv)', name_to_check, re.IGNORECASE))
  102. has_project_type = "输变电" in name_to_check or "变电站" in name_to_check or "送出工程" in name_to_check
  103. if has_voltage and has_project_type:
  104. # 包含电压等级和工程类型,是顶级大类
  105. return "1"
  106. # 2. 检查是否是子项目(固定名称,人为错误可能把"3"写成"三")
  107. # 子项目名称通常较短且是固定的工程类型
  108. subitem_exact = ["变电工程", "线路工程", "配套通信工程", "通信工程"]
  109. is_exact_subitem = name_to_check in subitem_exact
  110. if is_exact_subitem:
  111. # 完全匹配子项目名称,按二级处理
  112. logger.debug(f"[等级判断] 中文数字序号但名称是子项目,按二级处理: text={text}, name={name}")
  113. return "2"
  114. # 3. 其他情况:如果名称较长(>10字符),可能是顶级大类;否则按二级处理
  115. if len(name_to_check) > 10:
  116. # 较长的名称可能是顶级大类(即使没有匹配到电压等级模式)
  117. return "1"
  118. else:
  119. # 较短的名称,按二级处理
  120. logger.debug(f"[等级判断] 中文数字序号但名称较短,按二级处理: text={text}, name={name}")
  121. return "2"
  122. # 第二级: 小写阿拉伯数字
  123. # 匹配: "1、", "1,", "1.", "1 " (后面跟标点或空格)
  124. if re.match(r'^\d+[、,,.\s]', text) and not text.startswith('(') and not text.startswith('('):
  125. return "2"
  126. # 如果数字后面直接跟汉字(没有标点),也认为是第二级
  127. # 例如: "1周村220kV变电站"
  128. if re.match(r'^\d+[\u4e00-\u9fa5]', text) and not text.startswith('(') and not text.startswith('('):
  129. return "2"
  130. # 如果只是单独的阿拉伯数字(没有后续字符),也是第二级
  131. # 例如: "1", "2", "3"
  132. if re.match(r'^\d+$', text) and not text.startswith('(') and not text.startswith('('):
  133. return "2"
  134. # 第三级: 带括号的数字,或者数字后跟右括号
  135. # 匹配: "(1)", "(1)", "1)", "1)"
  136. if re.match(r'^[((]\d+[))]', text):
  137. return "3"
  138. # 数字后跟右括号,如 "1)", "2)"
  139. if re.match(r'^\d+[))]', text):
  140. return "3"
  141. return ""
  142. def clean_number_string(value: str) -> str:
  143. """
  144. 清理数字字符串
  145. - 移除千位分隔符
  146. - 移除单位
  147. - 保留小数点
  148. Args:
  149. value: 原始数字字符串
  150. Returns:
  151. str: 清理后的数字字符串
  152. """
  153. if not value or not value.strip():
  154. return ""
  155. value = value.strip()
  156. # 移除常见单位
  157. value = re.sub(r'[万元元]', '', value)
  158. # 移除千位分隔符
  159. value = value.replace(',', '').replace(',', '')
  160. # 移除空格
  161. value = value.replace(' ', '')
  162. return value
  163. def parse_feasibility_approval_investment(markdown_content: str) -> FeasibilityApprovalInvestment:
  164. """
  165. 解析可研批复投资估算
  166. 包含字段:
  167. - No: 序号
  168. - name: 工程或费用名称
  169. - Level: 明细等级
  170. - constructionScaleOverheadLine: 建设规模-架空线
  171. - constructionScaleBay: 建设规模-间隔
  172. - constructionScaleSubstation: 建设规模-变电
  173. - constructionScaleOpticalCable: 建设规模-光缆
  174. - staticInvestment: 静态投资(元)
  175. - dynamicInvestment: 动态投资(元)
  176. """
  177. record = FeasibilityApprovalInvestment()
  178. tables = extract_table_with_rowspan_colspan(markdown_content)
  179. if not tables:
  180. logger.warning("[可研批复投资] 未能提取出任何表格内容")
  181. return record
  182. # 找到所有投资估算表格并合并
  183. # 因为OCR可能将一个大表格拆分成多个<table>
  184. all_matching_tables = []
  185. for table_idx, table in enumerate(tables):
  186. table_text = ""
  187. for row in table:
  188. table_text += " ".join([str(cell) for cell in row])
  189. # 移除空格后再匹配
  190. table_text_no_space = table_text.replace(" ", "")
  191. # 选择包含"工程或费用名称"和"静态投资"的表格
  192. if "工程或费用名称" in table_text_no_space and "静态投资" in table_text_no_space:
  193. all_matching_tables.append((table_idx, table))
  194. logger.info(f"[可研批复投资] 找到投资估算表格 (表格{table_idx+1}), 行数: {len(table)}")
  195. if not all_matching_tables:
  196. logger.warning("[可研批复投资] 未找到包含投资估算的表格")
  197. return record
  198. # 如果只有一个表格,直接使用
  199. if len(all_matching_tables) == 1:
  200. target_table = all_matching_tables[0][1]
  201. else:
  202. # 多个表格:合并所有表格的数据行(跳过重复的表头行)
  203. logger.info(f"[可研批复投资] 发现 {len(all_matching_tables)} 个投资估算表格,将进行合并")
  204. target_table = []
  205. first_table = True
  206. for table_idx, table in all_matching_tables:
  207. if first_table:
  208. # 第一个表格:保留全部内容(包括表头)
  209. target_table.extend(table)
  210. first_table = False
  211. else:
  212. # 后续表格:跳过表头行(前几行包含"序号"、"工程或费用名称"等)
  213. header_end_idx = 0
  214. for row_idx, row in enumerate(table):
  215. row_text = " ".join([str(cell) for cell in row]).replace(" ", "")
  216. # 如果这行包含表头关键词,继续跳过
  217. if "序号" in row_text or "工程或费用名称" in row_text or "建设规模" in row_text:
  218. header_end_idx = row_idx + 1
  219. # 如果第一列是中文数字(一、二、三...),说明是数据行开始
  220. elif len(row) > 0:
  221. first_cell = str(row[0]).strip()
  222. if first_cell in ["一", "二", "三", "四", "五", "六", "七", "八", "九", "十"]:
  223. break
  224. # 只添加数据行
  225. target_table.extend(table[header_end_idx:])
  226. logger.debug(f"[可研批复投资] 表格{table_idx+1}: 跳过前{header_end_idx}行表头,添加{len(table)-header_end_idx}行数据")
  227. logger.info(f"[可研批复投资] 合并后总行数: {len(target_table)}")
  228. # 识别表头行和列索引
  229. # 注意:表格可能有多层表头(rowspan),需要扫描前几行来找到所有列名
  230. header_row_idx = -1
  231. no_idx = -1
  232. name_idx = -1
  233. overhead_line_idx = -1
  234. bay_idx = -1
  235. substation_idx = -1
  236. optical_cable_idx = -1
  237. static_investment_idx = -1
  238. dynamic_investment_idx = -1
  239. # 新增费用列索引
  240. construction_project_cost_idx = -1 # 建筑工程费
  241. equipment_purchase_cost_idx = -1 # 设备购置费
  242. installation_project_cost_idx = -1 # 安装工程费
  243. other_expenses_idx = -1 # 其他费用(合计)
  244. # 扫描前几行(最多5行)来识别列索引
  245. for row_idx in range(min(5, len(target_table))):
  246. row = target_table[row_idx]
  247. row_text = " ".join([str(cell) for cell in row])
  248. row_text_no_space = row_text.replace(" ", "")
  249. # 识别各列(遍历所有行的所有列)
  250. for col_idx, cell in enumerate(row):
  251. cell_text = str(cell).strip()
  252. cell_text_no_space = cell_text.replace(" ", "")
  253. if "序号" in cell_text and no_idx == -1:
  254. no_idx = col_idx
  255. elif ("工程或费用名称" in cell_text_no_space) and name_idx == -1:
  256. name_idx = col_idx
  257. elif "架空线" in cell_text_no_space and overhead_line_idx == -1:
  258. overhead_line_idx = col_idx
  259. elif "间隔" in cell_text and bay_idx == -1:
  260. bay_idx = col_idx
  261. elif "变电" in cell_text and substation_idx == -1:
  262. substation_idx = col_idx
  263. elif "光缆" in cell_text and optical_cable_idx == -1:
  264. optical_cable_idx = col_idx
  265. elif "静态投资" in cell_text_no_space and static_investment_idx == -1:
  266. static_investment_idx = col_idx
  267. elif "动态投资" in cell_text_no_space and dynamic_investment_idx == -1:
  268. dynamic_investment_idx = col_idx
  269. # 新增费用字段识别
  270. elif "建筑工程费" in cell_text_no_space and construction_project_cost_idx == -1:
  271. construction_project_cost_idx = col_idx
  272. elif "设备购置费" in cell_text_no_space and equipment_purchase_cost_idx == -1:
  273. equipment_purchase_cost_idx = col_idx
  274. elif "安装工程费" in cell_text_no_space and installation_project_cost_idx == -1:
  275. installation_project_cost_idx = col_idx
  276. elif ("其他费用" in cell_text_no_space or "合计" == cell_text_no_space) and other_expenses_idx == -1:
  277. # 其他费用列通常标题为"合计"或"其他费用"
  278. # 注意:表头可能有"合计"列在"其他费用"下面
  279. if "其他费用" in cell_text_no_space:
  280. other_expenses_idx = col_idx
  281. # 如果这一行包含"序号"或"工程或费用名称",记录为表头结束行
  282. if ("序号" in row_text or "工程或费用名称" in row_text_no_space) and header_row_idx == -1:
  283. header_row_idx = row_idx
  284. # 表头结束行应该是最后一个包含表头内容的行
  285. # 找到第一个数据行(通常是"一"、"二"等开头)
  286. for row_idx in range(min(5, len(target_table))):
  287. row = target_table[row_idx]
  288. if len(row) > 0:
  289. first_cell = str(row[0]).strip()
  290. # 如果第一列是中文数字或阿拉伯数字(不是"序号"),这是数据行
  291. if first_cell and first_cell not in ["序号", ""] and (first_cell in ["一", "二", "三", "四", "五"] or first_cell.isdigit()):
  292. header_row_idx = row_idx - 1
  293. logger.debug(f"[可研批复投资] 根据数据行确定表头结束于第{header_row_idx}行")
  294. break
  295. logger.info(f"[可研批复投资] 表头行: {header_row_idx}")
  296. logger.info(f"[可研批复投资] 列索引: 序号={no_idx}, 名称={name_idx}, "
  297. f"架空线={overhead_line_idx}, 间隔={bay_idx}, 变电={substation_idx}, "
  298. f"光缆={optical_cable_idx}, 静态投资={static_investment_idx}, 动态投资={dynamic_investment_idx}")
  299. logger.info(f"[可研批复投资] 费用列索引: 建筑工程费={construction_project_cost_idx}, "
  300. f"设备购置费={equipment_purchase_cost_idx}, 安装工程费={installation_project_cost_idx}, "
  301. f"其他费用={other_expenses_idx}")
  302. if header_row_idx == -1:
  303. logger.warning("[可研批复投资] 未找到表头行")
  304. return record
  305. # 解析数据行(输出全部数据,不再只筛选"四"区域)
  306. for row_idx in range(header_row_idx + 1, len(target_table)):
  307. row = target_table[row_idx]
  308. if len(row) < 3:
  309. continue
  310. # 检查是否是有效数据行(至少有名称)
  311. if name_idx >= 0 and name_idx < len(row):
  312. name = str(row[name_idx]).strip()
  313. if not name or name in ["", "nan", "None"]:
  314. continue
  315. # 提取序号
  316. no = ""
  317. if no_idx >= 0 and no_idx < len(row):
  318. no = str(row[no_idx]).strip()
  319. # 判断等级,传入 name 辅助区分顶级大类和子项
  320. level_input = (no + name) if no else name
  321. level = determine_level(level_input, name)
  322. item = InvestmentItem()
  323. item.no = no
  324. item.name = name
  325. item.level = level
  326. # 提取建设规模
  327. if overhead_line_idx >= 0 and overhead_line_idx < len(row):
  328. item.constructionScaleOverheadLine = str(row[overhead_line_idx]).strip()
  329. if bay_idx >= 0 and bay_idx < len(row):
  330. item.constructionScaleBay = str(row[bay_idx]).strip()
  331. if substation_idx >= 0 and substation_idx < len(row):
  332. item.constructionScaleSubstation = str(row[substation_idx]).strip()
  333. if optical_cable_idx >= 0 and optical_cable_idx < len(row):
  334. item.constructionScaleOpticalCable = str(row[optical_cable_idx]).strip()
  335. # 提取投资金额
  336. if static_investment_idx >= 0 and static_investment_idx < len(row):
  337. item.staticInvestment = clean_number_string(str(row[static_investment_idx]))
  338. if dynamic_investment_idx >= 0 and dynamic_investment_idx < len(row):
  339. item.dynamicInvestment = clean_number_string(str(row[dynamic_investment_idx]))
  340. # 提取费用明细
  341. if construction_project_cost_idx >= 0 and construction_project_cost_idx < len(row):
  342. item.constructionProjectCost = clean_number_string(str(row[construction_project_cost_idx]))
  343. if equipment_purchase_cost_idx >= 0 and equipment_purchase_cost_idx < len(row):
  344. item.equipmentPurchaseCost = clean_number_string(str(row[equipment_purchase_cost_idx]))
  345. if installation_project_cost_idx >= 0 and installation_project_cost_idx < len(row):
  346. item.installationProjectCost = clean_number_string(str(row[installation_project_cost_idx]))
  347. if other_expenses_idx >= 0 and other_expenses_idx < len(row):
  348. item.otherExpenses = clean_number_string(str(row[other_expenses_idx]))
  349. record.items.append(item)
  350. logger.info(f"[可研批复投资] 解析到数据: No={item.no}, Name={item.name}, Level={item.level}")
  351. logger.info(f"[可研批复投资] 共解析到 {len(record.items)} 条数据")
  352. return record
  353. def parse_safety_feasibility_approval_investment(markdown_content: str) -> FeasibilityApprovalInvestment:
  354. """
  355. 解析安全可研批复投资估算(湖北省格式)
  356. 特点:
  357. - 没有顶层大类(Level=1),直接从二级分类开始
  358. - 中文序号(一、二)表示二级分类(如"变电工程"、"线路工程")
  359. - 阿拉伯数字(1、2、3)表示具体项目
  360. - 列名使用"项目名称"和"静态合计/动态合计"
  361. - 先扫描项目信息表提取工程名称、项目单位、设计单位
  362. 返回结构:
  363. - Level 1: 二级分类(如"变电工程"、"线路工程")
  364. - Level 2: 具体项目(如"襄阳连云220千伏变电站新建工程")
  365. """
  366. record = FeasibilityApprovalInvestment()
  367. tables = extract_table_with_rowspan_colspan(markdown_content)
  368. if not tables:
  369. logger.warning("[安全可研批复投资] 未能提取出任何表格内容")
  370. return record
  371. # 首先尝试提取项目基本信息表格
  372. for table_idx, table in enumerate(tables):
  373. if len(table) < 2:
  374. continue
  375. table_text = ""
  376. for row in table:
  377. table_text += " ".join([str(cell) for cell in row])
  378. table_text_no_space = table_text.replace(" ", "").replace("(", "(").replace(")", ")")
  379. if "工程(项目)名称" in table_text_no_space or "工程项目名称" in table_text_no_space:
  380. logger.info(f"[安全可研批复投资] 找到项目信息表格 (表格{table_idx+1})")
  381. for row in table:
  382. if len(row) >= 2:
  383. key = str(row[0]).strip()
  384. value = str(row[1]).strip() if len(row) > 1 else ""
  385. if "工程" in key and "名称" in key:
  386. record.projectName = value
  387. logger.info(f"[安全可研批复投资] 提取工程名称: {value}")
  388. elif "项目单位" in key:
  389. record.projectUnit = value
  390. logger.info(f"[安全可研批复投资] 提取项目单位: {value}")
  391. elif "设计单位" in key:
  392. record.designUnit = value
  393. logger.info(f"[安全可研批复投资] 提取设计单位: {value}")
  394. break
  395. # 找到所有投资估算表格并合并
  396. all_matching_tables = []
  397. for table_idx, table in enumerate(tables):
  398. table_text = ""
  399. for row in table:
  400. table_text += " ".join([str(cell) for cell in row])
  401. table_text_no_space = table_text.replace(" ", "")
  402. has_name_col = "项目名称" in table_text_no_space
  403. has_investment_col = ("静态合计" in table_text_no_space or "静态投资" in table_text_no_space)
  404. if has_name_col and has_investment_col:
  405. all_matching_tables.append((table_idx, table))
  406. logger.info(f"[安全可研批复投资] 找到投资估算表格 (表格{table_idx+1}), 行数: {len(table)}")
  407. if not all_matching_tables:
  408. logger.warning("[安全可研批复投资] 未找到包含投资估算的表格")
  409. return record
  410. # 只使用第一个投资估算表,避免多表合并导致 data 中重复出现「变电站工程」「线路工程」
  411. target_table = all_matching_tables[0][1]
  412. if len(all_matching_tables) > 1:
  413. logger.info(f"[安全可研批复投资] 发现 {len(all_matching_tables)} 个投资估算表格,仅使用第一个表格避免重复")
  414. header_row_idx = -1
  415. no_idx = name_idx = overhead_line_idx = bay_idx = substation_idx = optical_cable_idx = -1
  416. static_investment_idx = dynamic_investment_idx = -1
  417. construction_project_cost_idx = equipment_purchase_cost_idx = installation_project_cost_idx = other_expenses_idx = -1
  418. for row_idx in range(min(5, len(target_table))):
  419. row = target_table[row_idx]
  420. row_text = " ".join([str(cell) for cell in row])
  421. row_text_no_space = row_text.replace(" ", "")
  422. for col_idx, cell in enumerate(row):
  423. cell_text = str(cell).strip()
  424. cell_text_no_space = cell_text.replace(" ", "")
  425. if "序号" in cell_text and no_idx == -1:
  426. no_idx = col_idx
  427. elif "项目名称" in cell_text_no_space and name_idx == -1:
  428. name_idx = col_idx
  429. elif "架空线" in cell_text_no_space and overhead_line_idx == -1:
  430. overhead_line_idx = col_idx
  431. elif "间隔" in cell_text and bay_idx == -1:
  432. bay_idx = col_idx
  433. elif "变电" in cell_text and substation_idx == -1:
  434. substation_idx = col_idx
  435. elif "光缆" in cell_text and optical_cable_idx == -1:
  436. optical_cable_idx = col_idx
  437. elif ("静态投资" in cell_text_no_space or "静态合计" in cell_text_no_space) and static_investment_idx == -1:
  438. static_investment_idx = col_idx
  439. elif ("动态投资" in cell_text_no_space or "动态合计" in cell_text_no_space) and dynamic_investment_idx == -1:
  440. dynamic_investment_idx = col_idx
  441. elif "建筑工程费" in cell_text_no_space and construction_project_cost_idx == -1:
  442. construction_project_cost_idx = col_idx
  443. elif "设备购置费" in cell_text_no_space and equipment_purchase_cost_idx == -1:
  444. equipment_purchase_cost_idx = col_idx
  445. elif "安装工程费" in cell_text_no_space and installation_project_cost_idx == -1:
  446. installation_project_cost_idx = col_idx
  447. elif ("其他费用" in cell_text_no_space or "合计" == cell_text_no_space) and other_expenses_idx == -1:
  448. if "其他费用" in cell_text_no_space:
  449. other_expenses_idx = col_idx
  450. if ("序号" in row_text or "项目名称" in row_text_no_space) and header_row_idx == -1:
  451. header_row_idx = row_idx
  452. for row_idx in range(min(5, len(target_table))):
  453. row = target_table[row_idx]
  454. if len(row) > 0:
  455. first_cell = str(row[0]).strip()
  456. if first_cell and first_cell not in ["序号", ""] and (first_cell in ["一", "二", "三", "四", "五"] or first_cell.isdigit()):
  457. header_row_idx = row_idx - 1
  458. break
  459. if header_row_idx == -1:
  460. logger.warning("[安全可研批复投资] 未找到表头行")
  461. return record
  462. for row_idx in range(header_row_idx + 1, len(target_table)):
  463. row = target_table[row_idx]
  464. if len(row) < 3:
  465. continue
  466. name = str(row[name_idx]).strip() if name_idx >= 0 and name_idx < len(row) else ""
  467. if not name or name in ["", "nan", "None"]:
  468. continue
  469. no = str(row[no_idx]).strip() if no_idx >= 0 and no_idx < len(row) else ""
  470. level_input = (no + name) if no else name
  471. level = determine_level(level_input, name, strict_mode=False)
  472. item = InvestmentItem()
  473. item.no = no
  474. item.name = name
  475. item.level = level
  476. if overhead_line_idx >= 0 and overhead_line_idx < len(row):
  477. item.constructionScaleOverheadLine = str(row[overhead_line_idx]).strip()
  478. if bay_idx >= 0 and bay_idx < len(row):
  479. item.constructionScaleBay = str(row[bay_idx]).strip()
  480. if substation_idx >= 0 and substation_idx < len(row):
  481. item.constructionScaleSubstation = str(row[substation_idx]).strip()
  482. if optical_cable_idx >= 0 and optical_cable_idx < len(row):
  483. item.constructionScaleOpticalCable = str(row[optical_cable_idx]).strip()
  484. if static_investment_idx >= 0 and static_investment_idx < len(row):
  485. item.staticInvestment = clean_number_string(str(row[static_investment_idx]))
  486. if dynamic_investment_idx >= 0 and dynamic_investment_idx < len(row):
  487. item.dynamicInvestment = clean_number_string(str(row[dynamic_investment_idx]))
  488. if construction_project_cost_idx >= 0 and construction_project_cost_idx < len(row):
  489. item.constructionProjectCost = clean_number_string(str(row[construction_project_cost_idx]))
  490. if equipment_purchase_cost_idx >= 0 and equipment_purchase_cost_idx < len(row):
  491. item.equipmentPurchaseCost = clean_number_string(str(row[equipment_purchase_cost_idx]))
  492. if installation_project_cost_idx >= 0 and installation_project_cost_idx < len(row):
  493. item.installationProjectCost = clean_number_string(str(row[installation_project_cost_idx]))
  494. if other_expenses_idx >= 0 and other_expenses_idx < len(row):
  495. item.otherExpenses = clean_number_string(str(row[other_expenses_idx]))
  496. record.items.append(item)
  497. logger.info(f"[安全可研批复投资] 解析到数据: No={item.no}, Name={item.name}, Level={item.level}")
  498. logger.info(f"[安全可研批复投资] 共解析到 {len(record.items)} 条数据")
  499. return record
  500. def parse_feasibility_review_investment(markdown_content: str) -> FeasibilityReviewInvestment:
  501. """
  502. 解析可研评审投资估算
  503. 包含字段:
  504. - No: 序号
  505. - name: 工程或费用名称
  506. - Level: 明细等级
  507. - staticInvestment: 静态投资(元)
  508. - dynamicInvestment: 动态投资(元)
  509. 注意:文档中可能包含多个表格,只解析"输变电工程建设规模及投资估算表"
  510. 排除"总估算表"类型的表格
  511. """
  512. record = FeasibilityReviewInvestment()
  513. # 使用正则表达式查找表格及其前面的标题
  514. # 查找 "输变电工程" + "投资估算表" 的标题,排除 "总估算表"
  515. import re
  516. # 找到目标表格的标题位置
  517. # 标题格式如: # 山西晋城周村220kV输变电工程建设规模及投资估算表
  518. target_table_pattern = re.compile(
  519. r'#\s*[^#\n]*?(输变电工程|输变电|变电工程)[^#\n]*?(建设规模及)?投资估算表',
  520. re.IGNORECASE
  521. )
  522. # 排除"总估算表"的模式
  523. exclude_pattern = re.compile(r'总估算表', re.IGNORECASE)
  524. # 查找所有匹配的标题
  525. target_title_match = None
  526. for match in target_table_pattern.finditer(markdown_content):
  527. title_text = match.group(0)
  528. if not exclude_pattern.search(title_text):
  529. target_title_match = match
  530. logger.info(f"[可研评审投资] 找到目标表格标题: {title_text}")
  531. break
  532. if not target_title_match:
  533. logger.warning("[可研评审投资] 未找到'输变电工程投资估算表'标题")
  534. # 回退到原有逻辑
  535. tables = extract_table_with_rowspan_colspan(markdown_content)
  536. if not tables:
  537. logger.warning("[可研评审投资] 未能提取出任何表格内容")
  538. return record
  539. target_table = None
  540. for table in tables:
  541. for row in table:
  542. row_text = " ".join([str(cell) for cell in row])
  543. row_text_no_space = row_text.replace(" ", "")
  544. if "工程或费用名称" in row_text_no_space or ("序号" in row_text and "静态投资" in row_text_no_space):
  545. target_table = table
  546. logger.info(f"[可研评审投资] 回退: 找到投资估算表格, 行数: {len(table)}")
  547. break
  548. if target_table:
  549. break
  550. if not target_table:
  551. logger.warning("[可研评审投资] 未找到包含投资估算的表格")
  552. return record
  553. else:
  554. # 提取标题后面到下一个标题之间的内容(包含目标表格)
  555. title_end = target_title_match.end()
  556. # 找到下一个标题或文档结束
  557. next_title_pattern = re.compile(r'\n#\s+[^#]')
  558. next_title_match = next_title_pattern.search(markdown_content, title_end)
  559. if next_title_match:
  560. section_content = markdown_content[target_title_match.start():next_title_match.start()]
  561. else:
  562. section_content = markdown_content[target_title_match.start():]
  563. logger.debug(f"[可研评审投资] 提取表格区域内容长度: {len(section_content)} 字符")
  564. # 从该区域提取表格
  565. tables = extract_table_with_rowspan_colspan(section_content)
  566. if not tables:
  567. logger.warning("[可研评审投资] 目标区域未能提取出任何表格内容")
  568. return record
  569. # 选择第一个有效表格
  570. target_table = None
  571. for table in tables:
  572. for row in table:
  573. row_text = " ".join([str(cell) for cell in row])
  574. row_text_no_space = row_text.replace(" ", "")
  575. if "工程或费用名称" in row_text_no_space or ("序号" in row_text and "静态投资" in row_text_no_space):
  576. target_table = table
  577. logger.info(f"[可研评审投资] 找到目标投资估算表格, 行数: {len(table)}")
  578. break
  579. if target_table:
  580. break
  581. if not target_table:
  582. logger.warning("[可研评审投资] 目标区域未找到包含投资估算的表格")
  583. return record
  584. # 识别表头行和列索引(多行表头处理)
  585. # 这个表格有多行表头(rowspan/colspan),需要扫描前几行来找到所有列索引
  586. no_idx = -1
  587. name_idx = -1
  588. static_investment_idx = -1
  589. dynamic_investment_idx = -1
  590. header_row_idx = -1
  591. # 扫描前5行查找列索引
  592. scan_rows = min(5, len(target_table))
  593. for row_idx in range(scan_rows):
  594. row = target_table[row_idx]
  595. for col_idx, cell in enumerate(row):
  596. cell_text = str(cell).strip()
  597. cell_text_no_space = cell_text.replace(" ", "")
  598. if "序号" in cell_text and no_idx == -1:
  599. no_idx = col_idx
  600. elif ("工程或费用名称" in cell_text_no_space or "工程名称" in cell_text_no_space) and name_idx == -1:
  601. name_idx = col_idx
  602. elif "静态投资" in cell_text_no_space and static_investment_idx == -1:
  603. static_investment_idx = col_idx
  604. elif "动态投资" in cell_text_no_space and dynamic_investment_idx == -1:
  605. dynamic_investment_idx = col_idx
  606. logger.info(f"[可研评审投资] 列索引: 序号={no_idx}, 名称={name_idx}, "
  607. f"静态投资={static_investment_idx}, 动态投资={dynamic_investment_idx}")
  608. # 确定表头结束行(第一个数据行的前一行)
  609. # 数据行特征:第一列是中文数字(一、二、三)或阿拉伯数字
  610. for row_idx in range(len(target_table)):
  611. row = target_table[row_idx]
  612. if len(row) > 0:
  613. first_cell = str(row[0]).strip()
  614. # 检查是否是数据行(以中文数字或阿拉伯数字开头)
  615. if re.match(r'^[一二三四五六七八九十]+$', first_cell) or re.match(r'^\d+$', first_cell):
  616. # 排除表头行(检查第二列是否是表头关键词)
  617. if len(row) > 1:
  618. second_cell = str(row[1]).strip().replace(" ", "")
  619. if second_cell not in ["工程或费用名称", "工程名称", "名称", ""]:
  620. header_row_idx = row_idx - 1
  621. logger.debug(f"[可研评审投资] 确定表头结束行: 第{header_row_idx}行")
  622. break
  623. if header_row_idx == -1:
  624. header_row_idx = 2 # 默认假设前3行是表头
  625. logger.debug(f"[可研评审投资] 使用默认表头结束行: 第{header_row_idx}行")
  626. # 解析数据行
  627. for row_idx in range(header_row_idx + 1, len(target_table)):
  628. row = target_table[row_idx]
  629. if len(row) < 2:
  630. continue
  631. if name_idx >= 0 and name_idx < len(row):
  632. name = str(row[name_idx]).strip()
  633. if not name or name in ["", "nan", "None"]:
  634. continue
  635. # 跳过重复的表头行
  636. name_no_space = name.replace(" ", "")
  637. if name_no_space in ["工程或费用名称", "工程名称", "名称"]:
  638. logger.debug(f"[可研评审投资] 跳过表头行: {name}")
  639. continue
  640. item = InvestmentItem()
  641. if no_idx >= 0 and no_idx < len(row):
  642. item.no = str(row[no_idx]).strip()
  643. # 跳过表头中的序号列
  644. if item.no == "序号":
  645. continue
  646. item.name = name
  647. # 判断等级 - 使用 no 和 name 分别判断
  648. # fsReview 使用非严格模式,中文数字直接判断为一级
  649. if item.no:
  650. # 优先使用 no 判断等级
  651. item.level = determine_level(item.no, item.name, strict_mode=False)
  652. if not item.level:
  653. # 如果 no 没有匹配,尝试使用 name
  654. item.level = determine_level(item.name, item.name, strict_mode=False)
  655. else:
  656. item.level = determine_level(item.name, item.name, strict_mode=False)
  657. # 提取投资金额
  658. if static_investment_idx >= 0 and static_investment_idx < len(row):
  659. item.staticInvestment = clean_number_string(str(row[static_investment_idx]))
  660. if dynamic_investment_idx >= 0 and dynamic_investment_idx < len(row):
  661. item.dynamicInvestment = clean_number_string(str(row[dynamic_investment_idx]))
  662. record.items.append(item)
  663. logger.info(f"[可研评审投资] 解析到数据: No={item.no}, Name={item.name}, Level={item.level}, "
  664. f"静态投资={item.staticInvestment}, 动态投资={item.dynamicInvestment}")
  665. logger.info(f"[可研评审投资] 共解析到 {len(record.items)} 条数据")
  666. return record
  667. def parse_preliminary_approval_investment(markdown_content: str) -> PreliminaryApprovalInvestment:
  668. """
  669. 解析初设批复概算投资
  670. 包含字段:
  671. - No: 序号
  672. - name: 工程名称
  673. - Level: 明细等级
  674. - staticInvestment: 静态投资(元)
  675. - dynamicInvestment: 动态投资(元)
  676. Note: 需要包含合计行,合计的level为0
  677. """
  678. logger.info("[初设批复投资] ========== 开始解析初设批复概算投资 ==========")
  679. logger.debug(f"[初设批复投资] Markdown内容长度: {len(markdown_content)} 字符")
  680. record = PreliminaryApprovalInvestment()
  681. logger.info("[初设批复投资] 开始提取表格...")
  682. tables = extract_table_with_rowspan_colspan(markdown_content)
  683. logger.info(f"[初设批复投资] 提取到 {len(tables) if tables else 0} 个表格")
  684. if not tables:
  685. logger.warning("[初设批复投资] 未能提取出任何表格内容")
  686. return record
  687. # 找到包含投资估算的表格
  688. logger.info("[初设批复投资] 开始查找投资估算表格...")
  689. target_table = None
  690. for table_idx, table in enumerate(tables):
  691. logger.debug(f"[初设批复投资] 检查表格 {table_idx + 1}/{len(tables)}, 行数: {len(table)}")
  692. for row_idx, row in enumerate(table):
  693. row_text = " ".join([str(cell) for cell in row])
  694. # 移除空格后再匹配,以处理OCR可能产生的空格
  695. row_text_no_space = row_text.replace(" ", "")
  696. # 输出前几行用于调试
  697. if row_idx < 3:
  698. logger.debug(f"[初设批复投资] 表格{table_idx+1} 第{row_idx+1}行: {row_text[:100]}")
  699. if "工程名称" in row_text_no_space or ("序号" in row_text and "静态投资" in row_text_no_space):
  700. target_table = table
  701. logger.info(f"[初设批复投资] ✓ 找到投资估算表格 (表格{table_idx+1}), 行数: {len(table)}")
  702. logger.debug(f"[初设批复投资] 匹配行内容: {row_text}")
  703. break
  704. if target_table:
  705. break
  706. if not target_table:
  707. logger.warning("[初设批复投资] ✗ 未找到包含投资估算的表格")
  708. logger.warning("[初设批复投资] 查找条件: 包含'工程名称' 或 ('序号' 且 '静态投资')")
  709. return record
  710. # 识别表头行和列索引
  711. logger.info("[初设批复投资] 开始识别表头行和列索引...")
  712. header_row_idx = -1
  713. no_idx = -1
  714. name_idx = -1
  715. static_investment_idx = -1
  716. dynamic_investment_idx = -1
  717. for row_idx, row in enumerate(target_table):
  718. row_text = " ".join([str(cell) for cell in row])
  719. # 移除空格后再匹配,以处理OCR可能产生的空格
  720. row_text_no_space = row_text.replace(" ", "")
  721. logger.debug(f"[初设批复投资] 检查第{row_idx}行: {row_text[:80]}")
  722. if "工程名称" in row_text_no_space or "序号" in row_text:
  723. header_row_idx = row_idx
  724. logger.info(f"[初设批复投资] ✓ 找到表头行: 第{row_idx}行")
  725. logger.debug(f"[初设批复投资] 表头内容: {row}")
  726. for col_idx, cell in enumerate(row):
  727. cell_text = str(cell).strip()
  728. # 移除空格后再匹配,以处理OCR可能产生的空格
  729. cell_text_no_space = cell_text.replace(" ", "")
  730. logger.debug(f"[初设批复投资] 列{col_idx}: '{cell_text}' (去空格: '{cell_text_no_space}')")
  731. if "序号" in cell_text:
  732. no_idx = col_idx
  733. logger.debug(f"[初设批复投资] → 序号列: {col_idx}")
  734. elif "工程名称" in cell_text_no_space or "名称" in cell_text:
  735. name_idx = col_idx
  736. logger.debug(f"[初设批复投资] → 名称列: {col_idx}")
  737. elif "静态投资" in cell_text_no_space:
  738. static_investment_idx = col_idx
  739. logger.debug(f"[初设批复投资] → 静态投资列: {col_idx}")
  740. elif "动态投资" in cell_text_no_space:
  741. dynamic_investment_idx = col_idx
  742. logger.debug(f"[初设批复投资] → 动态投资列: {col_idx}")
  743. logger.info(f"[初设批复投资] ✓ 列索引识别完成: 序号={no_idx}, 名称={name_idx}, "
  744. f"静态投资={static_investment_idx}, 动态投资={dynamic_investment_idx}")
  745. break
  746. if header_row_idx == -1:
  747. logger.warning("[初设批复投资] ✗ 未找到表头行")
  748. logger.warning("[初设批复投资] 查找条件: 包含'工程名称' 或 '序号'")
  749. return record
  750. # 解析数据行
  751. logger.info(f"[初设批复投资] 开始解析数据行 (从第{header_row_idx + 1}行到第{len(target_table)}行)...")
  752. parsed_count = 0
  753. skipped_count = 0
  754. for row_idx in range(header_row_idx + 1, len(target_table)):
  755. row = target_table[row_idx]
  756. logger.debug(f"[初设批复投资] 处理第{row_idx}行, 列数: {len(row)}")
  757. if len(row) < 2:
  758. logger.debug(f"[初设批复投资] 跳过第{row_idx}行: 列数不足 ({len(row)} < 2)")
  759. skipped_count += 1
  760. continue
  761. if name_idx >= 0 and name_idx < len(row):
  762. name = str(row[name_idx]).strip()
  763. logger.debug(f"[初设批复投资] 第{row_idx}行名称: '{name}'")
  764. if not name or name in ["", "nan", "None"]:
  765. logger.debug(f"[初设批复投资] 跳过第{row_idx}行: 名称为空")
  766. skipped_count += 1
  767. continue
  768. item = InvestmentItem()
  769. if no_idx >= 0 and no_idx < len(row):
  770. item.no = str(row[no_idx]).strip()
  771. item.name = name
  772. # 判断等级 - pdApproval 使用非严格模式,中文数字直接判断为一级
  773. level_input = (item.no + item.name) if item.no else item.name
  774. item.level = determine_level(level_input, item.name, strict_mode=False)
  775. logger.debug(f"[初设批复投资] 等级判断: '{level_input}' -> Level={item.level}")
  776. # 提取投资金额
  777. if static_investment_idx >= 0 and static_investment_idx < len(row):
  778. raw_static = str(row[static_investment_idx])
  779. item.staticInvestment = clean_number_string(raw_static)
  780. logger.debug(f"[初设批复投资] 静态投资: '{raw_static}' -> '{item.staticInvestment}'")
  781. if dynamic_investment_idx >= 0 and dynamic_investment_idx < len(row):
  782. raw_dynamic = str(row[dynamic_investment_idx])
  783. item.dynamicInvestment = clean_number_string(raw_dynamic)
  784. logger.debug(f"[初设批复投资] 动态投资: '{raw_dynamic}' -> '{item.dynamicInvestment}'")
  785. record.items.append(item)
  786. parsed_count += 1
  787. logger.info(f"[初设批复投资] ✓ 解析到数据 #{parsed_count}: No={item.no}, Name={item.name}, Level={item.level}, "
  788. f"静态={item.staticInvestment}, 动态={item.dynamicInvestment}")
  789. else:
  790. logger.debug(f"[初设批复投资] 跳过第{row_idx}行: name_idx={name_idx} 超出范围 (行长度={len(row)})")
  791. skipped_count += 1
  792. logger.info(f"[初设批复投资] ========== 解析完成 ==========")
  793. logger.info(f"[初设批复投资] 成功解析: {parsed_count} 条")
  794. logger.info(f"[初设批复投资] 跳过: {skipped_count} 条")
  795. logger.info(f"[初设批复投资] 总计: {len(record.items)} 条数据")
  796. return record
  797. def parse_investment_record(markdown_content: str, investment_type: Optional[str] = None):
  798. """
  799. 解析投资估算记录(统一入口)
  800. Args:
  801. markdown_content: Markdown内容
  802. investment_type: 投资类型(可选,如果不提供则自动检测)
  803. - "fsApproval" - 可研批复
  804. - "fsReview" - 可研评审
  805. - "pdApproval" - 初设批复
  806. - "safetyFsApproval" - 安评可研批复
  807. Returns:
  808. 解析后的记录对象
  809. """
  810. logger.info("=" * 80)
  811. logger.info("[投资估算] 开始解析投资估算记录")
  812. logger.info(f"[投资估算] Markdown内容长度: {len(markdown_content)} 字符")
  813. # 如果没有指定类型,自动检测
  814. if not investment_type:
  815. logger.info("[投资估算] 未指定类型,开始自动检测...")
  816. investment_type = detect_investment_type(markdown_content)
  817. logger.info(f"[投资估算] 自动检测结果: {investment_type}")
  818. else:
  819. logger.info(f"[投资估算] 指定类型: {investment_type}")
  820. if not investment_type:
  821. logger.error("[投资估算] 无法识别投资估算类型")
  822. logger.error(f"[投资估算] Markdown前500字符: {markdown_content[:500]}")
  823. return None
  824. # 根据类型调用对应的解析函数
  825. logger.info(f"[投资估算] 调用解析函数: {investment_type}")
  826. result = None
  827. if investment_type == "fsApproval":
  828. result = parse_feasibility_approval_investment(markdown_content)
  829. elif investment_type == "safetyFsApproval":
  830. # 安评可研批复使用独立解析(湖北省格式,含项目信息表)
  831. result = parse_safety_feasibility_approval_investment(markdown_content)
  832. elif investment_type == "fsReview":
  833. result = parse_feasibility_review_investment(markdown_content)
  834. elif investment_type == "pdApproval":
  835. result = parse_preliminary_approval_investment(markdown_content)
  836. else:
  837. logger.error(f"[投资估算] 未知的投资估算类型: {investment_type}")
  838. return None
  839. if result:
  840. logger.info(f"[投资估算] 解析完成,返回对象类型: {type(result).__name__}")
  841. logger.info(f"[投资估算] 记录数量: {len(result.items)}")
  842. else:
  843. logger.error("[投资估算] 解析函数返回 None")
  844. logger.info("=" * 80)
  845. return result
  846. def parse_final_account_record(markdown_content: str) -> Optional[FinalAccountRecord]:
  847. """
  848. 解析决算报告中的单项工程投资完成情况表格
  849. 从OCR输出的Markdown中提取表格数据:
  850. - 表格结构:费用项目 | 概算金额 | 决算金额(审定-不含税) | 增值税额 | 超节支金额 | 超节支率
  851. - 需要提取4个单项工程的投资完成情况
  852. Args:
  853. markdown_content: OCR转换后的Markdown内容
  854. Returns:
  855. FinalAccountRecord 对象,包含所有单项工程的费用明细
  856. """
  857. logger.info("=" * 80)
  858. logger.info("[决算报告] 开始解析决算报告")
  859. logger.info(f"[决算报告] Markdown内容长度: {len(markdown_content)} 字符")
  860. record = FinalAccountRecord()
  861. # 使用正则表达式提取单项工程名称和对应的表格
  862. # 匹配模式:数字序号 + 工程名称(在"单项工程的投资完成情况"章节内)
  863. project_patterns = [
  864. # 匹配 "1、周村 220kV 输变电工程变电站新建工程" 格式
  865. (r'(\d+)[、\..]\s*(.+?(?:工程|扩建))(?:\n|$)', 1),
  866. # 匹配 "# 1、周村220kV变电站新建工程" 格式(带标题标记)
  867. (r'#\s*(\d+)[、\..]\s*(.+?(?:工程|扩建))(?:\n|$)', 2),
  868. ]
  869. # 找到"单项工程的投资完成情况"章节的起始位置
  870. section_start = 0
  871. section_patterns = [
  872. r'单项工程的?(?:投资)?完成情况',
  873. r'#\s*单项工程',
  874. ]
  875. for pattern in section_patterns:
  876. match = re.search(pattern, markdown_content)
  877. if match:
  878. section_start = match.start()
  879. logger.info(f"[决算报告] 找到单项工程章节起始位置: {section_start}")
  880. break
  881. # 找到所有项目标题及其位置
  882. project_positions = []
  883. for pattern, priority in project_patterns:
  884. for match in re.finditer(pattern, markdown_content):
  885. # 只处理单项工程章节内的项目
  886. if match.start() < section_start:
  887. continue
  888. project_no = int(match.group(1))
  889. project_name = match.group(2).strip()
  890. # 清理项目名称中的多余空格和特殊字符
  891. project_name = re.sub(r'\s+', '', project_name)
  892. project_name = re.sub(r'\\[()\[\]]', '', project_name)
  893. # 清理LaTeX数学公式格式
  894. project_name = re.sub(r'\\mathrm\{([^}]+)\}', r'\1', project_name)
  895. project_name = re.sub(r'\\[a-zA-Z]+', '', project_name)
  896. project_positions.append({
  897. "no": project_no,
  898. "name": project_name,
  899. "start": match.start(),
  900. "end": match.end(),
  901. "priority": priority
  902. })
  903. # 按位置排序并去重
  904. project_positions.sort(key=lambda x: x["start"])
  905. seen_positions = set()
  906. unique_projects = []
  907. for proj in project_positions:
  908. # 避免重复的项目(位置相近的同名项目)
  909. key = (proj["no"], proj["start"] // 100)
  910. if key not in seen_positions:
  911. seen_positions.add(key)
  912. unique_projects.append(proj)
  913. logger.info(f"[决算报告] 找到 {len(unique_projects)} 个单项工程")
  914. for proj in unique_projects:
  915. logger.debug(f"[决算报告] 项目 {proj['no']}: {proj['name']}")
  916. # 提取HTML表格及其位置
  917. table_pattern = r'<table[^>]*>(.*?)</table>'
  918. table_matches = list(re.finditer(table_pattern, markdown_content, re.DOTALL | re.IGNORECASE))
  919. logger.info(f"[决算报告] 找到 {len(table_matches)} 个HTML表格")
  920. # 解析每个表格
  921. for table_idx, table_match in enumerate(table_matches):
  922. table_html = table_match.group(1)
  923. table_pos = table_match.start()
  924. # 检查是否为单项工程投资完成情况表格
  925. if not _is_final_account_table(table_html, table_pos, section_start):
  926. logger.debug(f"[决算报告] 表格 {table_idx + 1} 不是单项工程投资完成情况表格,跳过")
  927. continue
  928. # 查找最近的项目
  929. matched_project = None
  930. for proj in unique_projects:
  931. if proj["end"] < table_pos:
  932. matched_project = proj
  933. if not matched_project:
  934. # 如果没有找到匹配的项目,使用表格索引作为项目序号
  935. logger.warning(f"[决算报告] 表格 {table_idx + 1} 未找到对应的项目名称")
  936. matched_project = {"no": table_idx + 1, "name": f"未知工程{table_idx + 1}"}
  937. logger.info(f"[决算报告] 解析表格 {table_idx + 1},关联项目: {matched_project['no']}-{matched_project['name']}")
  938. # 解析表格内容
  939. items = _parse_final_account_table_html(table_html, matched_project["no"], matched_project["name"])
  940. record.items.extend(items)
  941. logger.info(f"[决算报告] 解析完成,共 {len(record.items)} 条记录")
  942. logger.info("=" * 80)
  943. return record
  944. def _is_final_account_table(table_html: str, table_pos: int, section_start: int) -> bool:
  945. """
  946. 判断表格是否为单项工程投资完成情况表格
  947. 特征:
  948. 1. 位于"单项工程的投资完成情况"章节内
  949. 2. 包含"费用项目"、"概算金额"、"决算金额"、"超"、"节"等关键词
  950. Args:
  951. table_html: 表格HTML内容
  952. table_pos: 表格在Markdown中的位置
  953. section_start: 单项工程章节的起始位置
  954. """
  955. # 表格必须在单项工程章节内
  956. if table_pos < section_start:
  957. return False
  958. table_text = table_html.lower()
  959. # 必须包含的关键词
  960. required_keywords = ["概算金额", "决算金额"]
  961. # 至少包含一个的关键词
  962. optional_keywords = ["费用项目", "建筑安装", "设备购置", "其他费用", "审定金额"]
  963. has_required = all(kw.lower() in table_text for kw in required_keywords)
  964. has_optional = any(kw.lower() in table_text for kw in optional_keywords)
  965. return has_required and has_optional
  966. def _parse_final_account_table_html(table_html: str, project_no: int, project_name: str) -> List[FinalAccountItem]:
  967. """
  968. 解析HTML表格内容
  969. 表格结构:
  970. 费用项目 | 概算金额 | 审定金额(不含税) | 增值税额 | 超节支金额 | 超节支率
  971. Args:
  972. table_html: HTML表格内容
  973. project_no: 项目序号
  974. project_name: 项目名称
  975. Returns:
  976. FinalAccountItem 列表
  977. """
  978. items = []
  979. # 提取所有行
  980. row_pattern = r'<tr[^>]*>(.*?)</tr>'
  981. rows = re.findall(row_pattern, table_html, re.DOTALL | re.IGNORECASE)
  982. if not rows:
  983. return items
  984. # 提取每行的单元格
  985. cell_pattern = r'<td[^>]*>(.*?)</td>'
  986. # 跳过表头行(通常前2-3行是表头)
  987. data_start_idx = 0
  988. for i, row in enumerate(rows):
  989. cells = re.findall(cell_pattern, row, re.DOTALL | re.IGNORECASE)
  990. row_text = " ".join(cells).lower()
  991. # 检测数据开始行(包含"建筑安装"等费用项目名称)
  992. if "建筑安装" in row_text or "设备购置" in row_text or "其他费用" in row_text:
  993. data_start_idx = i
  994. break
  995. # 跳过表头行(包含"1"、"2"、"3"等列序号)
  996. if re.match(r'^[\d\s=\-/]+$', row_text.replace(" ", "")):
  997. continue
  998. # 解析数据行
  999. for row in rows[data_start_idx:]:
  1000. cells = re.findall(cell_pattern, row, re.DOTALL | re.IGNORECASE)
  1001. if len(cells) < 2:
  1002. continue
  1003. # 清理单元格内容
  1004. cells = [_clean_cell_text(cell) for cell in cells]
  1005. # 跳过空行
  1006. if not any(cells):
  1007. continue
  1008. # 获取费用项目名称(第一列)
  1009. fee_name = cells[0] if len(cells) > 0 else ""
  1010. # 跳过合计行
  1011. if any(kw in fee_name for kw in ["合计", "总计", "小计"]):
  1012. continue
  1013. # 只保留主要费用项目
  1014. valid_fee_names = ["建筑安装工程", "建筑安装", "设备购置", "其他费用"]
  1015. is_valid = any(kw in fee_name for kw in valid_fee_names)
  1016. if not is_valid:
  1017. continue
  1018. # 创建记录项
  1019. item = FinalAccountItem()
  1020. item.no = project_no
  1021. item.name = project_name
  1022. item.feeName = fee_name
  1023. # 解析数值列
  1024. # 根据列数确定索引
  1025. if len(cells) >= 6:
  1026. item.estimatedCost = _parse_number_str(cells[1])
  1027. item.approvedFinalAccountExcludingVat = _parse_number_str(cells[2])
  1028. item.vatAmount = _parse_number_str(cells[3])
  1029. item.costVariance = _parse_number_str(cells[4])
  1030. item.varianceRate = _parse_rate_str(cells[5])
  1031. elif len(cells) >= 5:
  1032. item.estimatedCost = _parse_number_str(cells[1])
  1033. item.approvedFinalAccountExcludingVat = _parse_number_str(cells[2])
  1034. item.vatAmount = _parse_number_str(cells[3])
  1035. item.costVariance = _parse_number_str(cells[4])
  1036. item.varianceRate = ""
  1037. items.append(item)
  1038. logger.debug(f"[决算报告] 解析记录: {project_name} - {fee_name} = {item.estimatedCost}")
  1039. return items
  1040. def _clean_cell_text(cell: str) -> str:
  1041. """清理单元格文本,移除HTML标签和多余空格"""
  1042. # 移除HTML标签
  1043. text = re.sub(r'<[^>]+>', '', cell)
  1044. # 移除多余空格
  1045. text = re.sub(r'\s+', ' ', text).strip()
  1046. return text
  1047. def _parse_number_str(value: str) -> str:
  1048. """解析数字字符串,保留原始精度"""
  1049. if not value or not value.strip():
  1050. return "0"
  1051. value = value.strip()
  1052. # 移除千分位逗号
  1053. value = value.replace(',', '')
  1054. # 移除非数字字符(保留负号和小数点)
  1055. cleaned = re.sub(r'[^\d.\-]', '', value)
  1056. if not cleaned or cleaned == '-':
  1057. return "0"
  1058. return cleaned
  1059. def _parse_rate_str(value: str) -> str:
  1060. """解析百分比字符串"""
  1061. if not value or not value.strip():
  1062. return "0%"
  1063. value = value.strip()
  1064. if '%' not in value:
  1065. # 提取数字部分并添加百分号
  1066. num_str = re.sub(r'[^\d.\-]', '', value)
  1067. if num_str and num_str != '-':
  1068. return f"{num_str}%"
  1069. return "0%"
  1070. return value