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