Skip to content

Helper functions

Utility functions and helpers.

bpm_from_frames_per_beat(hr, fps)

Convert frames per beat to beats per minute (60 * fps / hr).

Source code in src\yarppg\helpers.py
def bpm_from_frames_per_beat(hr: ArrayLike, fps: float) -> np.ndarray:
    """Convert frames per beat to beats per minute (60 * fps / hr)."""
    return 60 * fps / np.asarray(hr)

frames_from_video(filename)

Read and yield frames from a video file.

Source code in src\yarppg\helpers.py
def frames_from_video(filename: str | pathlib.Path) -> Iterator[np.ndarray]:
    """Read and yield frames from a video file."""
    cap = cv2.VideoCapture(str(filename))
    while True:
        ret, frame = cap.read()
        if not ret:
            break
        yield frame

get_cached_resource_path(filename, url, reload=False)

Download a file from the web and store it locally.

Source code in src\yarppg\helpers.py
def get_cached_resource_path(filename: str, url: str, reload: bool = False):
    """Download a file from the web and store it locally."""
    RESOURCE_DIR.mkdir(exist_ok=True)
    local_file = RESOURCE_DIR / filename
    if not local_file.exists() or reload:
        urllib.request.urlretrieve(url, filename=str(local_file))
        if not local_file.exists():
            raise FileNotFoundError(
                f"Something went wrong when getting {filename=:!r} from {url=:!r}."
            )
    return local_file

get_video_fps(filename)

Find the frame rate of the given video file.

Source code in src\yarppg\helpers.py
def get_video_fps(filename: str | pathlib.Path) -> float:
    """Find the frame rate of the given video file."""
    if not pathlib.Path(filename).exists():
        raise FileNotFoundError(f"{filename=!r} not found.")
    cap = cv2.VideoCapture(str(filename))
    fps = cap.get(cv2.CAP_PROP_FPS)
    cap.release()
    return fps