### Example Search Queries Source: https://docs.rs/haqumei/0.7.0/haqumei/struct.Haqumei.html?search= These are example search queries demonstrating different search patterns. They can be used as a starting point for your own searches. ```text std::vec ``` ```text u32 -> bool ``` ```text Option, (T -> U) -> Option ``` -------------------------------- ### Haqumei::new Source: https://docs.rs/haqumei/0.7.0/src/haqumei/lib.rs.html?search=std%3A%3Avec Initializes a new Haqumei instance with default settings and OpenJTalk. This is the simplest way to get started. ```APIDOC ## Haqumei::new ### Description Initializes a new Haqumei instance with default settings and OpenJTalk. This is the simplest way to get started. ### Method `new()` ### Returns - `Result`: A `Result` containing the initialized `Haqumei` instance or a `HaqumeiError` if initialization fails. ``` -------------------------------- ### Initialize Haqumei Source: https://docs.rs/haqumei/0.7.0/src/haqumei/lib.rs.html?search=u32+-%3E+bool Creates a new Haqumei instance with default options. This is the simplest way to get started. ```rust use haqumei::Haqumei; let mut haqumei = Haqumei::new().unwrap(); ``` -------------------------------- ### Initialize Haqumei with Default Options Source: https://docs.rs/haqumei/0.7.0/src/haqumei/lib.rs.html?search=std%3A%3Avec Creates a new Haqumei instance with default OpenJTalk settings and options. This is the simplest way to get started. ```rust pub fn new() -> Result { Self::from_open_jtalk(OpenJTalk::new()?, HaqumeiOptions::default()) } ``` -------------------------------- ### Example Search: Option mapping Source: https://docs.rs/haqumei/0.7.0/haqumei/prosody/enum.PitchAccent.html?search= Demonstrates a search pattern for mapping Option with a function from T to U. ```text Option, (T -> U) -> Option ``` -------------------------------- ### Example Search: std::vec Source: https://docs.rs/haqumei/0.7.0/haqumei/prosody/enum.PitchAccent.html?search= Illustrates a basic search pattern for std::vec. ```text std::vec ``` -------------------------------- ### Example: Detailed G2P Mapping for Japanese Text Source: https://docs.rs/haqumei/0.7.0/src/haqumei/lib.rs.html?search=std%3A%3Avec Demonstrates how to use `g2p_mapping_detailed` to get a structured phoneme representation of a Japanese word, including its detailed linguistic features. ```rust use haqumei::Haqumei; let mut haqumei = Haqumei::new().unwrap(); let mapping = haqumei.g2p_mapping_detailed("薄明").unwrap(); // 結果: // [ WordPhonemeDetail { // word: "薄明", // phonemes: [ // "h", // "a", // "k", // "u", // "m", // "e", // "e", // ], // features: [ // "薄明", // "名詞", // "一般", // "*", // "*", // "*", // "*", // "薄明", // "ハクメイ", // "ハクメー", // "0/4", // "C2", // ], // pos: "名詞", // pos_group1: "一般", // pos_group2: "*", // pos_group3: "*", // ctype: "*", // cform: "*", // orig: "薄明", // read: "ハクメイ", // pron: "ハクメー", // accent_nucleus: 0, // mora_count: 4, // chain_rule: "C2", // chain_flag: -1, // is_unknown: false, // is_ignored: false, // } // ] ``` -------------------------------- ### Example Search Queries Source: https://docs.rs/haqumei/0.7.0/src/haqumei/lib.rs.html?search= Demonstrates common search query patterns in Rust, such as searching for standard library types, type conversions, and functional transformations. ```rust * std::vec * u32 -> bool * Option, (T -> U) -> Option ``` -------------------------------- ### Get Word-Level Phoneme Pairs with Example Source: https://docs.rs/haqumei/0.7.0/src/haqumei/open_jtalk.rs.html?search=u32+-%3E+bool Demonstrates how to use `g2p_pairs` to get phoneme sequences for each word in a given text. Shows the expected output structure for various Japanese characters and words. ```rust use haqumei::OpenJTalk; let mut open_jtalk = OpenJTalk::new().unwrap(); let pairs = open_jtalk.g2p_pairs("𰻞𰻞麺&お冷を頼んだ").unwrap(); // 結果: // [WordPhonemePair { // word: "𰻞𰻞", // phonemes: ["pau"] // }, WordPhonemePair { // word: "麺", // phonemes: ["m", "e", "N"] // }, WordPhonemePair { // word: "&", // phonemes: ["a", "N", "d", "o"] // }, WordPhonemePair { // word: "お冷", // phonemes: ["o", "h", "i", "y", "a"] // }, WordPhonemePair { // word: "を", // phonemes: ["o"] // }, WordPhonemePair { // word: "頼ん", // phonemes: ["t", "a", "n", "o", "N"] // }, WordPhonemePair { // word: "だ", // phonemes: ["d", "a"] // }] ``` -------------------------------- ### Example Search: u32 to bool Source: https://docs.rs/haqumei/0.7.0/haqumei/prosody/enum.PitchAccent.html?search= Shows a search pattern for type conversion from u32 to bool. ```text u32 -> bool ``` -------------------------------- ### Get Detailed Word Phoneme Mapping with Example Source: https://docs.rs/haqumei/0.7.0/src/haqumei/open_jtalk.rs.html?search=u32+-%3E+bool Illustrates the usage of `g2p_mapping` to obtain a detailed phoneme breakdown for text. The example shows how unknown words are represented as `["unk"]` and spaces as `["sp"]`. ```rust use haqumei::OpenJTalk; let mut open_jtalk = OpenJTalk::new().unwrap(); let mapping = open_jtalk.g2p_mapping("𰻞𰻞麺 お冷を頼んだ").unwrap(); // 結果: // [WordPhonemeMap { // word: "𰻞𰻞", // phonemes: ["unk"], // is_unknown: true, // is_ignored: false, // }, // WordPhonemeMap { // word: "麺", // phonemes: ["m", "e", "N"], // is_unknown: false, // is_ignored: false, // }, // WordPhonemeMap { // word: "\u{3000}", // phonemes: ["sp"], // is_unknown: false, // is_ignored: true, // }, // WordPhonemeMap { // word: "を", // phonemes: ["o"], // is_unknown: false, // is_ignored: false, // }, // WordPhonemeMap { // word: "\u{3000}", // phonemes: ["sp"], // is_unknown: false, // is_ignored: true, // }, // WordPhonemeMap { // word: "食べる", // phonemes: ["t", "a", "b", "e", "r", "u"], // is_unknown: false, // is_ignored: false, // }] ``` -------------------------------- ### Example: g2p_prosody with Default Format Source: https://docs.rs/haqumei/0.7.0/src/haqumei/lib.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates the usage of `g2p_prosody` with the default format for converting Japanese sentences into phoneme sequences with prosodic annotations. Shows expected output for different sentences. ```rust # use haqumei::Haqumei; # fn main() -> Result<(), Box> { # let mut haqumei = Haqumei::new()?; # # let phones = haqumei.g2p_prosody("こんにちは、世界!")?; # assert_eq!(phones.join(" "), "^ k o [ N n i ch i w a _ s e ] k a i ! $"); # # let phones = haqumei.g2p_prosody("青い空が、好きだ。")?; # assert_eq!(phones.join(" "), "^ a [ o ] i # s o ] r a g a _ s U [ k i ] d a _ $"); # # Ok(()) # } ``` -------------------------------- ### G2P Conversion Example Source: https://docs.rs/haqumei/0.7.0/haqumei/struct.Haqumei.html?search=u32+-%3E+bool Converts input text into a flat list of phonemes. Chain with `.join(" ")` for output similar to pyopenjtalk. ```rust use haqumei::Haqumei; let mut haqumei = Haqumei::new().unwrap(); // Ok(["k", "o", "N", "n", "i", "ch", "i", "w", "a"]) println!("{:?}", haqumei.g2p("こんにちは")); ``` -------------------------------- ### Example: Convert Text to Phonemes with Prosody (Default) Source: https://docs.rs/haqumei/0.7.0/src/haqumei/lib.rs.html?search= Demonstrates converting Japanese sentences to phonemes with prosody symbols using the default format. Asserts the expected output for specific inputs. ```rust # use haqumei::Haqumei; # fn main() -> Result<(), Box> { # let mut haqumei = Haqumei::new()?; let phones = haqumei.g2p_prosody("こんにちは、世界!")?; assert_eq!(phones.join(" "), "^ k o [ N n i ch i w a _ s e ] k a i ! $"); let phones = haqumei.g2p_prosody("青い空が、好きだ。")?; assert_eq!(phones.join(" "), "^ a [ o ] i # s o ] r a g a _ s U [ k i ] d a _ $"); # Ok(()) # } ``` -------------------------------- ### Example: G2P Conversion Source: https://docs.rs/haqumei/0.7.0/src/haqumei/open_jtalk.rs.html?search=u32+-%3E+bool Demonstrates converting Japanese text to a phoneme sequence using the `g2p` function. The output is printed as a debug representation of the vector. ```rust use haqumei::OpenJTalk; let mut open_jtalk = OpenJTalk::new().unwrap(); // Ok(["k", "o", "N", "n", "i", "ch", "i", "w", "a"]) println!("{:?}", open_jtalk.g2p("こんにちは")); ``` -------------------------------- ### Example: g2p_prosody with Japanese Text Source: https://docs.rs/haqumei/0.7.0/src/haqumei/open_jtalk.rs.html?search=std%3A%3Avec Demonstrates the usage of `g2p_prosody` to convert Japanese sentences into phoneme sequences with prosody symbols. Shows expected output for different sentence structures. ```rust let phones = haqumei.g2p_prosody("こんにちは、世界!")?; assert_eq!(phones.join(" "), "^ k o [ N n i ch i w a _ s e ] k a i ! $"); let phones = haqumei.g2p_prosody("青い空が、好きだ。")?; assert_eq!(phones.join(" "), "^ a [ o ] i # s o ] r a g a _ s U [ k i ] d a _ $"); ``` -------------------------------- ### Initialize Tokenizer and Get it if Enabled Source: https://docs.rs/haqumei/0.7.0/src/haqumei/lib.rs.html?search=std%3A%3Avec Initializes the tokenizer if `use_unidic_yomi` is enabled in options and returns a clone of it. Returns `None` if not enabled. ```rust pub(crate) fn init_tokenizer_if_needed_and_modify_kanji_yomi_enabled( &mut self, ) -> Result, HaqumeiError> { if self.options.use_unidic_yomi { self.init_tokenizer_if_needed()?; Ok(self.tokenizer.clone()) // かなり無料 } else { Ok(None) } } ``` -------------------------------- ### Example: Detailed G2P Conversion Source: https://docs.rs/haqumei/0.7.0/src/haqumei/open_jtalk.rs.html?search=u32+-%3E+bool Demonstrates detailed phoneme conversion for Japanese text, including handling of unknown characters. The output is printed as a debug representation of the vector. ```rust use haqumei::OpenJTalk; let mut open_jtalk = OpenJTalk::new().unwrap(); // Ok(["k", "o", "N", "n", "i", "ch", "i", "w", "a", "sp", "unk", "m", "e", "N"]) println!("{:?}", open_jtalk.g2p_detailed("こんにちは 𰻞𰻞麺")); ``` -------------------------------- ### Type 'u32' as Generic Parameter Example Source: https://docs.rs/haqumei/0.7.0/haqumei/open_jtalk/fn.build_mecab_dictionary.html?search=u32+-%3E+bool Demonstrates the usage of 'u32' as a generic parameter 'K' in various 'equivalent' methods. ```rust where u32 matches K ``` -------------------------------- ### Detailed G2P Conversion Example Source: https://docs.rs/haqumei/0.7.0/haqumei/struct.Haqumei.html?search=u32+-%3E+bool Performs a detailed G2P conversion, retaining information about known words, unknown words, and spaces. Chain with `.join(" ")` for output similar to pyopenjtalk. ```rust use haqumei::Haqumei; let mut haqumei = Haqumei::new().unwrap(); // Ok(["k", "o", "N", "n", "i", "ch", "i", "w", "a", "sp", "unk", "m", "e", "N"]) println!("{:?}", haqumei.g2p_detailed("こんにちは 𰻞𰻞麺")); ``` -------------------------------- ### Example: g2p_mapping usage Source: https://docs.rs/haqumei/0.7.0/src/haqumei/open_jtalk.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Illustrates the usage of the `g2p_mapping` function to obtain detailed word-phoneme mappings, including information about unknown words and ignored tokens. Shows the structure of the returned `WordPhonemeMap`. ```Rust use haqumei::OpenJTalk; let mut open_jtalk = OpenJTalk::new().unwrap(); let mapping = open_jtalk.g2p_mapping("𰻞𰻞麺 お冷を頼んだ").unwrap(); // 結果: // [WordPhonemeMap { // word: "𰻞𰻞", // phonemes: ["unk"], // is_unknown: true, // is_ignored: false, // }, // WordPhonemeMap { // word: "麺", // phonemes: ["m", "e", "N"], // is_unknown: false, // is_ignored: false, // }, // WordPhonemeMap { // word: "\u{3000}", // phonemes: ["sp"], // is_unknown: false, // is_ignored: true, // }, // WordPhonemeMap { // word: "を", // phonemes: ["o"], // is_unknown: false, // is_ignored: false, // }, // WordPhonemeMap { // word: "\u{3000}", // phonemes: ["sp"], // is_unknown: false, // is_ignored: true, // }, // WordPhonemeMap { // word: "食べる", // phonemes: ["t", "a", "b", "e", "r", "u"], // is_unknown: false, // is_ignored: false, // }] // ``` ``` -------------------------------- ### Example: Prosody-Annotated Phoneme List for "青い空が、好きだ。" Source: https://docs.rs/haqumei/0.7.0/src/haqumei/lib.rs.html?search=u32+-%3E+bool Demonstrates the output of `g2p_prosody` for the Japanese phrase "青い空が、好きだ。", showing sentence start/end, pauses, and accent information. ```rust let phones = haqumei.g2p_prosody("青い空が、好きだ。")?; assert_eq!(phones.join(" "), "^ a [ o ] i # s o ] r a g a _ s U [ k i ] d a _ $"); ``` -------------------------------- ### Example: Detailed Phoneme Mapping Source: https://docs.rs/haqumei/0.7.0/src/haqumei/lib.rs.html?search= Demonstrates how to obtain detailed linguistic and prosodic information for Japanese text, including word-level features and phoneme mappings. This is useful for advanced speech synthesis tasks requiring structured data. ```rust use haqumei::Haqumei; let mut haqumei = Haqumei::new().unwrap(); let mapping = haqumei.g2p_mapping_detailed("薄明").unwrap(); ``` -------------------------------- ### Example: Prosody-Annotated Phoneme List for "こんにちは、世界!" Source: https://docs.rs/haqumei/0.7.0/src/haqumei/lib.rs.html?search=u32+-%3E+bool Demonstrates the output of `g2p_prosody` for the Japanese phrase "こんにちは、世界!", showing sentence start/end, pauses, and accent information. ```rust let phones = haqumei.g2p_prosody("こんにちは、世界!")?; assert_eq!(phones.join(" "), "^ k o [ N n i ch i w a _ s e ] k a i ! $"); ``` -------------------------------- ### Option and Function Type Conversion Example Source: https://docs.rs/haqumei/0.7.0/src/haqumei/features.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates converting a function that takes a T and returns an Option to a function that takes an Option and returns an Option. This is useful for chaining operations on optional values. ```rust pub fn option_map(opt: Option, f: impl FnOnce(T) -> Option) -> Option { opt.and_then(f) } ``` -------------------------------- ### Rust Option Mapping Example Source: https://docs.rs/haqumei/0.7.0/src/haqumei/open_jtalk/njd.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates how to use the `map` method on an Option to transform its contained value if it exists. This is useful for applying a function to an optional value without needing to explicitly unwrap it. ```rust let maybe_number = Some(5); let maybe_squared = maybe_number.map(|x| x * x); let no_number: Option = None; let no_squared = no_number.map(|x| x * x); println!("Some(5) squared is {:?}", maybe_squared); // Output: Some(25) println!("None squared is {:?}", no_squared); // Output: None ``` -------------------------------- ### Haqumei::with_options Source: https://docs.rs/haqumei/0.7.0/haqumei/struct.Haqumei.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Initializes a Haqumei instance with custom options, allowing for output customization. ```APIDOC ## Haqumei::with_options ### Description Customizes the output by using `HaqumeiOptions`. ### Method `pub fn with_options(options: HaqumeiOptions) -> Result` ### Parameters * `options` (HaqumeiOptions) - The options to configure the Haqumei instance. ``` -------------------------------- ### Rust Function Examples Source: https://docs.rs/haqumei/0.7.0/src/haqumei/features.rs.html?search=std%3A%3Avec These are examples of Rust functions that access specific features based on ranges. They are used for retrieving string slices from a larger feature string. ```rust pub fn a_con_type(&self) -> &str { &self.feature[self.feature_ranges[25].clone()] } #[track_caller] pub fn a_mod_type(&self) -> &str { &self.feature[self.feature_ranges[26].clone()] } #[track_caller] pub fn lid(&self) -> &str { &self.feature[self.feature_ranges[27].clone()] } #[track_caller] pub fn lemma_id(&self) -> &str { &self.feature[self.feature_ranges[28].clone()] } } ``` -------------------------------- ### Any Trait Source: https://docs.rs/haqumei/0.7.0/haqumei/prosody/enum.PitchAccent.html?search= Provides the `type_id` method to get the `TypeId` of an object. ```APIDOC ## Any Trait ### Description Provides the `type_id` method to get the `TypeId` of an object. ### Method `fn type_id(&self) -> TypeId` ``` -------------------------------- ### impl Any for T Source: https://docs.rs/haqumei/0.7.0/haqumei/enum.UnicodeNormalization.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Provides the `type_id` method to get the `TypeId` of the type. ```APIDOC ## fn type_id(&self) -> TypeId ### Description Gets the `TypeId` of `self`. ### Method `type_id` ### Parameters None ### Returns - `TypeId`: The unique identifier for the type of `self`. ``` -------------------------------- ### Haqumei::with_options Source: https://docs.rs/haqumei/0.7.0/haqumei/struct.Haqumei.html?search=u32+-%3E+bool Creates a Haqumei instance with customizable output options, allowing for fine-grained control over the G2P conversion process. ```APIDOC ## Haqumei::with_options ### Description Creates a Haqumei instance with customizable output options, allowing for fine-grained control over the G2P conversion process. ### Method `pub fn with_options(options: HaqumeiOptions) -> Result` ### Parameters * `options` (HaqumeiOptions) - The configuration options for the Haqumei engine. ``` -------------------------------- ### type_id Source: https://docs.rs/haqumei/0.7.0/haqumei/struct.Haqumei.html Gets the `TypeId` of `self`. This method is part of the `Any` trait implementation. ```APIDOC ## fn type_id(&self) -> TypeId ### Description Gets the `TypeId` of `self`. ### Method `type_id` ### Parameters None ### Returns `TypeId` - The unique type identifier of the object. ``` -------------------------------- ### type_id Source: https://docs.rs/haqumei/0.7.0/haqumei/prosody/enum.PitchAccent.html?search=u32+-%3E+bool Gets the `TypeId` of `self`. This is a fundamental method for runtime type identification. ```APIDOC ## fn type_id(&self) -> TypeId ### Description Gets the `TypeId` of `self`. ### Method `type_id` ### Parameters None ### Returns `TypeId` - The unique identifier for the type of `self`. ``` -------------------------------- ### Initialize Haqumei from System and User Dictionary Paths Source: https://docs.rs/haqumei/0.7.0/src/haqumei/lib.rs.html?search=std%3A%3Avec Creates a Haqumei instance using both system and user-defined dictionary paths. This allows for custom vocabulary extensions. ```rust pub fn from_path_with_userdict, Q: AsRef>( dict_dir: P, user_dict: Q, options: HaqumeiOptions, ) -> Result { Self::from_open_jtalk( OpenJTalk::from_path_with_userdict(dict_dir, user_dict)?, options, ) } ``` -------------------------------- ### Haqumei::with_options Source: https://docs.rs/haqumei/0.7.0/src/haqumei/lib.rs.html?search=std%3A%3Avec Initializes a Haqumei instance with custom options, allowing for fine-grained control over the text-to-phoneme conversion process. ```APIDOC ## Haqumei::with_options ### Description Initializes a Haqumei instance with custom options, allowing for fine-grained control over the text-to-phoneme conversion process. ### Method `with_options(options: HaqumeiOptions) -> Result` ### Parameters #### Arguments - **options** (`HaqumeiOptions`): An instance of `HaqumeiOptions` to configure the behavior of Haqumei. ### Returns - `Result`: A `Result` containing the initialized `Haqumei` instance or a `HaqumeiError` if initialization fails. ``` -------------------------------- ### Get Type ID Source: https://docs.rs/haqumei/0.7.0/haqumei/open_jtalk/struct.OpenJTalk.html Retrieves the `TypeId` of the `self` instance. This is useful for runtime type identification. ```rust fn type_id(&self) -> TypeId ``` -------------------------------- ### Haqumei::new Source: https://docs.rs/haqumei/0.7.0/haqumei/struct.Haqumei.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Initializes a new Haqumei instance. This is the basic constructor for the G2P engine. ```APIDOC ## Haqumei::new ### Description Generates a Haqumei instance. ### Method `pub fn new() -> Result` ### Returns A `Result` containing a new `Haqumei` instance on success, or a `HaqumeiError` on failure. ``` -------------------------------- ### Unsafe Dereference Source: https://docs.rs/haqumei/0.7.0/haqumei/prosody/enum.PitchAccent.html?search=std%3A%3Avec Dereferences a raw pointer to get an immutable reference to the value. This is an unsafe operation from the `Pointable` trait. ```rust unsafe fn deref<'a>(ptr: usize) -> &'a T ``` -------------------------------- ### Initialize Haqumei from Dictionary and User Dictionary Paths Source: https://docs.rs/haqumei/0.7.0/src/haqumei/lib.rs.html?search= Constructs a Haqumei instance using both a system dictionary path and a user dictionary path, allowing for custom word additions. ```rust use haqumei::Haqumei; use haqumei::HaqumeiOptions; let dict_dir = "/path/to/system/dictionary"; let user_dict = "/path/to/user/dictionary"; let options = HaqumeiOptions::default(); let mut haqumei = Haqumei::from_path_with_userdict(dict_dir, user_dict, options).unwrap(); // Ok(["k", "o", "N", "n", "i", "ch", "i", "w", "a"]) println!("{:?}", haqumei.g2p("こんにちは")); ``` -------------------------------- ### Unsafe Mutable Dereference Source: https://docs.rs/haqumei/0.7.0/haqumei/prosody/enum.PitchAccent.html?search=std%3A%3Avec Dereferences a raw pointer to get a mutable reference to the value. This is an unsafe operation from the `Pointable` trait. ```rust unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T ``` -------------------------------- ### Accessing Connection Type in Haqumei Source: https://docs.rs/haqumei/0.7.0/src/haqumei/features.rs.html Retrieves the connection type string from the features. Use this method to get the specific connection type. ```rust #[track_caller] pub fn a_con_type(&self) -> &str { &self.feature[self.feature_ranges[25].clone()] } ``` -------------------------------- ### Initialize Haqumei with Custom Options Source: https://docs.rs/haqumei/0.7.0/src/haqumei/lib.rs.html?search= Creates a Haqumei instance with custom options, allowing for fine-grained control over the output. Requires `HaqumeiOptions` to be defined. ```rust use haqumei::Haqumei; use haqumei::HaqumeiOptions; let options = HaqumeiOptions::default(); let mut haqumei = Haqumei::with_options(options).unwrap(); // Ok(["k", "o", "N", "n", "i", "ch", "i", "w", "a"]) println!("{:?}", haqumei.g2p("こんにちは")); ``` -------------------------------- ### Loading Dictionary from Paths Source: https://docs.rs/haqumei/0.7.0/src/haqumei/open_jtalk/dictionary.rs.html?search=std%3A%3Avec Creates a Dictionary instance from system and optional user dictionary paths. Ensures paths are valid UTF-8 strings. ```rust use std::{ffi::{CString, NulError}, fs, io, path::{Path, PathBuf}, sync::{Arc, Mutex}}; use libc::{c_char, c_int}; use thiserror::Error; use crate::{errors::HaqumeiError, ffi, open_jtalk::model::MecabModel, setup_cpp_redirect, teardown_cpp_redirect}; static DICT_EXTRACT_LOCK: Mutex<()> = Mutex::new(()); /// `OpenJTalk` が使用する辞書オブジェクト #[derive(Debug, Clone)] pub struct Dictionary { pub(crate) model: Arc, pub(crate) dict_dir: PathBuf, } impl Dictionary { /// システム辞書パス、ユーザー辞書パスから [Dictionary] を生成します。 pub fn from_path>( dict_dir: P, user_dict: Option

, ) -> Result { let path_to_string = |p: &Path| -> Result { p.to_str().map(|s| s.to_string()).ok_or_else(|| { HaqumeiError::InvalidDictionaryPath(p.to_string_lossy().into_owned()) }) }; let dict_dir_str = path_to_string(dict_dir.as_ref())?; let user_dict_ref = user_dict.as_ref().map(|p| p.as_ref()); let user_dict_str = user_dict_ref.map(path_to_string).transpose()?; let model = MecabModel::new(&dict_dir_str, user_dict_str.as_deref())?; Ok(Self { model: Arc::new(model), dict_dir: dict_dir.as_ref().to_path_buf(), }) } ``` -------------------------------- ### Get Phoneme String Source: https://docs.rs/haqumei/0.7.0/src/haqumei/open_jtalk/jp_common_label.rs.html?search= Retrieves the phoneme string from a JPCommonLabelPhoneme pointer. Returns None for null pointers or specific invalid string values ('xx', '*'). ```Rust 81#[inline(always)] 82unsafe fn get_phoneme_str(ptr: *mut ffi::JPCommonLabelPhoneme) -> Option { 83 if ptr.is_null() { 84 return None; 85 } 86 let s_ptr = unsafe { (*ptr).phoneme }; 87 if s_ptr.is_null() { 88 return None; 89 } 90 let s = unsafe { CStr::from_ptr(s_ptr) }.to_string_lossy(); 91 if s == "xx" || s == "*" { 92 None 93 } else { 94 Some(s.into_owned()) 95 } 96} ``` -------------------------------- ### Initialize Haqumei with Custom Options Source: https://docs.rs/haqumei/0.7.0/src/haqumei/lib.rs.html?search=std%3A%3Avec Creates a Haqumei instance, allowing customization through HaqumeiOptions. Ensure OpenJTalk is initialized before passing options. ```rust pub fn with_options(options: HaqumeiOptions) -> Result { Self::from_open_jtalk(OpenJTalk::new()?, options) } ``` -------------------------------- ### Get Detailed Phoneme Mapping Source: https://docs.rs/haqumei/0.7.0/src/haqumei/lib.rs.html Converts input text into a detailed phoneme mapping, including phonemes for each segment. Ensures the dictionary is up-to-date before processing. ```rust pub fn g2p_detailed(&mut self, text: &str) -> Result, HaqumeiError> { if text.is_empty() { self.open_jtalk.ensure_dictionary_is_latest()?; return Ok(Vec::new()); } let detailed_mapping = self.g2p_mapping(text)?; let mut result_phonemes = Vec::new(); for map in detailed_mapping { result_phonemes.extend(map.phonemes); } Ok(result_phonemes) } ``` -------------------------------- ### Iterate Through Phonemes with Boundary Handling Source: https://docs.rs/haqumei/0.7.0/src/haqumei/open_jtalk/jp_common_label.rs.html?search= Iterates through phonemes, including special handling for start (-1) and end (size) indices representing silence ('sil'). ```rust for idx in -1..=size { let p_curr = if idx == -1 { phonemes[0] } else if idx == size { phonemes[(size - 1) as usize] } else { phonemes[idx as usize] }; let is_sil = idx == -1 || idx == size; let short_pause_flag = if is_sil { false } else { is_pau(p_curr) }; let phoneme = Phoneme { p2: get_ph(idx - 2), p1: get_ph(idx - 1), c: get_ph(idx), n1: get_ph(idx + 1), n2: get_ph(idx + 2), }; // ... rest of the loop body ``` -------------------------------- ### Initialize Mecab with Default Settings Source: https://docs.rs/haqumei/0.7.0/src/haqumei/open_jtalk/mecab.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Creates a new `Mecab` instance using default settings. This involves unsafe FFI calls to initialize the underlying C structure. It returns a `Result` which can be `Ok(Mecab)` on success or `Err(HaqumeiError)` on allocation failure. ```rust use crate::{errors::HaqumeiError, ffi, open_jtalk::model::MecabModel}; use std::{mem::MaybeUninit, ptr::NonNull}; #[derive(Debug)] pub(crate) struct Mecab { pub(crate) inner: NonNull, owns_model: bool, } impl Mecab { pub(crate) fn new() -> Result { unsafe { let mut mecab_uninit = Box::new(MaybeUninit::::uninit()); ffi::Mecab_initialize(mecab_uninit.as_mut_ptr()); let mecab_init = mecab_uninit.assume_init(); let raw_ptr = Box::into_raw(mecab_init); match NonNull::new(raw_ptr) { Some(inner) => Ok(Self { inner, owns_model: true, }), None => { let _ = Box::from_raw(raw_ptr); Err(HaqumeiError::AllocationError("_Mecab")) } } } } // ... other methods and impl Drop ``` -------------------------------- ### Haqumei::new Source: https://docs.rs/haqumei/0.7.0/haqumei/struct.Haqumei.html?search=u32+-%3E+bool Generates a new Haqumei instance with default options. This is the primary constructor for basic usage. ```APIDOC ## Haqumei::new ### Description Generates a new Haqumei instance with default options. ### Method `pub fn new() -> Result` ### Returns A `Result` containing a new `Haqumei` instance on success, or a `HaqumeiError` on failure. ``` -------------------------------- ### Get Word-Level Phoneme Pairs Source: https://docs.rs/haqumei/0.7.0/src/haqumei/open_jtalk.rs.html?search=u32+-%3E+bool Converts input text into a vector of word-phoneme pairs. Handles punctuation and unknown words by assigning `["pau"]` to them. ```rust pub fn g2p_pairs(&mut self, text: &str) -> Result>, HaqumeiError> { let mapping = self.g2p_pairs(text)?; Ok(mapping.into_iter().map(|m| m.phonemes).collect()) } ``` -------------------------------- ### Convert Text to Phonemes (G2P) Source: https://docs.rs/haqumei/0.7.0/src/haqumei/open_jtalk.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Converts input text into a flat list of phonemes. Chain with `.join(" ")` to get output similar to pyopenjtalk. ```rust pub fn g2p(&mut self, text: &str) -> Result, HaqumeiError> { self.ensure_dictionary_is_latest()?; if text.is_empty() { return Ok(Vec::new()); } let mecab_features = self.run_mecab(text.as_ref())?; let njd_features = self.run_njd_from_mecab(&mecab_features)?; if njd_features.is_empty() { return Ok(Vec::new()); } self.extract_phonemes(&njd_features) } ``` ```rust use haqumei::OpenJTalk; let mut open_jtalk = OpenJTalk::new().unwrap(); // Ok(["k", "o", "N", "n", "i", "ch", "i", "w", "a"]) println!("{:?}", open_jtalk.g2p("こんにちは")); ``` -------------------------------- ### Policy Combination: or Source: https://docs.rs/haqumei/0.7.0/haqumei/features/struct.UnidicFeature.html?search= Creates a new Policy that returns Action::Follow if either the self or other policy returns Action::Follow. ```APIDOC ## fn or(self, other: P) -> Or ### Description Creates a new `Policy` that returns `Action::Follow` if either `self` or `other` returns `Action::Follow`. ### Method Policy Combination ### Parameters - **other** (P): The other policy to combine with. ### Return Type Or ``` -------------------------------- ### Get Prosody Mapping for Text Source: https://docs.rs/haqumei/0.7.0/src/haqumei/lib.rs.html?search= Maps input text to prosodic phonemes, providing detailed information for each word. Useful for analyzing speech patterns and intonation. ```rust /// let mapping = haqumei.g2p_mapping_prosody("青い空が、好きだ!")?; /// /// // 1単語目「青い」の形態素情報 /// let aoi = &mapping[0]; /// assert_eq!(aoi.word, "青い"); /// assert_eq!(aoi.pos, "形容詞"); /// assert_eq!(aoi.read, "アオイ"); /// assert_eq!(aoi.accent_nucleus, 2); // 中高型 /// /// // 「青い」の音素とピッチ情報 (a: Low, o: High, i: Low) /// assert!(matches!( /// aoi.phonemes[0], /// ProsodicPhoneme::Phoneme { pitch: Some(PitchAccent::Low), .. } /// )); /// /// let da = mapping.last().unwrap(); /// assert_eq!(da.word, "!"); /// assert!(da.phonemes.contains(&ProsodicPhoneme::Exclamatory)); /// /// # Ok(()) /// # } /// ``` pub fn g2p_mapping_prosody( &mut self, text: &str, ) -> Result, HaqumeiError> { if text.is_empty() { self.open_jtalk.ensure_dictionary_is_latest()?; return Ok(Vec::new()); } // normalize_unicode_if_needed, revert_pron_to_read はここで実行される let (njd_features, morphs) = self.run_frontend_detailed(text)?; let mapping = self .open_jtalk .g2p_mapping_prosody_inner(&njd_features, self.options.is_non_pause_symbol)?; self.open_jtalk.make_phoneme_mapping(morphs, mapping) } ``` -------------------------------- ### setup_cpp_redirect and teardown_cpp_redirect functions Source: https://docs.rs/haqumei/0.7.0/src/haqumei/lib.rs.html?search=std%3A%3Avec Internal C functions for setting up and tearing down C++ redirection, likely used for managing FFI interactions. ```APIDOC ## unsafe extern "C" fn setup_cpp_redirect() ### Description Sets up C++ redirection. This function is intended for internal use and is called via FFI. ## unsafe extern "C" fn teardown_cpp_redirect() ### Description Tears down C++ redirection. This function is intended for internal use and is called via FFI. ``` -------------------------------- ### Get Nested Pointer Field Source: https://docs.rs/haqumei/0.7.0/src/haqumei/open_jtalk/jp_common_label.rs.html?search= Safely retrieves a field from a potentially null pointer, handling nested structures. Used for navigating complex C-style data. ```Rust 23macro_rules! get_ptr { 24 ($ptr:expr, $field:ident) => { 25 { 26 let p = $ptr; 27 if p.is_null() { 28 std::ptr::null_mut() 29 } else { 30 #[allow(unused_unsafe)] 31 unsafe { (*p).$field } 32 } 33 } 34 }; 35 ($ptr:expr, $field:ident $(, $rest:ident)+) => { 36 { 37 let p = $ptr; 38 if p.is_null() { 39 std::ptr::null_mut() 40 } else { 41 get_ptr!(unsafe { (*p).$field } $(, $rest)+) 42 } 43 } 44 }; 45} ``` -------------------------------- ### FFI Bindings for C Integration Source: https://docs.rs/haqumei/0.7.0/src/haqumei/lib.rs.html?search=std%3A%3Avec Includes generated FFI bindings for C compatibility and declares unsafe C functions for setup and teardown of C++ redirection. ```rust mod ffi { #![allow(non_upper_case_globals)] #![allow(non_camel_case_types)] #![allow(non_snake_case)] #![allow(dead_code)] #![allow(unnecessary_transmutes)] #![allow(clippy::upper_case_acronyms)] include!(concat!(env!("OUT_DIR"), "/bindings.rs")); } unsafe extern "C" { fn setup_cpp_redirect(); fn teardown_cpp_redirect(); } ``` -------------------------------- ### Initialize MecabModel Source: https://docs.rs/haqumei/0.7.0/src/haqumei/open_jtalk/model.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Creates a new MecabModel instance. Requires a dictionary directory and optionally accepts a user dictionary path. Handles CString conversions and FFI calls for MeCab model creation. ```Rust use std::ffi::{CString, c_char}; use crate::{errors::HaqumeiError, ffi}; #[derive(Debug)] pub(crate) struct MecabModel { pub(crate) ptr: *mut ffi::mecab_model_t, } impl MecabModel { pub fn new(dict_dir: &str, user_dict: Option<&str>) -> Result { let mut argv: Vec<*mut c_char> = Vec::new(); let arg0 = CString::new("mecab").unwrap(); let arg1 = CString::new("-d").unwrap(); let arg2 = CString::new(dict_dir).map_err(|_| HaqumeiError::MecabLoadError)?; let arg3 = CString::new("-u").unwrap(); let user_dic_c: Option = user_dict.map(CString::new).transpose()?; argv.push(arg0.as_ptr() as *mut _); argv.push(arg1.as_ptr() as *mut _); argv.push(arg2.as_ptr() as *mut _); if let Some(udic) = &user_dic_c { argv.push(arg3.as_ptr() as *mut _); argv.push(udic.as_ptr() as *mut _); } let model_ptr = unsafe { ffi::mecab_model_new(argv.len() as i32, argv.as_mut_ptr()) }; if model_ptr.is_null() { Err(HaqumeiError::MecabLoadError) } else { Ok(Self { ptr: model_ptr }) } } #[allow(unused)] pub(crate) fn new_uninitialized() -> Self { Self { ptr: std::ptr::null_mut(), } } pub(crate) fn is_initialized(&self) -> bool { !self.ptr.is_null() } } impl Drop for MecabModel { fn drop(&mut self) { unsafe { ffi::mecab_model_destroy(self.ptr); } } } ``` -------------------------------- ### Run MeCab Analysis and Get Features Source: https://docs.rs/haqumei/0.7.0/src/haqumei/open_jtalk.rs.html?search= Executes MeCab morphological analysis on the input text and returns a vector of feature strings. Handles potential errors during analysis. ```rust pub fn run_mecab(&mut self, text: &str) -> Result, HaqumeiError> { self.ensure_dictionary_is_latest()?; let c_text = CString::new(text)?; let mut buffer = vec![0u8; Self::BUFFER_SIZE]; let result = unsafe { ffi::text2mecab( buffer.as_mut_ptr() as *mut _, Self::BUFFER_SIZE, c_text.as_ptr(), ) }; match result { ffi::text2mecab_result_t_TEXT2MECAB_RESULT_SUCCESS => {} // Success ffi::text2mecab_result_t_TEXT2MECAB_RESULT_RANGE_ERROR => { return Err(HaqumeiError::Text2MecabError( "Text is too long".to_string(), )); } ffi::text2mecab_result_t_TEXT2MECAB_RESULT_INVALID_ARGUMENT => { return Err(HaqumeiError::Text2MecabError( "Invalid argument for text2mecab".to_string(), )); } _ => { return Err(HaqumeiError::Text2MecabError(format!( "Unknown error from text2mecab: {}", result ))); } } let result = unsafe { ffi::Mecab_analysis(self.mecab.inner.as_ptr(), buffer.as_ptr() as *const _) }; if result != 1 { return Err(HaqumeiError::MecabError( "Mecab_analysis failed to parse the text".to_string(), )); } let mut result_vec = Vec::new(); unsafe { let mecab_ptr = self.mecab.inner.as_ptr(); let lattice = (*mecab_ptr).lattice as *mut ffi::mecab_lattice_t; let mut node = ffi::mecab_lattice_get_bos_node(lattice); while !node.is_null() { let stat = (*node).stat; if stat != 2 && stat != 3 { // BOS/EOS 以外 let feat_ptr = (*node).feature; if !feat_ptr.is_null() { let c_feature = CStr::from_ptr(feat_ptr); let feature_str = c_feature.to_string_lossy(); if !feature_str.contains("記号,空白") { let surface_ptr = (*node).surface; let length = (*node).length as usize; let surface = if !surface_ptr.is_null() && length > 0 { let bytes = std::slice::from_raw_parts(surface_ptr as *const u8, length); String::from_utf8_lossy(bytes) } else { std::borrow::Cow::Borrowed("") }; result_vec.push(format!( ``` -------------------------------- ### extract_phonemes Source: https://docs.rs/haqumei/0.7.0/src/haqumei/open_jtalk.rs.html Extracts a flat list of phonemes directly from NjdFeatures. This method provides a simplified way to get phonetic information without the full label generation process. ```APIDOC ## extract_phonemes ### Description Extracts a flat list of phonemes directly from NjdFeatures. This method provides a simplified way to get phonetic information without the full label generation process. ### Method `extract_phonemes` ### Parameters - `features`: A slice of `NjdFeature` structs representing the processed linguistic features. ### Returns - `Result, HaqumeiError>`: A `Result` containing a vector of `Phoneme` structs on success, or a `HaqumeiError` on failure. ``` -------------------------------- ### Initialize Mecab with Default Settings Source: https://docs.rs/haqumei/0.7.0/src/haqumei/open_jtalk/mecab.rs.html?search=u32+-%3E+bool Creates a new Mecab instance using default settings. This method allocates necessary internal structures and assumes ownership of the Mecab model. Use this when you need a standalone Mecab instance. ```rust pub(crate) fn new() -> Result { unsafe { let mut mecab_uninit = Box::new(MaybeUninit::::uninit()); ffi::Mecab_initialize(mecab_uninit.as_mut_ptr()); let mecab_init = mecab_uninit.assume_init(); let raw_ptr = Box::into_raw(mecab_init); match NonNull::new(raw_ptr) { Some(inner) => Ok(Self { inner, owns_model: true, }), None => { let _ = Box::from_raw(raw_ptr); Err(HaqumeiError::AllocationError("_Mecab")) } } } } ``` -------------------------------- ### Basic Grapheme-to-Phoneme Conversion Source: https://docs.rs/haqumei/0.7.0/src/haqumei/lib.rs.html?search=std%3A%3Avec Converts input text into a flat vector of phonemes. Chain with `.join(" ")` to get a space-separated string similar to pyopenjtalk output. ```rust pub fn g2p(&mut self, text: &str) -> Result, HaqumeiError> { if text.is_empty() { self.open_jtalk.ensure_dictionary_is_latest()?; return Ok(Vec::new()); } let features = self.run_frontend(text)?; if features.is_empty() { return Ok(Vec::new()); } self.open_jtalk.extract_phonemes(&features) } ```