normalize_financial_numbers.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  1. import re
  2. import os
  3. from pathlib import Path
  4. from decimal import Decimal, InvalidOperation
  5. def _normalize_amount_token(token: str) -> str:
  6. """
  7. 规范单个金额 token 中逗号/小数点的用法。
  8. 仅在形态明显为金额时进行纠错,其他情况原样返回。
  9. """
  10. if not token:
  11. return token
  12. # 只处理包含数字的简单 token,避免带字母/其他符号的误改
  13. if not re.fullmatch(r"[+-]?\d[\d,\.]*\d", token):
  14. return token
  15. sign = ""
  16. core = token
  17. if core[0] in "+-":
  18. sign, core = core[0], core[1:]
  19. has_dot = "." in core
  20. has_comma = "," in core
  21. # 辅助: 尝试解析为 Decimal;失败则认为不安全,回退原值
  22. def _safe_decimal(s: str) -> bool:
  23. try:
  24. Decimal(s.replace(",", ""))
  25. return True
  26. except (InvalidOperation, ValueError):
  27. return False
  28. # 规则A:同时包含 . 和 ,,最后一个分隔符是逗号,且其后为 1-2 位数字
  29. if has_dot and has_comma:
  30. last_comma = core.rfind(",")
  31. last_dot = core.rfind(".")
  32. if last_comma > last_dot and last_comma != -1:
  33. frac = core[last_comma + 1 :]
  34. if 1 <= len(frac) <= 2 and frac.isdigit():
  35. # 先把所有点当作千分位逗号,再把最后一个逗号当作小数点
  36. temp = core.replace(".", ",")
  37. idx = temp.rfind(",")
  38. if idx != -1:
  39. candidate = temp[:idx] + "." + temp[idx + 1 :]
  40. if _safe_decimal(candidate):
  41. return sign + candidate
  42. # 规则B:只有 .,多个点,最后一段视为小数,其余为千分位
  43. if has_dot and not has_comma:
  44. parts = core.split(".")
  45. if len(parts) >= 3:
  46. last = parts[-1]
  47. ints = parts[:-1]
  48. if 1 <= len(last) <= 2 and all(len(p) == 3 for p in ints[1:]):
  49. candidate = ",".join(ints) + "." + last
  50. if _safe_decimal(candidate):
  51. return sign + candidate
  52. # 规则C:只有 ,,多个逗号,最后一段长度为 1-2 且前面为 3 位分组
  53. if has_comma and not has_dot:
  54. parts = core.split(",")
  55. if len(parts) >= 3:
  56. last = parts[-1]
  57. ints = parts[:-1]
  58. if 1 <= len(last) <= 2 and all(len(p) == 3 for p in ints[1:]):
  59. # 将最后一个逗号视为小数点
  60. idx = core.rfind(",")
  61. candidate = core[:idx] + "." + core[idx + 1 :]
  62. if _safe_decimal(candidate):
  63. return sign + candidate
  64. # 没有需要纠错的典型形态,直接返回原 token
  65. return token
  66. def normalize_financial_numbers(text: str) -> str:
  67. """
  68. 标准化财务数字:将全角字符转换为半角字符,并纠正常见的逗号/小数点错用。
  69. """
  70. if not text:
  71. return text
  72. # 定义全角到半角的映射
  73. fullwidth_to_halfwidth = {
  74. '0': '0', '1': '1', '2': '2', '3': '3', '4': '4',
  75. '5': '5', '6': '6', '7': '7', '8': '8', '9': '9',
  76. ',': ',', # 全角逗号转半角逗号
  77. '。': '.', # 全角句号转半角句号
  78. '.': '.', # 全角句点转半角句点
  79. ':': ':', # 全角冒号转半角冒号
  80. ';': ';', # 全角分号转半角分号
  81. '(': '(', # 全角左括号转半角左括号
  82. ')': ')', # 全角右括号转半角右括号
  83. '-': '-', # 全角减号转半角减号
  84. '+': '+', # 全角加号转半角加号
  85. '%': '%', # 全角百分号转半角百分号
  86. }
  87. # 第一步:执行基础字符替换(全角 -> 半角)
  88. normalized_text = text
  89. for fullwidth, halfwidth in fullwidth_to_halfwidth.items():
  90. normalized_text = normalized_text.replace(fullwidth, halfwidth)
  91. # 第二步:处理数字序列中的空格和分隔符(保留原有逻辑)
  92. number_sequence_pattern = r'(\d+(?:\s*[,,]\s*\d+)*(?:\s*[。..]\s*\d+)?)'
  93. def normalize_number_sequence(match):
  94. sequence = match.group(1)
  95. sequence = re.sub(r'(\d)\s*[,,]\s*(\d)', r'\1,\2', sequence)
  96. sequence = re.sub(r'(\d)\s*[。..]\s*(\d)', r'\1.\2', sequence)
  97. return sequence
  98. normalized_text = re.sub(number_sequence_pattern, normalize_number_sequence, normalized_text)
  99. # 第三步:对疑似金额 token 做逗号/小数点纠错
  100. amount_pattern = r'(?P<tok>[+-]?\d[\d,\.]*\d)'
  101. def _amount_sub(m: re.Match) -> str:
  102. tok = m.group('tok')
  103. return _normalize_amount_token(tok)
  104. normalized_text = re.sub(amount_pattern, _amount_sub, normalized_text)
  105. return normalized_text
  106. def normalize_markdown_table(markdown_content: str) -> str:
  107. """
  108. 专门处理Markdown表格中的数字标准化
  109. 注意:保留原始markdown中的换行符,只替换表格内的文本内容
  110. Args:
  111. markdown_content: Markdown内容
  112. Returns:
  113. 标准化后的Markdown内容
  114. """
  115. # 使用BeautifulSoup处理HTML表格
  116. from bs4 import BeautifulSoup, Tag
  117. import re
  118. # 使用正则表达式找到所有表格的位置,并保留其前后的内容
  119. # 匹配完整的HTML表格标签(包括嵌套)
  120. table_pattern = r'(<table[^>]*>.*?</table>)'
  121. def normalize_table_match(match):
  122. """处理单个表格匹配,保留原始格式,并追加数字标准化说明注释。"""
  123. table_html = match.group(1)
  124. original_table_html = table_html # 保存原始HTML用于比较
  125. # 解析表格HTML
  126. soup = BeautifulSoup(table_html, 'html.parser')
  127. tables = soup.find_all('table')
  128. # 记录本表格中所有数值修改
  129. changes: list[dict] = []
  130. for table in tables:
  131. if not isinstance(table, Tag):
  132. continue
  133. # 通过 tr / td(th) 计算行列位置
  134. for row_idx, tr in enumerate(table.find_all('tr')): # type: ignore[reportAttributeAccessIssue]
  135. cells = tr.find_all(['td', 'th']) # type: ignore[reportAttributeAccessIssue]
  136. for col_idx, cell in enumerate(cells):
  137. if not isinstance(cell, Tag):
  138. continue
  139. # 获取单元格纯文本
  140. original_text = cell.get_text()
  141. normalized_text = normalize_financial_numbers(original_text)
  142. if original_text == normalized_text:
  143. continue
  144. # 记录一条修改
  145. changes.append(
  146. {
  147. "row": row_idx,
  148. "col": col_idx,
  149. "old": original_text,
  150. "new": normalized_text,
  151. }
  152. )
  153. # 具体替换:保持原有逻辑,按文本节点逐个替换以保留空白
  154. from bs4.element import NavigableString
  155. for text_node in cell.find_all(string=True, recursive=True):
  156. if isinstance(text_node, NavigableString):
  157. text_str = str(text_node)
  158. if not text_str.strip():
  159. continue
  160. normalized = normalize_financial_numbers(text_str.strip())
  161. if normalized != text_str.strip():
  162. if text_str.strip() == text_str:
  163. text_node.replace_with(normalized)
  164. else:
  165. leading_ws = text_str[: len(text_str) - len(text_str.lstrip())]
  166. trailing_ws = text_str[len(text_str.rstrip()) :]
  167. text_node.replace_with(leading_ws + normalized + trailing_ws)
  168. # 如果没有任何数值修改,直接返回原始 HTML
  169. if not changes:
  170. return original_table_html
  171. # 获取修改后的HTML
  172. modified_html = str(soup)
  173. # 在表格后追加注释,说明哪些单元格被修改
  174. lines = ["<!-- 数字标准化说明:"]
  175. for ch in changes:
  176. lines.append(
  177. f" - [row={ch['row']},col={ch['col']}] {ch['old']} -> {ch['new']}"
  178. )
  179. lines.append("-->")
  180. comment = "\n".join(lines)
  181. return modified_html + "\n\n" + comment
  182. # 使用正则替换,只替换表格内容,保留其他部分(包括换行符)不变
  183. normalized_content = re.sub(table_pattern, normalize_table_match, markdown_content, flags=re.DOTALL)
  184. return normalized_content
  185. def normalize_json_table(json_content: str) -> str:
  186. """
  187. 专门处理JSON格式OCR结果中表格的数字标准化
  188. Args:
  189. json_content: JSON格式的OCR结果内容
  190. Returns:
  191. 标准化后的JSON内容
  192. """
  193. """
  194. json_content 示例:
  195. [
  196. {
  197. "category": "Table",
  198. "text": "<table>...</table>"
  199. },
  200. {
  201. "category": "Text",
  202. "text": "Some other text"
  203. }
  204. ]
  205. """
  206. import json
  207. from ast import literal_eval
  208. try:
  209. # 解析JSON内容
  210. data = json.loads(json_content) if isinstance(json_content, str) else json_content
  211. # 确保data是列表格式
  212. if not isinstance(data, list):
  213. return json_content
  214. # 遍历所有OCR结果项
  215. for item in data:
  216. if not isinstance(item, dict):
  217. continue
  218. # 检查是否是表格类型
  219. if item.get('category') == 'Table' and 'text' in item:
  220. table_html = item['text']
  221. # 使用BeautifulSoup处理HTML表格
  222. from bs4 import BeautifulSoup, Tag
  223. soup = BeautifulSoup(table_html, 'html.parser')
  224. tables = soup.find_all('table')
  225. table_changes: list[dict] = []
  226. for table in tables:
  227. if not isinstance(table, Tag):
  228. continue
  229. # 通过 tr / td(th) 计算行列位置
  230. for row_idx, tr in enumerate(table.find_all('tr')): # type: ignore[reportAttributeAccessIssue]
  231. cells = tr.find_all(['td', 'th']) # type: ignore[reportAttributeAccessIssue]
  232. for col_idx, cell in enumerate(cells):
  233. if not isinstance(cell, Tag):
  234. continue
  235. original_text = cell.get_text()
  236. normalized_text = normalize_financial_numbers(original_text)
  237. if original_text == normalized_text:
  238. continue
  239. # 记录本单元格的变更
  240. change: dict[str, object] = {
  241. "row": row_idx,
  242. "col": col_idx,
  243. "old": original_text,
  244. "new": normalized_text,
  245. }
  246. bbox_attr = cell.get("data-bbox")
  247. if isinstance(bbox_attr, str):
  248. try:
  249. change["bbox"] = literal_eval(bbox_attr)
  250. except Exception:
  251. change["bbox"] = bbox_attr
  252. table_changes.append(change)
  253. # 更新单元格内容(简单覆盖文本即可)
  254. cell.string = normalized_text
  255. # 更新 item 中的表格内容
  256. item['text'] = str(soup)
  257. if table_changes:
  258. item['number_normalization_changes'] = table_changes
  259. # 同时标准化普通文本中的数字(如果需要)
  260. # elif 'text' in item:
  261. # original_text = item['text']
  262. # normalized_text = normalize_financial_numbers(original_text)
  263. # if original_text != normalized_text:
  264. # item['text'] = normalized_text
  265. # 返回标准化后的JSON字符串
  266. return json.dumps(data, ensure_ascii=False, indent=2)
  267. except json.JSONDecodeError as e:
  268. print(f"⚠️ JSON解析失败: {e}")
  269. return json_content
  270. except Exception as e:
  271. print(f"⚠️ JSON表格标准化失败: {e}")
  272. return json_content
  273. def normalize_json_file(file_path: str, output_path: str | None = None) -> str:
  274. """
  275. 标准化JSON文件中的表格数字
  276. Args:
  277. file_path: 输入JSON文件路径
  278. output_path: 输出文件路径,如果为None则覆盖原文件
  279. Returns:
  280. 标准化后的JSON内容
  281. """
  282. input_file = Path(file_path)
  283. output_file = Path(output_path) if output_path else input_file
  284. if not input_file.exists():
  285. raise FileNotFoundError(f"找不到文件: {file_path}")
  286. # 读取原始JSON文件
  287. with open(input_file, 'r', encoding='utf-8') as f:
  288. original_content = f.read()
  289. print(f"🔧 正在标准化JSON文件: {input_file.name}")
  290. # 标准化内容
  291. normalized_content = normalize_json_table(original_content)
  292. # 保存标准化后的文件
  293. with open(output_file, 'w', encoding='utf-8') as f:
  294. f.write(normalized_content)
  295. # 统计变化
  296. changes = sum(1 for o, n in zip(original_content, normalized_content) if o != n)
  297. if changes > 0:
  298. print(f"✅ 标准化了 {changes} 个字符")
  299. # 如果输出路径不同,也保存原始版本
  300. if output_path and output_path != file_path:
  301. original_backup = Path(output_path).parent / f"{Path(output_path).stem}_original.json"
  302. with open(original_backup, 'w', encoding='utf-8') as f:
  303. f.write(original_content)
  304. print(f"📄 原始版本已保存到: {original_backup}")
  305. else:
  306. print("ℹ️ 无需标准化(已是标准格式)")
  307. print(f"📄 标准化结果已保存到: {output_file}")
  308. return normalized_content
  309. if __name__ == "__main__":
  310. """
  311. 简单验证:构造一份“故意打乱逗号/小数点”的 JSON / Markdown 示例,
  312. 并打印标准化前后的差异。
  313. """
  314. import json
  315. print("=== JSON 示例:金额格式纠错 + 变更记录 ===")
  316. demo_json_data = [
  317. {
  318. "category": "Table",
  319. "text": (
  320. "<table><tbody>"
  321. "<tr><td data-bbox=\"[0,0,10,10]\">项目</td>"
  322. "<td data-bbox=\"[10,0,20,10]\">2023 年12 月31 日</td></tr>"
  323. # 故意打乱的数字:应为 12,123,456.00 和 1,234,567.89
  324. "<tr><td data-bbox=\"[0,10,10,20]\">测试金额A</td>"
  325. "<td data-bbox=\"[10,10,20,20]\">12.123,456,00</td></tr>"
  326. "<tr><td data-bbox=\"[0,20,10,30]\">测试金额B</td>"
  327. "<td data-bbox=\"[10,20,20,30]\">1,234,567,89</td></tr>"
  328. "</tbody></table>"
  329. ),
  330. }
  331. ]
  332. demo_json_str = json.dumps(demo_json_data, ensure_ascii=False, indent=2)
  333. print("原始 JSON:")
  334. print(demo_json_str)
  335. normalized_json_str = normalize_json_table(demo_json_str)
  336. print("\n标准化后 JSON:")
  337. print(normalized_json_str)
  338. print("\n=== Markdown 示例:金额格式纠错 + 注释说明 ===")
  339. demo_md = """<table><tbody>
  340. <tr><td>项目</td><td>2023 年12 月31 日</td></tr>
  341. <tr><td>测试金额A</td><td>12.123,456,00</td></tr>
  342. <tr><td>测试金额B</td><td>1,234,567,89</td></tr>
  343. </tbody></table>
  344. """
  345. print("原始 Markdown:")
  346. print(demo_md)
  347. normalized_md = normalize_markdown_table(demo_md)
  348. print("\n标准化后 Markdown:")
  349. print(normalized_md)