module_debug_viz.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  1. """
  2. 模块级 Debug 可视化(Layout / OCR)
  3. 用于 ``{output_dir}/debug/{subdir}/`` 下基于 inference_image 的调试图;
  4. 用户审计图由 VisualizationUtils + original_image 负责,不在此模块。
  5. """
  6. from __future__ import annotations
  7. import json
  8. from pathlib import Path
  9. from typing import Any, Dict, List, Optional, Union
  10. import cv2
  11. import numpy as np
  12. from loguru import logger
  13. from PIL import Image
  14. # 各模块 debug_options 默认落盘根目录(相对 pipeline output_dir)
  15. MODULE_DEBUG_ROOT = "debug"
  16. def resolve_module_debug_dir(
  17. output_dir: Union[str, Path],
  18. subdir: str,
  19. *,
  20. debug_root: str = MODULE_DEBUG_ROOT,
  21. ) -> Path:
  22. """``{output_dir}/{debug_root}/{subdir}/``,目录不存在则创建。"""
  23. debug_dir = Path(output_dir) / debug_root / subdir
  24. debug_dir.mkdir(parents=True, exist_ok=True)
  25. return debug_dir
  26. LAYOUT_CATEGORY_COLORS_BGR = {
  27. 'table_body': (0, 0, 255),
  28. 'table_caption': (0, 0, 200),
  29. 'table_footnote': (0, 0, 150),
  30. 'text': (255, 0, 0),
  31. 'title': (0, 255, 255),
  32. 'header': (255, 0, 255),
  33. 'footer': (0, 165, 255),
  34. 'image_body': (0, 255, 0),
  35. 'image_caption': (0, 200, 0),
  36. 'image_footnote': (0, 150, 0),
  37. 'chart': (255, 255, 0), # 青色(BGR 下 B=255,G=255,R=0)
  38. # 注意:OpenCV 为 BGR,(0,255,255) 在屏幕上呈黄色(与 title 相同),勿用于 seal
  39. 'seal': (0, 140, 255), # 亮橙,与红 table / 黄 title / 蓝 text 均易区分
  40. 'abandon': (128, 128, 128),
  41. }
  42. # seal 常与 table 重叠:加粗线宽 + 黑色外描边
  43. LAYOUT_HIGHLIGHT_CATEGORIES = frozenset({'seal'})
  44. LAYOUT_HIGHLIGHT_LINE_THICKNESS = 4
  45. LAYOUT_HIGHLIGHT_OUTLINE_BGR = (0, 0, 0)
  46. LAYOUT_DEFAULT_LINE_THICKNESS = 2
  47. # 亮蓝(BGR),在白底/浅灰流水上比黄色更易辨认;与 layout 红色框区分
  48. OCR_BOX_COLOR_BGR = (255, 0, 0)
  49. OCR_BOX_LINE_THICKNESS = 2
  50. OCR_BOX_DASH_LENGTH = 8
  51. OCR_BOX_DASH_GAP = 6
  52. def _to_bgr(image: Union[np.ndarray, Image.Image]) -> np.ndarray:
  53. if isinstance(image, Image.Image):
  54. arr = np.array(image)
  55. else:
  56. arr = image.copy()
  57. if arr.ndim == 2:
  58. return cv2.cvtColor(arr, cv2.COLOR_GRAY2BGR)
  59. if arr.shape[2] == 3:
  60. return cv2.cvtColor(arr, cv2.COLOR_RGB2BGR)
  61. return arr
  62. def draw_layout_boxes_cv2(
  63. image: Union[np.ndarray, Image.Image],
  64. layout_results: List[Dict[str, Any]],
  65. ) -> np.ndarray:
  66. """在 BGR 图像上绘制 layout 检测框,返回新图像。"""
  67. vis = _to_bgr(image)
  68. for result in layout_results:
  69. bbox = result.get('bbox', [])
  70. if not bbox or len(bbox) < 4:
  71. continue
  72. category = result.get('category', 'unknown')
  73. color = LAYOUT_CATEGORY_COLORS_BGR.get(category, (128, 128, 128))
  74. thickness = (
  75. LAYOUT_HIGHLIGHT_LINE_THICKNESS
  76. if category in LAYOUT_HIGHLIGHT_CATEGORIES
  77. else LAYOUT_DEFAULT_LINE_THICKNESS
  78. )
  79. x1, y1, x2, y2 = int(bbox[0]), int(bbox[1]), int(bbox[2]), int(bbox[3])
  80. if category in LAYOUT_HIGHLIGHT_CATEGORIES:
  81. cv2.rectangle(
  82. vis, (x1, y1), (x2, y2),
  83. LAYOUT_HIGHLIGHT_OUTLINE_BGR,
  84. thickness + 2,
  85. )
  86. cv2.rectangle(vis, (x1, y1), (x2, y2), color, thickness)
  87. label = category
  88. confidence = result.get('confidence', result.get('score', 0))
  89. if confidence:
  90. label += f":{float(confidence):.2f}"
  91. font = cv2.FONT_HERSHEY_SIMPLEX
  92. font_scale = 0.5 if category in LAYOUT_HIGHLIGHT_CATEGORIES else 0.4
  93. text_thickness = 1
  94. (text_width, text_height), baseline = cv2.getTextSize(
  95. label, font, font_scale, text_thickness
  96. )
  97. text_y = max(y1 - baseline - 1, text_height + baseline)
  98. cv2.rectangle(
  99. vis,
  100. (x1, text_y - text_height - baseline - 2),
  101. (x1 + text_width, text_y),
  102. color,
  103. -1,
  104. )
  105. cv2.putText(
  106. vis, label, (x1, text_y - baseline - 1),
  107. font, font_scale, (255, 255, 255), text_thickness,
  108. )
  109. return vis
  110. def _draw_dashed_segment(
  111. vis: np.ndarray,
  112. p1: np.ndarray,
  113. p2: np.ndarray,
  114. color: tuple,
  115. thickness: int,
  116. *,
  117. dash_length: int = OCR_BOX_DASH_LENGTH,
  118. gap_length: int = OCR_BOX_DASH_GAP,
  119. ) -> None:
  120. """在 p1→p2 上绘制虚线段。"""
  121. start = p1.astype(np.float64)
  122. end = p2.astype(np.float64)
  123. vec = end - start
  124. length = float(np.linalg.norm(vec))
  125. if length < 1e-6:
  126. return
  127. direction = vec / length
  128. pos = 0.0
  129. draw = True
  130. while pos < length:
  131. seg = float(dash_length if draw else gap_length)
  132. seg_end = min(pos + seg, length)
  133. if draw:
  134. s = (start + direction * pos).astype(np.int32)
  135. e = (start + direction * seg_end).astype(np.int32)
  136. cv2.line(
  137. vis,
  138. (int(s[0]), int(s[1])),
  139. (int(e[0]), int(e[1])),
  140. color,
  141. thickness,
  142. cv2.LINE_AA,
  143. )
  144. pos = seg_end
  145. draw = not draw
  146. def _draw_span_outline(
  147. vis: np.ndarray,
  148. pts: np.ndarray,
  149. color: tuple,
  150. thickness: int,
  151. *,
  152. dashed: bool,
  153. ) -> None:
  154. n = len(pts)
  155. if n < 2:
  156. return
  157. for i in range(n):
  158. p1 = pts[i]
  159. p2 = pts[(i + 1) % n]
  160. if dashed:
  161. _draw_dashed_segment(vis, p1, p2, color, thickness)
  162. else:
  163. cv2.line(
  164. vis,
  165. (int(p1[0]), int(p1[1])),
  166. (int(p2[0]), int(p2[1])),
  167. color,
  168. thickness,
  169. cv2.LINE_AA,
  170. )
  171. def draw_ocr_spans_cv2(
  172. image: Union[np.ndarray, Image.Image],
  173. spans: List[Dict[str, Any]],
  174. *,
  175. max_label_chars: int = 12,
  176. ) -> np.ndarray:
  177. """在 BGR 图像上绘制 OCR span(poly 或 bbox);无文字用虚线框。"""
  178. vis = _to_bgr(image)
  179. for span in spans:
  180. poly = span.get('poly')
  181. bbox = span.get('bbox', [])
  182. pts = None
  183. if poly and len(poly) >= 4:
  184. pts = np.array(poly, dtype=np.int32).reshape(-1, 2)
  185. elif bbox and len(bbox) >= 4:
  186. x0, y0, x1, y1 = map(int, bbox[:4])
  187. pts = np.array(
  188. [[x0, y0], [x1, y0], [x1, y1], [x0, y1]], dtype=np.int32
  189. )
  190. if pts is not None:
  191. text_raw = str(span.get('text', '') or '').strip()
  192. _draw_span_outline(
  193. vis,
  194. pts,
  195. OCR_BOX_COLOR_BGR,
  196. OCR_BOX_LINE_THICKNESS,
  197. dashed=not text_raw,
  198. )
  199. text = str(span.get('text', '')).strip()[:max_label_chars]
  200. if text and pts is not None:
  201. x, y = int(pts[0][0]), int(pts[0][1])
  202. cv2.putText(
  203. vis, text, (x, max(y - 2, 10)),
  204. cv2.FONT_HERSHEY_SIMPLEX, 0.35, OCR_BOX_COLOR_BGR, 1, cv2.LINE_AA,
  205. )
  206. return vis
  207. def save_layout_debug(
  208. image: Union[np.ndarray, Image.Image],
  209. layout_results: List[Dict[str, Any]],
  210. output_dir: Union[str, Path],
  211. page_name: str,
  212. *,
  213. suffix: str = 'raw',
  214. subdir: str = 'layout_detection',
  215. image_format: str = 'jpg',
  216. save_json: bool = True,
  217. ) -> Optional[Dict[str, str]]:
  218. """保存 layout 模块 debug 图与 JSON。"""
  219. if not layout_results or not output_dir:
  220. return None
  221. try:
  222. fmt = (image_format or 'jpg').lstrip('.')
  223. debug_dir = resolve_module_debug_dir(output_dir, subdir)
  224. vis = draw_layout_boxes_cv2(image, layout_results)
  225. img_path = debug_dir / f'{page_name}_layout_{suffix}.{fmt}'
  226. cv2.imwrite(str(img_path), vis)
  227. paths: Dict[str, str] = {'image': str(img_path)}
  228. logger.info(f"Saved layout detection image ({suffix}): {img_path}")
  229. if save_json:
  230. json_data = {
  231. 'page_name': page_name,
  232. 'suffix': suffix,
  233. 'count': len(layout_results),
  234. 'results': [
  235. {
  236. 'category': r.get('category'),
  237. 'bbox': r.get('bbox'),
  238. 'confidence': r.get('confidence', r.get('score', 0.0)),
  239. }
  240. for r in layout_results
  241. ],
  242. }
  243. json_path = debug_dir / f'{page_name}_layout_{suffix}.json'
  244. json_path.write_text(
  245. json.dumps(json_data, ensure_ascii=False, indent=2),
  246. encoding='utf-8',
  247. )
  248. paths['json'] = str(json_path)
  249. logger.info(f"Saved layout detection JSON ({suffix}): {json_path}")
  250. return paths
  251. except Exception as e:
  252. logger.warning(f"Failed to save layout debug ({suffix}): {e}")
  253. return None
  254. def save_ocr_debug(
  255. image: Union[np.ndarray, Image.Image],
  256. spans: List[Dict[str, Any]],
  257. output_dir: Union[str, Path],
  258. page_name: str,
  259. *,
  260. subdir: str = 'ocr_recognition',
  261. image_format: str = 'png',
  262. save_json: bool = True,
  263. ) -> Optional[Dict[str, str]]:
  264. """保存 OCR 模块 debug 图与 JSON。"""
  265. if not output_dir:
  266. return None
  267. try:
  268. fmt = (image_format or 'png').lstrip('.')
  269. debug_dir = resolve_module_debug_dir(output_dir, subdir)
  270. vis = draw_ocr_spans_cv2(image, spans or [])
  271. img_path = debug_dir / f'{page_name}_ocr_spans.{fmt}'
  272. cv2.imwrite(str(img_path), vis)
  273. paths: Dict[str, str] = {'image': str(img_path)}
  274. logger.info(f"Saved OCR debug image: {img_path}")
  275. if save_json:
  276. json_data = {
  277. 'page_name': page_name,
  278. 'count': len(spans or []),
  279. 'spans': [
  280. {
  281. 'bbox': s.get('bbox'),
  282. 'poly': s.get('poly'),
  283. 'text': s.get('text'),
  284. 'confidence': s.get('confidence'),
  285. }
  286. for s in (spans or [])
  287. ],
  288. }
  289. json_path = debug_dir / f'{page_name}_ocr_spans.json'
  290. json_path.write_text(
  291. json.dumps(json_data, ensure_ascii=False, indent=2),
  292. encoding='utf-8',
  293. )
  294. paths['json'] = str(json_path)
  295. logger.info(f"Saved OCR debug JSON: {json_path}")
  296. return paths
  297. except Exception as e:
  298. logger.warning(f"Failed to save OCR debug: {e}")
  299. return None