Something went wrong. Try again.
Annotate fonts with ruby (pinyin/romaji) and produce modified TTF/WOFF2 outputs.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140//! Compiled dictionaries bundled with the binary.//!//! The data files under `data/` are generated by `cargo xtask update-dict`
use std::path::Path;
use anyhow::{Context, Result};use facet::Facet;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]pub enum Lang { /// Japanese words, readings in kana. Ja, /// Chinese words, readings in pinyin. Zh,}
impl Lang { pub fn name(self) -> &'static str { match self { Lang::Ja => "ja", Lang::Zh => "zh", } }}
/// A compiled dictionary.#[derive(Clone, Debug, Default, Facet)]pub struct Dictionary { /// Source datasets and the version each was compiled from. pub sources: Vec<(String, String)>, pub entries: Vec<DictionaryEntry>, /// Curated default readings in inline notation. pub defaults: Vec<String>, /// Forms never to annotate. pub bare: Vec<String>,}
/// One written form and its readings.#[derive(Clone, Debug, Default, Facet)]pub struct DictionaryEntry { pub form: String, pub readings: Vec<DictionaryReading>, /// A place name: it only fills runs no common word claims. pub place: bool,}
/// One reading of a form, with the metadata that ranks and selects it.#[derive(Clone, Debug, Default, Facet)]pub struct DictionaryReading { /// Alignment: `0:に;1:ほん`, or `0-1:きょう` for a reading spanning characters. pub words: String, /// Newspaper frequency bucket (0 when unranked). pub nf: u16, /// JLPT level listing this reading (0 when none). pub jlpt: u8, /// Priority tags, as a bitmask over [`crate::words::TAG_NAMES`]. pub tags: u16, /// Position of the reading among the form's readings, in JMdict order. pub order: u16, /// Uses in Tatoeba's example sentences. pub tatoeba: u16, /// Selected by the dictionary itself, whatever its ranking (CC-CEDICT /// entries carry no frequency metadata). pub common: bool, /// `来る`-type verb, whose kanji reads differently as it conjugates. pub conjugates: bool, /// Made the default by the curated list (1) or the user (2). pub pinned: u8,}
const ZLIB_LEVEL: u32 = 9;
pub fn encode(dictionary: &Dictionary) -> Result<Vec<u8>> { use std::io::Write;
let raw = facet_postcard::to_vec(dictionary) .map_err(|error| anyhow::anyhow!("Failed to serialize dictionary: {error:?}"))?; let mut encoder = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::new(ZLIB_LEVEL)); encoder .write_all(&raw) .context("Failed to compress dictionary")?;
encoder.finish().context("Failed to compress dictionary")}
pub fn decode(bytes: &[u8]) -> Result<Dictionary> { use std::io::Read;
let mut decoder = flate2::read::ZlibDecoder::new(bytes); let mut raw = Vec::new(); decoder .read_to_end(&mut raw) .context("Failed to decompress dictionary")?;
facet_postcard::from_slice(&raw) .map_err(|error| anyhow::anyhow!("Failed to decode dictionary: {error:?}"))}
pub fn load_path(path: &Path) -> Result<Dictionary> { let bytes = std::fs::read(path).with_context(|| format!("Failed to read dictionary {path:?}"))?;
decode(&bytes)}
#[cfg(feature = "dict-ja")]const DICT_JA: &[u8] = include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/data/dict-ja.bin"));#[cfg(not(feature = "dict-ja"))]const DICT_JA: &[u8] = &[];
#[cfg(feature = "dict-zh")]const DICT_ZH: &[u8] = include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/data/dict-zh.bin"));#[cfg(not(feature = "dict-zh"))]const DICT_ZH: &[u8] = &[];
/// Load the dictionary bundled for a language, if one is compiled in.pub fn load_bundled(lang: Lang) -> Option<Dictionary> { let bytes = match lang { Lang::Ja => DICT_JA, Lang::Zh => DICT_ZH, };
if bytes.is_empty() { return None; }
match decode(bytes) { Ok(dictionary) => Some(dictionary), Err(error) => { tracing::warn!( "Failed to decode bundled {} dictionary: {error:#}", lang.name() ); None } }}