id int64 0 190k | prompt stringlengths 21 13.4M | docstring stringlengths 1 12k ⌀ |
|---|---|---|
160,763 | from typing import Any, Dict, List, Optional, Tuple
import numpy as np
from augly.image import intensity as imint, utils as imutils
from augly.video.helpers import get_video_info
def distractor_overlay_intensity_helper(
topleft: Optional[Tuple[float, float]],
bottomright: Optional[Tuple[float, float]],
num_overlay_content: int,
**kwargs,
) -> float:
"""
Computes intensity of any distractor-type transform, which adds some kind
of media (images, emojis, text, dots, logos) on top of the src video within
a specified bounding box.
"""
assert topleft is None or all(
0.0 <= t <= 1.0 for t in topleft
), "Topleft must be in the range [0, 1]"
assert bottomright is None or all(
0.0 <= b <= 1.0 for b in bottomright
), "Bottomright must be in the range [0, 1]"
assert (
isinstance(num_overlay_content, int) and num_overlay_content >= 0
), "num_overlay_content must be a nonnegative int"
if topleft is None or bottomright is None:
return 100.0
max_num_overlay_content_val = 100
num_overlay_content_intensity = num_overlay_content / max_num_overlay_content_val
x1, y1 = topleft
x2, y2 = bottomright
distractor_area = (x2 - x1) * (y2 - y1)
return min((distractor_area * num_overlay_content_intensity) * 100.0, 100.0)
def overlay_text_intensity(
topleft: Optional[Tuple[float, float]],
bottomright: Optional[Tuple[float, float]],
**kwargs,
) -> float:
return distractor_overlay_intensity_helper(topleft, bottomright, 1) | null |
160,764 | from typing import Any, Dict, List, Optional, Tuple
import numpy as np
from augly.image import intensity as imint, utils as imutils
from augly.video.helpers import get_video_info
def pad_intensity(metadata: Dict[str, Any], **kwargs) -> float:
return imint.resize_intensity_helper(metadata) | null |
160,765 | from typing import Any, Dict, List, Optional, Tuple
import numpy as np
from augly.image import intensity as imint, utils as imutils
from augly.video.helpers import get_video_info
def perspective_transform_and_shake_intensity(
sigma: float, shake_radius: float, **kwargs
) -> float:
assert (
isinstance(sigma, (float, int)) and sigma >= 0
), "sigma must be a non-negative number"
assert (
isinstance(shake_radius, (float, int)) and shake_radius >= 0
), "shake_radius must be a non-negative number"
max_sigma_val = 100
max_shake_radius_val = 100
sigma_intensity = sigma / max_sigma_val
shake_radius_intensity = shake_radius / max_shake_radius_val
return min((sigma_intensity * shake_radius_intensity) * 100.0, 100.0) | null |
160,766 | from typing import Any, Dict, List, Optional, Tuple
import numpy as np
from augly.image import intensity as imint, utils as imutils
from augly.video.helpers import get_video_info
def pixelization_intensity(ratio: float, **kwargs) -> float:
assert (
isinstance(ratio, (float, int)) and 0 <= ratio <= 1
), "ratio must be a number in [0, 1]"
return (1 - ratio) * 100.0 | null |
160,767 | from typing import Any, Dict, List, Optional, Tuple
import numpy as np
from augly.image import intensity as imint, utils as imutils
from augly.video.helpers import get_video_info
def remove_audio_intensity(**kwargs) -> float:
return 100.0 | null |
160,768 | from typing import Any, Dict, List, Optional, Tuple
import numpy as np
from augly.image import intensity as imint, utils as imutils
from augly.video.helpers import get_video_info
The provided code snippet includes necessary dependencies for implementing the `insert_in_background_multiple_intensity` function. Write a Python function `def insert_in_background_multiple_intensity( metadata: Dict[str, Any], **kwargs ) -> float` to solve the following problem:
The intensity is calculated as the percentage of the result video that contains inserted segments.
Here is the function:
def insert_in_background_multiple_intensity(
metadata: Dict[str, Any], **kwargs
) -> float:
"""
The intensity is calculated as the percentage of the result video
that contains inserted segments.
"""
dst_duration = metadata["dst_duration"]
starts = metadata["src_segment_starts"]
ends = metadata["src_segment_ends"]
inserted = np.sum(ends - starts)
return inserted / dst_duration | The intensity is calculated as the percentage of the result video that contains inserted segments. |
160,769 | from typing import Any, Dict, List, Optional, Tuple
import numpy as np
from augly.image import intensity as imint, utils as imutils
from augly.video.helpers import get_video_info
The provided code snippet includes necessary dependencies for implementing the `replace_with_background_intensity` function. Write a Python function `def replace_with_background_intensity(metadata: Dict[str, Any], **kwargs) -> float` to solve the following problem:
The intensity of replace_with_background is the fraction of the source video duration that was replaced with background. Because the overall duration of the video is preserved, the background segments together must be shorter than the source duration so the intensity is never greater than 100.
Here is the function:
def replace_with_background_intensity(metadata: Dict[str, Any], **kwargs) -> float:
"""
The intensity of replace_with_background is the fraction of the source video duration
that was replaced with background. Because the overall duration of the video is preserved,
the background segments together must be shorter than the source duration so the intensity is never
greater than 100.
"""
src_duration = metadata["src_duration"]
total_bg_duration = (
metadata["starting_background_duration"]
+ metadata["ending_background_duration"]
)
return min((total_bg_duration / src_duration) * 100.0, 100.0) | The intensity of replace_with_background is the fraction of the source video duration that was replaced with background. Because the overall duration of the video is preserved, the background segments together must be shorter than the source duration so the intensity is never greater than 100. |
160,770 | from typing import Any, Dict, List, Optional, Tuple
import numpy as np
from augly.image import intensity as imint, utils as imutils
from augly.video.helpers import get_video_info
def replace_with_color_frames_intensity(
duration_factor: float, offset_factor: float, **kwargs
) -> float:
assert (
isinstance(duration_factor, (float, int)) and 0 <= duration_factor <= 1
), "duration_factor must be a number in [0, 1]"
assert (
isinstance(offset_factor, (float, int)) and 0 <= offset_factor <= 1
), "offset_factor must be a number in [0, 1]"
# The proportion of the video that is replaced by color frames is generally
# equal to duration factor, unless offset_factor + duration_factor > 1, in
# which case it will be 1 - offset_factor.
return min(duration_factor, 1 - offset_factor) * 100.0 | null |
160,771 | from typing import Any, Dict, List, Optional, Tuple
import numpy as np
from augly.image import intensity as imint, utils as imutils
from augly.video.helpers import get_video_info
def resize_intensity(metadata: Dict[str, Any], **kwargs) -> float:
return imint.resize_intensity_helper(metadata) | null |
160,772 | from typing import Any, Dict, List, Optional, Tuple
import numpy as np
from augly.image import intensity as imint, utils as imutils
from augly.video.helpers import get_video_info
def rotate_intensity(degrees: float, **kwargs) -> float:
assert isinstance(degrees, (float, int)), "degrees must be a number"
max_degrees_val = 180
degrees = abs(degrees) % 180
return (degrees / max_degrees_val) * 100.0 | null |
160,773 | from typing import Any, Dict, List, Optional, Tuple
import numpy as np
from augly.image import intensity as imint, utils as imutils
from augly.video.helpers import get_video_info
def scale_intensity(factor: float, **kwargs) -> float:
assert (
isinstance(factor, (float, int)) and factor > 0
), "factor must be a positive number"
if factor == 1.0:
return 0.0
max_factor_val = 10.0
scale_factor = factor if factor > 1 else 1 / factor
return min((scale_factor / max_factor_val) * 100.0, 100.0) | null |
160,774 | from typing import Any, Dict, List, Optional, Tuple
import numpy as np
from augly.image import intensity as imint, utils as imutils
from augly.video.helpers import get_video_info
def shift_intensity(x_factor: float, y_factor: float, **kwargs) -> float:
assert (
isinstance(x_factor, (float, int))
and 0 <= x_factor <= 1
and isinstance(y_factor, (float, int))
and 0 <= y_factor <= 1
), "x_factor & y_factor must be positive numbers in [0, 1]"
return (1 - x_factor) * (1 - y_factor) * 100.0 | null |
160,775 | from typing import Any, Dict, List, Optional, Tuple
import numpy as np
from augly.image import intensity as imint, utils as imutils
from augly.video.helpers import get_video_info
def time_crop_or_pad_intensity_helper(metadata: Dict[str, Any]) -> float:
"""
Computes intensity of a transform that consists of temporal cropping or
padding. For these types of transforms the intensity is defined as the
percentage of video time that has been cut out (for cropping) or added
(for padding). When computing the percentage, the denominator should be
the longer of the src & dst durations so the resulting percentage isn't
greater than 100.
"""
dst_duration = metadata["dst_duration"]
src_duration = metadata["src_duration"]
larger_duration = max(src_duration, dst_duration)
return (abs(dst_duration - src_duration) / larger_duration) * 100.0
def time_crop_intensity(metadata: Dict[str, Any], **kwargs) -> float:
return time_crop_or_pad_intensity_helper(metadata) | null |
160,776 | from typing import Any, Dict, List, Optional, Tuple
import numpy as np
from augly.image import intensity as imint, utils as imutils
from augly.video.helpers import get_video_info
def time_crop_or_pad_intensity_helper(metadata: Dict[str, Any]) -> float:
"""
Computes intensity of a transform that consists of temporal cropping or
padding. For these types of transforms the intensity is defined as the
percentage of video time that has been cut out (for cropping) or added
(for padding). When computing the percentage, the denominator should be
the longer of the src & dst durations so the resulting percentage isn't
greater than 100.
"""
dst_duration = metadata["dst_duration"]
src_duration = metadata["src_duration"]
larger_duration = max(src_duration, dst_duration)
return (abs(dst_duration - src_duration) / larger_duration) * 100.0
def time_decimate_intensity(metadata: Dict[str, Any], **kwargs) -> float:
return time_crop_or_pad_intensity_helper(metadata) | null |
160,777 | from typing import Any, Dict, List, Optional, Tuple
import numpy as np
from augly.image import intensity as imint, utils as imutils
from augly.video.helpers import get_video_info
def time_crop_or_pad_intensity_helper(metadata: Dict[str, Any]) -> float:
"""
Computes intensity of a transform that consists of temporal cropping or
padding. For these types of transforms the intensity is defined as the
percentage of video time that has been cut out (for cropping) or added
(for padding). When computing the percentage, the denominator should be
the longer of the src & dst durations so the resulting percentage isn't
greater than 100.
"""
dst_duration = metadata["dst_duration"]
src_duration = metadata["src_duration"]
larger_duration = max(src_duration, dst_duration)
return (abs(dst_duration - src_duration) / larger_duration) * 100.0
def trim_intensity(metadata: Dict[str, Any], **kwargs) -> float:
return time_crop_or_pad_intensity_helper(metadata) | null |
160,778 | from typing import Any, Dict, List, Optional, Tuple
import numpy as np
from augly.image import intensity as imint, utils as imutils
from augly.video.helpers import get_video_info
def vflip_intensity(**kwargs) -> float:
return 100.0 | null |
160,779 | from typing import Any, Dict, List, Optional, Tuple
import numpy as np
from augly.image import intensity as imint, utils as imutils
from augly.video.helpers import get_video_info
def vstack_intensity(metadata: Dict[str, Any], **kwargs) -> float:
return imint.resize_intensity_helper(metadata) | null |
160,780 | from copy import deepcopy
from typing import Any, Dict, List, Optional, Tuple
from augly import utils
from augly.video import helpers
from augly.video.helpers import intensity as vdintensity
def get_func_kwargs(
metadata: Optional[List[Dict[str, Any]]],
local_kwargs: Dict[str, Any],
video_path: str,
**kwargs,
) -> Dict[str, Any]:
if metadata is None:
return {}
func_kwargs = deepcopy(local_kwargs)
func_kwargs.pop("metadata")
func_kwargs.update(
{
"src_video_info": helpers.get_video_info(video_path),
"src_fps": helpers.get_video_fps(video_path),
**kwargs,
}
)
return func_kwargs | null |
160,781 | from copy import deepcopy
from typing import Any, Dict, List, Optional, Tuple
from augly import utils
from augly.video import helpers
from augly.video.helpers import intensity as vdintensity
def compute_segments(
name: str,
src_duration: float,
dst_duration: float,
metadata: List[Dict[str, Any]],
**kwargs,
) -> Tuple[List[Segment], List[Segment]]:
"""
Compute matching pairs of src_segment -> dst_segment, given the kwargs of the
transform, as well as the metadata about previously applied transforms.
"""
speed_factor = 1.0
src_id = kwargs.get("src_id", None)
if not metadata:
src_segments = [Segment(0.0, src_duration, src_id)]
dst_segments = [Segment(0.0, src_duration)]
else:
src_segments = [
Segment(
segment_dict["start"], segment_dict["end"], segment_dict.get("src_id")
)
for segment_dict in metadata[-1]["src_segments"]
]
dst_segments = [
Segment(segment_dict["start"], segment_dict["end"])
for segment_dict in metadata[-1]["dst_segments"]
]
for meta in metadata:
if meta["name"] in ["change_video_speed"]:
speed_factor *= meta["factor"]
if name in [
"insert_in_background",
"insert_in_background_multiple",
"replace_with_background",
"change_video_speed",
"loop",
"time_crop",
"time_decimate",
"trim",
"replace_with_color_frames",
"concat",
]:
return compute_changed_segments(
name,
src_segments,
dst_segments,
src_duration,
dst_duration,
speed_factor,
**kwargs,
)
else:
return src_segments, dst_segments
def get_metadata(
metadata: Optional[List[Dict[str, Any]]],
function_name: str,
video_path: str,
output_path: Optional[str],
src_video_info: Dict[str, Any],
src_fps: Optional[float],
**kwargs,
) -> None:
if metadata is None:
return
assert isinstance(
metadata, list
), "Expected 'metadata' to be set to None or of type list"
assert src_fps is not None
output_path = output_path or video_path
src_video_info = src_video_info
dst_video_info = helpers.get_video_info(output_path)
src_duration = float(src_video_info["duration"])
dst_duration = float(dst_video_info["duration"])
src_segments, dst_segments = compute_segments(
function_name, src_duration, dst_duration, metadata, **kwargs
)
# Json can't represent tuples, so they're represented as lists, which should
# be equivalent to tuples. So let's avoid tuples in the metadata by
# converting any tuples to lists here.
kwargs_types_fixed = dict(
(k, list(v)) if isinstance(v, tuple) else (k, v) for k, v in kwargs.items()
)
metadata.append(
{
"name": function_name,
"src_duration": src_duration,
"dst_duration": dst_duration,
"src_fps": src_fps,
"dst_fps": helpers.get_video_fps(output_path),
"src_width": src_video_info["width"],
"src_height": src_video_info["height"],
"dst_width": dst_video_info["width"],
"dst_height": dst_video_info["height"],
"src_segments": [src_segment._asdict() for src_segment in src_segments],
"dst_segments": [dst_segment._asdict() for dst_segment in dst_segments],
**kwargs_types_fixed,
}
)
intensity_kwargs = {"metadata": metadata[-1], **kwargs}
metadata[-1]["intensity"] = getattr(
vdintensity, f"{function_name}_intensity", lambda **_: 0.0
)(**intensity_kwargs) | null |
160,782 | import functools
import math
import os
import shutil
import tempfile
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
import numpy as np
from augly import audio as audaugs, image as imaugs, utils
from augly.audio import utils as audutils
from augly.video import helpers, utils as vdutils
from augly.video.augmenters import cv2 as ac, ffmpeg as af
The provided code snippet includes necessary dependencies for implementing the `add_noise` function. Write a Python function `def add_noise( video_path: str, output_path: Optional[str] = None, level: int = 25, metadata: Optional[List[Dict[str, Any]]] = None, ) -> str` to solve the following problem:
Adds noise to a video @param video_path: the path to the video to be augmented @param output_path: the path in which the resulting video will be stored. If not passed in, the original video file will be overwritten @param level: noise strength for specific pixel component. Default value is 25. Allowed range is [0, 100], where 0 indicates no change @param metadata: if set to be a list, metadata about the function execution including its name, the source & dest duration, fps, etc. will be appended to the inputted list. If set to None, no metadata will be appended or returned @returns: the path to the augmented video
Here is the function:
def add_noise(
video_path: str,
output_path: Optional[str] = None,
level: int = 25,
metadata: Optional[List[Dict[str, Any]]] = None,
) -> str:
"""
Adds noise to a video
@param video_path: the path to the video to be augmented
@param output_path: the path in which the resulting video will be stored.
If not passed in, the original video file will be overwritten
@param level: noise strength for specific pixel component. Default value is
25. Allowed range is [0, 100], where 0 indicates no change
@param metadata: if set to be a list, metadata about the function execution
including its name, the source & dest duration, fps, etc. will be appended
to the inputted list. If set to None, no metadata will be appended or returned
@returns: the path to the augmented video
"""
func_kwargs = helpers.get_func_kwargs(metadata, locals(), video_path)
noise_aug = af.VideoAugmenterByNoise(level)
noise_aug.add_augmenter(video_path, output_path)
if metadata is not None:
helpers.get_metadata(
metadata=metadata, function_name="add_noise", **func_kwargs
)
return output_path or video_path | Adds noise to a video @param video_path: the path to the video to be augmented @param output_path: the path in which the resulting video will be stored. If not passed in, the original video file will be overwritten @param level: noise strength for specific pixel component. Default value is 25. Allowed range is [0, 100], where 0 indicates no change @param metadata: if set to be a list, metadata about the function execution including its name, the source & dest duration, fps, etc. will be appended to the inputted list. If set to None, no metadata will be appended or returned @returns: the path to the augmented video |
160,783 | import functools
import math
import os
import shutil
import tempfile
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
import numpy as np
from augly import audio as audaugs, image as imaugs, utils
from augly.audio import utils as audutils
from augly.video import helpers, utils as vdutils
from augly.video.augmenters import cv2 as ac, ffmpeg as af
def apply_lambda(
video_path: str,
output_path: Optional[str] = None,
aug_function: Callable[..., Any] = helpers.identity_function,
metadata: Optional[List[Dict[str, Any]]] = None,
**kwargs,
) -> str:
"""
Apply a user-defined lambda on a video
If not passed in, the original video file will be overwritten
(should expect a video path and output path as input and output the augmented
video to the output path. Nothing needs to be returned)
including its name, the source & dest duration, fps, etc. will be appended
to the inputted list. If set to None, no metadata will be appended or returned
"""
assert callable(aug_function), (
repr(type(aug_function).__name__) + " object is not callable"
)
func_kwargs = helpers.get_func_kwargs(
metadata, locals(), video_path, aug_function=aug_function.__name__
)
aug_function(video_path, output_path or video_path, **kwargs)
if metadata is not None:
helpers.get_metadata(
metadata=metadata, function_name="apply_lambda", **func_kwargs
)
return output_path or video_path
def audio_swap(
video_path: str,
audio_path: str,
output_path: Optional[str] = None,
offset: float = 0.0,
metadata: Optional[List[Dict[str, Any]]] = None,
) -> str:
"""
Swaps the video audio for the audio passed in provided an offset
video's audio
If not passed in, the original video file will be overwritten
offset + video_duration is used in the audio swap. Default value is zero
including its name, the source & dest duration, fps, etc. will be appended
to the inputted list. If set to None, no metadata will be appended or returned
"""
func_kwargs = helpers.get_func_kwargs(metadata, locals(), video_path)
audio_swap_aug = af.VideoAugmenterByAudioSwap(audio_path, offset)
audio_swap_aug.add_augmenter(video_path, output_path)
if metadata is not None:
helpers.get_metadata(
metadata=metadata, function_name="audio_swap", **func_kwargs
)
return output_path or video_path
The provided code snippet includes necessary dependencies for implementing the `augment_audio` function. Write a Python function `def augment_audio( video_path: str, output_path: Optional[str] = None, audio_aug_function: Callable[..., Tuple[np.ndarray, int]] = audaugs.apply_lambda, metadata: Optional[List[Dict[str, Any]]] = None, **audio_aug_kwargs, ) -> str` to solve the following problem:
Augments the audio track of the input video using a given AugLy audio augmentation @param video_path: the path to the video to be augmented @param output_path: the path in which the resulting video will be stored. If not passed in, the original video file will be overwritten @param audio_aug_function: the augmentation function to be applied onto the video's audio track. Should have the standard API of an AugLy audio augmentation, i.e. expect input audio as a numpy array or path & output path as input, and output the augmented audio to the output path @param metadata: if set to be a list, metadata about the function execution including its name, the source & dest duration, fps, etc. will be appended to the inputted list. If set to None, no metadata will be appended or returned @param audio_aug_kwargs: the input attributes to be passed into `audio_aug` @returns: the path to the augmented video
Here is the function:
def augment_audio(
video_path: str,
output_path: Optional[str] = None,
audio_aug_function: Callable[..., Tuple[np.ndarray, int]] = audaugs.apply_lambda,
metadata: Optional[List[Dict[str, Any]]] = None,
**audio_aug_kwargs,
) -> str:
"""
Augments the audio track of the input video using a given AugLy audio augmentation
@param video_path: the path to the video to be augmented
@param output_path: the path in which the resulting video will be stored.
If not passed in, the original video file will be overwritten
@param audio_aug_function: the augmentation function to be applied onto the video's
audio track. Should have the standard API of an AugLy audio augmentation, i.e.
expect input audio as a numpy array or path & output path as input, and output
the augmented audio to the output path
@param metadata: if set to be a list, metadata about the function execution
including its name, the source & dest duration, fps, etc. will be appended
to the inputted list. If set to None, no metadata will be appended or returned
@param audio_aug_kwargs: the input attributes to be passed into `audio_aug`
@returns: the path to the augmented video
"""
assert callable(audio_aug_function), (
repr(type(audio_aug_function).__name__) + " object is not callable"
)
func_kwargs = helpers.get_func_kwargs(
metadata, locals(), video_path, audio_aug_function=audio_aug_function
)
if audio_aug_function is not None:
try:
func_kwargs["audio_aug_function"] = audio_aug_function.__name__
except AttributeError:
func_kwargs["audio_aug_function"] = type(audio_aug_function).__name__
audio_metadata = []
with tempfile.NamedTemporaryFile(suffix=".wav") as tmpfile:
helpers.extract_audio_to_file(video_path, tmpfile.name)
audio, sr = audutils.validate_and_load_audio(tmpfile.name)
aug_audio, aug_sr = audio_aug_function(
audio, sample_rate=sr, metadata=audio_metadata, **audio_aug_kwargs
)
audutils.ret_and_save_audio(aug_audio, tmpfile.name, aug_sr)
audio_swap(video_path, tmpfile.name, output_path=output_path or video_path)
if metadata is not None:
helpers.get_metadata(
metadata=metadata,
audio_metadata=audio_metadata,
function_name="augment_audio",
**func_kwargs,
)
return output_path or video_path | Augments the audio track of the input video using a given AugLy audio augmentation @param video_path: the path to the video to be augmented @param output_path: the path in which the resulting video will be stored. If not passed in, the original video file will be overwritten @param audio_aug_function: the augmentation function to be applied onto the video's audio track. Should have the standard API of an AugLy audio augmentation, i.e. expect input audio as a numpy array or path & output path as input, and output the augmented audio to the output path @param metadata: if set to be a list, metadata about the function execution including its name, the source & dest duration, fps, etc. will be appended to the inputted list. If set to None, no metadata will be appended or returned @param audio_aug_kwargs: the input attributes to be passed into `audio_aug` @returns: the path to the augmented video |
160,784 | import functools
import math
import os
import shutil
import tempfile
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
import numpy as np
from augly import audio as audaugs, image as imaugs, utils
from augly.audio import utils as audutils
from augly.video import helpers, utils as vdutils
from augly.video.augmenters import cv2 as ac, ffmpeg as af
The provided code snippet includes necessary dependencies for implementing the `blend_videos` function. Write a Python function `def blend_videos( video_path: str, overlay_path: str, output_path: Optional[str] = None, opacity: float = 0.5, overlay_size: float = 1.0, x_pos: float = 0.0, y_pos: float = 0.0, use_second_audio: bool = True, metadata: Optional[List[Dict[str, Any]]] = None, ) -> str` to solve the following problem:
Overlays a video onto another video at position (width * x_pos, height * y_pos) at a lower opacity @param video_path: the path to the video to be augmented @param overlay_path: the path to the video that will be overlaid onto the background video @param output_path: the path in which the resulting video will be stored. If not passed in, the original video file will be overwritten @param opacity: the lower the opacity, the more transparent the overlaid video @param overlay_size: size of the overlaid video is overlay_size * height of the background video @param x_pos: position of overlaid video relative to the background video width @param y_pos: position of overlaid video relative to the background video height @param use_second_audio: use the audio of the overlaid video rather than the audio of the background video @param metadata: if set to be a list, metadata about the function execution including its name, the source & dest duration, fps, etc. will be appended to the inputted list. If set to None, no metadata will be appended or returned @returns: the path to the augmented video
Here is the function:
def blend_videos(
video_path: str,
overlay_path: str,
output_path: Optional[str] = None,
opacity: float = 0.5,
overlay_size: float = 1.0,
x_pos: float = 0.0,
y_pos: float = 0.0,
use_second_audio: bool = True,
metadata: Optional[List[Dict[str, Any]]] = None,
) -> str:
"""
Overlays a video onto another video at position (width * x_pos, height * y_pos)
at a lower opacity
@param video_path: the path to the video to be augmented
@param overlay_path: the path to the video that will be overlaid onto the
background video
@param output_path: the path in which the resulting video will be stored.
If not passed in, the original video file will be overwritten
@param opacity: the lower the opacity, the more transparent the overlaid video
@param overlay_size: size of the overlaid video is overlay_size * height of
the background video
@param x_pos: position of overlaid video relative to the background video width
@param y_pos: position of overlaid video relative to the background video height
@param use_second_audio: use the audio of the overlaid video rather than the audio
of the background video
@param metadata: if set to be a list, metadata about the function execution
including its name, the source & dest duration, fps, etc. will be appended
to the inputted list. If set to None, no metadata will be appended or returned
@returns: the path to the augmented video
"""
func_kwargs = helpers.get_func_kwargs(metadata, locals(), video_path)
blend_func = functools.partial(
imaugs.overlay_image,
opacity=opacity,
overlay_size=overlay_size,
x_pos=x_pos,
y_pos=y_pos,
)
vdutils.apply_to_frames(
blend_func, video_path, overlay_path, output_path, use_second_audio
)
if metadata is not None:
helpers.get_metadata(
metadata=metadata, function_name="blend_videos", **func_kwargs
)
return output_path or video_path | Overlays a video onto another video at position (width * x_pos, height * y_pos) at a lower opacity @param video_path: the path to the video to be augmented @param overlay_path: the path to the video that will be overlaid onto the background video @param output_path: the path in which the resulting video will be stored. If not passed in, the original video file will be overwritten @param opacity: the lower the opacity, the more transparent the overlaid video @param overlay_size: size of the overlaid video is overlay_size * height of the background video @param x_pos: position of overlaid video relative to the background video width @param y_pos: position of overlaid video relative to the background video height @param use_second_audio: use the audio of the overlaid video rather than the audio of the background video @param metadata: if set to be a list, metadata about the function execution including its name, the source & dest duration, fps, etc. will be appended to the inputted list. If set to None, no metadata will be appended or returned @returns: the path to the augmented video |
160,785 | import functools
import math
import os
import shutil
import tempfile
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
import numpy as np
from augly import audio as audaugs, image as imaugs, utils
from augly.audio import utils as audutils
from augly.video import helpers, utils as vdutils
from augly.video.augmenters import cv2 as ac, ffmpeg as af
The provided code snippet includes necessary dependencies for implementing the `blur` function. Write a Python function `def blur( video_path: str, output_path: Optional[str] = None, sigma: float = 1, metadata: Optional[List[Dict[str, Any]]] = None, ) -> str` to solve the following problem:
Blurs a video @param video_path: the path to the video to be augmented @param output_path: the path in which the resulting video will be stored. If not passed in, the original video file will be overwritten @param sigma: horizontal sigma, standard deviation of Gaussian blur @param metadata: if set to be a list, metadata about the function execution including its name, the source & dest duration, fps, etc. will be appended to the inputted list. If set to None, no metadata will be appended or returned @returns: the path to the augmented video
Here is the function:
def blur(
video_path: str,
output_path: Optional[str] = None,
sigma: float = 1,
metadata: Optional[List[Dict[str, Any]]] = None,
) -> str:
"""
Blurs a video
@param video_path: the path to the video to be augmented
@param output_path: the path in which the resulting video will be stored.
If not passed in, the original video file will be overwritten
@param sigma: horizontal sigma, standard deviation of Gaussian blur
@param metadata: if set to be a list, metadata about the function execution
including its name, the source & dest duration, fps, etc. will be appended
to the inputted list. If set to None, no metadata will be appended or returned
@returns: the path to the augmented video
"""
func_kwargs = helpers.get_func_kwargs(metadata, locals(), video_path)
blur_aug = af.VideoAugmenterByBlur(sigma)
blur_aug.add_augmenter(video_path, output_path)
if metadata is not None:
helpers.get_metadata(metadata=metadata, function_name="blur", **func_kwargs)
return output_path or video_path | Blurs a video @param video_path: the path to the video to be augmented @param output_path: the path in which the resulting video will be stored. If not passed in, the original video file will be overwritten @param sigma: horizontal sigma, standard deviation of Gaussian blur @param metadata: if set to be a list, metadata about the function execution including its name, the source & dest duration, fps, etc. will be appended to the inputted list. If set to None, no metadata will be appended or returned @returns: the path to the augmented video |
160,786 | import functools
import math
import os
import shutil
import tempfile
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
import numpy as np
from augly import audio as audaugs, image as imaugs, utils
from augly.audio import utils as audutils
from augly.video import helpers, utils as vdutils
from augly.video.augmenters import cv2 as ac, ffmpeg as af
The provided code snippet includes necessary dependencies for implementing the `brightness` function. Write a Python function `def brightness( video_path: str, output_path: Optional[str] = None, level: float = 0.15, metadata: Optional[List[Dict[str, Any]]] = None, ) -> str` to solve the following problem:
Brightens or darkens a video @param video_path: the path to the video to be augmented @param output_path: the path in which the resulting video will be stored. If not passed in, the original video file will be overwritten @param level: the value must be a float value in range -1.0 to 1.0, where a negative value darkens and positive brightens @param metadata: if set to be a list, metadata about the function execution including its name, the source & dest duration, fps, etc. will be appended to the inputted list. If set to None, no metadata will be appended or returned @returns: the path to the augmented video
Here is the function:
def brightness(
video_path: str,
output_path: Optional[str] = None,
level: float = 0.15,
metadata: Optional[List[Dict[str, Any]]] = None,
) -> str:
"""
Brightens or darkens a video
@param video_path: the path to the video to be augmented
@param output_path: the path in which the resulting video will be stored.
If not passed in, the original video file will be overwritten
@param level: the value must be a float value in range -1.0 to 1.0, where a
negative value darkens and positive brightens
@param metadata: if set to be a list, metadata about the function execution
including its name, the source & dest duration, fps, etc. will be appended
to the inputted list. If set to None, no metadata will be appended or returned
@returns: the path to the augmented video
"""
func_kwargs = helpers.get_func_kwargs(metadata, locals(), video_path)
brightness_aug = af.VideoAugmenterByBrightness(level)
brightness_aug.add_augmenter(video_path, output_path)
if metadata is not None:
helpers.get_metadata(
metadata=metadata, function_name="brightness", **func_kwargs
)
return output_path or video_path | Brightens or darkens a video @param video_path: the path to the video to be augmented @param output_path: the path in which the resulting video will be stored. If not passed in, the original video file will be overwritten @param level: the value must be a float value in range -1.0 to 1.0, where a negative value darkens and positive brightens @param metadata: if set to be a list, metadata about the function execution including its name, the source & dest duration, fps, etc. will be appended to the inputted list. If set to None, no metadata will be appended or returned @returns: the path to the augmented video |
160,787 | import functools
import math
import os
import shutil
import tempfile
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
import numpy as np
from augly import audio as audaugs, image as imaugs, utils
from augly.audio import utils as audutils
from augly.video import helpers, utils as vdutils
from augly.video.augmenters import cv2 as ac, ffmpeg as af
The provided code snippet includes necessary dependencies for implementing the `change_aspect_ratio` function. Write a Python function `def change_aspect_ratio( video_path: str, output_path: Optional[str] = None, ratio: Union[float, str] = 1.0, metadata: Optional[List[Dict[str, Any]]] = None, ) -> str` to solve the following problem:
Changes the sample aspect ratio attribute of the video, and resizes the video to reflect the new aspect ratio @param video_path: the path to the video to be augmented @param output_path: the path in which the resulting video will be stored. If not passed in, the original video file will be overwritten @param ratio: aspect ratio of the new video, either as a float i.e. width/height, or as a string representing the ratio in the form "num:denom" @param metadata: if set to be a list, metadata about the function execution including its name, the source & dest duration, fps, etc. will be appended to the inputted list. If set to None, no metadata will be appended or returned @returns: the path to the augmented video
Here is the function:
def change_aspect_ratio(
video_path: str,
output_path: Optional[str] = None,
ratio: Union[float, str] = 1.0,
metadata: Optional[List[Dict[str, Any]]] = None,
) -> str:
"""
Changes the sample aspect ratio attribute of the video, and resizes the
video to reflect the new aspect ratio
@param video_path: the path to the video to be augmented
@param output_path: the path in which the resulting video will be stored.
If not passed in, the original video file will be overwritten
@param ratio: aspect ratio of the new video, either as a float i.e. width/height,
or as a string representing the ratio in the form "num:denom"
@param metadata: if set to be a list, metadata about the function execution
including its name, the source & dest duration, fps, etc. will be appended
to the inputted list. If set to None, no metadata will be appended or returned
@returns: the path to the augmented video
"""
func_kwargs = helpers.get_func_kwargs(metadata, locals(), video_path)
aspect_ratio_aug = af.VideoAugmenterByAspectRatio(ratio)
aspect_ratio_aug.add_augmenter(video_path, output_path)
if metadata is not None:
helpers.get_metadata(
metadata=metadata, function_name="change_aspect_ratio", **func_kwargs
)
return output_path or video_path | Changes the sample aspect ratio attribute of the video, and resizes the video to reflect the new aspect ratio @param video_path: the path to the video to be augmented @param output_path: the path in which the resulting video will be stored. If not passed in, the original video file will be overwritten @param ratio: aspect ratio of the new video, either as a float i.e. width/height, or as a string representing the ratio in the form "num:denom" @param metadata: if set to be a list, metadata about the function execution including its name, the source & dest duration, fps, etc. will be appended to the inputted list. If set to None, no metadata will be appended or returned @returns: the path to the augmented video |
160,788 | import functools
import math
import os
import shutil
import tempfile
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
import numpy as np
from augly import audio as audaugs, image as imaugs, utils
from augly.audio import utils as audutils
from augly.video import helpers, utils as vdutils
from augly.video.augmenters import cv2 as ac, ffmpeg as af
The provided code snippet includes necessary dependencies for implementing the `change_video_speed` function. Write a Python function `def change_video_speed( video_path: str, output_path: Optional[str] = None, factor: float = 1.0, metadata: Optional[List[Dict[str, Any]]] = None, ) -> str` to solve the following problem:
Changes the speed of the video @param video_path: the path to the video to be augmented @param output_path: the path in which the resulting video will be stored. If not passed in, the original video file will be overwritten @param factor: the factor by which to alter the speed of the video. A factor less than one will slow down the video, a factor equal to one won't alter the video, and a factor greater than one will speed up the video @param metadata: if set to be a list, metadata about the function execution including its name, the source & dest duration, fps, etc. will be appended to the inputted list. If set to None, no metadata will be appended or returned @returns: the path to the augmented video
Here is the function:
def change_video_speed(
video_path: str,
output_path: Optional[str] = None,
factor: float = 1.0,
metadata: Optional[List[Dict[str, Any]]] = None,
) -> str:
"""
Changes the speed of the video
@param video_path: the path to the video to be augmented
@param output_path: the path in which the resulting video will be stored.
If not passed in, the original video file will be overwritten
@param factor: the factor by which to alter the speed of the video. A factor
less than one will slow down the video, a factor equal to one won't alter
the video, and a factor greater than one will speed up the video
@param metadata: if set to be a list, metadata about the function execution
including its name, the source & dest duration, fps, etc. will be appended
to the inputted list. If set to None, no metadata will be appended or returned
@returns: the path to the augmented video
"""
func_kwargs = helpers.get_func_kwargs(metadata, locals(), video_path)
speed_aug = af.VideoAugmenterBySpeed(factor)
speed_aug.add_augmenter(video_path, output_path)
if metadata is not None:
helpers.get_metadata(
metadata=metadata, function_name="change_video_speed", **func_kwargs
)
return output_path or video_path | Changes the speed of the video @param video_path: the path to the video to be augmented @param output_path: the path in which the resulting video will be stored. If not passed in, the original video file will be overwritten @param factor: the factor by which to alter the speed of the video. A factor less than one will slow down the video, a factor equal to one won't alter the video, and a factor greater than one will speed up the video @param metadata: if set to be a list, metadata about the function execution including its name, the source & dest duration, fps, etc. will be appended to the inputted list. If set to None, no metadata will be appended or returned @returns: the path to the augmented video |
160,789 | import functools
import math
import os
import shutil
import tempfile
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
import numpy as np
from augly import audio as audaugs, image as imaugs, utils
from augly.audio import utils as audutils
from augly.video import helpers, utils as vdutils
from augly.video.augmenters import cv2 as ac, ffmpeg as af
The provided code snippet includes necessary dependencies for implementing the `color_jitter` function. Write a Python function `def color_jitter( video_path: str, output_path: Optional[str] = None, brightness_factor: float = 0, contrast_factor: float = 1.0, saturation_factor: float = 1.0, metadata: Optional[List[Dict[str, Any]]] = None, ) -> str` to solve the following problem:
Color jitters the video @param video_path: the path to the video to be augmented @param output_path: the path in which the resulting video will be stored. If not passed in, the original video file will be overwritten @param brightness_factor: set the brightness expression. The value must be a float value in range -1.0 to 1.0. The default value is 0 @param contrast_factor: set the contrast expression. The value must be a float value in range -1000.0 to 1000.0. The default value is 1 @param saturation_factor: set the saturation expression. The value must be a float in range 0.0 to 3.0. The default value is 1 @param metadata: if set to be a list, metadata about the function execution including its name, the source & dest duration, fps, etc. will be appended to the inputted list. If set to None, no metadata will be appended or returned @returns: the path to the augmented video
Here is the function:
def color_jitter(
video_path: str,
output_path: Optional[str] = None,
brightness_factor: float = 0,
contrast_factor: float = 1.0,
saturation_factor: float = 1.0,
metadata: Optional[List[Dict[str, Any]]] = None,
) -> str:
"""
Color jitters the video
@param video_path: the path to the video to be augmented
@param output_path: the path in which the resulting video will be stored.
If not passed in, the original video file will be overwritten
@param brightness_factor: set the brightness expression. The value must be a
float value in range -1.0 to 1.0. The default value is 0
@param contrast_factor: set the contrast expression. The value must be a float
value in range -1000.0 to 1000.0. The default value is 1
@param saturation_factor: set the saturation expression. The value must be a float
in range 0.0 to 3.0. The default value is 1
@param metadata: if set to be a list, metadata about the function execution
including its name, the source & dest duration, fps, etc. will be appended
to the inputted list. If set to None, no metadata will be appended or returned
@returns: the path to the augmented video
"""
func_kwargs = helpers.get_func_kwargs(metadata, locals(), video_path)
color_jitter_aug = af.VideoAugmenterByColorJitter(
brightness_level=brightness_factor,
contrast_level=contrast_factor,
saturation_level=saturation_factor,
)
color_jitter_aug.add_augmenter(video_path, output_path)
if metadata is not None:
helpers.get_metadata(
metadata=metadata, function_name="color_jitter", **func_kwargs
)
return output_path or video_path | Color jitters the video @param video_path: the path to the video to be augmented @param output_path: the path in which the resulting video will be stored. If not passed in, the original video file will be overwritten @param brightness_factor: set the brightness expression. The value must be a float value in range -1.0 to 1.0. The default value is 0 @param contrast_factor: set the contrast expression. The value must be a float value in range -1000.0 to 1000.0. The default value is 1 @param saturation_factor: set the saturation expression. The value must be a float in range 0.0 to 3.0. The default value is 1 @param metadata: if set to be a list, metadata about the function execution including its name, the source & dest duration, fps, etc. will be appended to the inputted list. If set to None, no metadata will be appended or returned @returns: the path to the augmented video |
160,790 | import functools
import math
import os
import shutil
import tempfile
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
import numpy as np
from augly import audio as audaugs, image as imaugs, utils
from augly.audio import utils as audutils
from augly.video import helpers, utils as vdutils
from augly.video.augmenters import cv2 as ac, ffmpeg as af
The provided code snippet includes necessary dependencies for implementing the `contrast` function. Write a Python function `def contrast( video_path: str, output_path: Optional[str] = None, level: float = 1.0, metadata: Optional[List[Dict[str, Any]]] = None, ) -> str` to solve the following problem:
Alters the contrast of a video @param video_path: the path to the video to be augmented @param output_path: the path in which the resulting video will be stored. If not passed in, the original video file will be overwritten @param level: the value must be a float value in range -1000.0 to 1000.0, where a negative value removes contrast and a positive value adds contrast @param metadata: if set to be a list, metadata about the function execution including its name, the source & dest duration, fps, etc. will be appended to the inputted list. If set to None, no metadata will be appended or returned @returns: the path to the augmented video
Here is the function:
def contrast(
video_path: str,
output_path: Optional[str] = None,
level: float = 1.0,
metadata: Optional[List[Dict[str, Any]]] = None,
) -> str:
"""
Alters the contrast of a video
@param video_path: the path to the video to be augmented
@param output_path: the path in which the resulting video will be stored.
If not passed in, the original video file will be overwritten
@param level: the value must be a float value in range -1000.0 to 1000.0,
where a negative value removes contrast and a positive value adds contrast
@param metadata: if set to be a list, metadata about the function execution
including its name, the source & dest duration, fps, etc. will be appended
to the inputted list. If set to None, no metadata will be appended or returned
@returns: the path to the augmented video
"""
func_kwargs = helpers.get_func_kwargs(metadata, locals(), video_path)
contrast_aug = af.VideoAugmenterByContrast(level)
contrast_aug.add_augmenter(video_path, output_path)
if metadata is not None:
helpers.get_metadata(metadata=metadata, function_name="contrast", **func_kwargs)
return output_path or video_path | Alters the contrast of a video @param video_path: the path to the video to be augmented @param output_path: the path in which the resulting video will be stored. If not passed in, the original video file will be overwritten @param level: the value must be a float value in range -1000.0 to 1000.0, where a negative value removes contrast and a positive value adds contrast @param metadata: if set to be a list, metadata about the function execution including its name, the source & dest duration, fps, etc. will be appended to the inputted list. If set to None, no metadata will be appended or returned @returns: the path to the augmented video |
160,791 | import functools
import math
import os
import shutil
import tempfile
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
import numpy as np
from augly import audio as audaugs, image as imaugs, utils
from augly.audio import utils as audutils
from augly.video import helpers, utils as vdutils
from augly.video.augmenters import cv2 as ac, ffmpeg as af
The provided code snippet includes necessary dependencies for implementing the `crop` function. Write a Python function `def crop( video_path: str, output_path: Optional[str] = None, left: float = 0.25, top: float = 0.25, right: float = 0.75, bottom: float = 0.75, metadata: Optional[List[Dict[str, Any]]] = None, ) -> str` to solve the following problem:
Crops the video @param video_path: the path to the video to be augmented @param output_path: the path in which the resulting video will be stored. If not passed in, the original video file will be overwritten @param left: left positioning of the crop; between 0 and 1, relative to the video width @param top: top positioning of the crop; between 0 and 1, relative to the video height @param right: right positioning of the crop; between 0 and 1, relative to the video width @param bottom: bottom positioning of the crop; between 0 and 1, relative to the video height @param metadata: if set to be a list, metadata about the function execution including its name, the source & dest duration, fps, etc. will be appended to the inputted list. If set to None, no metadata will be appended or returned @returns: the path to the augmented video
Here is the function:
def crop(
video_path: str,
output_path: Optional[str] = None,
left: float = 0.25,
top: float = 0.25,
right: float = 0.75,
bottom: float = 0.75,
metadata: Optional[List[Dict[str, Any]]] = None,
) -> str:
"""
Crops the video
@param video_path: the path to the video to be augmented
@param output_path: the path in which the resulting video will be stored.
If not passed in, the original video file will be overwritten
@param left: left positioning of the crop; between 0 and 1, relative to
the video width
@param top: top positioning of the crop; between 0 and 1, relative to
the video height
@param right: right positioning of the crop; between 0 and 1, relative to
the video width
@param bottom: bottom positioning of the crop; between 0 and 1, relative to
the video height
@param metadata: if set to be a list, metadata about the function execution
including its name, the source & dest duration, fps, etc. will be appended
to the inputted list. If set to None, no metadata will be appended or returned
@returns: the path to the augmented video
"""
func_kwargs = helpers.get_func_kwargs(metadata, locals(), video_path)
crop_aug = af.VideoAugmenterByCrop(left, top, right, bottom)
crop_aug.add_augmenter(video_path, output_path)
if metadata is not None:
helpers.get_metadata(metadata=metadata, function_name="crop", **func_kwargs)
return output_path or video_path | Crops the video @param video_path: the path to the video to be augmented @param output_path: the path in which the resulting video will be stored. If not passed in, the original video file will be overwritten @param left: left positioning of the crop; between 0 and 1, relative to the video width @param top: top positioning of the crop; between 0 and 1, relative to the video height @param right: right positioning of the crop; between 0 and 1, relative to the video width @param bottom: bottom positioning of the crop; between 0 and 1, relative to the video height @param metadata: if set to be a list, metadata about the function execution including its name, the source & dest duration, fps, etc. will be appended to the inputted list. If set to None, no metadata will be appended or returned @returns: the path to the augmented video |
160,792 | import functools
import math
import os
import shutil
import tempfile
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
import numpy as np
from augly import audio as audaugs, image as imaugs, utils
from augly.audio import utils as audutils
from augly.video import helpers, utils as vdutils
from augly.video.augmenters import cv2 as ac, ffmpeg as af
The provided code snippet includes necessary dependencies for implementing the `encoding_quality` function. Write a Python function `def encoding_quality( video_path: str, output_path: Optional[str] = None, quality: int = 23, metadata: Optional[List[Dict[str, Any]]] = None, ) -> str` to solve the following problem:
Alters the encoding quality of a video @param video_path: the path to the video to be augmented @param output_path: the path in which the resulting video will be stored. If not passed in, the original video file will be overwritten @param quality: CRF scale is 0–51, where 0 is lossless, 23 is the default, and 51 is worst quality possible. A lower value generally leads to higher quality, and a subjectively sane range is 17–28 @param metadata: if set to be a list, metadata about the function execution including its name, the source & dest duration, fps, etc. will be appended to the inputted list. If set to None, no metadata will be appended or returned @returns: the path to the augmented video
Here is the function:
def encoding_quality(
video_path: str,
output_path: Optional[str] = None,
quality: int = 23,
metadata: Optional[List[Dict[str, Any]]] = None,
) -> str:
"""
Alters the encoding quality of a video
@param video_path: the path to the video to be augmented
@param output_path: the path in which the resulting video will be stored.
If not passed in, the original video file will be overwritten
@param quality: CRF scale is 0–51, where 0 is lossless, 23 is the default,
and 51 is worst quality possible. A lower value generally leads to higher
quality, and a subjectively sane range is 17–28
@param metadata: if set to be a list, metadata about the function execution
including its name, the source & dest duration, fps, etc. will be appended
to the inputted list. If set to None, no metadata will be appended or returned
@returns: the path to the augmented video
"""
func_kwargs = helpers.get_func_kwargs(metadata, locals(), video_path)
encoding_aug = af.VideoAugmenterByQuality(quality)
encoding_aug.add_augmenter(video_path, output_path)
if metadata is not None:
helpers.get_metadata(
metadata=metadata, function_name="encoding_quality", **func_kwargs
)
return output_path or video_path | Alters the encoding quality of a video @param video_path: the path to the video to be augmented @param output_path: the path in which the resulting video will be stored. If not passed in, the original video file will be overwritten @param quality: CRF scale is 0–51, where 0 is lossless, 23 is the default, and 51 is worst quality possible. A lower value generally leads to higher quality, and a subjectively sane range is 17–28 @param metadata: if set to be a list, metadata about the function execution including its name, the source & dest duration, fps, etc. will be appended to the inputted list. If set to None, no metadata will be appended or returned @returns: the path to the augmented video |
160,793 | import functools
import math
import os
import shutil
import tempfile
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
import numpy as np
from augly import audio as audaugs, image as imaugs, utils
from augly.audio import utils as audutils
from augly.video import helpers, utils as vdutils
from augly.video.augmenters import cv2 as ac, ffmpeg as af
The provided code snippet includes necessary dependencies for implementing the `fps` function. Write a Python function `def fps( video_path: str, output_path: Optional[str] = None, fps: int = 15, metadata: Optional[List[Dict[str, Any]]] = None, ) -> str` to solve the following problem:
Alters the FPS of a video @param video_path: the path to the video to be augmented @param output_path: the path in which the resulting video will be stored. If not passed in, the original video file will be overwritten @param fps: the desired output frame rate. Note that a FPS value greater than the original FPS of the video will result in an unaltered video @param metadata: if set to be a list, metadata about the function execution including its name, the source & dest duration, fps, etc. will be appended to the inputted list. If set to None, no metadata will be appended or returned @returns: the path to the augmented video
Here is the function:
def fps(
video_path: str,
output_path: Optional[str] = None,
fps: int = 15,
metadata: Optional[List[Dict[str, Any]]] = None,
) -> str:
"""
Alters the FPS of a video
@param video_path: the path to the video to be augmented
@param output_path: the path in which the resulting video will be stored.
If not passed in, the original video file will be overwritten
@param fps: the desired output frame rate. Note that a FPS value greater than
the original FPS of the video will result in an unaltered video
@param metadata: if set to be a list, metadata about the function execution
including its name, the source & dest duration, fps, etc. will be appended
to the inputted list. If set to None, no metadata will be appended or returned
@returns: the path to the augmented video
"""
func_kwargs = helpers.get_func_kwargs(metadata, locals(), video_path)
fps_aug = af.VideoAugmenterByFPSChange(fps)
fps_aug.add_augmenter(video_path, output_path)
if metadata is not None:
helpers.get_metadata(metadata=metadata, function_name="fps", **func_kwargs)
return output_path or video_path | Alters the FPS of a video @param video_path: the path to the video to be augmented @param output_path: the path in which the resulting video will be stored. If not passed in, the original video file will be overwritten @param fps: the desired output frame rate. Note that a FPS value greater than the original FPS of the video will result in an unaltered video @param metadata: if set to be a list, metadata about the function execution including its name, the source & dest duration, fps, etc. will be appended to the inputted list. If set to None, no metadata will be appended or returned @returns: the path to the augmented video |
160,794 | import functools
import math
import os
import shutil
import tempfile
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
import numpy as np
from augly import audio as audaugs, image as imaugs, utils
from augly.audio import utils as audutils
from augly.video import helpers, utils as vdutils
from augly.video.augmenters import cv2 as ac, ffmpeg as af
The provided code snippet includes necessary dependencies for implementing the `grayscale` function. Write a Python function `def grayscale( video_path: str, output_path: Optional[str] = None, metadata: Optional[List[Dict[str, Any]]] = None, ) -> str` to solve the following problem:
Changes a video to be grayscale @param video_path: the path to the video to be augmented @param output_path: the path in which the resulting video will be stored. If not passed in, the original video file will be overwritten @param metadata: if set to be a list, metadata about the function execution including its name, the source & dest duration, fps, etc. will be appended to the inputted list. If set to None, no metadata will be appended or returned @returns: the path to the augmented video
Here is the function:
def grayscale(
video_path: str,
output_path: Optional[str] = None,
metadata: Optional[List[Dict[str, Any]]] = None,
) -> str:
"""
Changes a video to be grayscale
@param video_path: the path to the video to be augmented
@param output_path: the path in which the resulting video will be stored.
If not passed in, the original video file will be overwritten
@param metadata: if set to be a list, metadata about the function execution
including its name, the source & dest duration, fps, etc. will be appended
to the inputted list. If set to None, no metadata will be appended or returned
@returns: the path to the augmented video
"""
func_kwargs = helpers.get_func_kwargs(metadata, locals(), video_path)
grayscale_aug = af.VideoAugmenterByGrayscale()
grayscale_aug.add_augmenter(video_path, output_path)
if metadata is not None:
helpers.get_metadata(
metadata=metadata, function_name="grayscale", **func_kwargs
)
return output_path or video_path | Changes a video to be grayscale @param video_path: the path to the video to be augmented @param output_path: the path in which the resulting video will be stored. If not passed in, the original video file will be overwritten @param metadata: if set to be a list, metadata about the function execution including its name, the source & dest duration, fps, etc. will be appended to the inputted list. If set to None, no metadata will be appended or returned @returns: the path to the augmented video |
160,795 | import functools
import math
import os
import shutil
import tempfile
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
import numpy as np
from augly import audio as audaugs, image as imaugs, utils
from augly.audio import utils as audutils
from augly.video import helpers, utils as vdutils
from augly.video.augmenters import cv2 as ac, ffmpeg as af
The provided code snippet includes necessary dependencies for implementing the `hflip` function. Write a Python function `def hflip( video_path: str, output_path: Optional[str] = None, metadata: Optional[List[Dict[str, Any]]] = None, ) -> str` to solve the following problem:
Horizontally flips a video @param video_path: the path to the video to be augmented @param output_path: the path in which the resulting video will be stored. If not passed in, the original video file will be overwritten @param metadata: if set to be a list, metadata about the function execution including its name, the source & dest duration, fps, etc. will be appended to the inputted list. If set to None, no metadata will be appended or returned @returns: the path to the augmented video
Here is the function:
def hflip(
video_path: str,
output_path: Optional[str] = None,
metadata: Optional[List[Dict[str, Any]]] = None,
) -> str:
"""
Horizontally flips a video
@param video_path: the path to the video to be augmented
@param output_path: the path in which the resulting video will be stored.
If not passed in, the original video file will be overwritten
@param metadata: if set to be a list, metadata about the function execution
including its name, the source & dest duration, fps, etc. will be appended
to the inputted list. If set to None, no metadata will be appended or returned
@returns: the path to the augmented video
"""
func_kwargs = helpers.get_func_kwargs(metadata, locals(), video_path)
hflip_aug = af.VideoAugmenterByHFlip()
hflip_aug.add_augmenter(video_path, output_path)
if metadata is not None:
helpers.get_metadata(metadata=metadata, function_name="hflip", **func_kwargs)
return output_path or video_path | Horizontally flips a video @param video_path: the path to the video to be augmented @param output_path: the path in which the resulting video will be stored. If not passed in, the original video file will be overwritten @param metadata: if set to be a list, metadata about the function execution including its name, the source & dest duration, fps, etc. will be appended to the inputted list. If set to None, no metadata will be appended or returned @returns: the path to the augmented video |
160,796 | import functools
import math
import os
import shutil
import tempfile
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
import numpy as np
from augly import audio as audaugs, image as imaugs, utils
from augly.audio import utils as audutils
from augly.video import helpers, utils as vdutils
from augly.video.augmenters import cv2 as ac, ffmpeg as af
The provided code snippet includes necessary dependencies for implementing the `hstack` function. Write a Python function `def hstack( video_path: str, second_video_path: str, output_path: Optional[str] = None, use_second_audio: bool = False, metadata: Optional[List[Dict[str, Any]]] = None, ) -> str` to solve the following problem:
Horizontally stacks two videos @param video_path: the path to the video that will be stacked to the left @param second_video_path: the path to the video that will be stacked to the right @param output_path: the path in which the resulting video will be stored. If not passed in, the original video file will be overwritten @param use_second_audio: if set to True, the audio of the right video will be used instead of the left's @param metadata: if set to be a list, metadata about the function execution including its name, the source & dest duration, fps, etc. will be appended to the inputted list. If set to None, no metadata will be appended or returned @returns: the path to the augmented video
Here is the function:
def hstack(
video_path: str,
second_video_path: str,
output_path: Optional[str] = None,
use_second_audio: bool = False,
metadata: Optional[List[Dict[str, Any]]] = None,
) -> str:
"""
Horizontally stacks two videos
@param video_path: the path to the video that will be stacked to the left
@param second_video_path: the path to the video that will be stacked to the right
@param output_path: the path in which the resulting video will be stored.
If not passed in, the original video file will be overwritten
@param use_second_audio: if set to True, the audio of the right video will be
used instead of the left's
@param metadata: if set to be a list, metadata about the function execution
including its name, the source & dest duration, fps, etc. will be appended
to the inputted list. If set to None, no metadata will be appended or returned
@returns: the path to the augmented video
"""
func_kwargs = helpers.get_func_kwargs(metadata, locals(), video_path)
hstack_aug = af.VideoAugmenterByStack(second_video_path, use_second_audio, "hstack")
hstack_aug.add_augmenter(video_path, output_path)
if metadata is not None:
helpers.get_metadata(metadata=metadata, function_name="hstack", **func_kwargs)
return output_path or video_path | Horizontally stacks two videos @param video_path: the path to the video that will be stacked to the left @param second_video_path: the path to the video that will be stacked to the right @param output_path: the path in which the resulting video will be stored. If not passed in, the original video file will be overwritten @param use_second_audio: if set to True, the audio of the right video will be used instead of the left's @param metadata: if set to be a list, metadata about the function execution including its name, the source & dest duration, fps, etc. will be appended to the inputted list. If set to None, no metadata will be appended or returned @returns: the path to the augmented video |
160,797 | import functools
import math
import os
import shutil
import tempfile
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
import numpy as np
from augly import audio as audaugs, image as imaugs, utils
from augly.audio import utils as audutils
from augly.video import helpers, utils as vdutils
from augly.video.augmenters import cv2 as ac, ffmpeg as af
def concat(
video_paths: List[str],
output_path: Optional[str] = None,
src_video_path_index: int = 0,
transition: Optional[af.TransitionConfig] = None,
metadata: Optional[List[Dict[str, Any]]] = None,
) -> str:
"""
Concatenates videos together. Resizes all other videos to the size of the
`source` video (video_paths[src_video_path_index]), and modifies the sample
aspect ratios to match (ffmpeg will fail to concat if SARs don't match)
If not passed in, the original video file will be overwritten
the list `video_paths` should be considered the `source` or original video
including its name, the source & dest duration, fps, etc. will be appended
to the inputted list. If set to None, no metadata will be appended or returned
"""
func_kwargs = helpers.get_func_kwargs(
metadata, locals(), video_paths[src_video_path_index]
)
concat_aug = af.VideoAugmenterByConcat(
video_paths,
src_video_path_index,
transition,
)
concat_aug.add_augmenter(video_paths[src_video_path_index], output_path)
if metadata is not None:
helpers.get_metadata(
metadata=metadata,
function_name="concat",
video_path=video_paths[src_video_path_index],
**func_kwargs,
)
return output_path or video_paths[src_video_path_index]
def loop(
video_path: str,
output_path: Optional[str] = None,
num_loops: int = 0,
metadata: Optional[List[Dict[str, Any]]] = None,
) -> str:
"""
Loops a video `num_loops` times
If not passed in, the original video file will be overwritten
will play once (i.e. no loops)
including its name, the source & dest duration, fps, etc. will be appended
to the inputted list. If set to None, no metadata will be appended or returned
"""
func_kwargs = helpers.get_func_kwargs(metadata, locals(), video_path)
loop_aug = af.VideoAugmenterByLoops(num_loops)
loop_aug.add_augmenter(video_path, output_path)
if metadata is not None:
helpers.get_metadata(metadata=metadata, function_name="loop", **func_kwargs)
return output_path or video_path
def resize(
video_path: str,
output_path: Optional[str] = None,
height: Union[int, str] = "ih",
width: Union[int, str] = "iw",
metadata: Optional[List[Dict[str, Any]]] = None,
) -> str:
"""
Resizes a video
If not passed in, the original video file will be overwritten
the original video height will be used
the original video width will be used
including its name, the source & dest duration, fps, etc. will be appended
to the inputted list. If set to None, no metadata will be appended or returned
"""
func_kwargs = helpers.get_func_kwargs(metadata, locals(), video_path)
resize_aug = af.VideoAugmenterByResize(height, width)
resize_aug.add_augmenter(video_path, output_path)
if metadata is not None:
helpers.get_metadata(metadata=metadata, function_name="resize", **func_kwargs)
return output_path or video_path
def trim(
video_path: str,
output_path: Optional[str] = None,
start: Optional[float] = None,
end: Optional[float] = None,
metadata: Optional[List[Dict[str, Any]]] = None,
) -> str:
"""
Trims the video using the specified start and end parameters
If not passed in, the original video file will be overwritten
If None, start will be 0
If None, the end will be the duration of the video
including its name, the source & dest duration, fps, etc. will be appended
to the inputted list. If set to None, no metadata will be appended or returned
"""
func_kwargs = helpers.get_func_kwargs(metadata, locals(), video_path)
trim_aug = af.VideoAugmenterByTrim(start=start, end=end)
trim_aug.add_augmenter(video_path, output_path)
if metadata is not None:
helpers.get_metadata(metadata=metadata, function_name="trim", **func_kwargs)
return output_path or video_path
The provided code snippet includes necessary dependencies for implementing the `insert_in_background` function. Write a Python function `def insert_in_background( video_path: str, output_path: Optional[str] = None, background_path: Optional[str] = None, offset_factor: float = 0.0, source_percentage: Optional[float] = None, seed: Optional[int] = None, transition: Optional[af.TransitionConfig] = None, metadata: Optional[List[Dict[str, Any]]] = None, ) -> str` to solve the following problem:
Puts the video in the middle of the background video (at offset_factor * background.duration) @param video_path: the path to the video to be augmented @param output_path: the path in which the resulting video will be stored. If not passed in, the original video file will be overwritten @param background_path: the path to the video in which to insert the main video. If set to None, the main video will play in the middle of a silent video with black frames @param offset_factor: the point in the background video in which the main video starts to play (this factor is multiplied by the background video duration to determine the start point) @param source_percentage: when set, source_percentage of the duration of the final video (background + source) will be taken up by the source video. Randomly crops the background video to the correct duration. If the background video isn't long enough to get the desired source_percentage, it will be looped. @param seed: if provided, this will set the random seed to ensure consistency between runs @param transition: optional transition configuration to apply between the clips @param metadata: if set to be a list, metadata about the function execution including its name, the source & dest duration, fps, etc. will be appended to the inputted list. If set to None, no metadata will be appended or returned @returns: the path to the augmented video
Here is the function:
def insert_in_background(
video_path: str,
output_path: Optional[str] = None,
background_path: Optional[str] = None,
offset_factor: float = 0.0,
source_percentage: Optional[float] = None,
seed: Optional[int] = None,
transition: Optional[af.TransitionConfig] = None,
metadata: Optional[List[Dict[str, Any]]] = None,
) -> str:
"""
Puts the video in the middle of the background video
(at offset_factor * background.duration)
@param video_path: the path to the video to be augmented
@param output_path: the path in which the resulting video will be stored.
If not passed in, the original video file will be overwritten
@param background_path: the path to the video in which to insert the main
video. If set to None, the main video will play in the middle of a silent
video with black frames
@param offset_factor: the point in the background video in which the main video
starts to play (this factor is multiplied by the background video duration to
determine the start point)
@param source_percentage: when set, source_percentage of the duration
of the final video (background + source) will be taken up by the
source video. Randomly crops the background video to the correct duration.
If the background video isn't long enough to get the desired source_percentage,
it will be looped.
@param seed: if provided, this will set the random seed to ensure consistency
between runs
@param transition: optional transition configuration to apply between the clips
@param metadata: if set to be a list, metadata about the function execution including
its name, the source & dest duration, fps, etc. will be appended to the inputted
list. If set to None, no metadata will be appended or returned
@returns: the path to the augmented video
"""
assert (
0.0 <= offset_factor <= 1.0
), "Offset factor must be a value in the range [0.0, 1.0]"
if source_percentage is not None:
assert (
0.0 <= source_percentage <= 1.0
), "Source percentage must be a value in the range [0.0, 1.0]"
func_kwargs = helpers.get_func_kwargs(metadata, locals(), video_path)
local_path = utils.pathmgr.get_local_path(video_path)
utils.validate_video_path(local_path)
video_info = helpers.get_video_info(local_path)
video_duration = float(video_info["duration"])
width, height = video_info["width"], video_info["height"]
rng = np.random.RandomState(seed) if seed is not None else np.random
video_paths = []
with tempfile.TemporaryDirectory() as tmpdir:
tmp_video_path = os.path.join(tmpdir, "in.mp4")
resized_bg_path = os.path.join(tmpdir, "bg.mp4")
helpers.add_silent_audio(video_path, tmp_video_path)
if background_path is None:
helpers.create_color_video(resized_bg_path, video_duration, height, width)
else:
resize(background_path, resized_bg_path, height, width)
bg_video_info = helpers.get_video_info(resized_bg_path)
bg_video_duration = float(bg_video_info["duration"])
bg_start = 0
bg_end = bg_video_duration
desired_bg_duration = bg_video_duration
if source_percentage is not None:
# desired relationship: percent * (bg_len + s_len) = s_len
# solve for bg_len -> bg_len = s_len / percent - s_len
desired_bg_duration = video_duration / source_percentage - video_duration
# if background vid isn't long enough, loop
num_loops_needed = math.ceil(desired_bg_duration / bg_video_duration)
if num_loops_needed > 1:
loop(resized_bg_path, num_loops=num_loops_needed)
bg_video_duration *= num_loops_needed
bg_start = rng.uniform(0, bg_video_duration - desired_bg_duration)
bg_end = bg_start + desired_bg_duration
offset = desired_bg_duration * offset_factor
transition_before = False
if offset > 0:
before_path = os.path.join(tmpdir, "before.mp4")
trim(resized_bg_path, before_path, start=bg_start, end=bg_start + offset)
video_paths.append(before_path)
src_video_path_index = 1
transition_before = True
else:
src_video_path_index = 0
video_paths.append(tmp_video_path)
transition_after = False
if bg_start + offset < bg_end:
after_path = os.path.join(tmpdir, "after.mp4")
trim(resized_bg_path, after_path, start=bg_start + offset, end=bg_end)
video_paths.append(after_path)
transition_after = True
concat(
video_paths,
output_path or video_path,
src_video_path_index,
transition=transition,
)
if metadata is not None:
helpers.get_metadata(
metadata=metadata,
function_name="insert_in_background",
background_video_duration=desired_bg_duration,
transition_before=transition_before,
transition_after=transition_after,
**func_kwargs,
)
return output_path or video_path | Puts the video in the middle of the background video (at offset_factor * background.duration) @param video_path: the path to the video to be augmented @param output_path: the path in which the resulting video will be stored. If not passed in, the original video file will be overwritten @param background_path: the path to the video in which to insert the main video. If set to None, the main video will play in the middle of a silent video with black frames @param offset_factor: the point in the background video in which the main video starts to play (this factor is multiplied by the background video duration to determine the start point) @param source_percentage: when set, source_percentage of the duration of the final video (background + source) will be taken up by the source video. Randomly crops the background video to the correct duration. If the background video isn't long enough to get the desired source_percentage, it will be looped. @param seed: if provided, this will set the random seed to ensure consistency between runs @param transition: optional transition configuration to apply between the clips @param metadata: if set to be a list, metadata about the function execution including its name, the source & dest duration, fps, etc. will be appended to the inputted list. If set to None, no metadata will be appended or returned @returns: the path to the augmented video |
160,798 | import functools
import math
import os
import shutil
import tempfile
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
import numpy as np
from augly import audio as audaugs, image as imaugs, utils
from augly.audio import utils as audutils
from augly.video import helpers, utils as vdutils
from augly.video.augmenters import cv2 as ac, ffmpeg as af
def concat(
video_paths: List[str],
output_path: Optional[str] = None,
src_video_path_index: int = 0,
transition: Optional[af.TransitionConfig] = None,
metadata: Optional[List[Dict[str, Any]]] = None,
) -> str:
"""
Concatenates videos together. Resizes all other videos to the size of the
`source` video (video_paths[src_video_path_index]), and modifies the sample
aspect ratios to match (ffmpeg will fail to concat if SARs don't match)
If not passed in, the original video file will be overwritten
the list `video_paths` should be considered the `source` or original video
including its name, the source & dest duration, fps, etc. will be appended
to the inputted list. If set to None, no metadata will be appended or returned
"""
func_kwargs = helpers.get_func_kwargs(
metadata, locals(), video_paths[src_video_path_index]
)
concat_aug = af.VideoAugmenterByConcat(
video_paths,
src_video_path_index,
transition,
)
concat_aug.add_augmenter(video_paths[src_video_path_index], output_path)
if metadata is not None:
helpers.get_metadata(
metadata=metadata,
function_name="concat",
video_path=video_paths[src_video_path_index],
**func_kwargs,
)
return output_path or video_paths[src_video_path_index]
def loop(
video_path: str,
output_path: Optional[str] = None,
num_loops: int = 0,
metadata: Optional[List[Dict[str, Any]]] = None,
) -> str:
"""
Loops a video `num_loops` times
If not passed in, the original video file will be overwritten
will play once (i.e. no loops)
including its name, the source & dest duration, fps, etc. will be appended
to the inputted list. If set to None, no metadata will be appended or returned
"""
func_kwargs = helpers.get_func_kwargs(metadata, locals(), video_path)
loop_aug = af.VideoAugmenterByLoops(num_loops)
loop_aug.add_augmenter(video_path, output_path)
if metadata is not None:
helpers.get_metadata(metadata=metadata, function_name="loop", **func_kwargs)
return output_path or video_path
def trim(
video_path: str,
output_path: Optional[str] = None,
start: Optional[float] = None,
end: Optional[float] = None,
metadata: Optional[List[Dict[str, Any]]] = None,
) -> str:
"""
Trims the video using the specified start and end parameters
If not passed in, the original video file will be overwritten
If None, start will be 0
If None, the end will be the duration of the video
including its name, the source & dest duration, fps, etc. will be appended
to the inputted list. If set to None, no metadata will be appended or returned
"""
func_kwargs = helpers.get_func_kwargs(metadata, locals(), video_path)
trim_aug = af.VideoAugmenterByTrim(start=start, end=end)
trim_aug.add_augmenter(video_path, output_path)
if metadata is not None:
helpers.get_metadata(metadata=metadata, function_name="trim", **func_kwargs)
return output_path or video_path
The provided code snippet includes necessary dependencies for implementing the `insert_in_background_multiple` function. Write a Python function `def insert_in_background_multiple( video_path: str, output_path: str, background_path: str, src_ids: List[str], additional_video_paths: List[str], seed: Optional[int] = None, min_source_segment_duration: float = 5.0, max_source_segment_duration: float = 20.0, min_background_segment_duration: float = 2.0, min_result_video_duration: float = 30.0, max_result_video_duration: float = 60.0, transition: Optional[af.TransitionConfig] = None, metadata: Optional[List[Dict[str, Any]]] = None, ) -> str` to solve the following problem:
Places the video (and the additional videos) in the middle of the background video. @param video_path: the path of the main video to be augmented. @param output_path: the path in which the output video will be stored. @param background_path: the path of the video in which to insert the main (and additional) video. @param src_ids: the list of identifiers for the main video and additional videos. @param additional_video_paths: list of additional video paths to be inserted alongside the main video; one clip from each of the input videos will be inserted in order. @param seed: if provided, this will set the random seed to ensure consistency between runs. @param min_source_segment_duration: minimum duration in seconds of the source segments that will be inserted in the background video. @param max_source_segment_duration: maximum duration in seconds of the source segments that will be inserted in the background video. @param min_background_segment_duration: minimum duration in seconds of a background segment. @param min_result_video_duration: minimum duration in seconds of the output video. @param max_result_video_duration: maximum duration in seconds of the output video. @param transition: optional transition configuration to apply between the clips. @param metadata: if set to be a list, metadata about the function execution including its name, the source & dest duration, fps, etc. will be appended to the inputted list. If set to None, no metadata will be appended or returned @returns: the path to the augmented video
Here is the function:
def insert_in_background_multiple(
video_path: str,
output_path: str,
background_path: str,
src_ids: List[str],
additional_video_paths: List[str],
seed: Optional[int] = None,
min_source_segment_duration: float = 5.0,
max_source_segment_duration: float = 20.0,
min_background_segment_duration: float = 2.0,
min_result_video_duration: float = 30.0,
max_result_video_duration: float = 60.0,
transition: Optional[af.TransitionConfig] = None,
metadata: Optional[List[Dict[str, Any]]] = None,
) -> str:
"""
Places the video (and the additional videos) in the middle of the background video.
@param video_path: the path of the main video to be augmented.
@param output_path: the path in which the output video will be stored.
@param background_path: the path of the video in which to insert the main
(and additional) video.
@param src_ids: the list of identifiers for the main video and additional videos.
@param additional_video_paths: list of additional video paths to be
inserted alongside the main video; one clip from each of the input
videos will be inserted in order.
@param seed: if provided, this will set the random seed to ensure consistency
between runs.
@param min_source_segment_duration: minimum duration in seconds of the source
segments that will be inserted in the background video.
@param max_source_segment_duration: maximum duration in seconds of the source
segments that will be inserted in the background video.
@param min_background_segment_duration: minimum duration in seconds of a background segment.
@param min_result_video_duration: minimum duration in seconds of the output video.
@param max_result_video_duration: maximum duration in seconds of the output video.
@param transition: optional transition configuration to apply between the clips.
@param metadata: if set to be a list, metadata about the function execution including
its name, the source & dest duration, fps, etc. will be appended to the inputted
list. If set to None, no metadata will be appended or returned
@returns: the path to the augmented video
"""
if additional_video_paths:
assert len(additional_video_paths) + 1 == len(
src_ids
), "src_ids need to be specified for the main video and all additional videos."
func_kwargs = helpers.get_func_kwargs(metadata, locals(), video_path)
rng = np.random.RandomState(seed) if seed is not None else np.random
local_path = utils.pathmgr.get_local_path(video_path)
additional_local_paths = (
[utils.pathmgr.get_local_path(p) for p in additional_video_paths]
if additional_video_paths
else []
)
bkg_local_path = utils.pathmgr.get_local_path(background_path)
src_paths = [
local_path,
] + additional_local_paths
src_video_durations = np.array(
[float(helpers.get_video_info(v)["duration"]) for v in src_paths]
)
bkg_duration = float(helpers.get_video_info(bkg_local_path)["duration"])
src_segment_durations = (
rng.random_sample(len(src_video_durations))
* (max_source_segment_duration - min_source_segment_duration)
+ min_source_segment_duration
)
src_segment_durations = np.minimum(src_segment_durations, src_video_durations)
src_segment_starts = rng.random(len(src_video_durations)) * (
src_video_durations - src_segment_durations
)
src_segment_ends = src_segment_starts + src_segment_durations
sum_src_duration = np.sum(src_segment_durations)
required_result_duration = (
len(src_segment_durations) + 1
) * min_background_segment_duration + sum_src_duration
if required_result_duration > max_result_video_duration:
raise ValueError(
"Failed to generate config for source segments in insert_in_background_multiple."
)
duration_budget = max_result_video_duration - required_result_duration
bkg_budget = rng.random() * duration_budget
overall_bkg_needed_duration = (
len(src_segment_durations) + 1
) * min_background_segment_duration + bkg_budget
num_loops_needed = 0
if overall_bkg_needed_duration > bkg_duration:
num_loops_needed = math.ceil(overall_bkg_needed_duration / bkg_duration)
# Now sample insertion points by picking len(src_segment_durations) points in the interval [0, bkg_budget)
# Then sort the segments and add spacing for the minimum background segment duration.
bkg_insertion_points = (
np.sort(rng.random(len(src_segment_durations)) * bkg_budget)
+ np.arange(len(src_segment_durations)) * min_background_segment_duration
)
last_bkg_point = overall_bkg_needed_duration
dst_starts = bkg_insertion_points + np.concatenate(
(
[
0.0,
],
np.cumsum(src_segment_durations)[:-1],
)
)
# Start applying transforms.
with tempfile.TemporaryDirectory() as tmpdir:
# First, loop through background video if needed.
if num_loops_needed > 0:
buf = os.path.join(tmpdir, "bkg_loop.mp4")
loop(bkg_local_path, buf, num_loops=num_loops_needed)
bkg_path = buf
else:
bkg_path = bkg_local_path
bkg_videos = []
# Sample background segments.
prev = 0.0
for i, pt in enumerate(bkg_insertion_points):
out_path = os.path.join(tmpdir, f"bkg_{i}.mp4")
trim(bkg_path, out_path, start=prev, end=pt)
prev = pt
bkg_videos.append(out_path)
# last background segment
last_bkg_path = os.path.join(tmpdir, "bkg_last.mp4")
trim(bkg_path, last_bkg_path, start=prev, end=last_bkg_point)
src_videos = []
# Sample source segments.
for i, seg in enumerate(zip(src_segment_starts, src_segment_ends)):
out_path = os.path.join(tmpdir, f"src_{i}.mp4")
trim(src_paths[i], out_path, start=seg[0], end=seg[1])
src_videos.append(out_path)
all_videos = [v for pair in zip(bkg_videos, src_videos) for v in pair] + [
last_bkg_path,
]
concat(all_videos, output_path, 1, transition=transition)
if metadata is not None:
helpers.get_metadata(
metadata=metadata,
function_name="insert_in_background_multiple",
src_segment_starts=src_segment_starts,
src_segment_ends=src_segment_ends,
bkg_insertion_points=bkg_insertion_points,
**func_kwargs,
)
return output_path | Places the video (and the additional videos) in the middle of the background video. @param video_path: the path of the main video to be augmented. @param output_path: the path in which the output video will be stored. @param background_path: the path of the video in which to insert the main (and additional) video. @param src_ids: the list of identifiers for the main video and additional videos. @param additional_video_paths: list of additional video paths to be inserted alongside the main video; one clip from each of the input videos will be inserted in order. @param seed: if provided, this will set the random seed to ensure consistency between runs. @param min_source_segment_duration: minimum duration in seconds of the source segments that will be inserted in the background video. @param max_source_segment_duration: maximum duration in seconds of the source segments that will be inserted in the background video. @param min_background_segment_duration: minimum duration in seconds of a background segment. @param min_result_video_duration: minimum duration in seconds of the output video. @param max_result_video_duration: maximum duration in seconds of the output video. @param transition: optional transition configuration to apply between the clips. @param metadata: if set to be a list, metadata about the function execution including its name, the source & dest duration, fps, etc. will be appended to the inputted list. If set to None, no metadata will be appended or returned @returns: the path to the augmented video |
160,799 | import functools
import math
import os
import shutil
import tempfile
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
import numpy as np
from augly import audio as audaugs, image as imaugs, utils
from augly.audio import utils as audutils
from augly.video import helpers, utils as vdutils
from augly.video.augmenters import cv2 as ac, ffmpeg as af
def concat(
video_paths: List[str],
output_path: Optional[str] = None,
src_video_path_index: int = 0,
transition: Optional[af.TransitionConfig] = None,
metadata: Optional[List[Dict[str, Any]]] = None,
) -> str:
"""
Concatenates videos together. Resizes all other videos to the size of the
`source` video (video_paths[src_video_path_index]), and modifies the sample
aspect ratios to match (ffmpeg will fail to concat if SARs don't match)
If not passed in, the original video file will be overwritten
the list `video_paths` should be considered the `source` or original video
including its name, the source & dest duration, fps, etc. will be appended
to the inputted list. If set to None, no metadata will be appended or returned
"""
func_kwargs = helpers.get_func_kwargs(
metadata, locals(), video_paths[src_video_path_index]
)
concat_aug = af.VideoAugmenterByConcat(
video_paths,
src_video_path_index,
transition,
)
concat_aug.add_augmenter(video_paths[src_video_path_index], output_path)
if metadata is not None:
helpers.get_metadata(
metadata=metadata,
function_name="concat",
video_path=video_paths[src_video_path_index],
**func_kwargs,
)
return output_path or video_paths[src_video_path_index]
def loop(
video_path: str,
output_path: Optional[str] = None,
num_loops: int = 0,
metadata: Optional[List[Dict[str, Any]]] = None,
) -> str:
"""
Loops a video `num_loops` times
If not passed in, the original video file will be overwritten
will play once (i.e. no loops)
including its name, the source & dest duration, fps, etc. will be appended
to the inputted list. If set to None, no metadata will be appended or returned
"""
func_kwargs = helpers.get_func_kwargs(metadata, locals(), video_path)
loop_aug = af.VideoAugmenterByLoops(num_loops)
loop_aug.add_augmenter(video_path, output_path)
if metadata is not None:
helpers.get_metadata(metadata=metadata, function_name="loop", **func_kwargs)
return output_path or video_path
def resize(
video_path: str,
output_path: Optional[str] = None,
height: Union[int, str] = "ih",
width: Union[int, str] = "iw",
metadata: Optional[List[Dict[str, Any]]] = None,
) -> str:
"""
Resizes a video
If not passed in, the original video file will be overwritten
the original video height will be used
the original video width will be used
including its name, the source & dest duration, fps, etc. will be appended
to the inputted list. If set to None, no metadata will be appended or returned
"""
func_kwargs = helpers.get_func_kwargs(metadata, locals(), video_path)
resize_aug = af.VideoAugmenterByResize(height, width)
resize_aug.add_augmenter(video_path, output_path)
if metadata is not None:
helpers.get_metadata(metadata=metadata, function_name="resize", **func_kwargs)
return output_path or video_path
def trim(
video_path: str,
output_path: Optional[str] = None,
start: Optional[float] = None,
end: Optional[float] = None,
metadata: Optional[List[Dict[str, Any]]] = None,
) -> str:
"""
Trims the video using the specified start and end parameters
If not passed in, the original video file will be overwritten
If None, start will be 0
If None, the end will be the duration of the video
including its name, the source & dest duration, fps, etc. will be appended
to the inputted list. If set to None, no metadata will be appended or returned
"""
func_kwargs = helpers.get_func_kwargs(metadata, locals(), video_path)
trim_aug = af.VideoAugmenterByTrim(start=start, end=end)
trim_aug.add_augmenter(video_path, output_path)
if metadata is not None:
helpers.get_metadata(metadata=metadata, function_name="trim", **func_kwargs)
return output_path or video_path
The provided code snippet includes necessary dependencies for implementing the `replace_with_background` function. Write a Python function `def replace_with_background( video_path: str, output_path: Optional[str] = None, background_path: Optional[str] = None, source_offset: float = 0.0, background_offset: float = 0.0, source_percentage: float = 0.5, transition: Optional[af.TransitionConfig] = None, metadata: Optional[List[Dict[str, Any]]] = None, ) -> str` to solve the following problem:
Replaces the beginning and end of the source video with the background video, keeping the total duration of the output video equal to the original duration of the source video @param video_path: the path to the video to be augmented @param output_path: the path in which the resulting video will be stored. If not passed in, the original video file will be overwritten @param background_path: the path to the video in which to insert the main video. If set to None, the main video will play in the middle of a silent video with black frames @param source_offset: the starting point where the background video transitions to the source video. Prior to this point, the source video is replaced with the background video. A value of 0 means all background is at the beginning. A value of 1 means all background is at the end of the video @param background_offset: the starting point from which the background video starts to play, as a proportion of the background video duration (i.e. this factor is multiplied by the background video duration to determine the start point) @param source_percentage: the percentage of the source video that remains unreplaced by the background video. The source percentage plus source offset should be less than 1. If it is greater, the output video duration will be longer than the source. If the background video is not long enough to get the desired source percentage, it will be looped @param transition: optional transition configuration to apply between the clips @param metadata: if set to be a list, metadata about the function execution including its name, the source & dest duration, fps, etc. will be appended to the inputted list. If set to None, no metadata will be appended or returned @returns: the path to the augmented video
Here is the function:
def replace_with_background(
video_path: str,
output_path: Optional[str] = None,
background_path: Optional[str] = None,
source_offset: float = 0.0,
background_offset: float = 0.0,
source_percentage: float = 0.5,
transition: Optional[af.TransitionConfig] = None,
metadata: Optional[List[Dict[str, Any]]] = None,
) -> str:
"""
Replaces the beginning and end of the source video with the background video, keeping the
total duration of the output video equal to the original duration of the source video
@param video_path: the path to the video to be augmented
@param output_path: the path in which the resulting video will be stored. If not
passed in, the original video file will be overwritten
@param background_path: the path to the video in which to insert the main video.
If set to None, the main video will play in the middle of a silent video with
black frames
@param source_offset: the starting point where the background video transitions to
the source video. Prior to this point, the source video is replaced with the
background video. A value of 0 means all background is at the beginning. A value
of 1 means all background is at the end of the video
@param background_offset: the starting point from which the background video starts
to play, as a proportion of the background video duration (i.e. this factor is
multiplied by the background video duration to determine the start point)
@param source_percentage: the percentage of the source video that remains unreplaced
by the background video. The source percentage plus source offset should be less
than 1. If it is greater, the output video duration will be longer than the source.
If the background video is not long enough to get the desired source percentage,
it will be looped
@param transition: optional transition configuration to apply between the clips
@param metadata: if set to be a list, metadata about the function execution including
its name, the source & dest duration, fps, etc. will be appended to the inputted
list. If set to None, no metadata will be appended or returned
@returns: the path to the augmented video
"""
assert (
0.0 <= source_offset <= 1.0
), "Source offset factor must be a value in the range [0.0, 1.0]"
assert (
0.0 <= background_offset <= 1.0
), "Background offset factor must be a value in the range [0.0, 1.0]"
assert (
0.0 <= source_percentage <= 1.0
), "Source percentage must be a value in the range [0.0, 1.0]"
func_kwargs = helpers.get_func_kwargs(metadata, locals(), video_path)
local_path = utils.pathmgr.get_local_path(video_path)
utils.validate_video_path(local_path)
video_info = helpers.get_video_info(video_path)
video_duration = float(video_info["duration"])
width, height = video_info["width"], video_info["height"]
video_paths = []
with tempfile.TemporaryDirectory() as tmpdir:
tmp_video_path = os.path.join(tmpdir, "in.mp4")
resized_bg_path = os.path.join(tmpdir, "bg.mp4")
# create bg video
if background_path is None:
helpers.create_color_video(resized_bg_path, video_duration, height, width)
else:
resize(background_path, resized_bg_path, height, width)
helpers.add_silent_audio(resized_bg_path)
bg_video_info = helpers.get_video_info(resized_bg_path)
bg_video_duration = float(bg_video_info["duration"])
src_video_path_index = 1
final_bg_len = video_duration * (1 - source_percentage)
# if desired bg video too short, loop bg video
num_loops_needed = math.ceil(final_bg_len / bg_video_duration)
if num_loops_needed > 1:
loop(resized_bg_path, num_loops=num_loops_needed)
first_bg_segment_len = source_offset * final_bg_len
last_bg_segment_len = final_bg_len - first_bg_segment_len
# calculate bg start and end times of bg in output video
bg_start = background_offset * bg_video_duration
src_start = first_bg_segment_len
src_length = source_percentage * video_duration
src_end = src_start + src_length
# add pre src background segment
if source_offset > 0:
before_path = os.path.join(tmpdir, "before.mp4")
trim(
resized_bg_path,
before_path,
start=bg_start,
end=bg_start + first_bg_segment_len,
)
video_paths.append(before_path)
src_video_path_index = 1
else:
src_video_path_index = 0
# trim source to length satisfying source_percentage
helpers.add_silent_audio(video_path, tmp_video_path)
trimmed_src_path = os.path.join(tmpdir, "trim_src.mp4")
trim(tmp_video_path, trimmed_src_path, start=src_start, end=src_end)
video_paths.append(trimmed_src_path)
# add post src background segment
if source_offset < 1:
after_path = os.path.join(tmpdir, "after.mp4")
trim(
resized_bg_path,
after_path,
start=bg_start + src_start,
end=bg_start + src_start + last_bg_segment_len,
)
video_paths.append(after_path)
concat(
video_paths,
output_path or video_path,
src_video_path_index,
transition=transition,
)
if metadata is not None:
helpers.get_metadata(
metadata=metadata,
function_name="replace_with_background",
starting_background_duration=first_bg_segment_len,
source_duration=src_length,
ending_background_duration=last_bg_segment_len,
**func_kwargs,
)
return output_path or video_path | Replaces the beginning and end of the source video with the background video, keeping the total duration of the output video equal to the original duration of the source video @param video_path: the path to the video to be augmented @param output_path: the path in which the resulting video will be stored. If not passed in, the original video file will be overwritten @param background_path: the path to the video in which to insert the main video. If set to None, the main video will play in the middle of a silent video with black frames @param source_offset: the starting point where the background video transitions to the source video. Prior to this point, the source video is replaced with the background video. A value of 0 means all background is at the beginning. A value of 1 means all background is at the end of the video @param background_offset: the starting point from which the background video starts to play, as a proportion of the background video duration (i.e. this factor is multiplied by the background video duration to determine the start point) @param source_percentage: the percentage of the source video that remains unreplaced by the background video. The source percentage plus source offset should be less than 1. If it is greater, the output video duration will be longer than the source. If the background video is not long enough to get the desired source percentage, it will be looped @param transition: optional transition configuration to apply between the clips @param metadata: if set to be a list, metadata about the function execution including its name, the source & dest duration, fps, etc. will be appended to the inputted list. If set to None, no metadata will be appended or returned @returns: the path to the augmented video |
160,800 | import functools
import math
import os
import shutil
import tempfile
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
import numpy as np
from augly import audio as audaugs, image as imaugs, utils
from augly.audio import utils as audutils
from augly.video import helpers, utils as vdutils
from augly.video.augmenters import cv2 as ac, ffmpeg as af
The provided code snippet includes necessary dependencies for implementing the `meme_format` function. Write a Python function `def meme_format( video_path: str, output_path: Optional[str] = None, text: str = "LOL", font_file: str = utils.MEME_DEFAULT_FONT, opacity: float = 1.0, text_color: Tuple[int, int, int] = utils.DEFAULT_COLOR, caption_height: int = 250, meme_bg_color: Tuple[int, int, int] = utils.WHITE_RGB_COLOR, metadata: Optional[List[Dict[str, Any]]] = None, ) -> str` to solve the following problem:
Creates a new video that looks like a meme, given text and video @param video_path: the path to the video to be augmented @param output_path: the path in which the resulting video will be stored. If not passed in, the original video file will be overwritten @param text: the text to be overlaid/used in the meme. note: if using a very long string, please add in newline characters such that the text remains in a readable font size @param font_file: iopath uri to the .ttf font file @param opacity: the lower the opacity, the more transparent the text @param text_color: color of the text in RGB values @param caption_height: the height of the meme caption @param meme_bg_color: background color of the meme caption in RGB values @param metadata: if set to be a list, metadata about the function execution including its name, the source & dest duration, fps, etc. will be appended to the inputted list. If set to None, no metadata will be appended or returned @returns: the path to the augmented video
Here is the function:
def meme_format(
video_path: str,
output_path: Optional[str] = None,
text: str = "LOL",
font_file: str = utils.MEME_DEFAULT_FONT,
opacity: float = 1.0,
text_color: Tuple[int, int, int] = utils.DEFAULT_COLOR,
caption_height: int = 250,
meme_bg_color: Tuple[int, int, int] = utils.WHITE_RGB_COLOR,
metadata: Optional[List[Dict[str, Any]]] = None,
) -> str:
"""
Creates a new video that looks like a meme, given text and video
@param video_path: the path to the video to be augmented
@param output_path: the path in which the resulting video will be stored.
If not passed in, the original video file will be overwritten
@param text: the text to be overlaid/used in the meme. note: if using a very
long string, please add in newline characters such that the text remains
in a readable font size
@param font_file: iopath uri to the .ttf font file
@param opacity: the lower the opacity, the more transparent the text
@param text_color: color of the text in RGB values
@param caption_height: the height of the meme caption
@param meme_bg_color: background color of the meme caption in RGB values
@param metadata: if set to be a list, metadata about the function execution
including its name, the source & dest duration, fps, etc. will be appended
to the inputted list. If set to None, no metadata will be appended or returned
@returns: the path to the augmented video
"""
func_kwargs = helpers.get_func_kwargs(metadata, locals(), video_path)
meme_func = functools.partial(
imaugs.meme_format,
text=text,
font_file=font_file,
opacity=opacity,
text_color=text_color,
caption_height=caption_height,
meme_bg_color=meme_bg_color,
)
vdutils.apply_to_each_frame(meme_func, video_path, output_path)
if metadata is not None:
helpers.get_metadata(
metadata=metadata, function_name="meme_format", **func_kwargs
)
return output_path or video_path | Creates a new video that looks like a meme, given text and video @param video_path: the path to the video to be augmented @param output_path: the path in which the resulting video will be stored. If not passed in, the original video file will be overwritten @param text: the text to be overlaid/used in the meme. note: if using a very long string, please add in newline characters such that the text remains in a readable font size @param font_file: iopath uri to the .ttf font file @param opacity: the lower the opacity, the more transparent the text @param text_color: color of the text in RGB values @param caption_height: the height of the meme caption @param meme_bg_color: background color of the meme caption in RGB values @param metadata: if set to be a list, metadata about the function execution including its name, the source & dest duration, fps, etc. will be appended to the inputted list. If set to None, no metadata will be appended or returned @returns: the path to the augmented video |
160,801 | import functools
import math
import os
import shutil
import tempfile
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
import numpy as np
from augly import audio as audaugs, image as imaugs, utils
from augly.audio import utils as audutils
from augly.video import helpers, utils as vdutils
from augly.video.augmenters import cv2 as ac, ffmpeg as af
The provided code snippet includes necessary dependencies for implementing the `overlay_dots` function. Write a Python function `def overlay_dots( video_path: str, output_path: Optional[str] = None, num_dots: int = 100, dot_type: str = "colored", random_movement: bool = True, metadata: Optional[List[Dict[str, Any]]] = None, **kwargs, ) -> str` to solve the following problem:
Overlays dots onto a video @param video_path: the path to the video to be augmented @param output_path: the path in which the resulting video will be stored. If not passed in, the original video file will be overwritten @param num_dots: the number of dots to add to each frame @param dot_type: specify if you would like "blur" or "colored" @param random_movement: whether or not you want the dots to randomly move around across the frame or to move across in a "linear" way @param metadata: if set to be a list, metadata about the function execution including its name, the source & dest duration, fps, etc. will be appended to the inputted list. If set to None, no metadata will be appended or returned @returns: the path to the augmented video
Here is the function:
def overlay_dots(
video_path: str,
output_path: Optional[str] = None,
num_dots: int = 100,
dot_type: str = "colored",
random_movement: bool = True,
metadata: Optional[List[Dict[str, Any]]] = None,
**kwargs,
) -> str:
"""
Overlays dots onto a video
@param video_path: the path to the video to be augmented
@param output_path: the path in which the resulting video will be stored.
If not passed in, the original video file will be overwritten
@param num_dots: the number of dots to add to each frame
@param dot_type: specify if you would like "blur" or "colored"
@param random_movement: whether or not you want the dots to randomly move around
across the frame or to move across in a "linear" way
@param metadata: if set to be a list, metadata about the function execution
including its name, the source & dest duration, fps, etc. will be appended
to the inputted list. If set to None, no metadata will be appended or returned
@returns: the path to the augmented video
"""
func_kwargs = helpers.get_func_kwargs(metadata, locals(), video_path)
dots_aug = ac.VideoDistractorByDots(num_dots, dot_type, random_movement)
vdutils.apply_cv2_augmenter(dots_aug, video_path, output_path, **kwargs)
if metadata is not None:
helpers.get_metadata(
metadata=metadata, function_name="overlay_dots", **func_kwargs
)
return output_path or video_path | Overlays dots onto a video @param video_path: the path to the video to be augmented @param output_path: the path in which the resulting video will be stored. If not passed in, the original video file will be overwritten @param num_dots: the number of dots to add to each frame @param dot_type: specify if you would like "blur" or "colored" @param random_movement: whether or not you want the dots to randomly move around across the frame or to move across in a "linear" way @param metadata: if set to be a list, metadata about the function execution including its name, the source & dest duration, fps, etc. will be appended to the inputted list. If set to None, no metadata will be appended or returned @returns: the path to the augmented video |
160,802 | import functools
import math
import os
import shutil
import tempfile
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
import numpy as np
from augly import audio as audaugs, image as imaugs, utils
from augly.audio import utils as audutils
from augly.video import helpers, utils as vdutils
from augly.video.augmenters import cv2 as ac, ffmpeg as af
def overlay(
video_path: str,
overlay_path: str,
output_path: Optional[str] = None,
overlay_size: Optional[float] = None,
x_factor: float = 0.0,
y_factor: float = 0.0,
use_overlay_audio: bool = False,
metadata: Optional[List[Dict[str, Any]]] = None,
) -> str:
"""
Overlays media onto the video at position (width * x_factor, height * y_factor)
overlaid onto the video
If not passed in, the original video file will be overwritten
video. If set to None, the original size of the overlaid media is used
placed, relative to the video width
placed, relative to the video height
of the overlaid video will be used instead of the main/background video's audio
including its name, the source & dest duration, fps, etc. will be appended
to the inputted list. If set to None, no metadata will be appended or returned
"""
func_kwargs = helpers.get_func_kwargs(metadata, locals(), video_path)
local_path = utils.pathmgr.get_local_path(video_path)
overlay_path = utils.pathmgr.get_local_path(overlay_path)
tmp_overlay_path = None
if overlay_size is not None:
assert 0 < overlay_size <= 1, "overlay_size must be a value in the range (0, 1]"
video_info = helpers.get_video_info(local_path)
overlay_h = int(video_info["height"] * overlay_size)
overlay_w = int(video_info["width"] * overlay_size)
_, tmp_overlay_path = tempfile.mkstemp(suffix=os.path.splitext(overlay_path)[1])
if utils.is_image_file(overlay_path):
imaugs.resize(overlay_path, tmp_overlay_path, overlay_w, overlay_h)
else:
resize(overlay_path, tmp_overlay_path, overlay_h, overlay_w)
overlay_aug = af.VideoAugmenterByOverlay(
tmp_overlay_path or overlay_path, x_factor, y_factor, use_overlay_audio
)
overlay_aug.add_augmenter(local_path, output_path)
if tmp_overlay_path:
os.remove(tmp_overlay_path)
if metadata is not None:
helpers.get_metadata(metadata=metadata, function_name="overlay", **func_kwargs)
return output_path or video_path
def resize(
video_path: str,
output_path: Optional[str] = None,
height: Union[int, str] = "ih",
width: Union[int, str] = "iw",
metadata: Optional[List[Dict[str, Any]]] = None,
) -> str:
"""
Resizes a video
If not passed in, the original video file will be overwritten
the original video height will be used
the original video width will be used
including its name, the source & dest duration, fps, etc. will be appended
to the inputted list. If set to None, no metadata will be appended or returned
"""
func_kwargs = helpers.get_func_kwargs(metadata, locals(), video_path)
resize_aug = af.VideoAugmenterByResize(height, width)
resize_aug.add_augmenter(video_path, output_path)
if metadata is not None:
helpers.get_metadata(metadata=metadata, function_name="resize", **func_kwargs)
return output_path or video_path
The provided code snippet includes necessary dependencies for implementing the `overlay_emoji` function. Write a Python function `def overlay_emoji( video_path: str, output_path: Optional[str] = None, emoji_path: str = utils.EMOJI_PATH, x_factor: float = 0.4, y_factor: float = 0.4, opacity: float = 1.0, emoji_size: float = 0.15, metadata: Optional[List[Dict[str, Any]]] = None, ) -> str` to solve the following problem:
Overlays an emoji onto each frame of a video @param video_path: the path to the video to be augmented @param output_path: the path in which the resulting video will be stored. If not passed in, the original video file will be overwritten @param emoji_path: iopath uri to the emoji image @param x_factor: specifies where the left side of the emoji should be placed, relative to the video width @param y_factor: specifies where the top side of the emoji should be placed, relative to the video height @param opacity: opacity of the emoji image @param emoji_size: emoji size relative to the height of the video frame @param metadata: if set to be a list, metadata about the function execution including its name, the source & dest duration, fps, etc. will be appended to the inputted list. If set to None, no metadata will be appended or returned @returns: the path to the augmented video
Here is the function:
def overlay_emoji(
video_path: str,
output_path: Optional[str] = None,
emoji_path: str = utils.EMOJI_PATH,
x_factor: float = 0.4,
y_factor: float = 0.4,
opacity: float = 1.0,
emoji_size: float = 0.15,
metadata: Optional[List[Dict[str, Any]]] = None,
) -> str:
"""
Overlays an emoji onto each frame of a video
@param video_path: the path to the video to be augmented
@param output_path: the path in which the resulting video will be stored.
If not passed in, the original video file will be overwritten
@param emoji_path: iopath uri to the emoji image
@param x_factor: specifies where the left side of the emoji should be placed,
relative to the video width
@param y_factor: specifies where the top side of the emoji should be placed,
relative to the video height
@param opacity: opacity of the emoji image
@param emoji_size: emoji size relative to the height of the video frame
@param metadata: if set to be a list, metadata about the function execution
including its name, the source & dest duration, fps, etc. will be appended
to the inputted list. If set to None, no metadata will be appended or returned
@returns: the path to the augmented video
"""
func_kwargs = helpers.get_func_kwargs(metadata, locals(), video_path)
local_path = utils.pathmgr.get_local_path(video_path)
utils.validate_video_path(video_path)
video_info = helpers.get_video_info(local_path)
with tempfile.TemporaryDirectory() as tmpdir:
local_emoji_path = utils.pathmgr.get_local_path(emoji_path, cache_dir=tmpdir)
utils.validate_image_path(local_emoji_path)
emoji_output_path = os.path.join(tmpdir, "modified_emoji.png")
imaugs.resize(
local_emoji_path,
output_path=emoji_output_path,
height=int(emoji_size * video_info["height"]),
width=int(emoji_size * video_info["height"]),
)
imaugs.opacity(emoji_output_path, output_path=emoji_output_path, level=opacity)
overlay(
video_path,
emoji_output_path,
output_path,
x_factor=x_factor,
y_factor=y_factor,
)
if metadata is not None:
helpers.get_metadata(
metadata=metadata, function_name="overlay_emoji", **func_kwargs
)
return output_path or video_path | Overlays an emoji onto each frame of a video @param video_path: the path to the video to be augmented @param output_path: the path in which the resulting video will be stored. If not passed in, the original video file will be overwritten @param emoji_path: iopath uri to the emoji image @param x_factor: specifies where the left side of the emoji should be placed, relative to the video width @param y_factor: specifies where the top side of the emoji should be placed, relative to the video height @param opacity: opacity of the emoji image @param emoji_size: emoji size relative to the height of the video frame @param metadata: if set to be a list, metadata about the function execution including its name, the source & dest duration, fps, etc. will be appended to the inputted list. If set to None, no metadata will be appended or returned @returns: the path to the augmented video |
160,803 | import functools
import math
import os
import shutil
import tempfile
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
import numpy as np
from augly import audio as audaugs, image as imaugs, utils
from augly.audio import utils as audutils
from augly.video import helpers, utils as vdutils
from augly.video.augmenters import cv2 as ac, ffmpeg as af
def overlay(
video_path: str,
overlay_path: str,
output_path: Optional[str] = None,
overlay_size: Optional[float] = None,
x_factor: float = 0.0,
y_factor: float = 0.0,
use_overlay_audio: bool = False,
metadata: Optional[List[Dict[str, Any]]] = None,
) -> str:
"""
Overlays media onto the video at position (width * x_factor, height * y_factor)
overlaid onto the video
If not passed in, the original video file will be overwritten
video. If set to None, the original size of the overlaid media is used
placed, relative to the video width
placed, relative to the video height
of the overlaid video will be used instead of the main/background video's audio
including its name, the source & dest duration, fps, etc. will be appended
to the inputted list. If set to None, no metadata will be appended or returned
"""
func_kwargs = helpers.get_func_kwargs(metadata, locals(), video_path)
local_path = utils.pathmgr.get_local_path(video_path)
overlay_path = utils.pathmgr.get_local_path(overlay_path)
tmp_overlay_path = None
if overlay_size is not None:
assert 0 < overlay_size <= 1, "overlay_size must be a value in the range (0, 1]"
video_info = helpers.get_video_info(local_path)
overlay_h = int(video_info["height"] * overlay_size)
overlay_w = int(video_info["width"] * overlay_size)
_, tmp_overlay_path = tempfile.mkstemp(suffix=os.path.splitext(overlay_path)[1])
if utils.is_image_file(overlay_path):
imaugs.resize(overlay_path, tmp_overlay_path, overlay_w, overlay_h)
else:
resize(overlay_path, tmp_overlay_path, overlay_h, overlay_w)
overlay_aug = af.VideoAugmenterByOverlay(
tmp_overlay_path or overlay_path, x_factor, y_factor, use_overlay_audio
)
overlay_aug.add_augmenter(local_path, output_path)
if tmp_overlay_path:
os.remove(tmp_overlay_path)
if metadata is not None:
helpers.get_metadata(metadata=metadata, function_name="overlay", **func_kwargs)
return output_path or video_path
The provided code snippet includes necessary dependencies for implementing the `overlay_onto_background_video` function. Write a Python function `def overlay_onto_background_video( video_path: str, background_path: str, output_path: Optional[str] = None, overlay_size: Optional[float] = 0.7, x_factor: float = 0.0, y_factor: float = 0.0, use_background_audio: bool = False, metadata: Optional[List[Dict[str, Any]]] = None, ) -> str` to solve the following problem:
Overlays the video onto a background video, pointed to by background_path. @param video_path: the path to the video to be augmented @param background_path: the path to the background video @param output_path: the path in which the resulting video will be stored. If not passed in, the original video file will be overwritten @param overlay_size: size of the overlaid media with respect to the background video. If set to None, the original size of the overlaid media is used @param x_factor: specifies where the left side of the overlaid media should be placed, relative to the video width @param y_factor: specifies where the top side of the overlaid media should be placed, relative to the video height @param use_background_audio: if set to True and the media type is a video, the audio of the background video will be used instead of the src video's audio @param metadata: if set to be a list, metadata about the function execution including its name, the source & dest duration, fps, etc. will be appended to the inputted list. If set to None, no metadata will be appended or returned @returns: the path to the augmented video
Here is the function:
def overlay_onto_background_video(
video_path: str,
background_path: str,
output_path: Optional[str] = None,
overlay_size: Optional[float] = 0.7,
x_factor: float = 0.0,
y_factor: float = 0.0,
use_background_audio: bool = False,
metadata: Optional[List[Dict[str, Any]]] = None,
) -> str:
"""
Overlays the video onto a background video, pointed to by background_path.
@param video_path: the path to the video to be augmented
@param background_path: the path to the background video
@param output_path: the path in which the resulting video will be stored.
If not passed in, the original video file will be overwritten
@param overlay_size: size of the overlaid media with respect to the background
video. If set to None, the original size of the overlaid media is used
@param x_factor: specifies where the left side of the overlaid media should be
placed, relative to the video width
@param y_factor: specifies where the top side of the overlaid media should be
placed, relative to the video height
@param use_background_audio: if set to True and the media type is a video, the
audio of the background video will be used instead of the src video's audio
@param metadata: if set to be a list, metadata about the function execution
including its name, the source & dest duration, fps, etc. will be appended
to the inputted list. If set to None, no metadata will be appended or returned
@returns: the path to the augmented video
"""
func_kwargs = helpers.get_func_kwargs(metadata, locals(), video_path)
overlay(
video_path=background_path,
overlay_path=video_path,
output_path=output_path or video_path,
overlay_size=overlay_size,
x_factor=x_factor,
y_factor=y_factor,
use_overlay_audio=not use_background_audio,
)
if metadata is not None:
helpers.get_metadata(
metadata=metadata,
function_name="overlay_onto_background_video",
**func_kwargs,
)
return output_path or video_path | Overlays the video onto a background video, pointed to by background_path. @param video_path: the path to the video to be augmented @param background_path: the path to the background video @param output_path: the path in which the resulting video will be stored. If not passed in, the original video file will be overwritten @param overlay_size: size of the overlaid media with respect to the background video. If set to None, the original size of the overlaid media is used @param x_factor: specifies where the left side of the overlaid media should be placed, relative to the video width @param y_factor: specifies where the top side of the overlaid media should be placed, relative to the video height @param use_background_audio: if set to True and the media type is a video, the audio of the background video will be used instead of the src video's audio @param metadata: if set to be a list, metadata about the function execution including its name, the source & dest duration, fps, etc. will be appended to the inputted list. If set to None, no metadata will be appended or returned @returns: the path to the augmented video |
160,804 | import functools
import math
import os
import shutil
import tempfile
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
import numpy as np
from augly import audio as audaugs, image as imaugs, utils
from augly.audio import utils as audutils
from augly.video import helpers, utils as vdutils
from augly.video.augmenters import cv2 as ac, ffmpeg as af
The provided code snippet includes necessary dependencies for implementing the `overlay_onto_screenshot` function. Write a Python function `def overlay_onto_screenshot( video_path: str, output_path: Optional[str] = None, template_filepath: str = utils.TEMPLATE_PATH, template_bboxes_filepath: str = utils.BBOXES_PATH, max_image_size_pixels: Optional[int] = None, crop_src_to_fit: bool = False, metadata: Optional[List[Dict[str, Any]]] = None, ) -> str` to solve the following problem:
Overlays the video onto a screenshot template so it looks like it was screen-recorded on Instagram @param video_path: the path to the video to be augmented @param output_path: the path in which the resulting video will be stored. If not passed in, the original video file will be overwritten @param template_filepath: iopath uri to the screenshot template @param template_bboxes_filepath: iopath uri to the file containing the bounding box for each template @param max_image_size_pixels: if provided, the template image and/or src video will be scaled down to avoid an output image with an area greater than this size (in pixels) @param crop_src_to_fit: if True, the src image will be cropped if necessary to fit into the template image. If False, the src image will instead be resized if necessary @param metadata: if set to be a list, metadata about the function execution including its name, the source & dest duration, fps, etc. will be appended to the inputted list. If set to None, no metadata will be appended or returned @returns: the path to the augmented video
Here is the function:
def overlay_onto_screenshot(
video_path: str,
output_path: Optional[str] = None,
template_filepath: str = utils.TEMPLATE_PATH,
template_bboxes_filepath: str = utils.BBOXES_PATH,
max_image_size_pixels: Optional[int] = None,
crop_src_to_fit: bool = False,
metadata: Optional[List[Dict[str, Any]]] = None,
) -> str:
"""
Overlays the video onto a screenshot template so it looks like it was
screen-recorded on Instagram
@param video_path: the path to the video to be augmented
@param output_path: the path in which the resulting video will be stored.
If not passed in, the original video file will be overwritten
@param template_filepath: iopath uri to the screenshot template
@param template_bboxes_filepath: iopath uri to the file containing the bounding
box for each template
@param max_image_size_pixels: if provided, the template image and/or src video
will be scaled down to avoid an output image with an area greater than this
size (in pixels)
@param crop_src_to_fit: if True, the src image will be cropped if necessary to
fit into the template image. If False, the src image will instead be resized
if necessary
@param metadata: if set to be a list, metadata about the function execution
including its name, the source & dest duration, fps, etc. will be appended
to the inputted list. If set to None, no metadata will be appended or returned
@returns: the path to the augmented video
"""
func_kwargs = helpers.get_func_kwargs(metadata, locals(), video_path)
sc_func = functools.partial(
imaugs.overlay_onto_screenshot,
template_filepath=template_filepath,
template_bboxes_filepath=template_bboxes_filepath,
max_image_size_pixels=max_image_size_pixels,
crop_src_to_fit=crop_src_to_fit,
)
vdutils.apply_to_each_frame(sc_func, video_path, output_path)
if metadata is not None:
helpers.get_metadata(
metadata=metadata, function_name="overlay_onto_screenshot", **func_kwargs
)
return output_path or video_path | Overlays the video onto a screenshot template so it looks like it was screen-recorded on Instagram @param video_path: the path to the video to be augmented @param output_path: the path in which the resulting video will be stored. If not passed in, the original video file will be overwritten @param template_filepath: iopath uri to the screenshot template @param template_bboxes_filepath: iopath uri to the file containing the bounding box for each template @param max_image_size_pixels: if provided, the template image and/or src video will be scaled down to avoid an output image with an area greater than this size (in pixels) @param crop_src_to_fit: if True, the src image will be cropped if necessary to fit into the template image. If False, the src image will instead be resized if necessary @param metadata: if set to be a list, metadata about the function execution including its name, the source & dest duration, fps, etc. will be appended to the inputted list. If set to None, no metadata will be appended or returned @returns: the path to the augmented video |
160,805 | import functools
import math
import os
import shutil
import tempfile
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
import numpy as np
from augly import audio as audaugs, image as imaugs, utils
from augly.audio import utils as audutils
from augly.video import helpers, utils as vdutils
from augly.video.augmenters import cv2 as ac, ffmpeg as af
The provided code snippet includes necessary dependencies for implementing the `overlay_shapes` function. Write a Python function `def overlay_shapes( video_path: str, output_path: Optional[str] = None, num_shapes: int = 1, shape_type: Optional[str] = None, colors: Optional[List[Tuple[int, int, int]]] = None, thickness: Optional[int] = None, radius: Optional[float] = None, random_movement: bool = True, topleft: Optional[Tuple[float, float]] = None, bottomright: Optional[Tuple[float, float]] = None, metadata: Optional[List[Dict[str, Any]]] = None, **kwargs, ) -> str` to solve the following problem:
Overlays random shapes onto a video @param video_path: the path to the video to be augmented @param output_path: the path in which the resulting video will be stored. If not passed in, the original video file will be overwritten @param num_shapes: the number of shapes to add to each frame @param shape_type: specify if you would like circles or rectangles @param colors: list of (R, G, B) colors to sample from @param thickness: specify the thickness desired for the shapes @param random_movement: whether or not you want the shapes to randomly move around across the frame or to move across in a "linear" way @param topleft: specifying the boundary of shape region. The boundary are all floats [0, 1] representing the fraction w.r.t width/height @param bottomright: specifying the boundary of shape region. The boundary are all floats [0, 1] representing the fraction w.r.t width/height @param metadata: if set to be a list, metadata about the function execution including its name, the source & dest duration, fps, etc. will be appended to the inputted list. If set to None, no metadata will be appended or returned @returns: the path to the augmented video
Here is the function:
def overlay_shapes(
video_path: str,
output_path: Optional[str] = None,
num_shapes: int = 1,
shape_type: Optional[str] = None,
colors: Optional[List[Tuple[int, int, int]]] = None,
thickness: Optional[int] = None,
radius: Optional[float] = None,
random_movement: bool = True,
topleft: Optional[Tuple[float, float]] = None,
bottomright: Optional[Tuple[float, float]] = None,
metadata: Optional[List[Dict[str, Any]]] = None,
**kwargs,
) -> str:
"""
Overlays random shapes onto a video
@param video_path: the path to the video to be augmented
@param output_path: the path in which the resulting video will be stored.
If not passed in, the original video file will be overwritten
@param num_shapes: the number of shapes to add to each frame
@param shape_type: specify if you would like circles or rectangles
@param colors: list of (R, G, B) colors to sample from
@param thickness: specify the thickness desired for the shapes
@param random_movement: whether or not you want the shapes to randomly move
around across the frame or to move across in a "linear" way
@param topleft: specifying the boundary of shape region. The boundary are all
floats [0, 1] representing the fraction w.r.t width/height
@param bottomright: specifying the boundary of shape region. The boundary are all
floats [0, 1] representing the fraction w.r.t width/height
@param metadata: if set to be a list, metadata about the function execution
including its name, the source & dest duration, fps, etc. will be appended
to the inputted list. If set to None, no metadata will be appended or returned
@returns: the path to the augmented video
"""
func_kwargs = helpers.get_func_kwargs(metadata, locals(), video_path)
shapes_aug = ac.VideoDistractorByShapes(
num_shapes,
shape_type,
colors,
thickness,
radius,
random_movement,
topleft,
bottomright,
)
vdutils.apply_cv2_augmenter(shapes_aug, video_path, output_path, **kwargs)
if metadata is not None:
helpers.get_metadata(
metadata=metadata, function_name="overlay_shapes", **func_kwargs
)
return output_path or video_path | Overlays random shapes onto a video @param video_path: the path to the video to be augmented @param output_path: the path in which the resulting video will be stored. If not passed in, the original video file will be overwritten @param num_shapes: the number of shapes to add to each frame @param shape_type: specify if you would like circles or rectangles @param colors: list of (R, G, B) colors to sample from @param thickness: specify the thickness desired for the shapes @param random_movement: whether or not you want the shapes to randomly move around across the frame or to move across in a "linear" way @param topleft: specifying the boundary of shape region. The boundary are all floats [0, 1] representing the fraction w.r.t width/height @param bottomright: specifying the boundary of shape region. The boundary are all floats [0, 1] representing the fraction w.r.t width/height @param metadata: if set to be a list, metadata about the function execution including its name, the source & dest duration, fps, etc. will be appended to the inputted list. If set to None, no metadata will be appended or returned @returns: the path to the augmented video |
160,806 | import functools
import math
import os
import shutil
import tempfile
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
import numpy as np
from augly import audio as audaugs, image as imaugs, utils
from augly.audio import utils as audutils
from augly.video import helpers, utils as vdutils
from augly.video.augmenters import cv2 as ac, ffmpeg as af
The provided code snippet includes necessary dependencies for implementing the `overlay_text` function. Write a Python function `def overlay_text( video_path: str, output_path: Optional[str] = None, text_len: int = 10, text_change_nth: Optional[int] = None, fonts: Optional[List[Tuple[Any, Optional[str]]]] = None, fontscales: Optional[Tuple[float, float]] = None, colors: Optional[List[Tuple[int, int, int]]] = None, thickness: Optional[int] = None, random_movement: bool = False, topleft: Optional[Tuple[float, float]] = None, bottomright: Optional[Tuple[float, float]] = None, metadata: Optional[List[Dict[str, Any]]] = None, **kwargs, ) -> str` to solve the following problem:
Overlays random text onto a video @param video_path: the path to the video to be augmented @param output_path: the path in which the resulting video will be stored. If not passed in, the original video file will be overwritten @param text_len: length of string for randomized texts. @param text_change_nth: change random text every nth frame. None means using same text for all frames. @param fonts: list of fonts to sample from. Each font can be a cv2 fontFace, a PIL ImageFont, or a path to a PIL ImageFont file. Each font is coupled with a chars file (the second item in the tuple) - a path to a file which contains the characters associated with the given font. For example, non-western alphabets have different valid characters than the roman alphabet, and these must be specified in order to construct random valid text in that font. If the chars file path is None, the roman alphabet will be used. @param fontscales: 2-tuple of float (min_scale, max_scale). @param colors: list of (R, G, B) colors to sample from @param thickness: specify the thickness desired for the text. @param random_movement: whether or not you want the text to randomly move around across frame or to move across in a "linear" way @param topleft: specifying the boundary of text region. The boundary are all floats [0, 1] representing the fraction w.r.t width/height @param bottomright: specifying the boundary of text region. The boundary are all floats [0, 1] representing the fraction w.r.t width/height @param metadata: if set to be a list, metadata about the function execution including its name, the source & dest duration, fps, etc. will be appended to the inputted list. If set to None, no metadata will be appended or returned @returns: the path to the augmented video
Here is the function:
def overlay_text(
video_path: str,
output_path: Optional[str] = None,
text_len: int = 10,
text_change_nth: Optional[int] = None,
fonts: Optional[List[Tuple[Any, Optional[str]]]] = None,
fontscales: Optional[Tuple[float, float]] = None,
colors: Optional[List[Tuple[int, int, int]]] = None,
thickness: Optional[int] = None,
random_movement: bool = False,
topleft: Optional[Tuple[float, float]] = None,
bottomright: Optional[Tuple[float, float]] = None,
metadata: Optional[List[Dict[str, Any]]] = None,
**kwargs,
) -> str:
"""
Overlays random text onto a video
@param video_path: the path to the video to be augmented
@param output_path: the path in which the resulting video will be stored.
If not passed in, the original video file will be overwritten
@param text_len: length of string for randomized texts.
@param text_change_nth: change random text every nth frame. None means
using same text for all frames.
@param fonts: list of fonts to sample from. Each font can be a cv2 fontFace,
a PIL ImageFont, or a path to a PIL ImageFont file. Each font is coupled with
a chars file (the second item in the tuple) - a path to a file which contains
the characters associated with the given font. For example, non-western
alphabets have different valid characters than the roman alphabet, and these
must be specified in order to construct random valid text in that font. If the
chars file path is None, the roman alphabet will be used.
@param fontscales: 2-tuple of float (min_scale, max_scale).
@param colors: list of (R, G, B) colors to sample from
@param thickness: specify the thickness desired for the text.
@param random_movement: whether or not you want the text to randomly move around
across frame or to move across in a "linear" way
@param topleft: specifying the boundary of text region. The boundary are all
floats [0, 1] representing the fraction w.r.t width/height
@param bottomright: specifying the boundary of text region. The boundary are all
floats [0, 1] representing the fraction w.r.t width/height
@param metadata: if set to be a list, metadata about the function execution
including its name, the source & dest duration, fps, etc. will be appended
to the inputted list. If set to None, no metadata will be appended or returned
@returns: the path to the augmented video
"""
func_kwargs = helpers.get_func_kwargs(metadata, locals(), video_path)
text_aug = ac.VideoDistractorByText(
text_len,
text_change_nth,
fonts,
fontscales,
colors,
thickness,
random_movement,
topleft,
bottomright,
)
vdutils.apply_cv2_augmenter(text_aug, video_path, output_path, **kwargs)
if metadata is not None:
helpers.get_metadata(
metadata=metadata, function_name="overlay_text", **func_kwargs
)
return output_path or video_path | Overlays random text onto a video @param video_path: the path to the video to be augmented @param output_path: the path in which the resulting video will be stored. If not passed in, the original video file will be overwritten @param text_len: length of string for randomized texts. @param text_change_nth: change random text every nth frame. None means using same text for all frames. @param fonts: list of fonts to sample from. Each font can be a cv2 fontFace, a PIL ImageFont, or a path to a PIL ImageFont file. Each font is coupled with a chars file (the second item in the tuple) - a path to a file which contains the characters associated with the given font. For example, non-western alphabets have different valid characters than the roman alphabet, and these must be specified in order to construct random valid text in that font. If the chars file path is None, the roman alphabet will be used. @param fontscales: 2-tuple of float (min_scale, max_scale). @param colors: list of (R, G, B) colors to sample from @param thickness: specify the thickness desired for the text. @param random_movement: whether or not you want the text to randomly move around across frame or to move across in a "linear" way @param topleft: specifying the boundary of text region. The boundary are all floats [0, 1] representing the fraction w.r.t width/height @param bottomright: specifying the boundary of text region. The boundary are all floats [0, 1] representing the fraction w.r.t width/height @param metadata: if set to be a list, metadata about the function execution including its name, the source & dest duration, fps, etc. will be appended to the inputted list. If set to None, no metadata will be appended or returned @returns: the path to the augmented video |
160,807 | import functools
import math
import os
import shutil
import tempfile
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
import numpy as np
from augly import audio as audaugs, image as imaugs, utils
from augly.audio import utils as audutils
from augly.video import helpers, utils as vdutils
from augly.video.augmenters import cv2 as ac, ffmpeg as af
The provided code snippet includes necessary dependencies for implementing the `pad` function. Write a Python function `def pad( video_path: str, output_path: Optional[str] = None, w_factor: float = 0.25, h_factor: float = 0.25, color: Tuple[int, int, int] = utils.DEFAULT_COLOR, metadata: Optional[List[Dict[str, Any]]] = None, ) -> str` to solve the following problem:
Pads the video @param video_path: the path to the video to be augmented @param output_path: the path in which the resulting video will be stored. If not passed in, the original video file will be overwritten @param w_factor: pad right and left with w_factor * frame width @param h_factor: pad bottom and top with h_factor * frame height @param color: RGB color of the padded margin @param metadata: if set to be a list, metadata about the function execution including its name, the source & dest duration, fps, etc. will be appended to the inputted list. If set to None, no metadata will be appended or returned @returns: the path to the augmented video
Here is the function:
def pad(
video_path: str,
output_path: Optional[str] = None,
w_factor: float = 0.25,
h_factor: float = 0.25,
color: Tuple[int, int, int] = utils.DEFAULT_COLOR,
metadata: Optional[List[Dict[str, Any]]] = None,
) -> str:
"""
Pads the video
@param video_path: the path to the video to be augmented
@param output_path: the path in which the resulting video will be stored.
If not passed in, the original video file will be overwritten
@param w_factor: pad right and left with w_factor * frame width
@param h_factor: pad bottom and top with h_factor * frame height
@param color: RGB color of the padded margin
@param metadata: if set to be a list, metadata about the function execution
including its name, the source & dest duration, fps, etc. will be appended
to the inputted list. If set to None, no metadata will be appended or returned
@returns: the path to the augmented video
"""
func_kwargs = helpers.get_func_kwargs(metadata, locals(), video_path)
pad_aug = af.VideoAugmenterByPadding(w_factor, h_factor, color)
pad_aug.add_augmenter(video_path, output_path)
if metadata is not None:
helpers.get_metadata(metadata=metadata, function_name="pad", **func_kwargs)
return output_path or video_path | Pads the video @param video_path: the path to the video to be augmented @param output_path: the path in which the resulting video will be stored. If not passed in, the original video file will be overwritten @param w_factor: pad right and left with w_factor * frame width @param h_factor: pad bottom and top with h_factor * frame height @param color: RGB color of the padded margin @param metadata: if set to be a list, metadata about the function execution including its name, the source & dest duration, fps, etc. will be appended to the inputted list. If set to None, no metadata will be appended or returned @returns: the path to the augmented video |
160,808 | import functools
import math
import os
import shutil
import tempfile
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
import numpy as np
from augly import audio as audaugs, image as imaugs, utils
from augly.audio import utils as audutils
from augly.video import helpers, utils as vdutils
from augly.video.augmenters import cv2 as ac, ffmpeg as af
The provided code snippet includes necessary dependencies for implementing the `perspective_transform_and_shake` function. Write a Python function `def perspective_transform_and_shake( video_path: str, output_path: Optional[str] = None, sigma: float = 50.0, shake_radius: float = 0.0, seed: Optional[int] = None, metadata: Optional[List[Dict[str, Any]]] = None, ) -> str` to solve the following problem:
Apply a perspective transform to the video so it looks like it was taken as a photo from another device (e.g. taking a video from your phone of a video on a computer). Also has a shake factor to mimic the shakiness of someone holding a phone. @param video_path: the path to the video to be augmented @param output_path: the path in which the resulting video will be stored. If not passed in, the original video file will be overwritten @param sigma: the standard deviation of the distribution of destination coordinates. The larger the sigma value, the more intense the transform @param shake_radius: determines the amount by which to "shake" the video; the larger the radius, the more intense the shake. @param seed: if provided, this will set the random seed to ensure consistency between runs @param metadata: if set to be a list, metadata about the function execution including its name, the source & dest duration, fps, etc. will be appended to the inputted list. If set to None, no metadata will be appended or returned @returns: the path to the augmented video
Here is the function:
def perspective_transform_and_shake(
video_path: str,
output_path: Optional[str] = None,
sigma: float = 50.0,
shake_radius: float = 0.0,
seed: Optional[int] = None,
metadata: Optional[List[Dict[str, Any]]] = None,
) -> str:
"""
Apply a perspective transform to the video so it looks like it was taken
as a photo from another device (e.g. taking a video from your phone of a
video on a computer). Also has a shake factor to mimic the shakiness of
someone holding a phone.
@param video_path: the path to the video to be augmented
@param output_path: the path in which the resulting video will be stored.
If not passed in, the original video file will be overwritten
@param sigma: the standard deviation of the distribution of destination coordinates.
The larger the sigma value, the more intense the transform
@param shake_radius: determines the amount by which to "shake" the video; the larger
the radius, the more intense the shake.
@param seed: if provided, this will set the random seed to ensure consistency
between runs
@param metadata: if set to be a list, metadata about the function execution
including its name, the source & dest duration, fps, etc. will be appended
to the inputted list. If set to None, no metadata will be appended or returned
@returns: the path to the augmented video
"""
func_kwargs = helpers.get_func_kwargs(metadata, locals(), video_path)
perspective_func = functools.partial(
imaugs.perspective_transform, sigma=sigma, seed=seed
)
duration = float(helpers.get_video_info(video_path)["duration"])
rng = np.random.RandomState(seed) if seed is not None else np.random
def get_dx_dy(frame_number: int) -> Dict:
u = math.sin(frame_number / duration * math.pi) ** 2
return {
"dx": u * rng.normal(0, shake_radius),
"dy": u * rng.normal(0, shake_radius),
}
vdutils.apply_to_each_frame(perspective_func, video_path, output_path, get_dx_dy)
if metadata is not None:
helpers.get_metadata(
metadata=metadata,
function_name="perspective_transform_and_shake",
**func_kwargs,
)
return output_path or video_path | Apply a perspective transform to the video so it looks like it was taken as a photo from another device (e.g. taking a video from your phone of a video on a computer). Also has a shake factor to mimic the shakiness of someone holding a phone. @param video_path: the path to the video to be augmented @param output_path: the path in which the resulting video will be stored. If not passed in, the original video file will be overwritten @param sigma: the standard deviation of the distribution of destination coordinates. The larger the sigma value, the more intense the transform @param shake_radius: determines the amount by which to "shake" the video; the larger the radius, the more intense the shake. @param seed: if provided, this will set the random seed to ensure consistency between runs @param metadata: if set to be a list, metadata about the function execution including its name, the source & dest duration, fps, etc. will be appended to the inputted list. If set to None, no metadata will be appended or returned @returns: the path to the augmented video |
160,809 | import functools
import math
import os
import shutil
import tempfile
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
import numpy as np
from augly import audio as audaugs, image as imaugs, utils
from augly.audio import utils as audutils
from augly.video import helpers, utils as vdutils
from augly.video.augmenters import cv2 as ac, ffmpeg as af
def resize(
video_path: str,
output_path: Optional[str] = None,
height: Union[int, str] = "ih",
width: Union[int, str] = "iw",
metadata: Optional[List[Dict[str, Any]]] = None,
) -> str:
"""
Resizes a video
If not passed in, the original video file will be overwritten
the original video height will be used
the original video width will be used
including its name, the source & dest duration, fps, etc. will be appended
to the inputted list. If set to None, no metadata will be appended or returned
"""
func_kwargs = helpers.get_func_kwargs(metadata, locals(), video_path)
resize_aug = af.VideoAugmenterByResize(height, width)
resize_aug.add_augmenter(video_path, output_path)
if metadata is not None:
helpers.get_metadata(metadata=metadata, function_name="resize", **func_kwargs)
return output_path or video_path
The provided code snippet includes necessary dependencies for implementing the `pixelization` function. Write a Python function `def pixelization( video_path: str, output_path: Optional[str] = None, ratio: float = 1.0, metadata: Optional[List[Dict[str, Any]]] = None, ) -> str` to solve the following problem:
Pixelizes the video @param video_path: the path to the video to be augmented @param output_path: the path in which the resulting video will be stored. If not passed in, the original video file will be overwritten @param ratio: smaller values result in a more pixelated video, 1.0 indicates no change, and any value above one doesn't have a noticeable effect @param metadata: if set to be a list, metadata about the function execution including its name, the source & dest duration, fps, etc. will be appended to the inputted list. If set to None, no metadata will be appended or returned @returns: the path to the augmented video
Here is the function:
def pixelization(
video_path: str,
output_path: Optional[str] = None,
ratio: float = 1.0,
metadata: Optional[List[Dict[str, Any]]] = None,
) -> str:
"""
Pixelizes the video
@param video_path: the path to the video to be augmented
@param output_path: the path in which the resulting video will be stored.
If not passed in, the original video file will be overwritten
@param ratio: smaller values result in a more pixelated video, 1.0 indicates
no change, and any value above one doesn't have a noticeable effect
@param metadata: if set to be a list, metadata about the function execution
including its name, the source & dest duration, fps, etc. will be appended
to the inputted list. If set to None, no metadata will be appended or returned
@returns: the path to the augmented video
"""
func_kwargs = helpers.get_func_kwargs(metadata, locals(), video_path)
assert ratio > 0, "Expected 'ratio' to be a positive number"
video_info = helpers.get_video_info(video_path)
width, height = video_info["width"], video_info["height"]
output_path = output_path or video_path
resize(video_path, output_path, height * ratio, width * ratio)
resize(output_path, output_path, height, width)
if metadata is not None:
helpers.get_metadata(
metadata=metadata, function_name="pixelization", **func_kwargs
)
return output_path or video_path | Pixelizes the video @param video_path: the path to the video to be augmented @param output_path: the path in which the resulting video will be stored. If not passed in, the original video file will be overwritten @param ratio: smaller values result in a more pixelated video, 1.0 indicates no change, and any value above one doesn't have a noticeable effect @param metadata: if set to be a list, metadata about the function execution including its name, the source & dest duration, fps, etc. will be appended to the inputted list. If set to None, no metadata will be appended or returned @returns: the path to the augmented video |
160,810 | import functools
import math
import os
import shutil
import tempfile
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
import numpy as np
from augly import audio as audaugs, image as imaugs, utils
from augly.audio import utils as audutils
from augly.video import helpers, utils as vdutils
from augly.video.augmenters import cv2 as ac, ffmpeg as af
The provided code snippet includes necessary dependencies for implementing the `remove_audio` function. Write a Python function `def remove_audio( video_path: str, output_path: Optional[str] = None, metadata: Optional[List[Dict[str, Any]]] = None, ) -> str` to solve the following problem:
Removes the audio stream from a video @param video_path: the path to the video to be augmented @param output_path: the path in which the resulting video will be stored. If not passed in, the original video file will be overwritten @param metadata: if set to be a list, metadata about the function execution including its name, the source & dest duration, fps, etc. will be appended to the inputted list. If set to None, no metadata will be appended or returned @returns: the path to the augmented video
Here is the function:
def remove_audio(
video_path: str,
output_path: Optional[str] = None,
metadata: Optional[List[Dict[str, Any]]] = None,
) -> str:
"""
Removes the audio stream from a video
@param video_path: the path to the video to be augmented
@param output_path: the path in which the resulting video will be stored.
If not passed in, the original video file will be overwritten
@param metadata: if set to be a list, metadata about the function execution
including its name, the source & dest duration, fps, etc. will be appended
to the inputted list. If set to None, no metadata will be appended or returned
@returns: the path to the augmented video
"""
func_kwargs = helpers.get_func_kwargs(metadata, locals(), video_path)
remove_audio_aug = af.VideoAugmenterByRemovingAudio()
remove_audio_aug.add_augmenter(video_path, output_path)
if metadata is not None:
helpers.get_metadata(
metadata=metadata, function_name="remove_audio", **func_kwargs
)
return output_path or video_path | Removes the audio stream from a video @param video_path: the path to the video to be augmented @param output_path: the path in which the resulting video will be stored. If not passed in, the original video file will be overwritten @param metadata: if set to be a list, metadata about the function execution including its name, the source & dest duration, fps, etc. will be appended to the inputted list. If set to None, no metadata will be appended or returned @returns: the path to the augmented video |
160,811 | import functools
import math
import os
import shutil
import tempfile
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
import numpy as np
from augly import audio as audaugs, image as imaugs, utils
from augly.audio import utils as audutils
from augly.video import helpers, utils as vdutils
from augly.video.augmenters import cv2 as ac, ffmpeg as af
def audio_swap(
video_path: str,
audio_path: str,
output_path: Optional[str] = None,
offset: float = 0.0,
metadata: Optional[List[Dict[str, Any]]] = None,
) -> str:
"""
Swaps the video audio for the audio passed in provided an offset
video's audio
If not passed in, the original video file will be overwritten
offset + video_duration is used in the audio swap. Default value is zero
including its name, the source & dest duration, fps, etc. will be appended
to the inputted list. If set to None, no metadata will be appended or returned
"""
func_kwargs = helpers.get_func_kwargs(metadata, locals(), video_path)
audio_swap_aug = af.VideoAugmenterByAudioSwap(audio_path, offset)
audio_swap_aug.add_augmenter(video_path, output_path)
if metadata is not None:
helpers.get_metadata(
metadata=metadata, function_name="audio_swap", **func_kwargs
)
return output_path or video_path
def concat(
video_paths: List[str],
output_path: Optional[str] = None,
src_video_path_index: int = 0,
transition: Optional[af.TransitionConfig] = None,
metadata: Optional[List[Dict[str, Any]]] = None,
) -> str:
"""
Concatenates videos together. Resizes all other videos to the size of the
`source` video (video_paths[src_video_path_index]), and modifies the sample
aspect ratios to match (ffmpeg will fail to concat if SARs don't match)
If not passed in, the original video file will be overwritten
the list `video_paths` should be considered the `source` or original video
including its name, the source & dest duration, fps, etc. will be appended
to the inputted list. If set to None, no metadata will be appended or returned
"""
func_kwargs = helpers.get_func_kwargs(
metadata, locals(), video_paths[src_video_path_index]
)
concat_aug = af.VideoAugmenterByConcat(
video_paths,
src_video_path_index,
transition,
)
concat_aug.add_augmenter(video_paths[src_video_path_index], output_path)
if metadata is not None:
helpers.get_metadata(
metadata=metadata,
function_name="concat",
video_path=video_paths[src_video_path_index],
**func_kwargs,
)
return output_path or video_paths[src_video_path_index]
def trim(
video_path: str,
output_path: Optional[str] = None,
start: Optional[float] = None,
end: Optional[float] = None,
metadata: Optional[List[Dict[str, Any]]] = None,
) -> str:
"""
Trims the video using the specified start and end parameters
If not passed in, the original video file will be overwritten
If None, start will be 0
If None, the end will be the duration of the video
including its name, the source & dest duration, fps, etc. will be appended
to the inputted list. If set to None, no metadata will be appended or returned
"""
func_kwargs = helpers.get_func_kwargs(metadata, locals(), video_path)
trim_aug = af.VideoAugmenterByTrim(start=start, end=end)
trim_aug.add_augmenter(video_path, output_path)
if metadata is not None:
helpers.get_metadata(metadata=metadata, function_name="trim", **func_kwargs)
return output_path or video_path
The provided code snippet includes necessary dependencies for implementing the `replace_with_color_frames` function. Write a Python function `def replace_with_color_frames( video_path: str, output_path: Optional[str] = None, offset_factor: float = 0.0, duration_factor: float = 1.0, color: Tuple[int, int, int] = utils.DEFAULT_COLOR, transition: Optional[af.TransitionConfig] = None, metadata: Optional[List[Dict[str, Any]]] = None, ) -> str` to solve the following problem:
Replaces part of the video with frames of the specified color @param video_path: the path to the video to be augmented @param output_path: the path in which the resulting video will be stored. If not passed in, the original video file will be overwritten @param offset_factor: start point of the replacement relative to the video duration (this parameter is multiplied by the video duration) @param duration_factor: the length of the replacement relative to the video duration (this parameter is multiplied by the video duration) @param color: RGB color of the replaced frames. Default color is black @param transition: optional transition configuration to apply between the clips @param metadata: if set to be a list, metadata about the function execution including its name, the source & dest duration, fps, etc. will be appended to the inputted list. If set to None, no metadata will be appended or returned @returns: the path to the augmented video
Here is the function:
def replace_with_color_frames(
video_path: str,
output_path: Optional[str] = None,
offset_factor: float = 0.0,
duration_factor: float = 1.0,
color: Tuple[int, int, int] = utils.DEFAULT_COLOR,
transition: Optional[af.TransitionConfig] = None,
metadata: Optional[List[Dict[str, Any]]] = None,
) -> str:
"""
Replaces part of the video with frames of the specified color
@param video_path: the path to the video to be augmented
@param output_path: the path in which the resulting video will be stored.
If not passed in, the original video file will be overwritten
@param offset_factor: start point of the replacement relative to the video
duration (this parameter is multiplied by the video duration)
@param duration_factor: the length of the replacement relative to the video
duration (this parameter is multiplied by the video duration)
@param color: RGB color of the replaced frames. Default color is black
@param transition: optional transition configuration to apply between the clips
@param metadata: if set to be a list, metadata about the function execution
including its name, the source & dest duration, fps, etc. will be appended
to the inputted list. If set to None, no metadata will be appended or returned
@returns: the path to the augmented video
"""
utils.validate_video_path(video_path)
assert (
0.0 <= offset_factor <= 1.0 and 0.0 <= duration_factor <= 1.0
), "Both offset & duration factors must be values in the range [0.0, 1.0]"
func_kwargs = {
**helpers.get_func_kwargs(metadata, locals(), video_path),
"function_name": "replace_with_color_frames",
}
video_info = helpers.get_video_info(video_path)
video_duration = float(video_info["duration"])
width, height = video_info["width"], video_info["height"]
offset = video_duration * offset_factor
duration = video_duration * duration_factor
output_path = output_path or video_path
if duration == 0 or offset == video_duration:
if output_path != video_path:
shutil.copy(video_path, output_path)
if metadata is not None:
helpers.get_metadata(metadata=metadata, **func_kwargs)
return output_path or video_path
video_paths = []
src_video_path_index = 0 if offset > 0 else 2
with tempfile.TemporaryDirectory() as tmpdir:
color_duration = (
video_duration - offset if offset + duration >= video_duration else duration
)
color_path = os.path.join(tmpdir, "color_frames.mp4")
helpers.create_color_video(color_path, color_duration, height, width, color)
if helpers.has_audio_stream(video_path):
audio_path = os.path.join(tmpdir, "audio.aac")
helpers.extract_audio_to_file(video_path, audio_path)
audio_swap(color_path, audio_path, offset=offset)
if offset_factor == 0 and duration_factor == 1.0:
shutil.copy(color_path, output_path)
if metadata is not None:
helpers.get_metadata(metadata=metadata, **func_kwargs)
return output_path or video_path
if offset > 0:
before_path = os.path.join(tmpdir, "before.mp4")
trim(video_path, before_path, end=offset)
video_paths.append(before_path)
video_paths.append(color_path)
if offset + duration < video_duration:
after_path = os.path.join(tmpdir, "after.mp4")
trim(video_path, after_path, start=offset + duration)
video_paths.append(after_path)
concat(
video_paths,
output_path,
src_video_path_index=src_video_path_index,
transition=transition,
)
if metadata is not None:
helpers.get_metadata(metadata=metadata, **func_kwargs)
return output_path or video_path | Replaces part of the video with frames of the specified color @param video_path: the path to the video to be augmented @param output_path: the path in which the resulting video will be stored. If not passed in, the original video file will be overwritten @param offset_factor: start point of the replacement relative to the video duration (this parameter is multiplied by the video duration) @param duration_factor: the length of the replacement relative to the video duration (this parameter is multiplied by the video duration) @param color: RGB color of the replaced frames. Default color is black @param transition: optional transition configuration to apply between the clips @param metadata: if set to be a list, metadata about the function execution including its name, the source & dest duration, fps, etc. will be appended to the inputted list. If set to None, no metadata will be appended or returned @returns: the path to the augmented video |
160,812 | import functools
import math
import os
import shutil
import tempfile
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
import numpy as np
from augly import audio as audaugs, image as imaugs, utils
from augly.audio import utils as audutils
from augly.video import helpers, utils as vdutils
from augly.video.augmenters import cv2 as ac, ffmpeg as af
The provided code snippet includes necessary dependencies for implementing the `rotate` function. Write a Python function `def rotate( video_path: str, output_path: Optional[str] = None, degrees: float = 15.0, metadata: Optional[List[Dict[str, Any]]] = None, ) -> str` to solve the following problem:
Rotates a video @param video_path: the path to the video to be augmented @param output_path: the path in which the resulting video will be stored. If not passed in, the original video file will be overwritten @param degrees: expression for the angle by which to rotate the input video clockwise, expressed in degrees (supports negative values as well) @param metadata: if set to be a list, metadata about the function execution including its name, the source & dest duration, fps, etc. will be appended to the inputted list. If set to None, no metadata will be appended or returned @returns: the path to the augmented video
Here is the function:
def rotate(
video_path: str,
output_path: Optional[str] = None,
degrees: float = 15.0,
metadata: Optional[List[Dict[str, Any]]] = None,
) -> str:
"""
Rotates a video
@param video_path: the path to the video to be augmented
@param output_path: the path in which the resulting video will be stored.
If not passed in, the original video file will be overwritten
@param degrees: expression for the angle by which to rotate the input video
clockwise, expressed in degrees (supports negative values as well)
@param metadata: if set to be a list, metadata about the function execution
including its name, the source & dest duration, fps, etc. will be appended
to the inputted list. If set to None, no metadata will be appended or returned
@returns: the path to the augmented video
"""
func_kwargs = helpers.get_func_kwargs(metadata, locals(), video_path)
rotate_aug = af.VideoAugmenterByRotation(degrees)
rotate_aug.add_augmenter(video_path, output_path)
if metadata is not None:
helpers.get_metadata(metadata=metadata, function_name="rotate", **func_kwargs)
return output_path or video_path | Rotates a video @param video_path: the path to the video to be augmented @param output_path: the path in which the resulting video will be stored. If not passed in, the original video file will be overwritten @param degrees: expression for the angle by which to rotate the input video clockwise, expressed in degrees (supports negative values as well) @param metadata: if set to be a list, metadata about the function execution including its name, the source & dest duration, fps, etc. will be appended to the inputted list. If set to None, no metadata will be appended or returned @returns: the path to the augmented video |
160,813 | import functools
import math
import os
import shutil
import tempfile
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
import numpy as np
from augly import audio as audaugs, image as imaugs, utils
from augly.audio import utils as audutils
from augly.video import helpers, utils as vdutils
from augly.video.augmenters import cv2 as ac, ffmpeg as af
The provided code snippet includes necessary dependencies for implementing the `scale` function. Write a Python function `def scale( video_path: str, output_path: Optional[str] = None, factor: float = 0.5, metadata: Optional[List[Dict[str, Any]]] = None, ) -> str` to solve the following problem:
Alters the resolution of a video @param video_path: the path to the video to be augmented @param output_path: the path in which the resulting video will be stored. If not passed in, the original video file will be overwritten @param factor: the ratio by which the video should be downscaled or upscaled @param metadata: if set to be a list, metadata about the function execution including its name, the source & dest duration, fps, etc. will be appended to the inputted list. If set to None, no metadata will be appended or returned @returns: the path to the augmented video
Here is the function:
def scale(
video_path: str,
output_path: Optional[str] = None,
factor: float = 0.5,
metadata: Optional[List[Dict[str, Any]]] = None,
) -> str:
"""
Alters the resolution of a video
@param video_path: the path to the video to be augmented
@param output_path: the path in which the resulting video will be stored.
If not passed in, the original video file will be overwritten
@param factor: the ratio by which the video should be downscaled or upscaled
@param metadata: if set to be a list, metadata about the function execution
including its name, the source & dest duration, fps, etc. will be appended
to the inputted list. If set to None, no metadata will be appended or returned
@returns: the path to the augmented video
"""
func_kwargs = helpers.get_func_kwargs(metadata, locals(), video_path)
scale_aug = af.VideoAugmenterByResolution(factor)
scale_aug.add_augmenter(video_path, output_path)
if metadata is not None:
helpers.get_metadata(metadata=metadata, function_name="scale", **func_kwargs)
return output_path or video_path | Alters the resolution of a video @param video_path: the path to the video to be augmented @param output_path: the path in which the resulting video will be stored. If not passed in, the original video file will be overwritten @param factor: the ratio by which the video should be downscaled or upscaled @param metadata: if set to be a list, metadata about the function execution including its name, the source & dest duration, fps, etc. will be appended to the inputted list. If set to None, no metadata will be appended or returned @returns: the path to the augmented video |
160,814 | import functools
import math
import os
import shutil
import tempfile
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
import numpy as np
from augly import audio as audaugs, image as imaugs, utils
from augly.audio import utils as audutils
from augly.video import helpers, utils as vdutils
from augly.video.augmenters import cv2 as ac, ffmpeg as af
def overlay(
video_path: str,
overlay_path: str,
output_path: Optional[str] = None,
overlay_size: Optional[float] = None,
x_factor: float = 0.0,
y_factor: float = 0.0,
use_overlay_audio: bool = False,
metadata: Optional[List[Dict[str, Any]]] = None,
) -> str:
"""
Overlays media onto the video at position (width * x_factor, height * y_factor)
overlaid onto the video
If not passed in, the original video file will be overwritten
video. If set to None, the original size of the overlaid media is used
placed, relative to the video width
placed, relative to the video height
of the overlaid video will be used instead of the main/background video's audio
including its name, the source & dest duration, fps, etc. will be appended
to the inputted list. If set to None, no metadata will be appended or returned
"""
func_kwargs = helpers.get_func_kwargs(metadata, locals(), video_path)
local_path = utils.pathmgr.get_local_path(video_path)
overlay_path = utils.pathmgr.get_local_path(overlay_path)
tmp_overlay_path = None
if overlay_size is not None:
assert 0 < overlay_size <= 1, "overlay_size must be a value in the range (0, 1]"
video_info = helpers.get_video_info(local_path)
overlay_h = int(video_info["height"] * overlay_size)
overlay_w = int(video_info["width"] * overlay_size)
_, tmp_overlay_path = tempfile.mkstemp(suffix=os.path.splitext(overlay_path)[1])
if utils.is_image_file(overlay_path):
imaugs.resize(overlay_path, tmp_overlay_path, overlay_w, overlay_h)
else:
resize(overlay_path, tmp_overlay_path, overlay_h, overlay_w)
overlay_aug = af.VideoAugmenterByOverlay(
tmp_overlay_path or overlay_path, x_factor, y_factor, use_overlay_audio
)
overlay_aug.add_augmenter(local_path, output_path)
if tmp_overlay_path:
os.remove(tmp_overlay_path)
if metadata is not None:
helpers.get_metadata(metadata=metadata, function_name="overlay", **func_kwargs)
return output_path or video_path
The provided code snippet includes necessary dependencies for implementing the `shift` function. Write a Python function `def shift( video_path: str, output_path: Optional[str] = None, x_factor: float = 0.0, y_factor: float = 0.0, color: Tuple[int, int, int] = utils.DEFAULT_COLOR, metadata: Optional[List[Dict[str, Any]]] = None, ) -> str` to solve the following problem:
Shifts the original frame position from the center by a vector (width * x_factor, height * y_factor) and pads the rest with a colored margin @param video_path: the path to the video to be augmented @param output_path: the path in which the resulting video will be stored. If not passed in, the original video file will be overwritten @param x_factor: the horizontal amount that the video should be shifted, relative to the width of the video @param y_factor: the vertical amount that the video should be shifted, relative to the height of the video @param color: RGB color of the margin generated by the shift. Default color is black @param metadata: if set to be a list, metadata about the function execution including its name, the source & dest duration, fps, etc. will be appended to the inputted list. If set to None, no metadata will be appended or returned @returns: the path to the augmented video
Here is the function:
def shift(
video_path: str,
output_path: Optional[str] = None,
x_factor: float = 0.0,
y_factor: float = 0.0,
color: Tuple[int, int, int] = utils.DEFAULT_COLOR,
metadata: Optional[List[Dict[str, Any]]] = None,
) -> str:
"""
Shifts the original frame position from the center by a vector
(width * x_factor, height * y_factor) and pads the rest with a
colored margin
@param video_path: the path to the video to be augmented
@param output_path: the path in which the resulting video will be stored.
If not passed in, the original video file will be overwritten
@param x_factor: the horizontal amount that the video should be shifted,
relative to the width of the video
@param y_factor: the vertical amount that the video should be shifted,
relative to the height of the video
@param color: RGB color of the margin generated by the shift. Default color is black
@param metadata: if set to be a list, metadata about the function execution
including its name, the source & dest duration, fps, etc. will be appended
to the inputted list. If set to None, no metadata will be appended or returned
@returns: the path to the augmented video
"""
func_kwargs = helpers.get_func_kwargs(metadata, locals(), video_path)
utils.validate_video_path(video_path)
video_info = helpers.get_video_info(video_path)
with tempfile.TemporaryDirectory() as tmpdir:
background_path = os.path.join(tmpdir, "background.mp4")
helpers.create_color_video(
background_path,
float(video_info["duration"]),
video_info["height"],
video_info["width"],
color,
)
overlay(
background_path,
video_path,
output_path,
x_factor=x_factor,
y_factor=y_factor,
use_overlay_audio=True,
)
if metadata is not None:
helpers.get_metadata(metadata=metadata, function_name="shift", **func_kwargs)
return output_path or video_path | Shifts the original frame position from the center by a vector (width * x_factor, height * y_factor) and pads the rest with a colored margin @param video_path: the path to the video to be augmented @param output_path: the path in which the resulting video will be stored. If not passed in, the original video file will be overwritten @param x_factor: the horizontal amount that the video should be shifted, relative to the width of the video @param y_factor: the vertical amount that the video should be shifted, relative to the height of the video @param color: RGB color of the margin generated by the shift. Default color is black @param metadata: if set to be a list, metadata about the function execution including its name, the source & dest duration, fps, etc. will be appended to the inputted list. If set to None, no metadata will be appended or returned @returns: the path to the augmented video |
160,815 | import functools
import math
import os
import shutil
import tempfile
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
import numpy as np
from augly import audio as audaugs, image as imaugs, utils
from augly.audio import utils as audutils
from augly.video import helpers, utils as vdutils
from augly.video.augmenters import cv2 as ac, ffmpeg as af
The provided code snippet includes necessary dependencies for implementing the `time_crop` function. Write a Python function `def time_crop( video_path: str, output_path: Optional[str] = None, offset_factor: float = 0.0, duration_factor: float = 1.0, minimum_duration: float = 0.0, metadata: Optional[List[Dict[str, Any]]] = None, ) -> str` to solve the following problem:
Crops the video using the specified offset and duration factors @param video_path: the path to the video to be augmented @param output_path: the path in which the resulting video will be stored. If not passed in, the original video file will be overwritten @param offset_factor: start point of the crop relative to the video duration (this parameter is multiplied by the video duration) @param duration_factor: the length of the crop relative to the video duration (this parameter is multiplied by the video duration) @param minimum_duration: the minimum duration of a segment selected @param metadata: if set to be a list, metadata about the function execution including its name, the source & dest duration, fps, etc. will be appended to the inputted list. If set to None, no metadata will be appended or returned @returns: the path to the augmented video
Here is the function:
def time_crop(
video_path: str,
output_path: Optional[str] = None,
offset_factor: float = 0.0,
duration_factor: float = 1.0,
minimum_duration: float = 0.0,
metadata: Optional[List[Dict[str, Any]]] = None,
) -> str:
"""
Crops the video using the specified offset and duration factors
@param video_path: the path to the video to be augmented
@param output_path: the path in which the resulting video will be stored.
If not passed in, the original video file will be overwritten
@param offset_factor: start point of the crop relative to the video duration
(this parameter is multiplied by the video duration)
@param duration_factor: the length of the crop relative to the video duration
(this parameter is multiplied by the video duration)
@param minimum_duration: the minimum duration of a segment selected
@param metadata: if set to be a list, metadata about the function execution
including its name, the source & dest duration, fps, etc. will be appended
to the inputted list. If set to None, no metadata will be appended or returned
@returns: the path to the augmented video
"""
func_kwargs = helpers.get_func_kwargs(metadata, locals(), video_path)
time_crop_aug = af.VideoAugmenterByTrim(
offset_factor=offset_factor,
duration_factor=duration_factor,
minimum_duration=minimum_duration,
)
time_crop_aug.add_augmenter(video_path, output_path)
if metadata is not None:
helpers.get_metadata(
metadata=metadata, function_name="time_crop", **func_kwargs
)
return output_path or video_path | Crops the video using the specified offset and duration factors @param video_path: the path to the video to be augmented @param output_path: the path in which the resulting video will be stored. If not passed in, the original video file will be overwritten @param offset_factor: start point of the crop relative to the video duration (this parameter is multiplied by the video duration) @param duration_factor: the length of the crop relative to the video duration (this parameter is multiplied by the video duration) @param minimum_duration: the minimum duration of a segment selected @param metadata: if set to be a list, metadata about the function execution including its name, the source & dest duration, fps, etc. will be appended to the inputted list. If set to None, no metadata will be appended or returned @returns: the path to the augmented video |
160,816 | import functools
import math
import os
import shutil
import tempfile
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
import numpy as np
from augly import audio as audaugs, image as imaugs, utils
from augly.audio import utils as audutils
from augly.video import helpers, utils as vdutils
from augly.video.augmenters import cv2 as ac, ffmpeg as af
def concat(
video_paths: List[str],
output_path: Optional[str] = None,
src_video_path_index: int = 0,
transition: Optional[af.TransitionConfig] = None,
metadata: Optional[List[Dict[str, Any]]] = None,
) -> str:
"""
Concatenates videos together. Resizes all other videos to the size of the
`source` video (video_paths[src_video_path_index]), and modifies the sample
aspect ratios to match (ffmpeg will fail to concat if SARs don't match)
If not passed in, the original video file will be overwritten
the list `video_paths` should be considered the `source` or original video
including its name, the source & dest duration, fps, etc. will be appended
to the inputted list. If set to None, no metadata will be appended or returned
"""
func_kwargs = helpers.get_func_kwargs(
metadata, locals(), video_paths[src_video_path_index]
)
concat_aug = af.VideoAugmenterByConcat(
video_paths,
src_video_path_index,
transition,
)
concat_aug.add_augmenter(video_paths[src_video_path_index], output_path)
if metadata is not None:
helpers.get_metadata(
metadata=metadata,
function_name="concat",
video_path=video_paths[src_video_path_index],
**func_kwargs,
)
return output_path or video_paths[src_video_path_index]
def trim(
video_path: str,
output_path: Optional[str] = None,
start: Optional[float] = None,
end: Optional[float] = None,
metadata: Optional[List[Dict[str, Any]]] = None,
) -> str:
"""
Trims the video using the specified start and end parameters
If not passed in, the original video file will be overwritten
If None, start will be 0
If None, the end will be the duration of the video
including its name, the source & dest duration, fps, etc. will be appended
to the inputted list. If set to None, no metadata will be appended or returned
"""
func_kwargs = helpers.get_func_kwargs(metadata, locals(), video_path)
trim_aug = af.VideoAugmenterByTrim(start=start, end=end)
trim_aug.add_augmenter(video_path, output_path)
if metadata is not None:
helpers.get_metadata(metadata=metadata, function_name="trim", **func_kwargs)
return output_path or video_path
The provided code snippet includes necessary dependencies for implementing the `time_decimate` function. Write a Python function `def time_decimate( video_path: str, output_path: Optional[str] = None, start_offset_factor: float = 0.0, on_factor: float = 0.2, off_factor: float = 0.5, transition: Optional[af.TransitionConfig] = None, metadata: Optional[List[Dict[str, Any]]] = None, ) -> str` to solve the following problem:
Removes evenly sized (off) chunks, and concatenates evenly spaced (on) chunks from the video @param video_path: the path to the video to be augmented @param output_path: the path in which the resulting video will be stored. If not passed in, the original video file will be overwritten @param start_offset_factor: relative to the video duration; the offset at which to start taking "on" segments @param on_factor: relative to the video duration; the amount of time each "on" video chunk should be @param off_factor: relative to the "on" duration; the amount of time each "off" video chunk should be @param transition: optional transition configuration to apply between the clips @param metadata: if set to be a list, metadata about the function execution including its name, the source & dest duration, fps, etc. will be appended to the inputted list. If set to None, no metadata will be appended or returned @returns: the path to the augmented video
Here is the function:
def time_decimate(
video_path: str,
output_path: Optional[str] = None,
start_offset_factor: float = 0.0,
on_factor: float = 0.2,
off_factor: float = 0.5,
transition: Optional[af.TransitionConfig] = None,
metadata: Optional[List[Dict[str, Any]]] = None,
) -> str:
"""
Removes evenly sized (off) chunks, and concatenates evenly spaced (on)
chunks from the video
@param video_path: the path to the video to be augmented
@param output_path: the path in which the resulting video will be stored.
If not passed in, the original video file will be overwritten
@param start_offset_factor: relative to the video duration; the offset
at which to start taking "on" segments
@param on_factor: relative to the video duration; the amount of time each
"on" video chunk should be
@param off_factor: relative to the "on" duration; the amount of time each
"off" video chunk should be
@param transition: optional transition configuration to apply between the clips
@param metadata: if set to be a list, metadata about the function execution
including its name, the source & dest duration, fps, etc. will be appended
to the inputted list. If set to None, no metadata will be appended or returned
@returns: the path to the augmented video
"""
assert (
0 <= start_offset_factor < 1
), f"start_offset_factor value {start_offset_factor} must be in the range [0, 1)"
assert 0 < on_factor <= 1, "on_factor must be a value in the range (0, 1]"
assert 0 <= off_factor <= 1, "off_factor must be a value in the range [0, 1]"
func_kwargs = helpers.get_func_kwargs(metadata, locals(), video_path)
local_path = utils.pathmgr.get_local_path(video_path)
utils.validate_video_path(local_path)
video_info = helpers.get_video_info(local_path)
_, video_ext = os.path.splitext(local_path)
duration = float(video_info["duration"])
start_offset = duration * start_offset_factor
on_segment = duration * on_factor
off_segment = on_segment * off_factor
subclips = []
n = int((duration - start_offset) / (on_segment + off_segment))
# let a = on_segment and b = off_segment
# subclips: 0->a, a+b -> 2*a + b, 2a+2b -> 3a+2b, .., na+nb -> (n+1)a + nb
with tempfile.TemporaryDirectory() as tmpdir:
for i in range(n):
clip_path = os.path.join(tmpdir, f"{i}{video_ext}")
trim(
video_path,
clip_path,
start=start_offset + i * on_segment + i * off_segment,
end=min(
duration, start_offset + (i + 1) * on_segment + i * off_segment
),
)
subclips.append(clip_path)
# Skip concatenation if only 1 clip.
if n > 1:
concat(
subclips,
output_path,
transition=transition,
)
else:
if output_path is not None:
shutil.copy(subclips[0], output_path)
else:
shutil.copy(subclips[0], local_path)
if metadata is not None:
helpers.get_metadata(
metadata=metadata, function_name="time_decimate", **func_kwargs
)
return output_path or video_path | Removes evenly sized (off) chunks, and concatenates evenly spaced (on) chunks from the video @param video_path: the path to the video to be augmented @param output_path: the path in which the resulting video will be stored. If not passed in, the original video file will be overwritten @param start_offset_factor: relative to the video duration; the offset at which to start taking "on" segments @param on_factor: relative to the video duration; the amount of time each "on" video chunk should be @param off_factor: relative to the "on" duration; the amount of time each "off" video chunk should be @param transition: optional transition configuration to apply between the clips @param metadata: if set to be a list, metadata about the function execution including its name, the source & dest duration, fps, etc. will be appended to the inputted list. If set to None, no metadata will be appended or returned @returns: the path to the augmented video |
160,817 | import functools
import math
import os
import shutil
import tempfile
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
import numpy as np
from augly import audio as audaugs, image as imaugs, utils
from augly.audio import utils as audutils
from augly.video import helpers, utils as vdutils
from augly.video.augmenters import cv2 as ac, ffmpeg as af
The provided code snippet includes necessary dependencies for implementing the `vflip` function. Write a Python function `def vflip( video_path: str, output_path: Optional[str] = None, metadata: Optional[List[Dict[str, Any]]] = None, ) -> str` to solve the following problem:
Vertically flips a video @param video_path: the path to the video to be augmented @param output_path: the path in which the resulting video will be stored. If not passed in, the original video file will be overwritten @param metadata: if set to be a list, metadata about the function execution including its name, the source & dest duration, fps, etc. will be appended to the inputted list. If set to None, no metadata will be appended or returned @returns: the path to the augmented video
Here is the function:
def vflip(
video_path: str,
output_path: Optional[str] = None,
metadata: Optional[List[Dict[str, Any]]] = None,
) -> str:
"""
Vertically flips a video
@param video_path: the path to the video to be augmented
@param output_path: the path in which the resulting video will be stored.
If not passed in, the original video file will be overwritten
@param metadata: if set to be a list, metadata about the function execution
including its name, the source & dest duration, fps, etc. will be appended
to the inputted list. If set to None, no metadata will be appended or returned
@returns: the path to the augmented video
"""
func_kwargs = helpers.get_func_kwargs(metadata, locals(), video_path)
vflip_aug = af.VideoAugmenterByVFlip()
vflip_aug.add_augmenter(video_path, output_path)
if metadata is not None:
helpers.get_metadata(metadata=metadata, function_name="vflip", **func_kwargs)
return output_path or video_path | Vertically flips a video @param video_path: the path to the video to be augmented @param output_path: the path in which the resulting video will be stored. If not passed in, the original video file will be overwritten @param metadata: if set to be a list, metadata about the function execution including its name, the source & dest duration, fps, etc. will be appended to the inputted list. If set to None, no metadata will be appended or returned @returns: the path to the augmented video |
160,818 | import functools
import math
import os
import shutil
import tempfile
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
import numpy as np
from augly import audio as audaugs, image as imaugs, utils
from augly.audio import utils as audutils
from augly.video import helpers, utils as vdutils
from augly.video.augmenters import cv2 as ac, ffmpeg as af
The provided code snippet includes necessary dependencies for implementing the `vstack` function. Write a Python function `def vstack( video_path: str, second_video_path: str, output_path: Optional[str] = None, use_second_audio: bool = False, metadata: Optional[List[Dict[str, Any]]] = None, ) -> str` to solve the following problem:
Vertically stacks two videos @param video_path: the path to the video that will be stacked on top @param second_video_path: the path to the video that will be stacked on the bottom @param output_path: the path in which the resulting video will be stored. If not passed in, the original video file will be overwritten @param use_second_audio: if set to True, the audio of the bottom video will be used instead of the top's @param metadata: if set to be a list, metadata about the function execution including its name, the source & dest duration, fps, etc. will be appended to the inputted list. If set to None, no metadata will be appended or returned @returns: the path to the augmented video
Here is the function:
def vstack(
video_path: str,
second_video_path: str,
output_path: Optional[str] = None,
use_second_audio: bool = False,
metadata: Optional[List[Dict[str, Any]]] = None,
) -> str:
"""
Vertically stacks two videos
@param video_path: the path to the video that will be stacked on top
@param second_video_path: the path to the video that will be stacked on the bottom
@param output_path: the path in which the resulting video will be stored.
If not passed in, the original video file will be overwritten
@param use_second_audio: if set to True, the audio of the bottom video will be used
instead of the top's
@param metadata: if set to be a list, metadata about the function execution
including its name, the source & dest duration, fps, etc. will be appended
to the inputted list. If set to None, no metadata will be appended or returned
@returns: the path to the augmented video
"""
func_kwargs = helpers.get_func_kwargs(metadata, locals(), video_path)
vstack_aug = af.VideoAugmenterByStack(second_video_path, use_second_audio, "vstack")
vstack_aug.add_augmenter(video_path, output_path)
if metadata is not None:
helpers.get_metadata(metadata=metadata, function_name="vstack", **func_kwargs)
return output_path or video_path | Vertically stacks two videos @param video_path: the path to the video that will be stacked on top @param second_video_path: the path to the video that will be stacked on the bottom @param output_path: the path in which the resulting video will be stored. If not passed in, the original video file will be overwritten @param use_second_audio: if set to True, the audio of the bottom video will be used instead of the top's @param metadata: if set to be a list, metadata about the function execution including its name, the source & dest duration, fps, etc. will be appended to the inputted list. If set to None, no metadata will be appended or returned @returns: the path to the augmented video |
160,819 |
def install_libsndfile():
pass | null |
160,820 | import os
from typing import Tuple
import magic
from augly.utils.io import pathmgr
def is_audio_file(filename: str) -> bool:
return is_content_type(filename, "audio")
def is_video_file(filename: str) -> bool:
return is_content_type(filename, "video")
def validate_path(file_path: str) -> None:
correct_type = type(file_path) == str
path_exists = pathmgr.exists(file_path)
assert correct_type and path_exists, f"Path is invalid: {file_path}"
def validate_audio_path(audio_path: str) -> None:
validate_path(audio_path)
# since `librosa` can extract audio from audio and video
# paths, we check for both here
assert is_audio_file(audio_path) or is_video_file(
audio_path
), f"Audio path invalid: {audio_path}" | null |
160,821 | import os
from typing import Tuple
import magic
from augly.utils.io import pathmgr
def is_image_file(filename: str) -> bool:
return is_content_type(filename, "image")
def validate_path(file_path: str) -> None:
correct_type = type(file_path) == str
path_exists = pathmgr.exists(file_path)
assert correct_type and path_exists, f"Path is invalid: {file_path}"
def validate_image_path(image_path: str) -> None:
validate_path(image_path)
assert is_image_file(image_path), f"Image path invalid: {image_path}" | null |
160,822 | import os
from typing import Tuple
import magic
from augly.utils.io import pathmgr
def is_video_file(filename: str) -> bool:
def validate_path(file_path: str) -> None:
def validate_video_path(video_path: str) -> None:
validate_path(video_path)
assert is_video_file(video_path), f"Video path invalid: {video_path}" | null |
160,823 | import os
from typing import Tuple
import magic
from augly.utils.io import pathmgr
pathmgr = PathManager()
pathmgr.register_handler(HTTPURLHandler())
pathmgr.set_strict_kwargs_checking(False)
def validate_output_path(output_path: str) -> None:
correct_type = type(output_path) == str
dir_exists = pathmgr.exists(os.path.dirname(output_path))
assert correct_type and dir_exists, f"Output path invalid: {output_path}" | null |
160,824 | import os
from typing import Tuple
import magic
from augly.utils.io import pathmgr
def validate_rgb_color(color: Tuple[int, int, int]) -> None:
correct_len = len(color) == 3
correct_values = all(0 <= c <= 255 for c in color)
assert correct_len and correct_values, "Invalid RGB color specified" | null |
160,825 | from typing import List
from augly.utils.classes import Segment
class Segment(NamedTuple):
start: float
end: float
src_id: Optional[str] = None
def delta(self, start_delta: float, end_delta: float):
new_start = self.start + start_delta
new_end = self.end + end_delta
if new_start > new_end:
raise ValueError(
f"Invalid segment created: expected {new_start} < {new_end}."
)
return Segment(new_start, new_end, self.src_id)
The provided code snippet includes necessary dependencies for implementing the `compute_time_crop_segments` function. Write a Python function `def compute_time_crop_segments( src_segment: Segment, dst_segment: Segment, speed_factor: float, crop_start: float, crop_end: float, new_src_segments: List[Segment], new_dst_segments: List[Segment], ) -> None` to solve the following problem:
Calculates how the given matching pair src_segment & dst_segment change given a temporal crop starting at crop_start & ending at crop_end. We can use the same logic here for multiple transforms, by setting the crop_start & crop_end depending on the transform kwargs. Doesn't return anything, but appends the new matching segments in the dst video corresponding to the pair passed in to new_src_segments & new_dst_segments, if the segment pair still matches in the dst video. If the passed in segment pair is cropped out as a result of this temporal crop, nothing will be appended to the lists, since the segment pair doesn't exist in the dst video.
Here is the function:
def compute_time_crop_segments(
src_segment: Segment,
dst_segment: Segment,
speed_factor: float,
crop_start: float,
crop_end: float,
new_src_segments: List[Segment],
new_dst_segments: List[Segment],
) -> None:
"""
Calculates how the given matching pair src_segment & dst_segment change
given a temporal crop starting at crop_start & ending at crop_end. We can
use the same logic here for multiple transforms, by setting the crop_start
& crop_end depending on the transform kwargs.
Doesn't return anything, but appends the new matching segments in the dst
video corresponding to the pair passed in to new_src_segments & new_dst_segments,
if the segment pair still matches in the dst video. If the passed in segment
pair is cropped out as a result of this temporal crop, nothing will be
appended to the lists, since the segment pair doesn't exist in the dst video.
"""
# Crop segment is outside of the initial clip, so this matching segment
# pair no longer exists in the new video.
if crop_start >= dst_segment.end or crop_end <= dst_segment.start:
return
# new_start represents where the matching segment starts in the dst audio
# (if negative, then part of the matching segment is getting cut out, so
# we need to adjust both the src & dst starts).
new_start = dst_segment.start - crop_start
src_start, src_end, src_id = src_segment
if new_start < 0:
# We're cropping the beginning of the matching segment.
# Note: if the video was sped up before, we need to take this into account
# (the matching segment that is e.g. 10 seconds of dst audio might
# correspond to 5 seconds of src audio, if it was previously
# slowed down by 0.5x).
src_start = src_segment.start - new_start * speed_factor
new_start = 0
new_end = min(dst_segment.end - crop_start, crop_end - crop_start)
if crop_end < dst_segment.end:
# We're cropping the end of the matching segment.
# Note: if the video was sped up before, we need to take this into
# account (as above).
src_end = src_segment.end - (dst_segment.end - crop_end) * speed_factor
new_src_segments.append(Segment(src_start, src_end))
new_dst_segments.append(Segment(new_start, new_end)) | Calculates how the given matching pair src_segment & dst_segment change given a temporal crop starting at crop_start & ending at crop_end. We can use the same logic here for multiple transforms, by setting the crop_start & crop_end depending on the transform kwargs. Doesn't return anything, but appends the new matching segments in the dst video corresponding to the pair passed in to new_src_segments & new_dst_segments, if the segment pair still matches in the dst video. If the passed in segment pair is cropped out as a result of this temporal crop, nothing will be appended to the lists, since the segment pair doesn't exist in the dst video. |
160,826 | import os
from distutils import spawn
from typing import Tuple
def get_conditional_for_skipping_video_tests() -> Tuple[bool, str]:
return (True, "We currently do not need to skip any video tests") | null |
160,827 | import os
import sys
from ctypes import *
from pathlib import Path
import cv2
import numpy as np
def run(img_style, guides,
patch_size=5,
num_pyramid_levels=-1,
num_search_vote_iters=6,
num_patch_match_iters=4,
stop_threshold=5,
uniformity_weight=3500.0,
extraPass3x3=False,
):
if patch_size < 3:
raise ValueError("patch_size is too small")
if patch_size % 2 == 0:
raise ValueError("patch_size must be an odd number")
if len(guides) == 0:
raise ValueError("at least one guide must be specified")
global libebsynth
if libebsynth is None:
if sys.platform[0:3] == 'win':
libebsynth_path = str(Path(__file__).parent / 'ebsynth.dll')
libebsynth = CDLL(libebsynth_path)
else:
# todo: implement for linux
pass
if libebsynth is not None:
libebsynth.ebsynthRun.argtypes = ( \
c_int,
c_int,
c_int,
c_int,
c_int,
c_void_p,
c_void_p,
c_int,
c_int,
c_void_p,
c_void_p,
POINTER(c_float),
POINTER(c_float),
c_float,
c_int,
c_int,
c_int,
POINTER(c_int),
POINTER(c_int),
POINTER(c_int),
c_int,
c_void_p,
c_void_p
)
if libebsynth is None:
return img_style
img_style = _normalize_img_shape(img_style)
sh, sw, sc = img_style.shape
t_h, t_w, t_c = 0, 0, 0
if sc > EBSYNTH_MAX_STYLE_CHANNELS:
raise ValueError(f"error: too many style channels {sc}, maximum number is {EBSYNTH_MAX_STYLE_CHANNELS}")
guides_source = []
guides_target = []
guides_weights = []
for i in range(len(guides)):
source_guide, target_guide, guide_weight = guides[i]
source_guide = _normalize_img_shape(source_guide)
target_guide = _normalize_img_shape(target_guide)
s_h, s_w, s_c = source_guide.shape
nt_h, nt_w, nt_c = target_guide.shape
if s_h != sh or s_w != sw:
raise ValueError("guide source and style resolution must match style resolution.")
if t_c == 0:
t_h, t_w, t_c = nt_h, nt_w, nt_c
elif nt_h != t_h or nt_w != t_w:
raise ValueError("guides target resolutions must be equal")
if s_c != nt_c:
raise ValueError("guide source and target channels must match exactly.")
guides_source.append(source_guide)
guides_target.append(target_guide)
guides_weights += [guide_weight / s_c] * s_c
guides_source = np.concatenate(guides_source, axis=-1)
guides_target = np.concatenate(guides_target, axis=-1)
guides_weights = (c_float * len(guides_weights))(*guides_weights)
styleWeight = 1.0
style_weights = [styleWeight / sc for i in range(sc)]
style_weights = (c_float * sc)(*style_weights)
maxPyramidLevels = 0
for level in range(32, -1, -1):
if min(min(sh, t_h) * pow(2.0, -level), \
min(sw, t_w) * pow(2.0, -level)) >= (2 * patch_size + 1):
maxPyramidLevels = level + 1
break
if num_pyramid_levels == -1:
num_pyramid_levels = maxPyramidLevels
num_pyramid_levels = min(num_pyramid_levels, maxPyramidLevels)
num_search_vote_iters_per_level = (c_int * num_pyramid_levels)(*[num_search_vote_iters] * num_pyramid_levels)
num_patch_match_iters_per_level = (c_int * num_pyramid_levels)(*[num_patch_match_iters] * num_pyramid_levels)
stop_threshold_per_level = (c_int * num_pyramid_levels)(*[stop_threshold] * num_pyramid_levels)
buffer = cached_buffer.get((t_h, t_w, sc), None)
if buffer is None:
buffer = create_string_buffer(t_h * t_w * sc)
cached_buffer[(t_h, t_w, sc)] = buffer
libebsynth.ebsynthRun(EBSYNTH_BACKEND_AUTO, # backend
sc, # numStyleChannels
guides_source.shape[-1], # numGuideChannels
sw, # sourceWidth
sh, # sourceHeight
img_style.tobytes(),
# sourceStyleData (width * height * numStyleChannels) bytes, scan-line order
guides_source.tobytes(),
# sourceGuideData (width * height * numGuideChannels) bytes, scan-line order
t_w, # targetWidth
t_h, # targetHeight
guides_target.tobytes(),
# targetGuideData (width * height * numGuideChannels) bytes, scan-line order
None,
# targetModulationData (width * height * numGuideChannels) bytes, scan-line order; pass NULL to switch off the modulation
style_weights, # styleWeights (numStyleChannels) floats
guides_weights, # guideWeights (numGuideChannels) floats
uniformity_weight,
# uniformityWeight reasonable values are between 500-15000, 3500 is a good default
patch_size, # patchSize odd sizes only, use 5 for 5x5 patch, 7 for 7x7, etc.
EBSYNTH_VOTEMODE_WEIGHTED, # voteMode use VOTEMODE_WEIGHTED for sharper result
num_pyramid_levels, # numPyramidLevels
num_search_vote_iters_per_level,
# numSearchVoteItersPerLevel how many search/vote iters to perform at each level (array of ints, coarse first, fine last)
num_patch_match_iters_per_level,
# numPatchMatchItersPerLevel how many Patch-Match iters to perform at each level (array of ints, coarse first, fine last)
stop_threshold_per_level,
# stopThresholdPerLevel stop improving pixel when its change since last iteration falls under this threshold
1 if extraPass3x3 else 0,
# extraPass3x3 perform additional polishing pass with 3x3 patches at the finest level, use 0 to disable
None, # outputNnfData (width * height * 2) ints, scan-line order; pass NULL to ignore
buffer # outputImageData (width * height * numStyleChannels) bytes, scan-line order
)
return np.frombuffer(buffer, dtype=np.uint8).reshape((t_h, t_w, sc)).copy()
def color_transfer(img_source, img_target):
guides = [(cv2.cvtColor(img_source, cv2.COLOR_BGR2GRAY),
cv2.cvtColor(img_target, cv2.COLOR_BGR2GRAY),
1)]
h, w, c = img_source.shape
result = []
for i in range(c):
result += [
run(img_source[..., i:i + 1], guides=guides,
patch_size=11,
num_pyramid_levels=40,
num_search_vote_iters=6,
num_patch_match_iters=4,
stop_threshold=5,
uniformity_weight=500.0,
extraPass3x3=True,
)
]
return np.concatenate(result, axis=-1) | null |
160,828 | import os.path
import platform
import cv2
import numpy
import imageio
def get_mov_frame_count(file):
if file is None:
return None
cap = cv2.VideoCapture(file)
if not cap.isOpened():
return None
frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
cap.release()
return frames | null |
160,829 | import os.path
import platform
import cv2
import numpy
import imageio
def get_mov_fps(file):
if file is None:
return None
cap = cv2.VideoCapture(file)
if not cap.isOpened():
return None
fps = cap.get(cv2.CAP_PROP_FPS)
cap.release()
return fps | null |
160,830 | import importlib
import os
import platform
import shutil
import subprocess as sp
import sys
import gradio as gr
import modules
import modules.scripts as scripts
from modules import (
script_callbacks,
shared,
call_queue,
sd_samplers,
ui_prompt_styles,
sd_models,
)
from modules.call_queue import wrap_gradio_gpu_call
from modules.images import image_data
from modules.shared import opts
from modules.ui import (
ordered_ui_categories,
create_sampler_and_steps_selection,
switch_values_symbol,
create_override_settings_dropdown,
detect_image_size_symbol,
plaintext_to_html,
paste_symbol,
clear_prompt_symbol,
restore_progress_symbol,
)
from modules.ui_common import (
folder_symbol,
update_generation_info,
create_refresh_button,
)
from modules.ui_components import (
ResizeHandleRow,
FormRow,
ToolButton,
FormGroup,
InputAccordion,
)
from scripts import m2m_hook as patches
from scripts import m2m_util
from scripts import mov2mov
from scripts.mov2mov import scripts_mov2mov
from scripts.m2m_config import mov2mov_outpath_samples, mov2mov_output_dir
from scripts.movie_editor import MovieEditor
id_part = "mov2mov"
def create_refiner():
with InputAccordion(
False, label="Refiner", elem_id=f"{id_part}_enable"
) as enable_refiner:
with gr.Row():
refiner_checkpoint = gr.Dropdown(
label="Checkpoint",
elem_id=f"{id_part}_checkpoint",
choices=sd_models.checkpoint_tiles(),
value="",
tooltip="switch to another model in the middle of generation",
)
create_refresh_button(
refiner_checkpoint,
sd_models.list_models,
lambda: {"choices": sd_models.checkpoint_tiles()},
f"{id_part}_checkpoint_refresh",
)
refiner_switch_at = gr.Slider(
value=0.8,
label="Switch at",
minimum=0.01,
maximum=1.0,
step=0.01,
elem_id=f"{id_part}_switch_at",
tooltip="fraction of sampling steps when the switch to refiner model should happen; 1=never, 0.5=switch in the middle of generation",
)
return enable_refiner, refiner_checkpoint, refiner_switch_at | null |
160,831 | import importlib
import os
import platform
import shutil
import subprocess as sp
import sys
import gradio as gr
import modules
import modules.scripts as scripts
from modules import (
script_callbacks,
shared,
call_queue,
sd_samplers,
ui_prompt_styles,
sd_models,
)
from modules.call_queue import wrap_gradio_gpu_call
from modules.images import image_data
from modules.shared import opts
from modules.ui import (
ordered_ui_categories,
create_sampler_and_steps_selection,
switch_values_symbol,
create_override_settings_dropdown,
detect_image_size_symbol,
plaintext_to_html,
paste_symbol,
clear_prompt_symbol,
restore_progress_symbol,
)
from modules.ui_common import (
folder_symbol,
update_generation_info,
create_refresh_button,
)
from modules.ui_components import (
ResizeHandleRow,
FormRow,
ToolButton,
FormGroup,
InputAccordion,
)
from scripts import m2m_hook as patches
from scripts import m2m_util
from scripts import mov2mov
from scripts.mov2mov import scripts_mov2mov
from scripts.m2m_config import mov2mov_outpath_samples, mov2mov_output_dir
from scripts.movie_editor import MovieEditor
mov2mov_outpath_samples = 'outputs/mov2mov-images'
mov2mov_output_dir = 'outputs/mov2mov-videos'
def on_ui_settings():
section = ("mov2mov", "Mov2Mov")
shared.opts.add_option(
"mov2mov_outpath_samples",
shared.OptionInfo(
mov2mov_outpath_samples, "Mov2Mov output path for image", section=section
),
)
shared.opts.add_option(
"mov2mov_output_dir",
shared.OptionInfo(
mov2mov_output_dir, "Mov2Mov output path for video", section=section
),
) | null |
160,832 | import importlib
import os
import platform
import shutil
import subprocess as sp
import sys
import gradio as gr
import modules
import modules.scripts as scripts
from modules import (
script_callbacks,
shared,
call_queue,
sd_samplers,
ui_prompt_styles,
sd_models,
)
from modules.call_queue import wrap_gradio_gpu_call
from modules.images import image_data
from modules.shared import opts
from modules.ui import (
ordered_ui_categories,
create_sampler_and_steps_selection,
switch_values_symbol,
create_override_settings_dropdown,
detect_image_size_symbol,
plaintext_to_html,
paste_symbol,
clear_prompt_symbol,
restore_progress_symbol,
)
from modules.ui_common import (
folder_symbol,
update_generation_info,
create_refresh_button,
)
from modules.ui_components import (
ResizeHandleRow,
FormRow,
ToolButton,
FormGroup,
InputAccordion,
)
from scripts import m2m_hook as patches
from scripts import m2m_util
from scripts import mov2mov
from scripts.mov2mov import scripts_mov2mov
from scripts.m2m_config import mov2mov_outpath_samples, mov2mov_output_dir
from scripts.movie_editor import MovieEditor
def on_ui_tabs():
scripts_mov2mov.initialize_scripts(is_img2img=True)
# with gr.Blocks(analytics_enabled=False) as mov2mov_interface:
with gr.TabItem(
"mov2mov", id=f"tab_{id_part}", elem_id=f"tab_{id_part}"
) as mov2mov_interface:
toprow = Toprow(is_img2img=False, id_part=id_part)
dummy_component = gr.Label(visible=False)
with gr.Tab(
"Generation", id=f"{id_part}_generation"
) as mov2mov_generation_tab, ResizeHandleRow(equal_height=False):
with gr.Column(variant="compact", elem_id="mov2mov_settings"):
with gr.Tabs(elem_id=f"mode_{id_part}"):
init_mov = gr.Video(
label="Video for mov2mov",
elem_id=f"{id_part}_mov",
show_label=False,
source="upload",
)
with FormRow():
resize_mode = gr.Radio(
label="Resize mode",
elem_id=f"{id_part}_resize_mode",
choices=[
"Just resize",
"Crop and resize",
"Resize and fill",
"Just resize (latent upscale)",
],
type="index",
value="Just resize",
)
scripts_mov2mov.prepare_ui()
for category in ordered_ui_categories():
if category == "sampler":
steps, sampler_name = create_sampler_and_steps_selection(
sd_samplers.visible_sampler_names(), id_part
)
elif category == "dimensions":
with FormRow():
with gr.Column(elem_id=f"{id_part}_column_size", scale=4):
with gr.Tabs():
with gr.Tab(
label="Resize to",
elem_id=f"{id_part}_tab_resize_to",
) as tab_scale_to:
with FormRow():
with gr.Column(
elem_id=f"{id_part}_column_size",
scale=4,
):
width = gr.Slider(
minimum=64,
maximum=2048,
step=8,
label="Width",
value=512,
elem_id=f"{id_part}_width",
)
height = gr.Slider(
minimum=64,
maximum=2048,
step=8,
label="Height",
value=512,
elem_id=f"{id_part}_height",
)
with gr.Column(
elem_id=f"{id_part}_dimensions_row",
scale=1,
elem_classes="dimensions-tools",
):
res_switch_btn = ToolButton(
value=switch_values_symbol,
elem_id=f"{id_part}_res_switch_btn",
)
detect_image_size_btn = ToolButton(
value=detect_image_size_symbol,
elem_id=f"{id_part}_detect_image_size_btn",
)
elif category == "denoising":
denoising_strength = gr.Slider(
minimum=0.0,
maximum=1.0,
step=0.01,
label="Denoising strength",
value=0.75,
elem_id=f"{id_part}_denoising_strength",
)
noise_multiplier = gr.Slider(
minimum=0,
maximum=1.5,
step=0.01,
label="Noise multiplier",
elem_id=f"{id_part}_noise_multiplier",
value=1,
)
with gr.Row(elem_id=f"{id_part}_frames_setting"):
movie_frames = gr.Slider(
minimum=10,
maximum=60,
step=1,
label="Movie FPS",
elem_id=f"{id_part}_movie_frames",
value=30,
)
max_frames = gr.Number(
label="Max FPS",
value=-1,
elem_id=f"{id_part}_max_frames",
)
elif category == "cfg":
with gr.Row():
cfg_scale = gr.Slider(
minimum=1.0,
maximum=30.0,
step=0.5,
label="CFG Scale",
value=7.0,
elem_id=f"{id_part}_cfg_scale",
)
image_cfg_scale = gr.Slider(
minimum=0,
maximum=3.0,
step=0.05,
label="Image CFG Scale",
value=1.5,
elem_id=f"{id_part}_image_cfg_scale",
visible=False,
)
elif category == "checkboxes":
with FormRow(elem_classes="checkboxes-row", variant="compact"):
pass
elif category == "accordions":
with gr.Row(
elem_id=f"{id_part}_accordions", elem_classes="accordions"
):
scripts_mov2mov.setup_ui_for_section(category)
elif category == "override_settings":
with FormRow(elem_id=f"{id_part}_override_settings_row") as row:
override_settings = create_override_settings_dropdown(
"mov2mov", row
)
elif category == "scripts":
editor = MovieEditor(id_part, init_mov, movie_frames)
editor.render()
with FormGroup(elem_id=f"{id_part}_script_container"):
custom_inputs = scripts_mov2mov.setup_ui()
if category not in {"accordions"}:
scripts_mov2mov.setup_ui_for_section(category)
(
mov2mov_gallery,
result_video,
generation_info,
html_info,
html_log,
) = create_output_panel(id_part, opts.mov2mov_output_dir)
res_switch_btn.click(
fn=None,
_js="function(){switchWidthHeight('mov2mov')}",
inputs=None,
outputs=None,
show_progress=False,
)
# calc video size
detect_image_size_btn.click(
fn=calc_video_w_h,
inputs=[init_mov, width, height],
outputs=[width, height],
)
mov2mov_args = dict(
fn=wrap_gradio_gpu_call(mov2mov.mov2mov, extra_outputs=[None, "", ""]),
_js="submit_mov2mov",
inputs=[
dummy_component,
toprow.prompt,
toprow.negative_prompt,
toprow.ui_styles.dropdown,
init_mov,
steps,
sampler_name,
cfg_scale,
image_cfg_scale,
denoising_strength,
height,
width,
resize_mode,
override_settings,
# refiner
# enable_refiner, refiner_checkpoint, refiner_switch_at,
# mov2mov params
noise_multiplier,
movie_frames,
max_frames,
# editor
editor.gr_enable_movie_editor,
editor.gr_df,
editor.gr_eb_weight,
]
+ custom_inputs,
outputs=[
result_video,
generation_info,
html_info,
html_log,
],
show_progress=False,
)
toprow.submit.click(**mov2mov_args)
return [(mov2mov_interface, "mov2mov", f"{id_part}_tabs")]
origin_block_context_init = patches.patch(
__name__,
obj=gr.blocks.BlockContext,
field="__init__",
replacement=block_context_init,
)
def block_context_init(self, *args, **kwargs):
origin_block_context_init(self, *args, **kwargs)
if self.elem_id == "tab_img2img":
self.parent.__enter__()
on_ui_tabs()
self.parent.__exit__() | null |
160,833 | import importlib
import os
import platform
import shutil
import subprocess as sp
import sys
import gradio as gr
import modules
import modules.scripts as scripts
from modules import (
script_callbacks,
shared,
call_queue,
sd_samplers,
ui_prompt_styles,
sd_models,
)
from modules.call_queue import wrap_gradio_gpu_call
from modules.images import image_data
from modules.shared import opts
from modules.ui import (
ordered_ui_categories,
create_sampler_and_steps_selection,
switch_values_symbol,
create_override_settings_dropdown,
detect_image_size_symbol,
plaintext_to_html,
paste_symbol,
clear_prompt_symbol,
restore_progress_symbol,
)
from modules.ui_common import (
folder_symbol,
update_generation_info,
create_refresh_button,
)
from modules.ui_components import (
ResizeHandleRow,
FormRow,
ToolButton,
FormGroup,
InputAccordion,
)
from scripts import m2m_hook as patches
from scripts import m2m_util
from scripts import mov2mov
from scripts.mov2mov import scripts_mov2mov
from scripts.m2m_config import mov2mov_outpath_samples, mov2mov_output_dir
from scripts.movie_editor import MovieEditor
origin_block_context_init = patches.patch(
__name__,
obj=gr.blocks.BlockContext,
field="__init__",
replacement=block_context_init,
)
def on_app_reload():
global origin_block_context_init
if origin_block_context_init:
patches.undo(__name__, obj=gr.blocks.BlockContext, field="__init__")
origin_block_context_init = None | null |
160,834 | from collections import defaultdict
originals = defaultdict(dict)
The provided code snippet includes necessary dependencies for implementing the `patch` function. Write a Python function `def patch(key, obj, field, replacement)` to solve the following problem:
Replaces a function in a module or a class. Also stores the original function in this module, possible to be retrieved via original(key, obj, field). If the function is already replaced by this caller (key), an exception is raised -- use undo() before that. Arguments: key: identifying information for who is doing the replacement. You can use __name__. obj: the module or the class field: name of the function as a string replacement: the new function Returns: the original function
Here is the function:
def patch(key, obj, field, replacement):
"""Replaces a function in a module or a class.
Also stores the original function in this module, possible to be retrieved via original(key, obj, field).
If the function is already replaced by this caller (key), an exception is raised -- use undo() before that.
Arguments:
key: identifying information for who is doing the replacement. You can use __name__.
obj: the module or the class
field: name of the function as a string
replacement: the new function
Returns:
the original function
"""
patch_key = (obj, field)
if patch_key in originals[key]:
raise RuntimeError(f"patch for {field} is already applied")
original_func = getattr(obj, field)
originals[key][patch_key] = original_func
setattr(obj, field, replacement)
return original_func | Replaces a function in a module or a class. Also stores the original function in this module, possible to be retrieved via original(key, obj, field). If the function is already replaced by this caller (key), an exception is raised -- use undo() before that. Arguments: key: identifying information for who is doing the replacement. You can use __name__. obj: the module or the class field: name of the function as a string replacement: the new function Returns: the original function |
160,836 | import gradio
from modules import script_callbacks, ui_components
from scripts import m2m_hook as patches
def fix_elem_id(component, **kwargs):
if "elem_id" not in kwargs:
return None
elem_id = kwargs["elem_id"]
if not elem_id:
return None
if elem_id not in elem_ids:
elem_ids.append(elem_id)
else:
elem_id = elem_id + "_" + str(elem_ids.count(elem_id))
elem_ids.append(elem_id)
return elem_id
original_IOComponent_init = patches.patch(
__name__,
obj=gradio.components.IOComponent,
field="__init__",
replacement=IOComponent_init,
)
def IOComponent_init(self, *args, **kwargs):
elem_id = fix_elem_id(self, **kwargs)
if elem_id:
kwargs.pop("elem_id")
res = original_IOComponent_init(self, elem_id=elem_id, *args, **kwargs)
else:
res = original_IOComponent_init(self, *args, **kwargs)
return res | null |
160,837 | import gradio
from modules import script_callbacks, ui_components
from scripts import m2m_hook as patches
def fix_elem_id(component, **kwargs):
if "elem_id" not in kwargs:
return None
elem_id = kwargs["elem_id"]
if not elem_id:
return None
if elem_id not in elem_ids:
elem_ids.append(elem_id)
else:
elem_id = elem_id + "_" + str(elem_ids.count(elem_id))
elem_ids.append(elem_id)
return elem_id
original_InputAccordion_init = patches.patch(
__name__,
obj=ui_components.InputAccordion,
field="__init__",
replacement=InputAccordion_init,
)
def InputAccordion_init(self, *args, **kwargs):
elem_id = fix_elem_id(self, **kwargs)
if elem_id:
kwargs.pop("elem_id")
res = original_InputAccordion_init(self, elem_id=elem_id, *args, **kwargs)
else:
res = original_InputAccordion_init(self, *args, **kwargs)
return res | null |
160,838 | from setuptools import setup, find_packages
from pathlib import Path
import os
def _read_reqs(relpath):
fullpath = os.path.join(os.path.dirname(__file__), relpath)
with open(fullpath) as f:
return [s.strip() for s in f.readlines() if (s.strip() and not s.startswith("#"))] | null |
160,839 | from typing import List, Optional
import fire
import logging
from .logger import LoggerProcess
from .resizer import Resizer
from .blurrer import BoundingBoxBlurrer
from .writer import (
WebDatasetSampleWriter,
FilesSampleWriter,
ParquetSampleWriter,
TFRecordSampleWriter,
DummySampleWriter,
)
from .reader import Reader
from .downloader import Downloader
from .distributor import (
multiprocessing_distributor,
pyspark_distributor,
ray_distributor,
)
import fsspec
import sys
import signal
import os
def arguments_validator(params):
"""Validate the arguments"""
if params["compute_hash"] not in [None, "md5", "sha256", "sha512"]:
hash_type = params["compute_hash"]
raise ValueError(f"Unsupported hash to compute: {hash_type}")
if params["verify_hash"] is not None:
_, verify_hash_type = params["verify_hash"]
if verify_hash_type != params["compute_hash"]:
raise ValueError(
"verify_hash and compute_hash must be the same "
f"but got {verify_hash_type} and {params['compute_hash']}"
)
if params["save_additional_columns"] is not None:
save_additional_columns_set = set(params["save_additional_columns"])
forbidden_columns = set(
[
"key",
"caption",
"url",
"width",
"height",
"original_width",
"original_height",
"status",
"error_message",
"exif",
"md5",
"sha256",
"sha512",
]
)
intersection = save_additional_columns_set.intersection(forbidden_columns)
if intersection:
raise ValueError(
f"You cannot use in save_additional_columns the following columns: {intersection}."
+ "img2dataset reserves these columns for its own use. Please remove them from save_additional_columns."
)
class LoggerProcess(multiprocessing.context.SpawnProcess):
"""Logger process that reads stats files regularly, aggregates and send to wandb / print to terminal"""
def __init__(self, output_folder, enable_wandb, wandb_project, config_parameters, log_interval=5):
super().__init__()
self.log_interval = log_interval
self.enable_wandb = enable_wandb
self.output_folder = output_folder
self.stats_files = set()
self.wandb_project = wandb_project
self.done_shards = set()
self.config_parameters = config_parameters
ctx = multiprocessing.get_context("spawn")
self.q = ctx.Queue()
def run(self):
"""Run logger process"""
fs, output_path = fsspec.core.url_to_fs(self.output_folder, use_listings_cache=False)
if self.enable_wandb:
self.current_run = wandb.init(project=self.wandb_project, config=self.config_parameters, anonymous="allow")
else:
self.current_run = None
self.total_speed_logger = SpeedLogger("total", enable_wandb=self.enable_wandb)
self.status_table_logger = StatusTableLogger(enable_wandb=self.enable_wandb)
last_check = 0
total_status_dict = CappedCounter()
while True:
time.sleep(0.1)
try:
self.q.get(False)
last_one = True
except queue.Empty as _:
last_one = False
if not last_one and time.perf_counter() - last_check < self.log_interval:
continue
try:
# read stats files
stats_files = fs.glob(output_path + "/*.json")
# filter out files that have an id smaller that are already done
stats_files = [f for f in stats_files if int(f.split("/")[-1].split("_")[0]) not in self.done_shards]
# get new stats files
new_stats_files = set(stats_files) - self.stats_files
if len(new_stats_files) == 0:
if last_one:
self.finish()
return
# read new stats files
for stats_file in new_stats_files:
with fs.open(stats_file, "r") as f:
try:
stats = json.load(f)
SpeedLogger("worker", enable_wandb=self.enable_wandb)(
count=stats["count"],
success=stats["successes"],
failed_to_download=stats["failed_to_download"],
failed_to_resize=stats["failed_to_resize"],
start_time=stats["start_time"],
end_time=stats["end_time"],
)
self.total_speed_logger(
count=stats["count"],
success=stats["successes"],
failed_to_download=stats["failed_to_download"],
failed_to_resize=stats["failed_to_resize"],
start_time=stats["start_time"],
end_time=stats["end_time"],
)
status_dict = CappedCounter.load(stats["status_dict"])
total_status_dict.update(status_dict)
self.status_table_logger(total_status_dict, self.total_speed_logger.count)
except Exception as err: # pylint: disable=broad-except
print(f"failed to parse stats file {stats_file}", err)
self.stats_files.add(stats_file)
last_check = time.perf_counter()
if last_one:
self.finish()
return
except Exception as e: # pylint: disable=broad-except
traceback.print_exc()
print("logger error", e)
self.finish()
return
def finish(self):
"""Finish logger process"""
self.total_speed_logger.sync()
self.status_table_logger.sync()
if self.current_run is not None:
self.current_run.finish()
def join(self, timeout=None):
"""Stop logger process"""
self.q.put("stop")
super().join()
self.q.close()
class Resizer:
"""
Resize images
Expose a __call__ method to be used as a callable object
Should be used to resize one image at a time
Options:
resize_mode: "no", "keep_ratio", "center_crop", "border"
resize_only_if_bigger: if True, resize only if image is bigger than image_size
image_size: size of the output image to resize
"""
def __init__(
self,
image_size,
resize_mode,
resize_only_if_bigger,
upscale_interpolation="lanczos",
downscale_interpolation="area",
encode_quality=95,
encode_format="jpg",
skip_reencode=False,
disable_all_reencoding=False,
min_image_size=0,
max_image_area=float("inf"),
max_aspect_ratio=float("inf"),
blurrer=None,
):
if encode_format not in ["jpg", "png", "webp"]:
raise ValueError(f"Invalid encode format {encode_format}")
if encode_format == "png":
if encode_quality < 0 or encode_quality > 9:
raise ValueError(
"For png, encode quality represents compression which"
f"must be between 0 and 9, got {encode_quality}"
)
self.image_size = image_size
if isinstance(resize_mode, str):
if resize_mode not in ResizeMode.__members__: # pylint: disable=unsupported-membership-test
raise ValueError(f"Invalid option for resize_mode: {resize_mode}")
resize_mode = ResizeMode[resize_mode]
self.resize_mode = resize_mode
self.resize_only_if_bigger = resize_only_if_bigger
self.upscale_interpolation = inter_str_to_cv2(upscale_interpolation)
self.downscale_interpolation = inter_str_to_cv2(downscale_interpolation)
self.encode_format = encode_format
cv2_img_quality = None
if encode_format == "jpg":
cv2_img_quality = int(cv2.IMWRITE_JPEG_QUALITY)
self.what_ext = "jpeg"
elif encode_format == "png":
cv2_img_quality = int(cv2.IMWRITE_PNG_COMPRESSION)
self.what_ext = "png"
elif encode_format == "webp":
cv2_img_quality = int(cv2.IMWRITE_WEBP_QUALITY)
self.what_ext = "webp"
if cv2_img_quality is None:
raise ValueError(f"Invalid option for encode_format: {encode_format}")
self.encode_params = [cv2_img_quality, encode_quality]
self.skip_reencode = skip_reencode
self.disable_all_reencoding = disable_all_reencoding
self.min_image_size = min_image_size
self.max_image_area = max_image_area
self.max_aspect_ratio = max_aspect_ratio
self.blurrer = blurrer
def __call__(self, img_stream, blurring_bbox_list=None):
"""
input: an image stream, optionally a list of bounding boxes to blur.
output: img_str, width, height, original_width, original_height, err
"""
try:
if self.disable_all_reencoding:
return img_stream.read(), None, None, None, None, None
with SuppressStdoutStderr():
cv2.setNumThreads(1)
img_stream.seek(0)
encode_needed = imghdr.what(img_stream) != self.what_ext if self.skip_reencode else True
img_stream.seek(0)
img_buf = np.frombuffer(img_stream.read(), np.uint8)
img = cv2.imdecode(img_buf, cv2.IMREAD_UNCHANGED)
if img is None:
raise ValueError("Image decoding error")
if len(img.shape) == 3 and img.shape[-1] == 4:
# alpha matting with white background
alpha = img[:, :, 3, np.newaxis]
img = alpha / 255 * img[..., :3] + 255 - alpha
img = np.rint(img.clip(min=0, max=255)).astype(np.uint8)
encode_needed = True
original_height, original_width = img.shape[:2]
# check if image is too small
if min(original_height, original_width) < self.min_image_size:
return None, None, None, None, None, "image too small"
if original_height * original_width > self.max_image_area:
return None, None, None, None, None, "image area too large"
# check if wrong aspect ratio
if max(original_height, original_width) / min(original_height, original_width) > self.max_aspect_ratio:
return None, None, None, None, None, "aspect ratio too large"
# check if resizer was defined during init if needed
if blurring_bbox_list is not None and self.blurrer is None:
return None, None, None, None, None, "blurrer not defined"
# Flag to check if blurring is still needed.
maybe_blur_still_needed = True
# resizing in following conditions
if self.resize_mode in (ResizeMode.keep_ratio, ResizeMode.center_crop):
downscale = min(original_width, original_height) > self.image_size
if not self.resize_only_if_bigger or downscale:
interpolation = self.downscale_interpolation if downscale else self.upscale_interpolation
img = A.smallest_max_size(img, self.image_size, interpolation=interpolation)
if blurring_bbox_list is not None and self.blurrer is not None:
img = self.blurrer(img=img, bbox_list=blurring_bbox_list)
if self.resize_mode == ResizeMode.center_crop:
img = A.center_crop(img, self.image_size, self.image_size)
encode_needed = True
maybe_blur_still_needed = False
elif self.resize_mode in (ResizeMode.border, ResizeMode.keep_ratio_largest):
downscale = max(original_width, original_height) > self.image_size
if not self.resize_only_if_bigger or downscale:
interpolation = self.downscale_interpolation if downscale else self.upscale_interpolation
img = A.longest_max_size(img, self.image_size, interpolation=interpolation)
if blurring_bbox_list is not None and self.blurrer is not None:
img = self.blurrer(img=img, bbox_list=blurring_bbox_list)
if self.resize_mode == ResizeMode.border:
img = A.pad(
img,
self.image_size,
self.image_size,
border_mode=cv2.BORDER_CONSTANT,
value=[255, 255, 255],
)
encode_needed = True
maybe_blur_still_needed = False
# blur parts of the image if needed
if maybe_blur_still_needed and blurring_bbox_list is not None and self.blurrer is not None:
img = self.blurrer(img=img, bbox_list=blurring_bbox_list)
height, width = img.shape[:2]
if encode_needed:
img_str = cv2.imencode(f".{self.encode_format}", img, params=self.encode_params)[1].tobytes()
else:
img_str = img_buf.tobytes()
return img_str, width, height, original_width, original_height, None
except Exception as err: # pylint: disable=broad-except
return None, None, None, None, None, str(err)
class BoundingBoxBlurrer:
"""blur images based on a bounding box.
The bounding box used is assumed to have format [x_min, y_min, x_max, y_max]
(with elements being floats in [0,1], relative to the original shape of the
image).
"""
def __init__(self) -> None:
pass
def __call__(self, img, bbox_list):
"""Apply blurring to bboxes of an image.
Args:
img: The image to blur.
bbox_list: The list of bboxes to blur.
Returns:
The image with bboxes blurred.
"""
# Skip if there are no boxes to blur.
if len(bbox_list) == 0:
return img
height, width = img.shape[:2]
# Convert to float temporarily
img = img.astype(np.float32) / 255.0
mask = np.zeros_like(img)
# Incorporate max diagonal from ImageNet code.
max_diagonal = 0
for bbox in bbox_list:
adjusted_bbox = [
int(bbox[0] * width),
int(bbox[1] * height),
int(bbox[2] * width),
int(bbox[3] * height),
]
diagonal = max(adjusted_bbox[2] - adjusted_bbox[0], adjusted_bbox[3] - adjusted_bbox[1])
max_diagonal = max(max_diagonal, diagonal)
# Adjusting bbox as in:
# https://github.com/princetonvisualai/imagenet-face-obfuscation
adjusted_bbox[0] = int(adjusted_bbox[0] - 0.1 * diagonal)
adjusted_bbox[1] = int(adjusted_bbox[1] - 0.1 * diagonal)
adjusted_bbox[2] = int(adjusted_bbox[2] + 0.1 * diagonal)
adjusted_bbox[3] = int(adjusted_bbox[3] + 0.1 * diagonal)
# Clipping for indexing.
adjusted_bbox[0] = np.clip(adjusted_bbox[0], 0, width - 1)
adjusted_bbox[1] = np.clip(adjusted_bbox[1], 0, height - 1)
adjusted_bbox[2] = np.clip(adjusted_bbox[2], 0, width - 1)
adjusted_bbox[3] = np.clip(adjusted_bbox[3], 0, height - 1)
mask[adjusted_bbox[1] : adjusted_bbox[3], adjusted_bbox[0] : adjusted_bbox[2], ...] = 1
sigma = 0.1 * max_diagonal
ksize = int(2 * np.ceil(4 * sigma)) + 1
blurred_img = A.augmentations.gaussian_blur(img, ksize=ksize, sigma=sigma)
blurred_mask = A.augmentations.gaussian_blur(mask, ksize=ksize, sigma=sigma)
result = img * (1 - blurred_mask) + blurred_img * blurred_mask
# Convert back to uint8
result = (result * 255.0).astype(np.uint8)
return result
class ParquetSampleWriter:
"""ParquetSampleWriter is a image+caption writer to parquet"""
def __init__(
self,
shard_id,
output_folder,
save_caption,
oom_shard_count,
schema,
encode_format,
):
self.oom_shard_count = oom_shard_count
self.encode_format = encode_format
schema = schema.append(pa.field(encode_format, pa.binary()))
shard_name = "{shard_id:0{oom_shard_count}d}".format( # pylint: disable=consider-using-f-string
shard_id=shard_id, oom_shard_count=oom_shard_count
)
output_file = f"{output_folder}/{shard_name}.parquet"
self.buffered_parquet_writer = BufferedParquetWriter(output_file, schema, 100)
self.save_caption = save_caption
def write(self, img_str, key, caption, meta):
"""Keep sample in memory then write to disk when close() is called"""
if img_str is not None:
sample = {"key": key, self.encode_format: img_str}
if self.save_caption:
sample["txt"] = str(caption) if caption is not None else ""
else:
sample = {"key": key, self.encode_format: None}
if self.save_caption:
sample["txt"] = None
sample.update(meta)
self.buffered_parquet_writer.write(sample)
def close(self):
self.buffered_parquet_writer.close()
class WebDatasetSampleWriter:
"""WebDatasetSampleWriter is a image+caption writer to webdataset"""
def __init__(
self,
shard_id,
output_folder,
save_caption,
oom_shard_count,
schema,
encode_format,
):
self.oom_shard_count = oom_shard_count
shard_name = "{shard_id:0{oom_shard_count}d}".format( # pylint: disable=consider-using-f-string
shard_id=shard_id, oom_shard_count=oom_shard_count
)
self.shard_id = shard_id
fs, output_path = fsspec.core.url_to_fs(output_folder)
self.tar_fd = fs.open(f"{output_path}/{shard_name}.tar", "wb")
self.tarwriter = wds.TarWriter(self.tar_fd)
self.save_caption = save_caption
self.buffered_parquet_writer = BufferedParquetWriter(output_folder + "/" + shard_name + ".parquet", schema, 100)
self.encode_format = encode_format
def write(self, img_str, key, caption, meta):
"""write sample to tars"""
if img_str is not None:
sample = {"__key__": key, self.encode_format: img_str}
if self.save_caption:
sample["txt"] = str(caption) if caption is not None else ""
# some meta data may not be JSON serializable
for k, v in meta.items():
if isinstance(v, np.ndarray):
meta[k] = v.tolist()
sample["json"] = json.dumps(meta, indent=4)
self.tarwriter.write(sample)
self.buffered_parquet_writer.write(meta)
def close(self):
self.buffered_parquet_writer.close()
self.tarwriter.close()
self.tar_fd.close()
class TFRecordSampleWriter:
"""TFRecordSampleWriter is a image+caption writer to TFRecord"""
def __init__(
self,
shard_id,
output_folder,
save_caption,
oom_shard_count,
schema,
encode_format,
):
try:
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3"
import tensorflow_io as _ # pylint: disable=import-outside-toplevel
from tensorflow.python.lib.io.tf_record import TFRecordWriter # pylint: disable=import-outside-toplevel
from tensorflow.python.training.training import ( # pylint: disable=import-outside-toplevel
BytesList,
Example,
Feature,
Features,
FloatList,
Int64List,
)
self._BytesList = BytesList # pylint: disable=invalid-name
self._Int64List = Int64List # pylint: disable=invalid-name
self._FloatList = FloatList # pylint: disable=invalid-name
self._Example = Example # pylint: disable=invalid-name
self._Features = Features # pylint: disable=invalid-name
self._Feature = Feature # pylint: disable=invalid-name
except ImportError as e:
raise ModuleNotFoundError(
"tfrecords require tensorflow and tensorflow_io to be installed."
"Run `pip install tensorflow tensorflow_io`."
) from e
self.oom_shard_count = oom_shard_count
shard_name = "{shard_id:0{oom_shard_count}d}".format( # pylint: disable=consider-using-f-string
shard_id=shard_id, oom_shard_count=oom_shard_count
)
self.shard_id = shard_id
self.tf_writer = TFRecordWriter(f"{output_folder}/{shard_name}.tfrecord")
self.save_caption = save_caption
self.buffered_parquet_writer = BufferedParquetWriter(output_folder + "/" + shard_name + ".parquet", schema, 100)
self.encode_format = encode_format
def write(self, img_str, key, caption, meta):
"""Write a sample using tfrecord writer"""
if img_str is not None:
sample = {
"key": self._bytes_feature(key.encode()),
self.encode_format: self._bytes_feature(img_str),
}
if self.save_caption:
sample["txt"] = self._bytes_feature(str(caption) if caption is not None else "")
for k, v in meta.items():
sample[k] = self._feature(v)
tf_example = self._Example(features=self._Features(feature=sample))
self.tf_writer.write(tf_example.SerializeToString())
self.buffered_parquet_writer.write(meta)
def close(self):
self.buffered_parquet_writer.close()
self.tf_writer.close()
def _feature(self, value):
"""Convert to proper feature type"""
if isinstance(value, list):
return self._list_feature(value)
elif isinstance(value, int):
return self._int64_feature(value)
elif isinstance(value, float):
return self._float_feature(value)
else:
return self._bytes_feature(value)
def _bytes_feature(self, value):
"""Returns a bytes_list from a string / byte."""
if value is None:
value = ""
if isinstance(value, str):
value = value.encode()
return self._Feature(bytes_list=self._BytesList(value=[value]))
def _float_feature(self, value):
"""Returns a float_list from a float / double."""
return self._Feature(float_list=self._FloatList(value=[value]))
def _int64_feature(self, value):
"""Returns an int64_list from a bool / enum / int / uint."""
return self._Feature(int64_list=self._Int64List(value=[value]))
def _list_feature(self, value):
"""Returns an list of int64_list, float_list, bytes_list."""
if isinstance(value[0], int):
return self._Feature(int64_list=self._Int64List(value=value))
elif isinstance(value[0], float):
return self._Feature(float_list=self._FloatList(value=value))
else:
for i, bytes_feature in enumerate(value):
if bytes_feature is None:
value[i] = ""
if isinstance(bytes_feature, str):
value[i] = bytes_feature.encode()
return self._Feature(bytes_list=self._BytesList(value=value))
class FilesSampleWriter:
"""FilesSampleWriter is a caption+image writer to files"""
def __init__(
self,
shard_id,
output_folder,
save_caption,
oom_shard_count,
schema,
encode_format,
):
self.oom_shard_count = oom_shard_count
shard_name = "{shard_id:0{oom_shard_count}d}".format( # pylint: disable=consider-using-f-string
shard_id=shard_id, oom_shard_count=oom_shard_count
)
self.shard_id = shard_id
self.fs, self.subfolder = fsspec.core.url_to_fs(f"{output_folder}/{shard_name}")
if not self.fs.exists(self.subfolder):
self.fs.mkdir(self.subfolder)
self.save_caption = save_caption
self.buffered_parquet_writer = BufferedParquetWriter(output_folder + "/" + shard_name + ".parquet", schema, 100)
self.encode_format = encode_format
def write(self, img_str, key, caption, meta):
"""Write sample to disk"""
if img_str is not None:
filename = f"{self.subfolder}/{key}.{self.encode_format}"
with self.fs.open(filename, "wb") as f:
f.write(img_str)
if self.save_caption:
caption = str(caption) if caption is not None else ""
caption_filename = f"{self.subfolder}/{key}.txt"
with self.fs.open(caption_filename, "w") as f:
f.write(str(caption))
# some meta data may not be JSON serializable
for k, v in meta.items():
if isinstance(v, np.ndarray):
meta[k] = v.tolist()
j = json.dumps(meta, indent=4)
meta_filename = f"{self.subfolder}/{key}.json"
with self.fs.open(meta_filename, "w") as f:
f.write(j)
self.buffered_parquet_writer.write(meta)
def close(self):
self.buffered_parquet_writer.close()
class DummySampleWriter:
"""Does not write"""
def __init__(self, shard_id, output_folder, save_caption, oom_shard_count, schema, encode_format):
pass
def write(self, img_str, key, caption, meta):
pass
def close(self):
pass
class Reader:
"""
The reader class reads an url list and returns shards
It provides an iter method
It provides attributes:
- column_list: the list of columns to read
- input_format: the format of the input file
- url_col: the column name of the url
- caption_col: the column name of the caption
- verify_hash_col: the column containing the hash to verify.
- verify_hash_type: the type of hash to verify.
- save_additional_columns: the list of additional columns to save
- number_sample_per_shard: the number of samples per shard
- done_shards: a set of already done shards
- start_shard_id: the shard id to begin downloading from
"""
def __init__(
self,
url_list,
input_format,
url_col,
caption_col,
verify_hash_col,
verify_hash_type,
save_additional_columns,
number_sample_per_shard,
done_shards,
tmp_path,
start_shard_id: int = 0,
) -> None:
self.input_format = input_format
self.url_col = url_col
self.caption_col = caption_col
self.verify_hash_col = verify_hash_col
self.verify_hash_type = verify_hash_type
self.save_additional_columns = save_additional_columns
self.number_sample_per_shard = number_sample_per_shard
self.done_shards = done_shards
self.start_shard_id = start_shard_id
fs, url_path = fsspec.core.url_to_fs(url_list)
self.fs = fs
self.tmp_path = tmp_path
if fs.isdir(url_path):
self.input_files = sorted(fs.glob(url_path.rstrip("/") + "/*." + input_format))
if len(self.input_files) == 0:
raise ValueError(f"No file found at path {url_path} with extension {input_format}")
else:
self.input_files = [url_path]
if self.input_format in ["txt", "txt.gz"]:
self.column_list = ["url"]
elif self.input_format in ["json", "json.gz", "jsonl", "jsonl.gz", "csv", "csv.gz", "tsv", "tsv.gz", "parquet"]:
self.column_list = self.save_additional_columns if self.save_additional_columns is not None else []
if self.caption_col is not None:
self.column_list = self.column_list + ["caption"]
if self.verify_hash_col is not None:
if self.verify_hash_type in ["md5", "sha256", "sha512"]:
self.column_list = self.column_list + [self.verify_hash_type]
else:
raise ValueError(f"Invalid hash type {self.verify_hash_type}")
self.column_list = self.column_list + ["url"]
else:
raise ValueError(f"Invalid input format {self.input_format}")
def _save_to_arrow(self, input_file, start_shard_id):
"""Read the input file and save to arrow files in a temporary directory"""
if self.input_format in [
"txt",
"txt.gz",
"csv",
"csv.gz",
"tsv",
"tsv.gz",
"json",
"json.gz",
"jsonl",
"jsonl.gz",
]:
compression = None
if self.input_format.endswith(".gz"):
compression = "gzip"
with self.fs.open(input_file, encoding="utf-8", mode="rb", compression=compression) as file:
if self.input_format in ["txt", "txt.gz"]:
df = csv_pa.read_csv(file, read_options=csv_pa.ReadOptions(column_names=["url"]))
elif self.input_format in ["json", "json.gz"]:
df = pa.Table.from_pandas(pd.read_json(file))
elif self.input_format in ["csv", "csv.gz"]:
df = csv_pa.read_csv(file)
elif self.input_format in ["tsv", "tsv.gz"]:
df = csv_pa.read_csv(file, parse_options=csv_pa.ParseOptions(delimiter="\t"))
elif self.input_format in ["jsonl", "jsonl.gz"]:
df = json_pa.read_json(file)
else:
raise ValueError(f"Unknown input format {self.input_format}")
elif self.input_format == "parquet":
with self.fs.open(input_file, mode="rb") as file:
columns_to_read = [self.url_col]
if self.caption_col is not None:
columns_to_read += [self.caption_col]
if self.verify_hash_col is not None:
columns_to_read += [self.verify_hash_col]
if self.save_additional_columns is not None:
columns_to_read += self.save_additional_columns
df = pq.read_table(file, columns=columns_to_read)
else:
raise ValueError(f"Unknown input format {self.input_format}")
column_names = df.column_names
if self.caption_col is not None:
column_names = [c if c != self.caption_col else "caption" for c in column_names]
if self.verify_hash_col is not None:
column_names = [c if c != self.verify_hash_col else self.verify_hash_type for c in column_names]
column_names = [c if c != self.url_col else "url" for c in column_names]
df = df.rename_columns(column_names)
number_samples = df.num_rows
number_shards = math.ceil(df.num_rows / self.number_sample_per_shard)
shards_to_write = [
(start_shard_id + shard_id, shard_id)
for shard_id in range(number_shards)
if start_shard_id + shard_id not in self.done_shards
]
if len(shards_to_write) == 0:
return [], number_shards
def write_shard(t):
full_shard_id, shard_id = t
begin_shard = shard_id * self.number_sample_per_shard
end_shard = min(number_samples, (1 + shard_id) * self.number_sample_per_shard)
df_shard = df.slice(begin_shard, end_shard - begin_shard).select(self.column_list)
tmp_file = self.tmp_path + f"/{full_shard_id}.feather"
for i in range(10):
try:
fs, tmp_path = fsspec.core.url_to_fs(tmp_file)
with fs.open(tmp_path, "wb") as file:
with pa.ipc.new_file(file, df_shard.schema) as writer:
writer.write_table(df_shard)
return (full_shard_id, tmp_file)
except Exception as e: # pylint: disable=broad-except
if i != 9:
print("retrying to write to file due to error:", e)
time.sleep(1)
else:
raise e
# can't reach here
raise ValueError("Failed to write to file.")
for i in range(10):
shards = []
# thread pool to make it faster to write files to low latency file systems (ie s3, hdfs)
try:
with ThreadPool(32) as thread_pool:
for shard in thread_pool.imap_unordered(write_shard, shards_to_write):
shards.append(shard)
break
except Exception as e: # pylint: disable=broad-except
if i != 9:
print("retrying whole sharding to write to files due to error:", e)
time.sleep(2 * i)
else:
raise e
shards.sort(key=lambda k: k[0])
del df
return shards, number_shards
def __iter__(self):
"""
Iterate over shards, yield shards of size number_sample_per_shard or less for the last one
Each shard is a tuple (shard_id, shard)
shard is a tuple (sample id, sample)
sample is a tuple of the columns
"""
start_shard_id = self.start_shard_id
for i, input_file in enumerate(self.input_files):
print("Sharding file number " + str(i + 1) + " of " + str(len(self.input_files)) + " called " + input_file)
shards, number_shards = self._save_to_arrow(input_file, start_shard_id)
print("File sharded in " + str(len(shards)) + " shards")
print(
"Downloading starting now, check your bandwidth speed (with bwm-ng)"
"your cpu (with htop), and your disk usage (with iotop)!"
)
for shard_id, arrow_file in shards:
yield (
shard_id,
arrow_file,
)
start_shard_id += number_shards
class Downloader:
"""The downloader class gets calls with shards, download them then call the writer to write them down"""
def __init__(
self,
sample_writer_class,
resizer,
thread_count,
save_caption,
extract_exif,
output_folder,
column_list,
timeout,
number_sample_per_shard,
oom_shard_count,
compute_hash,
verify_hash_type,
encode_format,
retries,
user_agent_token,
disallowed_header_directives,
blurring_bbox_col=None,
) -> None:
self.sample_writer_class = sample_writer_class
self.resizer = resizer
self.thread_count = thread_count
self.save_caption = save_caption
self.extract_exif = extract_exif
self.output_folder = output_folder
self.column_list = column_list
self.timeout = timeout
self.number_sample_per_shard = number_sample_per_shard
self.oom_shard_count = oom_shard_count
self.compute_hash = compute_hash
self.verify_hash_type = verify_hash_type
self.encode_format = encode_format
self.retries = retries
self.user_agent_token = None if user_agent_token is None else user_agent_token.strip().lower()
self.disallowed_header_directives = (
None
if disallowed_header_directives is None
else {directive.strip().lower() for directive in disallowed_header_directives}
)
self.blurring_bbox_col = blurring_bbox_col
def __call__(
self,
row,
):
try:
self.download_shard(row)
return (True, row)
except Exception as err: # pylint: disable=broad-except
traceback.print_exc()
print(f"shard {row[0]} failed with error {err}")
return (False, row)
def download_shard(
self,
row,
):
"""Function to start an image downloading in one process"""
shard_id, shard_file = row
start_time = time.time()
fs, shard_path = fsspec.core.url_to_fs(shard_file)
with fs.open(shard_path, "rb") as f:
df = pa.ipc.open_file(f).read_all()
schema = df.schema
schema = (
schema.append(pa.field("key", pa.string()))
.append(pa.field("status", pa.string()))
.append(pa.field("error_message", pa.string()))
.append(pa.field("width", pa.int32()))
.append(pa.field("height", pa.int32()))
.append(pa.field("original_width", pa.int32()))
.append(pa.field("original_height", pa.int32()))
)
if self.extract_exif:
schema = schema.append(pa.field("exif", pa.string()))
if self.compute_hash is not None and self.compute_hash not in schema.names:
schema = schema.append(pa.field(self.compute_hash, pa.string()))
pydict = df.select(self.column_list).to_pydict()
shard_to_dl = list(enumerate(zip(*(pydict[col] for col in self.column_list))))
del pydict
del df
status_dict = CappedCounter()
count = len(shard_to_dl)
successes = 0
failed_to_download = 0
failed_to_resize = 0
url_indice = self.column_list.index("url")
caption_indice = self.column_list.index("caption") if "caption" in self.column_list else None
hash_indice = (
self.column_list.index(self.verify_hash_type) if self.verify_hash_type in self.column_list else None
)
bbox_indice = self.column_list.index(self.blurring_bbox_col) if self.blurring_bbox_col is not None else None
key_url_list = [(key, x[url_indice]) for key, x in shard_to_dl]
# this prevents an accumulation of more than twice the number of threads in sample ready to resize
# limit the memory usage
semaphore = Semaphore(self.thread_count * 2)
def data_generator():
for e in key_url_list:
semaphore.acquire() # pylint: disable=consider-using-with
yield e
loader = data_generator()
# give schema to writer
sample_writer = self.sample_writer_class(
shard_id,
self.output_folder,
self.save_caption,
self.oom_shard_count,
schema,
self.encode_format,
)
oom_sample_per_shard = math.ceil(math.log10(self.number_sample_per_shard))
with ThreadPool(self.thread_count) as thread_pool:
for key, img_stream, error_message in thread_pool.imap_unordered(
lambda x: download_image_with_retry(
x,
timeout=self.timeout,
retries=self.retries,
user_agent_token=self.user_agent_token,
disallowed_header_directives=self.disallowed_header_directives,
),
loader,
):
try:
_, sample_data = shard_to_dl[key]
str_key = compute_key(key, shard_id, oom_sample_per_shard, self.oom_shard_count)
meta = {
# Skip columns containing a the verification hash and only save the compute hash
**{
self.column_list[i]: sample_data[i]
for i in range(len(self.column_list))
if (hash_indice is None or i != hash_indice)
},
"key": str_key,
"status": None,
"error_message": error_message,
"width": None,
"height": None,
"original_width": None,
"original_height": None,
}
if self.extract_exif:
meta["exif"] = None
if self.compute_hash is not None:
meta[self.compute_hash] = None
if error_message is not None:
failed_to_download += 1
status = "failed_to_download"
status_dict.increment(error_message)
meta["status"] = status
sample_writer.write(
None,
str_key,
sample_data[caption_indice] if caption_indice is not None else None,
meta,
)
semaphore.release()
continue
if hash_indice is not None:
img_stream.seek(0)
test_hash = getattr(hashlib, self.verify_hash_type)(img_stream.read()).hexdigest()
if test_hash != sample_data[hash_indice]:
failed_to_download += 1
status = "failed_to_download"
status_dict.increment("hash mismatch")
meta["status"] = status
meta["error_message"] = "hash mismatch"
sample_writer.write(
None,
str_key,
sample_data[caption_indice] if caption_indice is not None else None,
meta,
)
img_stream.close()
del img_stream
semaphore.release()
continue
img_stream.seek(0)
bbox_list = sample_data[bbox_indice] if bbox_indice is not None else None
(
img,
width,
height,
original_width,
original_height,
error_message,
) = self.resizer(img_stream, bbox_list)
if error_message is not None:
failed_to_resize += 1
status = "failed_to_resize"
status_dict.increment(error_message)
meta["status"] = status
meta["error_message"] = error_message
sample_writer.write(
None,
str_key,
sample_data[caption_indice] if caption_indice is not None else None,
meta,
)
img_stream.close()
del img_stream
semaphore.release()
continue
successes += 1
status = "success"
status_dict.increment(status)
if self.extract_exif:
try:
img_stream.seek(0)
exif = json.dumps(
{
k: str(v).strip()
for k, v in exifread.process_file(img_stream, details=False).items()
if v is not None
}
)
except Exception as _: # pylint: disable=broad-except
exif = None
meta["exif"] = exif
if self.compute_hash is not None:
img_stream.seek(0)
meta[self.compute_hash] = getattr(hashlib, self.compute_hash)(img_stream.read()).hexdigest()
meta["status"] = status
meta["width"] = width
meta["height"] = height
meta["original_width"] = original_width
meta["original_height"] = original_height
img_stream.close()
del img_stream
sample_writer.write(
img,
str_key,
sample_data[caption_indice] if caption_indice is not None else None,
meta,
)
except Exception as err: # pylint: disable=broad-except
traceback.print_exc()
print(f"Sample {key} failed to download: {err}")
semaphore.release()
sample_writer.close()
thread_pool.terminate()
thread_pool.join()
del thread_pool
end_time = time.time()
write_stats(
self.output_folder,
shard_id,
count,
successes,
failed_to_download,
failed_to_resize,
start_time,
end_time,
status_dict,
self.oom_shard_count,
)
fs.rm(shard_path)
def multiprocessing_distributor(processes_count, downloader, reader, _, max_shard_retry):
"""Distribute the work to the processes using multiprocessing"""
ctx = get_context("spawn")
with ctx.Pool(processes_count, maxtasksperchild=5) as process_pool:
def run(gen):
failed_shards = []
for status, row in tqdm(process_pool.imap_unordered(downloader, gen)):
if status is False:
failed_shards.append(row)
return failed_shards
failed_shards = run(reader)
retrier(run, failed_shards, max_shard_retry)
process_pool.terminate()
process_pool.join()
del process_pool
def pyspark_distributor(processes_count, downloader, reader, subjob_size, max_shard_retry):
"""Distribute the work to the processes using pyspark"""
with _spark_session(processes_count) as spark:
def batcher(iterable, batch_size):
iterator = iter(iterable)
for first in iterator:
yield list(chain([first], islice(iterator, batch_size - 1)))
def run(gen):
failed_shards = []
for batch in batcher(gen, subjob_size):
rdd = spark.sparkContext.parallelize(batch, len(batch))
for status, row in rdd.map(downloader).collect():
if status is False:
failed_shards.append(row)
return failed_shards
failed_shards = run(reader)
retrier(run, failed_shards, max_shard_retry)
The provided code snippet includes necessary dependencies for implementing the `download` function. Write a Python function `def download( url_list: str, image_size: int = 256, output_folder: str = "images", processes_count: int = 1, resize_mode: str = "border", resize_only_if_bigger: bool = False, upscale_interpolation: str = "lanczos", downscale_interpolation: str = "area", encode_quality: int = 95, encode_format: str = "jpg", skip_reencode: bool = False, output_format: str = "files", input_format: str = "txt", url_col: str = "url", caption_col: Optional[str] = None, bbox_col: Optional[str] = None, thread_count: int = 256, number_sample_per_shard: int = 10000, extract_exif: bool = True, save_additional_columns: Optional[List[str]] = None, timeout: int = 10, enable_wandb: bool = False, wandb_project: str = "img2dataset", oom_shard_count: int = 5, compute_hash: Optional[str] = "sha256", verify_hash: Optional[List[str]] = None, distributor: str = "multiprocessing", subjob_size: int = 1000, retries: int = 0, disable_all_reencoding: bool = False, min_image_size: int = 0, max_image_area: float = float("inf"), max_aspect_ratio: float = float("inf"), incremental_mode: str = "incremental", max_shard_retry: int = 1, user_agent_token: Optional[str] = None, disallowed_header_directives: Optional[List[str]] = None, )` to solve the following problem:
Download is the main entry point of img2dataset, it uses multiple processes and download multiple files
Here is the function:
def download(
url_list: str,
image_size: int = 256,
output_folder: str = "images",
processes_count: int = 1,
resize_mode: str = "border",
resize_only_if_bigger: bool = False,
upscale_interpolation: str = "lanczos",
downscale_interpolation: str = "area",
encode_quality: int = 95,
encode_format: str = "jpg",
skip_reencode: bool = False,
output_format: str = "files",
input_format: str = "txt",
url_col: str = "url",
caption_col: Optional[str] = None,
bbox_col: Optional[str] = None,
thread_count: int = 256,
number_sample_per_shard: int = 10000,
extract_exif: bool = True,
save_additional_columns: Optional[List[str]] = None,
timeout: int = 10,
enable_wandb: bool = False,
wandb_project: str = "img2dataset",
oom_shard_count: int = 5,
compute_hash: Optional[str] = "sha256",
verify_hash: Optional[List[str]] = None,
distributor: str = "multiprocessing",
subjob_size: int = 1000,
retries: int = 0,
disable_all_reencoding: bool = False,
min_image_size: int = 0,
max_image_area: float = float("inf"),
max_aspect_ratio: float = float("inf"),
incremental_mode: str = "incremental",
max_shard_retry: int = 1,
user_agent_token: Optional[str] = None,
disallowed_header_directives: Optional[List[str]] = None,
):
"""Download is the main entry point of img2dataset, it uses multiple processes and download multiple files"""
if disallowed_header_directives is None:
disallowed_header_directives = ["noai", "noimageai", "noindex", "noimageindex"]
if len(disallowed_header_directives) == 0:
disallowed_header_directives = None
config_parameters = dict(locals())
arguments_validator(config_parameters)
def make_path_absolute(path):
fs, p = fsspec.core.url_to_fs(path)
if fs.protocol == "file":
return os.path.abspath(p)
return path
output_folder = make_path_absolute(output_folder)
url_list = make_path_absolute(url_list)
logger_process = LoggerProcess(output_folder, enable_wandb, wandb_project, config_parameters)
tmp_path = output_folder + "/_tmp"
fs, tmp_dir = fsspec.core.url_to_fs(tmp_path)
if not fs.exists(tmp_dir):
fs.mkdir(tmp_dir)
def signal_handler(signal_arg, frame): # pylint: disable=unused-argument
try:
fs.rm(tmp_dir, recursive=True)
except Exception as _: # pylint: disable=broad-except
pass
logger_process.terminate()
sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)
save_caption = caption_col is not None
fs, output_path = fsspec.core.url_to_fs(output_folder)
start_shard_id = 0
if not fs.exists(output_path):
fs.mkdir(output_path)
done_shards = set()
else:
if incremental_mode == "incremental":
done_shards = set(int(x.split("/")[-1].split("_")[0]) for x in fs.glob(output_path + "/*.json"))
elif incremental_mode == "overwrite":
fs.rm(output_path, recursive=True)
fs.mkdir(output_path)
done_shards = set()
elif incremental_mode == "extend":
existing_shards = [int(x.split("/")[-1].split("_")[0]) for x in fs.glob(output_path + "/*.json")]
start_shard_id = max(existing_shards, default=-1) + 1
done_shards = set()
else:
raise ValueError(f"Unknown incremental mode {incremental_mode}")
logger_process.done_shards = done_shards
logger_process.start()
if bbox_col is not None:
if save_additional_columns is None:
save_additional_columns = [bbox_col]
else:
save_additional_columns.append(bbox_col)
if verify_hash is not None:
verify_hash_col, verify_hash_type = verify_hash
else:
verify_hash_col = None
verify_hash_type = None
reader = Reader(
url_list,
input_format,
url_col,
caption_col,
verify_hash_col,
verify_hash_type,
save_additional_columns,
number_sample_per_shard,
done_shards,
tmp_path,
start_shard_id,
)
if output_format == "webdataset":
sample_writer_class = WebDatasetSampleWriter
elif output_format == "parquet":
sample_writer_class = ParquetSampleWriter # type: ignore
elif output_format == "files":
sample_writer_class = FilesSampleWriter # type: ignore
elif output_format == "tfrecord":
sample_writer_class = TFRecordSampleWriter # type: ignore
elif output_format == "dummy":
sample_writer_class = DummySampleWriter # type: ignore
else:
raise ValueError(f"Invalid output format {output_format}")
if bbox_col is not None:
blurrer = BoundingBoxBlurrer()
else:
blurrer = None
resizer = Resizer(
image_size=image_size,
resize_mode=resize_mode,
resize_only_if_bigger=resize_only_if_bigger,
upscale_interpolation=upscale_interpolation,
downscale_interpolation=downscale_interpolation,
encode_quality=encode_quality,
encode_format=encode_format,
skip_reencode=skip_reencode,
disable_all_reencoding=disable_all_reencoding,
min_image_size=min_image_size,
max_image_area=max_image_area,
max_aspect_ratio=max_aspect_ratio,
blurrer=blurrer,
)
downloader = Downloader(
sample_writer_class=sample_writer_class,
resizer=resizer,
thread_count=thread_count,
save_caption=save_caption,
extract_exif=extract_exif,
output_folder=output_folder,
column_list=reader.column_list,
timeout=timeout,
number_sample_per_shard=number_sample_per_shard,
oom_shard_count=oom_shard_count,
compute_hash=compute_hash,
verify_hash_type=verify_hash_type,
encode_format=encode_format,
retries=retries,
user_agent_token=user_agent_token,
disallowed_header_directives=disallowed_header_directives,
blurring_bbox_col=bbox_col,
)
print("Starting the downloading of this file")
if distributor == "multiprocessing":
distributor_fn = multiprocessing_distributor
elif distributor == "pyspark":
distributor_fn = pyspark_distributor
elif distributor == "ray":
distributor_fn = ray_distributor
else:
raise ValueError(f"Distributor {distributor} not supported")
distributor_fn(
processes_count,
downloader,
reader,
subjob_size,
max_shard_retry,
)
logger_process.join()
if not hasattr(fs, "s3"):
fs.rm(tmp_dir, recursive=True) | Download is the main entry point of img2dataset, it uses multiple processes and download multiple files |
160,840 | import wandb
import time
from collections import Counter
import fsspec
import json
import multiprocessing
import queue
import traceback
The provided code snippet includes necessary dependencies for implementing the `write_stats` function. Write a Python function `def write_stats( output_folder, shard_id, count, successes, failed_to_download, failed_to_resize, start_time, end_time, status_dict, oom_shard_count, )` to solve the following problem:
Write stats to disk
Here is the function:
def write_stats(
output_folder,
shard_id,
count,
successes,
failed_to_download,
failed_to_resize,
start_time,
end_time,
status_dict,
oom_shard_count,
):
"""Write stats to disk"""
stats = {
"count": count,
"successes": successes,
"failed_to_download": failed_to_download,
"failed_to_resize": failed_to_resize,
"duration": end_time - start_time,
"start_time": start_time,
"end_time": end_time,
"status_dict": status_dict.dump(),
}
fs, output_path = fsspec.core.url_to_fs(output_folder)
shard_name = "{shard_id:0{oom_shard_count}d}".format( # pylint: disable=consider-using-f-string
shard_id=shard_id, oom_shard_count=oom_shard_count
)
json_file = f"{output_path}/{shard_name}_stats.json"
with fs.open(json_file, "w") as f:
json.dump(stats, f, indent=4) | Write stats to disk |
160,841 | import albumentations as A
import cv2
import numpy as np
from enum import Enum
import imghdr
import os
_INTER_STR_TO_CV2 = {
"nearest": cv2.INTER_NEAREST,
"linear": cv2.INTER_LINEAR,
"bilinear": cv2.INTER_LINEAR,
"cubic": cv2.INTER_CUBIC,
"bicubic": cv2.INTER_CUBIC,
"area": cv2.INTER_AREA,
"lanczos": cv2.INTER_LANCZOS4,
"lanczos4": cv2.INTER_LANCZOS4,
}
def inter_str_to_cv2(inter_str):
inter_str = inter_str.lower()
if inter_str not in _INTER_STR_TO_CV2:
raise ValueError(f"Invalid option for interpolation: {inter_str}")
return _INTER_STR_TO_CV2[inter_str] | null |
160,842 | from multiprocessing.pool import ThreadPool
from threading import Semaphore
import urllib.request
import io
import math
import exifread
import json
import time
import hashlib
import pyarrow as pa
import traceback
import fsspec
from .logger import CappedCounter
from .logger import write_stats
def download_image(row, timeout, user_agent_token, disallowed_header_directives):
"""Download an image with urllib"""
key, url = row
img_stream = None
user_agent_string = "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:72.0) Gecko/20100101 Firefox/72.0"
if user_agent_token:
user_agent_string += f" (compatible; {user_agent_token}; +https://github.com/rom1504/img2dataset)"
try:
request = urllib.request.Request(url, data=None, headers={"User-Agent": user_agent_string})
with urllib.request.urlopen(request, timeout=timeout) as r:
if disallowed_header_directives and is_disallowed(
r.headers,
user_agent_token,
disallowed_header_directives,
):
return key, None, "Use of image disallowed by X-Robots-Tag directive"
img_stream = io.BytesIO(r.read())
return key, img_stream, None
except Exception as err: # pylint: disable=broad-except
if img_stream is not None:
img_stream.close()
return key, None, str(err)
def download_image_with_retry(row, timeout, retries, user_agent_token, disallowed_header_directives):
for _ in range(retries + 1):
key, img_stream, err = download_image(row, timeout, user_agent_token, disallowed_header_directives)
if img_stream is not None:
return key, img_stream, err
return key, None, err | null |
160,843 | from multiprocessing.pool import ThreadPool
from threading import Semaphore
import urllib.request
import io
import math
import exifread
import json
import time
import hashlib
import pyarrow as pa
import traceback
import fsspec
from .logger import CappedCounter
from .logger import write_stats
def compute_key(key, shard_id, oom_sample_per_shard, oom_shard_count):
true_key = (10**oom_sample_per_shard) * shard_id + key
key_format = oom_sample_per_shard + oom_shard_count
str_key = "{true_key:0{key_format}d}".format( # pylint: disable=consider-using-f-string
key_format=key_format, true_key=true_key
)
return str_key | null |
160,844 | import asyncio
from modules.export import export
from modules.write_log import log_writer
G = '\033[32m'
C = '\033[36m'
W = '\033[0m'
Y = '\033[33m'
async def run(ip_addr, result, threads):
queue = asyncio.Queue(maxsize=threads)
distrib = asyncio.create_task(insert(queue))
workers = [
asyncio.create_task(
consumer(queue, ip_addr, result)
) for _ in range(threads)]
await asyncio.gather(distrib)
await queue.join()
for worker in workers:
worker.cancel()
def ps_output(output, data, result):
data['module-Port Scan'] = result
result.update({'exported': False})
fname = f'{output["directory"]}/ports.{output["format"]}'
output['file'] = fname
export(output, data)
def log_writer(message):
logging.basicConfig(
filename=settings.log_file_path,
encoding='utf-8',
level=logging.INFO,
format='[%(asctime)s] : %(message)s',
datefmt='%m/%d/%Y %I:%M:%S %p'
)
logging.info(message)
def scan(ip_addr, output, data, threads):
result = {}
result['ports'] = []
print(f'\n{Y}[!] Starting Port Scan...{W}\n')
print(f'{G}[+] {C}Scanning Top 1000 Ports With {threads} Threads...{W}\n')
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
loop.run_until_complete(run(ip_addr, result, threads))
loop.close()
if output != 'None':
ps_output(output, data, result)
log_writer('[portscan] Completed') | null |
160,845 | import socket
import aiohttp
import asyncio
from datetime import date
from modules.export import export
from modules.write_log import log_writer
G = '\033[32m'
C = '\033[36m'
W = '\033[0m'
Y = '\033[33m'
async def run(target, threads, tout, wdlist, redir, sslv, dserv, filext, total_num_words):
queue = asyncio.Queue(maxsize=threads)
resolver = aiohttp.AsyncResolver(nameservers=dserv.split(', '))
conn = aiohttp.TCPConnector(limit=threads, resolver=resolver, family=socket.AF_INET, verify_ssl=sslv)
timeout = aiohttp.ClientTimeout(total=None, sock_connect=tout, sock_read=tout)
async with aiohttp.ClientSession(connector=conn, timeout=timeout) as session:
distrib = asyncio.create_task(insert(queue, filext, target, wdlist, redir))
workers = [
asyncio.create_task(
consumer(queue, target, session, redir, total_num_words)
) for _ in range(threads)]
await asyncio.gather(distrib)
await queue.join()
for worker in workers:
worker.cancel()
def dir_output(output, data):
result = {}
for entry in responses:
if entry is not None:
if entry[1] in {200}:
if output != 'None':
result.setdefault('Status 200', []).append(f'200, {entry[0]}')
elif entry[1] in {301, 302, 303, 307, 308}:
if output != 'None':
result.setdefault(f'Status {entry[1]}', []).append(f'{entry[1]}, {entry[0]}')
elif entry[1] in {403}:
if output != 'None':
result.setdefault('Status 403', []).append(f'{entry[1]}, {entry[0]}')
print(f'\n\n{G}[+] {C}Directories Found : {W}{len(found)}')
if output != 'None':
result.update({'exported': False})
data['module-Directory Search'] = result
fname = f'{output["directory"]}/directory_enum.{output["format"]}'
output['file'] = fname
export(output, data)
def log_writer(message):
logging.basicConfig(
filename=settings.log_file_path,
encoding='utf-8',
level=logging.INFO,
format='[%(asctime)s] : %(message)s',
datefmt='%m/%d/%Y %I:%M:%S %p'
)
logging.info(message)
def hammer(target, threads, tout, wdlist, redir, sslv, dserv, output, data, filext):
print(f'\n{Y}[!] Starting Directory Enum...{W}\n')
print(f'{G}[+] {C}Threads : {W}{threads}')
print(f'{G}[+] {C}Timeout : {W}{tout}')
print(f'{G}[+] {C}Wordlist : {W}{wdlist}')
print(f'{G}[+] {C}Allow Redirects : {W}{redir}')
print(f'{G}[+] {C}SSL Verification : {W}{sslv}')
print(f'{G}[+] {C}DNS Servers : {W}{dserv}')
with open(wdlist, 'r') as wordlist:
num_words = sum(1 for i in wordlist)
print(f'{G}[+] {C}Wordlist Size : {W}{num_words}')
print(f'{G}[+] {C}File Extensions : {W}{filext}\n')
if len(filext) != 0:
total_num_words = num_words * (len(filext.split(',')) + 1)
else:
total_num_words = num_words
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
loop.run_until_complete(run(target, threads, tout, wdlist, redir, sslv, dserv, filext, total_num_words))
dir_output(output, data)
loop.close()
log_writer('[dirrec] Completed') | null |
160,846 | import ssl
import socket
from modules.export import export
from modules.write_log import log_writer
from cryptography import x509
from cryptography.hazmat.backends import default_backend
R = '\033[31m'
G = '\033[32m'
C = '\033[36m'
W = '\033[0m'
Y = '\033[33m'
def export(output, data):
if output['format'] != 'txt':
print(f'{R}[-] {C}Invalid Output Format, Valid Formats : {W}txt')
sys.exit()
fname = output['file']
with open(fname, 'w') as outfile:
txt_export(data, outfile)
def log_writer(message):
logging.basicConfig(
filename=settings.log_file_path,
encoding='utf-8',
level=logging.INFO,
format='[%(asctime)s] : %(message)s',
datefmt='%m/%d/%Y %I:%M:%S %p'
)
logging.info(message)
def cert(hostname, sslp, output, data):
result = {}
presence = False
print(f'\n{Y}[!] SSL Certificate Information : {W}\n')
port_test = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
port_test.settimeout(5)
try:
port_test.connect((hostname, sslp))
port_test.close()
presence = True
except Exception:
port_test.close()
print(f'{R}[-] {C}SSL is not Present on Target URL...Skipping...{W}')
result.update({'Error': 'SSL is not Present on Target URL'})
log_writer('[sslinfo] SSL is not Present on Target URL...Skipping...')
def unpack(nested_tuple, pair):
for item in nested_tuple:
if isinstance(item, tuple):
if len(item) == 2:
pair[item[0]] = item[1]
else:
unpack(item, pair)
else:
pair[nested_tuple.index(item)] = item
def process_cert(info):
pair = {}
for key, val in info.items():
if isinstance(val, tuple):
print(f'{G}[+] {C}{key}{W}')
unpack(val, pair)
for sub_key, sub_val in pair.items():
print(f'\t{G}└╴{C}{sub_key}: {W}{sub_val}')
result.update({f'{key}-{sub_key}': sub_val})
pair.clear()
elif isinstance(val, dict):
print(f'{G}[+] {C}{key}{W}')
for sub_key, sub_val in val.items():
print(f'\t{G}└╴{C}{sub_key}: {W}{sub_val}')
result.update({f'{key}-{sub_key}': sub_val})
elif isinstance(val, list):
print(f'{G}[+] {C}{key}{W}')
for sub_val in val:
print(f'\t{G}└╴{C}{val.index(sub_val)}: {W}{sub_val}')
result.update({f'{key}-{val.index(sub_val)}': sub_val})
else:
print(f'{G}[+] {C}{key} : {W}{val}')
result.update({key: val})
if presence:
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
sock = socket.socket()
sock.settimeout(5)
ssl_conn = ctx.wrap_socket(sock, server_hostname=hostname)
ssl_conn.connect((hostname, sslp))
x509_cert = ssl_conn.getpeercert(binary_form=True)
decoded_cert = x509.load_der_x509_certificate(x509_cert, default_backend())
subject_dict = {}
issuer_dict = {}
def name_to_dict(attribute):
attr_name = attribute.oid._name
attr_value = attribute.value
return attr_name, attr_value
for attribute in decoded_cert.subject:
name, value = name_to_dict(attribute)
subject_dict[name] = value
for attribute in decoded_cert.issuer:
name, value = name_to_dict(attribute)
issuer_dict[name] = value
cert_dict = {
'protocol': ssl_conn.version(),
'cipher': ssl_conn.cipher(),
'subject': subject_dict,
'issuer': issuer_dict,
'version': decoded_cert.version,
'serialNumber': decoded_cert.serial_number,
'notBefore': decoded_cert.not_valid_before.strftime("%b %d %H:%M:%S %Y GMT"),
'notAfter': decoded_cert.not_valid_after.strftime("%b %d %H:%M:%S %Y GMT"),
}
extensions = decoded_cert.extensions
for ext in extensions:
if ext.oid != x509.ExtensionOID.SUBJECT_ALTERNATIVE_NAME:
continue
san_entries = ext.value
subject_alt_names = []
for entry in san_entries:
if isinstance(entry, x509.DNSName):
subject_alt_names.append(entry.value)
cert_dict['subjectAltName'] = subject_alt_names
process_cert(cert_dict)
result.update({'exported': False})
if output:
fname = f'{output["directory"]}/ssl.{output["format"]}'
output['file'] = fname
data['module-SSL Certificate Information'] = result
export(output, data)
log_writer('[sslinfo] Completed') | null |
160,847 | R = '\033[31m'
G = '\033[32m'
C = '\033[36m'
W = '\033[0m'
Y = '\033[33m'
from json import loads
import modules.subdom as parent
from modules.write_log import log_writer
def log_writer(message):
logging.basicConfig(
filename=settings.log_file_path,
encoding='utf-8',
level=logging.INFO,
format='[%(asctime)s] : %(message)s',
datefmt='%m/%d/%Y %I:%M:%S %p'
)
logging.info(message)
async def sonar(hostname, session):
print(f'{Y}[!] {C}Requesting {G}Sonar{W}')
url = f'https://sonar.omnisint.io/subdomains/{hostname}'
try:
async with session.get(url) as resp:
status = resp.status
if status == 200:
json_data = await resp.text()
json_read = loads(json_data)
print(f'{G}[+] {Y}Sonar {W}found {C}{len(json_read)} {W}subdomains!')
parent.found.extend(json_read)
else:
print(f'{R}[-] {C}Sonar Status : {W}{status}')
log_writer(f'[sonar_subs] Status = {status}, expected 200')
except Exception as exc:
print(f'{R}[-] {C}Sonar Exception : {W}{exc}')
log_writer(f'[sonar_subs] Exception = {exc}')
log_writer('[sonar_subs] Completed') | null |
160,848 | R = '\033[31m'
G = '\033[32m'
C = '\033[36m'
W = '\033[0m'
Y = '\033[33m'
from json import loads
import modules.subdom as parent
from modules.write_log import log_writer
def log_writer(message):
logging.basicConfig(
filename=settings.log_file_path,
encoding='utf-8',
level=logging.INFO,
format='[%(asctime)s] : %(message)s',
datefmt='%m/%d/%Y %I:%M:%S %p'
)
logging.info(message)
async def thcrowd(hostname, session):
print(f'{Y}[!] {C}Requesting {G}ThreatCrowd{W}')
url = 'https://www.threatcrowd.org/searchApi/v2/domain/report/'
thc_params = {
'domain': hostname
}
try:
async with session.get(url, params=thc_params) as resp:
status = resp.status
if status == 200:
output = await resp.text()
json_out = loads(output)
if json_out['response_code'] == '0':
pass
else:
subd = json_out['subdomains']
print(f'{G}[+] {Y}ThreatCrowd {W}found {C}{len(subd)} {W}subdomains!')
parent.found.extend(subd)
else:
print(f'{R}[-] {C}ThreatCrowd Status : {W}{status}')
log_writer(f'[thcrowd] Status = {status}, expected 200')
except Exception as exc:
print(f'{R}[-] {C}ThreatCrowd Exception : {W}{exc}')
log_writer(f'[thcrowd] Exception = {exc}')
log_writer('[thcrowd] Completed') | null |
160,849 | R = '\033[31m'
G = '\033[32m'
C = '\033[36m'
W = '\033[0m'
Y = '\033[33m'
import json
import requests
from datetime import date
from modules.export import export
from modules.write_log import log_writer
def export(output, data):
if output['format'] != 'txt':
print(f'{R}[-] {C}Invalid Output Format, Valid Formats : {W}txt')
sys.exit()
fname = output['file']
with open(fname, 'w') as outfile:
txt_export(data, outfile)
def log_writer(message):
logging.basicConfig(
filename=settings.log_file_path,
encoding='utf-8',
level=logging.INFO,
format='[%(asctime)s] : %(message)s',
datefmt='%m/%d/%Y %I:%M:%S %p'
)
logging.info(message)
def timetravel(target, data, output):
wayback_total = []
result = {}
is_avail = False
domain_query = f'{target}/*'
curr_yr = date.today().year
last_yr = curr_yr - 5
print(f'\n{Y}[!] Starting WayBack Machine...{W}\n')
print(f'{Y}[!] {C}Checking Availability on Wayback Machine{W}', end='', flush=True)
wm_avail = 'http://archive.org/wayback/available'
avail_data = {'url': target}
try:
check_rqst = requests.get(wm_avail, params=avail_data, timeout=10)
check_sc = check_rqst.status_code
if check_sc == 200:
check_data = check_rqst.text
json_chk_data = json.loads(check_data)
avail_data = json_chk_data['archived_snapshots']
if avail_data:
print(f'{G}{"[".rjust(5, ".")} Available ]{W}')
else:
print(f'{R}{"[".rjust(5, ".")} N/A ]{W}')
else:
print(f'\n{R}[-] Status : {C}{check_sc}{W}')
log_writer(f'[wayback] Status = {check_sc}, expected 200')
if avail_data:
print(f'{Y}[!] {C}Fetching URLs{W}', end='', flush=True)
wm_url = 'http://web.archive.org/cdx/search/cdx'
payload = {
'url': domain_query,
'fl': 'original',
'fastLatest': 'true',
'from': str(last_yr),
'to': str(curr_yr)
}
rqst = requests.get(wm_url, params=payload, timeout=10)
r_sc = rqst.status_code
if r_sc == 200:
r_data = rqst.text
if data:
r_data = set(r_data.split('\n'))
print(f'{G}{"[".rjust(5, ".")} {len(r_data)} ]{W}')
wayback_total.extend(r_data)
if output != 'None':
result.update({'links': list(r_data)})
result.update({'exported': False})
data['module-wayback_urls'] = result
fname = f'{output["directory"]}/wayback_urls.{output["format"]}'
output['file'] = fname
export(output, data)
else:
print(f'{R}{"[".rjust(5, ".")} Not Found ]{W}')
else:
print(f'{R}{"[".rjust(5, ".")} {r_sc} ]{W}')
except Exception as exc:
print(f'\n{R}[-] Exception : {C}{exc}{W}')
log_writer(f'[wayback] Exception = {exc}')
log_writer('[wayback] Completed') | null |
160,850 | import re
import bs4
import lxml
import asyncio
import requests
import threading
import tldextract
from modules.export import export
from modules.write_log import log_writer
requests.packages.urllib3.disable_warnings()
R = '\033[31m'
C = '\033[36m'
W = '\033[0m'
Y = '\033[33m'
user_agent = {'User-Agent': 'FinalRecon'}
async def robots(robo_url, base_url, data, output):
global r_total
print(f'{G}[+] {C}Looking for robots.txt{W}', end='', flush=True)
try:
r_rqst = requests.get(robo_url, headers=user_agent, verify=False, timeout=10)
r_sc = r_rqst.status_code
if r_sc == 200:
print(f'{G}{"[".rjust(9, ".")} Found ]{W}')
print(f'{G}[+] {C}Extracting robots Links{W}', end='', flush=True)
r_page = r_rqst.text
r_scrape = r_page.split('\n')
for entry in r_scrape:
if any([
entry.find('Disallow') == 0,
entry.find('Allow') == 0,
entry.find('Sitemap') == 0]):
url = entry.split(': ', 1)[1].strip()
tmp_url = url_filter(base_url, url)
if tmp_url is not None:
r_total.append(url_filter(base_url, url))
if url.endswith('xml'):
sm_total.append(url)
r_total = set(r_total)
print(f'{G}{"[".rjust(8, ".")} {len(r_total)} ]')
exporter(data, output, r_total, 'robots')
elif r_sc == 404:
print(f'{R}{"[".rjust(9, ".")} Not Found ]{W}')
else:
print(f'{R}{"[".rjust(9, ".")} {r_sc} ]{W}')
except Exception as exc:
print(f'\n{R}[-] Exception : {C}{exc}{W}')
log_writer(f'[crawler.robots] Exception = {exc}')
async def sitemap(target_url, data, output):
global sm_total
print(f'{G}[+] {C}Looking for sitemap.xml{W}', end='', flush=True)
try:
sm_rqst = requests.get(target_url, headers=user_agent, verify=False, timeout=10)
sm_sc = sm_rqst.status_code
if sm_sc == 200:
print(f'{G}{"[".rjust(8, ".")} Found ]{W}')
print(f'{G}[+] {C}Extracting sitemap Links{W}', end='', flush=True)
sm_page = sm_rqst.content
sm_soup = bs4.BeautifulSoup(sm_page, 'xml')
links = sm_soup.find_all('loc')
for url in links:
url = url.get_text()
if url is not None:
sm_total.append(url)
sm_total = set(sm_total)
print(f'{G}{"[".rjust(7, ".")} {len(sm_total)} ]{W}')
exporter(data, output, sm_total, 'sitemap')
elif sm_sc == 404:
print(f'{R}{"[".rjust(8, ".")} Not Found ]{W}')
else:
print(f'{R}{"[".rjust(8, ".")} Status Code : {sm_sc} ]{W}')
except Exception as exc:
print(f'\n{R}[-] Exception : {C}{exc}{W}')
log_writer(f'[crawler.sitemap] Exception = {exc}')
async def css(target, data, soup, output):
global css_total
print(f'{G}[+] {C}Extracting CSS Links{W}', end='', flush=True)
css_links = soup.find_all('link', href=True)
for link in css_links:
url = link.get('href')
if url is not None and '.css' in url:
css_total.append(url_filter(target, url))
css_total = set(css_total)
print(f'{G}{"[".rjust(11, ".")} {len(css_total)} ]{W}')
exporter(data, output, css_total, 'css')
async def js_scan(target, data, soup, output):
global js_total
print(f'{G}[+] {C}Extracting Javascript Links{W}', end='', flush=True)
scr_tags = soup.find_all('script', src=True)
for link in scr_tags:
url = link.get('src')
if url is not None and '.js' in url:
tmp_url = url_filter(target, url)
if tmp_url is not None:
js_total.append(tmp_url)
js_total = set(js_total)
print(f'{G}{"[".rjust(4, ".")} {len(js_total)} ]{W}')
exporter(data, output, js_total, 'javascripts')
async def internal_links(target, data, soup, output):
global int_total
print(f'{G}[+] {C}Extracting Internal Links{W}', end='', flush=True)
ext = tldextract.extract(target)
domain = ext.registered_domain
links = soup.find_all('a')
for link in links:
url = link.get('href')
if url is not None:
if domain in url:
int_total.append(url)
int_total = set(int_total)
print(f'{G}{"[".rjust(6, ".")} {len(int_total)} ]{W}')
exporter(data, output, int_total, 'internal_urls')
async def external_links(target, data, soup, output):
global ext_total
print(f'{G}[+] {C}Extracting External Links{W}', end='', flush=True)
ext = tldextract.extract(target)
domain = ext.registered_domain
links = soup.find_all('a')
for link in links:
url = link.get('href')
if url is not None:
if domain not in url and 'http' in url:
ext_total.append(url)
ext_total = set(ext_total)
print(f'{G}{"[".rjust(6, ".")} {len(ext_total)} ]{W}')
exporter(data, output, ext_total, 'external_urls')
async def images(target, data, soup, output):
global img_total
print(f'{G}[+] {C}Extracting Images{W}', end='', flush=True)
image_tags = soup.find_all('img')
for link in image_tags:
url = link.get('src')
if url is not None and len(url) > 1:
img_total.append(url_filter(target, url))
img_total = set(img_total)
print(f'{G}{"[".rjust(14, ".")} {len(img_total)} ]{W}')
exporter(data, output, img_total, 'images')
async def sm_crawl(data, output):
global sm_crawl_total
print(f'{G}[+] {C}Crawling Sitemaps{W}', end='', flush=True)
threads = []
def fetch(site_url):
try:
sm_rqst = requests.get(site_url, headers=user_agent, verify=False, timeout=10)
sm_sc = sm_rqst.status_code
if sm_sc == 200:
sm_data = sm_rqst.content.decode()
sm_soup = bs4.BeautifulSoup(sm_data, 'xml')
links = sm_soup.find_all('loc')
for url in links:
url = url.get_text()
if url is not None:
sm_crawl_total.append(url)
elif sm_sc == 404:
# print(R + '['.rjust(8, '.') + ' Not Found ]' + W)
pass
else:
# print(R + '['.rjust(8, '.') + ' {} ]'.format(sm_sc) + W)
pass
except Exception as exc:
# print(f'\n{R}[-] Exception : {C}{exc}{W}')
log_writer(f'[crawler.sm_crawl] Exception = {exc}')
for site_url in sm_total:
if site_url != sm_url:
if site_url.endswith('xml') is True:
task = threading.Thread(target=fetch, args=[site_url])
task.daemon = True
threads.append(task)
task.start()
for thread in threads:
thread.join()
sm_crawl_total = set(sm_crawl_total)
print(f'{G}{"[".rjust(14, ".")} {len(sm_crawl_total)} ]{W}')
exporter(data, output, sm_crawl_total, 'urls_inside_sitemap')
async def js_crawl(data, output):
global js_crawl_total
print(f'{G}[+] {C}Crawling Javascripts{W}', end='', flush=True)
threads = []
def fetch(js_url):
try:
js_rqst = requests.get(js_url, headers=user_agent, verify=False, timeout=10)
js_sc = js_rqst.status_code
if js_sc == 200:
js_data = js_rqst.content.decode()
js_data = js_data.split(';')
for line in js_data:
if any(['http://' in line, 'https://' in line]):
found = re.findall(r'\"(http[s]?://.*?)\"', line)
for item in found:
if len(item) > 8:
js_crawl_total.append(item)
except Exception as exc:
# print(f'\n{R}[-] Exception : {C}{exc}{W}')
log_writer(f'[crawler.js_crawl] Exception = {exc}')
for js_url in js_total:
task = threading.Thread(target=fetch, args=[js_url])
task.daemon = True
threads.append(task)
task.start()
for thread in threads:
thread.join()
js_crawl_total = set(js_crawl_total)
print(f'{G}{"[".rjust(11, ".")} {len(js_crawl_total)} ]{W}')
exporter(data, output, js_crawl_total, 'urls_inside_js')
def stats(output, data, soup):
global total
total.extend(r_total)
total.extend(sm_total)
total.extend(css_total)
total.extend(js_total)
total.extend(js_crawl_total)
total.extend(sm_crawl_total)
total.extend(int_total)
total.extend(ext_total)
total.extend(img_total)
total = set(total)
print(f'\n{G}[+] {C}Total Unique Links Extracted : {W}{len(total)}')
if output != 'None':
if len(total) != 0:
data['module-crawler-stats'] = {'Total Unique Links Extracted': str(len(total))}
try:
target_title = soup.title.string
except AttributeError:
target_title = 'None'
data['module-crawler-stats'].update({'Title ': str(target_title)})
data['module-crawler-stats'].update(
{
'total_urls_robots': len(r_total),
'total_urls_sitemap': len(sm_total),
'total_urls_css': len(css_total),
'total_urls_js': len(js_total),
'total_urls_in_js': len(js_crawl_total),
'total_urls_in_sitemaps': len(sm_crawl_total),
'total_urls_internal': len(int_total),
'total_urls_external': len(ext_total),
'total_urls_images': len(img_total),
'total_urls': len(total)
})
data['module-crawler-stats'].update({'exported': False})
def log_writer(message):
logging.basicConfig(
filename=settings.log_file_path,
encoding='utf-8',
level=logging.INFO,
format='[%(asctime)s] : %(message)s',
datefmt='%m/%d/%Y %I:%M:%S %p'
)
logging.info(message)
def crawler(target, output, data):
global r_url, sm_url
print(f'\n{Y}[!] Starting Crawler...{W}\n')
try:
rqst = requests.get(target, headers=user_agent, verify=False, timeout=10)
except Exception as exc:
print(f'{R} [-] Exception : {C}{exc}{W}')
log_writer(f'[crawler] Exception = {exc}')
return
status = rqst.status_code
if status == 200:
page = rqst.content
soup = bs4.BeautifulSoup(page, 'lxml')
protocol = target.split('://')
protocol = protocol[0]
temp_tgt = target.split('://')[1]
pattern = r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}:\d{2,5}'
custom = bool(re.match(pattern, temp_tgt))
if custom:
r_url = f'{protocol}://{temp_tgt}/robots.txt'
sm_url = f'{protocol}://{temp_tgt}/sitemap.xml'
base_url = f'{protocol}://{temp_tgt}'
else:
ext = tldextract.extract(target)
if ext.subdomain:
hostname = f'{ext.subdomain}.{ext.domain}.{ext.suffix}'
else:
hostname = ext.registered_domain
base_url = f'{protocol}://{hostname}'
r_url = f'{base_url}/robots.txt'
sm_url = f'{base_url}/sitemap.xml'
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
tasks = asyncio.gather(
robots(r_url, base_url, data, output),
sitemap(sm_url, data, output),
css(target, data, soup, output),
js_scan(target, data, soup, output),
internal_links(target, data, soup, output),
external_links(target, data, soup, output),
images(target, data, soup, output),
sm_crawl(data, output),
js_crawl(data, output))
loop.run_until_complete(tasks)
loop.close()
stats(output, data, soup)
log_writer('[crawler] Completed')
else:
print(f'{R}[-] {C}Status : {W}{status}')
log_writer(f'[crawler] Status code = {status}, expected 200') | null |
160,851 | import requests
from modules.export import export
from modules.write_log import log_writer
requests.packages.urllib3.disable_warnings()
R = '\033[31m'
C = '\033[36m'
W = '\033[0m'
Y = '\033[33m'
def export(output, data):
if output['format'] != 'txt':
print(f'{R}[-] {C}Invalid Output Format, Valid Formats : {W}txt')
sys.exit()
fname = output['file']
with open(fname, 'w') as outfile:
txt_export(data, outfile)
def log_writer(message):
logging.basicConfig(
filename=settings.log_file_path,
encoding='utf-8',
level=logging.INFO,
format='[%(asctime)s] : %(message)s',
datefmt='%m/%d/%Y %I:%M:%S %p'
)
logging.info(message)
def headers(target, output, data):
result = {}
print(f'\n{Y}[!] Headers :{W}\n')
try:
rqst = requests.get(target, verify=False, timeout=10)
for key, val in rqst.headers.items():
print(f'{C}{key} : {W}{val}')
if output != 'None':
result.update({key: val})
except Exception as exc:
print(f'\n{R}[-] {C}Exception : {W}{exc}\n')
if output != 'None':
result.update({'Exception': str(exc)})
log_writer(f'[headers] Exception = {exc}')
result.update({'exported': False})
if output != 'None':
fname = f'{output["directory"]}/headers.{output["format"]}'
output['file'] = fname
data['module-headers'] = result
export(output, data)
log_writer('[headers] Completed') | null |
160,852 | import asyncio
from json import load
from modules.export import export
from modules.write_log import log_writer
R = '\033[31m'
C = '\033[36m'
W = '\033[0m'
Y = '\033[33m'
async def get_whois(domain, server):
whois_result = {}
reader, writer = await asyncio.open_connection(server, 43)
writer.write((domain + '\r\n').encode())
raw_resp = b''
while True:
chunk = await reader.read(4096)
if not chunk:
break
raw_resp += chunk
writer.close()
await writer.wait_closed()
raw_result = raw_resp.decode()
if 'No match for' in raw_result:
whois_result = None
res_parts = raw_result.split('>>>', 1)
whois_result['whois'] = res_parts[0]
return whois_result
def export(output, data):
if output['format'] != 'txt':
print(f'{R}[-] {C}Invalid Output Format, Valid Formats : {W}txt')
sys.exit()
fname = output['file']
with open(fname, 'w') as outfile:
txt_export(data, outfile)
def log_writer(message):
logging.basicConfig(
filename=settings.log_file_path,
encoding='utf-8',
level=logging.INFO,
format='[%(asctime)s] : %(message)s',
datefmt='%m/%d/%Y %I:%M:%S %p'
)
logging.info(message)
def whois_lookup(domain, tld, script_path, output, data):
result = {}
db_path = f'{script_path}/whois_servers.json'
with open(db_path, 'r') as db_file:
db_json = load(db_file)
print(f'\n{Y}[!] Whois Lookup : {W}\n')
try:
whois_sv = db_json[tld]
whois_info = asyncio.run(get_whois(domain, whois_sv))
print(whois_info['whois'])
result.update(whois_info)
except KeyError:
print(f'{R}[-] Error : {C}This domain suffix is not supported.{W}')
result.update({'Error': 'This domain suffix is not supported.'})
log_writer('[whois] Exception = This domain suffix is not supported.')
except Exception as exc:
print(f'{R}[-] Error : {C}{exc}{W}')
result.update({'Error': str(exc)})
log_writer(f'[whois] Exception = {exc}')
result.update({'exported': False})
if output != 'None':
fname = f'{output["directory"]}/whois.{output["format"]}'
output['file'] = fname
data['module-whois'] = result
export(output, data)
log_writer('[whois] Completed') | null |
160,853 | import dnslib
from modules.export import export
from modules.write_log import log_writer
R = '\033[31m'
C = '\033[36m'
W = '\033[0m'
Y = '\033[33m'
def export(output, data):
if output['format'] != 'txt':
print(f'{R}[-] {C}Invalid Output Format, Valid Formats : {W}txt')
sys.exit()
fname = output['file']
with open(fname, 'w') as outfile:
txt_export(data, outfile)
def log_writer(message):
logging.basicConfig(
filename=settings.log_file_path,
encoding='utf-8',
level=logging.INFO,
format='[%(asctime)s] : %(message)s',
datefmt='%m/%d/%Y %I:%M:%S %p'
)
logging.info(message)
def dnsrec(domain, output, data):
result = {}
print(f'\n{Y}[!] Starting DNS Enumeration...{W}\n')
dns_records = ['A', 'AAAA', 'ANY', 'CAA', 'CNAME', 'MX', 'NS', 'TXT']
full_ans = []
for dns_record in dns_records:
query = dnslib.DNSRecord.question(domain, dns_record)
try:
pkt = query.send('8.8.8.8', 53, tcp='UDP')
ans = dnslib.DNSRecord.parse(pkt)
ans = str(ans)
ans = ans.split('\n')
full_ans.extend(ans)
except ConnectionRefusedError as exc:
print(f'\n{R}[-] {C}Exception : {W}{exc}\nServer is probably not listening!')
log_writer(f'[dns] Exception = {exc}')
return
full_ans = set(full_ans)
dns_found = []
for entry in full_ans:
if not entry.startswith(';'):
dns_found.append(entry)
if not dns_found:
print(f'{R}[-] {C}DNS Records Not Found!{W}')
if output != 'None':
result.setdefault('dns', ['DNS Records Not Found'])
else:
for entry in dns_found:
print(f'{C}{entry}{W}')
if output != 'None':
result.setdefault('dns', []).append(entry)
dmarc_target = f'_dmarc.{domain}'
query = dnslib.DNSRecord.question(dmarc_target, 'TXT')
pkt = query.send('8.8.8.8', 53, tcp='UDP')
dmarc_ans = dnslib.DNSRecord.parse(pkt)
dmarc_ans = str(dmarc_ans)
dmarc_ans = dmarc_ans.split('\n')
dmarc_found = []
for entry in dmarc_ans:
if entry.startswith('_dmarc'):
dmarc_found.append(entry)
if not dmarc_found:
print(f'\n{R}[-] {C}DMARC Record Not Found!{W}')
if output != 'None':
result.setdefault('dmarc', ['DMARC Record Not Found!'])
else:
for entry in dmarc_found:
print(f'{C}{entry}{W}')
if output != 'None':
result.setdefault('dmarc', []).append(entry)
result.update({'exported': False})
if output != 'None':
data['module-DNS Enumeration'] = result
fname = f'{output["directory"]}/dns_records.{output["format"]}'
output['file'] = fname
export(output, data)
log_writer('[dns] Completed') | null |
160,854 | import os
import sys
G = '\033[32m'
C = '\033[36m'
W = '\033[0m'
from modules.write_log import log_writer
import settings as config
meta_file_path = config.meta_file_path
import argparse
VERSION = '1.1.6'
import socket
import datetime
import ipaddress
import tldextract
from json import loads
def banner():
with open(meta_file_path, 'r') as metadata:
json_data = loads(metadata.read())
twitter_url = json_data['twitter']
comms_url = json_data['comms']
art = r'''
______ __ __ __ ______ __
/\ ___\/\ \ /\ "-.\ \ /\ __ \ /\ \
\ \ __\\ \ \\ \ \-. \\ \ __ \\ \ \____
\ \_\ \ \_\\ \_\\"\_\\ \_\ \_\\ \_____\
\/_/ \/_/ \/_/ \/_/ \/_/\/_/ \/_____/
______ ______ ______ ______ __ __
/\ == \ /\ ___\ /\ ___\ /\ __ \ /\ "-.\ \
\ \ __< \ \ __\ \ \ \____\ \ \/\ \\ \ \-. \
\ \_\ \_\\ \_____\\ \_____\\ \_____\\ \_\\"\_\
\/_/ /_/ \/_____/ \/_____/ \/_____/ \/_/ \/_/'''
print(f'{G}{art}{W}\n')
print(f'{G}[>]{C} Created By :{W} thewhiteh4t')
print(f'{G} |--->{C} Twitter :{W} {twitter_url}')
print(f'{G} |--->{C} Community :{W} {comms_url}')
print(f'{G}[>]{C} Version :{W} {VERSION}\n') | null |
160,855 | import os
import re
from setuptools import find_packages, setup
package_data = {"": ["*.json", "*.kv", "*.wav"], "katrain": [], "tests": []}
def include_data_files(directory):
for root, subfolders, files in os.walk(directory):
for fn in files:
filename = os.path.join(root.replace("/", os.path.sep), fn)
parts = filename.split(os.path.sep)
package_data[parts[0]].append(os.path.join(*parts[1:])) | null |
160,856 | import heapq
import math
import os
import random
import struct
import sys
from typing import List, Tuple, TypeVar
def check_thread(tb=False): # for checking if draws occur in correct thread
import threading
print("build in ", threading.current_thread().ident)
if tb:
import traceback
traceback.print_stack() | null |
160,857 | import heapq
import math
import os
import random
import struct
import sys
from typing import List, Tuple, TypeVar
PATHS = {}
def find_package_resource(path, silent_errors=False):
global PATHS
if path.startswith("katrain"):
if not PATHS.get("PACKAGE"):
try:
with pkg_resources.path("katrain", "gui.kv") as p:
PATHS["PACKAGE"] = os.path.split(str(p))[0]
except (ModuleNotFoundError, FileNotFoundError, ValueError) as e:
print(f"Package path not found, installation possibly broken. Error: {e}", file=sys.stderr)
return f"FILENOTFOUND/{path}"
return os.path.join(PATHS["PACKAGE"], path.replace("katrain\\", "katrain/").replace("katrain/", ""))
else:
return os.path.abspath(os.path.expanduser(path)) # absolute path | null |
160,858 | import heapq
import math
import os
import random
import struct
import sys
from typing import List, Tuple, TypeVar
def unpack_floats(str, num):
if not str:
return None
return struct.unpack(f"{num}e", str) | null |
160,859 | import heapq
import math
import os
import random
import struct
import sys
from typing import List, Tuple, TypeVar
def format_visits(n):
if n < 1000:
return str(n)
if n < 1e5:
return f"{n/1000:.1f}k"
if n < 1e6:
return f"{n/1000:.0f}k"
return f"{n/1e6:.0f}M" | null |
160,860 | import heapq
import math
import os
import random
import struct
import sys
from typing import List, Tuple, TypeVar
def json_truncate_arrays(data, lim=20):
if isinstance(data, list):
if data and isinstance(data[0], dict):
return [json_truncate_arrays(d) for d in data]
if len(data) > lim:
data = [f"{len(data)} x {type(data[0]).__name__}"]
return data
elif isinstance(data, dict):
return {k: json_truncate_arrays(v) for k, v in data.items()}
else:
return data | null |
160,861 | import heapq
import math
import random
import time
from typing import Dict, List, Optional, Tuple
from katrain.core.constants import (
AI_DEFAULT,
AI_HANDICAP,
AI_INFLUENCE,
AI_INFLUENCE_ELO_GRID,
AI_JIGO,
AI_ANTIMIRROR,
AI_LOCAL,
AI_LOCAL_ELO_GRID,
AI_PICK,
AI_PICK_ELO_GRID,
AI_POLICY,
AI_RANK,
AI_SCORELOSS,
AI_SCORELOSS_ELO,
AI_SETTLE_STONES,
AI_SIMPLE_OWNERSHIP,
AI_STRATEGIES_PICK,
AI_STRATEGIES_POLICY,
AI_STRENGTH,
AI_TENUKI,
AI_TENUKI_ELO_GRID,
AI_TERRITORY,
AI_TERRITORY_ELO_GRID,
AI_WEIGHTED,
AI_WEIGHTED_ELO,
CALIBRATED_RANK_ELO,
OUTPUT_DEBUG,
OUTPUT_ERROR,
OUTPUT_INFO,
PRIORITY_EXTRA_AI_QUERY,
ADDITIONAL_MOVE_ORDER,
)
from katrain.core.game import Game, GameNode, Move
from katrain.core.utils import var_to_grid, weighted_selection_without_replacement, evaluation_class
def interp1d(lst, x):
xs, ys = zip(*lst)
i, t = interp_ix(xs, x)
return (1 - t) * ys[i] + t * ys[i + 1]
def interp2d(gridspec, x, y):
xs, ys, matrix = gridspec
i, t = interp_ix(xs, x)
j, s = interp_ix(ys, y)
return (
matrix[j][i] * (1 - t) * (1 - s)
+ matrix[j][i + 1] * t * (1 - s)
+ matrix[j + 1][i] * (1 - t) * s
+ matrix[j + 1][i + 1] * t * s
)
AI_DEFAULT = "ai:default"
AI_HANDICAP = "ai:handicap"
AI_SCORELOSS = "ai:scoreloss"
AI_WEIGHTED = "ai:p:weighted"
AI_JIGO = "ai:jigo"
AI_PICK = "ai:p:pick"
AI_LOCAL = "ai:p:local"
AI_TENUKI = "ai:p:tenuki"
AI_INFLUENCE = "ai:p:influence"
AI_TERRITORY = "ai:p:territory"
AI_RANK = "ai:p:rank"
AI_STRENGTH = { # dan ranks, backup if model is missing. TODO: remove some?
AI_DEFAULT: 9,
AI_ANTIMIRROR: 9,
AI_POLICY: 5,
AI_JIGO: float("nan"),
AI_SCORELOSS: -4,
AI_WEIGHTED: -4,
AI_PICK: -7,
AI_LOCAL: -4,
AI_TENUKI: -7,
AI_INFLUENCE: -7,
AI_TERRITORY: -7,
AI_RANK: float("nan"),
AI_SIMPLE_OWNERSHIP: 2,
AI_SETTLE_STONES: 2,
}
CALIBRATED_RANK_ELO = [
(-21.679482223451032, 18),
(42.60243194422105, 17),
(106.88434611189314, 16),
(171.16626027956522, 15),
(235.44817444723742, 14),
(299.7300886149095, 13),
(364.0120027825817, 12),
(428.2939169502538, 11),
(492.5758311179259, 10),
(556.8577452855981, 9),
(621.1396594532702, 8),
(685.4215736209424, 7),
(749.7034877886144, 6),
(813.9854019562865, 5),
(878.2673161239586, 4),
(942.5492302916308, 3),
(1006.8311444593029, 2),
(1071.113058626975, 1),
(1135.3949727946472, 0),
(1199.6768869623193, -1),
(1263.9588011299913, -2),
(1700, -4),
]
AI_WEIGHTED_ELO = [
(0.5, 1591.5718897531551),
(1.0, 1269.9896556526198),
(1.25, 1042.25179764667),
(1.5, 848.9410084463602),
(1.75, 630.1483212024823),
(2, 575.3637091858013),
(2.5, 410.9747543504796),
(3.0, 219.8667371799533),
]
AI_SCORELOSS_ELO = [
(0.0, 539),
(0.05, 625),
(0.1, 859),
(0.2, 1035),
(0.3, 1201),
(0.4, 1299),
(0.5, 1346),
(0.75, 1374),
(1.0, 1386),
]
AI_LOCAL_ELO_GRID = [
[0.0, 0.05, 0.1, 0.2, 0.3, 0.5, 0.75, 1.0],
[0, 5, 10, 15, 25, 50],
[
[-204.0, 791.0, 1154.0, 1372.0, 1402.0, 1473.0, 1700.0, 1700.0],
[174.0, 1094.0, 1191.0, 1384.0, 1435.0, 1522.0, 1700.0, 1700.0],
[619.0, 1155.0, 1323.0, 1390.0, 1450.0, 1558.0, 1700.0, 1700.0],
[975.0, 1289.0, 1332.0, 1401.0, 1461.0, 1575.0, 1700.0, 1700.0],
[1344.0, 1348.0, 1358.0, 1467.0, 1477.0, 1616.0, 1700.0, 1700.0],
[1425.0, 1474.0, 1489.0, 1524.0, 1571.0, 1700.0, 1700.0, 1700.0],
],
]
AI_TENUKI_ELO_GRID = [
[0.0, 0.05, 0.1, 0.2, 0.3, 0.5, 0.75, 1.0],
[0, 5, 10, 15, 25, 50],
[
[47.0, 335.0, 530.0, 678.0, 830.0, 1070.0, 1376.0, 1700.0],
[99.0, 469.0, 546.0, 707.0, 855.0, 1090.0, 1413.0, 1700.0],
[327.0, 513.0, 605.0, 745.0, 875.0, 1110.0, 1424.0, 1700.0],
[429.0, 519.0, 620.0, 754.0, 900.0, 1130.0, 1435.0, 1700.0],
[492.0, 607.0, 682.0, 797.0, 1000.0, 1208.0, 1454.0, 1700.0],
[778.0, 830.0, 909.0, 949.0, 1169.0, 1461.0, 1483.0, 1700.0],
],
]
AI_TERRITORY_ELO_GRID = [
[0.0, 0.05, 0.1, 0.2, 0.3, 0.5, 0.75, 1.0],
[0, 5, 10, 15, 25, 50],
[
[34.0, 383.0, 566.0, 748.0, 980.0, 1264.0, 1527.0, 1700.0],
[131.0, 450.0, 586.0, 826.0, 995.0, 1280.0, 1537.0, 1700.0],
[291.0, 517.0, 627.0, 850.0, 1010.0, 1310.0, 1547.0, 1700.0],
[454.0, 526.0, 696.0, 870.0, 1038.0, 1340.0, 1590.0, 1700.0],
[491.0, 603.0, 747.0, 890.0, 1050.0, 1390.0, 1635.0, 1700.0],
[718.0, 841.0, 1039.0, 1076.0, 1332.0, 1523.0, 1700.0, 1700.0],
],
]
AI_INFLUENCE_ELO_GRID = [
[0.0, 0.05, 0.1, 0.2, 0.3, 0.5, 0.75, 1.0],
[0, 5, 10, 15, 25, 50],
[
[217.0, 439.0, 572.0, 768.0, 960.0, 1227.0, 1449.0, 1521.0],
[302.0, 551.0, 580.0, 800.0, 1028.0, 1257.0, 1470.0, 1529.0],
[388.0, 572.0, 619.0, 839.0, 1077.0, 1305.0, 1490.0, 1561.0],
[467.0, 591.0, 764.0, 878.0, 1097.0, 1390.0, 1530.0, 1591.0],
[539.0, 622.0, 815.0, 953.0, 1120.0, 1420.0, 1560.0, 1601.0],
[772.0, 912.0, 958.0, 1145.0, 1318.0, 1511.0, 1577.0, 1623.0],
],
]
AI_PICK_ELO_GRID = [
[0.0, 0.05, 0.1, 0.2, 0.3, 0.5, 0.75, 1.0],
[0, 5, 10, 15, 25, 50],
[
[-533.0, -515.0, -355.0, 234.0, 650.0, 1147.0, 1546.0, 1700.0],
[-531.0, -450.0, -69.0, 347.0, 670.0, 1182.0, 1550.0, 1700.0],
[-450.0, -311.0, 140.0, 459.0, 693.0, 1252.0, 1555.0, 1700.0],
[-365.0, -82.0, 265.0, 508.0, 864.0, 1301.0, 1619.0, 1700.0],
[-113.0, 273.0, 363.0, 641.0, 983.0, 1486.0, 1700.0, 1700.0],
[514.0, 670.0, 870.0, 1128.0, 1305.0, 1550.0, 1700.0, 1700.0],
],
]
def ai_rank_estimation(strategy, settings) -> int:
if strategy in [AI_DEFAULT, AI_HANDICAP, AI_JIGO]:
return 9
if strategy == AI_RANK:
return 1 - settings["kyu_rank"]
if strategy in [AI_WEIGHTED, AI_SCORELOSS, AI_LOCAL, AI_TENUKI, AI_TERRITORY, AI_INFLUENCE, AI_PICK]:
if strategy == AI_WEIGHTED:
elo = interp1d(AI_WEIGHTED_ELO, settings["weaken_fac"])
if strategy == AI_SCORELOSS:
elo = interp1d(AI_SCORELOSS_ELO, settings["strength"])
if strategy == AI_PICK:
elo = interp2d(AI_PICK_ELO_GRID, settings["pick_frac"], settings["pick_n"])
if strategy == AI_LOCAL:
elo = interp2d(AI_LOCAL_ELO_GRID, settings["pick_frac"], settings["pick_n"])
if strategy == AI_TENUKI:
elo = interp2d(AI_TENUKI_ELO_GRID, settings["pick_frac"], settings["pick_n"])
if strategy == AI_TERRITORY:
elo = interp2d(AI_TERRITORY_ELO_GRID, settings["pick_frac"], settings["pick_n"])
if strategy == AI_INFLUENCE:
elo = interp2d(AI_INFLUENCE_ELO_GRID, settings["pick_frac"], settings["pick_n"])
kyu = interp1d(CALIBRATED_RANK_ELO, elo)
return 1 - kyu
else:
return AI_STRENGTH[strategy] | null |
160,862 | import heapq
import math
import random
import time
from typing import Dict, List, Optional, Tuple
from katrain.core.constants import (
AI_DEFAULT,
AI_HANDICAP,
AI_INFLUENCE,
AI_INFLUENCE_ELO_GRID,
AI_JIGO,
AI_ANTIMIRROR,
AI_LOCAL,
AI_LOCAL_ELO_GRID,
AI_PICK,
AI_PICK_ELO_GRID,
AI_POLICY,
AI_RANK,
AI_SCORELOSS,
AI_SCORELOSS_ELO,
AI_SETTLE_STONES,
AI_SIMPLE_OWNERSHIP,
AI_STRATEGIES_PICK,
AI_STRATEGIES_POLICY,
AI_STRENGTH,
AI_TENUKI,
AI_TENUKI_ELO_GRID,
AI_TERRITORY,
AI_TERRITORY_ELO_GRID,
AI_WEIGHTED,
AI_WEIGHTED_ELO,
CALIBRATED_RANK_ELO,
OUTPUT_DEBUG,
OUTPUT_ERROR,
OUTPUT_INFO,
PRIORITY_EXTRA_AI_QUERY,
ADDITIONAL_MOVE_ORDER,
)
from katrain.core.game import Game, GameNode, Move
from katrain.core.utils import var_to_grid, weighted_selection_without_replacement, evaluation_class
ADDITIONAL_MOVE_ORDER = 999
def evaluation_class(points_lost: float, eval_thresholds: List[float]):
i = 0
while i < len(eval_thresholds) - 1 and points_lost < eval_thresholds[i]:
i += 1
return i
def game_report(game, thresholds, depth_filter=None):
cn = game.current_node
nodes = cn.nodes_from_root
while cn.children: # main branch
cn = cn.children[0]
nodes.append(cn)
x, y = game.board_size
depth_filter = [math.ceil(board_frac * x * y) for board_frac in depth_filter or (0, 1e9)]
nodes = [n for n in nodes if n.move and not n.is_root and depth_filter[0] <= n.depth < depth_filter[1]]
histogram = [{"B": 0, "W": 0} for _ in thresholds]
ai_top_move_count = {"B": 0, "W": 0}
ai_approved_move_count = {"B": 0, "W": 0}
player_ptloss = {"B": [], "W": []}
weights = {"B": [], "W": []}
for n in nodes:
points_lost = n.points_lost
if n.points_lost is None:
continue
else:
points_lost = max(0, points_lost)
bucket = len(thresholds) - 1 - evaluation_class(points_lost, thresholds)
player_ptloss[n.player].append(points_lost)
histogram[bucket][n.player] += 1
cands = n.parent.candidate_moves
filtered_cands = [d for d in cands if d["order"] < ADDITIONAL_MOVE_ORDER and "prior" in d]
weight = min(
1.0,
sum([max(d["pointsLost"], 0) * d["prior"] for d in filtered_cands])
/ (sum(d["prior"] for d in filtered_cands) or 1e-6),
) # complexity capped at 1
# adj_weight between 0.05 - 1, dependent on difficulty and points lost
adj_weight = max(0.05, min(1.0, max(weight, points_lost / 4)))
weights[n.player].append((weight, adj_weight))
if n.parent.analysis_complete:
ai_top_move_count[n.player] += int(cands[0]["move"] == n.move.gtp())
ai_approved_move_count[n.player] += int(
n.move.gtp()
in [d["move"] for d in filtered_cands if d["order"] == 0 or (d["pointsLost"] < 0.5 and d["order"] < 5)]
)
wt_loss = {
bw: sum(s * aw for s, (w, aw) in zip(player_ptloss[bw], weights[bw]))
/ (sum(aw for _, aw in weights[bw]) or 1e-6)
for bw in "BW"
}
sum_stats = {
bw: {
"accuracy": 100 * 0.75 ** wt_loss[bw],
"complexity": sum(w for w, aw in weights[bw]) / len(player_ptloss[bw]),
"mean_ptloss": sum(player_ptloss[bw]) / len(player_ptloss[bw]),
"weighted_ptloss": wt_loss[bw],
"ai_top_move": ai_top_move_count[bw] / len(player_ptloss[bw]),
"ai_top5_move": ai_approved_move_count[bw] / len(player_ptloss[bw]),
}
if len(player_ptloss[bw]) > 0
else {}
for bw in "BW"
}
return sum_stats, histogram, player_ptloss | null |
160,863 | import heapq
import math
import random
import time
from typing import Dict, List, Optional, Tuple
from katrain.core.constants import (
AI_DEFAULT,
AI_HANDICAP,
AI_INFLUENCE,
AI_INFLUENCE_ELO_GRID,
AI_JIGO,
AI_ANTIMIRROR,
AI_LOCAL,
AI_LOCAL_ELO_GRID,
AI_PICK,
AI_PICK_ELO_GRID,
AI_POLICY,
AI_RANK,
AI_SCORELOSS,
AI_SCORELOSS_ELO,
AI_SETTLE_STONES,
AI_SIMPLE_OWNERSHIP,
AI_STRATEGIES_PICK,
AI_STRATEGIES_POLICY,
AI_STRENGTH,
AI_TENUKI,
AI_TENUKI_ELO_GRID,
AI_TERRITORY,
AI_TERRITORY_ELO_GRID,
AI_WEIGHTED,
AI_WEIGHTED_ELO,
CALIBRATED_RANK_ELO,
OUTPUT_DEBUG,
OUTPUT_ERROR,
OUTPUT_INFO,
PRIORITY_EXTRA_AI_QUERY,
ADDITIONAL_MOVE_ORDER,
)
from katrain.core.game import Game, GameNode, Move
from katrain.core.utils import var_to_grid, weighted_selection_without_replacement, evaluation_class
def dirichlet_noise(num, dir_alpha=0.3):
sample = [random.gammavariate(dir_alpha, 1) for _ in range(num)]
sum_sample = sum(sample)
return [s / sum_sample for s in sample] | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.