Utils¶
Auto-generated documentation for musicalgestures._utils module.
- Mgt-python / Modules / Musicalgestures / Utils
- FFmpegError
- FFprobeError
- FilesNotMatchError
- MgFigure
- MgImage
- MgProgressbar
- NoDurationError
- NoStreamError
- WrongContainer
- audio_dilate
- cast_into_avi
- clamp
- convert
- convert_to_avi
- convert_to_grayscale
- convert_to_mp4
- convert_to_webm
- crop_ffmpeg
- cuda_build_available
- cuda_unavailable_reason
- embed_audio_in_video
- extract_frame
- extract_subclip
- extract_wav
- ffmpeg_cmd
- ffmpeg_has_encoder
- ffprobe
- frame2ms
- framediff_ffmpeg
- generate_outfilename
- get_box_video_ratio
- get_cuda_device_count
- get_first_frame_as_image
- get_fps
- get_frame_planecount
- get_framecount
- get_length
- get_rotation
- get_widthheight
- has_audio
- in_colab
- in_ipynb
- merge_videos
- motiongrams_ffmpeg
- motionvideo_ffmpeg
- normalize_rotation
- pass_if_container_is
- pass_if_containers_match
- quality_metrics
- resolve_filename
- rotate_video
- roundup
- scale_array
- scale_num
- show_progress
- str2sec
- threshold_ffmpeg
- unwrap_str
- wrap_str
FFmpegError¶
FFprobeError¶
FilesNotMatchError¶
MgFigure¶
class MgFigure():
def __init__(
figure=None,
figure_type: str = None,
data: dict = None,
layers: list = None,
image=None,
):
Class for working with figures and plots within the Musical Gestures Toolbox.
MgFigure().save¶
Save the rendered figure to target_name.
Copies the rendered PNG if one exists, otherwise re-saves the internal matplotlib figure. Returns an MgImage pointing to the saved file (or None if nothing to save).
MgFigure().show¶
Display the rendered figure.
In a Jupyter notebook the saved image is shown inline; otherwise it is opened in a viewer window. Additional keyword arguments are forwarded to the underlying MgImage.show(). If no rendered image is available, the internal matplotlib figure is returned instead.
MgFigure().to_html¶
Return an HTML snippet embedding the rendered figure (base64-encoded).
NB: This is intentionally not exposed as _repr_html_, so an MgFigure
is not auto-rendered as the last expression of a Jupyter cell. Use show()
to display the figure.
MgImage¶
Class for handling images in the Musical Gestures Toolbox.
MgImage().save¶
Save (copy) the image to target_name and return a new MgImage pointing to it.
MgImage().to_html¶
Return an HTML snippet embedding the image (base64-encoded).
NB: This is intentionally not exposed as _repr_html_, so an MgImage
is not auto-rendered as the last expression of a Jupyter cell. Use show()
to display the image.
MgProgressbar¶
class MgProgressbar():
def __init__(
total: int = 100,
time_limit: float = 0.5,
prefix: str = 'Progress',
suffix: str = 'Complete',
decimals: int = 1,
length: int = 40,
fill: str = '█',
):
Calls in a loop to create terminal progress bar.
MgProgressbar().adjust_printlength¶
MgProgressbar().get_now¶
Gets the current time.
Returns¶
datetime.datetime.timestamp- The current time.
MgProgressbar().over_time_limit¶
Checks if we should redraw the progress bar at this moment.
Returns¶
bool- True if equal or more time has passed thanself.time_limitsince the last redraw.
MgProgressbar().progress¶
Progresses the progress bar to the next step.
Arguments¶
iterationfloat - The current iteration. For example, the 57th out of 100 steps, or 12.3s out of the total 60s.
NoDurationError¶
See also¶
NoStreamError¶
See also¶
WrongContainer¶
audio_dilate¶
def audio_dilate(
filename: str,
dilation_ratio: float = 1,
target_name: str | None = None,
overwrite: bool = True,
) -> str:
Time-stretches or -shrinks (dilates) an audio file using ffmpeg.
Arguments¶
filenamestr - Path to the audio file to dilate.dilation_ratiofloat, optional - The source file's length divided by the resulting file's length. Defaults to 1.target_namestr, optional - The name of the output video. Defaults to None (which assumes that the input filename with the suffix "_dilated" should be used).overwritebool, optional - Whether to allow overwriting existing files or to automatically increment target filename to avoid overwriting. Defaults to True.
Returns¶
str- The path to the output audio file.
cast_into_avi¶
Experimental Casts a video into and .avi container using ffmpeg. Much faster than convert_to_avi, but does not always work well with cv2 or built-in video players.
Arguments¶
filenamestr - Path to the input video file.target_namestr, optional - Target filename as path. Defaults to None (which assumes that the input filename should be used).overwritebool, optional - Whether to allow overwriting existing files or to automatically increment target filename to avoid overwriting. Defaults to True.
Returns¶
str- The path to the output '.avi' file.
clamp¶
Clamps a number between a minimum and maximum value.
Arguments¶
numfloat - The number to clamp.min_valuefloat - The minimum allowed value.max_valuefloat - The maximum allowed value.
Returns¶
float- The clamped number.
convert¶
Converts a video to another format/container using ffmpeg.
Arguments¶
filenamestr - Path to the input video file to convert.target_namestr - Target filename as path.overwritebool, optional - Whether to allow overwriting existing files or to automatically increment target filename to avoid overwriting. Defaults to True.
Returns¶
str- The path to the output file.
convert_to_avi¶
def convert_to_avi(
filename: str,
target_name: str | None = None,
overwrite: bool = True,
) -> str:
Converts a video to one with .avi extension using ffmpeg.
Arguments¶
filenamestr - Path to the input video file to convert.target_namestr, optional - Target filename as path. Defaults to None (which assumes that the input filename should be used).overwritebool, optional - Whether to allow overwriting existing files or to automatically increment target filename to avoid overwriting. Defaults to True.
Returns¶
str- The path to the output '.avi' file.
convert_to_grayscale¶
def convert_to_grayscale(
filename: str,
target_name: str | None = None,
overwrite: bool = True,
) -> str:
Converts a video to grayscale using ffmpeg.
Arguments¶
filenamestr - Path to the input video file.target_namestr, optional - Target filename as path. Defaults to None (which assumes that the input filename with the suffix "_gray" should be used).overwritebool, optional - Whether to allow overwriting existing files or to automatically increment target filename to avoid overwriting. Defaults to True.
Returns¶
str- The path to the grayscale video file.
convert_to_mp4¶
def convert_to_mp4(
filename: str,
target_name: str | None = None,
overwrite: bool = True,
) -> str:
Converts a video to one with .mp4 extension using ffmpeg.
Arguments¶
filenamestr - Path to the input video file to convert.target_namestr, optional - Target filename as path. Defaults to None (which assumes that the input filename should be used).overwritebool, optional - Whether to allow overwriting existing files or to automatically increment target filename to avoid overwriting. Defaults to True.
Returns¶
str- The path to the output '.mp4' file.
convert_to_webm¶
def convert_to_webm(
filename: str,
target_name: str | None = None,
overwrite: bool = True,
) -> str:
Converts a video to one with .webm extension using ffmpeg.
Arguments¶
filenamestr - Path to the input video file to convert.target_namestr, optional - Target filename as path. Defaults to None (which assumes that the input filename should be used).overwritebool, optional - Whether to allow overwriting existing files or to automatically increment target filename to avoid overwriting. Defaults to True.
Returns¶
str- The path to the output '.webm' file.
crop_ffmpeg¶
def crop_ffmpeg(
filename: str,
w: int,
h: int,
x: int,
y: int,
target_name: str | None = None,
overwrite: bool = True,
) -> str:
Crops a video using ffmpeg.
Arguments¶
filenamestr - Path to the input video file.wint - The desired width.hint - The desired height.xint - The horizontal coordinate of the top left pixel of the cropping rectangle.yint - The vertical coordinate of the top left pixel of the cropping rectangle.target_namestr, optional - The name of the output video. Defaults to None (which assumes that the input filename with the suffix "_crop" should be used).overwritebool, optional - Whether to allow overwriting existing files or to automatically increment target filenames to avoid overwriting. Defaults to True.
Returns¶
str- Path to the output video.
cuda_build_available¶
Returns whether the installed OpenCV was compiled with CUDA support.
Returns¶
bool- True if OpenCV's build information reports CUDA support, else False.
cuda_unavailable_reason¶
Returns a short, actionable explanation of why the OpenCV CUDA backend is unavailable.
Distinguishes the common case (the pip OpenCV wheels are built without CUDA) from the case where OpenCV has CUDA but no GPU/driver is detected.
Returns¶
str- A human-readable explanation.
embed_audio_in_video¶
def embed_audio_in_video(
source_audio: str,
destination_video: str,
dilation_ratio: float = 1,
) -> None:
Embeds an audio file as the audio channel of a video file using ffmpeg.
Arguments¶
source_audiostr - Path to the audio file to embed.destination_videostr - Path to the video file to embed the audio file in.dilation_ratiofloat, optional - The source file's length divided by the resulting file's length. Defaults to 1.
extract_frame¶
def extract_frame(
filename: str,
frame: int = None,
time: Union[str, float] = None,
target_name: str = None,
overwrite: bool = False,
) -> str:
Extracts a single frame from a video using ffmpeg.
Arguments¶
filenamestr - Path to the input video file.frameint - The frame number to extract. time (Union[str, float]): The time in HH:MM:ss.ms where to extract the frame from. If float, it is interpreted as seconds from the start of the video.target_namestr, optional - The name for the output file. If None, the name will be FRAME.. Defaults to None. overwritebool, optional - Whether to allow overwriting existing files or to automatically increment target filename to avoid overwriting. Defaults to True.
extract_subclip¶
def extract_subclip(
filename: str,
t1: float,
t2: float,
target_name: str | None = None,
overwrite: bool = True,
) -> str:
Extracts a section of the video using ffmpeg.
Arguments¶
filenamestr - Path to the input video file.t1float - The start of the section to extract in seconds.t2float - The end of the section to extract in seconds.target_namestr, optional - The name for the output file. If None, the name will be SUB_ . . Defaults to None. overwritebool, optional - Whether to allow overwriting existing files or to automatically increment target filename to avoid overwriting. Defaults to True.
Returns¶
str- Path to the extracted section as a video.
extract_wav¶
Extracts audio from video into a .wav file via ffmpeg.
Arguments¶
filenamestr - Path to the video file from which the audio track shall be extracted.target_namestr, optional - The name of the output video. Defaults to None (which assumes that the input filename should be used).overwritebool, optional - Whether to allow overwriting existing files or to automatically increment target filename to avoid overwriting. Defaults to True.
Returns¶
str- The path to the output audio file.
ffmpeg_cmd¶
def ffmpeg_cmd(
command: list,
total_time: float,
pb_prefix: str = 'Progress',
print_cmd: bool = False,
stream: bool = True,
pipe: str | None = None,
):
Run an ffmpeg command in a subprocess and show progress using an MgProgressbar.
Arguments¶
commandlist - The ffmpeg command to execute as a list. Eg. ['ffmpeg', '-y', '-i', 'myVid.mp4', 'myVid.mov']total_timefloat - The length of the output. Needed mainly for the progress bar.pb_prefixstr, optional - The prefix for the progress bar. Defaults to 'Progress'.print_cmdbool, optional - Whether to print the full ffmpeg command to the console before executing it. Good for debugging. Defaults to False.streambool, optional - Whether to have a continuous output stream or just (the last) one. Defaults to True (continuous stream).pipestr, optional - Whether to pipe video frames from FFmpeg to numpy array. Possible to read the video frame by frame with pipe='read', to load video in memory with pipe='load', or to write the frames of a numpy array to a video file with pipe='write'. Defaults to None.
Raises¶
KeyboardInterrupt- If the user stops the process.FFmpegError- If the ffmpeg process was unsuccessful.
ffmpeg_has_encoder¶
Returns True if the installed FFmpeg has the named encoder (e.g. 'libtheora').
Useful for guarding format conversions whose codec may be missing from a given FFmpeg build (notably libtheora/libvorbis for .ogg on some macOS/Windows builds).
ffprobe¶
Returns info about video/audio file using FFprobe.
The result is cached per file (keyed by path + modification time + size), so repeated probes of an unchanged file don't spawn a new subprocess each time.
Arguments¶
filenamestr - Path to the video file to measure.
Returns¶
str- decoded FFprobe output (stdout) as one string.
frame2ms¶
Converts frames to milliseconds.
Arguments¶
frameint - The index of the frame to be converted to milliseconds.fpsint - Frames per second.
Returns¶
int- The rounded millisecond value of the input frame index.
framediff_ffmpeg¶
def framediff_ffmpeg(
filename: str,
target_name: str | None = None,
color: bool = True,
overwrite: bool = True,
) -> str:
Renders a frame difference video from the input using ffmpeg.
Arguments¶
filenamestr - Path to the input video file.target_namestr, optional - The name of the output video. Defaults to None (which assumes that the input filename with the suffix "_framediff" should be used).colorbool, optional - If False, the output will be grayscale. Defaults to True.overwritebool, optional - Whether to allow overwriting existing files or to automatically increment target filename to avoid overwriting. Defaults to True.
Returns¶
str- Path to the output video.
generate_outfilename¶
Returns a unique filepath to avoid overwriting existing files. Increments requested filename if necessary by appending an integer, like "_0" or "_1", etc to the file name.
Arguments¶
requested_namestr - Requested file name as path string.
Returns¶
str- If file at requested_name is not present, then requested_name, else an incremented filename.
get_box_video_ratio¶
Gets the box-to-video ratio between an arbitrarily defind box and the video dimensions. Useful to fit windows into a certain area.
Arguments¶
filenamestr - Path to the input video file.box_widthint, optional - The width of the box to fit the video into.box_heightint, optional - The height of the box to fit the video into.
Returns¶
int- The smallest ratio (ie. the one to use for scaling the video window to fit into the box).
get_cuda_device_count¶
Returns the number of CUDA-capable GPU devices visible to OpenCV.
Returns¶
int- Number of available CUDA devices, or 0 if the OpenCV CUDA module is unavailable or no devices are detected.
get_first_frame_as_image¶
def get_first_frame_as_image(
filename: str,
target_name: str | None = None,
pict_format: str = '.png',
overwrite: bool = True,
) -> str:
Extracts the first frame of a video and saves it as an image using ffmpeg.
Arguments¶
filenamestr - Path to the input video file.target_namestr, optional - The name for the output image. Defaults to None (which assumes that the input filename should be used).pict_formatstr, optional - The format to use for the output image. Defaults to '.png'.overwritebool, optional - Whether to allow overwriting existing files or to automatically increment target filename to avoid overwriting. Defaults to True.
Returns¶
str- Path to the output image file.
get_fps¶
Gets the FPS (frames per second) value of a video using FFprobe.
Arguments¶
filenamestr - Path to the video file to measure.
Returns¶
float- The FPS value of the input video file.
get_frame_planecount¶
Gets the planecount (color channel count) of a video frame.
Arguments¶
frame (numpy array): A frame extracted by cv2.VideoCapture().read().
Returns¶
int- The planecount of the input frame, 3 or 1.
get_framecount¶
Returns the number of frames in a video using FFprobe.
Arguments¶
filenamestr - Path to the video file to measure.fastbool, optional - If True (default), count demuxed video packets (-count_packets). This is fast (no decoding) and — unlike the container'snb_framesmetadata, which is unreliable (e.g. off by one on many AVIs, or absent on WebM) — matches the true decoded frame count for normal video streams. If False, fully decode and count frames (-count_frames): the ground truth, but slower. Defaults to True.
Returns¶
int- The number of frames in the input video file.
get_length¶
Gets the length (in seconds) of a video using FFprobe.
Arguments¶
filenamestr - Path to the video file to measure.
Returns¶
float- The length of the input video file in seconds.
get_rotation¶
Returns the display rotation (degrees) stored in a video's metadata.
Phone/portrait videos often store landscape pixels plus a rotation flag (display matrix). FFmpeg's frame pipe applies this automatically while OpenCV's VideoCapture does not, which can leave some processes rotated. This reads the flag so the orientation can be normalised.
Returns¶
int- rotation in degrees (e.g. 0, 90, 180, 270), or 0 if none/unknown.
get_widthheight¶
Gets the width and height of a video using FFprobe.
Arguments¶
filenamestr - Path to the video file to measure.
Returns¶
int- The width of the input video file.int- The height of the input video file.
has_audio¶
Checks if video has audio track using FFprobe.
Arguments¶
filenamestr - Path to the video file to check.
Returns¶
bool- True iffilenamehas an audio track, False otherwise.
in_colab¶
Check's if the environment is a Google Colab document.
Returns¶
bool- True if the environment is a Colab document, otherwise False.
in_ipynb¶
Check if the environment is a Jupyter notebook. Taken from https://stackoverflow.com/questions/15411967/how-can-i-check-if-code-is-executed-in-the-ipython-notebook.
Returns¶
bool- True if the environment is a Jupyter notebook, otherwise False.
merge_videos¶
def merge_videos(
media_paths: list,
target_name: str = None,
overwrite: bool = False,
print_cmd: bool = False,
) -> str:
Merges a list of video files into a single video file using ffmpeg.
Arguments¶
media_pathslist - List of paths to the video files to merge.target_namestr, optional - The name of the output video. Defaults to None (which assumes that the input filename with the suffix "_merged" should be used).overwritebool, optional - Whether to allow overwriting existing files or to automatically increment target filename to avoid overwriting. Defaults to True.
Returns¶
str- Path to the output video.
motiongrams_ffmpeg¶
def motiongrams_ffmpeg(
filename: str,
color: bool = True,
filtertype: str = 'regular',
threshold: float = 0.05,
blur: str = 'none',
use_median: bool = False,
kernel_size: int = 5,
invert: bool = False,
target_name_x: str | None = None,
target_name_y: str | None = None,
overwrite: bool = True,
) -> tuple:
Renders horizontal and vertical motiongrams using ffmpeg.
Arguments¶
filenamestr - Path to the input video file.colorbool, optional - If False the input is converted to grayscale at the start of the process. This can significantly reduce render time. Defaults to True.filtertypestr, optional - 'Regular' turns all values belowthresholdto 0. 'Binary' turns all values belowthresholdto 0, abovethresholdto 1. 'Blob' removes individual pixels with erosion method. Defaults to 'Regular'.thresholdfloat, optional - Eliminates pixel values less than given threshold. Ranges from 0 to 1. Defaults to 0.05.blurstr, optional - 'Average' to apply a 10px * 10px blurring filter, 'None' otherwise. Defaults to 'None'.use_medianbool, optional - If True the algorithm applies a median filter on the thresholded frame-difference stream. Defaults to False.kernel_sizeint, optional - Size of the median filter (ifuse_median=True) or the erosion filter (iffiltertype='blob'). Defaults to 5.invertbool, optional - If True, inverts colors of the motiongrams. Defaults to False.target_name_xstr, optional - Target output name for the motiongram on the X axis. Defaults to None (which assumes that the input filename with the suffix "_mgx_ffmpeg" should be used).target_name_ystr, optional - Target output name for the motiongram on the Y axis. Defaults to None (which assumes that the input filename with the suffix "_mgy_ffmpeg" should be used).overwritebool, optional - Whether to allow overwriting existing files or to automatically increment target filenames to avoid overwriting. Defaults to True.
Returns¶
str- Path to the output horizontal motiongram (_mgx).str- Path to the output vertical motiongram (_mgy).
motionvideo_ffmpeg¶
def motionvideo_ffmpeg(
filename: str,
color: bool = True,
filtertype: str = 'regular',
threshold: float = 0.05,
blur: str = 'none',
use_median: bool = False,
kernel_size: int = 5,
invert: bool = False,
target_name: str | None = None,
overwrite: bool = True,
) -> str:
Renders a motion video using ffmpeg.
Arguments¶
filenamestr - Path to the input video file.colorbool, optional - If False the input is converted to grayscale at the start of the process. This can significantly reduce render time. Defaults to True.filtertypestr, optional - 'Regular' turns all values belowthresholdto 0. 'Binary' turns all values belowthresholdto 0, abovethresholdto 1. 'Blob' removes individual pixels with erosion method. Defaults to 'Regular'.thresholdfloat, optional - Eliminates pixel values less than given threshold. Ranges from 0 to 1. Defaults to 0.05.blurstr, optional - 'Average' to apply a 10px * 10px blurring filter, 'None' otherwise. Defaults to 'None'.use_medianbool, optional - If True the algorithm applies a median filter on the thresholded frame-difference stream. Defaults to False.kernel_sizeint, optional - Size of the median filter (ifuse_median=True) or the erosion filter (iffiltertype='blob'). Defaults to 5.invertbool, optional - If True, inverts colors of the motion video. Defaults to False.target_namestr, optional - Defaults to None (which assumes that the input filename with the suffix "_motion" should be used).overwritebool, optional - Whether to allow overwriting existing files or to automatically increment target filename to avoid overwriting. Defaults to True.
Returns¶
str- Path to the output video.
normalize_rotation¶
If a video carries a display-rotation flag (e.g. a phone portrait recording with landscape pixels), re-encode it so the rotation is baked into the pixels and the flag removed. This makes every downstream reader (FFmpeg pipe, OpenCV, filters) agree on the orientation, preventing some processes from coming out rotated.
Arguments¶
filenamestr - Path to the video file.overwritebool - Overwrite the "_oriented" output if it exists. Defaults to True.
Returns¶
str- Path to an upright video — the original if it had no rotation, otherwise a new "_oriented" copy.
pass_if_container_is¶
Checks if a file's extension matches a desired one. Passes if so, raises WrongContainer if not.
Arguments¶
containerstr - The container to match.filestr - Path to the file to inspect.
Raises¶
WrongContainer- If the file extension (container) matches the desired one.
pass_if_containers_match¶
Checks if file extensions match between two files. If they do it passes, is they don't it raises WrongContainer exception.
Arguments¶
file_1str - First file in comparison.file_2str - Second file in comparison.
Raises¶
WrongContainer- If file extensions (containers) mismatch.
quality_metrics¶
Compute video quality metrics between two video files for comparing the quality of video codecs or measuring the efficacy of encoding configuration. Possible to compute three major video quality metrics used for objective evaluation, namely:
- PSNR: It is the most commonly used video quality metric. But it has the lowest predictive value, so the results are inconsistent. Used by major platforms like Netflix and Facebook to compare different codecs and for similar use cases. Overall usage is declining.
- SSIM: Mostly used by technical experts like codec researchers and compression engineers. Usage is declining steadily. However, it has a higher predictive value than PSNR.
- VMAF: Introduced first by Netflix but then converted into an open-source asset. VMAF is easily accessible and widely used. Designed specifically for evaluating the video quality of streams encoded for multiple-resolution rungs.
Arguments¶
originalstr - Path to the original/reference video file.processedstr - Path to the processed/distorted video file.metricstr, optional - Type of quality metric to compute ('vmaf', 'ssim', or 'psnr'). Defaults to None (which computes all the metrics).
resolve_filename¶
def resolve_filename(
stem: str,
suffix: str,
target_name: str | None = None,
overwrite: bool = True,
) -> str:
Resolve an output filename for a rendered result.
Centralises the target_name/overwrite logic that most methods repeat: use
stem + suffix when no name is given, otherwise honour the provided target_name but
enforce the extension from suffix; when overwrite is False, auto-increment the name so
nothing is clobbered.
Arguments¶
stemstr - Input filename stem (e.g.self.of), used whentarget_nameis None.suffixstr - Suffix incl. extension to append tostem(e.g.'_grid.png'); its extension is also the one enforced on a providedtarget_name.target_namestr, optional - Explicit output path (its extension is normalised to thesuffixextension). Defaults to None.overwritebool, optional - If False, auto-increment to avoid overwriting. Defaults to True.
Returns¶
str- The resolved output path.
rotate_video¶
def rotate_video(
filename: str,
angle: float,
target_name: str | None = None,
overwrite: bool = True,
) -> str:
Rotates a video by an angle using ffmpeg.
Arguments¶
filenamestr - Path to the input video file.anglefloat - The angle (in degrees) specifying the amount of rotation. Positive values rotate clockwise.target_namestr, optional - Target filename as path. Defaults to None (which assumes that the input filename with the suffix "_rot" should be used).overwritebool, optional - Whether to allow overwriting existing files or to automatically increment target filename to avoid overwriting. Defaults to True.
Returns¶
str- The path to the rotated video file.
roundup¶
Rounds up a number to the next integer multiple of another.
Arguments¶
numint - The number to round up.modulo_numint - The number whose next integer multiple we want.
Returns¶
int- The rounded-up number.
scale_array¶
Scales an array linearly.
Arguments¶
arrayarraylike - The array to be scaled.out_lowfloat - Minimum of output range.out_highfloat - Maximum of output range.
Returns¶
arraylike- The scaled array.
scale_num¶
def scale_num(
val: float,
in_low: float,
in_high: float,
out_low: float,
out_high: float,
) -> float:
Scales a number linearly.
Arguments¶
valfloat - The value to be scaled.in_lowfloat - Minimum of input range.in_highfloat - Maximum of input range.out_lowfloat - Minimum of output range.out_highfloat - Maximum of output range.
Returns¶
float- The scaled number.
show_progress¶
Enable or disable the MGT progress bars globally.
Disabling the progress bars is useful when running batch processing jobs or
when the output is captured by a logging framework where the repeated
\r updates would clutter the log.
Arguments¶
enabledbool - PassTrueto show progress bars (default behaviour) orFalseto suppress them.
Examples¶
>>> import musicalgestures as mg
>>> mg.show_progress(False) # suppress all progress bars
>>> # … batch processing …
>>> mg.show_progress(True) # re-enable for interactive use
## str2sec
[[find in source code]](https://github.com/fourMs/MGT-python/blob/master/musicalgestures/_utils.py#L1807)
```python
def str2sec(time_string: str) -> float:
Converts a time code string into seconds.
Arguments¶
time_stringstr - The time code to convert. Eg. '01:33:42'.
Returns¶
float- The time code converted to seconds.
threshold_ffmpeg¶
def threshold_ffmpeg(
filename: str,
threshold: float = 0.1,
target_name: str | None = None,
binary: bool = False,
overwrite: bool = True,
) -> str:
Renders a pixel-thresholded video from the input using ffmpeg.
Arguments¶
filenamestr - Path to the input video file.thresholdfloat, optional - The normalized pixel value to use as the threshold. Pixels below the threshold will turn black. Defaults to 0.1.target_namestr, optional - The name of the output video. Defaults to None (which assumes that the input filename with the suffix "_thresh" should be used).binarybool, optional - If True, the pixels above the threshold will turn white. Defaults to False.overwritebool, optional - Whether to allow overwriting existing files or to automatically increment target filename to avoid overwriting. Defaults to True.
Returns¶
str- Path to the output video.
unwrap_str¶
Unwraps a string from quotes.
Arguments¶
stringstr - The string to inspect.
Returns¶
str- The (unwrapped) string.
wrap_str¶
Wraps a string in double quotes if it contains any of matchers - by default: space or parentheses.
Useful when working with shell commands.
Arguments¶
stringstr - The string to inspect.matcherslist, optional - The list of characters to look for in the string. Defaults to [" ", "(", ")"].
Returns¶
str- The (wrapped) string.