table_form_filler.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685
  1. """
  2. 表/函填充器(V2 新增)
  3. 负责对投标模板中的表、函、表格进行智能填充。
  4. 核心策略:逻辑先行 → LLM 补充 → 逻辑校验
  5. 流程:
  6. 1. 逻辑层:填标准响应(15+ 常见资格项/实质性条款的标准应答)
  7. 2. LLM 层:补充非常规响应项 + 校验全部填充结果
  8. 3. 逻辑层:替换 %%占位符%% + 残留检查
  9. 迁移自 step4_writing/template_filler.py 的核心逻辑,
  10. 与 step6_exporting/table_filler.py 的 DOCX 操作能力结合。
  11. """
  12. from __future__ import annotations
  13. import logging
  14. import re
  15. from typing import Dict, List, Optional, Tuple
  16. from docx import Document as DocxDocument
  17. from llm_client import LLMClient
  18. from models import (
  19. CompanyInfo,
  20. ExtractedTable,
  21. FormatReconciliation,
  22. ReconciliationDecision,
  23. TenderAnalysis,
  24. )
  25. logger = logging.getLogger(__name__)
  26. # ============================================================
  27. # 标准响应库(15+ 常见资格项/实质性条款)
  28. # ============================================================
  29. # 映射:关键词 → 标准响应文本
  30. STANDARD_RESPONSES: Dict[str, str] = {
  31. # ---- 资格条件 ----
  32. "营业执照": "满足。我公司已提供合法有效的企业营业执照(统一社会信用代码:{unified_code}),详见投标文件对应章节。",
  33. "独立法人": "满足。我公司为依法注册的独立法人,具有独立承担民事责任的能力,已提供营业执照及相关证明材料。",
  34. "财务状况": "满足。我公司已提供经审计的财务报告,财务状况良好,资金充足,具备履行本项目的财务能力,详见投标文件对应章节。",
  35. "财务报告": "满足。我公司已提供{year}年度经审计的财务报告,详见投标文件对应章节。",
  36. "审计报告": "满足。我公司已提供经审计的财务审计报告,详见投标文件对应章节。",
  37. "税收": "满足。我公司依法缴纳税收,已提供税收完税凭证及纳税证明,详见投标文件对应章节。",
  38. "纳税": "满足。我公司依法纳税,已提供完税凭证,详见投标文件对应章节。",
  39. "社保": "满足。我公司依法为员工缴纳社会保障资金,已提供社会保险缴纳凭证,详见投标文件对应章节。",
  40. "社会保障": "满足。我公司依法为全体员工缴纳社会保障资金(含养老、医疗、失业、工伤、生育保险),已提供社保证明材料,详见投标文件对应章节。",
  41. "重大违法": "满足。我公司近三年在经营活动中无重大违法记录,已提供书面声明函,详见投标文件对应章节。",
  42. "违法记录": "满足。我公司近三年在经营活动中无重大违法记录,信誉良好,已提供书面声明。",
  43. "信用": "满足。我公司信用良好,未被列入失信被执行人、重大税收违法案件当事人名单及政府采购严重违法失信行为记录名单,已提供信用查询截图。",
  44. "失信": "满足。我公司未被列入失信被执行人名单,信用记录良好,已提供相关证明材料。",
  45. # ---- 实质性要求 ----
  46. "联合体": "响应。我公司为独立投标,不组成联合体参与本项目。",
  47. "分包": "响应。我公司不将本项目分包或转包,全部服务由我公司独立承担。",
  48. "转包": "响应。我公司承诺不将本项目转包或违法分包。",
  49. "不接受": "完全响应招标文件要求。我公司严格按照招标文件规定执行。",
  50. "不得": "完全响应。我公司承诺严格遵守招标文件中的相关规定。",
  51. # ---- 资质认证 ----
  52. "认证": "满足。我公司已通过ISO9001质量管理体系认证、ISO14001环境管理体系认证、ISO45001职业健康安全管理体系认证,认证证书详见投标文件对应章节。",
  53. "质量管理体系": "满足。我公司已通过ISO9001质量管理体系认证,建立了完善的质量管理体系,详见投标文件对应章节。",
  54. "环境管理体系": "满足。我公司已通过ISO14001环境管理体系认证,详见投标文件对应章节。",
  55. "职业健康安全": "满足。我公司已通过ISO45001职业健康安全管理体系认证,详见投标文件对应章节。",
  56. "物业资质": "满足。我公司持有物业管理企业一级资质证书,具备承接本项目的资质条件,详见投标文件对应章节。",
  57. # ---- 业绩相关 ----
  58. "业绩": "满足。我公司近三年承接了多个类似物业管理服务项目,具有丰富的同类项目管理经验,业绩证明材料详见投标文件对应章节。",
  59. "类似项目": "满足。我公司近三年承接了多个类似项目,积累了丰富的服务经验,详见投标文件对应章节。",
  60. # ---- 人员相关 ----
  61. "项目经理": "满足。我公司拟派项目经理持有物业管理师资格证书,具备丰富的项目管理经验,详见投标文件对应章节。",
  62. "人员配置": "满足。我公司按照招标文件要求配置服务人员,确保人员数量和资质满足项目需求,详见投标文件对应章节。",
  63. # ---- 设备相关 ----
  64. "设备配置": "满足。我公司按照招标文件要求配置服务设备和机具,确保设备满足项目服务需求,详见投标文件对应章节。",
  65. # ---- 其他常见项 ----
  66. "关联企业": "满足。我公司与本项目的其他投标人不存在关联关系,符合招标文件要求。",
  67. "控股关系": "满足。我公司与采购人、采购代理机构及其他投标人之间不存在控股或管理关系。",
  68. "行贿犯罪": "满足。我公司及其法定代表人近三年无行贿犯罪记录。",
  69. }
  70. # 年份占位符(动态填入当年的前一年;每次调用时计算,
  71. # 避免模块导入后跨年运行的进程输出过期年份)
  72. import datetime
  73. def _current_default_year() -> str:
  74. return str(datetime.datetime.now().year - 1)
  75. # ============================================================
  76. # 逻辑层:标准响应生成
  77. # ============================================================
  78. def generate_standard_response(
  79. requirement_text: str,
  80. company_info: CompanyInfo,
  81. ) -> Optional[str]:
  82. """根据要求描述生成标准响应文本
  83. 在 STANDARD_RESPONSES 中按关键词匹配,
  84. 返回格式化的响应文本。
  85. Args:
  86. requirement_text: 资格条件/实质性要求描述文本
  87. company_info: 公司信息(用于填充模板变量)
  88. Returns:
  89. 标准响应文本,如果未匹配到则返回 None
  90. """
  91. if not requirement_text.strip():
  92. return None
  93. # 按优先级顺序匹配关键词(长的先匹配,避免短词误匹配)
  94. sorted_keywords = sorted(
  95. STANDARD_RESPONSES.keys(),
  96. key=lambda k: -len(k) # 长关键词优先
  97. )
  98. for keyword in sorted_keywords:
  99. if keyword in requirement_text:
  100. response = STANDARD_RESPONSES[keyword]
  101. # 替换模板变量
  102. response = response.replace("{unified_code}", company_info.unified_code or "见营业执照")
  103. response = response.replace("{year}", _current_default_year())
  104. return response
  105. return None
  106. def fill_qualification_response_cells(
  107. table_cells: List[List[str]],
  108. company_info: CompanyInfo,
  109. header_row_idx: int = 0,
  110. requirement_col: int = 0,
  111. response_col: int = 1,
  112. ) -> List[List[str]]:
  113. """逻辑填充资格/实质性要求响应表的响应列
  114. 遍历表格数据行,对每行的要求列内容生成标准响应,
  115. 填入响应列。
  116. Args:
  117. table_cells: 表格数据(二维列表,含表头)
  118. company_info: 公司信息
  119. header_row_idx: 表头行索引
  120. requirement_col: 要求列索引
  121. response_col: 响应列索引
  122. Returns:
  123. 填充后的 table_cells(原地修改)
  124. """
  125. filled_count = 0
  126. unfilled_count = 0
  127. for row_idx in range(header_row_idx + 1, len(table_cells)):
  128. row = table_cells[row_idx]
  129. if requirement_col >= len(row):
  130. continue
  131. requirement = row[requirement_col].strip()
  132. if not requirement:
  133. continue
  134. # 确保响应列存在
  135. while len(row) <= response_col:
  136. row.append("")
  137. # 已有内容则跳过
  138. existing = row[response_col].strip()
  139. if existing and len(existing) > 5:
  140. continue
  141. response = generate_standard_response(requirement, company_info)
  142. if response:
  143. row[response_col] = response
  144. filled_count += 1
  145. else:
  146. unfilled_count += 1
  147. if filled_count > 0 or unfilled_count > 0:
  148. logger.info(
  149. f" 逻辑填充: {filled_count} 项标准响应, "
  150. f"{unfilled_count} 项需 LLM 补充"
  151. )
  152. return table_cells
  153. # ============================================================
  154. # LLM 层:非常规项补充 + 全表校验
  155. # ============================================================
  156. # LLM 补充 prompt
  157. FILL_NONSTANDARD_PROMPT = """你是投标书表格填写专家。你的任务是为资格条件/实质性要求响应表中无法通过逻辑自动填充的条目生成专业响应。
  158. ## 要求
  159. 1. 每个响应要具体、专业,明确说明公司如何满足该项要求
  160. 2. 使用正式投标语言,第一人称"我公司"
  161. 3. 明确标注证明材料所在的章节
  162. 4. 响应长度适中(30-100字)
  163. 5. 禁止输出"(内容待补充)""详见附件"等敷衍文本
  164. ## 输出格式
  165. 对于每个未填充的条目,输出:
  166. 序号: 响应文本
  167. 每个条目一行,不输出无关内容。"""
  168. # LLM 校验 prompt
  169. VERIFY_FILLED_TABLE_PROMPT = """你是投标书审核专家。请检查以下投标响应表中的填充结果。
  170. ## 检查项
  171. 1. 是否存在空白的响应格(必须全部有内容)
  172. 2. 是否存在敷衍文本(如"满足""详见附件"但没有详细说明)
  173. 3. 响应内容是否与要求一一对应
  174. 4. 是否存在逻辑矛盾或格式问题
  175. ## 输出格式
  176. ```json
  177. {"issues": [{"row": 行号, "col": 列名, "problem": "问题描述", "suggestion": "修改建议"}], "passed": true|false}
  178. ```"""
  179. def llm_fill_nonstandard_responses(
  180. table_cells: List[List[str]],
  181. unfilled_rows: List[Tuple[int, str]],
  182. company_info: CompanyInfo,
  183. section_name: str = "",
  184. ) -> Dict[int, str]:
  185. """使用 LLM 补充非常规响应的填充
  186. Args:
  187. table_cells: 表格数据(含已逻辑填充的)
  188. unfilled_rows: [(row_idx, requirement_text), ...] 需要补充的行
  189. company_info: 公司信息
  190. section_name: 表格区域名称
  191. Returns:
  192. {row_idx: response_text} 需要填入的响应
  193. """
  194. if not unfilled_rows:
  195. return {}
  196. # 构建 LLM 上下文
  197. context_parts = [
  198. f"表格名称: {section_name}",
  199. f"投标人: {company_info.full_name}",
  200. "",
  201. "以下条目需要生成响应文本:",
  202. ]
  203. for idx, (row_idx, requirement) in enumerate(unfilled_rows):
  204. context_parts.append(f"{idx + 1}. 要求: {requirement}")
  205. # 附加已填充的同行其他列作参考
  206. if row_idx < len(table_cells):
  207. context_parts.append(f" 该行其他列: {' | '.join(table_cells[row_idx][:5])}")
  208. try:
  209. llm = LLMClient()
  210. raw = llm.generate(
  211. system_prompt=FILL_NONSTANDARD_PROMPT,
  212. user_prompt="\n".join(context_parts),
  213. max_tokens=32768,
  214. temperature=0.3,
  215. )
  216. # 解析 LLM 输出:每行格式为 "序号: 响应文本"
  217. result: Dict[int, str] = {}
  218. for line in raw.strip().split("\n"):
  219. line = line.strip()
  220. # 匹配 "1: xxx" 或 "1. xxx"
  221. m = re.match(r"^(\d+)[::.]\s*(.+)", line)
  222. if m:
  223. llm_idx = int(m.group(1)) - 1 # LLM 输出是 1-based
  224. if llm_idx < len(unfilled_rows):
  225. row_idx = unfilled_rows[llm_idx][0]
  226. result[row_idx] = m.group(2).strip()
  227. logger.info(f" LLM 补充: {len(result)}/{len(unfilled_rows)} 项")
  228. return result
  229. except Exception as e:
  230. logger.warning(f"LLM 补充失败: {e}")
  231. return {}
  232. def llm_verify_table_filling(
  233. table_cells: List[List[str]],
  234. section_name: str = "",
  235. ) -> Tuple[bool, list]:
  236. """使用 LLM 校验表格填充质量
  237. Args:
  238. table_cells: 填充后的表格数据
  239. section_name: 表格区域名称
  240. Returns:
  241. (passed, issues): 是否通过,问题列表
  242. """
  243. # 构建校验上下文
  244. if not table_cells:
  245. return True, []
  246. # 将表格转为 Markdown 格式供 LLM 审核
  247. md_lines = []
  248. for row in table_cells[:min(len(table_cells), 20)]: # 最多取前 20 行
  249. md_lines.append("| " + " | ".join(cell[:30] for cell in row) + " |")
  250. table_md = "\n".join(md_lines)
  251. try:
  252. llm = LLMClient()
  253. result = llm.extract_json(
  254. system_prompt=VERIFY_FILLED_TABLE_PROMPT,
  255. user_prompt=f"表格名称: {section_name}\n\n请审核以下表格的填充质量:\n\n{table_md}",
  256. max_tokens=16384,
  257. )
  258. if isinstance(result, dict):
  259. passed = result.get("passed", True)
  260. issues = result.get("issues", [])
  261. if issues:
  262. logger.info(f" LLM 校验: {'通过' if passed else '发现问题'}, "
  263. f"{len(issues)} 个问题")
  264. return passed, issues
  265. except Exception as e:
  266. logger.warning(f"LLM 校验失败: {e}")
  267. return True, []
  268. # ============================================================
  269. # 逻辑层:占位符替换
  270. # ============================================================
  271. def fill_table_placeholders(
  272. table_cells: List[List[str]],
  273. placeholder_map: Dict[str, str],
  274. ) -> int:
  275. """替换表格单元格中的 %%...%% 占位符
  276. Args:
  277. table_cells: 表格数据(原地修改)
  278. placeholder_map: {键名: 值}
  279. Returns:
  280. 替换数量
  281. """
  282. placeholder_re = re.compile(r"%%(.+?)%%")
  283. count = 0
  284. unfilled: List[str] = []
  285. for row in table_cells:
  286. for col_idx, cell in enumerate(row):
  287. for match in placeholder_re.finditer(cell):
  288. key = match.group(1).strip()
  289. value = _resolve_placeholder(key, placeholder_map)
  290. if value:
  291. row[col_idx] = row[col_idx].replace(match.group(0), value)
  292. count += 1
  293. else:
  294. unfilled.append(key)
  295. if unfilled:
  296. unique = list(dict.fromkeys(unfilled))
  297. logger.warning(
  298. f" 未解析占位符 ({len(unique)} 个): "
  299. + ", ".join(f"%%{k}%%" for k in unique[:8])
  300. )
  301. return count
  302. def _resolve_placeholder(key: str, mapping: Dict[str, str]) -> str:
  303. """解析单个占位符(精确匹配 + 模糊匹配)"""
  304. key_clean = key.strip()
  305. # 精确匹配
  306. if key_clean in mapping:
  307. return mapping[key_clean]
  308. # 模糊匹配
  309. for mk, value in mapping.items():
  310. if mk.replace(" ", "") in key_clean or key_clean in mk.replace(" ", ""):
  311. return value
  312. return ""
  313. # ============================================================
  314. # 主入口:协同填充
  315. # ============================================================
  316. def fill_all_tables(
  317. doc: DocxDocument,
  318. reconciliations: List[FormatReconciliation],
  319. analysis: TenderAnalysis,
  320. company_info: CompanyInfo,
  321. placeholder_map: Optional[Dict[str, str]] = None,
  322. use_llm: bool = True,
  323. ) -> int:
  324. """对模板 DOCX 中的所有表格执行协同填充
  325. 根据 FormatReconciliation 的决策,对每个表格执行对应操作:
  326. - REPLACE_WITH_TENDER: 由 docx_builder 处理(此处跳过)
  327. - KEEP_TEMPLATE: 仅替换占位符
  328. - KEEP_TEMPLATE_WITH_TENDER_DATA: 逻辑填充 + LLM 补充 + 占位符
  329. Args:
  330. doc: 已加载的模板 DOCX(原地修改)
  331. reconciliations: 格式比对结果
  332. analysis: 招标分析结果
  333. company_info: 公司信息
  334. placeholder_map: 占位符映射表(如未提供则从 analysis/company_info 构建)
  335. use_llm: 是否使用 LLM
  336. Returns:
  337. 填充的表格数量
  338. """
  339. if placeholder_map is None:
  340. from step4_writing.placeholder_engine import build_placeholder_map
  341. # build_placeholder_map 需要 project_data,我们不方便获取
  342. # 降级:使用公司信息构建基础映射
  343. placeholder_map = _build_basic_placeholder_map(analysis, company_info)
  344. filled_count = 0
  345. for rec in reconciliations:
  346. if rec.decision == ReconciliationDecision.REPLACE_WITH_TENDER:
  347. # 替换操作由 docx_builder 执行
  348. continue
  349. table_idx = rec.template_table_idx
  350. if table_idx < 0 or table_idx >= len(doc.tables):
  351. continue
  352. table = doc.tables[table_idx]
  353. if rec.decision == ReconciliationDecision.KEEP_TEMPLATE:
  354. # 仅替换占位符
  355. count = _fill_table_placeholders_in_docx(table, placeholder_map)
  356. if count > 0:
  357. logger.debug(
  358. f" [{rec.reconciliation_id}] {rec.section_name}: "
  359. f"占位符替换 {count} 处"
  360. )
  361. filled_count += 1
  362. elif rec.decision == ReconciliationDecision.KEEP_TEMPLATE_WITH_TENDER_DATA:
  363. # 协同填充:逻辑 + LLM + 占位符
  364. _synergistic_fill_table(
  365. doc, table, table_idx, rec, analysis, company_info,
  366. placeholder_map, use_llm,
  367. )
  368. filled_count += 1
  369. logger.info(f"表格填充完成: {filled_count} 个表格")
  370. return filled_count
  371. def _synergistic_fill_table(
  372. doc: DocxDocument,
  373. table,
  374. table_idx: int,
  375. rec: FormatReconciliation,
  376. analysis: TenderAnalysis,
  377. company_info: CompanyInfo,
  378. placeholder_map: Dict[str, str],
  379. use_llm: bool,
  380. ):
  381. """协同填充单个表格(逻辑 + LLM + 占位符)
  382. 三步协同:
  383. 1. 逻辑:读取表格数据 → 标准响应填充
  384. 2. LLM:补充非常规项 + 校验
  385. 3. 逻辑:替换占位符
  386. """
  387. # Step 1: 提取当前表格数据(二维文本)
  388. table_cells = _extract_table_text(table)
  389. if not table_cells:
  390. return
  391. header_row_idx = _find_header_row(table_cells)
  392. # 确定响应列(包含"响应""应答""说明""投标人"等关键词的列)
  393. response_col = _find_response_column(table_cells, header_row_idx)
  394. requirement_col = 0 # 要求通常在首列
  395. # Step 2: 逻辑填充标准响应
  396. table_cells = fill_qualification_response_cells(
  397. table_cells, company_info,
  398. header_row_idx=header_row_idx,
  399. requirement_col=requirement_col,
  400. response_col=response_col,
  401. )
  402. # Step 3: LLM 补充非常规项
  403. if use_llm:
  404. unfilled = []
  405. for row_idx in range(header_row_idx + 1, len(table_cells)):
  406. row = table_cells[row_idx]
  407. if response_col < len(row) and not row[response_col].strip():
  408. req = row[requirement_col].strip() if requirement_col < len(row) else ""
  409. if req:
  410. unfilled.append((row_idx, req))
  411. if unfilled:
  412. llm_responses = llm_fill_nonstandard_responses(
  413. table_cells, unfilled, company_info, rec.section_name
  414. )
  415. for row_idx, response in llm_responses.items():
  416. if row_idx < len(table_cells) and response_col < len(table_cells[row_idx]):
  417. table_cells[row_idx][response_col] = response
  418. # LLM 校验
  419. passed, issues = llm_verify_table_filling(table_cells, rec.section_name)
  420. if not passed:
  421. logger.warning(
  422. f" [{rec.reconciliation_id}] LLM 校验发现 "
  423. f"{len(issues)} 个问题"
  424. )
  425. # Step 4: 占位符替换
  426. placeholder_count = fill_table_placeholders(table_cells, placeholder_map)
  427. # Step 5: 写回 DOCX 表格
  428. _write_table_text_back(table, table_cells)
  429. logger.info(
  430. f" [{rec.reconciliation_id}] {rec.section_name[:30]}: "
  431. f"协同填充完成"
  432. + (f" (含 {placeholder_count} 处占位符替换)" if placeholder_count else "")
  433. )
  434. def _extract_table_text(table) -> List[List[str]]:
  435. """从 python-docx 表格提取纯文本矩阵"""
  436. cells = []
  437. for row in table.rows:
  438. row_cells = []
  439. for cell in row.cells:
  440. text = cell.text.strip()
  441. # 清理多余空白
  442. text = re.sub(r"\s+", " ", text)
  443. row_cells.append(text)
  444. cells.append(row_cells)
  445. return cells
  446. def _find_header_row(table_cells: List[List[str]]) -> int:
  447. """查找表头行(第一个所有单元格都有内容或第一行)"""
  448. if not table_cells:
  449. return 0
  450. # 简单策略:第一行就是表头
  451. return 0
  452. def _find_response_column(
  453. table_cells: List[List[str]],
  454. header_row_idx: int,
  455. ) -> int:
  456. """在表头中查找响应列"""
  457. if header_row_idx >= len(table_cells):
  458. return 1 # 默认第 2 列
  459. header = table_cells[header_row_idx]
  460. for col_idx, cell in enumerate(header):
  461. if any(kw in cell for kw in ["响应", "应答", "说明", "投标人", "偏离"]):
  462. return col_idx
  463. # 降级:第二列
  464. return min(1, len(header) - 1) if len(header) > 1 else 0
  465. def _write_table_text_back(table, table_cells: List[List[str]]):
  466. """将填充后的文本矩阵写回 DOCX 表格(保留原始下划线等格式)
  467. 使用 set_cell_text_preserve_format 安全写回:
  468. - 原单元格有下划线格式 → 新文本保留下划线
  469. - 原单元格无下划线 → 新文本不添加下划线
  470. """
  471. from step6_exporting.docx_utils import set_cell_text_preserve_format
  472. for row_idx, row_data in enumerate(table_cells):
  473. if row_idx >= len(table.rows):
  474. break
  475. row = table.rows[row_idx]
  476. for col_idx, text in enumerate(row_data):
  477. if col_idx >= len(row.cells):
  478. break
  479. cell = row.cells[col_idx]
  480. # 只更新有变化的单元格
  481. current_text = cell.text.strip()
  482. if current_text != text and text:
  483. set_cell_text_preserve_format(cell, text)
  484. def _fill_table_placeholders_in_docx(
  485. table,
  486. placeholder_map: Dict[str, str],
  487. ) -> int:
  488. """在 DOCX 表格中替换占位符(原地修改)
  489. 类似 placeholder_engine.apply_placeholders 但仅作用于单个表格。
  490. """
  491. placeholder_re = re.compile(r"%%(.+?)%%")
  492. count = 0
  493. for row in table.rows:
  494. for cell in row.cells:
  495. for para in cell.paragraphs:
  496. for run in para.runs:
  497. for match in placeholder_re.finditer(run.text):
  498. key = match.group(1).strip()
  499. value = _resolve_placeholder(key, placeholder_map)
  500. if value:
  501. if key in ("服务内容", "服务要求", "服务期限"):
  502. value = re.sub(
  503. r"[。;;]+$", "", value.strip()
  504. ) + "。"
  505. run.text = re.sub(
  506. r"。{2,}",
  507. "。",
  508. run.text.replace(match.group(0), value),
  509. )
  510. count += 1
  511. return count
  512. def _build_basic_placeholder_map(
  513. analysis: TenderAnalysis,
  514. company_info: CompanyInfo,
  515. ) -> Dict[str, str]:
  516. """构建基础占位符映射(从 analysis 和 company_info)"""
  517. mapping: Dict[str, str] = {}
  518. # 项目信息
  519. if analysis.project_name:
  520. mapping["项目名称"] = analysis.project_name
  521. if analysis.buyer_name:
  522. mapping["采购人名称"] = analysis.buyer_name
  523. mapping["采购人"] = analysis.buyer_name
  524. # 公司信息
  525. if company_info.full_name:
  526. mapping["公司名称"] = company_info.full_name
  527. mapping["公司全称"] = company_info.full_name
  528. if company_info.address:
  529. mapping["公司地址"] = company_info.address
  530. if company_info.phone:
  531. mapping["公司电话"] = company_info.phone
  532. if company_info.fax:
  533. mapping["公司传真"] = company_info.fax
  534. if company_info.bank_name:
  535. mapping["开户银行"] = company_info.bank_name
  536. if company_info.bank_account:
  537. mapping["银行账号"] = company_info.bank_account
  538. if company_info.legal_rep:
  539. mapping["法定代表人"] = company_info.legal_rep
  540. if company_info.unified_code:
  541. mapping["统一社会信用代码"] = company_info.unified_code
  542. return {k: v for k, v in mapping.items() if v}
  543. __all__ = [
  544. "generate_standard_response",
  545. "fill_qualification_response_cells",
  546. "llm_fill_nonstandard_responses",
  547. "llm_verify_table_filling",
  548. "fill_table_placeholders",
  549. "fill_all_tables",
  550. ]