test_annotation_repair.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. """Annotation Repair Test - validation/repair of annotated text vs original article.
  2. Coverage:
  3. 1. Already valid (no repair needed)
  4. 2. raw_text wrongly filled with value (typical LLM error) -> rebuild
  5. 3. raw_text spelling deviation -> rebuild via difflib alignment
  6. 4. Body contains escape chars (|, }, \\) -> escape rules preserved
  7. 5. No text segment (all annotation) -> difflib can still repair
  8. 6. Insufficient body field count -> auto-fill and replace
  9. 7. Annotation at tail (no following text anchor)
  10. 8. Annotation at head (no preceding text anchor)
  11. 9. Quote hallucination: full-width "" <-> half-width "" in outer text
  12. 10. Punctuation hallucination: Chinese 。 <-> English . in outer text
  13. 11. Missing char in outer text (typical LLM omission)
  14. 12. Mixed errors: outer text + raw_text both deviate
  15. Usage:
  16. python test_annotation_repair.py
  17. """
  18. from __future__ import annotations
  19. import sys
  20. from pathlib import Path
  21. # Normalize Windows console to UTF-8 to avoid Chinese garbled output
  22. if sys.platform == "win32":
  23. try:
  24. sys.stdout.reconfigure(encoding="utf-8") # type: ignore[attr-defined]
  25. sys.stderr.reconfigure(encoding="utf-8") # type: ignore[attr-defined]
  26. except Exception:
  27. pass
  28. # Make `src` importable regardless of CWD
  29. sys.path.insert(0, str(Path(__file__).parent))
  30. from src.annotation_repair import ( # noqa: E402
  31. parse_annotated_segments,
  32. repair_annotation,
  33. validate_annotation,
  34. )
  35. def _ok(label: str, repaired: str | None = None) -> None:
  36. """打印 [OK] 标记;若提供了 repaired 则附带修复后文本。"""
  37. print(f"[OK] {label}")
  38. if repaired is not None:
  39. print(f" 修复后: {repaired}")
  40. # --- Scene 1: already valid --------------------------------------------------
  41. def test_already_valid():
  42. article = "2026年6月1日晚8点,刘阳作为总策划。"
  43. annotated = (
  44. "{{PDJH.JBXX.PDKSSJ||2026-06-01T20:00:00.000||2026年6月1日晚8点||"
  45. "日期范围||ISO→中文}},{{PDJH.RYXX.ZCH.XM||刘阳||刘阳||2~4字||不作转换}}"
  46. "作为总策划。"
  47. )
  48. is_valid, _ = validate_annotation(article, annotated)
  49. assert is_valid, "fully-matched annotation should pass validation"
  50. repaired, logs = repair_annotation(article, annotated)
  51. assert repaired == annotated, "matched annotation must not be modified"
  52. assert logs == [], "no logs when already valid"
  53. _ok("scene1: already valid")
  54. # --- Scene 2: raw_text wrongly filled with value (typical LLM error) ---------
  55. def test_raw_text_wrong_as_value():
  56. article = "2026年6月1日晚8点,刘阳作为总策划。"
  57. bad_annotated = (
  58. "{{PDJH.JBXX.PDKSSJ||2026-06-01T20:00:00.000||2026-06-01T20:00:00.000||"
  59. "日期范围||ISO→中文}},{{PDJH.RYXX.ZCH.XM||刘阳||刘阳||2~4字||不作转换}}"
  60. "作为总策划。"
  61. )
  62. is_valid, _ = validate_annotation(article, bad_annotated)
  63. assert not is_valid, "wrongly-filled annotation should fail validation"
  64. repaired, logs = repair_annotation(article, bad_annotated)
  65. is_valid_after, _ = validate_annotation(article, repaired)
  66. assert is_valid_after, f"should pass after repair, logs: {logs}"
  67. segs = parse_annotated_segments(repaired)
  68. ann = next(s for s in segs if s["type"] == "annotation")
  69. assert ann["raw_text"] == "2026年6月1日晚8点", (
  70. f"raw_text should be rebuilt from article, got: {ann['raw_text']!r}"
  71. )
  72. _ok("scene2: raw_text wrongly filled with value repaired", repaired)
  73. # --- Scene 3: multiple annotations with spelling deviation -------------------
  74. def test_raw_text_partial_deviation():
  75. article = "活动预算为3000元,已支付2000元。"
  76. bad_annotated = (
  77. "活动预算为{{PDJH.JBXX.PDZYS||3000.0||三千||数值||不做转换}}元,"
  78. "已支付{{PDJH.JBXX.YZF||2000.0||两千||数值||不做转换}}元。"
  79. )
  80. repaired, logs = repair_annotation(article, bad_annotated)
  81. is_valid, _ = validate_annotation(article, repaired)
  82. assert is_valid, f"should pass after repair, logs: {logs}"
  83. segs = parse_annotated_segments(repaired)
  84. anns = [s for s in segs if s["type"] == "annotation"]
  85. assert anns[0]["raw_text"] == "3000", f"first raw_text expected '3000', got: {anns[0]['raw_text']!r}"
  86. assert anns[1]["raw_text"] == "2000", f"second raw_text expected '2000', got: {anns[1]['raw_text']!r}"
  87. _ok("scene3: multiple annotations with deviation repaired", repaired)
  88. # --- Scene 4: body contains escape chars -------------------------------------
  89. def test_body_with_escape_chars():
  90. # Original article contains "|", must be escaped as "\|" in body
  91. article = "a|b|c 结束"
  92. # Python literal "\\|" represents the actual 2-char sequence "\|"
  93. annotated = "{{P||v||a\\|b\\|c||约束||规则1\\|规则2}} 结束"
  94. is_valid, _ = validate_annotation(article, annotated)
  95. assert is_valid, "annotated text with escape chars should match article"
  96. repaired, logs = repair_annotation(article, annotated)
  97. assert logs == [], "no repair should be triggered when already valid"
  98. assert repaired == annotated
  99. _ok("scene4: escape chars preserved")
  100. # --- Scene 5: no text segment (difflib can still repair) --------------------
  101. def test_no_text_segment_can_repair():
  102. """新算法用 difflib 对齐,无需 text segment 作为锚点也能修复."""
  103. article = "刘阳"
  104. bad_annotated = "{{P||刘阳||李四||约束||规则}}" # raw_text wrongly set to "李四"
  105. is_valid, _ = validate_annotation(article, bad_annotated)
  106. assert not is_valid
  107. repaired, logs = repair_annotation(article, bad_annotated)
  108. is_valid_after, _ = validate_annotation(article, repaired)
  109. assert is_valid_after, (
  110. f"difflib 应能修复纯标注文本,logs: {logs}"
  111. )
  112. segs = parse_annotated_segments(repaired)
  113. ann = next(s for s in segs if s["type"] == "annotation")
  114. assert ann["raw_text"] == "刘阳", (
  115. f"raw_text 应被重建为 '刘阳',实际:{ann['raw_text']!r}"
  116. )
  117. _ok("scene5: no text segment - repaired by difflib alignment", repaired)
  118. # --- Scene 6: insufficient body field count ----------------------------------
  119. def test_body_field_count_insufficient():
  120. article = "张三参加"
  121. # Truncated body: only path||value
  122. bad_annotated = "{{P||张三}}参加"
  123. is_valid, _ = validate_annotation(article, bad_annotated)
  124. assert not is_valid, "truncated body should fail validation"
  125. repaired, logs = repair_annotation(article, bad_annotated)
  126. is_valid_after, _ = validate_annotation(article, repaired)
  127. assert is_valid_after, f"should auto-fill and repair, logs: {logs}"
  128. _ok("scene6: insufficient body field count repaired", repaired)
  129. # --- Scene 7: annotation at tail (no following text anchor) ------------------
  130. def test_annotation_at_tail():
  131. article = "活动结束于2026年6月1日"
  132. bad_annotated = "活动结束于{{PDJH.JBXX.JSSJ||2026-06-01||结束时间||约束||规则}}"
  133. is_valid, _ = validate_annotation(article, bad_annotated)
  134. assert not is_valid
  135. repaired, logs = repair_annotation(article, bad_annotated)
  136. is_valid_after, _ = validate_annotation(article, repaired)
  137. assert is_valid_after, f"tail annotation should repair, logs: {logs}"
  138. segs = parse_annotated_segments(repaired)
  139. ann = next(s for s in segs if s["type"] == "annotation")
  140. assert ann["raw_text"] == "2026年6月1日", (
  141. f"tail raw_text expected '2026年6月1日', got: {ann['raw_text']!r}"
  142. )
  143. _ok("scene7: tail annotation repaired", repaired)
  144. # --- Scene 8: annotation at head (no preceding text anchor) ------------------
  145. def test_annotation_at_head():
  146. article = "2026年6月1日活动开始"
  147. bad_annotated = "{{PDJH.JBXX.KSSJ||2026-06-01||错误||约束||规则}}活动开始"
  148. repaired, logs = repair_annotation(article, bad_annotated)
  149. is_valid, _ = validate_annotation(article, repaired)
  150. assert is_valid, f"head annotation should repair, logs: {logs}"
  151. _ok("scene8: head annotation repaired", repaired)
  152. # --- Scene 9: quote hallucination in outer text (user's real case) -----------
  153. def test_quote_hallucination_in_outer_text():
  154. """LLM 把中文双引号 \u201c\u201d 改成英文双引号 "(或反向).
  155. 这是用户实际遇到的失败案例:text segment 在原文中找不到,
  156. 旧版 text-anchored 算法会直接报错放弃。difflib 应能修复。
  157. """
  158. article = '指挥员仍然感觉意犹未尽:\u201c每次训练,都是一次全新挑战!\u201d'
  159. # 把中文双引号 \u201c\u201d 改为英文双引号 "(LLM 典型幻觉)
  160. bad_annotated = '指挥员仍然感觉意犹未尽:"每次训练,都是一次全新挑战!"'
  161. assert article != bad_annotated, "测试前置:两段文本确实不同"
  162. repaired, logs = repair_annotation(article, bad_annotated)
  163. is_valid, _ = validate_annotation(article, repaired)
  164. assert is_valid, f"引号幻觉应被修复,logs: {logs}"
  165. assert repaired == article, "修复后 text segment 应与原文一致"
  166. _ok("scene9: quote hallucination in outer text repaired", repaired)
  167. # --- Scene 10: punctuation hallucination in outer text -----------------------
  168. def test_punctuation_hallucination_in_outer_text():
  169. """LLM 把中文句号 '。' 改成英文句点 '.',或类似标点偏差."""
  170. article = "训练结束。队伍带回。"
  171. bad_annotated = "训练结束.队伍带回."
  172. assert article != bad_annotated
  173. repaired, logs = repair_annotation(article, bad_annotated)
  174. is_valid, _ = validate_annotation(article, repaired)
  175. assert is_valid, f"标点幻觉应被修复,logs: {logs}"
  176. assert repaired == article
  177. _ok("scene10: punctuation hallucination in outer text repaired", repaired)
  178. # --- Scene 11: missing char in outer text (LLM omission) --------------------
  179. def test_missing_char_in_outer_text():
  180. """LLM 漏字:text segment 比原文少一个字."""
  181. article = "本次训练取得了圆满成功,全体官兵表现优秀。"
  182. # 漏掉 "全体" 中的 "体" 字
  183. bad_annotated = "本次训练取得了圆满成功,全官兵表现优秀。"
  184. assert article != bad_annotated
  185. repaired, logs = repair_annotation(article, bad_annotated)
  186. is_valid, _ = validate_annotation(article, repaired)
  187. assert is_valid, f"漏字应被修复,logs: {logs}"
  188. assert repaired == article
  189. _ok("scene11: missing char in outer text repaired", repaired)
  190. # --- Scene 12: mixed errors (outer text + raw_text both deviate) -------------
  191. def test_mixed_outer_and_inner_errors():
  192. """同时存在两种幻觉:{{}} 外引号偏差 + {{}} 内 raw_text 写成 value."""
  193. article = "2026年6月1日\u2014\u2014指挥员刘阳宣布:\u201c训练开始!\u201d"
  194. bad_annotated = (
  195. "{{PDJH.JBXX.RQ||2026-06-01||2026-06-01||日期||ISO}}\u2014\u2014" # raw_text 错填为 value
  196. "指挥员刘阳宣布:\u201c训练开始!\u201d" # 中文引号被改成英文引号
  197. )
  198. repaired, logs = repair_annotation(article, bad_annotated)
  199. is_valid, _ = validate_annotation(article, repaired)
  200. assert is_valid, f"混合错误应被修复,logs: {logs}"
  201. # 校验:raw_text 应被重建为 '2026年6月1日'
  202. segs = parse_annotated_segments(repaired)
  203. ann = next(s for s in segs if s["type"] == "annotation")
  204. assert ann["raw_text"] == "2026年6月1日", (
  205. f"raw_text 应被重建为 '2026年6月1日',实际:{ann['raw_text']!r}"
  206. )
  207. _ok("scene12: mixed outer text + raw_text errors repaired", repaired)
  208. def main():
  209. tests = [
  210. test_already_valid,
  211. test_raw_text_wrong_as_value,
  212. test_raw_text_partial_deviation,
  213. test_body_with_escape_chars,
  214. test_no_text_segment_can_repair,
  215. test_body_field_count_insufficient,
  216. test_annotation_at_tail,
  217. test_annotation_at_head,
  218. test_quote_hallucination_in_outer_text,
  219. test_punctuation_hallucination_in_outer_text,
  220. test_missing_char_in_outer_text,
  221. test_mixed_outer_and_inner_errors,
  222. ]
  223. failed = 0
  224. for test in tests:
  225. try:
  226. test()
  227. except AssertionError as e:
  228. failed += 1
  229. print(f"[FAIL] {test.__name__}: {e}")
  230. except Exception as e: # noqa: BLE001
  231. failed += 1
  232. print(f"[ERROR] {test.__name__}: {type(e).__name__}: {e}")
  233. print()
  234. total = len(tests)
  235. print(f"result: {total - failed}/{total} passed")
  236. sys.exit(0 if failed == 0 else 1)
  237. if __name__ == "__main__":
  238. main()