Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Synthesizer::newを非asyncにする #671

Merged
merged 4 commits into from
Nov 3, 2023
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions crates/voicevox_core/src/engine/synthesis_engine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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());

Expand All @@ -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();
Expand Down
2 changes: 1 addition & 1 deletion crates/voicevox_core/src/inference_core.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ pub struct InferenceCore {
}

impl InferenceCore {
pub(crate) async fn new(use_gpu: bool, cpu_num_threads: u16) -> Result<Self> {
pub(crate) fn new(use_gpu: bool, cpu_num_threads: u16) -> Result<Self> {
if !use_gpu || Self::can_support_gpu_feature()? {
let status = Status::new(use_gpu, cpu_num_threads);
Ok(Self { status })
Expand Down
33 changes: 8 additions & 25 deletions crates/voicevox_core/src/synthesizer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -96,13 +95,12 @@ impl Synthesizer {
/// acceleration_mode: ACCELERATION_MODE,
/// ..Default::default()
/// },
/// )
/// .await?;
/// )?;
/// #
/// # Ok(())
/// # }
/// ```
pub async fn new(open_jtalk: Arc<OpenJtalk>, options: &InitializeOptions) -> Result<Self> {
pub fn new(open_jtalk: Arc<OpenJtalk>, options: &InitializeOptions) -> Result<Self> {
#[cfg(windows)]
list_windows_video_cards();
let use_gpu = match options.acceleration_mode {
Expand All @@ -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,
Expand Down Expand Up @@ -259,8 +257,7 @@ impl Synthesizer {
/// # acceleration_mode: AccelerationMode::Cpu,
/// # ..Default::default()
/// # },
/// # )
/// # .await?;
/// # )?;
/// #
/// # let model = &VoiceModel::from_path(concat!(
/// # env!("CARGO_MANIFEST_DIR"),
Expand Down Expand Up @@ -313,8 +310,7 @@ impl Synthesizer {
/// # acceleration_mode: AccelerationMode::Cpu,
/// # ..Default::default()
/// # },
/// # )
/// # .await?;
/// # )?;
/// #
/// # let model = &VoiceModel::from_path(concat!(
/// # env!("CARGO_MANIFEST_DIR"),
Expand Down Expand Up @@ -403,8 +399,7 @@ impl Synthesizer {
/// # acceleration_mode: AccelerationMode::Cpu,
/// # ..Default::default()
/// # },
/// # )
/// # .await?;
/// # )?;
/// #
/// # let model = &VoiceModel::from_path(concat!(
/// # env!("CARGO_MANIFEST_DIR"),
Expand Down Expand Up @@ -458,8 +453,7 @@ impl Synthesizer {
/// # acceleration_mode: AccelerationMode::Cpu,
/// # ..Default::default()
/// # },
/// # )
/// # .await?;
/// # )?;
/// #
/// # let model = &VoiceModel::from_path(concat!(
/// # env!("CARGO_MANIFEST_DIR"),
Expand Down Expand Up @@ -586,7 +580,6 @@ mod tests {
..Default::default()
},
)
.await
.unwrap();

let result = syntesizer
Expand All @@ -610,7 +603,6 @@ mod tests {
..Default::default()
},
)
.await
.unwrap();
assert!(!syntesizer.is_gpu_mode());
}
Expand All @@ -627,7 +619,6 @@ mod tests {
..Default::default()
},
)
.await
.unwrap();
assert!(
!syntesizer.is_loaded_model_by_style_id(style_id),
Expand Down Expand Up @@ -656,7 +647,6 @@ mod tests {
..Default::default()
},
)
.await
.unwrap();

syntesizer
Expand Down Expand Up @@ -688,7 +678,6 @@ mod tests {
..Default::default()
},
)
.await
.unwrap();
syntesizer
.load_voice_model(&open_default_vvm_file().await)
Expand Down Expand Up @@ -730,7 +719,6 @@ mod tests {
..Default::default()
},
)
.await
.unwrap();
syntesizer
.load_voice_model(&open_default_vvm_file().await)
Expand Down Expand Up @@ -823,7 +811,6 @@ mod tests {
..Default::default()
},
)
.await
.unwrap();

let model = &VoiceModel::sample().await.unwrap();
Expand Down Expand Up @@ -892,7 +879,6 @@ mod tests {
..Default::default()
},
)
.await
.unwrap();

let model = &VoiceModel::sample().await.unwrap();
Expand Down Expand Up @@ -958,7 +944,6 @@ mod tests {
..Default::default()
},
)
.await
.unwrap();

let model = &VoiceModel::sample().await.unwrap();
Expand Down Expand Up @@ -995,7 +980,6 @@ mod tests {
..Default::default()
},
)
.await
.unwrap();

let model = &VoiceModel::sample().await.unwrap();
Expand Down Expand Up @@ -1028,7 +1012,6 @@ mod tests {
..Default::default()
},
)
.await
.unwrap();

let model = &VoiceModel::sample().await.unwrap();
Expand Down
8 changes: 6 additions & 2 deletions crates/voicevox_core_c_api/src/c_impls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,12 @@ impl OpenJtalkRc {
}

impl VoicevoxSynthesizer {
pub(crate) async fn new(open_jtalk: &OpenJtalkRc, options: &InitializeOptions) -> Result<Self> {
let synthesizer = Synthesizer::new(open_jtalk.open_jtalk.clone(), options).await?;
pub(crate) fn new(open_jtalk: &OpenJtalkRc, options: &InitializeOptions) -> Result<Self> {
// ロガーを起動
// 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 })
}

Expand Down
3 changes: 1 addition & 2 deletions crates/voicevox_core_c_api/src/compatible_engine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
4 changes: 1 addition & 3 deletions crates/voicevox_core_c_api/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(())
})())
Expand Down
5 changes: 1 addition & 4 deletions crates/voicevox_core_java_api/src/synthesizer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,10 +48,7 @@ unsafe extern "system" fn Java_jp_hiroshiba_voicevoxcore_Synthesizer_rsNew<'loca
let open_jtalk = env
.get_rust_field::<_, _, Arc<voicevox_core::OpenJtalk>>(&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(())
})
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down
32 changes: 15 additions & 17 deletions crates/voicevox_core_python_api/python/voicevox_core/_rust.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -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: ...
Expand Down
29 changes: 12 additions & 17 deletions crates/voicevox_core_python_api/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Self> {
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 {
Expand Down
2 changes: 1 addition & 1 deletion example/python/run.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
)

Expand Down
Loading