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