image.vision\ocr\postprocess.mbt

90.6% · 154 / 170 points · 484 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/postprocess
  3. 3///
  4. 4/// 图像处理库子模块
  5. 5/// 图像处理库子模块 Image processing library submodule
  6. 6// OCR 后处理
  7. 7// 词典匹配、N-gram语言模型、拼写纠错、置信度校准
  8. 8
  9. 9///|
  10. 10/// 后处理配置
  11. 11#derive(Eq, @debug.Debug)
  12. 12pub(all) struct PostProcessConfig {
  13. 13 use_dictionary : Bool
  14. 14 use_ngram : Bool
  15. 15 ngram_size : Int32
  16. 16 min_confidence : Double
  17. 17 max_candidates : Int32
  18. 18}
  19. 19
  20. 20///|
  21. 21pub extend PostProcessConfig with Eq::{not_equal, equal}
  22. 22
  23. 23///|
  24. 24pub extend PostProcessConfig with @debug.Debug::{to_repr}
  25. 25
  26. 26///|
  27. 27/// 创建默认后处理配置
  28. 28pub fn postprocess_default_config() -> PostProcessConfig {
  29. 29● PostProcessConfig::{
  30. 30 use_dictionary: true,
  31. 31 use_ngram: true,
  32. 32 ngram_size: 2,
  33. 33 min_confidence: 0.3,
  34. 34 max_candidates: 5,
  35. 35 }
  36. 36}
  37. 37
  38. 38///|
  39. 39/// 词典结构体
  40. 40#derive(Eq, @debug.Debug)
  41. 41pub(all) struct Dictionary {
  42. 42 words : Array[String]
  43. 43 word_set : Array[String] // 用于快速查找(简化版)
  44. 44}
  45. 45
  46. 46///|
  47. 47pub extend Dictionary with Eq::{not_equal, equal}
  48. 48
  49. 49///|
  50. 50pub extend Dictionary with @debug.Debug::{to_repr}
  51. 51
  52. 52///|
  53. 53/// 创建词典
  54. 54pub fn dictionary_create(
  55. 55 words : Array[String],
  56. 56) -> Dictionary raise @types.LoadError {
  57. 57 // 输入验证
  58. 58● if words.length() == 0 {
  59. 59● raise @types.LoadError::DecodeFailed(
  60. 60 "dictionary_create: 单词列表不能为空",
  61. 61 )
  62. 62 }
  63. 63
  64. 64 Dictionary::{ words, word_set: words, }
  65. 65}
  66. 66
  67. 67///|
  68. 68/// 创建常用英文单词词典
  69. 69pub fn dictionary_create_common_english() -> Dictionary {
  70. 70● let words : Array[String] = [
  71. 71 "the", "be", "to", "of", "and", "a", "in", "that", "have", "I", "it", "for",
  72. 72 "not", "on", "with", "he", "as", "you", "do", "at", "this", "but", "his", "by",
  73. 73 "from", "they", "we", "say", "her", "she", "or", "an", "will", "my", "one", "all",
  74. 74 "would", "there", "their", "what", "so", "up", "out", "if", "about", "who", "get",
  75. 75 "which", "go", "me", "when", "make", "can", "like", "time", "no", "just", "him",
  76. 76 "know", "take", "people", "into", "year", "your", "good", "some", "could", "them",
  77. 77 "see", "other", "than", "then", "now", "look", "only", "come", "its", "over",
  78. 78 "think", "also", "back", "after", "use", "two", "how", "our", "work", "first",
  79. 79 "well", "way", "even", "new", "want", "because", "any", "these", "give", "day",
  80. 80 "most", "us", "hello", "world", "image", "text", "ocr", "digit", "number", "letter",
  81. 81 "word", "line", "page", "document", "scan", "read", "write", "print", "font",
  82. 82 "size", "color", "black", "white", "gray", "bright", "dark", "contrast", "sharp",
  83. 83 "blur", "noise", "filter", "zero", "one", "two", "three", "four", "five", "six",
  84. 84 "seven", "eight", "nine", "ten", "hundred", "thousand", "million", "billion",
  85. 85 "yes", "no", "true", "false", "ok", "okay", "error", "warning", "info", "debug",
  86. 86 "start", "stop", "begin", "end", "open", "close", "save", "load", "delete", "copy",
  87. 87 "paste", "cut", "undo", "redo", "find", "replace", "search", "result", "output",
  88. 88 "input", "data", "file", "folder", "directory", "path", "name", "value", "key",
  89. 89 "code", "program", "software", "hardware", "system", "network", "server", "client",
  90. 90 "user", "admin", "password", "login", "logout", "register", "account", "profile",
  91. 91 "setting", "option", "config", "parameter", "argument", "variable", "function",
  92. 92 "class", "object", "method_type", "property", "attribute", "field", "element",
  93. 93 "node", "tree", "list", "array", "map", "set", "queue", "stack", "heap", "graph",
  94. 94 "string", "integer", "float", "double", "boolean", "char", "byte", "bit", "pixel",
  95. 95 "image", "width", "height", "channel", "format", "encode", "decode", "compress",
  96. 96 "decompress", "encrypt", "decrypt", "hash", "checksum", "signature", "test",
  97. 97 "test1", "test2", "abc", "abcd", "xyz", "foo", "bar", "baz",
  98. 98 ]
  99. 99 Dictionary::{ words, word_set: words, }
  100. 100}
  101. 101
  102. 102///|
  103. 103/// 计算编辑距离(Levenshtein距离)
  104. 104pub fn edit_distance(s1 : String, s2 : String) -> Int32 raise @types.LoadError {
  105. 105 // 输入验证
  106. 106● if s1.length() == 0 && s2.length() == 0 {
  107. 107● raise @types.LoadError::DecodeFailed(
  108. 108 "edit_distance: 两个字符串不能同时为空",
  109. 109 )
  110. 110 }
  111. 111
  112. 112● let len1 = s1.length()
  113. 113● let len2 = s2.length()
  114. 114 if len1 == 0 {
  115. 115● return len2
  116. 116 }
  117. 117 if len2 == 0 {
  118. 118● return len1
  119. 119 }
  120. 120 // 创建动态规划表
  121. 121● let dp : Array[Int32] = Array::make((len1 + 1) * (len2 + 1), 0)
  122. 122 // 初始化
  123. 123 for i in 0..<(len1 + 1) {
  124. 124● dp[i * (len2 + 1)] = i
  125. 125 }
  126. 126 for j in 0..<(len2 + 1) {
  127. 127● dp[j] = j
  128. 128 }
  129. 129 // 填充DP表
  130. 130 for i in 1..<(len1 + 1) {
  131. 131● for j in 1..<(len2 + 1) {
  132. 132● let cost = if s1[i - 1] == s2[j - 1] { 0 } else { 1 }
  133. 133 let insert = dp[i * (len2 + 1) + (j - 1)] + 1
  134. 134 let delete = dp[(i - 1) * (len2 + 1) + j] + 1
  135. 135 let substitute = dp[(i - 1) * (len2 + 1) + (j - 1)] + cost
  136. 136● let min1 = if insert < delete { insert } else { delete }
  137. 137● dp[i * (len2 + 1) + j] = if min1 < substitute { min1 } else { substitute }
  138. 138 }
  139. 139 }
  140. 140 dp[len1 * (len2 + 1) + len2]
  141. 141}
  142. 142
  143. 143///|
  144. 144/// 词典匹配:查找最相似的单词
  145. 145pub fn dictionary_match(
  146. 146 word : String,
  147. 147 dictionary : Dictionary,
  148. 148 max_distance~ : Int32 = 2,
  149. 149) -> Array[(String, Int32)] raise @types.LoadError {
  150. 150 // 输入验证
  151. 151● if word.length() == 0 {
  152. 152● raise @types.LoadError::DecodeFailed("dictionary_match: 单词不能为空")
  153. 153 }
  154. 154● if dictionary.words.length() == 0 {
  155. 155● raise @types.LoadError::DecodeFailed("dictionary_match: 词典不能为空")
  156. 156 }
  157. 157 if max_distance < 0 {
  158. 158● raise @types.LoadError::DecodeFailed(
  159. 159 "dictionary_match: max_distance不能为负数",
  160. 160 )
  161. 161 }
  162. 162
  163. 163 let results : Array[(String, Int32)] = []
  164. 164 for dict_word in dictionary.words {
  165. 165● let dist = edit_distance(word, dict_word)
  166. 166 if dist <= max_distance {
  167. 167● results.push((dict_word, dist))
  168. 168 }
  169. 169 }
  170. 170 // 按距离排序
  171. 171● for _ in 0..<results.length() {
  172. 172● for j in 0..<(results.length() - 1) {
  173. 173● if results[j].1 > results[j + 1].1 {
  174. 174● let temp = results[j]
  175. 175 results[j] = results[j + 1]
  176. 176 results[j + 1] = temp
  177. 177 }
  178. 178 }
  179. 179 }
  180. 180 results
  181. 181}
  182. 182
  183. 183///|
  184. 184/// N-gram 语言模型
  185. 185#derive(Eq, @debug.Debug)
  186. 186pub(all) struct NgramModel {
  187. 187 n : Int32
  188. 188 bigram_counts : Array[(String, Int32)] // 简化版:存储bigram和计数
  189. 189 unigram_counts : Array[(String, Int32)]
  190. 190}
  191. 191
  192. 192///|
  193. 193pub extend NgramModel with Eq::{not_equal, equal}
  194. 194
  195. 195///|
  196. 196pub extend NgramModel with @debug.Debug::{to_repr}
  197. 197
  198. 198///|
  199. 199/// 把字符串索引(码点 Int)还原成单字符字符串。
  200. 200fn pp_char_str(raw : UInt16) -> String {
  201. 201● raw.to_int().to_char().map(c => c.to_string()).unwrap_or("")
  202. 202}
  203. 203
  204. 204///|
  205. 205/// 创建 N-gram 模型(从文本训练)
  206. 206pub fn ngram_create(
  207. 207 texts : Array[String],
  208. 208 n~ : Int32 = 2,
  209. 209) -> NgramModel raise @types.LoadError {
  210. 210 // 输入验证
  211. 211● if texts.length() == 0 {
  212. 212● raise @types.LoadError::DecodeFailed(
  213. 213 "ngram_create: 文本列表不能为空",
  214. 214 )
  215. 215 }
  216. 216 if n < 1 {
  217. 217● raise @types.LoadError::DecodeFailed("ngram_create: n必须大于等于1")
  218. 218 }
  219. 219
  220. 220 let bigram_counts : Array[(String, Int32)] = []
  221. 221 let unigram_counts : Array[(String, Int32)] = []
  222. 222 for text in texts {
  223. 223 // 简化:按字符处理
  224. 224● for i in 0..<(text.length() - 1) {
  225. 225● let bigram = pp_char_str(text[i]) + pp_char_str(text[i + 1])
  226. 226 // 查找是否已存在
  227. 227 let mut found = false
  228. 228● for j in 0..<bigram_counts.length() {
  229. 229● if bigram_counts[j].0 == bigram {
  230. 230● bigram_counts[j] = (bigram, bigram_counts[j].1 + 1)
  231. 231 found = true
  232. 232 }
  233. 233 }
  234. 234 if !found {
  235. 235● bigram_counts.push((bigram, 1))
  236. 236 }
  237. 237 }
  238. 238 // unigram
  239. 239● for i in 0..<text.length() {
  240. 240● let unigram = pp_char_str(text[i])
  241. 241 let mut found = false
  242. 242● for j in 0..<unigram_counts.length() {
  243. 243● if unigram_counts[j].0 == unigram {
  244. 244● unigram_counts[j] = (unigram, unigram_counts[j].1 + 1)
  245. 245 found = true
  246. 246 }
  247. 247 }
  248. 248 if !found {
  249. 249● unigram_counts.push((unigram, 1))
  250. 250 }
  251. 251 }
  252. 252 }
  253. 253 NgramModel::{ n, bigram_counts, unigram_counts, }
  254. 254}
  255. 255
  256. 256///|
  257. 257/// 计算文本的 N-gram 概率(简化版)
  258. 258pub fn ngram_score(
  259. 259 text : String,
  260. 260 model : NgramModel,
  261. 261) -> Double raise @types.LoadError {
  262. 262 // 输入验证
  263. 263● if text.length() == 0 {
  264. 264● raise @types.LoadError::DecodeFailed("ngram_score: 文本不能为空")
  265. 265 }
  266. 266● if model.bigram_counts.length() == 0 && model.unigram_counts.length() == 0 {
  267. 267● raise @types.LoadError::DecodeFailed(
  268. 268 "ngram_score: N-gram模型不能为空",
  269. 269 )
  270. 270 }
  271. 271
  272. 272● if text.length() < 2 {
  273. 273● return 0.0
  274. 274 }
  275. 275 let mut total_score = 0.0
  276. 276 let mut count = 0
  277. 277● for i in 0..<(text.length() - 1) {
  278. 278● let bigram = pp_char_str(text[i]) + pp_char_str(text[i + 1])
  279. 279 // 查找bigram概率
  280. 280 let mut bigram_count = 0
  281. 281 let mut unigram_count = 0
  282. 282● for j in 0..<model.bigram_counts.length() {
  283. 283● if model.bigram_counts[j].0 == bigram {
  284. 284● bigram_count = model.bigram_counts[j].1
  285. 285 }
  286. 286 }
  287. 287● let first_char = pp_char_str(text[i])
  288. 288● for j in 0..<model.unigram_counts.length() {
  289. 289● if model.unigram_counts[j].0 == first_char {
  290. 290● unigram_count = model.unigram_counts[j].1
  291. 291 }
  292. 292 }
  293. 293 if unigram_count > 0 {
  294. 294● total_score += bigram_count.to_double() / unigram_count.to_double()
  295. 295 count += 1
  296. 296 }
  297. 297 }
  298. 298 if count > 0 {
  299. 299● total_score / count.to_double()
  300. 300 } else {
  301. 301● 0.0
  302. 302 }
  303. 303}
  304. 304
  305. 305///|
  306. 306/// 完整后处理流水线
  307. 307pub fn ocr_postprocess(
  308. 308 result : OcrResult,
  309. 309 config? : PostProcessConfig,
  310. 310 dictionary? : Dictionary,
  311. 311 ngram_model? : NgramModel,
  312. 312) -> OcrResult raise @types.LoadError {
  313. 313● ignore(ngram_model)
  314. 314 // 输入验证
  315. 315● if result.characters.length() == 0 && result.text.length() == 0 {
  316. 316● raise @types.LoadError::DecodeFailed(
  317. 317 "ocr_postprocess: OCR结果不能为空",
  318. 318 )
  319. 319 }
  320. 320
  321. 321● let cfg = match config {
  322. 322● Some(c) => c
  323. 323● None => postprocess_default_config()
  324. 324 }
  325. 325● let dict = match dictionary {
  326. 326● Some(d) => d
  327. 327● None => dictionary_create_common_english()
  328. 328 }
  329. 329 // 1. 低置信度字符标记
  330. 330 let mut corrected_text = ""
  331. 331 let mut total_confidence = 0.0
  332. 332 let corrected_chars : Array[OcrCharResult] = []
  333. 333 for char_result in result.characters {
  334. 334● let mut corrected_char = char_result.char
  335. 335 let mut confidence = char_result.confidence
  336. 336 // 2. 词典匹配(对低置信度字符)
  337. 337 if cfg.use_dictionary && confidence < cfg.min_confidence {
  338. 338 // 简化:只对单个字符进行常见纠错
  339. 339● let corrections = common_char_corrections(char_result.char)
  340. 340● if corrections.length() > 0 {
  341. 341● corrected_char = corrections[0]
  342. 342 confidence = confidence + 0.1
  343. 343 }
  344. 344 }
  345. 345 corrected_text += corrected_char
  346. 346 total_confidence += confidence
  347. 347● corrected_chars.push(OcrCharResult::{
  348. 348 char: corrected_char,
  349. 349 confidence,
  350. 350 x: char_result.x,
  351. 351 y: char_result.y,
  352. 352 width: char_result.width,
  353. 353 height: char_result.height,
  354. 354 })
  355. 355 }
  356. 356 // 3. 词典匹配(对整个文本中的单词)
  357. 357 if cfg.use_dictionary {
  358. 358● let words = split_into_words(corrected_text)
  359. 359 let mut corrected_words = ""
  360. 360 for word in words {
  361. 361● if word.length() >= 2 {
  362. 362● let matches = dictionary_match(word, dict, max_distance=1)
  363. 363● if matches.length() > 0 && matches[0].1 > 0 {
  364. 364● corrected_words += matches[0].0
  365. 365 } else {
  366. 366● corrected_words += word
  367. 367 }
  368. 368 } else {
  369. 369● corrected_words += word
  370. 370 }
  371. 371 }
  372. 372 corrected_text = corrected_words
  373. 373 }
  374. 374● let avg_confidence = if corrected_chars.length() > 0 {
  375. 375● total_confidence / corrected_chars.length().to_double()
  376. 376 } else {
  377. 377● 0.0
  378. 378 }
  379. 379 OcrResult::{
  380. 380 text: corrected_text,
  381. 381 confidence: avg_confidence,
  382. 382 characters: corrected_chars,
  383. 383 }
  384. 384}
  385. 385
  386. 386///|
  387. 387/// 常见字符纠错映射
  388. 388fn common_char_corrections(char : String) -> Array[String] {
  389. 389● let corrections : Array[String] = []
  390. 390 // OCR常见混淆字符对
  391. 391● match char {
  392. 392● "0" => corrections.push("O")
  393. 393● "O" => corrections.push("0")
  394. 394● "1" => corrections.push("I")
  395. 395● "I" => corrections.push("1")
  396. 396● "l" => corrections.push("1")
  397. 397● "2" => corrections.push("Z")
  398. 398○ "Z" => corrections.push("2")
  399. 399● "5" => corrections.push("S")
  400. 400○ "S" => corrections.push("5")
  401. 401○ "8" => corrections.push("B")
  402. 402○ "B" => corrections.push("8")
  403. 403○ "6" => corrections.push("G")
  404. 404○ "G" => corrections.push("6")
  405. 405○ "9" => corrections.push("g")
  406. 406○ "g" => corrections.push("9")
  407. 407● _ => ignore(())
  408. 408 }
  409. 409 corrections
  410. 410}
  411. 411
  412. 412///|
  413. 413/// 将文本分割成单词(简化版)
  414. 414fn split_into_words(text : String) -> Array[String] {
  415. 415● let words : Array[String] = []
  416. 416 let mut current_word = ""
  417. 417● for i in 0..<text.length() {
  418. 418● let raw = text[i]
  419. 419● let c = pp_char_str(raw)
  420. 420 if c == " " || c == "\n" || c == "\t" {
  421. 421● if current_word.length() > 0 {
  422. 422● words.push(current_word)
  423. 423 current_word = ""
  424. 424 }
  425. 425● words.push(c)
  426. 426 } else {
  427. 427● current_word += c
  428. 428 }
  429. 429 }
  430. 430● if current_word.length() > 0 {
  431. 431● words.push(current_word)
  432. 432 }
  433. 433 words
  434. 434}
  435. 435
  436. 436///|
  437. 437/// 置信度校准
  438. 438/// @deprecated 已废弃,请使用 calibrate_confidence_enhanced 代替
  439. 439#deprecated("Use calibrate_confidence_enhanced instead", skip_current_package=true)
  440. 440pub fn calibrate_confidence(
  441. 441 result : OcrResult,
  442. 442 factor~ : Double = 1.0,
  443. 443) -> OcrResult raise @types.LoadError {
  444. 444 // 输入验证
  445. 445 if result.characters.length() == 0 {
  446. 446 raise @types.LoadError::DecodeFailed(
  447. 447 "calibrate_confidence: OCR结果字符列表不能为空",
  448. 448 )
  449. 449 }
  450. 450 if factor <= 0.0 {
  451. 451 raise @types.LoadError::DecodeFailed(
  452. 452 "calibrate_confidence: factor必须大于0",
  453. 453 )
  454. 454 }
  455. 455
  456. 456 let calibrated_chars : Array[OcrCharResult] = []
  457. 457 let mut total = 0.0
  458. 458 for char_result in result.characters {
  459. 459 let new_confidence = if char_result.confidence * factor > 1.0 {
  460. 460 1.0
  461. 461 } else {
  462. 462 char_result.confidence * factor
  463. 463 }
  464. 464 total += new_confidence
  465. 465 calibrated_chars.push(OcrCharResult::{
  466. 466 char: char_result.char,
  467. 467 confidence: new_confidence,
  468. 468 x: char_result.x,
  469. 469 y: char_result.y,
  470. 470 width: char_result.width,
  471. 471 height: char_result.height,
  472. 472 })
  473. 473 }
  474. 474 let avg = if calibrated_chars.length() > 0 {
  475. 475 total / calibrated_chars.length().to_double()
  476. 476 } else {
  477. 477 0.0
  478. 478 }
  479. 479 OcrResult::{
  480. 480 text: result.text,
  481. 481 confidence: avg,
  482. 482 characters: calibrated_chars,
  483. 483 }
  484. 484}