image.vision\ocr\document_understanding.mbt

86.8% · 99 / 114 points · 418 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
  3. 3///
  4. 4/// 图像处理库子模块
  5. 5/// 图像处理库子模块 Image processing library submodule
  6. 6// 文档理解
  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 DocumentElementType {
  15. 15 Title
  16. 16 Subtitle
  17. 17 Heading1
  18. 18 Heading2
  19. 19 Heading3
  20. 20 Body
  21. 21 Caption
  22. 22 Footer
  23. 23 Header
  24. 24 List
  25. 25 Table
  26. 26 Image
  27. 27 Unknown
  28. 28}
  29. 29
  30. 30///|
  31. 31pub extend DocumentElementType with @debug.Debug::{to_repr}
  32. 32
  33. 33///|
  34. 34pub extend DocumentElementType with Eq::{not_equal, equal}
  35. 35
  36. 36///|
  37. 37/// 文档元素结构体
  38. 38#derive(Eq, @debug.Debug)
  39. 39pub(all) struct DocumentElement {
  40. 40 element_type : DocumentElementType
  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 font_weight : String // "normal" / "bold"
  49. 49 reading_order : Int32
  50. 50}
  51. 51
  52. 52///|
  53. 53pub extend DocumentElement with Eq::{not_equal, equal}
  54. 54
  55. 55///|
  56. 56pub extend DocumentElement with @debug.Debug::{to_repr}
  57. 57
  58. 58///|
  59. 59/// 文档结构结构体
  60. 60#derive(Eq, @debug.Debug)
  61. 61pub(all) struct DocumentStructure {
  62. 62 elements : Array[DocumentElement]
  63. 63 num_elements : Int32
  64. 64 title : String
  65. 65 num_headings : Int32
  66. 66 num_paragraphs : Int32
  67. 67 reading_order : Array[Int32]
  68. 68 bounding_box : (Int32, Int32, Int32, Int32)
  69. 69}
  70. 70
  71. 71///|
  72. 72pub extend DocumentStructure with Eq::{not_equal, equal}
  73. 73
  74. 74///|
  75. 75pub extend DocumentStructure with @debug.Debug::{to_repr}
  76. 76
  77. 77///|
  78. 78/// 分析文档版面(检测文本块、分类元素类型)
  79. 79pub fn analyze_document_layout(
  80. 80 img : @types.Image,
  81. 81) -> DocumentStructure raise @types.LoadError {
  82. 82 // 输入验证
  83. 83● if img.width <= 0 || img.height <= 0 {
  84. 84● raise @types.LoadError::DecodeFailed(
  85. 85 "analyze_document_layout: 图像尺寸必须大于0",
  86. 86 )
  87. 87 }
  88. 88 if img.channels < 1 || img.channels > 4 {
  89. 89● raise @types.LoadError::DecodeFailed(
  90. 90 "analyze_document_layout: 通道数必须在1-4之间",
  91. 91 )
  92. 92 }
  93. 93 let expected_size = img.width * img.height * img.channels
  94. 94● if img.data.length() != expected_size {
  95. 95● raise @types.LoadError::DecodeFailed(
  96. 96 "analyze_document_layout: 数据大小不匹配,期望 " +
  97. 97● expected_size.to_string() +
  98. 98 ",实际 " +
  99. 99● img.data.length().to_string(),
  100. 100 )
  101. 101 }
  102. 102 // 1. 预处理
  103. 103● let preprocessed = ocr_preprocess(img)
  104. 104 // 2. 文本行检测
  105. 105● let lines = detect_text_lines_projection(preprocessed)
  106. 106 // 3. 文本区域检测
  107. 107● let _ = detect_text_regions(preprocessed)
  108. 108 // 4. 分类元素类型
  109. 109 let elements : Array[DocumentElement] = []
  110. 110 let mut order = 0
  111. 111 for line in lines {
  112. 112 // 根据行高和位置判断元素类型
  113. 113● let element_type = classify_element_type(line, lines)
  114. 114 let font_size = line.height
  115. 115● let font_weight = if line.height > 20 { "bold" } else { "normal" }
  116. 116● elements.push(DocumentElement::{
  117. 117 element_type,
  118. 118 x: line.x_start,
  119. 119 y: line.y_start,
  120. 120 width: line.width,
  121. 121 height: line.height,
  122. 122 text: "",
  123. 123 confidence: 0.8,
  124. 124 font_size,
  125. 125 font_weight,
  126. 126 reading_order: order,
  127. 127 })
  128. 128 order += 1
  129. 129 }
  130. 130 // 5. 计算阅读顺序(从上到下,从左到右)
  131. 131 let reading_order : Array[Int32] = []
  132. 132● for i in 0..<elements.length() {
  133. 133● reading_order.push(i)
  134. 134 }
  135. 135 // 6. 提取标题
  136. 136 let mut title = ""
  137. 137 for elem in elements {
  138. 138● if elem.element_type == DocumentElementType::Title ||
  139. 139 elem.element_type == DocumentElementType::Heading1 {
  140. 140○ title = elem.text
  141. 141 break
  142. 142 }
  143. 143 }
  144. 144 // 7. 统计
  145. 145 let mut num_headings = 0
  146. 146 let mut num_paragraphs = 0
  147. 147 for elem in elements {
  148. 148● match elem.element_type {
  149. 149○ DocumentElementType::Heading1 => num_headings += 1
  150. 150○ DocumentElementType::Heading2 => num_headings += 1
  151. 151○ DocumentElementType::Heading3 => num_headings += 1
  152. 152○ DocumentElementType::Body => num_paragraphs += 1
  153. 153● _ => ignore(())
  154. 154 }
  155. 155 }
  156. 156 // 8. 边界框
  157. 157 let mut min_x = img.width
  158. 158 let mut min_y = img.height
  159. 159 let mut max_x = 0
  160. 160 let mut max_y = 0
  161. 161 for elem in elements {
  162. 162● if elem.x < min_x {
  163. 163● min_x = elem.x
  164. 164 }
  165. 165 if elem.y < min_y {
  166. 166● min_y = elem.y
  167. 167 }
  168. 168 if elem.x + elem.width > max_x {
  169. 169● max_x = elem.x + elem.width
  170. 170 }
  171. 171 if elem.y + elem.height > max_y {
  172. 172● max_y = elem.y + elem.height
  173. 173 }
  174. 174 }
  175. 175 DocumentStructure::{
  176. 176 elements,
  177. 177● num_elements: elements.length(),
  178. 178 title,
  179. 179 num_headings,
  180. 180 num_paragraphs,
  181. 181 reading_order,
  182. 182 bounding_box: (min_x, min_y, max_x - min_x, max_y - min_y),
  183. 183 }
  184. 184}
  185. 185
  186. 186///|
  187. 187/// 分类元素类型(基于行高和位置)
  188. 188fn classify_element_type(
  189. 189 line : TextLineInfo,
  190. 190 all_lines : Array[TextLineInfo],
  191. 191) -> DocumentElementType {
  192. 192 // 计算平均行高
  193. 193● let mut avg_height = 0
  194. 194 for l in all_lines {
  195. 195● avg_height += l.height
  196. 196 }
  197. 197● if all_lines.length() > 0 {
  198. 198● avg_height = avg_height / all_lines.length()
  199. 199 }
  200. 200 // 根据行高判断
  201. 201 let height_ratio = if avg_height > 0 {
  202. 202● line.height.to_double() / avg_height.to_double()
  203. 203 } else {
  204. 204○ 1.0
  205. 205 }
  206. 206 if height_ratio > 1.8 {
  207. 207○ DocumentElementType::Title
  208. 208● } else if height_ratio > 1.5 {
  209. 209○ DocumentElementType::Heading1
  210. 210● } else if height_ratio > 1.3 {
  211. 211○ DocumentElementType::Heading2
  212. 212● } else if height_ratio > 1.15 {
  213. 213○ DocumentElementType::Heading3
  214. 214● } else if line.y_start < 30 {
  215. 215● DocumentElementType::Header
  216. 216 } else {
  217. 217○ DocumentElementType::Body
  218. 218 }
  219. 219}
  220. 220
  221. 221///|
  222. 222/// 计算阅读顺序(从上到下,从左到右)
  223. 223pub fn compute_reading_order(
  224. 224 elements : Array[DocumentElement],
  225. 225) -> Array[Int32] raise @types.LoadError {
  226. 226 // 输入验证
  227. 227● if elements.length() == 0 {
  228. 228● raise @types.LoadError::DecodeFailed(
  229. 229 "compute_reading_order: 元素列表不能为空",
  230. 230 )
  231. 231 }
  232. 232 // 按 y 坐标排序,然后按 x 坐标排序
  233. 233 let indices : Array[Int32] = []
  234. 234● for i in 0..<elements.length() {
  235. 235● indices.push(i)
  236. 236 }
  237. 237 // 简单排序(冒泡排序)
  238. 238● for _ in 0..<indices.length() {
  239. 239● for j in 0..<(indices.length() - 1) {
  240. 240● let e1 = elements[indices[j]]
  241. 241 let e2 = elements[indices[j + 1]]
  242. 242 // 先按 y 排序,再按 x 排序
  243. 243 let should_swap = if e1.y > e2.y {
  244. 244● true
  245. 245● } else if e1.y == e2.y && e1.x > e2.x {
  246. 246● true
  247. 247 } else {
  248. 248● false
  249. 249 }
  250. 250 if should_swap {
  251. 251● let temp = indices[j]
  252. 252 indices[j] = indices[j + 1]
  253. 253 indices[j + 1] = temp
  254. 254 }
  255. 255 }
  256. 256 }
  257. 257 indices
  258. 258}
  259. 259
  260. 260///|
  261. 261/// 提取标题
  262. 262pub fn extract_title(structure : DocumentStructure) -> String {
  263. 263● for elem in structure.elements {
  264. 264● if elem.element_type == DocumentElementType::Title {
  265. 265● return elem.text
  266. 266 }
  267. 267 }
  268. 268 // 如果没有标题,返回第一个大字体元素
  269. 269 for elem in structure.elements {
  270. 270● if elem.font_size > 20 {
  271. 271● return elem.text
  272. 272 }
  273. 273 }
  274. 274 ""
  275. 275}
  276. 276
  277. 277///|
  278. 278/// 提取所有标题
  279. 279pub fn extract_headings(
  280. 280 structure : DocumentStructure,
  281. 281) -> Array[DocumentElement] {
  282. 282● let headings : Array[DocumentElement] = []
  283. 283 for elem in structure.elements {
  284. 284● match elem.element_type {
  285. 285● DocumentElementType::Title => headings.push(elem)
  286. 286● DocumentElementType::Heading1 => headings.push(elem)
  287. 287● DocumentElementType::Heading2 => headings.push(elem)
  288. 288● DocumentElementType::Heading3 => headings.push(elem)
  289. 289● _ => ignore(())
  290. 290 }
  291. 291 }
  292. 292 headings
  293. 293}
  294. 294
  295. 295///|
  296. 296/// 提取正文段落
  297. 297pub fn extract_paragraphs(
  298. 298 structure : DocumentStructure,
  299. 299) -> Array[DocumentElement] {
  300. 300● let paragraphs : Array[DocumentElement] = []
  301. 301 for elem in structure.elements {
  302. 302● if elem.element_type == DocumentElementType::Body {
  303. 303● paragraphs.push(elem)
  304. 304 }
  305. 305 }
  306. 306 paragraphs
  307. 307}
  308. 308
  309. 309///|
  310. 310/// 按阅读顺序获取元素
  311. 311pub fn get_elements_in_reading_order(
  312. 312 structure : DocumentStructure,
  313. 313) -> Array[DocumentElement] {
  314. 314● let ordered : Array[DocumentElement] = []
  315. 315 for idx in structure.reading_order {
  316. 316● if idx < structure.elements.length() {
  317. 317● ordered.push(structure.elements[idx])
  318. 318 }
  319. 319 }
  320. 320 ordered
  321. 321}
  322. 322
  323. 323///|
  324. 324/// 文档结构统计
  325. 325pub fn document_structure_stats(
  326. 326 structure : DocumentStructure,
  327. 327) -> (Int32, Int32, Int32, Int32, Int32) {
  328. 328● let mut titles = 0
  329. 329 let mut headings = 0
  330. 330 let mut paragraphs = 0
  331. 331 let mut lists = 0
  332. 332 let mut images = 0
  333. 333 for elem in structure.elements {
  334. 334● match elem.element_type {
  335. 335● DocumentElementType::Title => titles += 1
  336. 336● DocumentElementType::Heading1 => headings += 1
  337. 337● DocumentElementType::Heading2 => headings += 1
  338. 338● DocumentElementType::Heading3 => headings += 1
  339. 339● DocumentElementType::Body => paragraphs += 1
  340. 340● DocumentElementType::List => lists += 1
  341. 341● DocumentElementType::Image => images += 1
  342. 342● _ => ignore(())
  343. 343 }
  344. 344 }
  345. 345 (titles, headings, paragraphs, lists, images)
  346. 346}
  347. 347
  348. 348///|
  349. 349/// 检测多栏布局并返回栏数
  350. 350pub fn detect_document_columns(
  351. 351 img : @types.Image,
  352. 352) -> Int32 raise @types.LoadError {
  353. 353 // 输入验证
  354. 354● if img.width <= 0 || img.height <= 0 {
  355. 355● raise @types.LoadError::DecodeFailed(
  356. 356 "detect_document_columns: 图像尺寸必须大于0",
  357. 357 )
  358. 358 }
  359. 359 if img.channels < 1 || img.channels > 4 {
  360. 360● raise @types.LoadError::DecodeFailed(
  361. 361 "detect_document_columns: 通道数必须在1-4之间",
  362. 362 )
  363. 363 }
  364. 364 let expected_size = img.width * img.height * img.channels
  365. 365● if img.data.length() != expected_size {
  366. 366○ raise @types.LoadError::DecodeFailed(
  367. 367 "detect_document_columns: 数据大小不匹配,期望 " +
  368. 368○ expected_size.to_string() +
  369. 369 ",实际 " +
  370. 370○ img.data.length().to_string(),
  371. 371 )
  372. 372 }
  373. 373● let (num_cols, _) = detect_columns(img)
  374. 374 num_cols
  375. 375}
  376. 376
  377. 377///|
  378. 378/// 完整文档理解流水线
  379. 379/// @deprecated 已废弃,请使用 understand_document_enhanced 代替
  380. 380#deprecated("Use understand_document_enhanced instead", skip_current_package=true)
  381. 381pub fn understand_document(
  382. 382 img : @types.Image,
  383. 383) -> DocumentStructure raise @types.LoadError {
  384. 384 // 输入验证
  385. 385 if img.width <= 0 || img.height <= 0 {
  386. 386 raise @types.LoadError::DecodeFailed(
  387. 387 "understand_document: 图像尺寸必须大于0",
  388. 388 )
  389. 389 }
  390. 390 if img.channels < 1 || img.channels > 4 {
  391. 391 raise @types.LoadError::DecodeFailed(
  392. 392 "understand_document: 通道数必须在1-4之间",
  393. 393 )
  394. 394 }
  395. 395 let expected_size = img.width * img.height * img.channels
  396. 396 if img.data.length() != expected_size {
  397. 397 raise @types.LoadError::DecodeFailed(
  398. 398 "understand_document: 数据大小不匹配,期望 " +
  399. 399 expected_size.to_string() +
  400. 400 ",实际 " +
  401. 401 img.data.length().to_string(),
  402. 402 )
  403. 403 }
  404. 404 // 1. 版面分析
  405. 405 let structure = analyze_document_layout(img)
  406. 406 // 2. 计算阅读顺序
  407. 407 let order = compute_reading_order(structure.elements)
  408. 408 // 3. 更新阅读顺序
  409. 409 DocumentStructure::{
  410. 410 elements: structure.elements,
  411. 411 num_elements: structure.num_elements,
  412. 412 title: extract_title(structure),
  413. 413 num_headings: structure.num_headings,
  414. 414 num_paragraphs: structure.num_paragraphs,
  415. 415 reading_order: order,
  416. 416 bounding_box: structure.bounding_box,
  417. 417 }
  418. 418}