diff --git a/NOTICE.md b/NOTICE.md index 15c2efca1..ff082379c 100644 --- a/NOTICE.md +++ b/NOTICE.md @@ -90,6 +90,8 @@ gitignore),用于生成词库数据文件,其各自适用原项目的许 `opencc/emoji.txt` 与 `opencc/others.txt`(emoji 附加模块;`others.txt` 构建期按分组剔除 `FROST_OTHERS_EXCLUDE` 所列的组后分发) - **另用于**: 笔画输入方案词库的权重(取 `cn_dicts/8105`、`41448` 的单字字频,见 rime-stroke 条目) +- **五笔补充库**: 从 `cn_dicts/base.dict.yaml` 中筛选高频缺词并生成五笔编码,产物 + `wubi86_frost.dict.yaml` 默认关闭;该派生词库适用 GPL-3.0。 #### ECDICT diff --git a/data/schemas/wubi86.schema.toml b/data/schemas/wubi86.schema.toml index 19e01b630..cda0a016c 100644 --- a/data/schemas/wubi86.schema.toml +++ b/data/schemas/wubi86.schema.toml @@ -71,6 +71,15 @@ base_order = 3 # 整库同权 ⟹ 库内自动按 natural_order(文件顺序)排列,即该库 yaml 里 `sort: original` 的本意。 default_weight = 500 +[[dictionaries]] +id = "wubi86_frost" +label = "白霜高频补充" +description = "从白霜拼音基础词库生成的五笔高频缺词,默认关闭" +path = "wubi86/wubi86_frost.dict.yaml" +type = "rime_codetable" +default_enabled = false +base_order = 4 + [encoder] max_word_length = 10 diff --git a/docs/architecture/candidate-behavior-changelog.md b/docs/architecture/candidate-behavior-changelog.md index 2fe724f40..e4d406fa0 100644 --- a/docs/architecture/candidate-behavior-changelog.md +++ b/docs/architecture/candidate-behavior-changelog.md @@ -27,6 +27,15 @@ --- +## 2026-11-20 · 五笔白霜高频补充词库 + +- 合入:待填;范围:五笔方案。 +- 变化:启用补充词库后,原词库缺失的白霜高频词可按五笔词组编码召回,例如 `rvtf` 的「招行」。 +- 触发条件:在方案扩展词库中启用「白霜高频补充」;出厂关闭。 +- 回退旧行为:关闭该扩展词库。 +- 钉住的测试:`wind-tools` 的 `gen_dict::frost::tests::generates_only_missing_high_frequency_words_with_full_codes`; + `wind-engine/tests/engine_manager.rs::wubi_frost_supplement_is_opt_in`。 + ## 2026-11-15 · 码表整句不再混入直通命令/模板源码(0.132) - 合入:待填(push 前回填);范围:码表整句模式 diff --git a/docs/architecture/engine-candidate-pipeline.md b/docs/architecture/engine-candidate-pipeline.md index e3a6b345f..4e4be2b78 100644 --- a/docs/architecture/engine-candidate-pipeline.md +++ b/docs/architecture/engine-candidate-pipeline.md @@ -122,6 +122,11 @@ DAT 从已排序编码列表 BFS 直接构建,峰值内存仅 base/check 两 ### 2.3 多层合并(CompositeDict) +五笔方案另提供默认关闭的「白霜高频补充」扩展层:构建时从白霜基础词库筛选频次 +不低于 1000 的 2–10 字纯汉字词,排除五笔主库和文字扩展库已有词,用五笔单字全码 +生成词码。补充词权重低于主库的最低保底配置值,但不保证低于主库每个词; +启用后仍可能增加重码、改变候选顺序并影响自动上屏。 + `DictManager`(manager.rs:15-52)持一个方案的 `CompositeDict`(composite.rs),层类型优先级 (layer.rs):**Logic(0) > User(1) > Temp(2) > Cell(3) > System(4)**。 diff --git a/scripts/dev.ps1 b/scripts/dev.ps1 index 749d0eb36..9e2ce0ad9 100644 --- a/scripts/dev.ps1 +++ b/scripts/dev.ps1 @@ -828,6 +828,7 @@ function Verify-DistData ([string]$outdir = $BuildDir) { # 否则打出来的包五笔方案整个不可用 @{ Path = "schemas\wubi86\wubi86_jidian.dict.yaml"; Min = 1000000 }, @{ Path = "schemas\wubi86\wubi86_jidian_extra.dict.yaml"; Min = 10000 }, + @{ Path = "schemas\wubi86\wubi86_frost.dict.yaml"; Min = 100 }, @{ Path = "schemas\wubi86\wubi86_jidian_emoji.dict.yaml"; Min = 1000 }, @{ Path = "schemas\wubi86\wubi86_jidian_extra_district.dict.yaml"; Min = 10000 }, # 辅助码表同为生成物、同样不入库。功能虽出厂关闭, 缺表的后果仍是「用户在设置里 diff --git a/scripts/dev.sh b/scripts/dev.sh index 27756c03d..0ff166720 100755 --- a/scripts/dev.sh +++ b/scripts/dev.sh @@ -1321,6 +1321,7 @@ verify_dist_data() { # 五笔词库为 gen_dict 生成物、不入版本库 —— 忘跑 gen-data 时必须在此拦下 "schemas/wubi86/wubi86_jidian.dict.yaml|1000000" "schemas/wubi86/wubi86_jidian_extra.dict.yaml|10000" + "schemas/wubi86/wubi86_frost.dict.yaml|100" "schemas/wubi86/wubi86_jidian_emoji.dict.yaml|1000" "schemas/wubi86/wubi86_jidian_extra_district.dict.yaml|10000" # 笔画方案词库同为 gen_aux_code 生成物(实测约 1MB);全拼默认辅助码经 schema:stroke diff --git a/scripts/linux/verify-deb.sh b/scripts/linux/verify-deb.sh index 1b805d171..52f030fd6 100755 --- a/scripts/linux/verify-deb.sh +++ b/scripts/linux/verify-deb.sh @@ -71,6 +71,7 @@ check_min schemas/wubi86/wubi86_jidian.dict.yaml 1000000 check_min schemas/pinyin/cn_dicts/8105.dict.yaml 10000 check_min schemas/english/en.dict.yaml 1000 check_min schemas/wubi86/wubi86_jidian_extra.dict.yaml 10000 +check_min schemas/wubi86/wubi86_frost.dict.yaml 100 check_min schemas/wubi86/wubi86_jidian_emoji.dict.yaml 1000 check_min schemas/wubi86/wubi86_jidian_extra_district.dict.yaml 10000 check_min opencc/STPhrases.octrie 100000 diff --git a/scripts/linux/verify-rpm.sh b/scripts/linux/verify-rpm.sh index 0395823e4..dc9af3d1b 100755 --- a/scripts/linux/verify-rpm.sh +++ b/scripts/linux/verify-rpm.sh @@ -60,6 +60,7 @@ check_min() { } check_min schemas/pinyin/cn_dicts/base.dict.yaml 1000000 check_min schemas/wubi86/wubi86_jidian.dict.yaml 1000000 +check_min schemas/wubi86/wubi86_frost.dict.yaml 100 check_min schemas/pinyin/cn_dicts/8105.dict.yaml 10000 check_min schemas/english/en.dict.yaml 1000 check_min opencc/STPhrases.octrie 100000 diff --git a/scripts/mac/dev.sh b/scripts/mac/dev.sh index 4538b51ef..20758d784 100755 --- a/scripts/mac/dev.sh +++ b/scripts/mac/dev.sh @@ -1083,6 +1083,7 @@ verify_dist_data() { # 五笔词库为 gen_dict 生成物、不入版本库 —— 忘跑 gd 时必须在此拦下 _check_min "schemas/wubi86/wubi86_jidian.dict.yaml" 1000000 _check_min "schemas/wubi86/wubi86_jidian_extra.dict.yaml" 10000 + _check_min "schemas/wubi86/wubi86_frost.dict.yaml" 100 _check_min "schemas/wubi86/wubi86_jidian_emoji.dict.yaml" 1000 _check_min "schemas/wubi86/wubi86_jidian_extra_district.dict.yaml" 10000 # 笔画方案词库同为 gen_aux_code 生成物; 全拼默认辅助码经 schema:stroke 引用它 diff --git a/wind_input/Cargo.lock b/wind_input/Cargo.lock index eb056a987..cb8d38383 100644 --- a/wind_input/Cargo.lock +++ b/wind_input/Cargo.lock @@ -2534,6 +2534,7 @@ dependencies = [ "serde", "toml 0.8.23", "wind-candidate", + "wind-utils", ] [[package]] diff --git a/wind_input/apps/wind-tools/Cargo.toml b/wind_input/apps/wind-tools/Cargo.toml index 007cf0d89..98d66f0c3 100644 --- a/wind_input/apps/wind-tools/Cargo.toml +++ b/wind_input/apps/wind-tools/Cargo.toml @@ -33,6 +33,7 @@ path = "src/bin/gen_aux_code.rs" [dependencies] # gen_block_charsets 直接读区块表生成 charsets/blocks.yaml——两份数据因此同源。 wind-candidate = { path = "../../crates/wind-candidate" } +wind-utils = { path = "../../crates/wind-utils" } anyhow = { workspace = true } serde = { workspace = true } toml = { workspace = true } diff --git a/wind_input/apps/wind-tools/src/bin/gen_dict/frost.rs b/wind_input/apps/wind-tools/src/bin/gen_dict/frost.rs new file mode 100644 index 000000000..2bf6ae8a3 --- /dev/null +++ b/wind_input/apps/wind-tools/src/bin/gen_dict/frost.rs @@ -0,0 +1,170 @@ +//! 从白霜基础词库生成低权重的五笔补充词条。 + +use crate::entry::{Entry, is_valid_code}; +use crate::reverse::{CharCodes, encode_phrase}; +use std::collections::{HashMap, HashSet}; +use std::path::Path; + +const MIN_FREQUENCY: u64 = 1000; + +pub fn generate( + source: &Path, + main: &[Entry], + extra: &[Entry], + main_floor: i64, +) -> anyhow::Result> { + if main_floor <= 1 { + anyhow::bail!("主词库最低权重必须大于 1,才能生成低权重补充词库"); + } + let content = std::fs::read_to_string(source) + .map_err(|e| anyhow::anyhow!("读取白霜基础词库失败 {}: {e}", source.display()))?; + let normalized = wind_utils::text::normalize_input(&content); + let mut best: HashMap = HashMap::new(); + for entry in main.iter().chain(extra) { + let mut chars = entry.text.chars(); + let (Some(ch), None) = (chars.next(), chars.next()) else { + continue; + }; + let len = entry.code.len(); + if !(2..=4).contains(&len) || !is_valid_code(&entry.code) { + continue; + } + let replace = best.get(&ch).is_none_or(|cur| { + len > cur.code.len() + || (len == cur.code.len() + && (entry.weight > cur.weight + || (entry.weight == cur.weight && entry.code < cur.code))) + }); + if replace { + best.insert(ch, entry); + } + } + let codes: CharCodes = best + .into_iter() + .map(|(ch, e)| (ch, e.code.clone())) + .collect(); + let existing: HashSet<&str> = main.iter().chain(extra).map(|e| e.text.as_str()).collect(); + let mut frequencies: HashMap = HashMap::new(); + let mut in_body = false; + let mut eligible = 0usize; + for line in normalized.lines() { + if !in_body { + if line.trim() == "..." { + in_body = true; + } + continue; + } + let mut columns = line.split('\t'); + let Some(text) = columns.next() else { continue }; + let _pinyin = columns.next(); + let Some(freq) = columns.next().and_then(|v| v.trim().parse::().ok()) else { + continue; + }; + if freq < MIN_FREQUENCY + || !(2..=10).contains(&text.chars().count()) + || !text.chars().all(|c| ('\u{4e00}'..='\u{9fff}').contains(&c)) + { + continue; + } + eligible += 1; + if existing.contains(text) { + continue; + } + frequencies + .entry(text.to_owned()) + .and_modify(|f| *f = (*f).max(freq)) + .or_insert(freq); + } + if !in_body { + anyhow::bail!("白霜基础词库缺少正文分隔符: {}", source.display()); + } + if eligible == 0 { + anyhow::bail!("白霜基础词库没有符合条件的高频词: {}", source.display()); + } + let total = frequencies.len(); + let mut out: Vec = frequencies + .into_iter() + .filter_map(|(text, freq)| { + let code = encode_phrase(&text, &codes)?; + let weight = ((freq as f64).log10() * 10.0).round() as i64; + Some(Entry::new(text, code, weight.clamp(1, main_floor - 1), 0)) + }) + .collect(); + eprintln!( + " 白霜补充词库跳过 {} 条无法编码的词", + total - out.len() + ); + if total > 0 && out.is_empty() { + anyhow::bail!("白霜高频缺词均无法按五笔单字码编码"); + } + out.sort_by(|a, b| { + a.code + .cmp(&b.code) + .then_with(|| b.weight.cmp(&a.weight)) + .then_with(|| a.text.cmp(&b.text)) + }); + Ok(out) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::io::Write; + + fn e(text: &str, code: &str, weight: i64) -> Entry { + Entry::new(text.into(), code.into(), weight, 0) + } + + #[test] + fn generates_only_missing_high_frequency_words_with_full_codes() { + let path = std::env::temp_dir().join(format!("wind-frost-{}.yaml", std::process::id())); + let mut file = std::fs::File::create(&path).unwrap(); + write!(file, "---\nname: base\n...\n招行\tzhao hang\t1348\n招行\tzhao hang\t2000\n招招\tzhao zhao\t1000\n行行\thang hang\t999\n招鑫\tzhao xin\t1000\n招A\tzhao a\t1000\n").unwrap(); + drop(file); + let main = [ + e("招", "rvk", 100), + e("招", "rvkg", 10), + e("行", "tfhh", 10), + ]; + let extra = [e("招招", "rvrv", 10)]; + let result = generate(&path, &main, &extra, 120).unwrap(); + std::fs::remove_file(path).unwrap(); + assert_eq!(result.len(), 1); + assert_eq!((&result[0].text[..], &result[0].code[..]), ("招行", "rvtf")); + assert!((1..120).contains(&result[0].weight)); + } + + #[test] + fn complete_existing_dictionary_produces_an_empty_supplement() { + let path = + std::env::temp_dir().join(format!("wind-frost-complete-{}.yaml", std::process::id())); + std::fs::write(&path, "---\nname: base\n...\n招行\tzhao hang\t1348\n").unwrap(); + let result = generate(&path, &[e("招行", "rvtf", 100)], &[], 120).unwrap(); + std::fs::remove_file(path).unwrap(); + assert!(result.is_empty()); + } + + #[test] + fn normalizes_bom_and_lone_cr_line_endings() { + let path = std::env::temp_dir().join(format!("wind-frost-cr-{}.yaml", std::process::id())); + std::fs::write( + &path, + "\u{feff}---\rname: base\r...\r招行\tzhao hang\t1348\r", + ) + .unwrap(); + let main = [e("招", "rvk", 100), e("行", "tfhh", 10)]; + let result = generate(&path, &main, &[], 120).unwrap(); + std::fs::remove_file(path).unwrap(); + assert_eq!(result.len(), 1); + assert_eq!((&result[0].text[..], &result[0].code[..]), ("招行", "rvtf")); + } + + #[test] + fn invalid_source_is_not_silently_accepted() { + let path = + std::env::temp_dir().join(format!("wind-frost-invalid-{}.yaml", std::process::id())); + std::fs::write(&path, "---\nname: base\n").unwrap(); + assert!(generate(&path, &[], &[], 120).is_err()); + std::fs::remove_file(path).unwrap(); + } +} diff --git a/wind_input/apps/wind-tools/src/bin/gen_dict/main.rs b/wind_input/apps/wind-tools/src/bin/gen_dict/main.rs index 88c23f0d5..22dfb0f38 100644 --- a/wind_input/apps/wind-tools/src/bin/gen_dict/main.rs +++ b/wind_input/apps/wind-tools/src/bin/gen_dict/main.rs @@ -14,6 +14,7 @@ mod boost; mod config; mod entry; mod extra; +mod frost; mod order_report; mod parse; mod reverse; @@ -136,10 +137,10 @@ fn main() -> anyhow::Result<()> { } eprintln!(); - run(&cfg, &paths, &version) + run(&cfg, &paths, &version, &args.cache) } -fn run(cfg: &Config, paths: &config::Paths, version: &str) -> anyhow::Result<()> { +fn run(cfg: &Config, paths: &config::Paths, version: &str, cache: &Path) -> anyhow::Result<()> { let mut log = |s: String| eprintln!("{s}"); // ── 1. unigram ──────────────────────────────────── @@ -367,10 +368,30 @@ fn run(cfg: &Config, paths: &config::Paths, version: &str) -> anyhow::Result<()> .unwrap_or(0); eprintln!(" 完成: {} 条,{size_kb} KB", kept.len()); - if cfg.extra.enabled - && let Err(e) = process_extra(cfg, paths, &unigram, log_median, &char_codes, version) - { - eprintln!(" [警告] extra 处理失败: {e}"); + if cfg.extra.enabled { + let input = paths + .extra_input + .as_ref() + .ok_or_else(|| anyhow::anyhow!("extra.input_path 未配置"))?; + if !input.is_file() { + anyhow::bail!("五笔扩展词库不存在: {}", input.display()); + } + process_extra(cfg, paths, &unigram, log_median, &char_codes, version)?; + let extra_path = extra::extra_output_path(&paths.output, &cfg.output_name, "extra"); + let existing_extra = parse::parse_jidian(&extra_path)?; + let source = cache + .join("rime-frost") + .join("cn_dicts") + .join("base.dict.yaml"); + let supplement = + frost::generate(&source, &kept, &existing_extra, cfg.fallback.priority_10)?; + let supplement_path = paths.output.with_file_name("wubi86_frost.dict.yaml"); + writer::write_frost_dict(&supplement_path, &supplement, version)?; + eprintln!( + " 白霜补充词库: {} 条 → {}", + supplement.len(), + supplement_path.display() + ); } // 原样透传的词库:只清洗头部,条目顺序即数据,不得重排 diff --git a/wind_input/apps/wind-tools/src/bin/gen_dict/writer.rs b/wind_input/apps/wind-tools/src/bin/gen_dict/writer.rs index 9250612ed..77993cc36 100644 --- a/wind_input/apps/wind-tools/src/bin/gen_dict/writer.rs +++ b/wind_input/apps/wind-tools/src/bin/gen_dict/writer.rs @@ -43,6 +43,25 @@ fn atomic_write( Ok(()) } +pub fn write_frost_dict(path: &Path, entries: &[Entry], version: &str) -> anyhow::Result<()> { + atomic_write(path, |w| { + writeln!(w, "# 白霜拼音基础词库生成的五笔补充词库,GPL-3.0")?; + writeln!(w, "# 来源: https://github.com/gaboolic/rime-frost")?; + writeln!(w, "---")?; + writeln!(w, "name: wubi86_frost")?; + writeln!(w, "version: \"{version}\"")?; + writeln!(w, "columns:")?; + writeln!(w, " - code")?; + writeln!(w, " - text")?; + writeln!(w, " - weight")?; + writeln!(w, "...")?; + for e in entries { + writeln!(w, "{}\t{}\t{}", e.code, e.text, e.weight)?; + } + Ok(()) + }) +} + /// 写出五笔主词库。 pub fn write_main_dict( path: &Path, diff --git a/wind_input/crates/wind-engine/tests/engine_manager.rs b/wind_input/crates/wind-engine/tests/engine_manager.rs index cb22d0bad..7957ed3b4 100644 --- a/wind_input/crates/wind-engine/tests/engine_manager.rs +++ b/wind_input/crates/wind-engine/tests/engine_manager.rs @@ -32,6 +32,66 @@ fn schema_exists(dir: &std::path::Path, id: &str) -> bool { || dir.join(format!("schemas/{}.schema.yaml", id)).exists() } +#[test] +fn wubi_frost_supplement_is_opt_in() { + let id = format!( + "wubi_frost_{}_{}", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos() + ); + let dir = std::env::temp_dir().join(&id); + let schemas = dir.join("schemas"); + let dict_dir = schemas.join("wubi86"); + std::fs::create_dir_all(&dict_dir).unwrap(); + let schema = std::fs::read_to_string( + PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../../data/schemas/wubi86.schema.toml"), + ) + .unwrap() + .replacen("id = \"wubi86\"", &format!("id = \"{id}\""), 1); + let schema_path = schemas.join(format!("{id}.schema.toml")); + std::fs::write(&schema_path, &schema).unwrap(); + let dict = |body: &str| { + format!("---\nname: test\ncolumns:\n - code\n - text\n - weight\n...\n{body}") + }; + std::fs::write( + dict_dir.join("wubi86_jidian.dict.yaml"), + dict("rvtf\t其他\t150\n"), + ) + .unwrap(); + std::fs::write( + dict_dir.join("wubi86_frost.dict.yaml"), + dict("rvtf\t招行\t31\n"), + ) + .unwrap(); + let cfg = make_config(&[&id]); + let mgr = + EngineManager::with_store_override(&cfg, Some(&dir), None, Some(dir.join("overrides"))); + let has_word = |m: &EngineManager| { + m.convert("rvtf", 50) + .candidates + .iter() + .any(|c| c.text == "招行") + }; + assert!(!has_word(&mgr), "补充库默认关闭"); + + let overrides = dir.join("overrides"); + std::fs::create_dir_all(&overrides).unwrap(); + std::fs::write( + overrides.join(format!("{id}.toml")), + "[[dictionaries]]\nid = \"wubi86_frost\"\nenabled = true\n", + ) + .unwrap(); + mgr.set_dict_enabled_live(&id, "wubi86_frost", true); + let result = mgr.convert("rvtf", 50); + assert!(result.candidates.iter().any(|c| c.text == "招行")); + assert_eq!(result.candidates[0].text, "其他"); + drop(mgr); + std::fs::remove_dir_all(dir).unwrap(); +} + /// english 方案(隐藏,懒加载):ensure_schema 应可加载,convert_with 前缀查词命中, /// 候选来源标记为 English,且无自动上屏。词库/schema 缺失时跳过。 #[test] diff --git a/wind_linux/nix/data.nix b/wind_linux/nix/data.nix index 1c01cd66b..912bd3336 100644 --- a/wind_linux/nix/data.nix +++ b/wind_linux/nix/data.nix @@ -313,6 +313,7 @@ stdenv.mkDerivation { "$data/schemas/pinyin/cn_dicts/base.dict.yaml" \ "$data/schemas/wubi86/wubi86_jidian.dict.yaml" \ "$data/schemas/wubi86/wubi86_jidian_extra.dict.yaml" \ + "$data/schemas/wubi86/wubi86_frost.dict.yaml" \ "$data/schemas/stroke/stroke.dict.yaml" \ "$data/opencc/STCharacters.octrie" \ "$data/emoji/emoji_word.txt" \