image.vision\ocr\document_reconstruction.mbt

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