image.vision\ocr\multilingual_ocr.mbt

92.3% · 144 / 156 points · 676 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 ocr/multilingual_ocr
  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 LanguageType {
  15. 15 Chinese
  16. 16 English
  17. 17 Digit
  18. 18 Punctuation
  19. 19 Mixed
  20. 20 Unknown
  21. 21}
  22. 22
  23. 23///|
  24. 24pub extend LanguageType with @debug.Debug::{to_repr}
  25. 25
  26. 26///|
  27. 27pub extend LanguageType with Eq::{not_equal, equal}
  28. 28
  29. 29///|
  30. 30/// 多语言识别配置
  31. 31#derive(Eq, @debug.Debug)
  32. 32pub(all) struct MultilingualOcrConfig {
  33. 33 enable_chinese : Bool
  34. 34 enable_english : Bool
  35. 35 enable_digits : Bool
  36. 36 enable_punctuation : Bool
  37. 37 target_size : Int32
  38. 38 distance_metric : String
  39. 39 auto_language_detection : Bool
  40. 40}
  41. 41
  42. 42///|
  43. 43pub extend MultilingualOcrConfig with Eq::{not_equal, equal}
  44. 44
  45. 45///|
  46. 46pub extend MultilingualOcrConfig with @debug.Debug::{to_repr}
  47. 47
  48. 48///|
  49. 49/// 创建默认多语言识别配置
  50. 50pub fn multilingual_ocr_default_config() -> MultilingualOcrConfig {
  51. 51● MultilingualOcrConfig::{
  52. 52 enable_chinese: true,
  53. 53 enable_english: true,
  54. 54 enable_digits: true,
  55. 55 enable_punctuation: true,
  56. 56 target_size: 48,
  57. 57 distance_metric: "euclidean",
  58. 58 auto_language_detection: true,
  59. 59 }
  60. 60}
  61. 61
  62. 62///|
  63. 63/// 标点符号模板
  64. 64#derive(Eq, @debug.Debug)
  65. 65pub(all) struct PunctuationTemplate {
  66. 66 char : String
  67. 67 features : Array[Double]
  68. 68 width_ratio : Double // 相对宽度(窄/宽)
  69. 69}
  70. 70
  71. 71///|
  72. 72pub extend PunctuationTemplate with Eq::{not_equal, equal}
  73. 73
  74. 74///|
  75. 75pub extend PunctuationTemplate with @debug.Debug::{to_repr}
  76. 76
  77. 77///|
  78. 78/// 生成标点符号模板
  79. 79pub fn generate_punctuation_templates() -> Array[PunctuationTemplate] {
  80. 80● let templates : Array[PunctuationTemplate] = []
  81. 81 // 常见标点符号
  82. 82 let punctuations : Array[(String, Double)] = [
  83. 83 (",", 0.3), // 逗号(窄)
  84. 84 (".", 0.3), // 句号(窄)
  85. 85 ("!", 0.3), // 感叹号(窄)
  86. 86 ("?", 0.5), // 问号(中)
  87. 87 (";", 0.3), // 分号(窄)
  88. 88 (":", 0.3), // 冒号(窄)
  89. 89 ("\"", 0.4), // 引号(中)
  90. 90 ("'", 0.2), // 单引号(窄)
  91. 91 ("(", 0.4), // 左括号(中)
  92. 92 (")", 0.4), // 右括号(中)
  93. 93 ("[", 0.4), // 左方括号
  94. 94 ("]", 0.4), // 右方括号
  95. 95 ("{", 0.5), // 左花括号
  96. 96 ("}", 0.5), // 右花括号
  97. 97 ("-", 0.6), // 连字符(宽)
  98. 98 ("_", 0.6), // 下划线(宽)
  99. 99 ("/", 0.4), // 斜杠
  100. 100 ("\\", 0.4), // 反斜杠
  101. 101 ("|", 0.2), // 竖线(窄)
  102. 102 ("@", 0.7), // at符号(宽)
  103. 103 ("#", 0.6), // 井号
  104. 104 ("$", 0.5), // 美元符号
  105. 105 ("%", 0.6), // 百分号
  106. 106 ("^", 0.5), // 脱字符
  107. 107 ("&", 0.6), // 和号
  108. 108 ("*", 0.5), // 星号
  109. 109 ("+", 0.5), // 加号
  110. 110 ("=", 0.6), // 等号
  111. 111 ("<", 0.5), // 小于号
  112. 112 (">", 0.5), // 大于号
  113. 113 ("~", 0.6), // 波浪号
  114. 114 ("`", 0.3), // 反引号
  115. 115 (",", 0.5), // 中文逗号
  116. 116 ("。", 0.5), // 中文句号
  117. 117 ("!", 0.5), // 中文感叹号
  118. 118 ("?", 0.6), // 中文问号
  119. 119 (";", 0.5), // 中文分号
  120. 120 (":", 0.5), // 中文冒号
  121. 121 ("“", 0.6), // 中文左引号
  122. 122 ("”", 0.6), // 中文右引号
  123. 123 ("(", 0.6), // 中文左括号
  124. 124 (")", 0.6), // 中文右括号
  125. 125 ("、", 0.4), // 顿号
  126. 126 ("《", 0.6), // 书名号左
  127. 127 ("》", 0.6), // 书名号右
  128. 128 ("—", 0.8), // 破折号
  129. 129 ("…", 0.7), // 省略号
  130. 130 ]
  131. 131 for _tup0 in punctuations {
  132. 132● let (char, width_ratio) = _tup0
  133. 133● let features = generate_punctuation_features(char, width_ratio)
  134. 134● templates.push(PunctuationTemplate::{ char, features, width_ratio, })
  135. 135 }
  136. 136 templates
  137. 137}
  138. 138
  139. 139///|
  140. 140/// 生成标点符号特征
  141. 141fn generate_punctuation_features(
  142. 142 char : String,
  143. 143 width_ratio : Double,
  144. 144) -> Array[Double] {
  145. 145● let size = 16
  146. 146● let features : Array[Double] = Array::make(size * size, 0.0)
  147. 147● let seed = if char.length() > 0 { char[0].to_int() } else { 0 }
  148. 148 // 基于字符生成简单的标点模式
  149. 149● let center_x = (size.to_double() * (0.5 + (width_ratio - 0.5) * 0.3)).to_int()
  150. 150 let center_y = size / 2
  151. 151 for y in 0..<size {
  152. 152● for x in 0..<size {
  153. 153● let h = (seed * 31 + x * 17 + y * 13) % 100
  154. 154 let dist = ((x - center_x) * (x - center_x) +
  155. 155● (y - center_y) * (y - center_y)).to_double()
  156. 156 let center_factor = 1.0 - dist / 64.0
  157. 157● if h < 40 + (center_factor * 30.0).to_int() {
  158. 158● features[y * size + x] = 1.0
  159. 159 }
  160. 160 }
  161. 161 }
  162. 162 features
  163. 163}
  164. 164
  165. 165///|
  166. 166/// 检测字符语言类型(基于宽高比和尺寸)
  167. 167pub fn detect_char_language(
  168. 168 char_img : @types.Image,
  169. 169) -> LanguageType raise @types.LoadError {
  170. 170 // 输入验证
  171. 171● if char_img.width <= 0 || char_img.height <= 0 {
  172. 172● raise @types.LoadError::DecodeFailed(
  173. 173 "detect_char_language: 图像尺寸必须大于0",
  174. 174 )
  175. 175 }
  176. 176 if char_img.channels < 1 || char_img.channels > 4 {
  177. 177● raise @types.LoadError::DecodeFailed(
  178. 178 "detect_char_language: 通道数必须在1-4之间",
  179. 179 )
  180. 180 }
  181. 181 let expected_size = char_img.width * char_img.height * char_img.channels
  182. 182● if char_img.data.length() != expected_size {
  183. 183● raise @types.LoadError::DecodeFailed(
  184. 184 "detect_char_language: 数据大小不匹配,期望 " +
  185. 185● expected_size.to_string() +
  186. 186 ",实际 " +
  187. 187● char_img.data.length().to_string(),
  188. 188 )
  189. 189 }
  190. 190 let w = char_img.width
  191. 191 let h = char_img.height
  192. 192◐ let ratio = if h > 0 { w.to_double() / h.to_double() } else { 1.0 }
  193. 193 // 中文字符通常接近正方形(ratio 0.8-1.2)
  194. 194 if ratio > 0.75 && ratio < 1.35 && w > 20 && h > 20 {
  195. 195● return LanguageType::Chinese
  196. 196 }
  197. 197 // 英文字符通常较窄(ratio 0.4-0.8)
  198. 198 if ratio > 0.3 && ratio < 0.75 {
  199. 199● return LanguageType::English
  200. 200 }
  201. 201 // 数字
  202. 202 if ratio > 0.4 && ratio < 0.7 {
  203. 203○ return LanguageType::Digit
  204. 204 }
  205. 205 // 标点符号通常很窄或很宽
  206. 206 if ratio < 0.4 || ratio > 1.35 {
  207. 207● return LanguageType::Punctuation
  208. 208 }
  209. 209 LanguageType::Unknown
  210. 210}
  211. 211
  212. 212///|
  213. 213/// 检测文档主要语言
  214. 214pub fn detect_document_language(
  215. 215 img : @types.Image,
  216. 216) -> LanguageType raise @types.LoadError {
  217. 217 // 输入验证
  218. 218● if img.width <= 0 || img.height <= 0 {
  219. 219● raise @types.LoadError::DecodeFailed(
  220. 220 "detect_document_language: 图像尺寸必须大于0",
  221. 221 )
  222. 222 }
  223. 223 if img.channels < 1 || img.channels > 4 {
  224. 224● raise @types.LoadError::DecodeFailed(
  225. 225 "detect_document_language: 通道数必须在1-4之间",
  226. 226 )
  227. 227 }
  228. 228 let expected_size = img.width * img.height * img.channels
  229. 229● if img.data.length() != expected_size {
  230. 230● raise @types.LoadError::DecodeFailed(
  231. 231 "detect_document_language: 数据大小不匹配,期望 " +
  232. 232● expected_size.to_string() +
  233. 233 ",实际 " +
  234. 234● img.data.length().to_string(),
  235. 235 )
  236. 236 }
  237. 237 // 预处理
  238. 238● let preprocessed = ocr_preprocess(img)
  239. 239 // 检测文本行
  240. 240● let lines = detect_text_lines_projection(preprocessed)
  241. 241● if lines.length() == 0 {
  242. 242○ return LanguageType::Unknown
  243. 243 }
  244. 244 // 统计字符宽高比
  245. 245 let mut chinese_count = 0
  246. 246 let mut english_count = 0
  247. 247 let mut digit_count = 0
  248. 248 // 简单统计:基于文本行的平均字符宽度
  249. 249 for line in lines {
  250. 250● let avg_char_width = if line.width > 0 {
  251. 251● line.width.to_double() / (line.width.to_double() / 15.0).max(1.0)
  252. 252 } else {
  253. 253○ 15.0
  254. 254 }
  255. 255● let ratio = avg_char_width / line.height.to_double()
  256. 256 if ratio > 0.75 && ratio < 1.35 {
  257. 257● chinese_count += 1
  258. 258● } else if ratio > 0.3 && ratio < 0.75 {
  259. 259● english_count += 1
  260. 260 } else {
  261. 261● digit_count += 1
  262. 262 }
  263. 263 }
  264. 264 // 判断主要语言
  265. 265 if chinese_count > english_count && chinese_count > digit_count {
  266. 266● return LanguageType::Chinese
  267. 267 }
  268. 268 if english_count > chinese_count && english_count > digit_count {
  269. 269● return LanguageType::English
  270. 270 }
  271. 271 if chinese_count > 0 && english_count > 0 {
  272. 272○ return LanguageType::Mixed
  273. 273 }
  274. 274 LanguageType::Unknown
  275. 275}
  276. 276
  277. 277///|
  278. 278/// 多语言混合识别(完整流水线)
  279. 279/// @deprecated 已废弃,请使用 recognize_multilingual_enhanced 代替
  280. 280#deprecated("Use recognize_multilingual_enhanced instead", skip_current_package=true)
  281. 281pub fn recognize_multilingual(
  282. 282 img : @types.Image,
  283. 283 config? : MultilingualOcrConfig,
  284. 284) -> OcrResult raise @types.LoadError {
  285. 285 // 输入验证
  286. 286 if img.width <= 0 || img.height <= 0 {
  287. 287 raise @types.LoadError::DecodeFailed(
  288. 288 "recognize_multilingual: 图像尺寸必须大于0",
  289. 289 )
  290. 290 }
  291. 291 if img.channels < 1 || img.channels > 4 {
  292. 292 raise @types.LoadError::DecodeFailed(
  293. 293 "recognize_multilingual: 通道数必须在1-4之间",
  294. 294 )
  295. 295 }
  296. 296 let expected_size = img.width * img.height * img.channels
  297. 297 if img.data.length() != expected_size {
  298. 298 raise @types.LoadError::DecodeFailed(
  299. 299 "recognize_multilingual: 数据大小不匹配,期望 " +
  300. 300 expected_size.to_string() +
  301. 301 ",实际 " +
  302. 302 img.data.length().to_string(),
  303. 303 )
  304. 304 }
  305. 305 let cfg = match config {
  306. 306 Some(c) => c
  307. 307 None => multilingual_ocr_default_config()
  308. 308 }
  309. 309 // 1. 预处理
  310. 310 let preprocessed = ocr_preprocess(img)
  311. 311 // 2. 检测文档主要语言
  312. 312 let _ = if cfg.auto_language_detection {
  313. 313 detect_document_language(preprocessed)
  314. 314 } else {
  315. 315 LanguageType::Mixed
  316. 316 }
  317. 317 // 3. 字符分割
  318. 318 let char_regions = segment_multilingual_chars(preprocessed, cfg)
  319. 319 // 4. 生成各语言模板
  320. 320 let chinese_templates = if cfg.enable_chinese {
  321. 321 generate_3500_chinese_templates(char_set="common100")
  322. 322 } else {
  323. 323 []
  324. 324 }
  325. 325 let english_templates = if cfg.enable_english {
  326. 326 generate_english_templates(case_sensitive=false)
  327. 327 } else {
  328. 328 []
  329. 329 }
  330. 330 let digit_templates = if cfg.enable_digits {
  331. 331 generate_digit_templates()
  332. 332 } else {
  333. 333 []
  334. 334 }
  335. 335 let punctuation_templates = if cfg.enable_punctuation {
  336. 336 generate_punctuation_templates()
  337. 337 } else {
  338. 338 []
  339. 339 }
  340. 340 // 5. 对每个字符进行识别
  341. 341 let char_results : Array[OcrCharResult] = []
  342. 342 let mut text = ""
  343. 343 let mut total_confidence = 0.0
  344. 344 for _tup1 in char_regions {
  345. 345 let (x, y, w, h) = _tup1
  346. 346 // 提取字符图像
  347. 347 let char_img = extract_multilingual_char_region(
  348. 348 preprocessed,
  349. 349 x,
  350. 350 y,
  351. 351 w,
  352. 352 h,
  353. 353 cfg.target_size,
  354. 354 )
  355. 355 // 检测字符语言类型
  356. 356 let char_language = detect_char_language(char_img)
  357. 357 // 根据语言类型选择模板
  358. 358 let result = match char_language {
  359. 359 LanguageType::Chinese =>
  360. 360 if chinese_templates.length() > 0 {
  361. 361 match_multilingual_template(
  362. 362 extract_multilingual_features(char_img, 16),
  363. 363 chinese_templates,
  364. 364 cfg.distance_metric,
  365. 365 )
  366. 366 } else {
  367. 367 ("?", 0.0)
  368. 368 }
  369. 369 LanguageType::English =>
  370. 370 if english_templates.length() > 0 {
  371. 371 match_multilingual_template(
  372. 372 extract_multilingual_features(char_img, 16),
  373. 373 english_templates,
  374. 374 cfg.distance_metric,
  375. 375 )
  376. 376 } else {
  377. 377 ("?", 0.0)
  378. 378 }
  379. 379 LanguageType::Digit =>
  380. 380 if digit_templates.length() > 0 {
  381. 381 match_multilingual_template(
  382. 382 extract_multilingual_features(char_img, 16),
  383. 383 digit_templates,
  384. 384 cfg.distance_metric,
  385. 385 )
  386. 386 } else {
  387. 387 ("?", 0.0)
  388. 388 }
  389. 389 LanguageType::Punctuation =>
  390. 390 if punctuation_templates.length() > 0 {
  391. 391 match_punctuation_template(
  392. 392 extract_multilingual_features(char_img, 16),
  393. 393 punctuation_templates,
  394. 394 )
  395. 395 } else {
  396. 396 ("?", 0.0)
  397. 397 }
  398. 398 _ => {
  399. 399 // 未知语言,尝试所有模板
  400. 400 let all_templates : Array[(String, Array[Double])] = []
  401. 401 for t in chinese_templates {
  402. 402 all_templates.push(t)
  403. 403 }
  404. 404 for t in english_templates {
  405. 405 all_templates.push(t)
  406. 406 }
  407. 407 for t in digit_templates {
  408. 408 all_templates.push(t)
  409. 409 }
  410. 410 if all_templates.length() > 0 {
  411. 411 match_multilingual_template(
  412. 412 extract_multilingual_features(char_img, 16),
  413. 413 all_templates,
  414. 414 cfg.distance_metric,
  415. 415 )
  416. 416 } else {
  417. 417 ("?", 0.0)
  418. 418 }
  419. 419 }
  420. 420 }
  421. 421 text += result.0
  422. 422 total_confidence += result.1
  423. 423 char_results.push(OcrCharResult::{
  424. 424 char: result.0,
  425. 425 confidence: result.1,
  426. 426 x,
  427. 427 y,
  428. 428 width: w,
  429. 429 height: h,
  430. 430 })
  431. 431 }
  432. 432 let avg_confidence = if char_results.length() > 0 {
  433. 433 total_confidence / char_results.length().to_double()
  434. 434 } else {
  435. 435 0.0
  436. 436 }
  437. 437 OcrResult::{ text, confidence: avg_confidence, characters: char_results, }
  438. 438}
  439. 439
  440. 440///|
  441. 441/// 多语言字符分割
  442. 442fn segment_multilingual_chars(
  443. 443 img : @types.Image,
  444. 444 _cfg : MultilingualOcrConfig,
  445. 445) -> Array[(Int32, Int32, Int32, Int32)] {
  446. 446● let w = img.width
  447. 447 let h = img.height
  448. 448 let data = img.data
  449. 449 // 简单连通域标记
  450. 450● let labels : Array[Int32] = Array::make(w * h, 0)
  451. 451 let mut next_label = 1
  452. 452 for y in 0..<h {
  453. 453● for x in 0..<w {
  454. 454● if data[y * w + x].to_int() > 128 {
  455. 455● let mut label = 0
  456. 456 if x > 0 && labels[y * w + x - 1] > 0 {
  457. 457● label = labels[y * w + x - 1]
  458. 458 }
  459. 459 if y > 0 && labels[(y - 1) * w + x] > 0 {
  460. 460● if label == 0 {
  461. 461● label = labels[(y - 1) * w + x]
  462. 462 }
  463. 463 }
  464. 464 if label == 0 {
  465. 465● label = next_label
  466. 466 next_label += 1
  467. 467 }
  468. 468 labels[y * w + x] = label
  469. 469 }
  470. 470 }
  471. 471 }
  472. 472 // 计算边界框
  473. 473● let min_x : Array[Int32] = Array::make(next_label, w)
  474. 474● let max_x : Array[Int32] = Array::make(next_label, 0)
  475. 475● let min_y : Array[Int32] = Array::make(next_label, h)
  476. 476● let max_y : Array[Int32] = Array::make(next_label, 0)
  477. 477● let area : Array[Int32] = Array::make(next_label, 0)
  478. 478 for y in 0..<h {
  479. 479● for x in 0..<w {
  480. 480● let label = labels[y * w + x]
  481. 481 if label > 0 {
  482. 482● area[label] += 1
  483. 483 if x < min_x[label] {
  484. 484● min_x[label] = x
  485. 485 }
  486. 486 if x > max_x[label] {
  487. 487● max_x[label] = x
  488. 488 }
  489. 489 if y < min_y[label] {
  490. 490● min_y[label] = y
  491. 491 }
  492. 492 if y > max_y[label] {
  493. 493● max_y[label] = y
  494. 494 }
  495. 495 }
  496. 496 }
  497. 497 }
  498. 498 // 过滤(多语言更宽松)
  499. 499 let regions : Array[(Int32, Int32, Int32, Int32)] = []
  500. 500 for label in 1..<next_label {
  501. 501● let rw = max_x[label] - min_x[label] + 1
  502. 502 let rh = max_y[label] - min_y[label] + 1
  503. 503 if rw >= 5 && rw <= 100 && rh >= 8 && rh <= 100 && area[label] > 10 {
  504. 504● regions.push((min_x[label], min_y[label], rw, rh))
  505. 505 }
  506. 506 }
  507. 507 regions
  508. 508}
  509. 509
  510. 510///|
  511. 511/// 提取多语言字符区域
  512. 512fn extract_multilingual_char_region(
  513. 513 img : @types.Image,
  514. 514 x : Int32,
  515. 515 y : Int32,
  516. 516 width : Int32,
  517. 517 height : Int32,
  518. 518 target_size : Int32,
  519. 519) -> @types.Image {
  520. 520● let w = img.width
  521. 521 let h = img.height
  522. 522● let crop_w = if x + width > w { w - x } else { width }
  523. 523● let crop_h = if y + height > h { h - y } else { height }
  524. 524 if crop_w <= 0 || crop_h <= 0 {
  525. 525● let empty : Array[Byte] = Array::make(target_size * target_size, b'\x00')
  526. 526 return @types.Image::{
  527. 527 width: target_size,
  528. 528 height: target_size,
  529. 529 channels: 1,
  530. 530● data: Bytes::from_array(empty),
  531. 531 }
  532. 532 }
  533. 533● let out : Array[Byte] = Array::make(target_size * target_size, b'\x00')
  534. 534 let data = img.data
  535. 535 for py in 0..<target_size {
  536. 536● for px in 0..<target_size {
  537. 537● let src_x = x + px * crop_w / target_size
  538. 538 let src_y = y + py * crop_h / target_size
  539. 539 if src_x < w && src_y < h {
  540. 540● out[py * target_size + px] = data[src_y * w + src_x]
  541. 541 }
  542. 542 }
  543. 543 }
  544. 544 @types.Image::{
  545. 545 width: target_size,
  546. 546 height: target_size,
  547. 547 channels: 1,
  548. 548● data: Bytes::from_array(out),
  549. 549 }
  550. 550}
  551. 551
  552. 552///|
  553. 553/// 提取多语言字符特征
  554. 554fn extract_multilingual_features(
  555. 555 char_img : @types.Image,
  556. 556 grid_size : Int32,
  557. 557) -> Array[Double] {
  558. 558● let w = char_img.width
  559. 559 let h = char_img.height
  560. 560 let data = char_img.data
  561. 561 let cell_w = w / grid_size
  562. 562 let cell_h = h / grid_size
  563. 563 let features : Array[Double] = []
  564. 564 for r in 0..<grid_size {
  565. 565● for c in 0..<grid_size {
  566. 566● let mut count = 0
  567. 567 let mut total = 0
  568. 568 for py in 0..<cell_h {
  569. 569● for px in 0..<cell_w {
  570. 570● let sx = c * cell_w + px
  571. 571 let sy = r * cell_h + py
  572. 572 if sx < w && sy < h {
  573. 573● total += 1
  574. 574● if data[sy * w + sx].to_int() > 128 {
  575. 575● count += 1
  576. 576 }
  577. 577 }
  578. 578 }
  579. 579 }
  580. 580 let density = if total > 0 {
  581. 581● count.to_double() / total.to_double()
  582. 582 } else {
  583. 583○ 0.0
  584. 584 }
  585. 585● features.push(density)
  586. 586 }
  587. 587 }
  588. 588 features
  589. 589}
  590. 590
  591. 591///|
  592. 592/// 多语言模板匹配
  593. 593fn match_multilingual_template(
  594. 594 features : Array[Double],
  595. 595 templates : Array[(String, Array[Double])],
  596. 596 distance_metric : String,
  597. 597) -> (String, Double) {
  598. 598● let mut best_label = "?"
  599. 599 let mut best_dist = 1000000.0
  600. 600 for _tup2 in templates {
  601. 601● let (label, template) = _tup2
  602. 602● let dist = match distance_metric {
  603. 603● "manhattan" => manhattan_ml(features, template)
  604. 604● "cosine" => cosine_ml(features, template)
  605. 605● _ => euclidean_ml(features, template)
  606. 606 }
  607. 607 if dist < best_dist {
  608. 608● best_dist = dist
  609. 609 best_label = label
  610. 610 }
  611. 611 }
  612. 612● let confidence = if best_dist > 0.0 { 1.0 / (1.0 + best_dist) } else { 1.0 }
  613. 613 (best_label, confidence)
  614. 614}
  615. 615
  616. 616///|
  617. 617/// 标点符号模板匹配
  618. 618fn match_punctuation_template(
  619. 619 features : Array[Double],
  620. 620 templates : Array[PunctuationTemplate],
  621. 621) -> (String, Double) {
  622. 622● let mut best_label = "?"
  623. 623 let mut best_dist = 1000000.0
  624. 624 for template in templates {
  625. 625● let dist = euclidean_ml(features, template.features)
  626. 626 if dist < best_dist {
  627. 627● best_dist = dist
  628. 628 best_label = template.char
  629. 629 }
  630. 630 }
  631. 631● let confidence = if best_dist > 0.0 { 1.0 / (1.0 + best_dist) } else { 1.0 }
  632. 632 (best_label, confidence)
  633. 633}
  634. 634
  635. 635///|
  636. 636/// 局部欧氏距离
  637. 637fn euclidean_ml(a : Array[Double], b : Array[Double]) -> Double {
  638. 638◐ let n = if a.length() < b.length() { a.length() } else { b.length() }
  639. 639 let mut sum_sq = 0.0
  640. 640 for i in 0..<n {
  641. 641● let diff = a[i] - b[i]
  642. 642 sum_sq += diff * diff
  643. 643 }
  644. 644● sum_sq.sqrt()
  645. 645}
  646. 646
  647. 647///|
  648. 648/// 局部曼哈顿距离
  649. 649fn manhattan_ml(a : Array[Double], b : Array[Double]) -> Double {
  650. 650◐ let n = if a.length() < b.length() { a.length() } else { b.length() }
  651. 651 let mut sum = 0.0
  652. 652 for i in 0..<n {
  653. 653● sum += (a[i] - b[i]).abs()
  654. 654 }
  655. 655 sum
  656. 656}
  657. 657
  658. 658///|
  659. 659/// 局部余弦距离
  660. 660fn cosine_ml(a : Array[Double], b : Array[Double]) -> Double {
  661. 661◐ let n = if a.length() < b.length() { a.length() } else { b.length() }
  662. 662 let mut dot = 0.0
  663. 663 let mut norm_a = 0.0
  664. 664 let mut norm_b = 0.0
  665. 665 for i in 0..<n {
  666. 666● dot += a[i] * b[i]
  667. 667 norm_a += a[i] * a[i]
  668. 668 norm_b += b[i] * b[i]
  669. 669 }
  670. 670● let denom = norm_a.sqrt() * norm_b.sqrt()
  671. 671 if denom > 0.0 {
  672. 672● 1.0 - dot / denom
  673. 673 } else {
  674. 674● 1.0
  675. 675 }
  676. 676}