Skip to content

Commit

Permalink
[project] Enable more lint rules.
Browse files Browse the repository at this point in the history
  • Loading branch information
Breakthrough committed Jul 8, 2024
1 parent 4378874 commit 081b3f6
Show file tree
Hide file tree
Showing 20 changed files with 37 additions and 88 deletions.
14 changes: 7 additions & 7 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -27,26 +27,26 @@ docstring-code-format = true

[tool.ruff.lint]
select = [
# flake8-bugbear
"B",
# pycodestyle
"E",
# Pyflakes
"F",
# TODO - Rule sets to enable:
# isort
"I",
# TODO - Add additional rule sets (https://docs.astral.sh/ruff/rules/):
# pyupgrade
#"UP",
# flake8-bugbear
#"B",
# flake8-simplify
#"SIM",
# isort
#"I",
]
ignore = [
# TODO: Determine if we should use __all__, a reudndant alias, or keep this suppressed.
"F401",
# Line too long
# TODO: Line too long
"E501",
# Do not assign a `lambda` expression, use a `def`
# TODO: Do not assign a `lambda` expression, use a `def`
"E731",
]
fixable = ["ALL"]
Expand Down
7 changes: 2 additions & 5 deletions scenedetect/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@
can be used to open a video for a
:class:`SceneManager <scenedetect.scene_manager.SceneManager>`.
"""
# ruff: noqa: I001

from logging import getLogger
from typing import List, Optional, Tuple, Union
Expand All @@ -31,7 +30,7 @@
) from ex

# Commonly used classes/functions exported under the `scenedetect` namespace for brevity.
from scenedetect.platform import init_logger
from scenedetect.platform import init_logger # noqa: I001
from scenedetect.frame_timecode import FrameTimecode
from scenedetect.video_stream import VideoStream, VideoOpenFailure
from scenedetect.video_splitter import split_video_ffmpeg, split_video_mkvmerge
Expand All @@ -52,9 +51,7 @@
)
from scenedetect.stats_manager import StatsManager, StatsFileCorrupt
from scenedetect.scene_manager import SceneManager, save_images

# [DEPRECATED] DO NOT USE.
from scenedetect.video_manager import VideoManager
from scenedetect.video_manager import VideoManager # [DEPRECATED] DO NOT USE.

# Used for module identification and when printing version & about info
# (e.g. calling `scenedetect version` or `scenedetect about`).
Expand Down
2 changes: 1 addition & 1 deletion scenedetect/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ def main():
raise
else:
logger.critical("Unhandled exception:", exc_info=ex)
raise SystemExit(1)
raise SystemExit(1) from None


if __name__ == "__main__":
Expand Down
5 changes: 0 additions & 5 deletions scenedetect/_cli/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@
"""

# Some parts of this file need word wrap to be displayed.
# pylint: disable=line-too-long

import inspect
import logging
Expand Down Expand Up @@ -263,7 +262,6 @@ def _print_command_help(ctx: click.Context, command: click.Command):
help="Suppress output to terminal/stdout. Equivalent to setting --verbosity=none.",
)
@click.pass_context
# pylint: disable=redefined-builtin
def scenedetect(
ctx: click.Context,
input: ty.Optional[ty.AnyStr],
Expand Down Expand Up @@ -327,9 +325,6 @@ def scenedetect(
)


# pylint: enable=redefined-builtin


@click.command("help", cls=_Command)
@click.argument(
"command_name",
Expand Down
6 changes: 3 additions & 3 deletions scenedetect/_cli/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -234,7 +234,7 @@ def format(self, timecode: FrameTimecode) -> str:
return timecode.get_timecode()
if self == TimecodeFormat.SECONDS:
return "%.3f" % timecode.get_seconds()
assert False
raise RuntimeError("Unhandled format specifier.")


ConfigValue = Union[bool, int, float, str]
Expand Down Expand Up @@ -558,9 +558,9 @@ def _load_from_disk(self, path=None):
config_file_contents = config_file.read()
config.read_string(config_file_contents, source=path)
except ParsingError as ex:
raise ConfigLoadFailure(self._init_log, reason=ex)
raise ConfigLoadFailure(self._init_log, reason=ex) from None
except OSError as ex:
raise ConfigLoadFailure(self._init_log, reason=ex)
raise ConfigLoadFailure(self._init_log, reason=ex) from None
# At this point the config file syntax is correct, but we need to still validate
# the parsed options (i.e. that the options have valid values).
errors = _validate_structure(config)
Expand Down
11 changes: 6 additions & 5 deletions scenedetect/_cli/context.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,6 @@ def check_split_video_requirements(use_mkvmerge: bool) -> None:
raise click.BadParameter(error_str, param_hint="split-video")


# pylint: disable=too-many-instance-attributes,too-many-arguments,too-many-locals
class CliContext:
"""Context of the command-line interface and config file parameters passed between sub-commands.
Expand Down Expand Up @@ -324,7 +323,7 @@ def handle_options(
scene_manager.downscale = downscale
except ValueError as ex:
logger.debug(str(ex))
raise click.BadParameter(str(ex), param_hint="downscale factor")
raise click.BadParameter(str(ex), param_hint="downscale factor") from None
scene_manager.interpolation = Interpolation[
self.config.get_value("global", "downscale-method").upper()
]
Expand Down Expand Up @@ -357,7 +356,7 @@ def get_detect_content_params(
weights = ContentDetector.Components(*weights)
except ValueError as ex:
logger.debug(str(ex))
raise click.BadParameter(str(ex), param_hint="weights")
raise click.BadParameter(str(ex), param_hint="weights") from None

return {
"weights": self.config.get_value("detect-content", "weights", weights),
Expand Down Expand Up @@ -415,7 +414,7 @@ def get_detect_adaptive_params(
weights = ContentDetector.Components(*weights)
except ValueError as ex:
logger.debug(str(ex))
raise click.BadParameter(str(ex), param_hint="weights")
raise click.BadParameter(str(ex), param_hint="weights") from None
return {
"adaptive_threshold": self.config.get_value("detect-adaptive", "threshold", threshold),
"weights": self.config.get_value("detect-adaptive", "weights", weights),
Expand Down Expand Up @@ -903,7 +902,9 @@ def _open_video_stream(
param_hint="-i/--input",
) from ex
except OSError as ex:
raise click.BadParameter("Input error:\n\n\t%s\n" % str(ex), param_hint="-i/--input")
raise click.BadParameter(
"Input error:\n\n\t%s\n" % str(ex), param_hint="-i/--input"
) from None

def _on_duplicate_command(self, command: str) -> None:
"""Called when a command is duplicated to stop parsing and raise an error.
Expand Down
1 change: 0 additions & 1 deletion scenedetect/backends/pyav.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@
from logging import getLogger
from typing import AnyStr, BinaryIO, Optional, Tuple, Union

# pylint: disable=c-extension-no-member
import av
import numpy as np

Expand Down
4 changes: 1 addition & 3 deletions scenedetect/detectors/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,7 @@
processing videos, however they can also be used to process frames directly.
"""

# ruff: noqa: I001

from scenedetect.detectors.content_detector import ContentDetector
from scenedetect.detectors.content_detector import ContentDetector # noqa: I001
from scenedetect.detectors.threshold_detector import ThresholdDetector
from scenedetect.detectors.adaptive_detector import AdaptiveDetector
from scenedetect.detectors.hash_detector import HashDetector
Expand Down
12 changes: 0 additions & 12 deletions scenedetect/platform.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,6 @@
class FakeTqdmObject:
"""Provides a no-op tqdm-like object."""

# pylint: disable=unused-argument
def __init__(self, **kawrgs):
"""No-op."""

Expand All @@ -49,13 +48,10 @@ def close(self):
def set_description(self, desc=None, refresh=True):
"""No-op."""

# pylint: enable=unused-argument


class FakeTqdmLoggingRedirect:
"""Provides a no-op tqdm context manager for redirecting log messages."""

# pylint: disable=redefined-builtin,unused-argument
def __init__(self, **kawrgs):
"""No-op."""

Expand All @@ -65,20 +61,14 @@ def __enter__(self):
def __exit__(self, type, value, traceback):
"""No-op."""

# pylint: enable=redefined-builtin,unused-argument


# Try to import tqdm and the logging redirect, otherwise provide fake implementations..
try:
# pylint: disable=unused-import
from tqdm import tqdm
from tqdm.contrib.logging import logging_redirect_tqdm
# pylint: enable=unused-import
except ModuleNotFoundError:
# pylint: disable=invalid-name
tqdm = FakeTqdmObject
logging_redirect_tqdm = FakeTqdmLoggingRedirect
# pylint: enable=invalid-name

##
## OpenCV imwrite Supported Image Types & Quality/Compression Parameters
Expand Down Expand Up @@ -254,10 +244,8 @@ def get_ffmpeg_path() -> Optional[str]:

# Try invoking ffmpeg using the one from `imageio_ffmpeg` if available.
try:
# pylint: disable=import-outside-toplevel
from imageio_ffmpeg import get_ffmpeg_exe

# pylint: enable=import-outside-toplevel
subprocess.call([get_ffmpeg_exe(), "-v", "quiet"])
return get_ffmpeg_exe()
# Gracefully handle case where imageio_ffmpeg is not available.
Expand Down
3 changes: 1 addition & 2 deletions scenedetect/scene_detector.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,6 @@
from scenedetect.stats_manager import StatsManager


# pylint: disable=unused-argument, no-self-use
class SceneDetector:
"""Base class to inherit from when implementing a scene detection algorithm.
Expand Down Expand Up @@ -184,7 +183,7 @@ def filter(self, frame_num: int, above_threshold: bool) -> ty.List[int]:
return self._filter_merge(frame_num=frame_num, above_threshold=above_threshold)
elif self._mode == FlashFilter.Mode.SUPPRESS:
return self._filter_suppress(frame_num=frame_num, above_threshold=above_threshold)
assert False, "unhandled FlashFilter Mode!"
raise RuntimeError("Unhandled FlashFilter mode.")

def _filter_suppress(self, frame_num: int, above_threshold: bool) -> ty.List[int]:
min_length_met: bool = (frame_num - self._last_above) >= self._filter_length
Expand Down
6 changes: 0 additions & 6 deletions scenedetect/scene_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -1060,14 +1060,10 @@ def _decode_thread(
# Make sure main thread stops processing loop.
out_queue.put((None, None))

# pylint: enable=bare-except

#
# Deprecated Methods
#

# pylint: disable=unused-argument

def get_cut_list(
self, base_timecode: Optional[FrameTimecode] = None, show_warning: bool = True
) -> List[FrameTimecode]:
Expand Down Expand Up @@ -1117,8 +1113,6 @@ def get_event_list(
logger.error("`get_event_list()` is deprecated and will be removed in a future release.")
return self._get_event_list()

# pylint: enable=unused-argument

def _is_processing_required(self, frame_num: int) -> bool:
"""True if frame metrics not in StatsManager, False otherwise."""
if self.stats_manager is None:
Expand Down
7 changes: 3 additions & 4 deletions scenedetect/video_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -287,7 +287,7 @@ def __init__(
self,
video_files: List[str],
framerate: Optional[float] = None,
logger=getLogger("pyscenedetect"),
logger=None,
):
"""[DEPRECATED] DO NOT USE.
Expand All @@ -310,6 +310,8 @@ def __init__(
"""
# TODO(v0.7): Add DeprecationWarning that this class will be removed in v0.8: 'VideoManager
# will be removed in PySceneDetect v0.8. Use VideoStreamCv2 or VideoCaptureAdapter instead.'
if logger is None:
logger = getLogger("pyscenedetect")
logger.error("VideoManager is deprecated and will be removed.")
if not video_files:
raise ValueError("At least one string/integer must be passed in the video_files list.")
Expand Down Expand Up @@ -535,7 +537,6 @@ def start(self) -> None:
# This overrides the seek method from the VideoStream interface, but the name was changed
# from `timecode` to `target`. For compatibility, we allow calling seek with the form
# seek(0), seek(timecode=0), and seek(target=0). Specifying both arguments is an error.
# pylint: disable=arguments-differ
def seek(self, timecode: FrameTimecode = None, target: FrameTimecode = None) -> bool:
"""Seek forwards to the passed timecode.
Expand Down Expand Up @@ -589,8 +590,6 @@ def seek(self, timecode: FrameTimecode = None, target: FrameTimecode = None) ->
return False
return True

# pylint: enable=arguments-differ

def release(self) -> None:
"""Release (cv2.VideoCapture method), releases all open capture(s)."""
for cap in self._cap_list:
Expand Down
3 changes: 0 additions & 3 deletions scenedetect/video_stream.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,16 +53,13 @@ class SeekError(Exception):
class VideoOpenFailure(Exception):
"""Raised by a backend if opening a video fails."""

# pylint: disable=useless-super-delegation
def __init__(self, message: str = "Unknown backend error."):
"""
Arguments:
message: Additional context the backend can provide for the open failure.
"""
super().__init__(message)

# pylint: enable=useless-super-delegation


class FrameRateUnavailable(VideoOpenFailure):
"""Exception instance to provide consistent error messaging across backends when the video frame
Expand Down
2 changes: 0 additions & 2 deletions tests/test_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,6 @@
when calling `detect()` or `detect_scenes()`.
"""

# pylint: disable=import-outside-toplevel, redefined-outer-name, unused-argument


def test_api_detect(test_video_file: str):
"""Demonstrate usage of the `detect()` function to process a complete video."""
Expand Down
Loading

0 comments on commit 081b3f6

Please sign in to comment.