image.vision\ocr\accuracy_testing.mbt

88% · 169 / 192 points · 599 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/accuracy_testing
  3. 3///
  4. 4/// 图像处理库子模块
  5. 5/// Image processing library submodule
  6. 6// OCR 准确率测试框架(v12.21.0 P0 基础加固)
  7. 7// 提供准确率计算、混淆矩阵、错误分析、基准测试等工具
  8. 8
  9. 9///|
  10. 10/// 字符识别结果
  11. 11#derive(Eq, @debug.Debug)
  12. 12pub(all) struct CharRecognitionResult {
  13. 13 expected : String
  14. 14 actual : String
  15. 15 is_correct : Bool
  16. 16 confidence : Double
  17. 17 x : Int32
  18. 18 y : Int32
  19. 19}
  20. 20
  21. 21///|
  22. 22pub extend CharRecognitionResult with Eq::{not_equal, equal}
  23. 23
  24. 24///|
  25. 25pub extend CharRecognitionResult with @debug.Debug::{to_repr}
  26. 26
  27. 27///|
  28. 28/// 准确率统计
  29. 29#derive(Eq, @debug.Debug)
  30. 30pub(all) struct AccuracyStats {
  31. 31 total_chars : Int32
  32. 32 correct_chars : Int32
  33. 33 char_accuracy : Double
  34. 34 total_words : Int32
  35. 35 correct_words : Int32
  36. 36 word_accuracy : Double
  37. 37 total_lines : Int32
  38. 38 correct_lines : Int32
  39. 39 line_accuracy : Double
  40. 40 false_positives : Int32
  41. 41 false_negatives : Int32
  42. 42 precision : Double
  43. 43 recall : Double
  44. 44 f1_score : Double
  45. 45}
  46. 46
  47. 47///|
  48. 48pub extend AccuracyStats with Eq::{not_equal, equal}
  49. 49
  50. 50///|
  51. 51pub extend AccuracyStats with @debug.Debug::{to_repr}
  52. 52
  53. 53///|
  54. 54/// 混淆矩阵条目
  55. 55#derive(Eq, @debug.Debug)
  56. 56pub(all) struct ConfusionEntry {
  57. 57 expected : String
  58. 58 actual : String
  59. 59 count : Int32
  60. 60}
  61. 61
  62. 62///|
  63. 63pub extend ConfusionEntry with Eq::{not_equal, equal}
  64. 64
  65. 65///|
  66. 66pub extend ConfusionEntry with @debug.Debug::{to_repr}
  67. 67
  68. 68///|
  69. 69/// 混淆矩阵
  70. 70#derive(Eq, @debug.Debug)
  71. 71pub(all) struct ConfusionMatrix {
  72. 72 entries : Array[ConfusionEntry]
  73. 73 total_errors : Int32
  74. 74}
  75. 75
  76. 76///|
  77. 77pub extend ConfusionMatrix with Eq::{not_equal, equal}
  78. 78
  79. 79///|
  80. 80pub extend ConfusionMatrix with @debug.Debug::{to_repr}
  81. 81
  82. 82///|
  83. 83/// 错误类型
  84. 84/// `#non_exhaustive` 表示未来可能添加新构造器
  85. 85#derive(Eq, @debug.Debug)
  86. 86#non_exhaustive
  87. 87pub(all) enum OcrErrorType {
  88. 88 Substitution // 替换错误(A→B)
  89. 89 Insertion // 插入错误(多识别了字符)
  90. 90 Deletion // 删除错误(漏识别了字符)
  91. 91 Reorder // 顺序错误
  92. 92 Unknown
  93. 93}
  94. 94
  95. 95///|
  96. 96pub extend OcrErrorType with @debug.Debug::{to_repr}
  97. 97
  98. 98///|
  99. 99pub extend OcrErrorType with Eq::{not_equal, equal}
  100. 100
  101. 101///|
  102. 102/// 错误分析条目
  103. 103#derive(Eq, @debug.Debug)
  104. 104pub(all) struct ErrorAnalysisEntry {
  105. 105 error_type : OcrErrorType
  106. 106 expected : String
  107. 107 actual : String
  108. 108 context_before : String
  109. 109 context_after : String
  110. 110 confidence : Double
  111. 111 count : Int32
  112. 112}
  113. 113
  114. 114///|
  115. 115pub extend ErrorAnalysisEntry with Eq::{not_equal, equal}
  116. 116
  117. 117///|
  118. 118pub extend ErrorAnalysisEntry with @debug.Debug::{to_repr}
  119. 119
  120. 120///|
  121. 121/// 错误分析报告
  122. 122#derive(Eq, @debug.Debug)
  123. 123pub(all) struct ErrorAnalysisReport {
  124. 124 total_errors : Int32
  125. 125 substitution_count : Int32
  126. 126 insertion_count : Int32
  127. 127 deletion_count : Int32
  128. 128 reorder_count : Int32
  129. 129 top_errors : Array[ErrorAnalysisEntry]
  130. 130 suggestions : Array[String]
  131. 131}
  132. 132
  133. 133///|
  134. 134pub extend ErrorAnalysisReport with Eq::{not_equal, equal}
  135. 135
  136. 136///|
  137. 137pub extend ErrorAnalysisReport with @debug.Debug::{to_repr}
  138. 138
  139. 139///|
  140. 140/// 性能基准结果
  141. 141#derive(Eq, @debug.Debug)
  142. 142pub(all) struct PerformanceBenchmark {
  143. 143 total_time_ms : Double
  144. 144 preprocess_time_ms : Double
  145. 145 layout_time_ms : Double
  146. 146 recognition_time_ms : Double
  147. 147 postprocess_time_ms : Double
  148. 148 pages_per_second : Double
  149. 149 chars_per_second : Double
  150. 150 memory_usage_mb : Double
  151. 151 cpu_usage_percent : Double
  152. 152}
  153. 153
  154. 154///|
  155. 155pub extend PerformanceBenchmark with Eq::{not_equal, equal}
  156. 156
  157. 157///|
  158. 158pub extend PerformanceBenchmark with @debug.Debug::{to_repr}
  159. 159
  160. 160///|
  161. 161/// 计算字符级准确率
  162. 162pub fn calculate_char_accuracy(expected : String, actual : String) -> Double {
  163. 163● if expected.length() == 0 {
  164. 164● return if actual.length() == 0 { 1.0 } else { 0.0 }
  165. 165 }
  166. 166 let mut correct = 0
  167. 167● let min_len = if expected.length() < actual.length() {
  168. 168● expected.length()
  169. 169 } else {
  170. 170● actual.length()
  171. 171 }
  172. 172 for i in 0..<min_len {
  173. 173● if expected[i] == actual[i] {
  174. 174● correct += 1
  175. 175 }
  176. 176 }
  177. 177● correct.to_double() / expected.length().to_double()
  178. 178}
  179. 179
  180. 180///|
  181. 181/// 计算词级准确率
  182. 182pub fn calculate_word_accuracy(expected : String, actual : String) -> Double {
  183. 183● let expected_words = split_words(expected)
  184. 184● let actual_words = split_words(actual)
  185. 185● if expected_words.length() == 0 {
  186. 186◐ return if actual_words.length() == 0 { 1.0 } else { 0.0 }
  187. 187 }
  188. 188 let mut correct = 0
  189. 189● let min_len = if expected_words.length() < actual_words.length() {
  190. 190○ expected_words.length()
  191. 191 } else {
  192. 192● actual_words.length()
  193. 193 }
  194. 194 for i in 0..<min_len {
  195. 195● if expected_words[i] == actual_words[i] {
  196. 196● correct += 1
  197. 197 }
  198. 198 }
  199. 199● correct.to_double() / expected_words.length().to_double()
  200. 200}
  201. 201
  202. 202///|
  203. 203/// 简单分词(按空格和标点分割)
  204. 204fn split_words(text : String) -> Array[String] {
  205. 205● let words : Array[String] = []
  206. 206 let mut current = ""
  207. 207● for i in 0..<text.length() {
  208. 208● let c = text[i]
  209. 209 if c == ' ' ||
  210. 210 c == '\n' ||
  211. 211 c == '\t' ||
  212. 212 c == ',' ||
  213. 213 c == '.' ||
  214. 214 c == ',' ||
  215. 215 c == '。' ||
  216. 216 c == ';' ||
  217. 217 c == ':' {
  218. 218● if current.length() > 0 {
  219. 219● words.push(current)
  220. 220 current = ""
  221. 221 }
  222. 222 } else {
  223. 223● current = current + c.to_string()
  224. 224 }
  225. 225 }
  226. 226● if current.length() > 0 {
  227. 227● words.push(current)
  228. 228 }
  229. 229 words
  230. 230}
  231. 231
  232. 232///|
  233. 233/// 计算编辑距离(Levenshtein)
  234. 234pub fn calculate_edit_distance(s1 : String, s2 : String) -> Int32 {
  235. 235● let m = s1.length()
  236. 236● let n = s2.length()
  237. 237 if m == 0 {
  238. 238● return n
  239. 239 }
  240. 240 if n == 0 {
  241. 241● return m
  242. 242 }
  243. 243 // 使用滚动数组优化空间
  244. 244 let mut prev : Array[Int32] = []
  245. 245 let mut curr : Array[Int32] = []
  246. 246 for j in 0..<(n + 1) {
  247. 247● prev.push(j)
  248. 248● curr.push(0)
  249. 249 }
  250. 250 for i in 1..<(m + 1) {
  251. 251● curr[0] = i
  252. 252 for j in 1..<(n + 1) {
  253. 253● let cost = if s1[i - 1] == s2[j - 1] { 0 } else { 1 }
  254. 254 let del = prev[j] + 1
  255. 255 let ins = curr[j - 1] + 1
  256. 256 let sub = prev[j - 1] + cost
  257. 257 curr[j] = if del < ins {
  258. 258● if del < sub {
  259. 259● del
  260. 260 } else {
  261. 261● sub
  262. 262 }
  263. 263● } else if ins < sub {
  264. 264● ins
  265. 265 } else {
  266. 266● sub
  267. 267 }
  268. 268 }
  269. 269 let temp = prev
  270. 270 prev = curr
  271. 271 curr = temp
  272. 272 }
  273. 273 prev[n]
  274. 274}
  275. 275
  276. 276///|
  277. 277/// 计算完整准确率统计
  278. 278pub fn calculate_accuracy_stats(
  279. 279 expected_lines : Array[String],
  280. 280 actual_lines : Array[String],
  281. 281) -> AccuracyStats raise @types.LoadError {
  282. 282 // 输入验证
  283. 283● if expected_lines.length() == 0 {
  284. 284● raise @types.LoadError::DecodeFailed(
  285. 285 "calculate_accuracy_stats: 期望文本行列表不能为空",
  286. 286 )
  287. 287 }
  288. 288● if actual_lines.length() == 0 {
  289. 289● raise @types.LoadError::DecodeFailed(
  290. 290 "calculate_accuracy_stats: 实际文本行列表不能为空",
  291. 291 )
  292. 292 }
  293. 293 let mut total_chars = 0
  294. 294 let mut correct_chars = 0
  295. 295 let mut total_words = 0
  296. 296 let mut correct_words = 0
  297. 297● let total_lines = expected_lines.length()
  298. 298 let mut correct_lines = 0
  299. 299 let mut false_positives = 0
  300. 300 let mut false_negatives = 0
  301. 301
  302. 302● let min_lines = if expected_lines.length() < actual_lines.length() {
  303. 303○ expected_lines.length()
  304. 304 } else {
  305. 305● actual_lines.length()
  306. 306 }
  307. 307
  308. 308 for i in 0..<min_lines {
  309. 309● let expected = expected_lines[i]
  310. 310 let actual = actual_lines[i]
  311. 311● total_chars += expected.length()
  312. 312 let mut line_correct = 0
  313. 313● let min_chars = if expected.length() < actual.length() {
  314. 314○ expected.length()
  315. 315 } else {
  316. 316● actual.length()
  317. 317 }
  318. 318 for j in 0..<min_chars {
  319. 319● if expected[j] == actual[j] {
  320. 320● correct_chars += 1
  321. 321 line_correct += 1
  322. 322 }
  323. 323 }
  324. 324● if actual.length() > expected.length() {
  325. 325○ false_positives += actual.length() - expected.length()
  326. 326 } else {
  327. 327● false_negatives += expected.length() - actual.length()
  328. 328 }
  329. 329● if line_correct == expected.length() && expected.length() == actual.length() {
  330. 330● correct_lines += 1
  331. 331 }
  332. 332 // 词级准确率
  333. 333● let exp_words = split_words(expected)
  334. 334● let act_words = split_words(actual)
  335. 335● total_words += exp_words.length()
  336. 336● let min_words = if exp_words.length() < act_words.length() {
  337. 337○ exp_words.length()
  338. 338 } else {
  339. 339● act_words.length()
  340. 340 }
  341. 341 for j in 0..<min_words {
  342. 342● if exp_words[j] == act_words[j] {
  343. 343● correct_words += 1
  344. 344 }
  345. 345 }
  346. 346 }
  347. 347
  348. 348 // 多出的行
  349. 349● if actual_lines.length() > expected_lines.length() {
  350. 350○ for i in expected_lines.length()..<actual_lines.length() {
  351. 351○ false_positives += actual_lines[i].length()
  352. 352 }
  353. 353 } else {
  354. 354● for i in actual_lines.length()..<expected_lines.length() {
  355. 355● false_negatives += expected_lines[i].length()
  356. 356 }
  357. 357 }
  358. 358
  359. 359 let char_accuracy = if total_chars > 0 {
  360. 360● correct_chars.to_double() / total_chars.to_double()
  361. 361 } else {
  362. 362○ 1.0
  363. 363 }
  364. 364 let word_accuracy = if total_words > 0 {
  365. 365● correct_words.to_double() / total_words.to_double()
  366. 366 } else {
  367. 367○ 1.0
  368. 368 }
  369. 369 let line_accuracy = if total_lines > 0 {
  370. 370● correct_lines.to_double() / total_lines.to_double()
  371. 371 } else {
  372. 372○ 1.0
  373. 373 }
  374. 374
  375. 375 let precision = if correct_chars + false_positives > 0 {
  376. 376● correct_chars.to_double() / (correct_chars + false_positives).to_double()
  377. 377 } else {
  378. 378○ 1.0
  379. 379 }
  380. 380 let recall = if correct_chars + false_negatives > 0 {
  381. 381● correct_chars.to_double() / (correct_chars + false_negatives).to_double()
  382. 382 } else {
  383. 383○ 1.0
  384. 384 }
  385. 385 let f1_score = if precision + recall > 0 {
  386. 386● 2.0 * precision * recall / (precision + recall)
  387. 387 } else {
  388. 388○ 0.0
  389. 389 }
  390. 390
  391. 391 AccuracyStats::{
  392. 392 total_chars,
  393. 393 correct_chars,
  394. 394 char_accuracy,
  395. 395 total_words,
  396. 396 correct_words,
  397. 397 word_accuracy,
  398. 398 total_lines,
  399. 399 correct_lines,
  400. 400 line_accuracy,
  401. 401 false_positives,
  402. 402 false_negatives,
  403. 403 precision,
  404. 404 recall,
  405. 405 f1_score,
  406. 406 }
  407. 407}
  408. 408
  409. 409///|
  410. 410/// 生成准确率报告
  411. 411pub fn generate_accuracy_report(
  412. 412 stats : AccuracyStats,
  413. 413 dataset_name : String,
  414. 414) -> String {
  415. 415● let mut report = "## OCR 准确率测试报告\n\n"
  416. 416 report = report + "**测试集**: " + dataset_name + "\n\n"
  417. 417 report = report + "### 整体指标\n\n"
  418. 418 report = report + "| 指标 | 数值 |\n"
  419. 419 report = report + "|------|------|\n"
  420. 420 report = report +
  421. 421 "| 字符准确率 | " +
  422. 422● (stats.char_accuracy * 100.0).to_string() +
  423. 423 "% |\n"
  424. 424 report = report +
  425. 425 "| 词准确率 | " +
  426. 426● (stats.word_accuracy * 100.0).to_string() +
  427. 427 "% |\n"
  428. 428 report = report +
  429. 429 "| 行准确率 | " +
  430. 430● (stats.line_accuracy * 100.0).to_string() +
  431. 431 "% |\n"
  432. 432 report = report +
  433. 433 "| 精确率 (Precision) | " +
  434. 434● (stats.precision * 100.0).to_string() +
  435. 435 "% |\n"
  436. 436 report = report +
  437. 437 "| 召回率 (Recall) | " +
  438. 438● (stats.recall * 100.0).to_string() +
  439. 439 "% |\n"
  440. 440 report = report +
  441. 441 "| F1 分数 | " +
  442. 442● (stats.f1_score * 100.0).to_string() +
  443. 443 "% |\n\n"
  444. 444 report = report + "### 详细统计\n\n"
  445. 445 report = report + "| 指标 | 数值 |\n"
  446. 446 report = report + "|------|------|\n"
  447. 447● report = report + "| 总字符数 | " + stats.total_chars.to_string() + " |\n"
  448. 448 report = report +
  449. 449 "| 正确字符数 | " +
  450. 450● stats.correct_chars.to_string() +
  451. 451 " |\n"
  452. 452● report = report + "| 总词数 | " + stats.total_words.to_string() + " |\n"
  453. 453 report = report +
  454. 454 "| 正确词数 | " +
  455. 455● stats.correct_words.to_string() +
  456. 456 " |\n"
  457. 457● report = report + "| 总行数 | " + stats.total_lines.to_string() + " |\n"
  458. 458 report = report +
  459. 459 "| 正确行数 | " +
  460. 460● stats.correct_lines.to_string() +
  461. 461 " |\n"
  462. 462 report = report +
  463. 463 "| 误报 (False Positives) | " +
  464. 464● stats.false_positives.to_string() +
  465. 465 " |\n"
  466. 466 report = report +
  467. 467 "| 漏报 (False Negatives) | " +
  468. 468● stats.false_negatives.to_string() +
  469. 469 " |\n"
  470. 470 report
  471. 471}
  472. 472
  473. 473///|
  474. 474/// 生成性能基准报告
  475. 475pub fn generate_performance_report(
  476. 476 benchmark : PerformanceBenchmark,
  477. 477 dataset_name : String,
  478. 478) -> String {
  479. 479● let mut report = "## OCR 性能基准测试报告\n\n"
  480. 480 report = report + "**测试集**: " + dataset_name + "\n\n"
  481. 481 report = report + "### 处理时间\n\n"
  482. 482 report = report + "| 阶段 | 耗时 (ms) | 占比 |\n"
  483. 483 report = report + "|------|-----------|------|\n"
  484. 484 let total = if benchmark.total_time_ms > 0 {
  485. 485● benchmark.total_time_ms
  486. 486 } else {
  487. 487● 1.0
  488. 488 }
  489. 489 report = report +
  490. 490 "| 预处理 | " +
  491. 491● benchmark.preprocess_time_ms.to_string() +
  492. 492 " | " +
  493. 493● (benchmark.preprocess_time_ms / total * 100.0).to_string() +
  494. 494 "% |\n"
  495. 495 report = report +
  496. 496 "| 版面分析 | " +
  497. 497● benchmark.layout_time_ms.to_string() +
  498. 498 " | " +
  499. 499● (benchmark.layout_time_ms / total * 100.0).to_string() +
  500. 500 "% |\n"
  501. 501 report = report +
  502. 502 "| 字符识别 | " +
  503. 503● benchmark.recognition_time_ms.to_string() +
  504. 504 " | " +
  505. 505● (benchmark.recognition_time_ms / total * 100.0).to_string() +
  506. 506 "% |\n"
  507. 507 report = report +
  508. 508 "| 后处理 | " +
  509. 509● benchmark.postprocess_time_ms.to_string() +
  510. 510 " | " +
  511. 511● (benchmark.postprocess_time_ms / total * 100.0).to_string() +
  512. 512 "% |\n"
  513. 513 report = report +
  514. 514 "| **总计** | **" +
  515. 515● benchmark.total_time_ms.to_string() +
  516. 516 "** | **100%** |\n\n"
  517. 517 report = report + "### 吞吐量\n\n"
  518. 518 report = report + "| 指标 | 数值 |\n"
  519. 519 report = report + "|------|------|\n"
  520. 520 report = report +
  521. 521 "| 处理速度 (页/秒) | " +
  522. 522● benchmark.pages_per_second.to_string() +
  523. 523 " |\n"
  524. 524 report = report +
  525. 525 "| 识别速度 (字符/秒) | " +
  526. 526● benchmark.chars_per_second.to_string() +
  527. 527 " |\n"
  528. 528 report = report +
  529. 529 "| 内存占用 (MB) | " +
  530. 530● benchmark.memory_usage_mb.to_string() +
  531. 531 " |\n"
  532. 532 report = report +
  533. 533 "| CPU 使用率 (%) | " +
  534. 534● benchmark.cpu_usage_percent.to_string() +
  535. 535 " |\n"
  536. 536 report
  537. 537}
  538. 538
  539. 539///|
  540. 540/// 验证准确率是否达标
  541. 541pub fn check_accuracy_threshold(
  542. 542 stats : AccuracyStats,
  543. 543 min_char_accuracy~ : Double = 0.95,
  544. 544 min_word_accuracy~ : Double = 0.90,
  545. 545 min_f1_score~ : Double = 0.92,
  546. 546) -> (Bool, Array[String]) raise @types.LoadError {
  547. 547 // 输入验证
  548. 548● if min_char_accuracy < 0.0 || min_char_accuracy > 1.0 {
  549. 549● raise @types.LoadError::DecodeFailed(
  550. 550 "check_accuracy_threshold: 字符准确率阈值必须在0-1之间",
  551. 551 )
  552. 552 }
  553. 553 if min_word_accuracy < 0.0 || min_word_accuracy > 1.0 {
  554. 554● raise @types.LoadError::DecodeFailed(
  555. 555 "check_accuracy_threshold: 词准确率阈值必须在0-1之间",
  556. 556 )
  557. 557 }
  558. 558 if min_f1_score < 0.0 || min_f1_score > 1.0 {
  559. 559● raise @types.LoadError::DecodeFailed(
  560. 560 "check_accuracy_threshold: F1分数阈值必须在0-1之间",
  561. 561 )
  562. 562 }
  563. 563 let min_char = min_char_accuracy
  564. 564 let min_word = min_word_accuracy
  565. 565 let min_f1 = min_f1_score
  566. 566 let mut passed = true
  567. 567 let issues : Array[String] = []
  568. 568 if stats.char_accuracy < min_char {
  569. 569● passed = false
  570. 570● issues.push(
  571. 571 "字符准确率 " +
  572. 572● (stats.char_accuracy * 100.0).to_string() +
  573. 573 "% 低于阈值 " +
  574. 574● (min_char * 100.0).to_string() +
  575. 575 "%",
  576. 576 )
  577. 577 }
  578. 578 if stats.word_accuracy < min_word {
  579. 579● passed = false
  580. 580● issues.push(
  581. 581 "词准确率 " +
  582. 582● (stats.word_accuracy * 100.0).to_string() +
  583. 583 "% 低于阈值 " +
  584. 584● (min_word * 100.0).to_string() +
  585. 585 "%",
  586. 586 )
  587. 587 }
  588. 588 if stats.f1_score < min_f1 {
  589. 589● passed = false
  590. 590● issues.push(
  591. 591 "F1 分数 " +
  592. 592● (stats.f1_score * 100.0).to_string() +
  593. 593 "% 低于阈值 " +
  594. 594● (min_f1 * 100.0).to_string() +
  595. 595 "%",
  596. 596 )
  597. 597 }
  598. 598 (passed, issues)
  599. 599}