ocr_validator_utils.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613
  1. """
  2. OCR验证工具的工具函数模块
  3. 包含数据处理、图像处理、统计分析等功能
  4. """
  5. import json
  6. import pandas as pd
  7. import numpy as np
  8. from pathlib import Path
  9. from PIL import Image, ImageDraw
  10. from typing import Dict, List, Optional, Tuple, Union
  11. from io import StringIO, BytesIO
  12. import re
  13. from html import unescape
  14. import yaml
  15. def load_config(config_path: str = "config.yaml") -> Dict:
  16. """加载配置文件"""
  17. try:
  18. with open(config_path, 'r', encoding='utf-8') as f:
  19. return yaml.safe_load(f)
  20. except Exception as e:
  21. # 返回默认配置
  22. return get_default_config()
  23. def get_default_config() -> Dict:
  24. """获取默认配置"""
  25. return {
  26. 'styles': {
  27. 'font_sizes': {'small': 10, 'medium': 12, 'large': 14, 'extra_large': 16},
  28. 'colors': {
  29. 'primary': '#0288d1', 'secondary': '#ff9800', 'success': '#4caf50',
  30. 'error': '#f44336', 'warning': '#ff9800', 'background': '#fafafa', 'text': '#333333'
  31. },
  32. 'layout': {'default_zoom': 1.0, 'default_height': 600, 'sidebar_width': 0.3, 'content_width': 0.7}
  33. },
  34. 'ui': {
  35. 'page_title': 'OCR可视化校验工具', 'page_icon': '🔍', 'layout': 'wide',
  36. 'sidebar_state': 'expanded', 'default_font_size': 'medium', 'default_layout': '标准布局'
  37. },
  38. 'paths': {
  39. 'ocr_out_dir': './sample_data', 'src_img_dir': './sample_data',
  40. 'supported_image_formats': ['.png', '.jpg', '.jpeg']
  41. },
  42. 'ocr': {
  43. 'min_text_length': 2, 'default_confidence': 1.0, 'exclude_texts': ['Picture', ''],
  44. 'tools': {
  45. 'dots_ocr': {
  46. 'name': 'Dots OCR', 'json_structure': 'array',
  47. 'text_field': 'text', 'bbox_field': 'bbox', 'category_field': 'category'
  48. },
  49. 'ppstructv3': {
  50. 'name': 'PPStructV3', 'json_structure': 'object', 'parsing_results_field': 'parsing_res_list',
  51. 'text_field': 'block_content', 'bbox_field': 'block_bbox', 'category_field': 'block_label'
  52. }
  53. },
  54. 'auto_detection': {
  55. 'enabled': True,
  56. 'rules': [
  57. {'field_exists': 'parsing_res_list', 'tool_type': 'ppstructv3'},
  58. {'json_is_array': True, 'tool_type': 'dots_ocr'}
  59. ]
  60. }
  61. }
  62. }
  63. def load_css_styles(css_path: str = "styles.css") -> str:
  64. """加载CSS样式文件"""
  65. try:
  66. with open(css_path, 'r', encoding='utf-8') as f:
  67. return f.read()
  68. except Exception:
  69. # 返回基本样式
  70. return """
  71. .main > div { background-color: white !important; color: #333333 !important; }
  72. .stApp { background-color: white !important; }
  73. .block-container { background-color: white !important; color: #333333 !important; }
  74. """
  75. def rotate_image_and_coordinates(image: Image.Image, angle: float, coordinates_list: List[List[int]]) -> Tuple[Image.Image, List[List[int]]]:
  76. """
  77. 根据角度旋转图像和坐标 - 修复坐标变换和图片显示
  78. Args:
  79. image: 原始图像
  80. angle: 旋转角度(度数)
  81. coordinates_list: 坐标列表,每个坐标为[x1, y1, x2, y2]格式
  82. Returns:
  83. rotated_image: 旋转后的图像
  84. rotated_coordinates: 旋转后的坐标列表
  85. """
  86. if angle == 0:
  87. return image, coordinates_list
  88. # 标准化旋转角度
  89. if angle == 270:
  90. rotation_angle = -90 # 顺时针90度
  91. elif angle == 90:
  92. rotation_angle = 90 # 逆时针90度
  93. elif angle == 180:
  94. rotation_angle = 180 # 180度
  95. else:
  96. rotation_angle = angle
  97. # 旋转图像
  98. rotated_image = image.rotate(rotation_angle, expand=True)
  99. # 获取原始和旋转后的图像尺寸
  100. orig_width, orig_height = image.size
  101. new_width, new_height = rotated_image.size
  102. # 计算旋转后的坐标
  103. rotated_coordinates = []
  104. for coord in coordinates_list:
  105. if len(coord) < 4:
  106. rotated_coordinates.append(coord)
  107. continue
  108. x1, y1, x2, y2 = coord[:4]
  109. # 根据旋转角度变换坐标 - 修复变换逻辑
  110. if rotation_angle == -90: # 顺时针90度 (270度逆时针)
  111. # 变换公式: (x, y) -> (y, orig_width - x)
  112. new_x1 = y1
  113. new_y1 = orig_width - x2
  114. new_x2 = y2
  115. new_y2 = orig_width - x1
  116. elif rotation_angle == 90: # 逆时针90度
  117. # 变换公式: (x, y) -> (orig_height - y, x)
  118. new_x1 = orig_height - y2
  119. new_y1 = x1
  120. new_x2 = orig_height - y1
  121. new_y2 = x2
  122. elif rotation_angle == 180: # 180度
  123. # 变换公式: (x, y) -> (orig_width - x, orig_height - y)
  124. new_x1 = orig_width - x2
  125. new_y1 = orig_height - y2
  126. new_x2 = orig_width - x1
  127. new_y2 = orig_height - y1
  128. else:
  129. # 对于其他角度,使用通用的旋转矩阵
  130. center_x, center_y = orig_width / 2, orig_height / 2
  131. new_center_x, new_center_y = new_width / 2, new_height / 2
  132. angle_rad = np.radians(rotation_angle)
  133. cos_angle = np.cos(angle_rad)
  134. sin_angle = np.sin(angle_rad)
  135. # 旋转四个角点
  136. corners = [
  137. (x1 - center_x, y1 - center_y),
  138. (x2 - center_x, y1 - center_y),
  139. (x2 - center_x, y2 - center_y),
  140. (x1 - center_x, y2 - center_y)
  141. ]
  142. rotated_corners = []
  143. for x, y in corners:
  144. new_x = x * cos_angle - y * sin_angle
  145. new_y = x * sin_angle + y * cos_angle
  146. rotated_corners.append((new_x + new_center_x, new_y + new_center_y))
  147. # 计算边界框
  148. x_coords = [corner[0] for corner in rotated_corners]
  149. y_coords = [corner[1] for corner in rotated_corners]
  150. new_x1 = int(min(x_coords))
  151. new_y1 = int(min(y_coords))
  152. new_x2 = int(max(x_coords))
  153. new_y2 = int(max(y_coords))
  154. # 确保坐标在有效范围内
  155. new_x1 = max(0, min(new_width, new_x1))
  156. new_y1 = max(0, min(new_height, new_y1))
  157. new_x2 = max(0, min(new_width, new_x2))
  158. new_y2 = max(0, min(new_height, new_y2))
  159. # 确保x1 < x2, y1 < y2
  160. if new_x1 > new_x2:
  161. new_x1, new_x2 = new_x2, new_x1
  162. if new_y1 > new_y2:
  163. new_y1, new_y2 = new_y2, new_y1
  164. rotated_coordinates.append([new_x1, new_y1, new_x2, new_y2])
  165. return rotated_image, rotated_coordinates
  166. def detect_ocr_tool_type(data: Union[List, Dict], config: Dict) -> str:
  167. """自动检测OCR工具类型"""
  168. if not config['ocr']['auto_detection']['enabled']:
  169. return 'dots_ocr' # 默认类型
  170. rules = config['ocr']['auto_detection']['rules']
  171. for rule in rules:
  172. if 'field_exists' in rule:
  173. field_name = rule['field_exists']
  174. if isinstance(data, dict) and field_name in data:
  175. return rule['tool_type']
  176. if 'json_is_array' in rule:
  177. if rule['json_is_array'] and isinstance(data, list):
  178. return rule['tool_type']
  179. # 默认返回dots_ocr
  180. return 'dots_ocr'
  181. def parse_dots_ocr_data(data: List, config: Dict) -> List[Dict]:
  182. """解析Dots OCR格式的数据"""
  183. tool_config = config['ocr']['tools']['dots_ocr']
  184. parsed_data = []
  185. for item in data:
  186. if not isinstance(item, dict):
  187. continue
  188. # 提取字段
  189. text = item.get(tool_config['text_field'], '')
  190. bbox = item.get(tool_config['bbox_field'], [])
  191. category = item.get(tool_config['category_field'], 'Text')
  192. confidence = item.get(tool_config.get('confidence_field', 'confidence'),
  193. config['ocr']['default_confidence'])
  194. if text and bbox and len(bbox) >= 4:
  195. parsed_data.append({
  196. 'text': str(text).strip(),
  197. 'bbox': bbox[:4], # 确保只取前4个坐标
  198. 'category': category,
  199. 'confidence': confidence,
  200. 'source_tool': 'dots_ocr'
  201. })
  202. return parsed_data
  203. def parse_ppstructv3_data(data: Dict, config: Dict) -> List[Dict]:
  204. """解析PPStructV3格式的数据"""
  205. tool_config = config['ocr']['tools']['ppstructv3']
  206. parsed_data = []
  207. # 获取解析结果列表
  208. parsing_results_field = tool_config['parsing_results_field']
  209. if parsing_results_field not in data:
  210. return parsed_data
  211. parsing_results = data[parsing_results_field]
  212. if not isinstance(parsing_results, list):
  213. return parsed_data
  214. for item in parsing_results:
  215. if not isinstance(item, dict):
  216. continue
  217. # 提取字段
  218. text = item.get(tool_config['text_field'], '')
  219. bbox = item.get(tool_config['bbox_field'], [])
  220. category = item.get(tool_config['category_field'], 'text')
  221. confidence = item.get(tool_config.get('confidence_field', 'confidence'),
  222. config['ocr']['default_confidence'])
  223. if text and bbox and len(bbox) >= 4:
  224. parsed_data.append({
  225. 'text': str(text).strip(),
  226. 'bbox': bbox[:4], # 确保只取前4个坐标
  227. 'category': category,
  228. 'confidence': confidence,
  229. 'source_tool': 'ppstructv3'
  230. })
  231. # 如果有OCR文本识别结果,也添加进来
  232. if 'overall_ocr_res' in data:
  233. ocr_res = data['overall_ocr_res']
  234. if isinstance(ocr_res, dict) and 'rec_texts' in ocr_res and 'rec_boxes' in ocr_res:
  235. texts = ocr_res['rec_texts']
  236. boxes = ocr_res['rec_boxes']
  237. scores = ocr_res.get('rec_scores', [])
  238. for i, (text, box) in enumerate(zip(texts, boxes)):
  239. if text and len(box) >= 4:
  240. confidence = scores[i] if i < len(scores) else config['ocr']['default_confidence']
  241. parsed_data.append({
  242. 'text': str(text).strip(),
  243. 'bbox': box[:4],
  244. 'category': 'OCR_Text',
  245. 'confidence': confidence,
  246. 'source_tool': 'ppstructv3_ocr'
  247. })
  248. return parsed_data
  249. def normalize_ocr_data(raw_data: Union[List, Dict], config: Dict) -> List[Dict]:
  250. """统一不同OCR工具的数据格式"""
  251. # 自动检测OCR工具类型
  252. tool_type = detect_ocr_tool_type(raw_data, config)
  253. if tool_type == 'dots_ocr':
  254. return parse_dots_ocr_data(raw_data, config)
  255. elif tool_type == 'ppstructv3':
  256. return parse_ppstructv3_data(raw_data, config)
  257. else:
  258. raise ValueError(f"不支持的OCR工具类型: {tool_type}")
  259. def get_rotation_angle_from_ppstructv3(data: Dict) -> float:
  260. """从PPStructV3数据中获取旋转角度"""
  261. if 'doc_preprocessor_res' in data:
  262. doc_res = data['doc_preprocessor_res']
  263. if isinstance(doc_res, dict) and 'angle' in doc_res:
  264. return float(doc_res['angle'])
  265. return 0.0
  266. def load_ocr_data_file(json_path: str, config: Dict) -> Tuple[List, str, str]:
  267. """加载OCR相关数据文件"""
  268. json_file = Path(json_path)
  269. ocr_data = []
  270. md_content = ""
  271. image_path = ""
  272. # 加载JSON数据
  273. try:
  274. with open(json_file, 'r', encoding='utf-8') as f:
  275. raw_data = json.load(f)
  276. # 统一数据格式
  277. ocr_data = normalize_ocr_data(raw_data, config)
  278. # 检查是否需要处理图像旋转
  279. rotation_angle = 0.0
  280. if isinstance(raw_data, dict):
  281. rotation_angle = get_rotation_angle_from_ppstructv3(raw_data)
  282. # 如果有旋转角度,记录下来供后续图像处理使用
  283. if rotation_angle != 0:
  284. for item in ocr_data:
  285. item['rotation_angle'] = rotation_angle
  286. except Exception as e:
  287. raise Exception(f"加载JSON文件失败: {e}")
  288. # 加载MD文件
  289. md_file = json_file.with_suffix('.md')
  290. if md_file.exists():
  291. with open(md_file, 'r', encoding='utf-8') as f:
  292. md_content = f.read()
  293. # 推断图片路径
  294. image_name = json_file.stem
  295. src_img_dir = Path(config['paths']['src_img_dir'])
  296. image_candidates = []
  297. for ext in config['paths']['supported_image_formats']:
  298. image_candidates.extend([
  299. src_img_dir / f"{image_name}{ext}",
  300. json_file.parent / f"{image_name}{ext}",
  301. # 对于PPStructV3,可能图片名包含page信息 # 去掉page后缀的通用匹配
  302. src_img_dir / f"{image_name.split('_page_')[0]}{ext}" if '_page_' in image_name else None,
  303. ])
  304. # 移除None值
  305. image_candidates = [candidate for candidate in image_candidates if candidate is not None]
  306. for candidate in image_candidates:
  307. if candidate.exists():
  308. image_path = str(candidate)
  309. break
  310. return ocr_data, md_content, image_path
  311. def process_ocr_data(ocr_data: List, config: Dict) -> Dict[str, List]:
  312. """处理OCR数据,建立文本到bbox的映射"""
  313. text_bbox_mapping = {}
  314. exclude_texts = config['ocr']['exclude_texts']
  315. min_text_length = config['ocr']['min_text_length']
  316. if not isinstance(ocr_data, list):
  317. return text_bbox_mapping
  318. for i, item in enumerate(ocr_data):
  319. if not isinstance(item, dict):
  320. continue
  321. text = str(item['text']).strip()
  322. if text and text not in exclude_texts and len(text) >= min_text_length:
  323. bbox = item['bbox']
  324. if isinstance(bbox, list) and len(bbox) == 4:
  325. if text not in text_bbox_mapping:
  326. text_bbox_mapping[text] = []
  327. text_bbox_mapping[text].append({
  328. 'bbox': bbox,
  329. 'category': item.get('category', 'Text'),
  330. 'index': i,
  331. 'confidence': item.get('confidence', config['ocr']['default_confidence']),
  332. 'source_tool': item.get('source_tool', 'unknown'),
  333. 'rotation_angle': item.get('rotation_angle', 0.0) # 添加旋转角度信息
  334. })
  335. return text_bbox_mapping
  336. def find_available_ocr_files(ocr_out_dir: str) -> List[str]:
  337. """查找可用的OCR文件"""
  338. available_files = []
  339. # 搜索多个可能的目录
  340. search_dirs = [
  341. Path(ocr_out_dir),
  342. ]
  343. for search_dir in search_dirs:
  344. if search_dir.exists():
  345. # 递归搜索JSON文件
  346. for json_file in search_dir.rglob("*.json"):
  347. available_files.append(str(json_file))
  348. return available_files
  349. def get_ocr_tool_info(ocr_data: List) -> Dict:
  350. """获取OCR工具信息统计"""
  351. tool_counts = {}
  352. for item in ocr_data:
  353. if isinstance(item, dict):
  354. source_tool = item.get('source_tool', 'unknown')
  355. tool_counts[source_tool] = tool_counts.get(source_tool, 0) + 1
  356. return tool_counts
  357. def draw_bbox_on_image(image: Image.Image, bbox: List[int], color: str = "red", width: int = 3) -> Image.Image:
  358. """在图片上绘制bbox框"""
  359. img_copy = image.copy()
  360. draw = ImageDraw.Draw(img_copy)
  361. x1, y1, x2, y2 = bbox
  362. # 绘制矩形框
  363. draw.rectangle([x1, y1, x2, y2], outline=color, width=width)
  364. # 添加半透明填充
  365. overlay = Image.new('RGBA', img_copy.size, (0, 0, 0, 0))
  366. overlay_draw = ImageDraw.Draw(overlay)
  367. color_map = {
  368. "red": (255, 0, 0, 30),
  369. "blue": (0, 0, 255, 30),
  370. "green": (0, 255, 0, 30)
  371. }
  372. fill_color = color_map.get(color, (255, 255, 0, 30))
  373. overlay_draw.rectangle([x1, y1, x2, y2], fill=fill_color)
  374. img_copy = Image.alpha_composite(img_copy.convert('RGBA'), overlay).convert('RGB')
  375. return img_copy
  376. def get_ocr_statistics(ocr_data: List, text_bbox_mapping: Dict, marked_errors: set) -> Dict:
  377. """获取OCR数据统计信息"""
  378. if not isinstance(ocr_data, list) or not ocr_data:
  379. return {
  380. 'total_texts': 0, 'clickable_texts': 0, 'marked_errors': 0,
  381. 'categories': {}, 'accuracy_rate': 0, 'tool_info': {}
  382. }
  383. total_texts = len(ocr_data)
  384. clickable_texts = len(text_bbox_mapping)
  385. marked_errors_count = len(marked_errors)
  386. # 按类别统计
  387. categories = {}
  388. for item in ocr_data:
  389. if isinstance(item, dict):
  390. category = item.get('category', 'Unknown')
  391. categories[category] = categories.get(category, 0) + 1
  392. # OCR工具信息统计
  393. tool_info = get_ocr_tool_info(ocr_data)
  394. accuracy_rate = (clickable_texts - marked_errors_count) / clickable_texts * 100 if clickable_texts > 0 else 0
  395. return {
  396. 'total_texts': total_texts,
  397. 'clickable_texts': clickable_texts,
  398. 'marked_errors': marked_errors_count,
  399. 'categories': categories,
  400. 'accuracy_rate': accuracy_rate,
  401. 'tool_info': tool_info
  402. }
  403. def convert_html_table_to_markdown(content: str) -> str:
  404. """将HTML表格转换为Markdown表格格式"""
  405. def replace_table(match):
  406. table_html = match.group(0)
  407. # 提取所有行
  408. rows = re.findall(r'<tr>(.*?)</tr>', table_html, re.DOTALL | re.IGNORECASE)
  409. if not rows:
  410. return table_html
  411. markdown_rows = []
  412. for i, row in enumerate(rows):
  413. # 提取单元格
  414. cells = re.findall(r'<td[^>]*>(.*?)</td>', row, re.DOTALL | re.IGNORECASE)
  415. if cells:
  416. # 清理单元格内容
  417. clean_cells = []
  418. for cell in cells:
  419. cell_text = re.sub(r'<[^>]+>', '', cell).strip()
  420. cell_text = unescape(cell_text)
  421. clean_cells.append(cell_text)
  422. # 构建Markdown行
  423. markdown_row = '| ' + ' | '.join(clean_cells) + ' |'
  424. markdown_rows.append(markdown_row)
  425. # 在第一行后添加分隔符
  426. if i == 0:
  427. separator = '| ' + ' | '.join(['---'] * len(clean_cells)) + ' |'
  428. markdown_rows.append(separator)
  429. return '\n'.join(markdown_rows) if markdown_rows else table_html
  430. # 替换所有HTML表格
  431. converted = re.sub(r'<table[^>]*>.*?</table>', replace_table, content, flags=re.DOTALL | re.IGNORECASE)
  432. return converted
  433. def parse_html_tables(html_content: str) -> List[pd.DataFrame]:
  434. """解析HTML内容中的表格为DataFrame列表"""
  435. try:
  436. tables = pd.read_html(StringIO(html_content))
  437. return tables if tables else []
  438. except Exception:
  439. return []
  440. def create_dynamic_css(config: Dict, font_size_key: str, height: int) -> str:
  441. """根据配置动态创建CSS样式"""
  442. colors = config['styles']['colors']
  443. font_size = config['styles']['font_sizes'][font_size_key]
  444. return f"""
  445. <style>
  446. .dynamic-content {{
  447. height: {height}px;
  448. font-size: {font_size}px !important;
  449. line-height: 1.4;
  450. background-color: {colors['background']} !important;
  451. color: {colors['text']} !important;
  452. border: 1px solid #ddd;
  453. padding: 10px;
  454. border-radius: 5px;
  455. }}
  456. .highlight-selected {{
  457. background-color: {colors['success']} !important;
  458. color: white !important;
  459. }}
  460. .highlight-error {{
  461. background-color: {colors['error']} !important;
  462. color: white !important;
  463. }}
  464. </style>
  465. """
  466. def export_tables_to_excel(tables: List[pd.DataFrame], filename: str = "ocr_tables.xlsx") -> BytesIO:
  467. """导出表格数据到Excel"""
  468. output = BytesIO()
  469. with pd.ExcelWriter(output, engine='openpyxl') as writer:
  470. for i, table in enumerate(tables):
  471. table.to_excel(writer, sheet_name=f'Table_{i+1}', index=False)
  472. return output
  473. def get_table_statistics(tables: List[pd.DataFrame]) -> List[Dict]:
  474. """获取表格统计信息"""
  475. stats = []
  476. for i, table in enumerate(tables):
  477. numeric_cols = len(table.select_dtypes(include=[np.number]).columns)
  478. stats.append({
  479. 'table_index': i + 1,
  480. 'rows': len(table),
  481. 'columns': len(table.columns),
  482. 'numeric_columns': numeric_cols
  483. })
  484. return stats
  485. def group_texts_by_category(text_bbox_mapping: Dict[str, List]) -> Dict[str, List[str]]:
  486. """按类别对文本进行分组"""
  487. categories = {}
  488. for text, info_list in text_bbox_mapping.items():
  489. category = info_list[0]['category']
  490. if category not in categories:
  491. categories[category] = []
  492. categories[category].append(text)
  493. return categories