Skip to content

Commit

Permalink
Fix various linter issues and switch to ruff
Browse files Browse the repository at this point in the history
commit 641c66f
Author: Alex H. <[email protected]>
Date:   Thu May 9 15:12:59 2024 +0200

    Fix remaining comparison complaints

commit 12132c8
Author: Alex H. <[email protected]>
Date:   Thu May 9 15:10:12 2024 +0200

    Remove ambiguous variable names

commit 0a504a8
Author: Alex H. <[email protected]>
Date:   Thu May 9 15:08:57 2024 +0200

    Remove * imports

commit 4e73e22
Author: Alex H. <[email protected]>
Date:   Thu May 9 15:06:02 2024 +0200

    Remove unused f-strings and imports

commit 449a33c
Author: Alex H. <[email protected]>
Date:   Thu May 9 15:04:52 2024 +0200

    Use ruff and add config to pyproject
  • Loading branch information
Vodes committed May 9, 2024
1 parent 5bc0986 commit 4d98724
Show file tree
Hide file tree
Showing 17 changed files with 67 additions and 51 deletions.
11 changes: 6 additions & 5 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
{
"editor.formatOnSave": true,
"python.formatting.blackArgs": ["--line-length", "150"],
"python.formatting.provider": "black",
"[python]": {
"diffEditor.ignoreTrimWhitespace": false,
"editor.defaultFormatter": "ms-python.black-formatter",
"editor.formatOnType": false,
"editor.formatOnSave": true,
"editor.defaultFormatter": "charliermarsh.ruff"
},
"ruff.lint.enable": true,
"ruff.lint.args": ["--config", "./pyproject.toml"],
"ruff.format.args": ["--config", "./pyproject.toml"]
}
12 changes: 6 additions & 6 deletions muxtools/audio/audioutils.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@
from ..muxing.muxfiles import AudioFile
from ..utils.log import debug, warn, error
from ..utils.download import get_executable
from ..utils.env import get_temp_workdir, run_commandline
from ..utils.types import DitherType, Trim, AudioFormat, ValidInputType, PathLike
from ..utils.env import get_temp_workdir
from ..utils.types import Trim, AudioFormat, ValidInputType, PathLike
from ..utils.subprogress import run_cmd_pb, ProgressBarConfig

__all__ = ["ensure_valid_in", "sanitize_trims", "format_from_track", "is_fancy_codec", "has_libFLAC", "has_libFDK"]
Expand Down Expand Up @@ -126,12 +126,12 @@ def get_pcm(
output = make_output(fileIn.file, "aiff" if valid_type == ValidInputType.AIFF else "w64", "ffmpeg", temp=True)

if supports_pipe and valid_type != ValidInputType.RF64:
debug(f"Piping audio to ensure valid input using ffmpeg...", caller)
debug("Piping audio to ensure valid input using ffmpeg...", caller)
args.extend(["-f", "aiff" if valid_type == ValidInputType.AIFF else "w64", "-"])
p = subprocess.Popen(args, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=False)
return p
else:
debug(f"Preparing audio to ensure valid input using ffmpeg...", caller)
debug("Preparing audio to ensure valid input using ffmpeg...", caller)
args.append(str(output))
if not run_cmd_pb(args, pbc=ProgressBarConfig("Preparing...", duration_from_file(fileIn))):
return AudioFile(output, fileIn.container_delay, fileIn.source)
Expand Down Expand Up @@ -163,10 +163,10 @@ def sanitize_trims(

has_negative = (trim[1] is not None and trim[1] < 0) or (trim[0] is not None and trim[0] < 0)
if not uses_frames and has_negative and index != 0:
raise error(f"If you use milliseconds to trim you cannot use negative values.")
raise error("If you use milliseconds to trim you cannot use negative values.")

if not total_frames and has_negative:
raise error(f"If you want to use negative trims you gotta pass a total frame number.")
raise error("If you want to use negative trims you gotta pass a total frame number.")

if trim[1] is not None and trim[1] < 0:
trim = (trim[0], total_frames + trim[1])
Expand Down
4 changes: 2 additions & 2 deletions muxtools/audio/encoders.py
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,7 @@ def encode_audio(self, fileIn: AudioFile | PathLike, quiet: bool = True, **kwarg
fileIn = AudioFile.from_file(fileIn, self)
output = make_output(fileIn.file, "flac", "ffmpeg", self.output)
if "temp" in kwargs.keys():
debug(f"Preparing audio for input to other encoder using ffmpeg...", self)
debug("Preparing audio for input to other encoder using ffmpeg...", self)
else:
debug(f"Encoding '{fileIn.file.stem}' to FLAC using ffmpeg...", self)
args = self._base_command(fileIn, self.compression_level)
Expand All @@ -155,7 +155,7 @@ def encode_audio(self, fileIn: AudioFile | PathLike, quiet: bool = True, **kwarg
raise crit("Encoding to flac using ffmpeg failed!", self)

def get_pipe(self, fileIn: AudioFile) -> subprocess.Popen:
debug(f"Piping audio for input to other encoder using ffmpeg...", self)
debug("Piping audio for input to other encoder using ffmpeg...", self)
args = self._base_command(fileIn, 0)
args.extend(["-f", "flac", "-"])
p = subprocess.Popen(args, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=False)
Expand Down
8 changes: 4 additions & 4 deletions muxtools/audio/extractors.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@
import re

from .audioutils import format_from_track, is_fancy_codec, sanitize_trims, ensure_valid_in, duration_from_file
from .tools import *
from ..utils.files import *
from .tools import Extractor, Trimmer, AudioFile, HasExtractor, HasTrimmer
from ..utils.files import ensure_path_exists, make_output, clean_temp_files
from ..utils.log import error, warn, debug
from ..utils.download import get_executable
from ..utils.parsing import parse_audioinfo
Expand Down Expand Up @@ -213,7 +213,7 @@ def trim_audio(self, input: AudioFile, quiet: bool = True) -> AudioFile:
args.extend(["-c:a", "flac", "-compression_level", "0"])
extension = "flac"

out = make_output(input.file, extension, f"trimmed", self.output)
out = make_output(input.file, extension, "trimmed", self.output)
ainfo = parse_audioinfo(input.file, caller=self) if not input.info else input.info

if len(self.trim) == 1:
Expand Down Expand Up @@ -314,7 +314,7 @@ def trim_audio(self, input: AudioFile, quiet: bool = True) -> AudioFile:

if not isinstance(input, AudioFile):
input = AudioFile.from_file(input, self)
out = make_output(input.file, "flac", f"trimmed", self.output)
out = make_output(input.file, "flac", "trimmed", self.output)
self.trim = sanitize_trims(self.trim, self.num_frames, not self.trim_use_ms, allow_negative_start=True, caller=self)
source = ensure_valid_in(input, caller=self, supports_pipe=False)

Expand Down
4 changes: 2 additions & 2 deletions muxtools/audio/memecoders.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
from ..utils.files import clean_temp_files, make_output
from ..utils.subprogress import run_cmd_pb, ProgressBarConfig
from .audioutils import ensure_valid_in, qaac_compatcheck, duration_from_file, get_preprocess_args
from ..utils.types import DitherType, LossyWavQuality, PathLike, ValidInputType
from ..utils.types import LossyWavQuality, PathLike, ValidInputType

__all__ = ["qALAC", "TTA", "TrueAudio", "TheTrueAudio", "LossyWav", "Wavpack"]

Expand Down Expand Up @@ -177,7 +177,7 @@ def encode_audio(self, fileIn: AudioFile | PathLike, quiet: bool = True, **kwarg
output = ensure_valid_in(fileIn, False, self.preprocess, valid_type=ValidInputType.W64, caller=self)

args = [get_executable("lossyWAV", False), str(output.file), "--quality", self.quality.name.lower(), "-o", str(get_temp_workdir())]
debug(f"Doing lossywav magic...", self)
debug("Doing lossywav magic...", self)
if run_cmd_pb(args, quiet, ProgressBarConfig("Encoding...")):
raise crit("LossyWAV conversion failed!", self)

Expand Down
6 changes: 3 additions & 3 deletions muxtools/audio/preprocess.py
Original file line number Diff line number Diff line change
Expand Up @@ -184,7 +184,7 @@ def analyze(self, file: AudioFile):
"-i",
str(ensure_path_exists(file.file, self).resolve()),
"-map",
f"0:a:0",
"0:a:0",
"-filter:a",
"loudnorm=print_format=json",
"-f",
Expand All @@ -200,7 +200,7 @@ def analyze(self, file: AudioFile):
thresh_match = re.findall(r"input_thresh.+?(-?\d+(?:\.\d+)?)", output, re.I)
offset_match = re.findall(r"target_offset.+?(-?\d+(?:\.\d+)?)", output, re.I)
if not all([i_match, tp_match, lra_match, thresh_match, offset_match]):
raise error(f"Could not properly measure the input file!", self)
raise error("Could not properly measure the input file!", self)

self.measurements = self.Measurements(
float(i_match[0]),
Expand All @@ -212,7 +212,7 @@ def analyze(self, file: AudioFile):

def get_filter(self, caller: Any = None) -> str | None:
if caller:
debug(f"Applying loudnorm...", caller)
debug("Applying loudnorm...", caller)
if not hasattr(self, "measurements"):
# Ideally shouldn't run into this lmfao
return ""
Expand Down
4 changes: 2 additions & 2 deletions muxtools/misc/chapters.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ def set_names(self: ChaptersSelf, names: list[str | None]) -> ChaptersSelf:
old: list[str] = [chapter[1] for chapter in self.chapters]
if len(names) > len(old):
self.print()
raise error(f"Chapters: too many names!", self)
raise error("Chapters: too many names!", self)
if len(names) < len(old):
names += [None] * (len(old) - len(names))

Expand Down Expand Up @@ -232,7 +232,7 @@ def from_sub(
chapters.append((line.start, ""))

if not chapters:
warn(f"Could not find any chapters in subtitle!", "Chapters")
warn("Could not find any chapters in subtitle!", "Chapters")
ch = Chapters(chapters, fps)
if _print and chapters:
ch.print()
Expand Down
2 changes: 1 addition & 1 deletion muxtools/muxing/tracks.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ def mkvmerge_args(self) -> list[str]:
if self.type == TrackType.ATTACHMENT:
is_font = self.file.suffix.lower() in [".ttf", ".otf"]
if not is_font and not self.lang:
raise ValueError(f"Please specify a mimetype for the attachments if they're not fonts!")
raise ValueError("Please specify a mimetype for the attachments if they're not fonts!")
if not is_font:
args = ["--attachment-mime-type", self.lang]
else:
Expand Down
3 changes: 1 addition & 2 deletions muxtools/subtitle/basesub.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
from collections.abc import Callable
from enum import IntEnum

from ..utils.glob import GlobSearch
from ..utils.log import error, warn
from ..utils.types import PathLike
from ..muxing.muxfiles import MuxingFile
Expand Down Expand Up @@ -70,7 +69,7 @@ def validate_input(self, value: str | int | bool | None, caller: Any = None) ->
if self == 6 and value is not None:
if not isinstance(value, bool) and str(value).lower() not in ["yes", "no"]:
raise error(f"The valid values for {self.name} are 'yes', 'no' or a boolean with the same meaning.", caller)
if str(value).lower() == "no" or value == False:
if str(value).lower() == "no" or value is False:
warn(f"There's practically no good reason for {self.name} to be 'no'. Carry on if you are sure.", caller, 1)
if isinstance(value, bool):
return "yes" if value else "no"
Expand Down
12 changes: 6 additions & 6 deletions muxtools/subtitle/sub.py
Original file line number Diff line number Diff line change
Expand Up @@ -328,12 +328,12 @@ def merge(
# Find syncpoint in current document if sync is a string
for line in doc.events:
events.append(line)
if target == None and isinstance(sync, str):
if target is None and isinstance(sync, str):
field = line.name if use_actor_field else line.effect
if field.lower().strip() == sync.lower().strip() or line.text.lower().strip() == sync.lower().strip():
target = timedelta_to_frame(line.start, fps, exclude_boundary=True) + 1

if target == None and isinstance(sync, str):
if target is None and isinstance(sync, str):
msg = f"Syncpoint '{sync}' was not found."
if no_error:
warn(msg, self)
Expand All @@ -356,15 +356,15 @@ def merge(
sorted_lines = sorted(mergedoc.events, key=lambda event: event.start)

# Assume the first line to be the second syncpoint if none was found
if second_sync == None:
for l in filter(lambda event: event.TYPE != "Comment", sorted_lines):
second_sync = timedelta_to_frame(l.start, fps, exclude_boundary=True) + 1
if second_sync is None:
for line in filter(lambda event: event.TYPE != "Comment", sorted_lines):
second_sync = timedelta_to_frame(line.start, fps, exclude_boundary=True) + 1
break

# Merge lines from file
for line in sorted_lines:
# Don't apply any offset if sync=None for plain merging or if target == source
if target == None or target == second_sync:
if target is None or target == second_sync:
tomerge.append(line)
continue

Expand Down
3 changes: 1 addition & 2 deletions muxtools/utils/convert.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import os
from math import trunc
from decimal import *
from decimal import Decimal, ROUND_HALF_DOWN
from fractions import Fraction
from datetime import timedelta

Expand Down
6 changes: 3 additions & 3 deletions muxtools/utils/download.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from .env import download_allowed
from .types import PathLike
from .log import *
from .log import crit, error, info

import os
import wget
Expand Down Expand Up @@ -59,7 +59,7 @@ def get_executable(type: str, can_download: bool | None = None, can_error: bool
raise error(f"Custom executable for {type} not found!", get_executable)

if path is None:
if not can_download or can_download == False:
if not can_download or can_download is False:
if not can_error:
return None
raise crit(f"{type.lower()} executable not found in path!", get_executable)
Expand Down Expand Up @@ -101,7 +101,7 @@ def download_binary(type: str) -> str:

wget.download(url, str(binary_dir.resolve()))
print("")
info(f"Done.", get_executable)
info("Done.", get_executable)
unpack_all(binary_dir)

executables = binary_dir.rglob(type.lower() + "*.exe")
Expand Down
12 changes: 6 additions & 6 deletions muxtools/utils/files.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
from collections.abc import Callable
from pymediainfo import Track, MediaInfo

from .log import *
from .log import crit, error
from .glob import GlobSearch
from .types import PathLike, TrackType
from .env import get_temp_workdir, get_workdir
Expand Down Expand Up @@ -58,7 +58,7 @@ def ensure_path_exists(pathIn: PathLike | list[PathLike] | GlobSearch, caller: A
if not path.exists():
raise crit(f"Path target '{path}' does not exist.", caller)
if not allow_dir and path.is_dir():
raise crit(f"Path cannot be a directory.", caller)
raise crit("Path cannot be a directory.", caller)
return path


Expand Down Expand Up @@ -185,7 +185,7 @@ def name_matches(title: str) -> bool:

def get_languages(track: MediaInfo) -> list[str]:
languages: list[str] = getattr(track, "other_language", None) or list[str]()
return [l.casefold() for l in languages]
return [lang.casefold() for lang in languages]

if name:
tracks = [track for track in tracks if name_matches(getattr(track, "title", "") or "")]
Expand Down Expand Up @@ -230,21 +230,21 @@ def get_absolute_track(file: PathLike, track: int, type: TrackType, caller: Any
try:
return videos[track]
except:
raise error(f"Your requested track doesn't exist.", caller)
raise error("Your requested track doesn't exist.", caller)
case TrackType.AUDIO:
if not audios:
raise error(f"No audio tracks have been found in '{file.name}'!", caller)
try:
return audios[track]
except:
raise error(f"Your requested track doesn't exist.", caller)
raise error("Your requested track doesn't exist.", caller)
case TrackType.SUB:
if not subtitles:
raise error(f"No subtitle tracks have been found in '{file.name}'!", caller)
try:
return subtitles[track]
except:
raise error(f"Your requested track doesn't exist.", caller)
raise error("Your requested track doesn't exist.", caller)
case _:
raise error("Not implemented for anything other than Video, Audio or Subtitles.", caller)

Expand Down
6 changes: 3 additions & 3 deletions muxtools/utils/format.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,21 +33,21 @@ def get_absolute_track(file: PathLike, track: int, type: TrackType) -> Track:
try:
return videos[track]
except:
raise error(f"Your requested track doesn't exist.", get_absolute_track)
raise error("Your requested track doesn't exist.", get_absolute_track)
case TrackType.AUDIO:
if not audios:
raise error(f"No audio tracks have been found in '{file.name}'!", get_absolute_track)
try:
return audios[track]
except:
raise error(f"Your requested track doesn't exist.", get_absolute_track)
raise error("Your requested track doesn't exist.", get_absolute_track)
case TrackType.SUB:
if not subtitles:
raise error(f"No subtitle tracks have been found in '{file.name}'!", get_absolute_track)
try:
return subtitles[track]
except:
raise error(f"Your requested track doesn't exist.", get_absolute_track)
raise error("Your requested track doesn't exist.", get_absolute_track)
case _:
raise error("Not implemented for anything other than Video, Audio or Subtitles.", get_absolute_track)

Expand Down
6 changes: 3 additions & 3 deletions muxtools/utils/parsing.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ def parse_audioinfo(file: PathLike, track: int = 0, caller: Any = None, is_thd:
caller = parse_audioinfo
debug(f"Parsing frames and stats for '{file.stem}'", caller)
else:
debug(f"Parsing frames and stats...", caller)
debug("Parsing frames and stats...", caller)
out = subprocess.run(args, capture_output=True, text=True, encoding="utf-8", errors="ignore")
frames = []
stats = AudioStats()
Expand Down Expand Up @@ -152,11 +152,11 @@ def parse_chapters_bdmv(
src = ensure_path_exists(src, parse_chapters_bdmv)
stream_dir = src.parent
if stream_dir.name.lower() != "stream":
print(f"Your source file is not in a default bdmv structure!\nWill skip chapters.")
print("Your source file is not in a default bdmv structure!\nWill skip chapters.")
return None
playlist_dir = Path(os.path.join(stream_dir.parent, "PLAYLIST"))
if not playlist_dir.exists():
print(f"PLAYLIST folder couldn't have been found!\nWill skip chapters.")
print("PLAYLIST folder couldn't have been found!\nWill skip chapters.")
return None

chapters: list[Chapter] = []
Expand Down
2 changes: 1 addition & 1 deletion muxtools/utils/types.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from enum import IntEnum, Enum
from enum import IntEnum
from pathlib import Path
from typing import Union, Optional
from datetime import timedelta
Expand Down
17 changes: 17 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -40,3 +40,20 @@ build-backend = "setuptools.build_meta"

[project.scripts]
muxtools = "muxtools:entry_point"

[tool.ruff]
line-length = 150
indent-width = 4
target-version = "py310"

[tool.ruff.lint]
ignore = ["E722"]
fixable = ["F541", "F401", "E712", "E711"]
exclude = ["__init__.py"]

[tool.ruff.format]
quote-style = "double"
indent-style = "space"
skip-magic-trailing-comma = false
line-ending = "auto"
docstring-code-format = false

0 comments on commit 4d98724

Please sign in to comment.