Skip to content

Commit

Permalink
fic lint errors:
Browse files Browse the repository at this point in the history
- move timestamp helper to "helper/" folder
  • Loading branch information
Totto16 committed Aug 11, 2023
1 parent 34d1309 commit 41bf6da
Show file tree
Hide file tree
Showing 4 changed files with 5 additions and 184 deletions.
184 changes: 2 additions & 182 deletions src/classifier.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
import math
import sys
from dataclasses import dataclass
from datetime import timedelta
from enum import Enum
from functools import reduce
from math import floor
Expand All @@ -14,13 +13,13 @@
import psutil
from enlighten import Manager
from helper.ffprobe import ffprobe
from helper.timestamp import Timestamp
from humanize import naturalsize
from pynvml import nvmlDeviceGetHandleByIndex, nvmlDeviceGetMemoryInfo, nvmlInit
from speechbrain.pretrained import EncoderClassifier
from timestamp import Timestamp # type: ignore[attr-defined]
from torch import cuda

from ffmpeg import FFmpeg, FFmpegError, Progress
from ffmpeg import FFmpeg, FFmpegError, Progress # type: ignore[attr-defined]

filterwarnings("ignore")

Expand All @@ -29,185 +28,6 @@
TEMP_MAX_LENGTH = 1


def parse_int_safely(inp: str) -> Optional[int]:
try:
return int(inp)
except ValueError:
return None


class Timestamp:
__delta: timedelta

def __init__(self: Self, delta: timedelta) -> None:
self.__delta = delta

@property
def delta(self: Self) -> timedelta:
return self.__delta

@property
def minutes(self: Self) -> float:
return self.__delta.total_seconds() / 60.0 + (
self.__delta.microseconds / (60.0 * 10**6)
)

@staticmethod
def zero() -> "Timestamp":
return Timestamp(timedelta(seconds=0))

@staticmethod
def from_minutes(minutes: float) -> "Timestamp":
return Timestamp(timedelta(minutes=minutes))

@staticmethod
def from_seconds(seconds: float) -> "Timestamp":
return Timestamp(timedelta(seconds=seconds))

def __str__(self: Self) -> str:
return str(self.__delta)

def __repr__(self: Self) -> str:
return str(self)

def __format__(self: Self, spec: str) -> str:
"""This is responsible for formatting the Timestamp
Args:
spec (str): a format string, if empty or "d" no microseconds will be printed
otherwise you can provide an int from 1-5 inclusive, to determine how much you wan't to round
the microseconds, you can provide a "n" afterwards, to not have ".00". e.g , it ignores 0's with e.g. "2n"
Examples:
f"{timestamp:2}" => "00:01:00.20"
f"{timestamp:4}" => "00:01:00.2010"
f"{timestamp2:2}" => "00:05:00.00"
f"{timestamp2:4}" => "00:05:00"
"""

delta: timedelta = timedelta(
seconds=int(self.__delta.total_seconds()),
microseconds=0,
)
ms: int = self.__delta.microseconds

if spec in ("", "d"):
return str(delta)

def round_to_tens(value: int, tens: int) -> int:
return int(round(value / (10**tens)))

def emit_error(reason: str) -> Never:
msg = f"Invalid format specifier '{spec}' for object of type 'Timestamp': reason {reason}"
raise ValueError(msg)

ignore_zero: bool = False
if spec.endswith("n"):
ignore_zero = True
spec = spec[:-1]

if ignore_zero and ms == 0:
return str(delta)

val: Optional[int] = parse_int_safely(spec)
if val is None:
msg = f"Couldn't parse int: '{spec}'"
emit_error(msg)

if val > 5 or val <= 0:
msg = f"{val} is out of allowed range 0 < value <= 5"
emit_error(msg)

# val is between 1 and 5 inclusive
ms = round_to_tens(ms, 5 - val)

return "{delta}.{ms:0{val}d}".format( # noqa: PLE1300
delta=str(delta),
ms=ms,
val=val,
)

def __eq__(self: Self, value: object) -> bool:
if isinstance(value, Timestamp):
return self.__delta == value.delta

return False

def __ne__(self: Self, value: object) -> bool:
return not self.__eq__(value)

def __lt__(self: Self, value: object) -> bool:
if isinstance(value, Timestamp):
return self.__delta < value.delta

msg = f"'<' not supported between instances of 'Timestamp' and '{value.__class__.__name__}'"
raise TypeError(msg)

def __le__(self: Self, value: object) -> bool:
if isinstance(value, Timestamp):
return self.__delta <= value.delta

msg = f"'<=' not supported between instances of 'Timestamp' and '{value.__class__.__name__}'"
raise TypeError(msg)

def __gt__(self: Self, value: object) -> bool:
if isinstance(value, Timestamp):
return self.__delta > value.delta

msg = f"'>' not supported between instances of 'Timestamp' and '{value.__class__.__name__}'"
raise TypeError(msg)

def __ge__(self: Self, value: object) -> bool:
if isinstance(value, Timestamp):
return self.__delta >= value.delta

msg = f"'>=' not supported between instances of 'Timestamp' and '{value.__class__.__name__}'"
raise TypeError(msg)

def __iadd__(self: Self, value: object) -> Self:
if isinstance(value, Timestamp):
self.__delta += value.delta
return self
if isinstance(value, timedelta):
self.__delta += value
return self

msg = f"'+=' not supported between instances of 'Timestamp' and '{value.__class__.__name__}'"
raise TypeError(msg)

def __add__(self: Self, value: object) -> "Timestamp":
new_value: Timestamp = Timestamp(self.__delta)
new_value += value
return new_value

def __sub__(self: Self, value: object) -> "Timestamp":
if isinstance(value, Timestamp):
result: timedelta = self.__delta - value.delta
return Timestamp(result)
if isinstance(value, float):
result2: Timestamp = self - Timestamp.from_minutes(value)
return result2

msg = f"'-' not supported between instances of 'Timestamp' and '{value.__class__.__name__}'"
raise TypeError(msg)

def __abs__(self: Self) -> "Timestamp":
return Timestamp(abs(self.__delta))

def __float__(self: Self) -> float:
return self.minutes

def __truediv__(self: Self, value: object) -> float:
if isinstance(value, Timestamp):
return self.__delta / value.delta
if isinstance(value, float):
return self / Timestamp.from_minutes(value)

msg = f"'/' not supported between instances of 'Timestamp' and '{value.__class__.__name__}'"
raise TypeError(msg)


class FileType(Enum):
wav = "wav"
video = "video"
Expand Down
3 changes: 2 additions & 1 deletion src/entry.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,10 @@
from pathlib import Path
from typing import Optional, Self

from classifier import Language, parse_int_safely
from classifier import Language
from content.base_class import Content # noqa: TCH002
from content.general import NameParser, Summary
from helper.timestamp import parse_int_safely
from main import AllContent, generate_json_schema, parse_contents
from typing_extensions import override

Expand Down
File renamed without changes.
2 changes: 1 addition & 1 deletion tests/test_timestamp.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import pytest

from timestamp import parse_int_safely
from helper.timestamp import parse_int_safely


def test_int_parsing() -> None:
Expand Down

0 comments on commit 41bf6da

Please sign in to comment.