From 7c4e155cc5d7c19c788dc24dfd4da29775f959d8 Mon Sep 17 00:00:00 2001 From: Nanahuse <109294061+Nanahuse@users.noreply.github.com> Date: Fri, 7 Aug 2026 02:18:00 +0900 Subject: [PATCH 1/2] Fix Ruff lint errors --- pyproject.toml | 4 +- test/manual_voicepeak_file_generation.py | 106 +++++++++-------- test/test_voicepeak.py | 55 +++++---- voicepeak_wrapper/voicepeak.py | 140 +++++++++++++---------- 4 files changed, 157 insertions(+), 148 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 5a5f57f..13a09bf 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -39,6 +39,4 @@ lint.ignore = [ "D", "TD", ] - -[tool.ruff.per-file-ignores] -"test/*" = ["INP001", "PLR2004", "SLF001"] +lint.per-file-ignores = { "test/*" = ["INP001", "PLR2004", "SLF001"] } diff --git a/test/manual_voicepeak_file_generation.py b/test/manual_voicepeak_file_generation.py index 1dfd812..b4e0f26 100644 --- a/test/manual_voicepeak_file_generation.py +++ b/test/manual_voicepeak_file_generation.py @@ -1,3 +1,7 @@ +# Copyright (c) 2023 Nanahuse +# This software is released under the MIT License +# https://opensource.org/license/mit/ + """VOICEPEAK integration tests that create output files. These tests require a local VOICEPEAK installation. Pytest does not collect this @@ -6,97 +10,89 @@ uv run --extra dev --with-editable . pytest test/manual_voicepeak_file_generation.py """ -import os +import asyncio +from pathlib import Path import pytest -TEST_DIRECTORY = os.path.dirname(os.path.abspath(__file__)) -OUTPUT_PATH = os.path.join(TEST_DIRECTORY, "output") +import voicepeak_wrapper +TEST_DIRECTORY = Path(__file__).resolve().parent +OUTPUT_PATH = TEST_DIRECTORY / "output" -@pytest.mark.asyncio -async def test_get_narrator_list(): - import voicepeak_wrapper +def _write_text(path: Path, text: str) -> None: + with path.open(mode="w", encoding="UTF-8") as f: + f.write(text) + + +@pytest.mark.asyncio +async def test_get_narrator_list() -> None: client = voicepeak_wrapper.Voicepeak() narrators = await client.get_narrator_list() - with open(os.path.join(OUTPUT_PATH, "narrators.txt"), mode="w", encoding="UTF-8") as f: - for narrator in narrators: - f.write(narrator.name) - f.write(" : ") - f.write(", ".join(narrator.emotions)) - f.write("\n") - - await client.say_text( - "本日は晴天なり", - output_path=os.path.join(OUTPUT_PATH, f"narrator_{narrator.name}.wav"), - narrator=narrator, - emotions={narrator.emotions[1]: 100}, - ) + output = [] + for narrator in narrators: + output.append(f"{narrator.name} : {', '.join(narrator.emotions)}\n") + await client.say_text( + "本日は晴天なり", + output_path=OUTPUT_PATH / f"narrator_{narrator.name}.wav", + narrator=narrator, + emotions={narrator.emotions[1]: 100}, + ) + await asyncio.to_thread(_write_text, OUTPUT_PATH / "narrators.txt", "".join(output)) @pytest.mark.asyncio -async def test_get_narrator_name_list(): - import voicepeak_wrapper - +async def test_get_narrator_name_list() -> None: client = voicepeak_wrapper.Voicepeak() narrator_names = await client.get_narrator_name_list() - with open(os.path.join(OUTPUT_PATH, "narrator_names.txt"), mode="w", encoding="UTF-8") as f: - f.writelines(f"{name}\n" for name in narrator_names) + content = "".join(f"{name}\n" for name in narrator_names) + await asyncio.to_thread(_write_text, OUTPUT_PATH / "narrator_names.txt", content) @pytest.mark.asyncio -async def test_get_emotion_list(): - import voicepeak_wrapper - +async def test_get_emotion_list() -> None: client = voicepeak_wrapper.Voicepeak() narrator_names = await client.get_narrator_name_list() - with open(os.path.join(OUTPUT_PATH, "emotions.txt"), mode="w", encoding="UTF-8") as f: - for name in narrator_names: - emotion_list = await client.get_emotion_list(name) - - f.write(name) - f.write(" : ") - f.write(", ".join(emotion_list)) - f.write("\n") + output = [] + for name in narrator_names: + emotion_list = await client.get_emotion_list(name) + output.append(f"{name} : {', '.join(emotion_list)}\n") + await asyncio.to_thread(_write_text, OUTPUT_PATH / "emotions.txt", "".join(output)) with pytest.raises(RuntimeError): await client.get_emotion_list("hogehoge") @pytest.mark.asyncio -async def test_say_text(): - import voicepeak_wrapper - +async def test_say_text() -> None: client = voicepeak_wrapper.Voicepeak() - await client.say_text("本日は晴天なり", output_path=os.path.join(OUTPUT_PATH, "test_say_text.wav")) + await client.say_text("本日は晴天なり", output_path=OUTPUT_PATH / "test_say_text.wav") await client.say_text( - "本日は晴天なり", output_path=os.path.join(OUTPUT_PATH, "test_say_text_upper.wav"), speed=200, pitch=300 + "本日は晴天なり", output_path=OUTPUT_PATH / "test_say_text_upper.wav", speed=200, pitch=300 ) await client.say_text( - "本日は晴天なり", output_path=os.path.join(OUTPUT_PATH, "test_say_text_lower.wav"), speed=50, pitch=-300 + "本日は晴天なり", output_path=OUTPUT_PATH / "test_say_text_lower.wav", speed=50, pitch=-300 ) - with pytest.raises(ValueError): - await client.say_text("エラー", output_path=os.path.join(OUTPUT_PATH, "error.wav"), speed=201) - with pytest.raises(ValueError): - await client.say_text("エラー", output_path=os.path.join(OUTPUT_PATH, "error.wav"), speed=49) - with pytest.raises(ValueError): - await client.say_text("エラー", output_path=os.path.join(OUTPUT_PATH, "error.wav"), pitch=-301) - with pytest.raises(ValueError): - await client.say_text("エラー", output_path=os.path.join(OUTPUT_PATH, "error.wav"), pitch=301) + with pytest.raises(ValueError, match="speed"): + await client.say_text("エラー", output_path=OUTPUT_PATH / "error.wav", speed=201) + with pytest.raises(ValueError, match="speed"): + await client.say_text("エラー", output_path=OUTPUT_PATH / "error.wav", speed=49) + with pytest.raises(ValueError, match="pitch"): + await client.say_text("エラー", output_path=OUTPUT_PATH / "error.wav", pitch=-301) + with pytest.raises(ValueError, match="pitch"): + await client.say_text("エラー", output_path=OUTPUT_PATH / "error.wav", pitch=301) with pytest.raises(RuntimeError): - await client.say_text("1" * 141, output_path=os.path.join(OUTPUT_PATH, "error.wav")) + await client.say_text("1" * 141, output_path=OUTPUT_PATH / "error.wav") @pytest.mark.asyncio -async def test_say_testfile(): - import voicepeak_wrapper - +async def test_say_testfile() -> None: client = voicepeak_wrapper.Voicepeak() - text_file = os.path.join(TEST_DIRECTORY, "sample.txt") + text_file = TEST_DIRECTORY / "sample.txt" - await client.say_textfile(text_file, output_path=os.path.join(OUTPUT_PATH, "say_text.wav")) + await client.say_textfile(text_file, output_path=OUTPUT_PATH / "say_text.wav") diff --git a/test/test_voicepeak.py b/test/test_voicepeak.py index d256b7a..e210cc6 100644 --- a/test/test_voicepeak.py +++ b/test/test_voicepeak.py @@ -9,36 +9,34 @@ import pytest +import voicepeak_wrapper + class ProcessResult: - def __init__(self, stdout: bytes = b"", stderr: bytes = b""): + def __init__(self, stdout: bytes = b"", stderr: bytes = b"") -> None: self.communicate = AsyncMock(return_value=(stdout, stderr)) -def create_client(monkeypatch): - monkeypatch.setenv("ProgramFiles", os.path.dirname(__file__)) - import voicepeak_wrapper - +def create_client(monkeypatch: pytest.MonkeyPatch) -> voicepeak_wrapper.Voicepeak: + monkeypatch.setenv("PROGRAMFILES", str(Path(__file__).parent)) return voicepeak_wrapper.Voicepeak(exe_path=__file__) -def create_client_with_pathlib_path(monkeypatch): - monkeypatch.setenv("ProgramFiles", os.path.dirname(__file__)) - import voicepeak_wrapper - +def create_client_with_pathlib_path(monkeypatch: pytest.MonkeyPatch) -> voicepeak_wrapper.Voicepeak: + monkeypatch.setenv("PROGRAMFILES", str(Path(__file__).parent)) return voicepeak_wrapper.Voicepeak(exe_path=Path(__file__)) -def mock_process(monkeypatch, *results): +def mock_process(monkeypatch: pytest.MonkeyPatch, *results: ProcessResult) -> AsyncMock: create_subprocess = AsyncMock(side_effect=results) monkeypatch.setattr(asyncio, "create_subprocess_exec", create_subprocess) return create_subprocess @pytest.mark.asyncio -async def test_get_narrator_name_list_decodes_terminal_output(monkeypatch): +async def test_get_narrator_name_list_decodes_terminal_output(monkeypatch: pytest.MonkeyPatch) -> None: client = create_client(monkeypatch) - process = ProcessResult("Japanese Female 1\nJapanese Male 1\n".encode()) + process = ProcessResult(b"Japanese Female 1\nJapanese Male 1\n") create_subprocess = mock_process(monkeypatch, process) assert await client.get_narrator_name_list() == ("Japanese Female 1", "Japanese Male 1") @@ -52,23 +50,22 @@ async def test_get_narrator_name_list_decodes_terminal_output(monkeypatch): @pytest.mark.asyncio -async def test_get_emotion_list_decodes_terminal_output(monkeypatch): +async def test_get_emotion_list_decodes_terminal_output(monkeypatch: pytest.MonkeyPatch) -> None: client = create_client(monkeypatch) - process = ProcessResult("happy\nsad\n".encode()) + process = ProcessResult(b"happy\nsad\n") mock_process(monkeypatch, process) assert await client.get_emotion_list("Japanese Female 1") == ("happy", "sad") @pytest.mark.asyncio -async def test_get_narrator_list_uses_each_terminal_output(monkeypatch): +async def test_get_narrator_list_uses_each_terminal_output(monkeypatch: pytest.MonkeyPatch) -> None: client = create_client(monkeypatch) - import voicepeak_wrapper processes = ( - ProcessResult("Japanese Female 1\nJapanese Male 1\n".encode()), - ProcessResult("happy\nsad\n".encode()), - ProcessResult("happy\nangry\n".encode()), + ProcessResult(b"Japanese Female 1\nJapanese Male 1\n"), + ProcessResult(b"happy\nsad\n"), + ProcessResult(b"happy\nangry\n"), ) mock_process(monkeypatch, *processes) @@ -79,9 +76,9 @@ async def test_get_narrator_list_uses_each_terminal_output(monkeypatch): @pytest.mark.asyncio -async def test_say_text_returns_decoded_terminal_output(monkeypatch): +async def test_say_text_returns_decoded_terminal_output(monkeypatch: pytest.MonkeyPatch) -> None: client = create_client(monkeypatch) - process = ProcessResult("completed\n".encode()) + process = ProcessResult(b"completed\n") create_subprocess = mock_process(monkeypatch, process) result = await client.say_text("本日は晴天なり", output_path="output.wav") @@ -100,9 +97,9 @@ async def test_say_text_returns_decoded_terminal_output(monkeypatch): @pytest.mark.asyncio -async def test_terminal_error_is_decoded_as_runtime_error(monkeypatch): +async def test_terminal_error_is_decoded_as_runtime_error(monkeypatch: pytest.MonkeyPatch) -> None: client = create_client(monkeypatch) - process = ProcessResult(stderr="narrator not found\n".encode()) + process = ProcessResult(stderr=b"narrator not found\n") mock_process(monkeypatch, process) with pytest.raises(RuntimeError, match="narrator not found"): @@ -110,9 +107,9 @@ async def test_terminal_error_is_decoded_as_runtime_error(monkeypatch): @pytest.mark.asyncio -async def test_say_text_accepts_pathlib_path_for_output_path(monkeypatch): +async def test_say_text_accepts_pathlib_path_for_output_path(monkeypatch: pytest.MonkeyPatch) -> None: client = create_client(monkeypatch) - process = ProcessResult("completed\n".encode()) + process = ProcessResult(b"completed\n") create_subprocess = mock_process(monkeypatch, process) await client.say_text("本日は晴天なり", output_path=Path("output.wav")) @@ -129,9 +126,9 @@ async def test_say_text_accepts_pathlib_path_for_output_path(monkeypatch): @pytest.mark.asyncio -async def test_say_textfile_accepts_pathlib_path(monkeypatch): +async def test_say_textfile_accepts_pathlib_path(monkeypatch: pytest.MonkeyPatch) -> None: client = create_client(monkeypatch) - process = ProcessResult("completed\n".encode()) + process = ProcessResult(b"completed\n") create_subprocess = mock_process(monkeypatch, process) await client.say_textfile(Path("input.txt"), output_path=Path("output.wav")) @@ -148,9 +145,9 @@ async def test_say_textfile_accepts_pathlib_path(monkeypatch): @pytest.mark.asyncio -async def test_voicepeak_accepts_pathlib_path_for_exe_path(monkeypatch): +async def test_voicepeak_accepts_pathlib_path_for_exe_path(monkeypatch: pytest.MonkeyPatch) -> None: client = create_client_with_pathlib_path(monkeypatch) - process = ProcessResult("Japanese Female 1\n".encode()) + process = ProcessResult(b"Japanese Female 1\n") create_subprocess = mock_process(monkeypatch, process) assert await client.get_narrator_name_list() == ("Japanese Female 1",) diff --git a/voicepeak_wrapper/voicepeak.py b/voicepeak_wrapper/voicepeak.py index 16869ec..a2c587c 100644 --- a/voicepeak_wrapper/voicepeak.py +++ b/voicepeak_wrapper/voicepeak.py @@ -6,6 +6,7 @@ import os from dataclasses import dataclass from os import PathLike +from pathlib import Path @dataclass @@ -14,11 +15,40 @@ class Narrator: emotions: tuple[str, ...] +@dataclass(frozen=True) +class _SayRequest: + text: str | None = None + text_file: str | PathLike[str] | None = None + output_path: str | PathLike[str] | None = None + narrator: Narrator | str | None = None + emotions: dict[str, int] | None = None + speed: int | None = None + pitch: int | None = None + + +_SPEED_RANGE = (50, 200) +_PITCH_RANGE = (-300, 300) +_DEFAULT_EXE_PATH = os.path.join( # noqa: PTH118 + os.environ["ProgramFiles"], # noqa: SIM112 + "VOICEPEAK", + "voicepeak.exe", +) + + +def _append_range(args: list[str], option: str, label: str, value: int | None, value_range: tuple[int, int]) -> None: + if value is None: + return + if isinstance(value, int) and value_range[0] <= value <= value_range[1]: + args += [option, str(value)] + return + raise ValueError(f"{label}は{value_range[0]} - {value_range[1]}の範囲内の整数") + + class Voicepeak: def __init__( self, - exe_path: str | PathLike[str] = os.path.join(os.environ["ProgramFiles"], "VOICEPEAK", "voicepeak.exe"), - ): + exe_path: str | PathLike[str] = _DEFAULT_EXE_PATH, + ) -> None: """ 標準のインストール先ではない場所にVOICEPEAKインストールした場合はexe_pathを指定してください。 @@ -26,8 +56,7 @@ def __init__( exe_path (str | os.PathLike[str], optional): voicepeak.exeへのパス。strまたはpathlib.Pathで指定できる。 Defaultは標準のインストール先。 """ - - if not os.path.exists(exe_path): + if not Path(exe_path).exists(): raise FileNotFoundError("VOICEPEAKの実行ファイルが見つかりません") self.__exe_path = exe_path @@ -47,23 +76,10 @@ async def __async_run(self, args: list[str]) -> str: return stdout.decode() - def __make_say_command( - self, - text: str | None = None, - text_file: str | PathLike[str] | None = None, - output_path: str | PathLike[str] | None = None, - narrator: Narrator | str | None = None, - emotions: dict[str, int] | None = None, - speed: int | None = None, - pitch: int | None = None, - ) -> list[str]: - args = [] - - if text_file is not None: - text_file = os.fspath(text_file) - if output_path is not None: - output_path = os.fspath(output_path) - + @staticmethod + def __append_text_args(args: list[str], request: _SayRequest) -> None: + text = request.text + text_file = os.fspath(request.text_file) if request.text_file is not None else None match text, text_file: case str(), str(): raise ValueError("textかtext_fileの一方のみ指定してください") @@ -76,9 +92,8 @@ def __make_say_command( case _: raise ValueError("textまたはtext_fileが不正な値です。") - if output_path is not None: - args += ["-o", output_path] - + @staticmethod + def __append_narrator(args: list[str], narrator: Narrator | str | None) -> None: match narrator: case Narrator(): args += ["-n", narrator.name] @@ -87,28 +102,23 @@ def __make_say_command( case None: pass + @staticmethod + def __append_emotions(args: list[str], emotions: dict[str, int] | None) -> None: if emotions is not None: args += ["-e", ",".join(f"{param}={value}" for param, value in emotions.items())] - SPEED_RANGE = (50, 200) - if isinstance(speed, int) and (SPEED_RANGE[0] <= speed <= SPEED_RANGE[1]): - args += ["--speed", str(speed)] - elif speed is None: - pass - else: - raise ValueError(f"speedは{SPEED_RANGE[0]} - {SPEED_RANGE[1]}の範囲内の整数") - - PITCH_RANGE = (-300, 300) - if isinstance(pitch, int) and (PITCH_RANGE[0] <= pitch <= PITCH_RANGE[1]): - args += ["--pitch", str(pitch)] - elif pitch is None: - pass - else: - raise ValueError(f"pitchは{PITCH_RANGE[0]} - {PITCH_RANGE[1]}の範囲内の整数") - + def __make_say_command(self, request: _SayRequest) -> list[str]: + args: list[str] = [] + self.__append_text_args(args, request) + if request.output_path is not None: + args += ["-o", os.fspath(request.output_path)] + self.__append_narrator(args, request.narrator) + self.__append_emotions(args, request.emotions) + _append_range(args, "--speed", "speed", request.speed, _SPEED_RANGE) + _append_range(args, "--pitch", "pitch", request.pitch, _PITCH_RANGE) return args - async def say_text( + async def say_text( # noqa: PLR0913 self, text: str, *, @@ -117,7 +127,7 @@ async def say_text( emotions: dict[str, int] | None = None, speed: int | None = None, pitch: int | None = None, - ): + ) -> str: """ テキストを読み上げたwavファイルを保存する。 @@ -127,9 +137,11 @@ async def say_text( output_path (str | os.PathLike[str] | None, optional): wavファイル出力先。strまたはpathlib.Pathで指定可。 指定しないとvoicepeak.exeと同じ階層にoutput.wavが生成される。 Defaults to None. - narrator (Narrator | str | None, optional): 読み上げを行うナレータの種類。Narrator型またはstr型の名前で指定する。 Defaults to None. + narrator (Narrator | str | None, optional): 読み上げを行うナレータの種類。 + Narrator型またはstr型の名前で指定する。 Defaults to None. - emotions (dict[str, int] | None, optional): 読み上げ時の感情の指示。形式は{"感情名","値"}の辞書型。 Defaults to None. + emotions (dict[str, int] | None, optional): 読み上げ時の感情の指示。 + 形式は{"感情名","値"}の辞書型。 Defaults to None. speed (int | None, optional): 読み上げのスピード。100が等倍。50~200の範囲。 Defaults to None. @@ -137,16 +149,18 @@ async def say_text( """ return await self.__async_run( self.__make_say_command( - text=text, - output_path=output_path, - narrator=narrator, - emotions=emotions, - speed=speed, - pitch=pitch, + _SayRequest( + text=text, + output_path=output_path, + narrator=narrator, + emotions=emotions, + speed=speed, + pitch=pitch, + ) ) ) - async def say_textfile( + async def say_textfile( # noqa: PLR0913 self, text_path: str | PathLike[str], *, @@ -155,7 +169,7 @@ async def say_textfile( emotions: dict[str, int] | None = None, speed: int | None = None, pitch: int | None = None, - ): + ) -> str: """ テキストファイル内のテキストを読み上げたwavファイルを保存する。 @@ -165,9 +179,11 @@ async def say_textfile( output_path (str | os.PathLike[str], optional): wavファイル出力先。strまたはpathlib.Pathで指定できる。 Defaultはoutput.wavが生成される。 - narrator (Narrator | str | None, optional): 読み上げを行うナレータの種類。Narrator型またはstr型の名前で指定する。 Defaults to None. + narrator (Narrator | str | None, optional): 読み上げを行うナレータの種類。 + Narrator型またはstr型の名前で指定する。 Defaults to None. - emotions (dict[str, int] | None, optional): 読み上げ時の感情の指示。形式は{"感情名","値"}の辞書型。 Defaults to None. + emotions (dict[str, int] | None, optional): 読み上げ時の感情の指示。 + 形式は{"感情名","値"}の辞書型。 Defaults to None. speed (int | None, optional): 読み上げのスピード。100が等倍。50~200の範囲。 Defaults to None. @@ -175,12 +191,14 @@ async def say_textfile( """ return await self.__async_run( self.__make_say_command( - text_file=text_path, - output_path=output_path, - narrator=narrator, - emotions=emotions, - speed=speed, - pitch=pitch, + _SayRequest( + text_file=text_path, + output_path=output_path, + narrator=narrator, + emotions=emotions, + speed=speed, + pitch=pitch, + ) ) ) @@ -192,7 +210,7 @@ async def get_narrator_list(self) -> tuple[Narrator, ...]: tuple[Narrator]: ナレーター一覧 """ narrators = await self.get_narrator_name_list() - narrator_list = list() + narrator_list = [] for name in narrators: emotions = await self.get_emotion_list(name) narrator_list.append(Narrator(name, emotions)) From e4acc0828f20af27bc4d3da13740082ab1ecac15 Mon Sep 17 00:00:00 2001 From: Nanahuse <109294061+Nanahuse@users.noreply.github.com> Date: Fri, 7 Aug 2026 08:37:18 +0900 Subject: [PATCH 2/2] Run CI tests on Windows --- .github/workflows/test.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 48dc079..c46ecff 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -8,7 +8,7 @@ permissions: jobs: test: - runs-on: ubuntu-latest + runs-on: windows-latest steps: - name: Checkout uses: actions/checkout@v6