Skip to content

Commit

Permalink
solve return-value errors reported by mypy
Browse files Browse the repository at this point in the history
  • Loading branch information
SoulMelody committed Oct 10, 2024
1 parent 99410e8 commit 82dd8f1
Show file tree
Hide file tree
Showing 15 changed files with 62 additions and 64 deletions.
4 changes: 2 additions & 2 deletions libresvip/extension/meta_info.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ def load(cls, plugfile_path: Traversable) -> Optional[PluginInfo_co]:
with plugfile_path.open(encoding="utf-8") as metafile:
cp = RawConfigParser()
cp.read_file(metafile)
return cls(cp)
return cls(cp) # type: ignore[return-value]
except Exception:
logger.error(f"Failed to load plugin info from {plugfile_path}")

Expand All @@ -64,7 +64,7 @@ def load_from_string(cls, content: str) -> Optional[PluginInfo_co]:
with contextlib.suppress(Exception):
cp = RawConfigParser()
cp.read_string(content)
return cls(cp)
return cls(cp) # type: ignore[return-value]

@property
@abc.abstractmethod
Expand Down
2 changes: 1 addition & 1 deletion libresvip/gui/models/list_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ def __init__(self, role_names: RoleNames) -> None:
self._defaults = {x: "" for x in role_names}

@property
def _role_names(self) -> tuple[str]:
def _role_names(self) -> tuple[str, ...]:
return tuple(self._name_2_role.keys())

@property
Expand Down
10 changes: 5 additions & 5 deletions libresvip/gui/modules/vendor/qasync/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -201,7 +201,7 @@ def __init__(self) -> None:
self._stopped = False
self.__debug_enabled = False

def add_callback(self, handle: asyncio.Handle, delay: float = 0) -> asyncio.Handle:
def add_callback(self, handle: asyncio.TimerHandle, delay: float = 0) -> asyncio.TimerHandle:
timerid = self.start_timer(int(max(0, delay) * 1000))
self.__log_debug("Registering timer id {}", timerid)
assert timerid not in self.__callbacks
Expand Down Expand Up @@ -283,7 +283,7 @@ def __init__(
self._write_notifiers: dict[FileDescriptor, QtCore.QSocketNotifier] = {}
self._timer = _SimpleTimer()

self.__call_soon_signaller = signaller = make_signaller(object, tuple)
signaller = make_signaller(object, tuple)
self.__call_soon_signal = signaller.signal
signaller.signal.connect(lambda callback, args: self.call_soon(callback, *args))

Expand Down Expand Up @@ -415,9 +415,9 @@ def call_later(
delay,
)

return self._add_callback(asyncio.Handle(callback, args, self, context=context), delay)
return self._add_callback(asyncio.TimerHandle(delay, callback, args, self, context=context))

def _add_callback(self, handle: asyncio.Handle, delay: float = 0) -> asyncio.Handle:
def _add_callback(self, handle: asyncio.TimerHandle, delay: float = 0) -> asyncio.TimerHandle:
return self._timer.add_callback(handle, delay)

def call_soon(
Expand Down Expand Up @@ -571,7 +571,7 @@ def __on_notifier_ready(

# Methods for interacting with threads.

def call_soon_threadsafe(
def call_soon_threadsafe( # type: ignore[return-value]
self,
callback: Callable[[Unpack[_Ts]], _T],
*args: Unpack[_Ts],
Expand Down
2 changes: 1 addition & 1 deletion libresvip/gui/modules/vendor/qasync/_unix.py
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,7 @@ def close(self) -> None:
self.__write_notifiers.clear()

def get_map(self) -> Mapping[FileDescriptorLike, selectors.SelectorKey]:
return self.__map
return self.__map # type: ignore[return-value]

def _key_from_fd(self, fd: FileDescriptor) -> Optional[selectors.SelectorKey]:
"""
Expand Down
2 changes: 1 addition & 1 deletion libresvip/middlewares/project_zoom/project_zoom.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,4 @@ class ProjectZoomMiddleware(plugin_base.MiddlewareBase):
def process(self, project: Project, options: ProcessOptions) -> Project:
if (zoom_factor := float(fractions.Fraction(options.factor.value))) != 1.0:
return zoom_project(project, zoom_factor)
return
return project
12 changes: 6 additions & 6 deletions libresvip/plugins/acep/ace_studio_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -205,14 +205,14 @@ def parse_params(self, ace_params: AcepParams, ace_note_list: list[AcepNote]) ->
def linear_transform(
lower_bound: float, middle_value: float, upper_bound: float
) -> Callable[[float], int]:
return lambda x: clamp(
round(
return lambda x: round(
clamp(
(x - middle_value) / (upper_bound - middle_value) * 1000
if x >= middle_value
else (x - middle_value) / (middle_value - lower_bound) * 1000
),
-1000,
1000,
else (x - middle_value) / (middle_value - lower_bound) * 1000,
-1000,
1000,
)
)

if self.options.breath_normalization.enabled:
Expand Down
2 changes: 1 addition & 1 deletion libresvip/plugins/acep/options.py
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,7 @@ def _validate_normalization_argument(
) -> NormalizationArgument:
if isinstance(v, str):
v = NormalizationArgument.from_str(v).model_dump()
return v
return NormalizationArgument.model_validate(v)


class OutputOptions(BaseModel):
Expand Down
6 changes: 4 additions & 2 deletions libresvip/plugins/ds/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,12 +64,14 @@ def _validate_glide_list(
mode="before",
)
@classmethod
def _validate_float_list(cls, value: Optional[str], _info: ValidationInfo) -> list[float]:
def _validate_float_list(
cls, value: Optional[str], _info: ValidationInfo
) -> Optional[list[float]]:
return None if value is None else [float(x) for x in value.split()]

@field_validator("is_slur_seq", "note_slur", "ph_num", mode="before")
@classmethod
def _validate_int_list(cls, value: Optional[str], _info: ValidationInfo) -> list[int]:
def _validate_int_list(cls, value: Optional[str], _info: ValidationInfo) -> Optional[list[int]]:
return None if value is None else [int(x) for x in value.split()]

@field_serializer(
Expand Down
2 changes: 1 addition & 1 deletion libresvip/plugins/ds/utils/project_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ def split_into_segments(
) -> Iterable[tuple[float, Project, float]]:
track = next((t for t in project.track_list if isinstance(t, SingingTrack)), None)
if not track or not track.note_list:
return []
return

project = reset_time_axis(project)
buffer = [track.note_list[0]]
Expand Down
65 changes: 30 additions & 35 deletions libresvip/plugins/svip/binsvip_generator.py
Original file line number Diff line number Diff line change
Expand Up @@ -143,8 +143,7 @@ def generate_track(self, track: Track) -> Optional[XSITrack]:

note_list = s_track.note_list.buf.items
for note in track.note_list:
new_note = self.generate_note(note)
if new_note is not None:
if (new_note := self.generate_note(note)) is not None:
note_list.append(new_note)
s_track.note_list.buf.size = len(note_list)
s_track.note_list.buf.version = VALUE_LIST_VERSION_SONG_NOTE
Expand All @@ -171,39 +170,35 @@ def generate_track(self, track: Track) -> Optional[XSITrack]:
s_track.pan = track.pan
return s_track

def generate_note(self, note: Note) -> XSNote:
if note.lyric or note.pronunciation:
xs_note = XSNote(
start_pos=round(self.synchronizer.get_actual_ticks_from_ticks(note.start_pos)),
key_index=note.key_number + 12,
head_tag=XSNoteHeadTag(
value=svip_note_head_tags.get(note.head_tag, XSNoteHeadTagEnum.NoTag)
),
lyric=note.lyric
if CHINESE_RE.match(note.lyric) is not None
else DEFAULT_CHINESE_LYRIC,
pronouncing=note.pronunciation or "",
)
xs_note.width_pos = (
round(self.synchronizer.get_actual_ticks_from_ticks(note.end_pos))
- xs_note.start_pos
)
note_duration = self.synchronizer.get_duration_secs_from_ticks(
note.start_pos, note.end_pos
)
if note_duration < MIN_NOTE_DURATION:
msg_prefix = _("Note duration is too short:")
show_warning(f"{msg_prefix} {note.lyric}")
elif note_duration > MAX_NOTE_DURATION:
msg_prefix = _("Note duration is too long:")
show_warning(f"{msg_prefix} {note.lyric}")
if note.edited_phones is not None:
xs_note.note_phone_info = self.generate_phones(note.edited_phones)
if note.vibrato is not None:
percent, vibrato = self.generate_vibrato(note.vibrato)
xs_note.vibrato_percent_info = percent
xs_note.vibrato = vibrato
return xs_note
def generate_note(self, note: Note) -> Optional[XSNote]:
if not note.lyric and not note.pronunciation:
return None
xs_note = XSNote(
start_pos=round(self.synchronizer.get_actual_ticks_from_ticks(note.start_pos)),
key_index=note.key_number + 12,
head_tag=XSNoteHeadTag(
value=svip_note_head_tags.get(note.head_tag, XSNoteHeadTagEnum.NoTag)
),
lyric=note.lyric if CHINESE_RE.match(note.lyric) is not None else DEFAULT_CHINESE_LYRIC,
pronouncing=note.pronunciation or "",
)
xs_note.width_pos = (
round(self.synchronizer.get_actual_ticks_from_ticks(note.end_pos)) - xs_note.start_pos
)
note_duration = self.synchronizer.get_duration_secs_from_ticks(note.start_pos, note.end_pos)
if note_duration < MIN_NOTE_DURATION:
msg_prefix = _("Note duration is too short:")
show_warning(f"{msg_prefix} {note.lyric}")
elif note_duration > MAX_NOTE_DURATION:
msg_prefix = _("Note duration is too long:")
show_warning(f"{msg_prefix} {note.lyric}")
if note.edited_phones is not None:
xs_note.note_phone_info = self.generate_phones(note.edited_phones)
if note.vibrato is not None:
percent, vibrato = self.generate_vibrato(note.vibrato)
xs_note.vibrato_percent_info = percent
xs_note.vibrato = vibrato
return xs_note

@staticmethod
def generate_phones(edited_phones: Phones) -> XSNotePhoneInfo:
Expand Down
8 changes: 4 additions & 4 deletions libresvip/plugins/tlp/model.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from __future__ import annotations

from itertools import chain
from typing import Annotated, Any, Literal, NamedTuple, Optional, Union
from typing import Annotated, Any, Literal, NamedTuple, Optional, Union, cast

from more_itertools import batched
from pydantic import Field, RootModel, ValidationInfo, field_validator, model_serializer
Expand Down Expand Up @@ -101,14 +101,14 @@ class TuneLabMidiPart(TuneLabBasePart):
@field_validator("pitch", mode="before")
@classmethod
def validate_pitch(
cls, pitch: list[Union[list[float], TuneLabPoints]], _info: ValidationInfo
) -> TuneLabPoints:
cls, pitch: Union[list[list[float]], list[TuneLabPoints]], _info: ValidationInfo
) -> list[TuneLabPoints]:
if _info.mode == "json":
return [
TuneLabPoints(root=[TuneLabPoint._make(each) for each in batched(values, 2)])
for values in pitch
]
return pitch
return cast(list[TuneLabPoints], pitch)


class TuneLabAudioPart(TuneLabBasePart):
Expand Down
2 changes: 1 addition & 1 deletion libresvip/utils/module_loading.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ def __init__(self, zip_file: zipfile.ZipFile, file_path: str) -> None:
self.zip_file = zip_file
self.file_path = file_path

def create_module(self, spec: ModuleSpec) -> ModuleType:
def create_module(self, spec: ModuleSpec) -> Optional[ModuleType]:
return sys.modules.get(spec.name)

def get_filename(self, name: Optional[str] = None) -> str:
Expand Down
5 changes: 3 additions & 2 deletions libresvip/utils/music_math.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ def midi2note(midi: float) -> str:
return f"{pitch}{octave}"


def note2midi(note: str) -> Optional[int]:
def note2midi(note: str) -> int:
pitch_map = {"C": 0, "D": 2, "E": 4, "F": 5, "G": 7, "A": 9, "B": 11}
acc_map = {
"#": 1,
Expand All @@ -37,7 +37,8 @@ def note2midi(note: str) -> Optional[int]:
note,
)
if not match:
return None
msg = f"Invalid note format: {note!r}"
raise ValueError(msg)

pitch = match["note"].upper()
offset = sum(acc_map[o] for o in match["accidental"])
Expand Down
2 changes: 1 addition & 1 deletion libresvip/web/pages.py
Original file line number Diff line number Diff line change
Expand Up @@ -936,7 +936,7 @@ def export_one(self, request: Request) -> Response:

def _export_one(self, filename: str) -> Optional[tuple[bytes, int, dict[str, str], str]]:
if not (task := self.files_to_convert.get(filename)) or not task.success:
return
return None
if self._conversion_mode == ConversionMode.SPLIT:
buffer = io.BytesIO()
with zipfile.ZipFile(buffer, "w") as zip_file:
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -187,7 +187,7 @@ ignore = [
known-first-party = ['libresvip', 'tests']

[tool.mypy]
disable_error_code = "import-not-found,operator,return-value,unused-ignore"
disable_error_code = "import-not-found,operator,unused-ignore"
allow_redefinition = true
warn_redundant_casts = true
warn_unused_ignores = true
Expand Down

0 comments on commit 82dd8f1

Please sign in to comment.