Skip to content

Commit

Permalink
修正: deprecated な型付けを更新 (#1218)
Browse files Browse the repository at this point in the history
* fix: deprecated な `List` を廃止

* fix: deprecated な `Tuple` を廃止

* fix: deprecated な `Optional` を廃止

* fix: deprecated な `Dict` を廃止
  • Loading branch information
tarepan authored May 6, 2024
1 parent a6f601c commit b91d076
Show file tree
Hide file tree
Showing 13 changed files with 80 additions and 90 deletions.
3 changes: 1 addition & 2 deletions build_util/get_cost_candidates.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@
import argparse
import statistics
from pathlib import Path
from typing import List

import numpy as np

Expand All @@ -30,7 +29,7 @@ def get_candidates(
pos_detail_1: str,
pos_detail_2: str,
pos_detail_3: str,
) -> List[int]:
) -> list[int]:
costs = []
with naist_jdic_path.open(encoding="utf-8") as f:
for line in f:
Expand Down
2 changes: 1 addition & 1 deletion voicevox_engine/cancellable_engine.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ class CancellableEngine:
----------
watch_con_list: list[tuple[Request, Process]]
Requestは接続の監視に使用され、Processは通信切断時のプロセスキルに使用される
クライアントから接続があるとListにTupleが追加される
クライアントから接続があるとlistにtupleが追加される
接続が切断、もしくは音声合成が終了すると削除される
procs_and_cons: queue.Queue[tuple[Process, ConnectionType]]
音声合成の準備が終わっているプロセスのList
Expand Down
20 changes: 9 additions & 11 deletions voicevox_engine/engine_manifest/EngineManifest.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,6 @@
# エラーを吐いて表示が崩壊する可能性がある。これを防止するため、EngineManifest関連の定義を
# 変更する際は、Optionalにする必要があることに留意しなければならない。

from typing import List, Optional

from pydantic import BaseModel, Field


Expand All @@ -14,8 +12,8 @@ class UpdateInfo(BaseModel):
"""

version: str = Field(title="エンジンのバージョン名")
descriptions: List[str] = Field(title="アップデートの詳細についての説明")
contributors: Optional[List[str]] = Field(title="貢献者名")
descriptions: list[str] = Field(title="アップデートの詳細についての説明")
contributors: list[str] | None = Field(title="貢献者名")


class LicenseInfo(BaseModel):
Expand All @@ -24,8 +22,8 @@ class LicenseInfo(BaseModel):
"""

name: str = Field(title="依存ライブラリ名")
version: Optional[str] = Field(title="依存ライブラリのバージョン")
license: Optional[str] = Field(title="依存ライブラリのライセンス名")
version: str | None = Field(title="依存ライブラリのバージョン")
license: str | None = Field(title="依存ライブラリのライセンス名")
text: str = Field(title="依存ライブラリのライセンス本文")


Expand All @@ -44,8 +42,8 @@ class SupportedFeatures(BaseModel):
synthesis_morphing: bool = Field(
title="2種類のスタイルでモーフィングした音声を合成"
)
sing: Optional[bool] = Field(title="歌唱音声合成")
manage_library: Optional[bool] = Field(
sing: bool | None = Field(title="歌唱音声合成")
manage_library: bool | None = Field(
title="音声ライブラリのインストール・アンインストール"
)

Expand All @@ -64,9 +62,9 @@ class EngineManifest(BaseModel):
default_sampling_rate: int = Field(title="デフォルトのサンプリング周波数")
frame_rate: float = Field(title="エンジンのフレームレート")
terms_of_service: str = Field(title="エンジンの利用規約")
update_infos: List[UpdateInfo] = Field(title="エンジンのアップデート情報")
dependency_licenses: List[LicenseInfo] = Field(title="依存関係のライセンス情報")
supported_vvlib_manifest_version: Optional[str] = Field(
update_infos: list[UpdateInfo] = Field(title="エンジンのアップデート情報")
dependency_licenses: list[LicenseInfo] = Field(title="依存関係のライセンス情報")
supported_vvlib_manifest_version: str | None = Field(
title="エンジンが対応するvvlibのバージョン"
)
supported_features: SupportedFeatures = Field(title="エンジンが持つ機能")
2 changes: 1 addition & 1 deletion voicevox_engine/library_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ def installed_libraries(self) -> dict[str, InstalledLibraryInfo]:
インストール済み音声ライブラリの情報を取得
Returns
-------
library : Dict[str, InstalledLibraryInfo]
library : dict[str, InstalledLibraryInfo]
インストール済みライブラリの情報
"""
library: dict[str, InstalledLibraryInfo] = {}
Expand Down
12 changes: 6 additions & 6 deletions voicevox_engine/metas/Metas.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from enum import Enum
from typing import List, Literal, NewType, Optional
from typing import Literal, NewType

from pydantic import BaseModel, Field

Expand All @@ -16,7 +16,7 @@ class SpeakerStyle(BaseModel):

name: str = Field(title="スタイル名")
id: StyleId = Field(title="スタイルID")
type: Optional[StyleType] = Field(
type: StyleType | None = Field(
default="talk",
title=(
"スタイルの種類。"
Expand Down Expand Up @@ -56,7 +56,7 @@ class Speaker(BaseModel):

name: str = Field(title="名前")
speaker_uuid: str = Field(title="話者のUUID")
styles: List[SpeakerStyle] = Field(title="スタイルの一覧")
styles: list[SpeakerStyle] = Field(title="スタイルの一覧")
version: str = Field("話者のバージョン")
supported_features: SpeakerSupportedFeatures = Field(
title="話者の対応機能", default_factory=SpeakerSupportedFeatures
Expand All @@ -70,10 +70,10 @@ class StyleInfo(BaseModel):

id: StyleId = Field(title="スタイルID")
icon: str = Field(title="当該スタイルのアイコンをbase64エンコードしたもの")
portrait: Optional[str] = Field(
portrait: str | None = Field(
title="当該スタイルのportrait.pngをbase64エンコードしたもの"
)
voice_samples: List[str] = Field(
voice_samples: list[str] = Field(
title="voice_sampleのwavファイルをbase64エンコードしたもの"
)

Expand All @@ -85,4 +85,4 @@ class SpeakerInfo(BaseModel):

policy: str = Field(title="policy.md")
portrait: str = Field(title="portrait.pngをbase64エンコードしたもの")
style_infos: List[StyleInfo] = Field(title="スタイルの追加情報")
style_infos: list[StyleInfo] = Field(title="スタイルの追加情報")
20 changes: 10 additions & 10 deletions voicevox_engine/metas/MetasStore.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import json
from copy import deepcopy
from pathlib import Path
from typing import TYPE_CHECKING, Dict, List, Literal, NewType, Tuple
from typing import TYPE_CHECKING, Literal, NewType

from pydantic import BaseModel, Field

Expand Down Expand Up @@ -46,7 +46,7 @@ class _CoreSpeaker(BaseModel):

name: str
speaker_uuid: str
styles: List[_CoreSpeakerStyle]
styles: list[_CoreSpeakerStyle]
version: str = Field("話者のバージョン")


Expand All @@ -73,16 +73,16 @@ def __init__(self, engine_speakers_path: Path) -> None:
エンジンに含まれる話者メタ情報ディレクトリのパス。
"""
# エンジンに含まれる各話者のメタ情報
self._loaded_metas: Dict[str, _EngineSpeaker] = {
self._loaded_metas: dict[str, _EngineSpeaker] = {
folder.name: _EngineSpeaker(
**json.loads((folder / "metas.json").read_text(encoding="utf-8"))
)
for folder in engine_speakers_path.iterdir()
}

# FIXME: engineではなくList[CoreSpeaker]を渡す形にすることで
# FIXME: engineではなくlist[CoreSpeaker]を渡す形にすることで
# TTSEngineによる循環importを修正する
def load_combined_metas(self, core: "CoreAdapter") -> List[Speaker]:
def load_combined_metas(self, core: "CoreAdapter") -> list[Speaker]:
"""
コアに含まれる話者メタ情報とエンジンに含まれる話者メタ情報を統合
Parameters
Expand All @@ -91,7 +91,7 @@ def load_combined_metas(self, core: "CoreAdapter") -> List[Speaker]:
話者メタ情報をもったコア
Returns
-------
ret : List[Speaker]
ret : list[Speaker]
エンジンとコアに含まれる話者メタ情報
"""
# コアに含まれる話者メタ情報の収集
Expand All @@ -112,17 +112,17 @@ def load_combined_metas(self, core: "CoreAdapter") -> List[Speaker]:


def construct_lookup(
speakers: List[Speaker],
) -> Dict[StyleId, Tuple[Speaker, SpeakerStyle]]:
speakers: list[Speaker],
) -> dict[StyleId, tuple[Speaker, SpeakerStyle]]:
"""
スタイルID に話者メタ情報・スタイルメタ情報を紐付ける対応表を生成
Parameters
----------
speakers : List[Speaker]
speakers : list[Speaker]
話者メタ情報
Returns
-------
ret : Dict[StyleId, Tuple[Speaker, SpeakerStyle]]
ret : dict[StyleId, tuple[Speaker, SpeakerStyle]]
スタイルID に話者メタ情報・スタイルメタ情報が紐付いた対応表
"""
lookup_table: dict[StyleId, tuple[Speaker, SpeakerStyle]] = dict()
Expand Down
40 changes: 20 additions & 20 deletions voicevox_engine/model.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from enum import Enum
from re import findall, fullmatch
from typing import Any, Dict, List, Optional
from typing import Any

from pydantic import BaseModel, Field, StrictStr, validator

Expand All @@ -13,8 +13,8 @@ class Mora(BaseModel):
"""

text: str = Field(title="文字")
consonant: Optional[str] = Field(title="子音の音素")
consonant_length: Optional[float] = Field(title="子音の音長")
consonant: str | None = Field(title="子音の音素")
consonant_length: float | None = Field(title="子音の音長")
vowel: str = Field(title="母音の音素")
vowel_length: float = Field(title="母音の音長")
pitch: float = Field(
Expand All @@ -23,7 +23,7 @@ class Mora(BaseModel):

def __hash__(self) -> int:
items = [
(k, tuple(v)) if isinstance(v, List) else (k, v)
(k, tuple(v)) if isinstance(v, list) else (k, v)
for k, v in self.__dict__.items()
]
return hash(tuple(sorted(items)))
Expand All @@ -37,14 +37,14 @@ class AccentPhrase(BaseModel):
アクセント句ごとの情報
"""

moras: List[Mora] = Field(title="モーラのリスト")
moras: list[Mora] = Field(title="モーラのリスト")
accent: int = Field(title="アクセント箇所")
pause_mora: Optional[Mora] = Field(title="後ろに無音を付けるかどうか")
pause_mora: Mora | None = Field(title="後ろに無音を付けるかどうか")
is_interrogative: bool = Field(default=False, title="疑問系かどうか")

def __hash__(self) -> int:
items = [
(k, tuple(v)) if isinstance(v, List) else (k, v)
(k, tuple(v)) if isinstance(v, list) else (k, v)
for k, v in self.__dict__.items()
]
return hash(tuple(sorted(items)))
Expand All @@ -55,7 +55,7 @@ class AudioQuery(BaseModel):
音声合成用のクエリ
"""

accent_phrases: List[AccentPhrase] = Field(title="アクセント句のリスト")
accent_phrases: list[AccentPhrase] = Field(title="アクセント句のリスト")
speedScale: float = Field(title="全体の話速")
pitchScale: float = Field(title="全体の音高")
intonationScale: float = Field(title="全体の抑揚")
Expand All @@ -64,13 +64,13 @@ class AudioQuery(BaseModel):
postPhonemeLength: float = Field(title="音声の後の無音時間")
outputSamplingRate: int = Field(title="音声データの出力サンプリングレート")
outputStereo: bool = Field(title="音声データをステレオ出力するか否か")
kana: Optional[str] = Field(
kana: str | None = Field(
title="[読み取り専用]AquesTalk 風記法によるテキスト。音声合成用のクエリとしては無視される"
)

def __hash__(self) -> int:
items = [
(k, tuple(v)) if isinstance(v, List) else (k, v)
(k, tuple(v)) if isinstance(v, list) else (k, v)
for k, v in self.__dict__.items()
]
return hash(tuple(sorted(items)))
Expand All @@ -91,7 +91,7 @@ class Score(BaseModel):
楽譜情報
"""

notes: List[Note] = Field(title="音符のリスト")
notes: list[Note] = Field(title="音符のリスト")


class FramePhoneme(BaseModel):
Expand All @@ -108,9 +108,9 @@ class FrameAudioQuery(BaseModel):
フレームごとの音声合成用のクエリ
"""

f0: List[float] = Field(title="フレームごとの基本周波数")
volume: List[float] = Field(title="フレームごとの音量")
phonemes: List[FramePhoneme] = Field(title="音素のリスト")
f0: list[float] = Field(title="フレームごとの基本周波数")
volume: list[float] = Field(title="フレームごとの音量")
phonemes: list[FramePhoneme] = Field(title="音素のリスト")
volumeScale: float = Field(title="全体の音量")
outputSamplingRate: int = Field(title="音声データの出力サンプリングレート")
outputStereo: bool = Field(title="音声データをステレオ出力するか否か")
Expand Down Expand Up @@ -147,7 +147,7 @@ class ParseKanaBadRequest(BaseModel):
]
),
)
error_args: Dict[str, str] = Field(title="エラーを起こした箇所")
error_args: dict[str, str] = Field(title="エラーを起こした箇所")

def __init__(self, err: ParseKanaError):
super().__init__(text=err.text, error_name=err.errname, error_args=err.kwargs)
Expand All @@ -156,7 +156,7 @@ def __init__(self, err: ParseKanaError):
class MorphableTargetInfo(BaseModel):
is_morphable: bool = Field(title="指定した話者に対してモーフィングの可否")
# FIXME: add reason property
# reason: Optional[str] = Field(title="is_morphableがfalseである場合、その理由")
# reason: str | None = Field(title="is_morphableがfalseである場合、その理由")


class StyleIdNotFoundError(LookupError):
Expand Down Expand Up @@ -184,7 +184,7 @@ class BaseLibraryInfo(BaseModel):
version: str = Field(title="音声ライブラリのバージョン")
download_url: str = Field(title="音声ライブラリのダウンロードURL")
bytes: int = Field(title="音声ライブラリのバイト数")
speakers: List[LibrarySpeaker] = Field(title="音声ライブラリに含まれる話者のリスト")
speakers: list[LibrarySpeaker] = Field(title="音声ライブラリに含まれる話者のリスト")


# 今後InstalledLibraryInfo同様に拡張する可能性を考え、モデルを分けている
Expand Down Expand Up @@ -228,7 +228,7 @@ class UserDictWord(BaseModel):
yomi: str = Field(title="読み")
pronunciation: str = Field(title="発音")
accent_type: int = Field(title="アクセント型")
mora_count: Optional[int] = Field(title="モーラ数")
mora_count: int | None = Field(title="モーラ数")
accent_associative_rule: str = Field(title="アクセント結合規則")

class Config:
Expand Down Expand Up @@ -310,8 +310,8 @@ class PartOfSpeechDetail(BaseModel):
# context_idは辞書の左・右文脈IDのこと
# https://github.com/VOICEVOX/open_jtalk/blob/427cfd761b78efb6094bea3c5bb8c968f0d711ab/src/mecab-naist-jdic/_left-id.def # noqa
context_id: int = Field(title="文脈ID")
cost_candidates: List[int] = Field(title="コストのパーセンタイル")
accent_associative_rules: List[str] = Field(title="アクセント結合規則の一覧")
cost_candidates: list[int] = Field(title="コストのパーセンタイル")
accent_associative_rules: list[str] = Field(title="アクセント結合規則の一覧")


class WordTypes(str, Enum):
Expand Down
3 changes: 1 addition & 2 deletions voicevox_engine/preset/PresetManager.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
from pathlib import Path
from typing import List

import yaml
from pydantic import ValidationError, parse_obj_as
Expand Down Expand Up @@ -40,7 +39,7 @@ def _refresh_cache(self) -> None:
if obj is None:
raise PresetInternalError("プリセットの設定ファイルが空の内容です")
try:
_presets = parse_obj_as(List[Preset], obj)
_presets = parse_obj_as(list[Preset], obj)
except ValidationError:
raise PresetInternalError("プリセットの設定ファイルにミスがあります")

Expand Down
3 changes: 1 addition & 2 deletions voicevox_engine/setting/Setting.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
from enum import Enum
from typing import Optional

from pydantic import BaseModel, Field

Expand All @@ -19,4 +18,4 @@ class Setting(BaseModel):
"""

cors_policy_mode: CorsPolicyMode = Field(title="リソース共有ポリシー")
allow_origin: Optional[str] = Field(title="許可するオリジン")
allow_origin: str | None = Field(title="許可するオリジン")
Loading

0 comments on commit b91d076

Please sign in to comment.