module_debug_viz.py 7.1 KB

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