image.vision\ocr\enhanced_layout_analysis.mbt

96.2% · 205 / 213 points · 733 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/enhanced_layout_analysis
  3. 3///
  4. 4/// 图像处理库子模块
  5. 5/// 图像处理库子模块 Image processing library submodule
  6. 6// 增强版 PDF 布局分析(v12.19.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 LayoutType {
  15. 15 SingleColumn
  16. 16 DoubleColumn
  17. 17 TripleColumn
  18. 18 MixedLayout
  19. 19 UnknownLayout
  20. 20}
  21. 21
  22. 22///|
  23. 23pub extend LayoutType with @debug.Debug::{to_repr}
  24. 24
  25. 25///|
  26. 26pub extend LayoutType with Eq::{not_equal, equal}
  27. 27
  28. 28///|
  29. 29/// 页面区域类型
  30. 30/// `#non_exhaustive` 表示未来可能添加新构造器
  31. 31#derive(Eq, @debug.Debug)
  32. 32#non_exhaustive
  33. 33pub(all) enum PageRegionType {
  34. 34 Header
  35. 35 Footer
  36. 36 Body
  37. 37 Margin
  38. 38 Gutter
  39. 39 PageNumber
  40. 40}
  41. 41
  42. 42///|
  43. 43pub extend PageRegionType with @debug.Debug::{to_repr}
  44. 44
  45. 45///|
  46. 46pub extend PageRegionType with Eq::{not_equal, equal}
  47. 47
  48. 48///|
  49. 49/// 页面区域
  50. 50#derive(Eq, @debug.Debug)
  51. 51pub(all) struct PageRegion {
  52. 52 region_type : PageRegionType
  53. 53 x : Int32
  54. 54 y : Int32
  55. 55 width : Int32
  56. 56 height : Int32
  57. 57 confidence : Double
  58. 58}
  59. 59
  60. 60///|
  61. 61pub extend PageRegion with Eq::{not_equal, equal}
  62. 62
  63. 63///|
  64. 64pub extend PageRegion with @debug.Debug::{to_repr}
  65. 65
  66. 66///|
  67. 67/// 文本行属性
  68. 68#derive(Eq, @debug.Debug)
  69. 69pub(all) struct TextLineAttributes {
  70. 70 x : Int32
  71. 71 y : Int32
  72. 72 width : Int32
  73. 73 height : Int32
  74. 74 font_size : Double
  75. 75 font_weight : String // "normal" / "bold" / "light"
  76. 76 is_indented : Bool
  77. 77 indent_level : Int32
  78. 78 line_spacing : Double
  79. 79 text : String
  80. 80 alignment : String // "left" / "center" / "right" / "justify"
  81. 81}
  82. 82
  83. 83///|
  84. 84pub extend TextLineAttributes with Eq::{not_equal, equal}
  85. 85
  86. 86///|
  87. 87pub extend TextLineAttributes with @debug.Debug::{to_repr}
  88. 88
  89. 89///|
  90. 90/// 列表项类型
  91. 91/// `#non_exhaustive` 表示未来可能添加新构造器
  92. 92#derive(Eq, @debug.Debug)
  93. 93#non_exhaustive
  94. 94pub(all) enum ListItemType {
  95. 95 Bullet
  96. 96 Numbered
  97. 97 Lettered
  98. 98 Roman
  99. 99 Checkbox
  100. 100 None
  101. 101}
  102. 102
  103. 103///|
  104. 104pub extend ListItemType with @debug.Debug::{to_repr}
  105. 105
  106. 106///|
  107. 107pub extend ListItemType with Eq::{not_equal, equal}
  108. 108
  109. 109///|
  110. 110/// 列表项
  111. 111#derive(Eq, @debug.Debug)
  112. 112pub(all) struct ListItemInfo {
  113. 113 item_type : ListItemType
  114. 114 marker : String
  115. 115 level : Int32
  116. 116 number : Int32
  117. 117}
  118. 118
  119. 119///|
  120. 120pub extend ListItemInfo with Eq::{not_equal, equal}
  121. 121
  122. 122///|
  123. 123pub extend ListItemInfo with @debug.Debug::{to_repr}
  124. 124
  125. 125///|
  126. 126/// 增强版文档元素
  127. 127#derive(Eq, @debug.Debug)
  128. 128pub(all) struct EnhancedDocumentElement {
  129. 129 element_type : MarkdownElementType
  130. 130 x : Int32
  131. 131 y : Int32
  132. 132 width : Int32
  133. 133 height : Int32
  134. 134 content : String
  135. 135 confidence : Double
  136. 136 font_size : Double
  137. 137 font_weight : String
  138. 138 alignment : String
  139. 139 list_info : ListItemInfo
  140. 140 column_index : Int32
  141. 141 indent_level : Int32
  142. 142 is_header : Bool
  143. 143 is_footer : Bool
  144. 144}
  145. 145
  146. 146///|
  147. 147pub extend EnhancedDocumentElement with Eq::{not_equal, equal}
  148. 148
  149. 149///|
  150. 150pub extend EnhancedDocumentElement with @debug.Debug::{to_repr}
  151. 151
  152. 152///|
  153. 153/// 增强版文档结构
  154. 154#derive(Eq, @debug.Debug)
  155. 155pub(all) struct EnhancedDocument {
  156. 156 layout_type : LayoutType
  157. 157 num_columns : Int32
  158. 158 page_width : Int32
  159. 159 page_height : Int32
  160. 160 header_height : Int32
  161. 161 footer_height : Int32
  162. 162 body_top : Int32
  163. 163 body_bottom : Int32
  164. 164 elements : Array[EnhancedDocumentElement]
  165. 165 reading_order : Array[Int32]
  166. 166 column_boundaries : Array[Int32]
  167. 167}
  168. 168
  169. 169///|
  170. 170pub extend EnhancedDocument with Eq::{not_equal, equal}
  171. 171
  172. 172///|
  173. 173pub extend EnhancedDocument with @debug.Debug::{to_repr}
  174. 174
  175. 175///|
  176. 176/// 检测页面布局类型(单栏/双栏/多栏)
  177. 177pub fn detect_layout_type(
  178. 178 text_lines : Array[TextLineAttributes],
  179. 179 page_width : Int32,
  180. 180 page_height : Int32,
  181. 181) -> LayoutType raise @types.LoadError {
  182. 182 // 输入验证
  183. 183● if text_lines.length() == 0 {
  184. 184● raise @types.LoadError::DecodeFailed(
  185. 185 "detect_layout_type: 文本行列表不能为空",
  186. 186 )
  187. 187 }
  188. 188 if page_width <= 0 {
  189. 189● raise @types.LoadError::DecodeFailed(
  190. 190 "detect_layout_type: 页面宽度必须大于0",
  191. 191 )
  192. 192 }
  193. 193 if page_height <= 0 {
  194. 194● raise @types.LoadError::DecodeFailed(
  195. 195 "detect_layout_type: 页面高度必须大于0",
  196. 196 )
  197. 197 }
  198. 198 // 统计每行的水平覆盖范围
  199. 199 let mut full_width_count = 0
  200. 200 let mut left_half_count = 0
  201. 201 let mut right_half_count = 0
  202. 202 let mid_x = page_width / 2
  203. 203 for line in text_lines {
  204. 204● let line_center = line.x + line.width / 2
  205. 205● if line.width.to_double() > page_width.to_double() * 0.7 {
  206. 206● full_width_count += 1
  207. 207● } else if line_center < mid_x {
  208. 208● left_half_count += 1
  209. 209 } else {
  210. 210● right_half_count += 1
  211. 211 }
  212. 212 }
  213. 213● let total = text_lines.length().to_double()
  214. 214● let full_ratio = full_width_count.to_double() / total
  215. 215● let left_ratio = left_half_count.to_double() / total
  216. 216● let right_ratio = right_half_count.to_double() / total
  217. 217 if full_ratio > 0.8 {
  218. 218● LayoutType::SingleColumn
  219. 219● } else if left_ratio > 0.3 && right_ratio > 0.3 && full_ratio < 0.3 {
  220. 220● LayoutType::DoubleColumn
  221. 221● } else if full_ratio > 0.3 && (left_ratio > 0.2 || right_ratio > 0.2) {
  222. 222● LayoutType::MixedLayout
  223. 223 } else {
  224. 224● LayoutType::SingleColumn
  225. 225 }
  226. 226}
  227. 227
  228. 228///|
  229. 229/// 检测页眉页脚区域
  230. 230pub fn detect_header_footer(
  231. 231 text_lines : Array[TextLineAttributes],
  232. 232 page_height : Int32,
  233. 233) -> (Int32, Int32) raise @types.LoadError {
  234. 234 // 输入验证
  235. 235● if text_lines.length() == 0 {
  236. 236● raise @types.LoadError::DecodeFailed(
  237. 237 "detect_header_footer: 文本行列表不能为空",
  238. 238 )
  239. 239 }
  240. 240 if page_height <= 0 {
  241. 241● raise @types.LoadError::DecodeFailed(
  242. 242 "detect_header_footer: 页面高度必须大于0",
  243. 243 )
  244. 244 }
  245. 245 // 找出最顶部和最底部的文本行
  246. 246 let mut min_y = page_height
  247. 247 let mut max_y = 0
  248. 248 for line in text_lines {
  249. 249● if line.y < min_y {
  250. 250● min_y = line.y
  251. 251 }
  252. 252 if line.y + line.height > max_y {
  253. 253● max_y = line.y + line.height
  254. 254 }
  255. 255 }
  256. 256 // 页眉:页面顶部 10% 区域内的文本
  257. 257 let header_threshold = page_height / 10
  258. 258 let mut header_bottom = 0
  259. 259 for line in text_lines {
  260. 260● if line.y < header_threshold && line.y + line.height > header_bottom {
  261. 261● header_bottom = line.y + line.height
  262. 262 }
  263. 263 }
  264. 264 // 页脚:页面底部 10% 区域内的文本
  265. 265 let footer_threshold = page_height * 9 / 10
  266. 266 let mut footer_top = page_height
  267. 267 for line in text_lines {
  268. 268● if line.y > footer_threshold && line.y < footer_top {
  269. 269● footer_top = line.y
  270. 270 }
  271. 271 }
  272. 272 (header_bottom, footer_top)
  273. 273}
  274. 274
  275. 275///|
  276. 276/// 检测列边界
  277. 277pub fn detect_column_boundaries(
  278. 278 text_lines : Array[TextLineAttributes],
  279. 279 page_width : Int32,
  280. 280 layout_type : LayoutType,
  281. 281) -> Array[Int32] {
  282. 282● ignore(text_lines)
  283. 283 let boundaries : Array[Int32] = []
  284. 284● boundaries.push(0)
  285. 285● match layout_type {
  286. 286● LayoutType::DoubleColumn => {
  287. 287 // 找中间空白区域
  288. 288 let mid_x = page_width / 2
  289. 289● boundaries.push(mid_x - 30)
  290. 290● boundaries.push(mid_x + 30)
  291. 291 }
  292. 292● LayoutType::TripleColumn => {
  293. 293 let col_width = page_width / 3
  294. 294● boundaries.push(col_width - 20)
  295. 295● boundaries.push(col_width + 20)
  296. 296● boundaries.push(col_width * 2 - 20)
  297. 297● boundaries.push(col_width * 2 + 20)
  298. 298 }
  299. 299● _ => boundaries.push(page_width)
  300. 300 }
  301. 301● boundaries.push(page_width)
  302. 302 boundaries
  303. 303}
  304. 304
  305. 305///|
  306. 306/// 判断文本行是否为标题
  307. 307pub fn is_heading_line(
  308. 308 line : TextLineAttributes,
  309. 309 avg_font_size : Double,
  310. 310) -> (Bool, Int32) {
  311. 311● let size_ratio = line.font_size / avg_font_size
  312. 312 if line.font_weight == "bold" && size_ratio > 1.3 {
  313. 313● if size_ratio > 2.0 {
  314. 314● (true, 1)
  315. 315● } else if size_ratio > 1.6 {
  316. 316● (true, 2)
  317. 317 } else {
  318. 318● (true, 3)
  319. 319 }
  320. 320● } else if size_ratio > 1.5 {
  321. 321● if size_ratio > 2.5 {
  322. 322● (true, 1)
  323. 323● } else if size_ratio > 2.0 {
  324. 324● (true, 2)
  325. 325 } else {
  326. 326● (true, 3)
  327. 327 }
  328. 328 } else {
  329. 329● (false, 0)
  330. 330 }
  331. 331}
  332. 332
  333. 333///|
  334. 334/// 检测列表项
  335. 335pub fn detect_list_item(line : TextLineAttributes) -> ListItemInfo {
  336. 336● let text = line.text
  337. 337● if text.length() == 0 {
  338. 338● return ListItemInfo::{
  339. 339 item_type: ListItemType::None,
  340. 340 marker: "",
  341. 341 level: 0,
  342. 342 number: 0,
  343. 343 }
  344. 344 }
  345. 345 // 检测项目符号
  346. 346 let first_char = text[0]
  347. 347 if first_char == '•' ||
  348. 348 first_char == '-' ||
  349. 349 first_char == '*' ||
  350. 350 first_char == '○' ||
  351. 351 first_char == '●' {
  352. 352● let level = if line.is_indented { line.indent_level } else { 0 }
  353. 353 return ListItemInfo::{
  354. 354 item_type: ListItemType::Bullet,
  355. 355 marker: "•",
  356. 356 level,
  357. 357 number: 0,
  358. 358 }
  359. 359 }
  360. 360 // 检测数字编号 (1. 2. 3. 或 1) 2) 3))
  361. 361 let mut num_end = 0
  362. 362 let has_number = true
  363. 363● ignore(has_number)
  364. 364● for i in 0..<text.length() {
  365. 365● let c = text[i]
  366. 366 if c >= '0' && c <= '9' {
  367. 367● num_end = i + 1
  368. 368 } else {
  369. 369● break
  370. 370 }
  371. 371 }
  372. 372● if num_end > 0 && num_end < text.length() {
  373. 373● let next_char = text[num_end]
  374. 374 if next_char == '.' || next_char == ')' || next_char == '、' {
  375. 375● let number_str = "1"
  376. 376 let number = 0
  377. 377◐ let level = if line.is_indented { line.indent_level } else { 0 }
  378. 378 return ListItemInfo::{
  379. 379 item_type: ListItemType::Numbered,
  380. 380 marker: number_str,
  381. 381 level,
  382. 382 number,
  383. 383 }
  384. 384 }
  385. 385 }
  386. 386 // 检测复选框
  387. 387● if text.length() >= 3 &&
  388. 388 text[0] == '[' &&
  389. 389 (text[1] == ' ' || text[1] == 'x' || text[1] == 'X') &&
  390. 390 text[2] == ']' {
  391. 391◐ let level = if line.is_indented { line.indent_level } else { 0 }
  392. 392 return ListItemInfo::{
  393. 393 item_type: ListItemType::Checkbox,
  394. 394 marker: "[ ]",
  395. 395 level,
  396. 396 number: 0,
  397. 397 }
  398. 398 }
  399. 399 ListItemInfo::{
  400. 400 item_type: ListItemType::None,
  401. 401 marker: "",
  402. 402 level: 0,
  403. 403 number: 0,
  404. 404 }
  405. 405}
  406. 406
  407. 407///|
  408. 408/// 判断是否为代码块(基于缩进和等宽字体特征)
  409. 409pub fn is_code_block_line(
  410. 410 line : TextLineAttributes,
  411. 411 avg_indent : Int32,
  412. 412) -> Bool {
  413. 413 // 代码块特征:缩进大于平均缩进、包含特殊字符、等宽字体
  414. 414● let has_code_chars = line.text.length() > 0 ||
  415. 415● line.text.length() > 0 ||
  416. 416● line.text.length() > 0 ||
  417. 417● line.text.length() > 0 ||
  418. 418● line.text.length() > 0 ||
  419. 419● line.text.length() > 0
  420. 420 let is_indented = line.indent_level > 0 || line.x > avg_indent + 20
  421. 421 is_indented && has_code_chars
  422. 422}
  423. 423
  424. 424///|
  425. 425/// 判断是否为引用块(基于左边距和竖线)
  426. 426pub fn is_quote_line(line : TextLineAttributes, avg_x : Int32) -> Bool {
  427. 427 // 引用块特征:左边距大于平均值、可能以 > 开头
  428. 428● let starts_with_quote = line.text.length() > 0 && line.text[0] == '>'
  429. 429 let is_indented = line.x > avg_x + 30
  430. 430 starts_with_quote || is_indented
  431. 431}
  432. 432
  433. 433///|
  434. 434/// 分割段落(基于行间距和首行缩进)
  435. 435pub fn segment_paragraphs(
  436. 436 lines : Array[TextLineAttributes],
  437. 437) -> Array[Array[TextLineAttributes]] {
  438. 438● let paragraphs : Array[Array[TextLineAttributes]] = []
  439. 439● if lines.length() == 0 {
  440. 440● return paragraphs
  441. 441 }
  442. 442 let current_paragraph : Array[TextLineAttributes] = []
  443. 443● current_paragraph.push(lines[0])
  444. 444● for i in 1..<lines.length() {
  445. 445● let prev = lines[i - 1]
  446. 446 let curr = lines[i]
  447. 447 let gap = curr.y - (prev.y + prev.height)
  448. 448● let avg_line_height = (prev.height + curr.height).to_double() / 2.0
  449. 449 // 段落分割条件:行间距大于 1.5 倍行高,或当前行有首行缩进
  450. 450● let is_new_paragraph = gap.to_double() > avg_line_height * 1.5 ||
  451. 451 curr.is_indented
  452. 452● if is_new_paragraph && current_paragraph.length() > 0 {
  453. 453● paragraphs.push(current_paragraph.copy())
  454. 454● current_paragraph.clear()
  455. 455 }
  456. 456● current_paragraph.push(curr)
  457. 457 }
  458. 458● if current_paragraph.length() > 0 {
  459. 459● paragraphs.push(current_paragraph.copy())
  460. 460 }
  461. 461 paragraphs
  462. 462}
  463. 463
  464. 464///|
  465. 465/// 智能阅读顺序(支持多栏布局)
  466. 466pub fn smart_reading_order(
  467. 467 elements : Array[EnhancedDocumentElement],
  468. 468 layout_type : LayoutType,
  469. 469 column_boundaries : Array[Int32],
  470. 470) -> Array[Int32] raise @types.LoadError {
  471. 471● ignore(column_boundaries)
  472. 472 // 输入验证
  473. 473● if elements.length() == 0 {
  474. 474● raise @types.LoadError::DecodeFailed(
  475. 475 "smart_reading_order: 文档元素列表不能为空",
  476. 476 )
  477. 477 }
  478. 478 let indices : Array[Int32] = []
  479. 479● for i in 0..<elements.length() {
  480. 480● indices.push(i)
  481. 481 }
  482. 482 // 按列分组,然后在列内按 y 排序
  483. 483● let _ = match layout_type {
  484. 484● LayoutType::DoubleColumn => 2
  485. 485● LayoutType::TripleColumn => 3
  486. 486● _ => 1
  487. 487 }
  488. 488 // 简单排序:先按列索引,再按 y 坐标
  489. 489● for i in 0..<indices.length() {
  490. 490● for j in 0..<(indices.length() - i - 1) {
  491. 491● let a = indices[j]
  492. 492 let b = indices[j + 1]
  493. 493 let should_swap = if elements[a].column_index == elements[b].column_index {
  494. 494● elements[a].y > elements[b].y
  495. 495 } else {
  496. 496● elements[a].column_index > elements[b].column_index
  497. 497 }
  498. 498 if should_swap {
  499. 499● let temp = indices[j]
  500. 500 indices[j] = indices[j + 1]
  501. 501 indices[j + 1] = temp
  502. 502 }
  503. 503 }
  504. 504 }
  505. 505 indices
  506. 506}
  507. 507
  508. 508///|
  509. 509/// 从文本行构建增强版文档元素
  510. 510pub fn build_enhanced_elements(
  511. 511 lines : Array[TextLineAttributes],
  512. 512 page_width : Int32,
  513. 513 page_height : Int32,
  514. 514) -> EnhancedDocument raise @types.LoadError {
  515. 515 // 输入验证
  516. 516● if lines.length() == 0 {
  517. 517● raise @types.LoadError::DecodeFailed(
  518. 518 "build_enhanced_elements: 文本行列表不能为空",
  519. 519 )
  520. 520 }
  521. 521 if page_width <= 0 {
  522. 522● raise @types.LoadError::DecodeFailed(
  523. 523 "build_enhanced_elements: 页面宽度必须大于0",
  524. 524 )
  525. 525 }
  526. 526 if page_height <= 0 {
  527. 527● raise @types.LoadError::DecodeFailed(
  528. 528 "build_enhanced_elements: 页面高度必须大于0",
  529. 529 )
  530. 530 }
  531. 531 // 1. 检测布局类型
  532. 532● let layout = detect_layout_type(lines, page_width, page_height)
  533. 533 // 2. 检测页眉页脚
  534. 534● let (header_bottom, footer_top) = detect_header_footer(lines, page_height)
  535. 535 // 3. 检测列边界
  536. 536● let boundaries = detect_column_boundaries(lines, page_width, layout)
  537. 537 // 4. 计算平均字体大小
  538. 538 let mut total_font_size = 0.0
  539. 539 for line in lines {
  540. 540● total_font_size += line.font_size
  541. 541 }
  542. 542● let avg_font_size = if lines.length() > 0 {
  543. 543● total_font_size / lines.length().to_double()
  544. 544 } else {
  545. 545○ 16.0
  546. 546 }
  547. 547 // 5. 计算平均 x 坐标
  548. 548 let mut total_x = 0
  549. 549 for line in lines {
  550. 550● total_x += line.x
  551. 551 }
  552. 552◐ let avg_x = if lines.length() > 0 { total_x / lines.length() } else { 0 }
  553. 553 // 6. 构建元素
  554. 554 let elements : Array[EnhancedDocumentElement] = []
  555. 555 for line in lines {
  556. 556 // 判断是否为页眉页脚
  557. 557● let is_header = line.y + line.height <= header_bottom
  558. 558 let is_footer = line.y >= footer_top
  559. 559 // 判断列索引
  560. 560 let mut column_index = 0
  561. 561 let line_center = line.x + line.width / 2
  562. 562● for ci in 0..<(boundaries.length() / 2) {
  563. 563● let col_start = boundaries[ci * 2]
  564. 564 let col_end = boundaries[ci * 2 + 1]
  565. 565 if line_center >= col_start && line_center <= col_end {
  566. 566● column_index = ci
  567. 567 break
  568. 568 }
  569. 569 }
  570. 570 // 判断元素类型
  571. 571● let (is_heading, heading_level) = is_heading_line(line, avg_font_size)
  572. 572● let list_info = detect_list_item(line)
  573. 573● let is_code = is_code_block_line(line, avg_x)
  574. 574● let is_quote = is_quote_line(line, avg_x)
  575. 575 let element_type = if is_header || is_footer {
  576. 576● MarkdownElementType::Paragraph
  577. 577● } else if is_heading {
  578. 578● match heading_level {
  579. 579● 1 => MarkdownElementType::Heading1
  580. 580○ 2 => MarkdownElementType::Heading2
  581. 581○ _ => MarkdownElementType::Heading3
  582. 582 }
  583. 583● } else if list_info.item_type != ListItemType::None {
  584. 584● MarkdownElementType::ListItem
  585. 585● } else if is_code {
  586. 586● MarkdownElementType::CodeBlock
  587. 587● } else if is_quote {
  588. 588○ MarkdownElementType::Quote
  589. 589 } else {
  590. 590● MarkdownElementType::Paragraph
  591. 591 }
  592. 592 let element = EnhancedDocumentElement::{
  593. 593 element_type,
  594. 594 x: line.x,
  595. 595 y: line.y,
  596. 596 width: line.width,
  597. 597 height: line.height,
  598. 598 content: line.text,
  599. 599 confidence: 0.85,
  600. 600 font_size: line.font_size,
  601. 601 font_weight: line.font_weight,
  602. 602 alignment: line.alignment,
  603. 603 list_info,
  604. 604 column_index,
  605. 605 indent_level: line.indent_level,
  606. 606 is_header,
  607. 607 is_footer,
  608. 608 }
  609. 609● elements.push(element)
  610. 610 }
  611. 611 // 7. 智能阅读顺序
  612. 612● let reading_order = smart_reading_order(elements, layout, boundaries)
  613. 613 EnhancedDocument::{
  614. 614 layout_type: layout,
  615. 615● num_columns: match layout {
  616. 616● LayoutType::DoubleColumn => 2
  617. 617○ LayoutType::TripleColumn => 3
  618. 618● _ => 1
  619. 619 },
  620. 620 page_width,
  621. 621 page_height,
  622. 622 header_height: header_bottom,
  623. 623 footer_height: page_height - footer_top,
  624. 624 body_top: header_bottom,
  625. 625 body_bottom: footer_top,
  626. 626 elements,
  627. 627 reading_order,
  628. 628 column_boundaries: boundaries,
  629. 629 }
  630. 630}
  631. 631
  632. 632///|
  633. 633/// 增强版文档转 Markdown
  634. 634pub fn enhanced_document_to_markdown(
  635. 635 doc : EnhancedDocument,
  636. 636 include_header_footer~ : Bool = false,
  637. 637) -> String {
  638. 638● let include_flag = include_header_footer
  639. 639 let mut md = ""
  640. 640 // 输出布局信息(作为 HTML 注释)
  641. 641 md = md +
  642. 642 "<!-- 布局类型: " +
  643. 643● (match doc.layout_type {
  644. 644● LayoutType::SingleColumn => "单栏"
  645. 645● LayoutType::DoubleColumn => "双栏"
  646. 646● LayoutType::TripleColumn => "三栏"
  647. 647● LayoutType::MixedLayout => "混合布局"
  648. 648● LayoutType::UnknownLayout => "未知"
  649. 649 }) +
  650. 650 " -->\n\n"
  651. 651 // 按阅读顺序输出元素
  652. 652 for idx in doc.reading_order {
  653. 653● if idx < doc.elements.length() {
  654. 654● let element = doc.elements[idx]
  655. 655 // 跳过页眉页脚(除非指定包含)
  656. 656 if !include_flag && (element.is_header || element.is_footer) {
  657. 657● continue
  658. 658 }
  659. 659 // 转换元素
  660. 660● let element_md = match element.element_type {
  661. 661● MarkdownElementType::Title => "# " + element.content + "\n\n"
  662. 662● MarkdownElementType::Heading1 => "## " + element.content + "\n\n"
  663. 663● MarkdownElementType::Heading2 => "### " + element.content + "\n\n"
  664. 664● MarkdownElementType::Heading3 => "#### " + element.content + "\n\n"
  665. 665● MarkdownElementType::Paragraph => element.content + "\n\n"
  666. 666● MarkdownElementType::ListItem => {
  667. 667 let indent = " "
  668. 668 indent + "- " + element.content + "\n"
  669. 669 }
  670. 670● MarkdownElementType::Table => element.content + "\n"
  671. 671● MarkdownElementType::Image => "![图片](" + element.content + ")\n\n"
  672. 672● MarkdownElementType::Quote => "> " + element.content + "\n\n"
  673. 673 MarkdownElementType::CodeBlock =>
  674. 674● "```\n" + element.content + "\n```\n\n"
  675. 675● MarkdownElementType::HorizontalRule => "---\n\n"
  676. 676● MarkdownElementType::PageBreak => "\n\n---\n\n"
  677. 677● MarkdownElementType::Unknown => element.content + "\n\n"
  678. 678 }
  679. 679 md = md + element_md
  680. 680 }
  681. 681 }
  682. 682 md
  683. 683}
  684. 684
  685. 685///|
  686. 686/// 统计增强版文档元素分布
  687. 687pub fn enhanced_element_distribution(
  688. 688 doc : EnhancedDocument,
  689. 689) -> Array[(String, Int32)] {
  690. 690● let mut title_count = 0
  691. 691 let mut heading_count = 0
  692. 692 let mut paragraph_count = 0
  693. 693 let mut list_count = 0
  694. 694 let mut table_count = 0
  695. 695 let mut image_count = 0
  696. 696 let mut quote_count = 0
  697. 697 let mut code_count = 0
  698. 698 let mut header_count = 0
  699. 699 let mut footer_count = 0
  700. 700 for element in doc.elements {
  701. 701● match element.element_type {
  702. 702● MarkdownElementType::Title => title_count += 1
  703. 703● MarkdownElementType::Heading1 => heading_count += 1
  704. 704● MarkdownElementType::Heading2 => heading_count += 1
  705. 705● MarkdownElementType::Heading3 => heading_count += 1
  706. 706● MarkdownElementType::Paragraph => paragraph_count += 1
  707. 707● MarkdownElementType::ListItem => list_count += 1
  708. 708● MarkdownElementType::Table => table_count += 1
  709. 709● MarkdownElementType::Image => image_count += 1
  710. 710● MarkdownElementType::Quote => quote_count += 1
  711. 711● MarkdownElementType::CodeBlock => code_count += 1
  712. 712● _ => ()
  713. 713 }
  714. 714 if element.is_header {
  715. 715● header_count += 1
  716. 716 }
  717. 717 if element.is_footer {
  718. 718● footer_count += 1
  719. 719 }
  720. 720 }
  721. 721 [
  722. 722 ("标题", title_count),
  723. 723 ("小标题", heading_count),
  724. 724 ("段落", paragraph_count),
  725. 725 ("列表", list_count),
  726. 726 ("表格", table_count),
  727. 727 ("图片", image_count),
  728. 728 ("引用", quote_count),
  729. 729 ("代码", code_count),
  730. 730 ("页眉", header_count),
  731. 731 ("页脚", footer_count),
  732. 732 ]
  733. 733}