module_debug_viz.py 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  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. 'abandon': (128, 128, 128),
  38. }
  39. # 亮蓝(BGR),在白底/浅灰流水上比黄色更易辨认;与 layout 红色框区分
  40. OCR_BOX_COLOR_BGR = (255, 0, 0)
  41. OCR_BOX_LINE_THICKNESS = 2
  42. def _to_bgr(image: Union[np.ndarray, Image.Image]) -> np.ndarray:
  43. if isinstance(image, Image.Image):
  44. arr = np.array(image)
  45. else:
  46. arr = image.copy()
  47. if arr.ndim == 2:
  48. return cv2.cvtColor(arr, cv2.COLOR_GRAY2BGR)
  49. if arr.shape[2] == 3:
  50. return cv2.cvtColor(arr, cv2.COLOR_RGB2BGR)
  51. return arr
  52. def draw_layout_boxes_cv2(
  53. image: Union[np.ndarray, Image.Image],
  54. layout_results: List[Dict[str, Any]],
  55. ) -> np.ndarray:
  56. """在 BGR 图像上绘制 layout 检测框,返回新图像。"""
  57. vis = _to_bgr(image)
  58. for result in layout_results:
  59. bbox = result.get('bbox', [])
  60. if not bbox or len(bbox) < 4:
  61. continue
  62. category = result.get('category', 'unknown')
  63. color = LAYOUT_CATEGORY_COLORS_BGR.get(category, (128, 128, 128))
  64. x1, y1, x2, y2 = int(bbox[0]), int(bbox[1]), int(bbox[2]), int(bbox[3])
  65. cv2.rectangle(vis, (x1, y1), (x2, y2), color, 2)
  66. label = category
  67. confidence = result.get('confidence', result.get('score', 0))
  68. if confidence:
  69. label += f":{float(confidence):.2f}"
  70. font = cv2.FONT_HERSHEY_SIMPLEX
  71. font_scale = 0.4
  72. text_thickness = 1
  73. (text_width, text_height), baseline = cv2.getTextSize(
  74. label, font, font_scale, text_thickness
  75. )
  76. text_y = max(y1 - baseline - 1, text_height + baseline)
  77. cv2.rectangle(
  78. vis,
  79. (x1, text_y - text_height - baseline - 2),
  80. (x1 + text_width, text_y),
  81. color,
  82. -1,
  83. )
  84. cv2.putText(
  85. vis, label, (x1, text_y - baseline - 1),
  86. font, font_scale, (255, 255, 255), text_thickness,
  87. )
  88. return vis
  89. def draw_ocr_spans_cv2(
  90. image: Union[np.ndarray, Image.Image],
  91. spans: List[Dict[str, Any]],
  92. *,
  93. max_label_chars: int = 12,
  94. ) -> np.ndarray:
  95. """在 BGR 图像上绘制 OCR span(poly 或 bbox)。"""
  96. vis = _to_bgr(image)
  97. for span in spans:
  98. poly = span.get('poly')
  99. bbox = span.get('bbox', [])
  100. pts = None
  101. if poly and len(poly) >= 4:
  102. pts = np.array(poly, dtype=np.int32).reshape(-1, 2)
  103. elif bbox and len(bbox) >= 4:
  104. x0, y0, x1, y1 = map(int, bbox[:4])
  105. pts = np.array(
  106. [[x0, y0], [x1, y0], [x1, y1], [x0, y1]], dtype=np.int32
  107. )
  108. if pts is not None:
  109. cv2.polylines(
  110. vis, [pts], True, OCR_BOX_COLOR_BGR, OCR_BOX_LINE_THICKNESS
  111. )
  112. text = str(span.get('text', ''))[:max_label_chars]
  113. if text and pts is not None:
  114. x, y = int(pts[0][0]), int(pts[0][1])
  115. cv2.putText(
  116. vis, text, (x, max(y - 2, 10)),
  117. cv2.FONT_HERSHEY_SIMPLEX, 0.35, OCR_BOX_COLOR_BGR, 1, cv2.LINE_AA,
  118. )
  119. return vis
  120. def save_layout_debug(
  121. image: Union[np.ndarray, Image.Image],
  122. layout_results: List[Dict[str, Any]],
  123. output_dir: Union[str, Path],
  124. page_name: str,
  125. *,
  126. suffix: str = 'raw',
  127. subdir: str = 'layout_detection',
  128. image_format: str = 'jpg',
  129. save_json: bool = True,
  130. ) -> Optional[Dict[str, str]]:
  131. """保存 layout 模块 debug 图与 JSON。"""
  132. if not layout_results or not output_dir:
  133. return None
  134. try:
  135. fmt = (image_format or 'jpg').lstrip('.')
  136. debug_dir = resolve_module_debug_dir(output_dir, subdir)
  137. vis = draw_layout_boxes_cv2(image, layout_results)
  138. img_path = debug_dir / f'{page_name}_layout_{suffix}.{fmt}'
  139. cv2.imwrite(str(img_path), vis)
  140. paths: Dict[str, str] = {'image': str(img_path)}
  141. logger.info(f"Saved layout detection image ({suffix}): {img_path}")
  142. if save_json:
  143. json_data = {
  144. 'page_name': page_name,
  145. 'suffix': suffix,
  146. 'count': len(layout_results),
  147. 'results': [
  148. {
  149. 'category': r.get('category'),
  150. 'bbox': r.get('bbox'),
  151. 'confidence': r.get('confidence', r.get('score', 0.0)),
  152. }
  153. for r in layout_results
  154. ],
  155. }
  156. json_path = debug_dir / f'{page_name}_layout_{suffix}.json'
  157. json_path.write_text(
  158. json.dumps(json_data, ensure_ascii=False, indent=2),
  159. encoding='utf-8',
  160. )
  161. paths['json'] = str(json_path)
  162. logger.info(f"Saved layout detection JSON ({suffix}): {json_path}")
  163. return paths
  164. except Exception as e:
  165. logger.warning(f"Failed to save layout debug ({suffix}): {e}")
  166. return None
  167. def save_ocr_debug(
  168. image: Union[np.ndarray, Image.Image],
  169. spans: List[Dict[str, Any]],
  170. output_dir: Union[str, Path],
  171. page_name: str,
  172. *,
  173. subdir: str = 'ocr_recognition',
  174. image_format: str = 'png',
  175. save_json: bool = True,
  176. ) -> Optional[Dict[str, str]]:
  177. """保存 OCR 模块 debug 图与 JSON。"""
  178. if not output_dir:
  179. return None
  180. try:
  181. fmt = (image_format or 'png').lstrip('.')
  182. debug_dir = resolve_module_debug_dir(output_dir, subdir)
  183. vis = draw_ocr_spans_cv2(image, spans or [])
  184. img_path = debug_dir / f'{page_name}_ocr_spans.{fmt}'
  185. cv2.imwrite(str(img_path), vis)
  186. paths: Dict[str, str] = {'image': str(img_path)}
  187. logger.info(f"Saved OCR debug image: {img_path}")
  188. if save_json:
  189. json_data = {
  190. 'page_name': page_name,
  191. 'count': len(spans or []),
  192. 'spans': [
  193. {
  194. 'bbox': s.get('bbox'),
  195. 'poly': s.get('poly'),
  196. 'text': s.get('text'),
  197. 'confidence': s.get('confidence'),
  198. }
  199. for s in (spans or [])
  200. ],
  201. }
  202. json_path = debug_dir / f'{page_name}_ocr_spans.json'
  203. json_path.write_text(
  204. json.dumps(json_data, ensure_ascii=False, indent=2),
  205. encoding='utf-8',
  206. )
  207. paths['json'] = str(json_path)
  208. logger.info(f"Saved OCR debug JSON: {json_path}")
  209. return paths
  210. except Exception as e:
  211. logger.warning(f"Failed to save OCR debug: {e}")
  212. return None