diff --git a/crates/voicevox_core/src/engine/synthesis_engine.rs b/crates/voicevox_core/src/engine/synthesis_engine.rs index 9c5fb7ca4..22ced6f84 100644 --- a/crates/voicevox_core/src/engine/synthesis_engine.rs +++ b/crates/voicevox_core/src/engine/synthesis_engine.rs @@ -652,7 +652,7 @@ mod tests { #[rstest] #[tokio::test] async fn is_openjtalk_dict_loaded_works() { - let core = InferenceCore::new(false, 0).await.unwrap(); + let core = InferenceCore::new(false, 0).unwrap(); let synthesis_engine = SynthesisEngine::new(core, OpenJtalk::new(OPEN_JTALK_DIC_DIR).unwrap().into()); @@ -662,7 +662,7 @@ mod tests { #[rstest] #[tokio::test] async fn create_accent_phrases_works() { - let core = InferenceCore::new(false, 0).await.unwrap(); + let core = InferenceCore::new(false, 0).unwrap(); let model = &VoiceModel::sample().await.unwrap(); core.load_model(model).await.unwrap(); diff --git a/crates/voicevox_core/src/inference_core.rs b/crates/voicevox_core/src/inference_core.rs index af382a967..4b0d08be2 100644 --- a/crates/voicevox_core/src/inference_core.rs +++ b/crates/voicevox_core/src/inference_core.rs @@ -9,7 +9,7 @@ pub struct InferenceCore { } impl InferenceCore { - pub(crate) async fn new(use_gpu: bool, cpu_num_threads: u16) -> Result { + pub(crate) fn new(use_gpu: bool, cpu_num_threads: u16) -> Result { if !use_gpu || Self::can_support_gpu_feature()? { let status = Status::new(use_gpu, cpu_num_threads); Ok(Self { status }) diff --git a/crates/voicevox_core/src/synthesizer.rs b/crates/voicevox_core/src/synthesizer.rs index 6ca01d2c5..98c3a5f82 100644 --- a/crates/voicevox_core/src/synthesizer.rs +++ b/crates/voicevox_core/src/synthesizer.rs @@ -80,8 +80,7 @@ impl Synthesizer { /// #[cfg_attr(windows, doc = "```no_run")] // https://github.com/VOICEVOX/voicevox_core/issues/537 #[cfg_attr(not(windows), doc = "```")] - /// # #[tokio::main] - /// # async fn main() -> anyhow::Result<()> { + /// # fn main() -> anyhow::Result<()> { /// # use test_util::OPEN_JTALK_DIC_DIR; /// # /// # const ACCELERATION_MODE: AccelerationMode = AccelerationMode::Cpu; @@ -96,13 +95,12 @@ impl Synthesizer { /// acceleration_mode: ACCELERATION_MODE, /// ..Default::default() /// }, - /// ) - /// .await?; + /// )?; /// # /// # Ok(()) /// # } /// ``` - pub async fn new(open_jtalk: Arc, options: &InitializeOptions) -> Result { + pub fn new(open_jtalk: Arc, options: &InitializeOptions) -> Result { #[cfg(windows)] list_windows_video_cards(); let use_gpu = match options.acceleration_mode { @@ -124,7 +122,7 @@ impl Synthesizer { Ok(Self { synthesis_engine: SynthesisEngine::new( - InferenceCore::new(use_gpu, options.cpu_num_threads).await?, + InferenceCore::new(use_gpu, options.cpu_num_threads)?, open_jtalk, ), use_gpu, @@ -259,8 +257,7 @@ impl Synthesizer { /// # acceleration_mode: AccelerationMode::Cpu, /// # ..Default::default() /// # }, - /// # ) - /// # .await?; + /// # )?; /// # /// # let model = &VoiceModel::from_path(concat!( /// # env!("CARGO_MANIFEST_DIR"), @@ -313,8 +310,7 @@ impl Synthesizer { /// # acceleration_mode: AccelerationMode::Cpu, /// # ..Default::default() /// # }, - /// # ) - /// # .await?; + /// # )?; /// # /// # let model = &VoiceModel::from_path(concat!( /// # env!("CARGO_MANIFEST_DIR"), @@ -403,8 +399,7 @@ impl Synthesizer { /// # acceleration_mode: AccelerationMode::Cpu, /// # ..Default::default() /// # }, - /// # ) - /// # .await?; + /// # )?; /// # /// # let model = &VoiceModel::from_path(concat!( /// # env!("CARGO_MANIFEST_DIR"), @@ -458,8 +453,7 @@ impl Synthesizer { /// # acceleration_mode: AccelerationMode::Cpu, /// # ..Default::default() /// # }, - /// # ) - /// # .await?; + /// # )?; /// # /// # let model = &VoiceModel::from_path(concat!( /// # env!("CARGO_MANIFEST_DIR"), @@ -586,7 +580,6 @@ mod tests { ..Default::default() }, ) - .await .unwrap(); let result = syntesizer @@ -610,7 +603,6 @@ mod tests { ..Default::default() }, ) - .await .unwrap(); assert!(!syntesizer.is_gpu_mode()); } @@ -627,7 +619,6 @@ mod tests { ..Default::default() }, ) - .await .unwrap(); assert!( !syntesizer.is_loaded_model_by_style_id(style_id), @@ -656,7 +647,6 @@ mod tests { ..Default::default() }, ) - .await .unwrap(); syntesizer @@ -688,7 +678,6 @@ mod tests { ..Default::default() }, ) - .await .unwrap(); syntesizer .load_voice_model(&open_default_vvm_file().await) @@ -730,7 +719,6 @@ mod tests { ..Default::default() }, ) - .await .unwrap(); syntesizer .load_voice_model(&open_default_vvm_file().await) @@ -823,7 +811,6 @@ mod tests { ..Default::default() }, ) - .await .unwrap(); let model = &VoiceModel::sample().await.unwrap(); @@ -892,7 +879,6 @@ mod tests { ..Default::default() }, ) - .await .unwrap(); let model = &VoiceModel::sample().await.unwrap(); @@ -958,7 +944,6 @@ mod tests { ..Default::default() }, ) - .await .unwrap(); let model = &VoiceModel::sample().await.unwrap(); @@ -995,7 +980,6 @@ mod tests { ..Default::default() }, ) - .await .unwrap(); let model = &VoiceModel::sample().await.unwrap(); @@ -1028,7 +1012,6 @@ mod tests { ..Default::default() }, ) - .await .unwrap(); let model = &VoiceModel::sample().await.unwrap(); diff --git a/crates/voicevox_core_c_api/src/c_impls.rs b/crates/voicevox_core_c_api/src/c_impls.rs index 80f71d6ca..4548444cb 100644 --- a/crates/voicevox_core_c_api/src/c_impls.rs +++ b/crates/voicevox_core_c_api/src/c_impls.rs @@ -13,8 +13,12 @@ impl OpenJtalkRc { } impl VoicevoxSynthesizer { - pub(crate) async fn new(open_jtalk: &OpenJtalkRc, options: &InitializeOptions) -> Result { - let synthesizer = Synthesizer::new(open_jtalk.open_jtalk.clone(), options).await?; + pub(crate) fn new(open_jtalk: &OpenJtalkRc, options: &InitializeOptions) -> Result { + // ロガーを起動 + // FIXME: `into_result_code_with_error`を`run`とかに改名し、`init_logger`をその中に移動 + let _ = *crate::RUNTIME; + + let synthesizer = Synthesizer::new(open_jtalk.open_jtalk.clone(), options)?; Ok(Self { synthesizer }) } diff --git a/crates/voicevox_core_c_api/src/compatible_engine.rs b/crates/voicevox_core_c_api/src/compatible_engine.rs index f10d47986..dd8ce8e94 100644 --- a/crates/voicevox_core_c_api/src/compatible_engine.rs +++ b/crates/voicevox_core_c_api/src/compatible_engine.rs @@ -115,8 +115,7 @@ pub extern "C" fn initialize(use_gpu: bool, cpu_num_threads: c_int, load_all_mod }, cpu_num_threads: cpu_num_threads as u16, }, - ) - .await?; + )?; if load_all_models { for model in &voice_model_set().all_vvms { diff --git a/crates/voicevox_core_c_api/src/lib.rs b/crates/voicevox_core_c_api/src/lib.rs index 2abe03f13..302089a95 100644 --- a/crates/voicevox_core_c_api/src/lib.rs +++ b/crates/voicevox_core_c_api/src/lib.rs @@ -343,9 +343,7 @@ pub unsafe extern "C" fn voicevox_synthesizer_new( into_result_code_with_error((|| { let options = options.into(); - let synthesizer = RUNTIME - .block_on(VoicevoxSynthesizer::new(open_jtalk, &options))? - .into(); + let synthesizer = VoicevoxSynthesizer::new(open_jtalk, &options)?.into(); out_synthesizer.as_ptr().write_unaligned(synthesizer); Ok(()) })()) diff --git a/crates/voicevox_core_java_api/lib/src/main/java/jp/hiroshiba/voicevoxcore/GlobalInfo.java b/crates/voicevox_core_java_api/lib/src/main/java/jp/hiroshiba/voicevoxcore/GlobalInfo.java new file mode 100644 index 000000000..26f9ccddd --- /dev/null +++ b/crates/voicevox_core_java_api/lib/src/main/java/jp/hiroshiba/voicevoxcore/GlobalInfo.java @@ -0,0 +1,89 @@ +package jp.hiroshiba.voicevoxcore; + +import com.google.gson.Gson; +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; +import jakarta.annotation.Nonnull; + +/** VOICEVOX CORE自体の情報。 */ +public class GlobalInfo extends Dll { + /** + * ライブラリのバージョン。 + * + * @return ライブラリのバージョン。 + */ + @Nonnull + public static String getVersion() { + return rsGetVersion(); + } + + /** + * このライブラリで利用可能なデバイスの情報を取得する。 + * + * @return {@link SupportedDevices}。 + */ + @Nonnull + public static SupportedDevices getSupportedDevices() { + Gson gson = new Gson(); + String supportedDevicesJson = rsGetSupportedDevicesJson(); + SupportedDevices supportedDevices = gson.fromJson(supportedDevicesJson, SupportedDevices.class); + if (supportedDevices == null) { + throw new NullPointerException("supported_devices"); + } + return supportedDevices; + } + + @Nonnull + private static native String rsGetVersion(); + + @Nonnull + private static native String rsGetSupportedDevicesJson(); + + /** + * このライブラリで利用可能なデバイスの情報。 + * + *

あくまで本ライブラリが対応しているデバイスの情報であることに注意。GPUが使える環境ではなかったとしても {@link #cuda} や {@link #dml} は {@code + * true} を示しうる。 + */ + public static class SupportedDevices { + /** + * CPUが利用可能。 + * + *

常に true 。 + */ + @SerializedName("cpu") + @Expose + @Nonnull + public final boolean cpu; + + /** + * CUDAが利用可能。 + * + *

ONNX Runtimeの CUDAExecutionProviderに対応する。 必要な環境についてはそちらを参照。 + */ + @SerializedName("cuda") + @Expose + @Nonnull + public final boolean cuda; + + /** + * DirectMLが利用可能。 + * + *

ONNX Runtimeの DmlExecutionProviderに対応する。 必要な環境についてはそちらを参照。 + */ + @SerializedName("dml") + @Expose + @Nonnull + public final boolean dml; + + private SupportedDevices() { + this.cpu = false; + this.cuda = false; + this.dml = false; + } + } +} diff --git a/crates/voicevox_core_java_api/lib/src/main/java/jp/hiroshiba/voicevoxcore/OpenJtalk.java b/crates/voicevox_core_java_api/lib/src/main/java/jp/hiroshiba/voicevoxcore/OpenJtalk.java index afdee7d76..032ec1b76 100644 --- a/crates/voicevox_core_java_api/lib/src/main/java/jp/hiroshiba/voicevoxcore/OpenJtalk.java +++ b/crates/voicevox_core_java_api/lib/src/main/java/jp/hiroshiba/voicevoxcore/OpenJtalk.java @@ -1,5 +1,6 @@ package jp.hiroshiba.voicevoxcore; +/** テキスト解析機としてのOpen JTalk。 */ public class OpenJtalk extends Dll { private long handle; diff --git a/crates/voicevox_core_java_api/lib/src/main/java/jp/hiroshiba/voicevoxcore/Synthesizer.java b/crates/voicevox_core_java_api/lib/src/main/java/jp/hiroshiba/voicevoxcore/Synthesizer.java index 66d4f5df2..a3fe0de6c 100644 --- a/crates/voicevox_core_java_api/lib/src/main/java/jp/hiroshiba/voicevoxcore/Synthesizer.java +++ b/crates/voicevox_core_java_api/lib/src/main/java/jp/hiroshiba/voicevoxcore/Synthesizer.java @@ -25,10 +25,36 @@ protected void finalize() throws Throwable { super.finalize(); } + /** + * ハードウェアアクセラレーションがGPUモードかどうかを返す。 + * + * @return ハードウェアアクセラレーションがGPUモードかどうか。 + */ + public boolean isGpuMode() { + return rsIsGpuMode(); + } + + /** + * メタ情報を取得する。 + * + * @return メタ情報。 + */ + @Nonnull + public VoiceModel.SpeakerMeta[] metas() { + Gson gson = new Gson(); + String metasJson = rsGetMetasJson(); + VoiceModel.SpeakerMeta[] rawMetas = gson.fromJson(metasJson, VoiceModel.SpeakerMeta[].class); + if (rawMetas == null) { + throw new NullPointerException("metas"); + } + return rawMetas; + } + /** * モデルを読み込む。 * * @param voiceModel 読み込むモデル。 + * @throws InvalidModelDataException 無効なモデルデータの場合。 */ public void loadVoiceModel(VoiceModel voiceModel) throws InvalidModelDataException { rsLoadVoiceModel(voiceModel); @@ -59,6 +85,7 @@ public boolean isLoadedVoiceModel(String voiceModelId) { * @param kana AquesTalk風記法。 * @param styleId スタイルID。 * @return {@link AudioQuery}。 + * @throws InferenceFailedException 推論に失敗した場合。 */ @Nonnull public AudioQuery createAudioQueryFromKana(String kana, int styleId) @@ -82,6 +109,7 @@ public AudioQuery createAudioQueryFromKana(String kana, int styleId) * @param text 日本語のテキスト。 * @param styleId スタイルID。 * @return {@link AudioQuery}。 + * @throws InferenceFailedException 推論に失敗した場合。 */ @Nonnull public AudioQuery createAudioQuery(String text, int styleId) throws InferenceFailedException { @@ -104,6 +132,7 @@ public AudioQuery createAudioQuery(String text, int styleId) throws InferenceFai * @param kana AquesTalk風記法。 * @param styleId スタイルID。 * @return {@link AccentPhrase} のリスト。 + * @throws InferenceFailedException 推論に失敗した場合。 */ @Nonnull public List createAccentPhrasesFromKana(String kana, int styleId) @@ -123,6 +152,7 @@ public List createAccentPhrasesFromKana(String kana, int styleId) * @param text 日本語のテキスト。 * @param styleId スタイルID。 * @return {@link AccentPhrase} のリスト。 + * @throws InferenceFailedException 推論に失敗した場合。 */ @Nonnull public List createAccentPhrases(String text, int styleId) @@ -142,6 +172,7 @@ public List createAccentPhrases(String text, int styleId) * @param accentPhrases 変更元のアクセント句の配列。 * @param styleId スタイルID。 * @return 変更後のアクセント句の配列。 + * @throws InferenceFailedException 推論に失敗した場合。 */ @Nonnull public List replaceMoraData(List accentPhrases, int styleId) @@ -161,6 +192,7 @@ public List replaceMoraData(List accentPhrases, int * @param accentPhrases 変更元のアクセント句の配列。 * @param styleId スタイルID。 * @return 変更後のアクセント句の配列。 + * @throws InferenceFailedException 推論に失敗した場合。 */ @Nonnull public List replacePhonemeLength(List accentPhrases, int styleId) @@ -180,6 +212,7 @@ public List replacePhonemeLength(List accentPhrases, * @param accentPhrases 変更元のアクセント句の配列。 * @param styleId スタイルID。 * @return 変更後のアクセント句の配列。 + * @throws InferenceFailedException 推論に失敗した場合。 */ @Nonnull public List replaceMoraPitch(List accentPhrases, int styleId) @@ -234,6 +267,11 @@ public TtsConfigurator tts(String text, int styleId) { private native void rsNew(OpenJtalk openJtalk, Builder builder); + private native boolean rsIsGpuMode(); + + @Nonnull + private native String rsGetMetasJson(); + private native void rsLoadVoiceModel(VoiceModel voiceModel) throws InvalidModelDataException; private native void rsUnloadVoiceModel(String voiceModelId); @@ -382,6 +420,7 @@ public SynthesisConfigurator interrogativeUpspeak(boolean interrogativeUpspeak) * {@link AudioQuery} から音声合成する。 * * @return 音声データ。 + * @throws InferenceFailedException 推論に失敗した場合。 */ @Nonnull public byte[] execute() throws InferenceFailedException { @@ -426,6 +465,7 @@ public TtsFromKanaConfigurator interrogativeUpspeak(boolean interrogativeUpspeak * {@link AudioQuery} から音声合成する。 * * @return 音声データ。 + * @throws InferenceFailedException 推論に失敗した場合。 */ @Nonnull public byte[] execute() throws InferenceFailedException { @@ -468,6 +508,7 @@ public TtsConfigurator interrogativeUpspeak(boolean interrogativeUpspeak) { * {@link AudioQuery} から音声合成する。 * * @return 音声データ。 + * @throws InferenceFailedException 推論に失敗した場合。 */ @Nonnull public byte[] execute() throws InferenceFailedException { diff --git a/crates/voicevox_core_java_api/lib/src/main/java/jp/hiroshiba/voicevoxcore/UserDict.java b/crates/voicevox_core_java_api/lib/src/main/java/jp/hiroshiba/voicevoxcore/UserDict.java index de1e612be..21f6843dd 100644 --- a/crates/voicevox_core_java_api/lib/src/main/java/jp/hiroshiba/voicevoxcore/UserDict.java +++ b/crates/voicevox_core_java_api/lib/src/main/java/jp/hiroshiba/voicevoxcore/UserDict.java @@ -74,6 +74,7 @@ public void importDict(UserDict dict) { * ユーザー辞書を読み込む。 * * @param path ユーザー辞書のパス。 + * @throws LoadUserDictException ユーザー辞書を読み込めなかった場合。 */ public void load(String path) throws LoadUserDictException { rsLoad(path); @@ -83,6 +84,7 @@ public void load(String path) throws LoadUserDictException { * ユーザー辞書を保存する。 * * @param path ユーザー辞書のパス。 + * @throws SaveUserDictException ユーザー辞書を保存できなかった場合。 */ public void save(String path) throws SaveUserDictException { rsSave(path); diff --git a/crates/voicevox_core_java_api/lib/src/test/java/jp/hiroshiba/voicevoxcore/InfoTest.java b/crates/voicevox_core_java_api/lib/src/test/java/jp/hiroshiba/voicevoxcore/InfoTest.java new file mode 100644 index 000000000..52915abad --- /dev/null +++ b/crates/voicevox_core_java_api/lib/src/test/java/jp/hiroshiba/voicevoxcore/InfoTest.java @@ -0,0 +1,24 @@ +/* + * GlobalInfoのテスト。 + */ +package jp.hiroshiba.voicevoxcore; + +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.Test; + +class InfoTest { + @Test + void checkVersion() { + assertNotNull(GlobalInfo.getVersion()); + } + + @Test + void checkSupportedDevices() { + GlobalInfo.SupportedDevices supportedDevices = GlobalInfo.getSupportedDevices(); + + assertNotNull(supportedDevices); + assertTrue(supportedDevices.cpu); + } +} diff --git a/crates/voicevox_core_java_api/lib/src/test/java/jp/hiroshiba/voicevoxcore/SynthesizerTest.java b/crates/voicevox_core_java_api/lib/src/test/java/jp/hiroshiba/voicevoxcore/SynthesizerTest.java index efa91eed8..1eb8fe057 100644 --- a/crates/voicevox_core_java_api/lib/src/test/java/jp/hiroshiba/voicevoxcore/SynthesizerTest.java +++ b/crates/voicevox_core_java_api/lib/src/test/java/jp/hiroshiba/voicevoxcore/SynthesizerTest.java @@ -18,6 +18,14 @@ interface MoraCheckCallback { boolean check(Mora mora, Mora otherMora); } + @Test + void checkIsGpuMode() { + OpenJtalk openJtalk = loadOpenJtalk(); + Synthesizer synthesizer = + Synthesizer.builder(openJtalk).accelerationMode(Synthesizer.AccelerationMode.CPU).build(); + assertFalse(synthesizer.isGpuMode()); + } + boolean checkAllMoras( List accentPhrases, List otherAccentPhrases, @@ -40,9 +48,17 @@ void checkModel() throws InvalidModelDataException { VoiceModel model = loadModel(); OpenJtalk openJtalk = loadOpenJtalk(); Synthesizer synthesizer = Synthesizer.builder(openJtalk).build(); + + assertTrue(synthesizer.metas().length == 0); + synthesizer.loadVoiceModel(model); + + assertTrue(synthesizer.metas().length >= 1); assertTrue(synthesizer.isLoadedVoiceModel(model.id)); + synthesizer.unloadVoiceModel(model.id); + + assertTrue(synthesizer.metas().length == 0); assertFalse(synthesizer.isLoadedVoiceModel(model.id)); } diff --git a/crates/voicevox_core_java_api/src/info.rs b/crates/voicevox_core_java_api/src/info.rs new file mode 100644 index 000000000..71b8db228 --- /dev/null +++ b/crates/voicevox_core_java_api/src/info.rs @@ -0,0 +1,22 @@ +use crate::common::throw_if_err; +use jni::{sys::jobject, JNIEnv}; +#[no_mangle] +extern "system" fn Java_jp_hiroshiba_voicevoxcore_GlobalInfo_rsGetVersion( + env: JNIEnv<'_>, +) -> jobject { + throw_if_err(env, std::ptr::null_mut(), |env| { + let version = env.new_string(env!("CARGO_PKG_VERSION"))?; + Ok(version.into_raw()) + }) +} +#[no_mangle] +extern "system" fn Java_jp_hiroshiba_voicevoxcore_GlobalInfo_rsGetSupportedDevicesJson( + env: JNIEnv<'_>, +) -> jobject { + throw_if_err(env, std::ptr::null_mut(), |env| { + let supported_devices = voicevox_core::SupportedDevices::create()?; + let json = serde_json::to_string(&supported_devices).expect("Should not fail"); + let json = env.new_string(json)?; + Ok(json.into_raw()) + }) +} diff --git a/crates/voicevox_core_java_api/src/lib.rs b/crates/voicevox_core_java_api/src/lib.rs index 4ea35c0b2..4fdea9cab 100644 --- a/crates/voicevox_core_java_api/src/lib.rs +++ b/crates/voicevox_core_java_api/src/lib.rs @@ -1,4 +1,5 @@ mod common; +mod info; mod open_jtalk; mod synthesizer; mod user_dict; diff --git a/crates/voicevox_core_java_api/src/synthesizer.rs b/crates/voicevox_core_java_api/src/synthesizer.rs index 9307c11b7..9d3cb9f9f 100644 --- a/crates/voicevox_core_java_api/src/synthesizer.rs +++ b/crates/voicevox_core_java_api/src/synthesizer.rs @@ -18,6 +18,10 @@ unsafe extern "system" fn Java_jp_hiroshiba_voicevoxcore_Synthesizer_rsNew<'loca builder: JObject<'local>, ) { throw_if_err(env, (), |env| { + // ロガーを起動 + // FIXME: `throw_if_err`を`run`とかに改名し、`init_logger`をその中に移動 + let _ = *RUNTIME; + let mut options = voicevox_core::InitializeOptions::default(); let acceleration_mode = env @@ -48,14 +52,42 @@ unsafe extern "system" fn Java_jp_hiroshiba_voicevoxcore_Synthesizer_rsNew<'loca let open_jtalk = env .get_rust_field::<_, _, Arc>(&open_jtalk, "handle")? .clone(); - let internal = RUNTIME.block_on(voicevox_core::Synthesizer::new( - open_jtalk, - Box::leak(Box::new(options)), - ))?; + let internal = voicevox_core::Synthesizer::new(open_jtalk, Box::leak(Box::new(options)))?; env.set_rust_field(&this, "handle", Arc::new(internal))?; Ok(()) }) } +#[no_mangle] +unsafe extern "system" fn Java_jp_hiroshiba_voicevoxcore_Synthesizer_rsIsGpuMode<'local>( + env: JNIEnv<'local>, + this: JObject<'local>, +) -> jboolean { + throw_if_err(env, false, |env| { + let internal = env + .get_rust_field::<_, _, Arc>(&this, "handle")? + .clone(); + + Ok(internal.is_gpu_mode()) + }) + .into() +} +#[no_mangle] +unsafe extern "system" fn Java_jp_hiroshiba_voicevoxcore_Synthesizer_rsGetMetasJson<'local>( + env: JNIEnv<'local>, + this: JObject<'local>, +) -> jobject { + throw_if_err(env, std::ptr::null_mut(), |env| { + let internal = env + .get_rust_field::<_, _, Arc>(&this, "handle")? + .clone(); + + let metas_json = serde_json::to_string(&internal.metas()).expect("should not fail"); + + let j_metas_json = env.new_string(metas_json)?; + + Ok(j_metas_json.into_raw()) + }) +} #[no_mangle] unsafe extern "system" fn Java_jp_hiroshiba_voicevoxcore_Synthesizer_rsLoadVoiceModel<'local>( diff --git a/crates/voicevox_core_python_api/python/test/test_pseudo_raii_for_synthesizer.py b/crates/voicevox_core_python_api/python/test/test_pseudo_raii_for_synthesizer.py index 295db3941..9859b85d7 100644 --- a/crates/voicevox_core_python_api/python/test/test_pseudo_raii_for_synthesizer.py +++ b/crates/voicevox_core_python_api/python/test/test_pseudo_raii_for_synthesizer.py @@ -37,7 +37,7 @@ def test_access_after_exit_denied(synthesizer: Synthesizer) -> None: @pytest_asyncio.fixture async def synthesizer(open_jtalk: OpenJtalk) -> Synthesizer: - return await Synthesizer.new(open_jtalk) + return Synthesizer(open_jtalk) @pytest.fixture(scope="module") diff --git a/crates/voicevox_core_python_api/python/test/test_user_dict_load.py b/crates/voicevox_core_python_api/python/test/test_user_dict_load.py index 3a8b9c120..ba009f37d 100644 --- a/crates/voicevox_core_python_api/python/test/test_user_dict_load.py +++ b/crates/voicevox_core_python_api/python/test/test_user_dict_load.py @@ -12,9 +12,7 @@ async def test_user_dict_load() -> None: open_jtalk = voicevox_core.OpenJtalk(conftest.open_jtalk_dic_dir) model = await voicevox_core.VoiceModel.from_path(conftest.model_dir) - synthesizer = await voicevox_core.Synthesizer.new( - open_jtalk=open_jtalk, - ) + synthesizer = voicevox_core.Synthesizer(open_jtalk) await synthesizer.load_voice_model(model) diff --git a/crates/voicevox_core_python_api/python/voicevox_core/_rust.pyi b/crates/voicevox_core_python_api/python/voicevox_core/_rust.pyi index 62de7b0e6..1560a5cde 100644 --- a/crates/voicevox_core_python_api/python/voicevox_core/_rust.pyi +++ b/crates/voicevox_core_python_api/python/voicevox_core/_rust.pyi @@ -76,29 +76,27 @@ class OpenJtalk: ... class Synthesizer: - """音声シンセサイザ。""" + """ + 音声シンセサイザ。 - @staticmethod - async def new( + Parameters + ---------- + open_jtalk + Open JTalk。 + acceleration_mode + ハードウェアアクセラレーションモード。 + cpu_num_threads + CPU利用数を指定。0を指定すると環境に合わせたCPUが利用される。 + """ + + def __init__( + self, open_jtalk: OpenJtalk, acceleration_mode: Union[ AccelerationMode, Literal["AUTO", "CPU", "GPU"] ] = AccelerationMode.AUTO, cpu_num_threads: int = 0, - ) -> "Synthesizer": - """ - :class:`Synthesizer` を生成する。 - - Parameters - ---------- - open_jtalk - Open JTalk。 - acceleration_mode - ハードウェアアクセラレーションモード。 - cpu_num_threads - CPU利用数を指定。0を指定すると環境に合わせたCPUが利用される。 - """ - ... + ) -> None: ... def __repr__(self) -> str: ... def __enter__(self) -> "Synthesizer": ... def __exit__(self, exc_type, exc_value, traceback) -> None: ... @@ -107,7 +105,7 @@ class Synthesizer: """ハードウェアアクセラレーションがGPUモードかどうか。""" ... @property - def metas(self) -> SpeakerMeta: + def metas(self) -> List[SpeakerMeta]: """メタ情報。""" ... async def load_voice_model(self, model: VoiceModel) -> None: diff --git a/crates/voicevox_core_python_api/src/lib.rs b/crates/voicevox_core_python_api/src/lib.rs index ba971c5d1..c39c72e1a 100644 --- a/crates/voicevox_core_python_api/src/lib.rs +++ b/crates/voicevox_core_python_api/src/lib.rs @@ -145,32 +145,27 @@ struct Synthesizer { #[pymethods] impl Synthesizer { - #[allow(clippy::new_ret_no_self)] - #[staticmethod] + #[new] #[pyo3(signature =( open_jtalk, acceleration_mode = InitializeOptions::default().acceleration_mode, cpu_num_threads = InitializeOptions::default().cpu_num_threads, ))] fn new( - py: Python, open_jtalk: OpenJtalk, #[pyo3(from_py_with = "from_acceleration_mode")] acceleration_mode: AccelerationMode, cpu_num_threads: u16, - ) -> PyResult<&PyAny> { - pyo3_asyncio::tokio::future_into_py(py, async move { - let synthesizer = voicevox_core::Synthesizer::new( - open_jtalk.open_jtalk.clone(), - &InitializeOptions { - acceleration_mode, - cpu_num_threads, - }, - ) - .await; - let synthesizer = Python::with_gil(|py| synthesizer.into_py_result(py))?.into(); - let synthesizer = Closable::new(synthesizer); - Ok(Self { synthesizer }) - }) + ) -> PyResult { + let synthesizer = voicevox_core::Synthesizer::new( + open_jtalk.open_jtalk.clone(), + &InitializeOptions { + acceleration_mode, + cpu_num_threads, + }, + ); + let synthesizer = Python::with_gil(|py| synthesizer.into_py_result(py))?.into(); + let synthesizer = Closable::new(synthesizer); + Ok(Self { synthesizer }) } fn __repr__(&self) -> &'static str { diff --git a/example/kotlin/.gitattributes b/example/kotlin/.gitattributes new file mode 100644 index 000000000..493fdc40f --- /dev/null +++ b/example/kotlin/.gitattributes @@ -0,0 +1,12 @@ +# +# https://help.github.com/articles/dealing-with-line-endings/ +# +# Linux start script should use lf +./gradlew text eol=lf linguist-vendored linguist-generated + +# These are Windows script files and should use crlf +*.bat text eol=crlf + +./gradlew linguist-vendored linguist-generated +./gradlew.bat linguist-vendored linguist-generated +./gradle/wrapper/gradle-wrapper.jar linguist-vendored linguist-generated diff --git a/example/kotlin/.gitignore b/example/kotlin/.gitignore new file mode 100644 index 000000000..9d8d26b7f --- /dev/null +++ b/example/kotlin/.gitignore @@ -0,0 +1,16 @@ +# Ignore Gradle project-specific cache directory +.gradle + +# Ignore Gradle build output directory +build +output.wav + +# OpenJTalk-dictionary's dir +open_jtalk_dic_utf_8-* + +# shared library +*.so +*.so.* +*.dylib +*.dll +*.jar diff --git a/example/kotlin/README.md b/example/kotlin/README.md new file mode 100644 index 000000000..908bdd51f --- /dev/null +++ b/example/kotlin/README.md @@ -0,0 +1,66 @@ +# Kotlin サンプルコード(jni-rs によるバインディング経由) + +voicevox_core ライブラリ の Java バインディングを使った音声合成のサンプルコードです。 + +## 準備 + +1. VOICEVOX CORE Java API をビルドします。 + +crates/voicevox_core_java_api/README.md を参照してください。 + +2. ダウンローダーを使って環境構築します。 + +linux/mac の場合 + +download-linux-x64 のところはアーキテクチャや OS によって適宜読み替えてください。 +https://github.com/VOICEVOX/voicevox_core/releases/latest#%E3%83%80%E3%82%A6%E3%83%B3%E3%83%AD%E3%83%BC%E3%83%80 + +```console +❯ binary=download-linux-x64 +❯ curl -sSfL https://github.com/VOICEVOX/voicevox_core/releases/latest/download/${binary} -o download +❯ chmod +x download +❯ ./download -o ./example/kotlin +❯ # いくつかのファイルは不要なので消すことができます +❯ #rm -r ./example/kotlin/{model,VERSION,*voicevox_core*} +``` + +windows の場合 + +```console +❯ Invoke-WebRequest https://github.com/VOICEVOX/voicevox_core/releases/latest/download/download-windows-x64.exe -OutFile ./download.exe +❯ ./download -o ./example/kotlin +❯ # いくつかのファイルは不要なので消すことができます +❯ #Remove-Item -Recurse ./example/kotlin/model,./example/kotlin/VERSION,./example/kotlin/*voicevox_core* +``` + +## 実行 + +Open JTalk 辞書ディレクトリ、読み上げさせたい文章、出力 wav ファイルのパスをオプションで指定することができます。 + +```console +❯ ./gradlew run --args="-h" +# または +❯ ./gradlew build +❯ java -jar ./app/build/libs/app-all.jar -h + +Usage: voicevoxcoreexample options_list +Options: + --mode [AUTO] -> モード { Value should be one of [auto, cpu, gpu] } + --vvm -> vvmファイルへのパス (always required) { String } + --dictDir [./open_jtalk_dic_utf_8-1.11] -> Open JTalkの辞書ディレクトリ { String } + --text [この音声は、ボイスボックスを使用して、出力されています。] -> 読み上げさせたい文章 { String } + --out [./output.wav] -> 出力wavファイルのパス { String } + --styleId [0] -> 話者IDを指定 { Int } + --help, -h -> Usage info +``` + +## 実行例 + +```console +❯ ./gradlew run --args="--vvm ../../model/sample.vvm" +Inititalizing: AUTO, ./open_jtalk_dic_utf_8-1.11 +Loading: ../../model/sample.vvm +Creating an AudioQuery from the text: この音声は、ボイスボックスを使用して、出力されています。 +Synthesizing... +Saving the audio to ./output.wav +``` diff --git a/example/kotlin/app/build.gradle b/example/kotlin/app/build.gradle new file mode 100644 index 000000000..81ac24a49 --- /dev/null +++ b/example/kotlin/app/build.gradle @@ -0,0 +1,52 @@ +plugins { + id 'org.jetbrains.kotlin.jvm' version '1.8.20' + + id 'application' + + id 'com.github.johnrengelman.shadow' version '8.1.1' +} + +repositories { + // Use Maven Central for resolving dependencies. + mavenCentral() +} + +dependencies { + // Use the Kotlin JUnit 5 integration. + testImplementation 'org.jetbrains.kotlin:kotlin-test-junit5' + + // Use the JUnit 5 integration. + testImplementation 'org.junit.jupiter:junit-jupiter-engine:5.9.2' + + testRuntimeOnly 'org.junit.platform:junit-platform-launcher' + + implementation("org.jetbrains.kotlinx:kotlinx-cli:0.3.6") + + // TODO: ちゃんと配布したらそれに置き換える + implementation files("../../../crates/voicevox_core_java_api/lib/build/libs/lib-0.0.0.jar") + // https://mvnrepository.com/artifact/com.google.code.gson/gson + implementation group: 'com.google.code.gson', name: 'gson', version: "2.10.1" + // https://mvnrepository.com/artifact/jakarta.validation/jakarta.validation-api + implementation group: 'jakarta.validation', name: 'jakarta.validation-api', version: "3.0.2" + // https://mvnrepository.com/artifact/jakarta.annotation/jakarta.annotation-api + implementation group: 'jakarta.annotation', name: 'jakarta.annotation-api', version: "2.1.1" + implementation group: 'com.microsoft.onnxruntime', name: 'onnxruntime', version: "1.14.0" +} + +// Apply a specific Java toolchain to ease working on different environments. +java { + toolchain { + languageVersion = JavaLanguageVersion.of(11) + } +} + +application { + // Define the main class for the application. + mainClass = 'app.AppKt' + tasks.run.workingDir = rootProject.projectDir +} + +tasks.named('test') { + // Use JUnit Platform for unit tests. + useJUnitPlatform() +} diff --git a/example/kotlin/app/src/main/kotlin/app/App.kt b/example/kotlin/app/src/main/kotlin/app/App.kt new file mode 100644 index 000000000..3e76043f4 --- /dev/null +++ b/example/kotlin/app/src/main/kotlin/app/App.kt @@ -0,0 +1,56 @@ +package app + +import java.io.File +import jp.hiroshiba.voicevoxcore.* +import kotlinx.cli.* + +enum class Mode { + AUTO, + CPU, + GPU +} + +fun main(args: Array) { + val parser = ArgParser("voicevoxcoreexample") + val mode by parser.option(ArgType.Choice(), description = "モード").default(Mode.AUTO) + val vvmPath by + parser.option(ArgType.String, fullName = "vvm", description = "vvmファイルへのパス").required() + val dictDir by + parser + .option(ArgType.String, description = "Open JTalkの辞書ディレクトリ") + .default("./open_jtalk_dic_utf_8-1.11") + val text by + parser + .option(ArgType.String, description = "読み上げさせたい文章") + .default("この音声は、ボイスボックスを使用して、出力されています。") + val out by parser.option(ArgType.String, description = "出力wavファイルのパス").default("./output.wav") + val styleId by parser.option(ArgType.Int, description = "話者IDを指定").default(0) + + parser.parse(args) + + println("Inititalizing: ${mode}, ${dictDir}") + val openJtalk = OpenJtalk(dictDir) + val synthesizer = + Synthesizer.builder(openJtalk) + .accelerationMode( + when (mode) { + Mode.AUTO -> Synthesizer.AccelerationMode.AUTO + Mode.CPU -> Synthesizer.AccelerationMode.CPU + Mode.GPU -> Synthesizer.AccelerationMode.GPU + } + ) + .build() + + println("Loading: ${vvmPath}") + val vvm = VoiceModel(vvmPath) + synthesizer.loadVoiceModel(vvm) + + println("Creating an AudioQuery from the text: ${text}") + val audioQuery = synthesizer.createAudioQuery(text, styleId) + + println("Synthesizing...") + val audio = synthesizer.synthesis(audioQuery, styleId).execute() + + println("Saving the audio to ${out}") + File(out).writeBytes(audio) +} diff --git a/example/kotlin/gradle/wrapper/gradle-wrapper.properties b/example/kotlin/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 000000000..9f4197d5f --- /dev/null +++ b/example/kotlin/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.2.1-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/example/kotlin/gradlew b/example/kotlin/gradlew new file mode 100755 index 000000000..fcb6fca14 --- /dev/null +++ b/example/kotlin/gradlew @@ -0,0 +1,248 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/example/kotlin/gradlew.bat b/example/kotlin/gradlew.bat new file mode 100644 index 000000000..93e3f59f1 --- /dev/null +++ b/example/kotlin/gradlew.bat @@ -0,0 +1,92 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/example/kotlin/settings.gradle b/example/kotlin/settings.gradle new file mode 100644 index 000000000..46c449b92 --- /dev/null +++ b/example/kotlin/settings.gradle @@ -0,0 +1,14 @@ +/* + * This file was generated by the Gradle 'init' task. + * + * The settings file is used to specify which projects to include in your build. + * For more detailed information on multi-project builds, please refer to https://docs.gradle.org/8.2.1/userguide/building_swift_projects.html in the Gradle documentation. + */ + +plugins { + // Apply the foojay-resolver plugin to allow automatic download of JDKs + id 'org.gradle.toolchains.foojay-resolver-convention' version '0.4.0' +} + +rootProject.name = 'voicevoxcoreexample' +include('app') diff --git a/example/python/run.py b/example/python/run.py index d224a509d..27b787b00 100644 --- a/example/python/run.py +++ b/example/python/run.py @@ -36,7 +36,7 @@ async def main() -> None: logger.debug("%s", f"{voicevox_core.supported_devices()=}") logger.info("%s", f"Initializing ({acceleration_mode=}, {open_jtalk_dict_dir=})") - synthesizer = await Synthesizer.new( + synthesizer = Synthesizer( OpenJtalk(open_jtalk_dict_dir), acceleration_mode=acceleration_mode )