image.vision\ocr\batch_processing.mbt

83.3% · 95 / 114 points · 566 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/batch_processing
  3. 3///
  4. 4/// 图像处理库子模块
  5. 5/// 图像处理库子模块 Image processing library submodule
  6. 6// OCR 批处理引擎(v12.25.0 P4 工程化)
  7. 7// 批量文档处理、进度跟踪、错误恢复、结果汇总、内存管理、性能优化
  8. 8
  9. 9///|
  10. 10/// 批处理配置
  11. 11#derive(Eq, @debug.Debug)
  12. 12pub(all) struct BatchOcrConfig {
  13. 13 max_concurrent : Int32 // 最大并发数
  14. 14 batch_size : Int32 // 每批处理数量
  15. 15 enable_progress_callback : Bool // 是否启用进度回调
  16. 16 enable_error_recovery : Bool // 是否启用错误恢复
  17. 17 output_format : String // 输出格式:"text" / "hocr" / "json" / "markdown"
  18. 18 dpi : Int32 // 处理 DPI
  19. 19 preprocess_config : String // 预处理配置:"auto" / "standard" / "enhanced" / "heavy"
  20. 20 save_intermediate : Bool // 是否保存中间结果
  21. 21 output_directory : String // 输出目录
  22. 22}
  23. 23
  24. 24///|
  25. 25pub extend BatchOcrConfig with Eq::{not_equal, equal}
  26. 26
  27. 27///|
  28. 28pub extend BatchOcrConfig with @debug.Debug::{to_repr}
  29. 29
  30. 30///|
  31. 31/// 批处理任务状态
  32. 32#derive(Eq, @debug.Debug)
  33. 33pub(all) enum BatchTaskStatus {
  34. 34 Pending
  35. 35 Processing
  36. 36 Completed
  37. 37 Failed
  38. 38 Skipped
  39. 39}
  40. 40
  41. 41///|
  42. 42pub extend BatchTaskStatus with @debug.Debug::{to_repr}
  43. 43
  44. 44///|
  45. 45pub extend BatchTaskStatus with Eq::{not_equal, equal}
  46. 46
  47. 47///|
  48. 48/// 单个批处理任务
  49. 49#derive(Eq, @debug.Debug)
  50. 50pub(all) struct BatchTask {
  51. 51 task_id : String
  52. 52 input_path : String
  53. 53 output_path : String
  54. 54 status : BatchTaskStatus
  55. 55 progress : Double
  56. 56 error_message : String
  57. 57 start_time : Double
  58. 58 end_time : Double
  59. 59 page_count : Int32
  60. 60 char_count : Int32
  61. 61 accuracy_estimate : Double
  62. 62}
  63. 63
  64. 64///|
  65. 65pub extend BatchTask with Eq::{not_equal, equal}
  66. 66
  67. 67///|
  68. 68pub extend BatchTask with @debug.Debug::{to_repr}
  69. 69
  70. 70///|
  71. 71/// 批处理进度
  72. 72#derive(Eq, @debug.Debug)
  73. 73pub(all) struct BatchProgress {
  74. 74 total_tasks : Int32
  75. 75 completed_tasks : Int32
  76. 76 failed_tasks : Int32
  77. 77 skipped_tasks : Int32
  78. 78 current_task_index : Int32
  79. 79 overall_progress : Double
  80. 80 current_task_progress : Double
  81. 81 elapsed_time_ms : Double
  82. 82 estimated_remaining_ms : Double
  83. 83 pages_per_second : Double
  84. 84 chars_per_second : Double
  85. 85}
  86. 86
  87. 87///|
  88. 88pub extend BatchProgress with Eq::{not_equal, equal}
  89. 89
  90. 90///|
  91. 91pub extend BatchProgress with @debug.Debug::{to_repr}
  92. 92
  93. 93///|
  94. 94/// 批处理结果汇总
  95. 95#derive(Eq, @debug.Debug)
  96. 96pub(all) struct BatchResultSummary {
  97. 97 total_tasks : Int32
  98. 98 successful_tasks : Int32
  99. 99 failed_tasks : Int32
  100. 100 skipped_tasks : Int32
  101. 101 success_rate : Double
  102. 102 total_pages : Int32
  103. 103 total_chars : Int32
  104. 104 total_time_ms : Double
  105. 105 average_accuracy : Double
  106. 106 average_pages_per_second : Double
  107. 107 average_chars_per_second : Double
  108. 108 failed_task_ids : Array[String]
  109. 109 output_files : Array[String]
  110. 110}
  111. 111
  112. 112///|
  113. 113pub extend BatchResultSummary with Eq::{not_equal, equal}
  114. 114
  115. 115///|
  116. 116pub extend BatchResultSummary with @debug.Debug::{to_repr}
  117. 117
  118. 118///|
  119. 119/// 内存使用统计
  120. 120#derive(Eq, @debug.Debug)
  121. 121pub(all) struct MemoryUsageStats {
  122. 122 current_usage_mb : Double
  123. 123 peak_usage_mb : Double
  124. 124 average_usage_mb : Double
  125. 125 total_allocated : Int32
  126. 126 total_freed : Int32
  127. 127 gc_count : Int32
  128. 128}
  129. 129
  130. 130///|
  131. 131pub extend MemoryUsageStats with Eq::{not_equal, equal}
  132. 132
  133. 133///|
  134. 134pub extend MemoryUsageStats with @debug.Debug::{to_repr}
  135. 135
  136. 136///|
  137. 137/// 创建默认批处理配置
  138. 138pub fn create_default_batch_config() -> BatchOcrConfig {
  139. 139● BatchOcrConfig::{
  140. 140 max_concurrent: 2,
  141. 141 batch_size: 10,
  142. 142 enable_progress_callback: true,
  143. 143 enable_error_recovery: true,
  144. 144 output_format: "markdown",
  145. 145 dpi: 300,
  146. 146 preprocess_config: "auto",
  147. 147 save_intermediate: false,
  148. 148 output_directory: "./ocr_output",
  149. 149 }
  150. 150}
  151. 151
  152. 152///|
  153. 153/// 创建批处理任务列表
  154. 154pub fn create_batch_tasks(
  155. 155 input_files : Array[String],
  156. 156 output_directory : String,
  157. 157 output_format : String,
  158. 158) -> Array[BatchTask] raise @types.LoadError {
  159. 159 // 输入验证
  160. 160● if input_files.length() == 0 {
  161. 161● raise @types.LoadError::DecodeFailed(
  162. 162 "create_batch_tasks: 输入文件列表不能为空",
  163. 163 )
  164. 164 }
  165. 165● if output_directory.length() == 0 {
  166. 166● raise @types.LoadError::DecodeFailed(
  167. 167 "create_batch_tasks: 输出目录不能为空",
  168. 168 )
  169. 169 }
  170. 170● if output_format.length() == 0 {
  171. 171● raise @types.LoadError::DecodeFailed(
  172. 172 "create_batch_tasks: 输出格式不能为空",
  173. 173 )
  174. 174 }
  175. 175 let tasks : Array[BatchTask] = []
  176. 176● for i in 0..<input_files.length() {
  177. 177● let input_path = input_files[i]
  178. 178 // 生成输出路径
  179. 179● let extension = match output_format {
  180. 180● "text" => ".txt"
  181. 181○ "hocr" => ".hocr"
  182. 182○ "json" => ".json"
  183. 183● "markdown" => ".md"
  184. 184○ _ => ".txt"
  185. 185 }
  186. 186● let output_path = output_directory + "/output_" + i.to_string() + extension
  187. 187● let task_id = "task_" + i.to_string()
  188. 188● tasks.push(BatchTask::{
  189. 189 task_id,
  190. 190 input_path,
  191. 191 output_path,
  192. 192 status: BatchTaskStatus::Pending,
  193. 193 progress: 0.0,
  194. 194 error_message: "",
  195. 195 start_time: 0.0,
  196. 196 end_time: 0.0,
  197. 197 page_count: 0,
  198. 198 char_count: 0,
  199. 199 accuracy_estimate: 0.0,
  200. 200 })
  201. 201 }
  202. 202 tasks
  203. 203}
  204. 204
  205. 205///|
  206. 206/// 更新任务进度
  207. 207pub fn update_task_progress(
  208. 208 task : BatchTask,
  209. 209 progress : Double,
  210. 210 current_page : Int32,
  211. 211 total_pages : Int32,
  212. 212) -> BatchTask {
  213. 213● ignore(current_page)
  214. 214 let new_progress = if progress > 1.0 {
  215. 215○ 1.0
  216. 216● } else if progress < 0.0 {
  217. 217○ 0.0
  218. 218 } else {
  219. 219● progress
  220. 220 }
  221. 221 BatchTask::{
  222. 222 task_id: task.task_id,
  223. 223 input_path: task.input_path,
  224. 224 output_path: task.output_path,
  225. 225 status: BatchTaskStatus::Processing,
  226. 226 progress: new_progress,
  227. 227 error_message: task.error_message,
  228. 228 start_time: task.start_time,
  229. 229 end_time: task.end_time,
  230. 230 page_count: total_pages,
  231. 231 char_count: task.char_count,
  232. 232 accuracy_estimate: task.accuracy_estimate,
  233. 233 }
  234. 234}
  235. 235
  236. 236///|
  237. 237/// 标记任务完成
  238. 238pub fn mark_task_completed(
  239. 239 task : BatchTask,
  240. 240 char_count : Int32,
  241. 241 accuracy : Double,
  242. 242 end_time : Double,
  243. 243) -> BatchTask {
  244. 244● BatchTask::{
  245. 245 task_id: task.task_id,
  246. 246 input_path: task.input_path,
  247. 247 output_path: task.output_path,
  248. 248 status: BatchTaskStatus::Completed,
  249. 249 progress: 1.0,
  250. 250 error_message: "",
  251. 251 start_time: task.start_time,
  252. 252 end_time,
  253. 253 page_count: task.page_count,
  254. 254 char_count,
  255. 255 accuracy_estimate: accuracy,
  256. 256 }
  257. 257}
  258. 258
  259. 259///|
  260. 260/// 标记任务失败
  261. 261pub fn mark_task_failed(
  262. 262 task : BatchTask,
  263. 263 error_message : String,
  264. 264 end_time : Double,
  265. 265) -> BatchTask {
  266. 266● BatchTask::{
  267. 267 task_id: task.task_id,
  268. 268 input_path: task.input_path,
  269. 269 output_path: task.output_path,
  270. 270 status: BatchTaskStatus::Failed,
  271. 271 progress: task.progress,
  272. 272 error_message,
  273. 273 start_time: task.start_time,
  274. 274 end_time,
  275. 275 page_count: task.page_count,
  276. 276 char_count: task.char_count,
  277. 277 accuracy_estimate: 0.0,
  278. 278 }
  279. 279}
  280. 280
  281. 281///|
  282. 282/// 计算批处理进度
  283. 283pub fn calculate_batch_progress(
  284. 284 tasks : Array[BatchTask],
  285. 285 elapsed_time_ms : Double,
  286. 286) -> BatchProgress raise @types.LoadError {
  287. 287 // 输入验证
  288. 288● if tasks.length() == 0 {
  289. 289● raise @types.LoadError::DecodeFailed(
  290. 290 "calculate_batch_progress: 任务列表不能为空",
  291. 291 )
  292. 292 }
  293. 293 if elapsed_time_ms < 0.0 {
  294. 294○ raise @types.LoadError::DecodeFailed(
  295. 295 "calculate_batch_progress: 已用时间不能为负数",
  296. 296 )
  297. 297 }
  298. 298 let mut completed = 0
  299. 299 let mut failed = 0
  300. 300 let mut skipped = 0
  301. 301 let mut current_index = 0
  302. 302 let mut total_progress = 0.0
  303. 303 let mut current_progress = 0.0
  304. 304 let mut total_pages = 0
  305. 305 let mut total_chars = 0
  306. 306
  307. 307● for i in 0..<tasks.length() {
  308. 308● let task = tasks[i]
  309. 309● match task.status {
  310. 310● BatchTaskStatus::Completed => {
  311. 311 completed += 1
  312. 312 total_progress += 1.0
  313. 313 total_pages += task.page_count
  314. 314 total_chars += task.char_count
  315. 315 }
  316. 316● BatchTaskStatus::Failed => {
  317. 317 failed += 1
  318. 318 total_progress += task.progress
  319. 319 }
  320. 320○ BatchTaskStatus::Skipped => skipped += 1
  321. 321● BatchTaskStatus::Processing => {
  322. 322 current_index = i
  323. 323 current_progress = task.progress
  324. 324 total_progress += task.progress
  325. 325 }
  326. 326○ BatchTaskStatus::Pending => ()
  327. 327 }
  328. 328 }
  329. 329
  330. 330● let overall = if tasks.length() > 0 {
  331. 331● total_progress / tasks.length().to_double()
  332. 332 } else {
  333. 333○ 0.0
  334. 334 }
  335. 335 let elapsed_seconds = elapsed_time_ms / 1000.0
  336. 336 let pages_per_second = if elapsed_seconds > 0 {
  337. 337● total_pages.to_double() / elapsed_seconds
  338. 338 } else {
  339. 339○ 0.0
  340. 340 }
  341. 341 let chars_per_second = if elapsed_seconds > 0 {
  342. 342● total_chars.to_double() / elapsed_seconds
  343. 343 } else {
  344. 344○ 0.0
  345. 345 }
  346. 346
  347. 347 // 估算剩余时间
  348. 348 let estimated_remaining = if completed > 0 {
  349. 349● let avg_time_per_task = elapsed_time_ms / completed.to_double()
  350. 350● let remaining_tasks = tasks.length() - completed - failed
  351. 351● avg_time_per_task * remaining_tasks.to_double()
  352. 352 } else {
  353. 353○ 0.0
  354. 354 }
  355. 355
  356. 356 BatchProgress::{
  357. 357● total_tasks: tasks.length(),
  358. 358 completed_tasks: completed,
  359. 359 failed_tasks: failed,
  360. 360 skipped_tasks: skipped,
  361. 361 current_task_index: current_index,
  362. 362 overall_progress: overall,
  363. 363 current_task_progress: current_progress,
  364. 364 elapsed_time_ms,
  365. 365 estimated_remaining_ms: estimated_remaining,
  366. 366 pages_per_second,
  367. 367 chars_per_second,
  368. 368 }
  369. 369}
  370. 370
  371. 371///|
  372. 372/// 生成批处理结果汇总
  373. 373pub fn generate_batch_summary(
  374. 374 tasks : Array[BatchTask],
  375. 375 total_time_ms : Double,
  376. 376) -> BatchResultSummary raise @types.LoadError {
  377. 377 // 输入验证
  378. 378● if tasks.length() == 0 {
  379. 379● raise @types.LoadError::DecodeFailed(
  380. 380 "generate_batch_summary: 任务列表不能为空",
  381. 381 )
  382. 382 }
  383. 383 if total_time_ms < 0.0 {
  384. 384○ raise @types.LoadError::DecodeFailed(
  385. 385 "generate_batch_summary: 总时间不能为负数",
  386. 386 )
  387. 387 }
  388. 388 let mut successful = 0
  389. 389 let mut failed = 0
  390. 390 let mut skipped = 0
  391. 391 let mut total_pages = 0
  392. 392 let mut total_chars = 0
  393. 393 let mut total_accuracy = 0.0
  394. 394 let failed_ids : Array[String] = []
  395. 395 let output_files : Array[String] = []
  396. 396
  397. 397 for task in tasks {
  398. 398● match task.status {
  399. 399● BatchTaskStatus::Completed => {
  400. 400 successful += 1
  401. 401 total_pages += task.page_count
  402. 402 total_chars += task.char_count
  403. 403 total_accuracy += task.accuracy_estimate
  404. 404● output_files.push(task.output_path)
  405. 405 }
  406. 406● BatchTaskStatus::Failed => {
  407. 407 failed += 1
  408. 408● failed_ids.push(task.task_id)
  409. 409 }
  410. 410○ BatchTaskStatus::Skipped => skipped += 1
  411. 411○ _ => ()
  412. 412 }
  413. 413 }
  414. 414
  415. 415● let success_rate = if tasks.length() > 0 {
  416. 416● successful.to_double() / tasks.length().to_double()
  417. 417 } else {
  418. 418○ 0.0
  419. 419 }
  420. 420 let avg_accuracy = if successful > 0 {
  421. 421● total_accuracy / successful.to_double()
  422. 422 } else {
  423. 423○ 0.0
  424. 424 }
  425. 425 let total_seconds = total_time_ms / 1000.0
  426. 426 let avg_pages_per_second = if total_seconds > 0 {
  427. 427● total_pages.to_double() / total_seconds
  428. 428 } else {
  429. 429○ 0.0
  430. 430 }
  431. 431 let avg_chars_per_second = if total_seconds > 0 {
  432. 432● total_chars.to_double() / total_seconds
  433. 433 } else {
  434. 434○ 0.0
  435. 435 }
  436. 436
  437. 437 BatchResultSummary::{
  438. 438● total_tasks: tasks.length(),
  439. 439 successful_tasks: successful,
  440. 440 failed_tasks: failed,
  441. 441 skipped_tasks: skipped,
  442. 442 success_rate,
  443. 443 total_pages,
  444. 444 total_chars,
  445. 445 total_time_ms,
  446. 446 average_accuracy: avg_accuracy,
  447. 447 average_pages_per_second: avg_pages_per_second,
  448. 448 average_chars_per_second: avg_chars_per_second,
  449. 449 failed_task_ids: failed_ids,
  450. 450 output_files,
  451. 451 }
  452. 452}
  453. 453
  454. 454///|
  455. 455/// 生成批处理报告
  456. 456pub fn batch_summary_to_string(summary : BatchResultSummary) -> String {
  457. 457● let mut report = "## OCR 批处理结果报告\n\n"
  458. 458 report = report + "### 整体统计\n\n"
  459. 459 report = report + "| 指标 | 数值 |\n"
  460. 460 report = report + "|------|------|\n"
  461. 461 report = report +
  462. 462 "| 总任务数 | " +
  463. 463● summary.total_tasks.to_string() +
  464. 464 " |\n"
  465. 465 report = report +
  466. 466 "| 成功任务 | " +
  467. 467● summary.successful_tasks.to_string() +
  468. 468 " |\n"
  469. 469 report = report +
  470. 470 "| 失败任务 | " +
  471. 471● summary.failed_tasks.to_string() +
  472. 472 " |\n"
  473. 473 report = report +
  474. 474 "| 跳过任务 | " +
  475. 475● summary.skipped_tasks.to_string() +
  476. 476 " |\n"
  477. 477 report = report +
  478. 478 "| **成功率** | **" +
  479. 479● (summary.success_rate * 100.0).to_string() +
  480. 480 "%** |\n"
  481. 481● report = report + "| 总页数 | " + summary.total_pages.to_string() + " |\n"
  482. 482 report = report +
  483. 483 "| 总字符数 | " +
  484. 484● summary.total_chars.to_string() +
  485. 485 " |\n"
  486. 486 report = report +
  487. 487 "| 总耗时 | " +
  488. 488● (summary.total_time_ms / 1000.0).to_string() +
  489. 489 " 秒 |\n"
  490. 490 report = report +
  491. 491 "| 平均准确率 | " +
  492. 492● (summary.average_accuracy * 100.0).to_string() +
  493. 493 "% |\n"
  494. 494 report = report +
  495. 495 "| 处理速度 | " +
  496. 496● summary.average_pages_per_second.to_string() +
  497. 497 " 页/秒 |\n"
  498. 498 report = report +
  499. 499 "| 识别速度 | " +
  500. 500● summary.average_chars_per_second.to_string() +
  501. 501 " 字符/秒 |\n\n"
  502. 502
  503. 503 if summary.failed_tasks > 0 {
  504. 504● report = report + "### 失败任务列表\n\n"
  505. 505● for i in 0..<summary.failed_task_ids.length() {
  506. 506● report = report +
  507. 507● (i + 1).to_string() +
  508. 508 ". " +
  509. 509 summary.failed_task_ids[i] +
  510. 510 "\n"
  511. 511 }
  512. 512 report = report + "\n"
  513. 513 }
  514. 514
  515. 515 report = report + "### 输出文件\n\n"
  516. 516● for i in 0..<summary.output_files.length() {
  517. 517● report = report +
  518. 518● (i + 1).to_string() +
  519. 519 ". " +
  520. 520 summary.output_files[i] +
  521. 521 "\n"
  522. 522 }
  523. 523
  524. 524 report
  525. 525}
  526. 526
  527. 527///|
  528. 528/// 生成进度条字符串
  529. 529pub fn progress_bar_to_string(progress : Double, width~ : Int32 = 30) -> String {
  530. 530● let bar_width = width
  531. 531● let filled = (progress * bar_width.to_double()).to_int()
  532. 532 let mut bar = "["
  533. 533 for i in 0..<bar_width {
  534. 534● if i < filled {
  535. 535● bar = bar + "="
  536. 536● } else if i == filled {
  537. 537● bar = bar + ">"
  538. 538 } else {
  539. 539● bar = bar + " "
  540. 540 }
  541. 541 }
  542. 542● bar = bar + "] " + (progress * 100.0).to_string() + "%"
  543. 543 bar
  544. 544}
  545. 545
  546. 546///|
  547. 547/// 估算内存使用(简化版)
  548. 548pub fn estimate_memory_usage(
  549. 549 image_count : Int32,
  550. 550 image_width : Int32,
  551. 551 image_height : Int32,
  552. 552 channels : Int32,
  553. 553) -> MemoryUsageStats {
  554. 554● let per_image_mb = (image_width * image_height * channels).to_double() /
  555. 555 (1024.0 * 1024.0)
  556. 556 let current_usage = per_image_mb * 3.0 // 原图+预处理+二值化
  557. 557● let peak_usage = per_image_mb * image_count.to_double() * 1.5
  558. 558 MemoryUsageStats::{
  559. 559 current_usage_mb: current_usage,
  560. 560 peak_usage_mb: peak_usage,
  561. 561 average_usage_mb: (current_usage + peak_usage) / 2.0,
  562. 562 total_allocated: image_count * 3,
  563. 563 total_freed: image_count * 2,
  564. 564 gc_count: image_count,
  565. 565 }
  566. 566}