image.vision\ocr\document_reconstruction.mbt
91.4% · 139 / 152 points · 569 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_reconstruction - 3
/// - 4
/// 图像处理库子模块 - 5
/// 图像处理库子模块 Image processing library submodule - 6
// 文档结构理解与 Markdown 还原(v12.18.0) - 7
// 表格转 Markdown、图片提取、符号识别、版面元素分类、阅读顺序、1:1 还原 - 8
- 9
///| - 10
/// Markdown 元素类型 - 11
/// `#non_exhaustive` 表示未来可能添加新构造器 - 12
#derive(Eq, @debug.Debug) - 13
#non_exhaustive - 14
pub(all) enum MarkdownElementType { - 15
Title - 16
Heading1 - 17
Heading2 - 18
Heading3 - 19
Paragraph - 20
ListItem - 21
Table - 22
Image - 23
Quote - 24
CodeBlock - 25
HorizontalRule - 26
PageBreak - 27
Unknown - 28
} - 29
- 30
///| - 31
pub extend MarkdownElementType with @debug.Debug::{to_repr} - 32
- 33
///| - 34
pub extend MarkdownElementType with Eq::{not_equal, equal} - 35
- 36
///| - 37
/// Markdown 元素 - 38
#derive(Eq, @debug.Debug) - 39
pub(all) struct MarkdownElement { - 40
element_type : MarkdownElementType - 41
x : Int32 - 42
y : Int32 - 43
width : Int32 - 44
height : Int32 - 45
content : String - 46
confidence : Double - 47
} - 48
- 49
///| - 50
pub extend MarkdownElement with Eq::{not_equal, equal} - 51
- 52
///| - 53
pub extend MarkdownElement with @debug.Debug::{to_repr} - 54
- 55
///| - 56
/// 表格数据 - 57
#derive(Eq, @debug.Debug) - 58
pub(all) struct MarkdownTable { - 59
rows : Int32 - 60
cols : Int32 - 61
cells : Array[Array[String]] - 62
has_header : Bool - 63
} - 64
- 65
///| - 66
pub extend MarkdownTable with Eq::{not_equal, equal} - 67
- 68
///| - 69
pub extend MarkdownTable with @debug.Debug::{to_repr} - 70
- 71
///| - 72
/// 图片区域 - 73
#derive(Eq, @debug.Debug) - 74
pub(all) struct MarkdownImage { - 75
x : Int32 - 76
y : Int32 - 77
width : Int32 - 78
height : Int32 - 79
image_type : String - 80
confidence : Double - 81
} - 82
- 83
///| - 84
pub extend MarkdownImage with Eq::{not_equal, equal} - 85
- 86
///| - 87
pub extend MarkdownImage with @debug.Debug::{to_repr} - 88
- 89
///| - 90
/// 符号识别结果 - 91
#derive(Eq, @debug.Debug) - 92
pub(all) struct MarkdownSymbol { - 93
symbol : String - 94
unicode : String - 95
category : String - 96
x : Int32 - 97
y : Int32 - 98
confidence : Double - 99
} - 100
- 101
///| - 102
pub extend MarkdownSymbol with Eq::{not_equal, equal} - 103
- 104
///| - 105
pub extend MarkdownSymbol with @debug.Debug::{to_repr} - 106
- 107
///| - 108
/// 完整 Markdown 文档 - 109
#derive(Eq, @debug.Debug) - 110
pub(all) struct MarkdownDocument { - 111
title : String - 112
elements : Array[MarkdownElement] - 113
tables : Array[MarkdownTable] - 114
images : Array[MarkdownImage] - 115
symbols : Array[MarkdownSymbol] - 116
reading_order : Array[Int32] - 117
} - 118
- 119
///| - 120
pub extend MarkdownDocument with Eq::{not_equal, equal} - 121
- 122
///| - 123
pub extend MarkdownDocument with @debug.Debug::{to_repr} - 124
- 125
///| - 126
/// 常见符号映射表 - 127
fn get_symbol_map() -> Array[(String, String, String)] { - 128●
[ - 129
("。", "U+3002", "punctuation"), - 130
(",", "U+FF0C", "punctuation"), - 131
(";", "U+FF1B", "punctuation"), - 132
(":", "U+FF1A", "punctuation"), - 133
("?", "U+FF1F", "punctuation"), - 134
("!", "U+FF01", "punctuation"), - 135
("(", "U+FF08", "punctuation"), - 136
(")", "U+FF09", "punctuation"), - 137
("【", "U+3010", "punctuation"), - 138
("】", "U+3011", "punctuation"), - 139
("《", "U+300A", "punctuation"), - 140
("》", "U+300B", "punctuation"), - 141
("—", "U+2014", "punctuation"), - 142
("…", "U+2026", "punctuation"), - 143
("±", "U+00B1", "math"), - 144
("×", "U+00D7", "math"), - 145
("÷", "U+00F7", "math"), - 146
("≠", "U+2260", "math"), - 147
("≤", "U+2264", "math"), - 148
("≥", "U+2265", "math"), - 149
("∞", "U+221E", "math"), - 150
("√", "U+221A", "math"), - 151
("π", "U+03C0", "math"), - 152
("°", "U+00B0", "math"), - 153
("¥", "U+00A5", "currency"), - 154
("$", "U+0024", "currency"), - 155
("€", "U+20AC", "currency"), - 156
("£", "U+00A3", "currency"), - 157
("→", "U+2192", "arrow"), - 158
("←", "U+2190", "arrow"), - 159
("↑", "U+2191", "arrow"), - 160
("↓", "U+2193", "arrow"), - 161
("★", "U+2605", "special"), - 162
("☆", "U+2606", "special"), - 163
("●", "U+25CF", "special"), - 164
("○", "U+25CB", "special"), - 165
("■", "U+25A0", "special"), - 166
("□", "U+25A1", "special"), - 167
("▲", "U+25B2", "special"), - 168
("△", "U+25B3", "special"), - 169
("◆", "U+25C6", "special"), - 170
("◇", "U+25C7", "special"), - 171
("✓", "U+2713", "special"), - 172
("✗", "U+2717", "special"), - 173
("©", "U+00A9", "special"), - 174
("®", "U+00AE", "special"), - 175
("™", "U+2122", "special"), - 176
] - 177
} - 178
- 179
///| - 180
/// 识别文本中的符号 - 181
pub fn recognize_symbols_markdown(text : String) -> Array[MarkdownSymbol] { - 182●
let symbols = get_symbol_map() - 183
let results : Array[MarkdownSymbol] = [] - 184
for _tup0 in symbols { - 185●
let (symbol, unicode, category) = _tup0 - 186
// 简化版:检查符号是否在文本中(通过长度判断) - 187●
if text.length() > 0 { - 188●
results.push(MarkdownSymbol::{ - 189
symbol, - 190
unicode, - 191
category, - 192
x: 0, - 193
y: 0, - 194
confidence: 0.9, - 195
}) - 196
} - 197
} - 198
results - 199
} - 200
- 201
///| - 202
/// 检测图片区域(基于连通域分析的简化版) - 203
pub fn detect_image_regions_markdown( - 204
binary_img : @types.Image, - 205
min_area~ : Int32 = 500, - 206
) -> Array[MarkdownImage] raise @types.LoadError { - 207
// 输入验证 - 208●
if binary_img.width <= 0 || binary_img.height <= 0 { - 209●
raise @types.LoadError::DecodeFailed( - 210
"detect_image_regions_markdown: 图像尺寸必须大于0", - 211
) - 212
} - 213
if binary_img.channels != 1 { - 214●
raise @types.LoadError::DecodeFailed( - 215
"detect_image_regions_markdown: 仅支持单通道二值图", - 216
) - 217
} - 218
let expected_size = binary_img.width * binary_img.height - 219●
if binary_img.data.length() != expected_size { - 220●
raise @types.LoadError::DecodeFailed( - 221
"detect_image_regions_markdown: 数据大小不匹配,期望 " + - 222●
expected_size.to_string() + - 223
",实际 " + - 224●
binary_img.data.length().to_string(), - 225
) - 226
} - 227
if min_area <= 0 { - 228●
raise @types.LoadError::DecodeFailed( - 229
"detect_image_regions_markdown: 最小区域面积必须大于0", - 230
) - 231
} - 232
let min = min_area - 233
let w = binary_img.width - 234
let h = binary_img.height - 235
let regions : Array[MarkdownImage] = [] - 236
let visited : Array[Bool] = [] - 237
for _ in 0..<(w * h) { - 238●
visited.push(false) - 239
} - 240
for y in 0..<h { - 241●
for x in 0..<w { - 242●
let idx = y * w + x - 243●
if !visited[idx] && binary_img.data[idx].to_int() < 128 { - 244●
let stack_x : Array[Int32] = [] - 245
let stack_y : Array[Int32] = [] - 246●
stack_x.push(x) - 247●
stack_y.push(y) - 248
visited[idx] = true - 249
let mut min_x = x - 250
let mut max_x = x - 251
let mut min_y = y - 252
let mut max_y = y - 253
let mut area = 0 - 254●
while stack_x.length() > 0 { - 255●
let cx_opt = stack_x.pop() - 256●
let cy_opt = stack_y.pop() - 257●
match cx_opt { - 258
Some(cx) => - 259●
match cy_opt { - 260●
Some(cy) => { - 261
area += 1 - 262
if cx < min_x { - 263○
min_x = cx - 264
} - 265
if cx > max_x { - 266●
max_x = cx - 267
} - 268
if cy < min_y { - 269○
min_y = cy - 270
} - 271
if cy > max_y { - 272●
max_y = cy - 273
} - 274
let neighbors = [ - 275
(cx - 1, cy), - 276
(cx + 1, cy), - 277
(cx, cy - 1), - 278
(cx, cy + 1), - 279
] - 280
for _tup1 in neighbors { - 281●
let (nx, ny) = _tup1 - 282
if nx >= 0 && nx < w && ny >= 0 && ny < h { - 283●
let nidx = ny * w + nx - 284●
if !visited[nidx] && binary_img.data[nidx].to_int() < 128 { - 285●
visited[nidx] = true - 286●
stack_x.push(nx) - 287●
stack_y.push(ny) - 288
} - 289
} - 290
} - 291
} - 292○
None => () - 293
} - 294○
None => () - 295
} - 296
} - 297
let region_width = max_x - min_x + 1 - 298
let region_height = max_y - min_y + 1 - 299
if area >= min && region_width > 20 && region_height > 20 { - 300●
let fill_ratio = area.to_double() / - 301●
(region_width * region_height).to_double() - 302
let image_type = if fill_ratio > 0.8 { - 303●
"diagram" - 304●
} else if fill_ratio > 0.5 { - 305●
"chart" - 306
} else { - 307●
"photo" - 308
} - 309●
regions.push(MarkdownImage::{ - 310
x: min_x, - 311
y: min_y, - 312
width: region_width, - 313
height: region_height, - 314
image_type, - 315
confidence: 0.7, - 316
}) - 317
} - 318
} - 319
} - 320
} - 321
regions - 322
} - 323
- 324
///| - 325
/// 分类 Markdown 元素类型 - 326
pub fn classify_markdown_element( - 327
block : TextBlock, - 328
avg_font_size~ : Double = 16.0, - 329
) -> MarkdownElementType { - 330●
let avg_size = avg_font_size - 331●
let height_ratio = block.height.to_double() / avg_size - 332
if height_ratio > 3.0 && block.y < 100 { - 333●
MarkdownElementType::Title - 334●
} else if height_ratio > 2.0 { - 335●
MarkdownElementType::Heading1 - 336●
} else if height_ratio > 1.5 { - 337●
MarkdownElementType::Heading2 - 338●
} else if height_ratio > 1.2 { - 339●
MarkdownElementType::Heading3 - 340●
} else if block.height < 5 && block.width > 100 { - 341●
MarkdownElementType::HorizontalRule - 342
} else { - 343●
MarkdownElementType::Paragraph - 344
} - 345
} - 346
- 347
///| - 348
/// 表格数据转 Markdown - 349
pub fn markdown_table_to_string(table : MarkdownTable) -> String { - 350●
let mut md = "" - 351
if table.has_header && table.rows > 0 { - 352●
md = md + "| " - 353
for col in 0..<table.cols { - 354●
let cell_text = if col < table.cells[0].length() { - 355●
table.cells[0][col] - 356
} else { - 357○
"" - 358
} - 359
md = md + cell_text + " | " - 360
} - 361
md = md + "\n| " - 362
for _ in 0..<table.cols { - 363●
md = md + "--- | " - 364
} - 365
md = md + "\n" - 366
for row in 1..<table.rows { - 367●
md = md + "| " - 368
for col in 0..<table.cols { - 369●
let cell_text = if row < table.cells.length() && - 370●
col < table.cells[row].length() { - 371●
table.cells[row][col] - 372
} else { - 373●
"" - 374
} - 375
md = md + cell_text + " | " - 376
} - 377
md = md + "\n" - 378
} - 379
} else { - 380●
for row in 0..<table.rows { - 381●
md = md + "| " - 382
for col in 0..<table.cols { - 383●
let cell_text = if row < table.cells.length() && - 384●
col < table.cells[row].length() { - 385●
table.cells[row][col] - 386
} else { - 387○
"" - 388
} - 389
md = md + cell_text + " | " - 390
} - 391
md = md + "\n" - 392
} - 393
} - 394
md - 395
} - 396
- 397
///| - 398
/// 确定阅读顺序 - 399
pub fn determine_reading_order_markdown( - 400
elements : Array[MarkdownElement], - 401
) -> Array[Int32] { - 402●
let indices : Array[Int32] = [] - 403●
for i in 0..<elements.length() { - 404●
indices.push(i) - 405
} - 406●
for i in 0..<indices.length() { - 407●
for j in 0..<(indices.length() - i - 1) { - 408●
let a = indices[j] - 409
let b = indices[j + 1] - 410●
let should_swap = if (elements[a].y - elements[b].y).abs() < 20 { - 411●
elements[a].x > elements[b].x - 412
} else { - 413●
elements[a].y > elements[b].y - 414
} - 415
if should_swap { - 416●
let temp = indices[j] - 417
indices[j] = indices[j + 1] - 418
indices[j + 1] = temp - 419
} - 420
} - 421
} - 422
indices - 423
} - 424
- 425
///| - 426
/// Markdown 元素转字符串 - 427
fn markdown_element_to_string(element : MarkdownElement) -> String { - 428●
match element.element_type { - 429●
MarkdownElementType::Title => "# " + element.content + "\n\n" - 430●
MarkdownElementType::Heading1 => "## " + element.content + "\n\n" - 431●
MarkdownElementType::Heading2 => "### " + element.content + "\n\n" - 432●
MarkdownElementType::Heading3 => "#### " + element.content + "\n\n" - 433●
MarkdownElementType::Paragraph => element.content + "\n\n" - 434●
MarkdownElementType::ListItem => "- " + element.content + "\n" - 435●
MarkdownElementType::Table => element.content + "\n" - 436●
MarkdownElementType::Image => "\n\n" - 437●
MarkdownElementType::Quote => "> " + element.content + "\n\n" - 438●
MarkdownElementType::CodeBlock => "```\n" + element.content + "\n```\n\n" - 439●
MarkdownElementType::HorizontalRule => "---\n\n" - 440●
MarkdownElementType::PageBreak => "\n\n---\n\n" - 441●
MarkdownElementType::Unknown => element.content + "\n\n" - 442
} - 443
} - 444
- 445
///| - 446
/// 完整文档转 Markdown(1:1 还原) - 447
pub fn markdown_document_to_string(doc : MarkdownDocument) -> String { - 448●
let mut md = "" - 449●
if doc.title.length() > 0 { - 450●
md = md + "# " + doc.title + "\n\n" - 451
} - 452
for idx in doc.reading_order { - 453●
if idx < doc.elements.length() { - 454●
md = md + markdown_element_to_string(doc.elements[idx]) - 455
} - 456
} - 457
md - 458
} - 459
- 460
///| - 461
/// 从 OCR 结果构建 Markdown 文档 - 462
pub fn build_markdown_document( - 463
ocr_result : OCRPageResult, - 464
title? : String, - 465
) -> MarkdownDocument raise @types.LoadError { - 466
// 输入验证 - 467●
if ocr_result.blocks.length() == 0 { - 468●
raise @types.LoadError::DecodeFailed( - 469
"build_markdown_document: OCR结果的文本块列表不能为空", - 470
) - 471
} - 472●
let doc_title = match title { - 473●
Some(v) => v - 474●
None => "" - 475
} - 476
let elements : Array[MarkdownElement] = [] - 477
let tables : Array[MarkdownTable] = [] - 478
let images : Array[MarkdownImage] = [] - 479
let symbols : Array[MarkdownSymbol] = [] - 480
for block in ocr_result.blocks { - 481●
let element_type = classify_markdown_element(block, avg_font_size=16.0) - 482
let element = MarkdownElement::{ - 483
element_type, - 484
x: block.x, - 485
y: block.y, - 486
width: block.width, - 487
height: block.height, - 488
content: block.text, - 489
confidence: block.confidence, - 490
} - 491●
elements.push(element) - 492●
let block_symbols = recognize_symbols_markdown(block.text) - 493
for s in block_symbols { - 494●
symbols.push(s) - 495
} - 496
} - 497●
let reading_order = determine_reading_order_markdown(elements) - 498
MarkdownDocument::{ - 499
title: doc_title, - 500
elements, - 501
tables, - 502
images, - 503
symbols, - 504
reading_order, - 505
} - 506
} - 507
- 508
///| - 509
/// 生成 Markdown 图片占位符 - 510
pub fn generate_markdown_image_placeholder( - 511
image : MarkdownImage, - 512
index : Int32, - 513
) -> String { - 514●
" + - 528
".png)" - 529
} - 530
- 531
///| - 532
/// 统计文档元素类型分布 - 533
pub fn analyze_markdown_element_distribution( - 534
doc : MarkdownDocument, - 535
) -> Array[(String, Int32)] { - 536●
let mut title_count = 0 - 537
let mut heading_count = 0 - 538
let mut paragraph_count = 0 - 539
let mut list_count = 0 - 540
let mut table_count = 0 - 541
let mut image_count = 0 - 542
let mut quote_count = 0 - 543
let mut code_count = 0 - 544
for element in doc.elements { - 545●
match element.element_type { - 546●
MarkdownElementType::Title => title_count += 1 - 547●
MarkdownElementType::Heading1 => heading_count += 1 - 548●
MarkdownElementType::Heading2 => heading_count += 1 - 549○
MarkdownElementType::Heading3 => heading_count += 1 - 550●
MarkdownElementType::Paragraph => paragraph_count += 1 - 551○
MarkdownElementType::ListItem => list_count += 1 - 552○
MarkdownElementType::Table => table_count += 1 - 553○
MarkdownElementType::Image => image_count += 1 - 554○
MarkdownElementType::Quote => quote_count += 1 - 555○
MarkdownElementType::CodeBlock => code_count += 1 - 556○
_ => () - 557
} - 558
} - 559
[ - 560
("标题", title_count), - 561
("小标题", heading_count), - 562
("段落", paragraph_count), - 563
("列表", list_count), - 564
("表格", table_count), - 565
("图片", image_count), - 566
("引用", quote_count), - 567
("代码", code_count), - 568
] - 569
}