image.vision\ocr\document_understanding_enhanced.mbt

90.3% · 167 / 185 points · 578 lines

Background color reports the state of each line. Underlined characters mark exact instrumented byte offsets; hover them to inspect the visit count.

  1. 1///|
  2. 2/// # 文档理解 ocr/document_understanding_enhanced
  3. 3///
  4. 4/// 图像处理库子模块
  5. 5/// 图像处理库子模块 Image processing library submodule
  6. 6// 文档理解增强版(v10.2.0)
  7. 7// 增强版面分析、阅读顺序优化、标题检测、段落检测、多栏处理、文档结构树
  8. 8
  9. 9///|
  10. 10/// 文档块类型(增强版)
  11. 11/// `#non_exhaustive` 表示未来可能添加新构造器
  12. 12#derive(Eq, @debug.Debug)
  13. 13#non_exhaustive
  14. 14pub(all) enum DocumentBlockType {
  15. 15 Title
  16. 16 Heading1
  17. 17 Heading2
  18. 18 Heading3
  19. 19 Paragraph
  20. 20 ListItem
  21. 21 Table
  22. 22 Image
  23. 23 Caption
  24. 24 Header
  25. 25 Footer
  26. 26 PageNumber
  27. 27 Unknown
  28. 28}
  29. 29
  30. 30///|
  31. 31pub extend DocumentBlockType with @debug.Debug::{to_repr}
  32. 32
  33. 33///|
  34. 34pub extend DocumentBlockType with Eq::{not_equal, equal}
  35. 35
  36. 36///|
  37. 37/// 文档块结构体(增强版)
  38. 38#derive(Eq, @debug.Debug)
  39. 39pub(all) struct DocumentBlock {
  40. 40 block_type : DocumentBlockType
  41. 41 x : Int32
  42. 42 y : Int32
  43. 43 width : Int32
  44. 44 height : Int32
  45. 45 text : String
  46. 46 confidence : Double
  47. 47 font_size : Int32
  48. 48 is_bold : Bool
  49. 49 is_italic : Bool
  50. 50 line_spacing : Double
  51. 51 indent_level : Int32
  52. 52 column_index : Int32
  53. 53 mut reading_order : Int32
  54. 54 parent_id : Int32
  55. 55 children_ids : Array[Int32]
  56. 56}
  57. 57
  58. 58///|
  59. 59pub extend DocumentBlock with Eq::{not_equal, equal}
  60. 60
  61. 61///|
  62. 62pub extend DocumentBlock with @debug.Debug::{to_repr}
  63. 63
  64. 64///|
  65. 65/// 文档结构树节点
  66. 66#derive(Eq, @debug.Debug)
  67. 67pub(all) struct DocumentTreeNode {
  68. 68 node_id : Int32
  69. 69 block : DocumentBlock
  70. 70 children : Array[DocumentTreeNode]
  71. 71 depth : Int32
  72. 72}
  73. 73
  74. 74///|
  75. 75pub extend DocumentTreeNode with Eq::{not_equal, equal}
  76. 76
  77. 77///|
  78. 78pub extend DocumentTreeNode with @debug.Debug::{to_repr}
  79. 79
  80. 80///|
  81. 81/// 增强文档理解配置
  82. 82#derive(Eq, @debug.Debug)
  83. 83pub(all) struct DocumentUnderstandingEnhancedConfig {
  84. 84 min_block_width : Int32
  85. 85 min_block_height : Int32
  86. 86 title_font_size_threshold : Int32
  87. 87 heading_font_size_threshold : Int32
  88. 88 max_line_spacing_ratio : Double
  89. 89 enable_column_detection : Bool
  90. 90 enable_hierarchy : Bool
  91. 91 enable_title_detection : Bool
  92. 92}
  93. 93
  94. 94///|
  95. 95pub extend DocumentUnderstandingEnhancedConfig with Eq::{not_equal, equal}
  96. 96
  97. 97///|
  98. 98pub extend DocumentUnderstandingEnhancedConfig with @debug.Debug::{to_repr}
  99. 99
  100. 100///|
  101. 101/// 创建默认增强文档理解配置
  102. 102pub fn document_understanding_enhanced_default_config() -> DocumentUnderstandingEnhancedConfig {
  103. 103● DocumentUnderstandingEnhancedConfig::{
  104. 104 min_block_width: 20,
  105. 105 min_block_height: 10,
  106. 106 title_font_size_threshold: 24,
  107. 107 heading_font_size_threshold: 18,
  108. 108 max_line_spacing_ratio: 2.0,
  109. 109 enable_column_detection: true,
  110. 110 enable_hierarchy: true,
  111. 111 enable_title_detection: true,
  112. 112 }
  113. 113}
  114. 114
  115. 115///|
  116. 116/// 增强版面分析(基于连通域的文本块检测)
  117. 117pub fn analyze_layout_enhanced(
  118. 118 img : @types.Image,
  119. 119 config? : DocumentUnderstandingEnhancedConfig,
  120. 120) -> Array[DocumentBlock] raise @types.LoadError {
  121. 121 // 输入验证
  122. 122● if img.width <= 0 || img.height <= 0 {
  123. 123● raise @types.LoadError::DecodeFailed(
  124. 124 "analyze_layout_enhanced: 图像尺寸必须大于0",
  125. 125 )
  126. 126 }
  127. 127 if img.channels < 1 || img.channels > 4 {
  128. 128● raise @types.LoadError::DecodeFailed(
  129. 129 "analyze_layout_enhanced: 通道数必须在1-4之间",
  130. 130 )
  131. 131 }
  132. 132 let expected_size = img.width * img.height * img.channels
  133. 133● if img.data.length() != expected_size {
  134. 134● raise @types.LoadError::DecodeFailed(
  135. 135 "analyze_layout_enhanced: 数据大小不匹配,期望 " +
  136. 136● expected_size.to_string() +
  137. 137 ",实际 " +
  138. 138● img.data.length().to_string(),
  139. 139 )
  140. 140 }
  141. 141● let cfg = match config {
  142. 142● Some(c) => c
  143. 143● None => document_understanding_enhanced_default_config()
  144. 144 }
  145. 145 // 1. 预处理
  146. 146● let preprocessed = ocr_preprocess(img)
  147. 147 // 2. 检测文本行
  148. 148● let lines = detect_text_lines_projection(preprocessed)
  149. 149 // 3. 检测文本区域(连通域合并)
  150. 150● let _ = detect_text_regions(preprocessed)
  151. 151 // 4. 多栏检测
  152. 152 let num_columns = if cfg.enable_column_detection {
  153. 153● let (cols, _) = detect_columns(preprocessed)
  154. 154 cols
  155. 155 } else {
  156. 156● 1
  157. 157 }
  158. 158 // 5. 构建文档块
  159. 159 let blocks : Array[DocumentBlock] = []
  160. 160 let mut order = 0
  161. 161 for line in lines {
  162. 162 // 估计字体大小(基于行高)
  163. 163● let font_size = line.height
  164. 164 // 判断块类型
  165. 165● let block_type = classify_block_type_enhanced(line, font_size, cfg, order)
  166. 166 // 判断是否加粗(基于笔画密度)
  167. 167● let is_bold = estimate_bold(preprocessed, line)
  168. 168 // 计算行间距
  169. 169○ let line_spacing = if order > 0 && order < blocks.length() {
  170. 170○ let prev = blocks[order - 1]
  171. 171○ (line.y_start - (prev.y + prev.height)).to_double() /
  172. 172○ font_size.to_double()
  173. 173 } else {
  174. 174● 1.0
  175. 175 }
  176. 176 // 计算缩进级别
  177. 177 let indent_level = if line.x_start > img.width / 10 {
  178. 178○ ((line.x_start - img.width / 20) / (img.width / 20)).max(0).min(3)
  179. 179 } else {
  180. 180● 0
  181. 181 }
  182. 182 // 计算列索引
  183. 183 let column_index = if num_columns > 1 {
  184. 184● let col_width = img.width / num_columns
  185. 185● (line.x_start / col_width).min(num_columns - 1)
  186. 186 } else {
  187. 187● 0
  188. 188 }
  189. 189● blocks.push(DocumentBlock::{
  190. 190 block_type,
  191. 191 x: line.x_start,
  192. 192 y: line.y_start,
  193. 193 width: line.width,
  194. 194 height: line.height,
  195. 195 text: "",
  196. 196 confidence: 0.8,
  197. 197 font_size,
  198. 198 is_bold,
  199. 199 is_italic: false,
  200. 200 line_spacing,
  201. 201 indent_level,
  202. 202 column_index,
  203. 203 reading_order: order,
  204. 204 parent_id: -1,
  205. 205 children_ids: [],
  206. 206 })
  207. 207 order += 1
  208. 208 }
  209. 209 blocks
  210. 210}
  211. 211
  212. 212///|
  213. 213/// 分类块类型(增强版)
  214. 214fn classify_block_type_enhanced(
  215. 215 line : TextLineInfo,
  216. 216 font_size : Int32,
  217. 217 cfg : DocumentUnderstandingEnhancedConfig,
  218. 218 order : Int32,
  219. 219) -> DocumentBlockType {
  220. 220 // 标题检测(第一行且字体大)
  221. 221● if cfg.enable_title_detection &&
  222. 222 order == 0 &&
  223. 223 font_size >= cfg.title_font_size_threshold {
  224. 224● return DocumentBlockType::Title
  225. 225 }
  226. 226 // 标题检测(字体大且加粗)
  227. 227 if font_size >= cfg.heading_font_size_threshold {
  228. 228● if font_size >= cfg.title_font_size_threshold {
  229. 229● return DocumentBlockType::Heading1
  230. 230● } else if font_size >= cfg.heading_font_size_threshold + 2 {
  231. 231● return DocumentBlockType::Heading2
  232. 232 } else {
  233. 233○ return DocumentBlockType::Heading3
  234. 234 }
  235. 235 }
  236. 236 // 列表项检测(缩进且短)
  237. 237 if line.width < 200 && line.x_start > 30 {
  238. 238○ return DocumentBlockType::ListItem
  239. 239 }
  240. 240 // 普通段落
  241. 241 DocumentBlockType::Paragraph
  242. 242}
  243. 243
  244. 244///|
  245. 245/// 估计是否加粗(基于笔画密度)
  246. 246fn estimate_bold(img : @types.Image, line : TextLineInfo) -> Bool {
  247. 247● let w = img.width
  248. 248 let h = img.height
  249. 249 let data = img.data
  250. 250 let mut ink_pixels = 0
  251. 251 let mut total = 0
  252. 252◐ let y_start = if line.y_start > 0 { line.y_start } else { 0 }
  253. 253 let y_end = if line.y_start + line.height < h {
  254. 254○ line.y_start + line.height
  255. 255 } else {
  256. 256● h
  257. 257 }
  258. 258◐ let x_start = if line.x_start > 0 { line.x_start } else { 0 }
  259. 259 let x_end = if line.x_start + line.width < w {
  260. 260○ line.x_start + line.width
  261. 261 } else {
  262. 262● w
  263. 263 }
  264. 264 for y in y_start..<y_end {
  265. 265● for x in x_start..<x_end {
  266. 266● total += 1
  267. 267● if data[y * w + x].to_int() > 128 {
  268. 268● ink_pixels += 1
  269. 269 }
  270. 270 }
  271. 271 }
  272. 272 let density = if total > 0 {
  273. 273● ink_pixels.to_double() / total.to_double()
  274. 274 } else {
  275. 275○ 0.0
  276. 276 }
  277. 277 // 加粗字符通常密度更高
  278. 278 density > 0.35
  279. 279}
  280. 280
  281. 281///|
  282. 282/// 优化阅读顺序(基于列和几何关系)
  283. 283pub fn optimize_reading_order(
  284. 284 blocks : Array[DocumentBlock],
  285. 285 num_columns : Int32,
  286. 286) -> Array[Int32] {
  287. 287 // 按列分组,然后每列内按 y 排序,再按 x 排序
  288. 288● let indices : Array[Int32] = []
  289. 289 for col in 0..<num_columns {
  290. 290● let col_indices : Array[Int32] = []
  291. 291● for i in 0..<blocks.length() {
  292. 292● if blocks[i].column_index == col {
  293. 293● col_indices.push(i)
  294. 294 }
  295. 295 }
  296. 296 // 列内按 y 排序,再按 x 排序(冒泡排序)
  297. 297● for _ in 0..<col_indices.length() {
  298. 298● for j in 0..<(col_indices.length() - 1) {
  299. 299● let b1 = blocks[col_indices[j]]
  300. 300 let b2 = blocks[col_indices[j + 1]]
  301. 301 let should_swap = if b1.y > b2.y {
  302. 302● true
  303. 303● } else if b1.y == b2.y && b1.x > b2.x {
  304. 304○ true
  305. 305 } else {
  306. 306● false
  307. 307 }
  308. 308 if should_swap {
  309. 309● let temp = col_indices[j]
  310. 310 col_indices[j] = col_indices[j + 1]
  311. 311 col_indices[j + 1] = temp
  312. 312 }
  313. 313 }
  314. 314 }
  315. 315 for idx in col_indices {
  316. 316● indices.push(idx)
  317. 317 }
  318. 318 }
  319. 319 // 如果没有检测到列,按全局 y/x 排序
  320. 320● if indices.length() == 0 {
  321. 321● for i in 0..<blocks.length() {
  322. 322● indices.push(i)
  323. 323 }
  324. 324● for _ in 0..<indices.length() {
  325. 325● for j in 0..<(indices.length() - 1) {
  326. 326● let b1 = blocks[indices[j]]
  327. 327 let b2 = blocks[indices[j + 1]]
  328. 328 let should_swap = if b1.y > b2.y {
  329. 329● true
  330. 330● } else if b1.y == b2.y && b1.x > b2.x {
  331. 331○ true
  332. 332 } else {
  333. 333● false
  334. 334 }
  335. 335 if should_swap {
  336. 336● let temp = indices[j]
  337. 337 indices[j] = indices[j + 1]
  338. 338 indices[j + 1] = temp
  339. 339 }
  340. 340 }
  341. 341 }
  342. 342 }
  343. 343 indices
  344. 344}
  345. 345
  346. 346///|
  347. 347/// 段落检测(基于行间距和缩进)
  348. 348pub fn detect_paragraphs(
  349. 349 blocks : Array[DocumentBlock],
  350. 350 max_line_spacing_ratio~ : Double = 2.0,
  351. 351) -> Array[Array[Int32]] {
  352. 352● let paragraphs : Array[Array[Int32]] = []
  353. 353 let current_paragraph : Array[Int32] = []
  354. 354● for i in 0..<blocks.length() {
  355. 355● let block = blocks[i]
  356. 356 // 只处理段落类型的块
  357. 357 if block.block_type != DocumentBlockType::Paragraph &&
  358. 358 block.block_type != DocumentBlockType::ListItem {
  359. 359● if current_paragraph.length() > 0 {
  360. 360● paragraphs.push(current_paragraph)
  361. 361● current_paragraph.clear()
  362. 362 }
  363. 363 continue
  364. 364 }
  365. 365 // 检查是否是新段落的开始
  366. 366 let is_new_paragraph = if i > 0 {
  367. 367● let prev = blocks[i - 1]
  368. 368 // 行间距过大
  369. 369 let spacing_too_large = block.line_spacing > max_line_spacing_ratio
  370. 370 // 缩进变化
  371. 371 let indent_changed = block.indent_level != prev.indent_level
  372. 372 // 前一个块不是段落
  373. 373 let prev_not_paragraph = prev.block_type != DocumentBlockType::Paragraph &&
  374. 374 prev.block_type != DocumentBlockType::ListItem
  375. 375 spacing_too_large || indent_changed || prev_not_paragraph
  376. 376 } else {
  377. 377● true
  378. 378 }
  379. 379● if is_new_paragraph && current_paragraph.length() > 0 {
  380. 380● paragraphs.push(current_paragraph)
  381. 381● current_paragraph.clear()
  382. 382 }
  383. 383● current_paragraph.push(i)
  384. 384 }
  385. 385● if current_paragraph.length() > 0 {
  386. 386● paragraphs.push(current_paragraph)
  387. 387 }
  388. 388 paragraphs
  389. 389}
  390. 390
  391. 391///|
  392. 392/// 标题检测(基于字体大小、位置、加粗特征)
  393. 393pub fn detect_titles(
  394. 394 blocks : Array[DocumentBlock],
  395. 395 title_font_size_threshold~ : Int32 = 24,
  396. 396) -> Array[Int32] {
  397. 397● let title_indices : Array[Int32] = []
  398. 398● for i in 0..<blocks.length() {
  399. 399● let block = blocks[i]
  400. 400 // 标题特征:字体大、加粗、在页面顶部、独占一行
  401. 401 let is_large = block.font_size >= title_font_size_threshold
  402. 402 let is_at_top = block.y < 100
  403. 403 let is_short = block.width < 400
  404. 404 if is_large && (block.is_bold || is_at_top) && is_short {
  405. 405● title_indices.push(i)
  406. 406 }
  407. 407 }
  408. 408 title_indices
  409. 409}
  410. 410
  411. 411///|
  412. 412/// 构建文档结构树(层级结构)
  413. 413pub fn build_document_structure_tree(
  414. 414 blocks : Array[DocumentBlock],
  415. 415) -> Array[DocumentTreeNode] {
  416. 416 // 按阅读顺序排序
  417. 417● let order = optimize_reading_order(blocks, 1)
  418. 418 let ordered_blocks : Array[DocumentBlock] = []
  419. 419 for idx in order {
  420. 420● ordered_blocks.push(blocks[idx])
  421. 421 }
  422. 422 // 构建树(基于标题层级)
  423. 423 let roots : Array[DocumentTreeNode] = []
  424. 424 let stack : Array[DocumentTreeNode] = []
  425. 425 let mut node_id = 0
  426. 426 for block in ordered_blocks {
  427. 427 // 计算深度(基于块类型)
  428. 428● let depth = match block.block_type {
  429. 429● DocumentBlockType::Title => 0
  430. 430● DocumentBlockType::Heading1 => 1
  431. 431● DocumentBlockType::Heading2 => 2
  432. 432● DocumentBlockType::Heading3 => 3
  433. 433● _ => 4
  434. 434 }
  435. 435 let node = DocumentTreeNode::{ node_id, block, children: [], depth, }
  436. 436 node_id += 1
  437. 437 // 弹出栈中深度 >= 当前深度的节点
  438. 438● while stack.length() > 0 && stack[stack.length() - 1].depth >= depth {
  439. 439● let _ = stack.pop()
  440. 440 }
  441. 441 // 如果栈为空,添加到根节点
  442. 442● if stack.length() == 0 {
  443. 443● roots.push(node)
  444. 444 } else {
  445. 445 // 添加为栈顶节点的子节点
  446. 446● let parent = stack[stack.length() - 1]
  447. 447● parent.children.push(node)
  448. 448 }
  449. 449 // 将当前节点压入栈
  450. 450● stack.push(node)
  451. 451 }
  452. 452 roots
  453. 453}
  454. 454
  455. 455///|
  456. 456/// 提取文档纯文本(按阅读顺序)
  457. 457pub fn extract_document_text(
  458. 458 blocks : Array[DocumentBlock],
  459. 459 include_headers~ : Bool = true,
  460. 460 include_footers~ : Bool = false,
  461. 461) -> String {
  462. 462● let order = optimize_reading_order(blocks, 1)
  463. 463 let mut text = ""
  464. 464 for idx in order {
  465. 465● let block = blocks[idx]
  466. 466 // 过滤页眉页脚
  467. 467 if !include_headers && block.block_type == DocumentBlockType::Header {
  468. 468● continue
  469. 469 }
  470. 470 if !include_footers && block.block_type == DocumentBlockType::Footer {
  471. 471● continue
  472. 472 }
  473. 473● if block.text.length() > 0 {
  474. 474● text += block.text
  475. 475 // 标题和段落之间加换行
  476. 476● match block.block_type {
  477. 477● DocumentBlockType::Title => text += "\n\n"
  478. 478○ DocumentBlockType::Heading1 => text += "\n\n"
  479. 479● DocumentBlockType::Heading2 => text += "\n\n"
  480. 480○ DocumentBlockType::Heading3 => text += "\n\n"
  481. 481● DocumentBlockType::Paragraph => text += "\n"
  482. 482● DocumentBlockType::ListItem => text += "\n"
  483. 483● _ => text += " "
  484. 484 }
  485. 485 }
  486. 486 }
  487. 487 text
  488. 488}
  489. 489
  490. 490///|
  491. 491/// 文档统计信息(增强版)
  492. 492pub fn document_statistics_enhanced(
  493. 493 blocks : Array[DocumentBlock],
  494. 494) -> (Int32, Int32, Int32, Int32, Int32, Int32, Int32) {
  495. 495● let mut titles = 0
  496. 496 let mut headings = 0
  497. 497 let mut paragraphs = 0
  498. 498 let mut list_items = 0
  499. 499 let mut tables = 0
  500. 500 let mut images = 0
  501. 501 let mut total_chars = 0
  502. 502 for block in blocks {
  503. 503● match block.block_type {
  504. 504● DocumentBlockType::Title => titles += 1
  505. 505● DocumentBlockType::Heading1 => headings += 1
  506. 506● DocumentBlockType::Heading2 => headings += 1
  507. 507● DocumentBlockType::Heading3 => headings += 1
  508. 508● DocumentBlockType::Paragraph => paragraphs += 1
  509. 509● DocumentBlockType::ListItem => list_items += 1
  510. 510● DocumentBlockType::Table => tables += 1
  511. 511● DocumentBlockType::Image => images += 1
  512. 512● _ => ignore(())
  513. 513 }
  514. 514● total_chars += block.text.length()
  515. 515 }
  516. 516 (titles, headings, paragraphs, list_items, tables, images, total_chars)
  517. 517}
  518. 518
  519. 519///|
  520. 520/// 完整增强文档理解流水线
  521. 521pub fn understand_document_enhanced(
  522. 522 img : @types.Image,
  523. 523 config? : DocumentUnderstandingEnhancedConfig,
  524. 524) -> (Array[DocumentBlock], Array[DocumentTreeNode], String) raise @types.LoadError {
  525. 525 // 输入验证
  526. 526● if img.width <= 0 || img.height <= 0 {
  527. 527● raise @types.LoadError::DecodeFailed(
  528. 528 "understand_document_enhanced: 图像尺寸必须大于0",
  529. 529 )
  530. 530 }
  531. 531 if img.channels < 1 || img.channels > 4 {
  532. 532● raise @types.LoadError::DecodeFailed(
  533. 533 "understand_document_enhanced: 通道数必须在1-4之间",
  534. 534 )
  535. 535 }
  536. 536 let expected_size = img.width * img.height * img.channels
  537. 537● if img.data.length() != expected_size {
  538. 538● raise @types.LoadError::DecodeFailed(
  539. 539 "understand_document_enhanced: 数据大小不匹配,期望 " +
  540. 540● expected_size.to_string() +
  541. 541 ",实际 " +
  542. 542● img.data.length().to_string(),
  543. 543 )
  544. 544 }
  545. 545● let cfg = match config {
  546. 546● Some(c) => c
  547. 547● None => document_understanding_enhanced_default_config()
  548. 548 }
  549. 549 // 1. 增强版面分析
  550. 550● let blocks = analyze_layout_enhanced(img, config=cfg)
  551. 551 // 2. 多栏检测
  552. 552 let num_columns = if cfg.enable_column_detection {
  553. 553● let preprocessed = ocr_preprocess(img)
  554. 554● let (cols, _) = detect_columns(preprocessed)
  555. 555 cols
  556. 556 } else {
  557. 557● 1
  558. 558 }
  559. 559 // 3. 优化阅读顺序
  560. 560● let order = optimize_reading_order(blocks, num_columns)
  561. 561 // 更新块的阅读顺序
  562. 562● for i in 0..<order.length() {
  563. 563● blocks[order[i]].reading_order = i
  564. 564 }
  565. 565 // 4. 构建文档结构树
  566. 566 let tree = if cfg.enable_hierarchy {
  567. 567● build_document_structure_tree(blocks)
  568. 568 } else {
  569. 569● []
  570. 570 }
  571. 571 // 5. 提取纯文本
  572. 572● let text = extract_document_text(
  573. 573 blocks,
  574. 574 include_headers=true,
  575. 575 include_footers=false,
  576. 576 )
  577. 577 (blocks, tree, text)
  578. 578}