nwo
stringlengths 10
28
| sha
stringlengths 40
40
| path
stringlengths 11
97
| identifier
stringlengths 1
64
| parameters
stringlengths 2
2.24k
| return_statement
stringlengths 0
2.17k
| docstring
stringlengths 0
5.45k
| docstring_summary
stringlengths 0
3.83k
| func_begin
int64 1
13.4k
| func_end
int64 2
13.4k
| function
stringlengths 28
56.4k
| url
stringlengths 106
209
| project
int64 1
48
| executed_lines
sequence | executed_lines_pc
float64 0
153
| missing_lines
sequence | missing_lines_pc
float64 0
100
| covered
bool 2
classes | filecoverage
float64 2.53
100
| function_lines
int64 2
1.46k
| mccabe
int64 1
253
| coverage
float64 0
100
| docstring_lines
int64 0
112
| function_nodoc
stringlengths 9
56.4k
| id
int64 0
29.8k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Zulko/moviepy | 858bb81fba7e09f1f562283ed6d1394db883b6c7 | moviepy/video/fx/multiply_speed.py | multiply_speed | (clip, factor=None, final_duration=None) | return new_clip | Returns a clip playing the current clip but at a speed multiplied by ``factor``.
Instead of factor one can indicate the desired ``final_duration`` of the clip, and
the factor will be automatically computed. The same effect is applied to the clip's
audio and mask if any. | Returns a clip playing the current clip but at a speed multiplied by ``factor``. | 1 | 16 | def multiply_speed(clip, factor=None, final_duration=None):
"""Returns a clip playing the current clip but at a speed multiplied by ``factor``.
Instead of factor one can indicate the desired ``final_duration`` of the clip, and
the factor will be automatically computed. The same effect is applied to the clip's
audio and mask if any.
"""
if final_duration:
factor = 1.0 * clip.duration / final_duration
new_clip = clip.time_transform(lambda t: factor * t, apply_to=["mask", "audio"])
if clip.duration is not None:
new_clip = new_clip.with_duration(1.0 * clip.duration / factor)
return new_clip | https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/fx/multiply_speed.py#L1-L16 | 46 | [
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15
] | 100 | [] | 0 | true | 100 | 16 | 3 | 100 | 5 | def multiply_speed(clip, factor=None, final_duration=None):
if final_duration:
factor = 1.0 * clip.duration / final_duration
new_clip = clip.time_transform(lambda t: factor * t, apply_to=["mask", "audio"])
if clip.duration is not None:
new_clip = new_clip.with_duration(1.0 * clip.duration / factor)
return new_clip | 28,567 |
Zulko/moviepy | 858bb81fba7e09f1f562283ed6d1394db883b6c7 | moviepy/video/fx/resize.py | _get_cv2_resizer | () | return (resizer, []) | 4 | 20 | def _get_cv2_resizer():
try:
import cv2
except ImportError:
return (None, ["OpenCV not found (install 'opencv-python')"])
def resizer(pic, new_size):
lx, ly = int(new_size[0]), int(new_size[1])
if lx > pic.shape[1] or ly > pic.shape[0]:
# For upsizing use linear for good quality & decent speed
interpolation = cv2.INTER_LINEAR
else:
# For dowsizing use area to prevent aliasing
interpolation = cv2.INTER_AREA
return cv2.resize(+pic.astype("uint8"), (lx, ly), interpolation=interpolation)
return (resizer, []) | https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/fx/resize.py#L4-L20 | 46 | [
0,
1,
2,
3,
4,
5
] | 35.294118 | [
6,
7,
8,
10,
13,
14,
16
] | 41.176471 | false | 78.095238 | 17 | 5 | 58.823529 | 0 | def _get_cv2_resizer():
try:
import cv2
except ImportError:
return (None, ["OpenCV not found (install 'opencv-python')"])
def resizer(pic, new_size):
lx, ly = int(new_size[0]), int(new_size[1])
if lx > pic.shape[1] or ly > pic.shape[0]:
# For upsizing use linear for good quality & decent speed
interpolation = cv2.INTER_LINEAR
else:
# For dowsizing use area to prevent aliasing
interpolation = cv2.INTER_AREA
return cv2.resize(+pic.astype("uint8"), (lx, ly), interpolation=interpolation)
return (resizer, []) | 28,568 |
||
Zulko/moviepy | 858bb81fba7e09f1f562283ed6d1394db883b6c7 | moviepy/video/fx/resize.py | _get_PIL_resizer | () | return (resizer, []) | 23 | 45 | def _get_PIL_resizer():
try:
from PIL import Image
except ImportError:
return (None, ["PIL not found (install 'Pillow')"])
import numpy as np
def resizer(pic, new_size):
new_size = list(map(int, new_size))[::-1]
# shape = pic.shape
# if len(shape) == 3:
# newshape = (new_size[0], new_size[1], shape[2])
# else:
# newshape = (new_size[0], new_size[1])
pil_img = Image.fromarray(pic)
resized_pil = pil_img.resize(new_size[::-1], Image.ANTIALIAS)
# arr = np.fromstring(resized_pil.tostring(), dtype="uint8")
# arr.reshape(newshape)
return np.array(resized_pil)
return (resizer, []) | https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/fx/resize.py#L23-L45 | 46 | [
0,
1,
2,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
16,
17,
18,
19,
20,
21,
22
] | 91.304348 | [
3,
4
] | 8.695652 | false | 78.095238 | 23 | 3 | 91.304348 | 0 | def _get_PIL_resizer():
try:
from PIL import Image
except ImportError:
return (None, ["PIL not found (install 'Pillow')"])
import numpy as np
def resizer(pic, new_size):
new_size = list(map(int, new_size))[::-1]
# shape = pic.shape
# if len(shape) == 3:
# newshape = (new_size[0], new_size[1], shape[2])
# else:
# newshape = (new_size[0], new_size[1])
pil_img = Image.fromarray(pic)
resized_pil = pil_img.resize(new_size[::-1], Image.ANTIALIAS)
# arr = np.fromstring(resized_pil.tostring(), dtype="uint8")
# arr.reshape(newshape)
return np.array(resized_pil)
return (resizer, []) | 28,569 |
||
Zulko/moviepy | 858bb81fba7e09f1f562283ed6d1394db883b6c7 | moviepy/video/fx/resize.py | _get_scipy_resizer | () | return (resizer, []) | 48 | 77 | def _get_scipy_resizer():
try:
from scipy.misc import imresize
except ImportError:
try:
from scipy import __version__ as __scipy_version__
except ImportError:
return (None, ["Scipy not found (install 'scipy' or 'Pillow')"])
scipy_version_info = tuple(
int(num) for num in __scipy_version__.split(".") if num.isdigit()
)
# ``scipy.misc.imresize`` was removed in v1.3.0
if scipy_version_info >= (1, 3, 0):
return (
None,
[
"scipy.misc.imresize not found (was removed in scipy v1.3.0,"
f" you are using v{__scipy_version__}, install 'Pillow')"
],
)
# unknown reason
return (None, "scipy.misc.imresize not found")
def resizer(pic, new_size):
return imresize(pic, map(int, new_size[::-1]))
return (resizer, []) | https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/fx/resize.py#L48-L77 | 46 | [
0,
1,
2,
3,
4,
5,
6,
7,
8
] | 30 | [
9,
14,
15,
24,
26,
27,
29
] | 23.333333 | false | 78.095238 | 30 | 5 | 76.666667 | 0 | def _get_scipy_resizer():
try:
from scipy.misc import imresize
except ImportError:
try:
from scipy import __version__ as __scipy_version__
except ImportError:
return (None, ["Scipy not found (install 'scipy' or 'Pillow')"])
scipy_version_info = tuple(
int(num) for num in __scipy_version__.split(".") if num.isdigit()
)
# ``scipy.misc.imresize`` was removed in v1.3.0
if scipy_version_info >= (1, 3, 0):
return (
None,
[
"scipy.misc.imresize not found (was removed in scipy v1.3.0,"
f" you are using v{__scipy_version__}, install 'Pillow')"
],
)
# unknown reason
return (None, "scipy.misc.imresize not found")
def resizer(pic, new_size):
return imresize(pic, map(int, new_size[::-1]))
return (resizer, []) | 28,570 |
||
Zulko/moviepy | 858bb81fba7e09f1f562283ed6d1394db883b6c7 | moviepy/video/fx/resize.py | _get_resizer | () | return {"resizer": None, "origin": None, "error_msgs": reversed(error_messages)} | Tries to define a ``resizer`` function using next libraries, in the given
order:
- cv2
- PIL
- scipy
Returns a dictionary with following attributes:
- ``resizer``: Function used to resize images in ``resize`` FX function.
- ``origin``: Library used to resize.
- ``error_msgs``: If any of the libraries is available, shows the user why
this feature is not available and how to fix it in several error messages
which are formatted in the error displayed, if resizing is not possible. | Tries to define a ``resizer`` function using next libraries, in the given
order: | 80 | 110 | def _get_resizer():
"""Tries to define a ``resizer`` function using next libraries, in the given
order:
- cv2
- PIL
- scipy
Returns a dictionary with following attributes:
- ``resizer``: Function used to resize images in ``resize`` FX function.
- ``origin``: Library used to resize.
- ``error_msgs``: If any of the libraries is available, shows the user why
this feature is not available and how to fix it in several error messages
which are formatted in the error displayed, if resizing is not possible.
"""
error_messages = []
resizer_getters = {
"cv2": _get_cv2_resizer,
"PIL": _get_PIL_resizer,
"scipy": _get_scipy_resizer,
}
for origin, resizer_getter in resizer_getters.items():
resizer, _error_messages = resizer_getter()
if resizer is not None:
return {"resizer": resizer, "origin": origin, "error_msgs": []}
else:
error_messages.extend(_error_messages)
return {"resizer": None, "origin": None, "error_msgs": reversed(error_messages)} | https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/fx/resize.py#L80-L110 | 46 | [
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
16,
17,
18,
19,
20,
21,
22,
23,
24,
25,
26,
27,
28,
29
] | 96.774194 | [
30
] | 3.225806 | false | 78.095238 | 31 | 3 | 96.774194 | 14 | def _get_resizer():
error_messages = []
resizer_getters = {
"cv2": _get_cv2_resizer,
"PIL": _get_PIL_resizer,
"scipy": _get_scipy_resizer,
}
for origin, resizer_getter in resizer_getters.items():
resizer, _error_messages = resizer_getter()
if resizer is not None:
return {"resizer": resizer, "origin": origin, "error_msgs": []}
else:
error_messages.extend(_error_messages)
return {"resizer": None, "origin": None, "error_msgs": reversed(error_messages)} | 28,571 |
Zulko/moviepy | 858bb81fba7e09f1f562283ed6d1394db883b6c7 | moviepy/video/fx/resize.py | resize | (clip, new_size=None, height=None, width=None, apply_to_mask=True) | return new_clip | Returns a video clip that is a resized version of the clip.
Parameters
----------
new_size : tuple or float or function, optional
Can be either
- ``(width, height)`` in pixels or a float representing
- A scaling factor, like ``0.5``.
- A function of time returning one of these.
width : int, optional
Width of the new clip in pixels. The height is then computed so
that the width/height ratio is conserved.
height : int, optional
Height of the new clip in pixels. The width is then computed so
that the width/height ratio is conserved.
Examples
--------
>>> myClip.resize( (460,720) ) # New resolution: (460,720)
>>> myClip.resize(0.6) # width and height multiplied by 0.6
>>> myClip.resize(width=800) # height computed automatically.
>>> myClip.resize(lambda t : 1+0.02*t) # slow swelling of the clip | Returns a video clip that is a resized version of the clip. | 121 | 236 | def resize(clip, new_size=None, height=None, width=None, apply_to_mask=True):
"""Returns a video clip that is a resized version of the clip.
Parameters
----------
new_size : tuple or float or function, optional
Can be either
- ``(width, height)`` in pixels or a float representing
- A scaling factor, like ``0.5``.
- A function of time returning one of these.
width : int, optional
Width of the new clip in pixels. The height is then computed so
that the width/height ratio is conserved.
height : int, optional
Height of the new clip in pixels. The width is then computed so
that the width/height ratio is conserved.
Examples
--------
>>> myClip.resize( (460,720) ) # New resolution: (460,720)
>>> myClip.resize(0.6) # width and height multiplied by 0.6
>>> myClip.resize(width=800) # height computed automatically.
>>> myClip.resize(lambda t : 1+0.02*t) # slow swelling of the clip
"""
w, h = clip.size
if new_size is not None:
def translate_new_size(new_size_):
"""Returns a [w, h] pair from `new_size_`. If `new_size_` is a
scalar, then work out the correct pair using the clip's size.
Otherwise just return `new_size_`
"""
if isinstance(new_size_, numbers.Number):
return [new_size_ * w, new_size_ * h]
else:
return new_size_
if hasattr(new_size, "__call__"):
# The resizing is a function of time
def get_new_size(t):
return translate_new_size(new_size(t))
if clip.is_mask:
def filter(get_frame, t):
return (
resizer((255 * get_frame(t)).astype("uint8"), get_new_size(t))
/ 255.0
)
else:
def filter(get_frame, t):
return resizer(get_frame(t).astype("uint8"), get_new_size(t))
newclip = clip.transform(
filter, keep_duration=True, apply_to=(["mask"] if apply_to_mask else [])
)
if apply_to_mask and clip.mask is not None:
newclip.mask = resize(clip.mask, new_size, apply_to_mask=False)
return newclip
else:
new_size = translate_new_size(new_size)
elif height is not None:
if hasattr(height, "__call__"):
def func(t):
return 1.0 * int(height(t)) / h
return resize(clip, func)
else:
new_size = [w * height / h, height]
elif width is not None:
if hasattr(width, "__call__"):
def func(t):
return 1.0 * width(t) / w
return resize(clip, func)
else:
new_size = [width, h * width / w]
else:
raise ValueError("You must provide either 'new_size' or 'height' or 'width'")
# From here, the resizing is constant (not a function of time), size=newsize
if clip.is_mask:
def image_filter(pic):
return 1.0 * resizer((255 * pic).astype("uint8"), new_size) / 255.0
else:
def image_filter(pic):
return resizer(pic.astype("uint8"), new_size)
new_clip = clip.image_transform(image_filter)
if apply_to_mask and clip.mask is not None:
new_clip.mask = resize(clip.mask, new_size, apply_to_mask=False)
return new_clip | https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/fx/resize.py#L121-L236 | 46 | [
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
16,
17,
18,
19,
20,
21,
22,
23,
24,
25,
26,
27,
28,
29,
30,
31,
32,
33,
34,
35,
36,
37,
38,
39,
40,
41,
42,
43,
44,
45,
46,
47,
48,
49,
50,
51,
52,
53,
54,
55,
56,
57,
58,
59,
60,
61,
62,
63,
64,
65,
66,
67,
68,
69,
70,
71,
72,
73,
74,
75,
76,
77,
78,
79,
80,
81,
82,
83,
84,
85,
86,
87,
88,
89,
90,
91,
92,
93,
94,
95,
96,
97,
98,
99,
100,
101,
102,
103,
104,
105,
106,
107,
108,
109,
110,
111,
112,
113,
114,
115
] | 100 | [] | 0 | true | 78.095238 | 116 | 22 | 100 | 26 | def resize(clip, new_size=None, height=None, width=None, apply_to_mask=True):
w, h = clip.size
if new_size is not None:
def translate_new_size(new_size_):
if isinstance(new_size_, numbers.Number):
return [new_size_ * w, new_size_ * h]
else:
return new_size_
if hasattr(new_size, "__call__"):
# The resizing is a function of time
def get_new_size(t):
return translate_new_size(new_size(t))
if clip.is_mask:
def filter(get_frame, t):
return (
resizer((255 * get_frame(t)).astype("uint8"), get_new_size(t))
/ 255.0
)
else:
def filter(get_frame, t):
return resizer(get_frame(t).astype("uint8"), get_new_size(t))
newclip = clip.transform(
filter, keep_duration=True, apply_to=(["mask"] if apply_to_mask else [])
)
if apply_to_mask and clip.mask is not None:
newclip.mask = resize(clip.mask, new_size, apply_to_mask=False)
return newclip
else:
new_size = translate_new_size(new_size)
elif height is not None:
if hasattr(height, "__call__"):
def func(t):
return 1.0 * int(height(t)) / h
return resize(clip, func)
else:
new_size = [w * height / h, height]
elif width is not None:
if hasattr(width, "__call__"):
def func(t):
return 1.0 * width(t) / w
return resize(clip, func)
else:
new_size = [width, h * width / w]
else:
raise ValueError("You must provide either 'new_size' or 'height' or 'width'")
# From here, the resizing is constant (not a function of time), size=newsize
if clip.is_mask:
def image_filter(pic):
return 1.0 * resizer((255 * pic).astype("uint8"), new_size) / 255.0
else:
def image_filter(pic):
return resizer(pic.astype("uint8"), new_size)
new_clip = clip.image_transform(image_filter)
if apply_to_mask and clip.mask is not None:
new_clip.mask = resize(clip.mask, new_size, apply_to_mask=False)
return new_clip | 28,572 |
Zulko/moviepy | 858bb81fba7e09f1f562283ed6d1394db883b6c7 | moviepy/video/fx/blackwhite.py | blackwhite | (clip, RGB=None, preserve_luminosity=True) | return clip.image_transform(filter) | Desaturates the picture, makes it black and white.
Parameter RGB allows to set weights for the different color
channels.
If RBG is 'CRT_phosphor' a special set of values is used.
preserve_luminosity maintains the sum of RGB to 1. | Desaturates the picture, makes it black and white.
Parameter RGB allows to set weights for the different color
channels.
If RBG is 'CRT_phosphor' a special set of values is used.
preserve_luminosity maintains the sum of RGB to 1. | 4 | 23 | def blackwhite(clip, RGB=None, preserve_luminosity=True):
"""Desaturates the picture, makes it black and white.
Parameter RGB allows to set weights for the different color
channels.
If RBG is 'CRT_phosphor' a special set of values is used.
preserve_luminosity maintains the sum of RGB to 1.
"""
if RGB is None:
RGB = [1, 1, 1]
if RGB == "CRT_phosphor":
RGB = [0.2125, 0.7154, 0.0721]
R, G, B = 1.0 * np.array(RGB) / (sum(RGB) if preserve_luminosity else 1)
def filter(im):
im = R * im[:, :, 0] + G * im[:, :, 1] + B * im[:, :, 2]
return np.dstack(3 * [im]).astype("uint8")
return clip.image_transform(filter) | https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/fx/blackwhite.py#L4-L23 | 46 | [
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
16,
17,
18,
19
] | 100 | [] | 0 | true | 100 | 20 | 4 | 100 | 5 | def blackwhite(clip, RGB=None, preserve_luminosity=True):
if RGB is None:
RGB = [1, 1, 1]
if RGB == "CRT_phosphor":
RGB = [0.2125, 0.7154, 0.0721]
R, G, B = 1.0 * np.array(RGB) / (sum(RGB) if preserve_luminosity else 1)
def filter(im):
im = R * im[:, :, 0] + G * im[:, :, 1] + B * im[:, :, 2]
return np.dstack(3 * [im]).astype("uint8")
return clip.image_transform(filter) | 28,573 |
Zulko/moviepy | 858bb81fba7e09f1f562283ed6d1394db883b6c7 | moviepy/video/fx/mask_color.py | mask_color | (clip, color=None, threshold=0, stiffness=1) | return new_clip | Returns a new clip with a mask for transparency where the original
clip is of the given color.
You can also have a "progressive" mask by specifying a non-null distance
threshold ``threshold``. In this case, if the distance between a pixel and
the given color is d, the transparency will be
d**stiffness / (threshold**stiffness + d**stiffness)
which is 1 when d>>threshold and 0 for d<<threshold, the stiffness of the
effect being parametrized by ``stiffness`` | Returns a new clip with a mask for transparency where the original
clip is of the given color. | 4 | 34 | def mask_color(clip, color=None, threshold=0, stiffness=1):
"""Returns a new clip with a mask for transparency where the original
clip is of the given color.
You can also have a "progressive" mask by specifying a non-null distance
threshold ``threshold``. In this case, if the distance between a pixel and
the given color is d, the transparency will be
d**stiffness / (threshold**stiffness + d**stiffness)
which is 1 when d>>threshold and 0 for d<<threshold, the stiffness of the
effect being parametrized by ``stiffness``
"""
if color is None:
color = [0, 0, 0]
color = np.array(color)
def hill(x):
if threshold:
return x**stiffness / (threshold**stiffness + x**stiffness)
else:
return 1.0 * (x != 0)
def flim(im):
return hill(np.sqrt(((im - color) ** 2).sum(axis=2)))
mask = clip.image_transform(flim)
mask.is_mask = True
new_clip = clip.with_mask(mask)
return new_clip | https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/fx/mask_color.py#L4-L34 | 46 | [
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
15,
16,
17,
18,
19,
21,
22,
23,
24,
25,
26,
27,
28,
29,
30
] | 93.548387 | [
14,
20
] | 6.451613 | false | 86.666667 | 31 | 5 | 93.548387 | 11 | def mask_color(clip, color=None, threshold=0, stiffness=1):
if color is None:
color = [0, 0, 0]
color = np.array(color)
def hill(x):
if threshold:
return x**stiffness / (threshold**stiffness + x**stiffness)
else:
return 1.0 * (x != 0)
def flim(im):
return hill(np.sqrt(((im - color) ** 2).sum(axis=2)))
mask = clip.image_transform(flim)
mask.is_mask = True
new_clip = clip.with_mask(mask)
return new_clip | 28,574 |
Zulko/moviepy | 858bb81fba7e09f1f562283ed6d1394db883b6c7 | moviepy/video/fx/freeze.py | freeze | (clip, t=0, freeze_duration=None, total_duration=None, padding_end=0) | return concatenate_videoclips(before + freeze + after) | Momentarily freeze the clip at time t.
Set `t='end'` to freeze the clip at the end (actually it will freeze on the
frame at time clip.duration - padding_end seconds - 1 / clip_fps).
With ``duration`` you can specify the duration of the freeze.
With ``total_duration`` you can specify the total duration of
the clip and the freeze (i.e. the duration of the freeze is
automatically computed). One of them must be provided. | Momentarily freeze the clip at time t. | 6 | 29 | def freeze(clip, t=0, freeze_duration=None, total_duration=None, padding_end=0):
"""Momentarily freeze the clip at time t.
Set `t='end'` to freeze the clip at the end (actually it will freeze on the
frame at time clip.duration - padding_end seconds - 1 / clip_fps).
With ``duration`` you can specify the duration of the freeze.
With ``total_duration`` you can specify the total duration of
the clip and the freeze (i.e. the duration of the freeze is
automatically computed). One of them must be provided.
"""
if t == "end":
t = clip.duration - padding_end - 1 / clip.fps
if freeze_duration is None:
if total_duration is None:
raise ValueError(
"You must provide either 'freeze_duration' or 'total_duration'"
)
freeze_duration = total_duration - clip.duration
before = [clip.subclip(0, t)] if (t != 0) else []
freeze = [clip.to_ImageClip(t).with_duration(freeze_duration)]
after = [clip.subclip(t)] if (t != clip.duration) else []
return concatenate_videoclips(before + freeze + after) | https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/fx/freeze.py#L6-L29 | 46 | [
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
16,
17,
18,
19,
20,
21,
22,
23
] | 100 | [] | 0 | true | 100 | 24 | 4 | 100 | 8 | def freeze(clip, t=0, freeze_duration=None, total_duration=None, padding_end=0):
if t == "end":
t = clip.duration - padding_end - 1 / clip.fps
if freeze_duration is None:
if total_duration is None:
raise ValueError(
"You must provide either 'freeze_duration' or 'total_duration'"
)
freeze_duration = total_duration - clip.duration
before = [clip.subclip(0, t)] if (t != 0) else []
freeze = [clip.to_ImageClip(t).with_duration(freeze_duration)]
after = [clip.subclip(t)] if (t != clip.duration) else []
return concatenate_videoclips(before + freeze + after) | 28,575 |
Zulko/moviepy | 858bb81fba7e09f1f562283ed6d1394db883b6c7 | moviepy/video/fx/headblur.py | headblur | (clip, fx, fy, radius, intensity=None) | return clip.transform(filter) | Returns a filter that will blur a moving part (a head ?) of the frames.
The position of the blur at time t is defined by (fx(t), fy(t)), the radius
of the blurring by ``radius`` and the intensity of the blurring by ``intensity``.
Requires OpenCV for the circling and the blurring. Automatically deals with the
case where part of the image goes offscreen. | Returns a filter that will blur a moving part (a head ?) of the frames. | 16 | 46 | def headblur(clip, fx, fy, radius, intensity=None):
"""Returns a filter that will blur a moving part (a head ?) of the frames.
The position of the blur at time t is defined by (fx(t), fy(t)), the radius
of the blurring by ``radius`` and the intensity of the blurring by ``intensity``.
Requires OpenCV for the circling and the blurring. Automatically deals with the
case where part of the image goes offscreen.
"""
if intensity is None:
intensity = int(2 * radius / 3)
def filter(gf, t):
im = gf(t).copy()
h, w, d = im.shape
x, y = int(fx(t)), int(fy(t))
x1, x2 = max(0, x - radius), min(x + radius, w)
y1, y2 = max(0, y - radius), min(y + radius, h)
region_size = y2 - y1, x2 - x1
mask = np.zeros(region_size).astype("uint8")
cv2.circle(mask, (radius, radius), radius, 255, -1, lineType=cv2.CV_AA)
mask = np.dstack(3 * [(1.0 / 255) * mask])
orig = im[y1:y2, x1:x2]
blurred = cv2.blur(orig, (intensity, intensity))
im[y1:y2, x1:x2] = mask * blurred + (1 - mask) * orig
return im
return clip.transform(filter) | https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/fx/headblur.py#L16-L46 | 46 | [
0,
1,
2,
3,
4,
5,
6,
7,
8
] | 29.032258 | [
9,
10,
12,
13,
14,
15,
16,
17,
18,
20,
21,
23,
25,
26,
27,
28,
30
] | 54.83871 | false | 32.258065 | 31 | 3 | 45.16129 | 7 | def headblur(clip, fx, fy, radius, intensity=None):
if intensity is None:
intensity = int(2 * radius / 3)
def filter(gf, t):
im = gf(t).copy()
h, w, d = im.shape
x, y = int(fx(t)), int(fy(t))
x1, x2 = max(0, x - radius), min(x + radius, w)
y1, y2 = max(0, y - radius), min(y + radius, h)
region_size = y2 - y1, x2 - x1
mask = np.zeros(region_size).astype("uint8")
cv2.circle(mask, (radius, radius), radius, 255, -1, lineType=cv2.CV_AA)
mask = np.dstack(3 * [(1.0 / 255) * mask])
orig = im[y1:y2, x1:x2]
blurred = cv2.blur(orig, (intensity, intensity))
im[y1:y2, x1:x2] = mask * blurred + (1 - mask) * orig
return im
return clip.transform(filter) | 28,576 |
Zulko/moviepy | 858bb81fba7e09f1f562283ed6d1394db883b6c7 | moviepy/video/fx/fadeout.py | fadeout | (clip, duration, final_color=None) | return clip.transform(filter) | Makes the clip progressively fade to some color (black by default),
over ``duration`` seconds at the end of the clip. Can be used for masks too,
where the final color must be a number between 0 and 1.
For cross-fading (progressive appearance or disappearance of a clip over another
clip, see ``transfx.crossfadeout`` | Makes the clip progressively fade to some color (black by default),
over ``duration`` seconds at the end of the clip. Can be used for masks too,
where the final color must be a number between 0 and 1. | 7 | 27 | def fadeout(clip, duration, final_color=None):
"""Makes the clip progressively fade to some color (black by default),
over ``duration`` seconds at the end of the clip. Can be used for masks too,
where the final color must be a number between 0 and 1.
For cross-fading (progressive appearance or disappearance of a clip over another
clip, see ``transfx.crossfadeout``
"""
if final_color is None:
final_color = 0 if clip.is_mask else [0, 0, 0]
final_color = np.array(final_color)
def filter(get_frame, t):
if (clip.duration - t) >= duration:
return get_frame(t)
else:
fading = 1.0 * (clip.duration - t) / duration
return fading * get_frame(t) + (1 - fading) * final_color
return clip.transform(filter) | https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/fx/fadeout.py#L7-L27 | 46 | [
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
16,
17,
18,
19,
20
] | 100 | [] | 0 | true | 100 | 21 | 4 | 100 | 6 | def fadeout(clip, duration, final_color=None):
if final_color is None:
final_color = 0 if clip.is_mask else [0, 0, 0]
final_color = np.array(final_color)
def filter(get_frame, t):
if (clip.duration - t) >= duration:
return get_frame(t)
else:
fading = 1.0 * (clip.duration - t) / duration
return fading * get_frame(t) + (1 - fading) * final_color
return clip.transform(filter) | 28,577 |
Zulko/moviepy | 858bb81fba7e09f1f562283ed6d1394db883b6c7 | moviepy/video/fx/mirror_x.py | mirror_x | (clip, apply_to="mask") | return clip.image_transform(lambda img: img[:, ::-1], apply_to=apply_to) | Flips the clip horizontally (and its mask too, by default). | Flips the clip horizontally (and its mask too, by default). | 1 | 3 | def mirror_x(clip, apply_to="mask"):
"""Flips the clip horizontally (and its mask too, by default)."""
return clip.image_transform(lambda img: img[:, ::-1], apply_to=apply_to) | https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/fx/mirror_x.py#L1-L3 | 46 | [
0,
1,
2
] | 100 | [] | 0 | true | 100 | 3 | 1 | 100 | 1 | def mirror_x(clip, apply_to="mask"):
return clip.image_transform(lambda img: img[:, ::-1], apply_to=apply_to) | 28,578 |
Zulko/moviepy | 858bb81fba7e09f1f562283ed6d1394db883b6c7 | moviepy/video/fx/mirror_y.py | mirror_y | (clip, apply_to="mask") | return clip.image_transform(lambda img: img[::-1], apply_to=apply_to) | Flips the clip vertically (and its mask too, by default). | Flips the clip vertically (and its mask too, by default). | 1 | 3 | def mirror_y(clip, apply_to="mask"):
"""Flips the clip vertically (and its mask too, by default)."""
return clip.image_transform(lambda img: img[::-1], apply_to=apply_to) | https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/fx/mirror_y.py#L1-L3 | 46 | [
0,
1,
2
] | 100 | [] | 0 | true | 100 | 3 | 1 | 100 | 1 | def mirror_y(clip, apply_to="mask"):
return clip.image_transform(lambda img: img[::-1], apply_to=apply_to) | 28,579 |
Zulko/moviepy | 858bb81fba7e09f1f562283ed6d1394db883b6c7 | moviepy/video/fx/even_size.py | even_size | (clip) | return clip.image_transform(image_filter) | Crops the clip to make dimensions even. | Crops the clip to make dimensions even. | 5 | 28 | def even_size(clip):
"""Crops the clip to make dimensions even."""
w, h = clip.size
w_even = w % 2 == 0
h_even = h % 2 == 0
if w_even and h_even:
return clip
if not w_even and not h_even:
def image_filter(a):
return a[:-1, :-1, :]
elif h_even:
def image_filter(a):
return a[:, :-1, :]
else:
def image_filter(a):
return a[:-1, :, :]
return clip.image_transform(image_filter) | https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/fx/even_size.py#L5-L28 | 46 | [
0,
1,
2,
3,
4,
5,
7,
8,
9,
10,
11,
12,
13,
14,
15,
16,
17,
18,
19,
20,
21,
22,
23
] | 95.833333 | [
6
] | 4.166667 | false | 94.117647 | 24 | 9 | 95.833333 | 1 | def even_size(clip):
w, h = clip.size
w_even = w % 2 == 0
h_even = h % 2 == 0
if w_even and h_even:
return clip
if not w_even and not h_even:
def image_filter(a):
return a[:-1, :-1, :]
elif h_even:
def image_filter(a):
return a[:, :-1, :]
else:
def image_filter(a):
return a[:-1, :, :]
return clip.image_transform(image_filter) | 28,580 |
Zulko/moviepy | 858bb81fba7e09f1f562283ed6d1394db883b6c7 | moviepy/video/fx/freeze_region.py | freeze_region | (clip, t=0, region=None, outside_region=None, mask=None) | Freezes one region of the clip while the rest remains animated.
You can choose one of three methods by providing either `region`,
`outside_region`, or `mask`.
Parameters
----------
t
Time at which to freeze the freezed region.
region
A tuple (x1, y1, x2, y2) defining the region of the screen (in pixels)
which will be freezed. You can provide outside_region or mask instead.
outside_region
A tuple (x1, y1, x2, y2) defining the region of the screen (in pixels)
which will be the only non-freezed region.
mask
If not None, will overlay a freezed version of the clip on the current clip,
with the provided mask. In other words, the "visible" pixels in the mask
indicate the freezed region in the final picture. | Freezes one region of the clip while the rest remains animated. | 5 | 51 | def freeze_region(clip, t=0, region=None, outside_region=None, mask=None):
"""Freezes one region of the clip while the rest remains animated.
You can choose one of three methods by providing either `region`,
`outside_region`, or `mask`.
Parameters
----------
t
Time at which to freeze the freezed region.
region
A tuple (x1, y1, x2, y2) defining the region of the screen (in pixels)
which will be freezed. You can provide outside_region or mask instead.
outside_region
A tuple (x1, y1, x2, y2) defining the region of the screen (in pixels)
which will be the only non-freezed region.
mask
If not None, will overlay a freezed version of the clip on the current clip,
with the provided mask. In other words, the "visible" pixels in the mask
indicate the freezed region in the final picture.
"""
if region is not None:
x1, y1, x2, y2 = region
freeze = (
clip.fx(crop, *region)
.to_ImageClip(t=t)
.with_duration(clip.duration)
.with_position((x1, y1))
)
return CompositeVideoClip([clip, freeze])
elif outside_region is not None:
x1, y1, x2, y2 = outside_region
animated_region = clip.fx(crop, *outside_region).with_position((x1, y1))
freeze = clip.to_ImageClip(t=t).with_duration(clip.duration)
return CompositeVideoClip([freeze, animated_region])
elif mask is not None:
freeze = clip.to_ImageClip(t=t).with_duration(clip.duration).with_mask(mask)
return CompositeVideoClip([clip, freeze]) | https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/fx/freeze_region.py#L5-L51 | 46 | [
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
16,
17,
18,
19,
20,
21,
22,
23,
24,
25,
26,
27,
28,
29,
30,
31,
32,
33,
34,
35,
36,
37,
38,
39,
40,
41,
42,
43
] | 93.617021 | [
44,
45,
46
] | 6.382979 | false | 80 | 47 | 4 | 93.617021 | 23 | def freeze_region(clip, t=0, region=None, outside_region=None, mask=None):
if region is not None:
x1, y1, x2, y2 = region
freeze = (
clip.fx(crop, *region)
.to_ImageClip(t=t)
.with_duration(clip.duration)
.with_position((x1, y1))
)
return CompositeVideoClip([clip, freeze])
elif outside_region is not None:
x1, y1, x2, y2 = outside_region
animated_region = clip.fx(crop, *outside_region).with_position((x1, y1))
freeze = clip.to_ImageClip(t=t).with_duration(clip.duration)
return CompositeVideoClip([freeze, animated_region])
elif mask is not None:
freeze = clip.to_ImageClip(t=t).with_duration(clip.duration).with_mask(mask)
return CompositeVideoClip([clip, freeze]) | 28,581 |
|
Zulko/moviepy | 858bb81fba7e09f1f562283ed6d1394db883b6c7 | moviepy/video/fx/fadein.py | fadein | (clip, duration, initial_color=None) | return clip.transform(filter) | Makes the clip progressively appear from some color (black by default),
over ``duration`` seconds at the beginning of the clip. Can be used for
masks too, where the initial color must be a number between 0 and 1.
For cross-fading (progressive appearance or disappearance of a clip
over another clip, see ``transfx.crossfadein`` | Makes the clip progressively appear from some color (black by default),
over ``duration`` seconds at the beginning of the clip. Can be used for
masks too, where the initial color must be a number between 0 and 1. | 4 | 24 | def fadein(clip, duration, initial_color=None):
"""Makes the clip progressively appear from some color (black by default),
over ``duration`` seconds at the beginning of the clip. Can be used for
masks too, where the initial color must be a number between 0 and 1.
For cross-fading (progressive appearance or disappearance of a clip
over another clip, see ``transfx.crossfadein``
"""
if initial_color is None:
initial_color = 0 if clip.is_mask else [0, 0, 0]
initial_color = np.array(initial_color)
def filter(get_frame, t):
if t >= duration:
return get_frame(t)
else:
fading = 1.0 * t / duration
return fading * get_frame(t) + (1 - fading) * initial_color
return clip.transform(filter) | https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/fx/fadein.py#L4-L24 | 46 | [
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
16,
17,
18,
19,
20
] | 100 | [] | 0 | true | 100 | 21 | 4 | 100 | 6 | def fadein(clip, duration, initial_color=None):
if initial_color is None:
initial_color = 0 if clip.is_mask else [0, 0, 0]
initial_color = np.array(initial_color)
def filter(get_frame, t):
if t >= duration:
return get_frame(t)
else:
fading = 1.0 * t / duration
return fading * get_frame(t) + (1 - fading) * initial_color
return clip.transform(filter) | 28,582 |
Zulko/moviepy | 858bb81fba7e09f1f562283ed6d1394db883b6c7 | moviepy/video/fx/gamma_corr.py | gamma_corr | (clip, gamma) | return clip.image_transform(filter) | Gamma-correction of a video clip. | Gamma-correction of a video clip. | 1 | 8 | def gamma_corr(clip, gamma):
"""Gamma-correction of a video clip."""
def filter(im):
corrected = 255 * (1.0 * im / 255) ** gamma
return corrected.astype("uint8")
return clip.image_transform(filter) | https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/fx/gamma_corr.py#L1-L8 | 46 | [
0,
1,
2
] | 37.5 | [
3,
4,
5,
7
] | 50 | false | 20 | 8 | 2 | 50 | 1 | def gamma_corr(clip, gamma):
def filter(im):
corrected = 255 * (1.0 * im / 255) ** gamma
return corrected.astype("uint8")
return clip.image_transform(filter) | 28,583 |
Zulko/moviepy | 858bb81fba7e09f1f562283ed6d1394db883b6c7 | moviepy/video/fx/multiply_color.py | multiply_color | (clip, factor) | return clip.image_transform(
lambda frame: np.minimum(255, (factor * frame)).astype("uint8")
) | Multiplies the clip's colors by the given factor, can be used
to decrease or increase the clip's brightness (is that the
right word ?) | Multiplies the clip's colors by the given factor, can be used
to decrease or increase the clip's brightness (is that the
right word ?) | 4 | 12 | def multiply_color(clip, factor):
"""
Multiplies the clip's colors by the given factor, can be used
to decrease or increase the clip's brightness (is that the
right word ?)
"""
return clip.image_transform(
lambda frame: np.minimum(255, (factor * frame)).astype("uint8")
) | https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/fx/multiply_color.py#L4-L12 | 46 | [
0,
1,
2,
3,
4,
5,
6,
7,
8
] | 100 | [] | 0 | true | 100 | 9 | 1 | 100 | 3 | def multiply_color(clip, factor):
return clip.image_transform(
lambda frame: np.minimum(255, (factor * frame)).astype("uint8")
) | 28,584 |
Zulko/moviepy | 858bb81fba7e09f1f562283ed6d1394db883b6c7 | moviepy/video/fx/time_symmetrize.py | time_symmetrize | (clip) | return concatenate_videoclips([clip, clip.fx(time_mirror)]) | Returns a clip that plays the current clip once forwards and
then once backwards. This is very practival to make video that
loop well, e.g. to create animated GIFs.
This effect is automatically applied to the clip's mask and audio
if they exist. | Returns a clip that plays the current clip once forwards and
then once backwards. This is very practival to make video that
loop well, e.g. to create animated GIFs.
This effect is automatically applied to the clip's mask and audio
if they exist. | 8 | 16 | def time_symmetrize(clip):
"""
Returns a clip that plays the current clip once forwards and
then once backwards. This is very practival to make video that
loop well, e.g. to create animated GIFs.
This effect is automatically applied to the clip's mask and audio
if they exist.
"""
return concatenate_videoclips([clip, clip.fx(time_mirror)]) | https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/fx/time_symmetrize.py#L8-L16 | 46 | [
0,
1,
2,
3,
4,
5,
6,
7,
8
] | 100 | [] | 0 | true | 100 | 9 | 1 | 100 | 5 | def time_symmetrize(clip):
return concatenate_videoclips([clip, clip.fx(time_mirror)]) | 28,585 |
Zulko/moviepy | 858bb81fba7e09f1f562283ed6d1394db883b6c7 | moviepy/video/compositing/concatenate.py | concatenate_videoclips | (
clips, method="chain", transition=None, bg_color=None, is_mask=False, padding=0
) | return result | Concatenates several video clips.
Returns a video clip made by clip by concatenating several video clips.
(Concatenated means that they will be played one after another).
There are two methods:
- method="chain": will produce a clip that simply outputs
the frames of the successive clips, without any correction if they are
not of the same size of anything. If none of the clips have masks the
resulting clip has no mask, else the mask is a concatenation of masks
(using completely opaque for clips that don't have masks, obviously).
If you have clips of different size and you want to write directly the
result of the concatenation to a file, use the method "compose" instead.
- method="compose", if the clips do not have the same resolution, the final
resolution will be such that no clip has to be resized.
As a consequence the final clip has the height of the highest clip and the
width of the widest clip of the list. All the clips with smaller dimensions
will appear centered. The border will be transparent if mask=True, else it
will be of the color specified by ``bg_color``.
The clip with the highest FPS will be the FPS of the result clip.
Parameters
----------
clips
A list of video clips which must all have their ``duration``
attributes set.
method
"chain" or "compose": see above.
transition
A clip that will be played between each two clips of the list.
bg_color
Only for method='compose'. Color of the background.
Set to None for a transparent clip
padding
Only for method='compose'. Duration during two consecutive clips.
Note that for negative padding, a clip will partly play at the same
time as the clip it follows (negative padding is cool for clips who fade
in on one another). A non-null padding automatically sets the method to
`compose`. | Concatenates several video clips. | 12 | 122 | def concatenate_videoclips(
clips, method="chain", transition=None, bg_color=None, is_mask=False, padding=0
):
"""Concatenates several video clips.
Returns a video clip made by clip by concatenating several video clips.
(Concatenated means that they will be played one after another).
There are two methods:
- method="chain": will produce a clip that simply outputs
the frames of the successive clips, without any correction if they are
not of the same size of anything. If none of the clips have masks the
resulting clip has no mask, else the mask is a concatenation of masks
(using completely opaque for clips that don't have masks, obviously).
If you have clips of different size and you want to write directly the
result of the concatenation to a file, use the method "compose" instead.
- method="compose", if the clips do not have the same resolution, the final
resolution will be such that no clip has to be resized.
As a consequence the final clip has the height of the highest clip and the
width of the widest clip of the list. All the clips with smaller dimensions
will appear centered. The border will be transparent if mask=True, else it
will be of the color specified by ``bg_color``.
The clip with the highest FPS will be the FPS of the result clip.
Parameters
----------
clips
A list of video clips which must all have their ``duration``
attributes set.
method
"chain" or "compose": see above.
transition
A clip that will be played between each two clips of the list.
bg_color
Only for method='compose'. Color of the background.
Set to None for a transparent clip
padding
Only for method='compose'. Duration during two consecutive clips.
Note that for negative padding, a clip will partly play at the same
time as the clip it follows (negative padding is cool for clips who fade
in on one another). A non-null padding automatically sets the method to
`compose`.
"""
if transition is not None:
clip_transition_pairs = [[v, transition] for v in clips[:-1]]
clips = reduce(lambda x, y: x + y, clip_transition_pairs) + [clips[-1]]
transition = None
timings = np.cumsum([0] + [clip.duration for clip in clips])
sizes = [clip.size for clip in clips]
w = max(size[0] for size in sizes)
h = max(size[1] for size in sizes)
timings = np.maximum(0, timings + padding * np.arange(len(timings)))
timings[-1] -= padding # Last element is the duration of the whole
if method == "chain":
def make_frame(t):
i = max([i for i, e in enumerate(timings) if e <= t])
return clips[i].get_frame(t - timings[i])
def get_mask(clip):
mask = clip.mask or ColorClip([1, 1], color=1, is_mask=True)
if mask.duration is None:
mask.duration = clip.duration
return mask
result = VideoClip(is_mask=is_mask, make_frame=make_frame)
if any([clip.mask is not None for clip in clips]):
masks = [get_mask(clip) for clip in clips]
result.mask = concatenate_videoclips(masks, method="chain", is_mask=True)
result.clips = clips
elif method == "compose":
result = CompositeVideoClip(
[
clip.with_start(t).with_position("center")
for (clip, t) in zip(clips, timings)
],
size=(w, h),
bg_color=bg_color,
is_mask=is_mask,
)
else:
raise Exception(
"Moviepy Error: The 'method' argument of "
"concatenate_videoclips must be 'chain' or 'compose'"
)
result.timings = timings
result.start_times = timings[:-1]
result.start, result.duration, result.end = 0, timings[-1], timings[-1]
audio_t = [
(clip.audio, t) for clip, t in zip(clips, timings) if clip.audio is not None
]
if audio_t:
result.audio = CompositeAudioClip([a.with_start(t) for a, t in audio_t])
fpss = [clip.fps for clip in clips if getattr(clip, "fps", None) is not None]
result.fps = max(fpss) if fpss else None
return result | https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/compositing/concatenate.py#L12-L122 | 46 | [
0,
48,
49,
53,
54,
55,
56,
57,
58,
59,
60,
61,
62,
63,
64,
65,
66,
67,
68,
69,
70,
71,
72,
73,
74,
75,
76,
77,
78,
79,
80,
81,
82,
83,
84,
85,
86,
87,
88,
89,
90,
91,
92,
93,
94,
95,
96,
97,
98,
99,
100,
101,
102,
103,
104,
105,
106,
107,
108,
109,
110
] | 54.954955 | [
50,
51,
52
] | 2.702703 | false | 92.857143 | 111 | 20 | 97.297297 | 44 | def concatenate_videoclips(
clips, method="chain", transition=None, bg_color=None, is_mask=False, padding=0
):
if transition is not None:
clip_transition_pairs = [[v, transition] for v in clips[:-1]]
clips = reduce(lambda x, y: x + y, clip_transition_pairs) + [clips[-1]]
transition = None
timings = np.cumsum([0] + [clip.duration for clip in clips])
sizes = [clip.size for clip in clips]
w = max(size[0] for size in sizes)
h = max(size[1] for size in sizes)
timings = np.maximum(0, timings + padding * np.arange(len(timings)))
timings[-1] -= padding # Last element is the duration of the whole
if method == "chain":
def make_frame(t):
i = max([i for i, e in enumerate(timings) if e <= t])
return clips[i].get_frame(t - timings[i])
def get_mask(clip):
mask = clip.mask or ColorClip([1, 1], color=1, is_mask=True)
if mask.duration is None:
mask.duration = clip.duration
return mask
result = VideoClip(is_mask=is_mask, make_frame=make_frame)
if any([clip.mask is not None for clip in clips]):
masks = [get_mask(clip) for clip in clips]
result.mask = concatenate_videoclips(masks, method="chain", is_mask=True)
result.clips = clips
elif method == "compose":
result = CompositeVideoClip(
[
clip.with_start(t).with_position("center")
for (clip, t) in zip(clips, timings)
],
size=(w, h),
bg_color=bg_color,
is_mask=is_mask,
)
else:
raise Exception(
"Moviepy Error: The 'method' argument of "
"concatenate_videoclips must be 'chain' or 'compose'"
)
result.timings = timings
result.start_times = timings[:-1]
result.start, result.duration, result.end = 0, timings[-1], timings[-1]
audio_t = [
(clip.audio, t) for clip, t in zip(clips, timings) if clip.audio is not None
]
if audio_t:
result.audio = CompositeAudioClip([a.with_start(t) for a, t in audio_t])
fpss = [clip.fps for clip in clips if getattr(clip, "fps", None) is not None]
result.fps = max(fpss) if fpss else None
return result | 28,586 |
Zulko/moviepy | 858bb81fba7e09f1f562283ed6d1394db883b6c7 | moviepy/video/compositing/CompositeVideoClip.py | clips_array | (array, rows_widths=None, cols_heights=None, bg_color=None) | return CompositeVideoClip(array.flatten(), size=(xs[-1], ys[-1]), bg_color=bg_color) | Given a matrix whose rows are clips, creates a CompositeVideoClip where
all clips are placed side by side horizontally for each clip in each row
and one row on top of the other for each row. So given next matrix of clips
with same size:
```python
clips_array([[clip1, clip2, clip3], [clip4, clip5, clip6]])
```
the result will be a CompositeVideoClip with a layout displayed like:
```
┏━━━━━━━┳━━━━━━━┳━━━━━━━┓
┃ ┃ ┃ ┃
┃ clip1 ┃ clip2 ┃ clip3 ┃
┃ ┃ ┃ ┃
┣━━━━━━━╋━━━━━━━╋━━━━━━━┫
┃ ┃ ┃ ┃
┃ clip4 ┃ clip5 ┃ clip6 ┃
┃ ┃ ┃ ┃
┗━━━━━━━┻━━━━━━━┻━━━━━━━┛
```
If some clips doesn't fulfill the space required by the rows or columns
in which are placed, that space will be filled by the color defined in
``bg_color``.
array
Matrix of clips included in the returned composited video clip.
rows_widths
Widths of the different rows in pixels. If ``None``, is set automatically.
cols_heights
Heights of the different columns in pixels. If ``None``, is set automatically.
bg_color
Fill color for the masked and unfilled regions. Set to ``None`` for these
regions to be transparent (processing will be slower). | Given a matrix whose rows are clips, creates a CompositeVideoClip where
all clips are placed side by side horizontally for each clip in each row
and one row on top of the other for each row. So given next matrix of clips
with same size: | 151 | 217 | def clips_array(array, rows_widths=None, cols_heights=None, bg_color=None):
"""Given a matrix whose rows are clips, creates a CompositeVideoClip where
all clips are placed side by side horizontally for each clip in each row
and one row on top of the other for each row. So given next matrix of clips
with same size:
```python
clips_array([[clip1, clip2, clip3], [clip4, clip5, clip6]])
```
the result will be a CompositeVideoClip with a layout displayed like:
```
┏━━━━━━━┳━━━━━━━┳━━━━━━━┓
┃ ┃ ┃ ┃
┃ clip1 ┃ clip2 ┃ clip3 ┃
┃ ┃ ┃ ┃
┣━━━━━━━╋━━━━━━━╋━━━━━━━┫
┃ ┃ ┃ ┃
┃ clip4 ┃ clip5 ┃ clip6 ┃
┃ ┃ ┃ ┃
┗━━━━━━━┻━━━━━━━┻━━━━━━━┛
```
If some clips doesn't fulfill the space required by the rows or columns
in which are placed, that space will be filled by the color defined in
``bg_color``.
array
Matrix of clips included in the returned composited video clip.
rows_widths
Widths of the different rows in pixels. If ``None``, is set automatically.
cols_heights
Heights of the different columns in pixels. If ``None``, is set automatically.
bg_color
Fill color for the masked and unfilled regions. Set to ``None`` for these
regions to be transparent (processing will be slower).
"""
array = np.array(array)
sizes_array = np.array([[clip.size for clip in line] for line in array])
# find row width and col_widths automatically if not provided
if rows_widths is None:
rows_widths = sizes_array[:, :, 1].max(axis=1)
if cols_heights is None:
cols_heights = sizes_array[:, :, 0].max(axis=0)
# compute start positions of X for rows and Y for columns
xs = np.cumsum([0] + list(cols_heights))
ys = np.cumsum([0] + list(rows_widths))
for j, (x, ch) in enumerate(zip(xs[:-1], cols_heights)):
for i, (y, rw) in enumerate(zip(ys[:-1], rows_widths)):
clip = array[i, j]
w, h = clip.size
# if clip not fulfill row width or column height
if (w < ch) or (h < rw):
clip = CompositeVideoClip(
[clip.with_position("center")], size=(ch, rw), bg_color=bg_color
).with_duration(clip.duration)
array[i, j] = clip.with_position((x, y))
return CompositeVideoClip(array.flatten(), size=(xs[-1], ys[-1]), bg_color=bg_color) | https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/compositing/CompositeVideoClip.py#L151-L217 | 46 | [
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
16,
17,
18,
19,
20,
21,
22,
23,
24,
25,
26,
27,
28,
29,
30,
31,
32,
33,
34,
35,
36,
37,
38,
39,
40,
41,
42,
43,
44,
45,
46,
47,
48,
49,
50,
51,
52,
53,
54,
55,
56,
57,
58,
59,
63,
64,
65,
66
] | 95.522388 | [
60
] | 1.492537 | false | 92 | 67 | 9 | 98.507463 | 39 | def clips_array(array, rows_widths=None, cols_heights=None, bg_color=None):
array = np.array(array)
sizes_array = np.array([[clip.size for clip in line] for line in array])
# find row width and col_widths automatically if not provided
if rows_widths is None:
rows_widths = sizes_array[:, :, 1].max(axis=1)
if cols_heights is None:
cols_heights = sizes_array[:, :, 0].max(axis=0)
# compute start positions of X for rows and Y for columns
xs = np.cumsum([0] + list(cols_heights))
ys = np.cumsum([0] + list(rows_widths))
for j, (x, ch) in enumerate(zip(xs[:-1], cols_heights)):
for i, (y, rw) in enumerate(zip(ys[:-1], rows_widths)):
clip = array[i, j]
w, h = clip.size
# if clip not fulfill row width or column height
if (w < ch) or (h < rw):
clip = CompositeVideoClip(
[clip.with_position("center")], size=(ch, rw), bg_color=bg_color
).with_duration(clip.duration)
array[i, j] = clip.with_position((x, y))
return CompositeVideoClip(array.flatten(), size=(xs[-1], ys[-1]), bg_color=bg_color) | 28,587 |
Zulko/moviepy | 858bb81fba7e09f1f562283ed6d1394db883b6c7 | moviepy/video/compositing/CompositeVideoClip.py | CompositeVideoClip.__init__ | (
self, clips, size=None, bg_color=None, use_bgclip=False, is_mask=False
) | 54 | 116 | def __init__(
self, clips, size=None, bg_color=None, use_bgclip=False, is_mask=False
):
if size is None:
size = clips[0].size
if use_bgclip and (clips[0].mask is None):
transparent = False
else:
transparent = bg_color is None
if bg_color is None:
bg_color = 0.0 if is_mask else (0, 0, 0)
fpss = [clip.fps for clip in clips if getattr(clip, "fps", None)]
self.fps = max(fpss) if fpss else None
VideoClip.__init__(self)
self.size = size
self.is_mask = is_mask
self.clips = clips
self.bg_color = bg_color
if use_bgclip:
self.bg = clips[0]
self.clips = clips[1:]
self.created_bg = False
else:
self.clips = clips
self.bg = ColorClip(size, color=self.bg_color, is_mask=is_mask)
self.created_bg = True
# order self.clips by layer
self.clips = sorted(self.clips, key=lambda clip: clip.layer)
# compute duration
ends = [clip.end for clip in self.clips]
if None not in ends:
duration = max(ends)
self.duration = duration
self.end = duration
# compute audio
audioclips = [v.audio for v in self.clips if v.audio is not None]
if audioclips:
self.audio = CompositeAudioClip(audioclips)
# compute mask if necessary
if transparent:
maskclips = [
(clip.mask if (clip.mask is not None) else clip.add_mask().mask)
.with_position(clip.pos)
.with_end(clip.end)
.with_start(clip.start, change_end=False)
.with_layer(clip.layer)
for clip in self.clips
]
self.mask = CompositeVideoClip(
maskclips, self.size, is_mask=True, bg_color=0.0
) | https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/compositing/CompositeVideoClip.py#L54-L116 | 46 | [
0,
3,
4,
5,
6,
7,
8,
10,
11,
12,
13,
14,
15,
16,
17,
18,
19,
20,
21,
22,
23,
24,
25,
26,
27,
28,
30,
31,
32,
33,
34,
35,
36,
37,
38,
39,
40,
41,
42,
43,
44,
45,
46,
47,
48,
49,
50,
51,
59,
60
] | 79.365079 | [] | 0 | false | 92 | 63 | 13 | 100 | 0 | def __init__(
self, clips, size=None, bg_color=None, use_bgclip=False, is_mask=False
):
if size is None:
size = clips[0].size
if use_bgclip and (clips[0].mask is None):
transparent = False
else:
transparent = bg_color is None
if bg_color is None:
bg_color = 0.0 if is_mask else (0, 0, 0)
fpss = [clip.fps for clip in clips if getattr(clip, "fps", None)]
self.fps = max(fpss) if fpss else None
VideoClip.__init__(self)
self.size = size
self.is_mask = is_mask
self.clips = clips
self.bg_color = bg_color
if use_bgclip:
self.bg = clips[0]
self.clips = clips[1:]
self.created_bg = False
else:
self.clips = clips
self.bg = ColorClip(size, color=self.bg_color, is_mask=is_mask)
self.created_bg = True
# order self.clips by layer
self.clips = sorted(self.clips, key=lambda clip: clip.layer)
# compute duration
ends = [clip.end for clip in self.clips]
if None not in ends:
duration = max(ends)
self.duration = duration
self.end = duration
# compute audio
audioclips = [v.audio for v in self.clips if v.audio is not None]
if audioclips:
self.audio = CompositeAudioClip(audioclips)
# compute mask if necessary
if transparent:
maskclips = [
(clip.mask if (clip.mask is not None) else clip.add_mask().mask)
.with_position(clip.pos)
.with_end(clip.end)
.with_start(clip.start, change_end=False)
.with_layer(clip.layer)
for clip in self.clips
]
self.mask = CompositeVideoClip(
maskclips, self.size, is_mask=True, bg_color=0.0
) | 28,588 |
|||
Zulko/moviepy | 858bb81fba7e09f1f562283ed6d1394db883b6c7 | moviepy/video/compositing/CompositeVideoClip.py | CompositeVideoClip.make_frame | (self, t) | return np.array(im) | The clips playing at time `t` are blitted over one another. | The clips playing at time `t` are blitted over one another. | 118 | 131 | def make_frame(self, t):
"""The clips playing at time `t` are blitted over one another."""
frame = self.bg.get_frame(t).astype("uint8")
im = Image.fromarray(frame)
if self.bg.mask is not None:
frame_mask = self.bg.mask.get_frame(t)
im_mask = Image.fromarray(255 * frame_mask).convert("L")
im = im.putalpha(im_mask)
for clip in self.playing_clips(t):
im = clip.blit_on(im, t)
return np.array(im) | https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/compositing/CompositeVideoClip.py#L118-L131 | 46 | [
0,
1,
2,
3,
4,
5,
9,
10,
11,
12,
13
] | 78.571429 | [
6,
7,
8
] | 21.428571 | false | 92 | 14 | 3 | 78.571429 | 1 | def make_frame(self, t):
frame = self.bg.get_frame(t).astype("uint8")
im = Image.fromarray(frame)
if self.bg.mask is not None:
frame_mask = self.bg.mask.get_frame(t)
im_mask = Image.fromarray(255 * frame_mask).convert("L")
im = im.putalpha(im_mask)
for clip in self.playing_clips(t):
im = clip.blit_on(im, t)
return np.array(im) | 28,589 |
Zulko/moviepy | 858bb81fba7e09f1f562283ed6d1394db883b6c7 | moviepy/video/compositing/CompositeVideoClip.py | CompositeVideoClip.playing_clips | (self, t=0) | return [clip for clip in self.clips if clip.is_playing(t)] | Returns a list of the clips in the composite clips that are
actually playing at the given time `t`. | Returns a list of the clips in the composite clips that are
actually playing at the given time `t`. | 133 | 137 | def playing_clips(self, t=0):
"""Returns a list of the clips in the composite clips that are
actually playing at the given time `t`.
"""
return [clip for clip in self.clips if clip.is_playing(t)] | https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/compositing/CompositeVideoClip.py#L133-L137 | 46 | [
0,
1,
2,
3,
4
] | 100 | [] | 0 | true | 92 | 5 | 2 | 100 | 2 | def playing_clips(self, t=0):
return [clip for clip in self.clips if clip.is_playing(t)] | 28,590 |
Zulko/moviepy | 858bb81fba7e09f1f562283ed6d1394db883b6c7 | moviepy/video/compositing/CompositeVideoClip.py | CompositeVideoClip.close | (self) | Closes the instance, releasing all the resources. | Closes the instance, releasing all the resources. | 139 | 148 | def close(self):
"""Closes the instance, releasing all the resources."""
if self.created_bg and self.bg:
# Only close the background clip if it was locally created.
# Otherwise, it remains the job of whoever created it.
self.bg.close()
self.bg = None
if hasattr(self, "audio") and self.audio:
self.audio.close()
self.audio = None | https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/compositing/CompositeVideoClip.py#L139-L148 | 46 | [
0,
1,
2,
3,
4,
5,
6,
7
] | 80 | [
8,
9
] | 20 | false | 92 | 10 | 5 | 80 | 1 | def close(self):
if self.created_bg and self.bg:
# Only close the background clip if it was locally created.
# Otherwise, it remains the job of whoever created it.
self.bg.close()
self.bg = None
if hasattr(self, "audio") and self.audio:
self.audio.close()
self.audio = None | 28,591 |
|
Zulko/moviepy | 858bb81fba7e09f1f562283ed6d1394db883b6c7 | moviepy/video/compositing/transitions.py | crossfadein | (clip, duration) | return new_clip | Makes the clip appear progressively, over ``duration`` seconds.
Only works when the clip is included in a CompositeVideoClip. | Makes the clip appear progressively, over ``duration`` seconds.
Only works when the clip is included in a CompositeVideoClip. | 15 | 22 | def crossfadein(clip, duration):
"""Makes the clip appear progressively, over ``duration`` seconds.
Only works when the clip is included in a CompositeVideoClip.
"""
clip.mask.duration = clip.duration
new_clip = clip.copy()
new_clip.mask = clip.mask.fx(fadein, duration)
return new_clip | https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/compositing/transitions.py#L15-L22 | 46 | [
0,
1,
2,
3,
4,
5,
6,
7
] | 100 | [] | 0 | true | 100 | 8 | 1 | 100 | 2 | def crossfadein(clip, duration):
clip.mask.duration = clip.duration
new_clip = clip.copy()
new_clip.mask = clip.mask.fx(fadein, duration)
return new_clip | 28,592 |
Zulko/moviepy | 858bb81fba7e09f1f562283ed6d1394db883b6c7 | moviepy/video/compositing/transitions.py | crossfadeout | (clip, duration) | return new_clip | Makes the clip disappear progressively, over ``duration`` seconds.
Only works when the clip is included in a CompositeVideoClip. | Makes the clip disappear progressively, over ``duration`` seconds.
Only works when the clip is included in a CompositeVideoClip. | 27 | 34 | def crossfadeout(clip, duration):
"""Makes the clip disappear progressively, over ``duration`` seconds.
Only works when the clip is included in a CompositeVideoClip.
"""
clip.mask.duration = clip.duration
new_clip = clip.copy()
new_clip.mask = clip.mask.fx(fadeout, duration)
return new_clip | https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/compositing/transitions.py#L27-L34 | 46 | [
0,
1,
2,
3,
4,
5,
6,
7
] | 100 | [] | 0 | true | 100 | 8 | 1 | 100 | 2 | def crossfadeout(clip, duration):
clip.mask.duration = clip.duration
new_clip = clip.copy()
new_clip.mask = clip.mask.fx(fadeout, duration)
return new_clip | 28,593 |
Zulko/moviepy | 858bb81fba7e09f1f562283ed6d1394db883b6c7 | moviepy/video/compositing/transitions.py | slide_in | (clip, duration, side) | return clip.with_position(pos_dict[side]) | Makes the clip arrive from one side of the screen.
Only works when the clip is included in a CompositeVideoClip,
and if the clip has the same size as the whole composition.
Parameters
----------
clip : moviepy.Clip.Clip
A video clip.
duration : float
Time taken for the clip to be fully visible
side : str
Side of the screen where the clip comes from. One of
'top', 'bottom', 'left' or 'right'.
Examples
--------
>>> from moviepy import *
>>>
>>> clips = [... make a list of clips]
>>> slided_clips = [
... CompositeVideoClip([clip.fx(transfx.slide_in, 1, "left")])
... for clip in clips
... ]
>>> final_clip = concatenate_videoclips(slided_clips, padding=-1)
>>>
>>> clip = ColorClip(
... color=(255, 0, 0), duration=1, size=(300, 300)
... ).with_fps(60)
>>> final_clip = CompositeVideoClip([transfx.slide_in(clip, 1, "right")]) | Makes the clip arrive from one side of the screen. | 37 | 81 | def slide_in(clip, duration, side):
"""Makes the clip arrive from one side of the screen.
Only works when the clip is included in a CompositeVideoClip,
and if the clip has the same size as the whole composition.
Parameters
----------
clip : moviepy.Clip.Clip
A video clip.
duration : float
Time taken for the clip to be fully visible
side : str
Side of the screen where the clip comes from. One of
'top', 'bottom', 'left' or 'right'.
Examples
--------
>>> from moviepy import *
>>>
>>> clips = [... make a list of clips]
>>> slided_clips = [
... CompositeVideoClip([clip.fx(transfx.slide_in, 1, "left")])
... for clip in clips
... ]
>>> final_clip = concatenate_videoclips(slided_clips, padding=-1)
>>>
>>> clip = ColorClip(
... color=(255, 0, 0), duration=1, size=(300, 300)
... ).with_fps(60)
>>> final_clip = CompositeVideoClip([transfx.slide_in(clip, 1, "right")])
"""
w, h = clip.size
pos_dict = {
"left": lambda t: (min(0, w * (t / duration - 1)), "center"),
"right": lambda t: (max(0, w * (1 - t / duration)), "center"),
"top": lambda t: ("center", min(0, h * (t / duration - 1))),
"bottom": lambda t: ("center", max(0, h * (1 - t / duration))),
}
return clip.with_position(pos_dict[side]) | https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/compositing/transitions.py#L37-L81 | 46 | [
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
16,
17,
18,
19,
20,
21,
22,
23,
24,
25,
26,
27,
28,
29,
30,
31,
32,
33,
34,
35,
36,
37,
38,
39,
40,
41,
42,
43,
44
] | 100 | [] | 0 | true | 100 | 45 | 1 | 100 | 34 | def slide_in(clip, duration, side):
w, h = clip.size
pos_dict = {
"left": lambda t: (min(0, w * (t / duration - 1)), "center"),
"right": lambda t: (max(0, w * (1 - t / duration)), "center"),
"top": lambda t: ("center", min(0, h * (t / duration - 1))),
"bottom": lambda t: ("center", max(0, h * (1 - t / duration))),
}
return clip.with_position(pos_dict[side]) | 28,594 |
Zulko/moviepy | 858bb81fba7e09f1f562283ed6d1394db883b6c7 | moviepy/video/compositing/transitions.py | slide_out | (clip, duration, side) | return clip.with_position(pos_dict[side]) | Makes the clip go away by one side of the screen.
Only works when the clip is included in a CompositeVideoClip,
and if the clip has the same size as the whole composition.
Parameters
----------
clip : moviepy.Clip.Clip
A video clip.
duration : float
Time taken for the clip to fully disappear.
side : str
Side of the screen where the clip goes. One of
'top', 'bottom', 'left' or 'right'.
Examples
--------
>>> clips = [... make a list of clips]
>>> slided_clips = [
... CompositeVideoClip([clip.fx(transfx.slide_out, 1, "left")])
... for clip in clips
... ]
>>> final_clip = concatenate_videoclips(slided_clips, padding=-1)
>>>
>>> clip = ColorClip(
... color=(255, 0, 0), duration=1, size=(300, 300)
... ).with_fps(60)
>>> final_clip = CompositeVideoClip([transfx.slide_out(clip, 1, "right")]) | Makes the clip go away by one side of the screen. | 85 | 128 | def slide_out(clip, duration, side):
"""Makes the clip go away by one side of the screen.
Only works when the clip is included in a CompositeVideoClip,
and if the clip has the same size as the whole composition.
Parameters
----------
clip : moviepy.Clip.Clip
A video clip.
duration : float
Time taken for the clip to fully disappear.
side : str
Side of the screen where the clip goes. One of
'top', 'bottom', 'left' or 'right'.
Examples
--------
>>> clips = [... make a list of clips]
>>> slided_clips = [
... CompositeVideoClip([clip.fx(transfx.slide_out, 1, "left")])
... for clip in clips
... ]
>>> final_clip = concatenate_videoclips(slided_clips, padding=-1)
>>>
>>> clip = ColorClip(
... color=(255, 0, 0), duration=1, size=(300, 300)
... ).with_fps(60)
>>> final_clip = CompositeVideoClip([transfx.slide_out(clip, 1, "right")])
"""
w, h = clip.size
ts = clip.duration - duration # start time of the effect.
pos_dict = {
"left": lambda t: (min(0, w * (-(t - ts) / duration)), "center"),
"right": lambda t: (max(0, w * ((t - ts) / duration)), "center"),
"top": lambda t: ("center", min(0, h * (-(t - ts) / duration))),
"bottom": lambda t: ("center", max(0, h * ((t - ts) / duration))),
}
return clip.with_position(pos_dict[side]) | https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/compositing/transitions.py#L85-L128 | 46 | [
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
16,
17,
18,
19,
20,
21,
22,
23,
24,
25,
26,
27,
28,
29,
30,
31,
32,
33,
34,
35,
36,
37,
38,
39,
40,
41,
42,
43
] | 100 | [] | 0 | true | 100 | 44 | 1 | 100 | 32 | def slide_out(clip, duration, side):
w, h = clip.size
ts = clip.duration - duration # start time of the effect.
pos_dict = {
"left": lambda t: (min(0, w * (-(t - ts) / duration)), "center"),
"right": lambda t: (max(0, w * ((t - ts) / duration)), "center"),
"top": lambda t: ("center", min(0, h * (-(t - ts) / duration))),
"bottom": lambda t: ("center", max(0, h * ((t - ts) / duration))),
}
return clip.with_position(pos_dict[side]) | 28,595 |
Alir3z4/html2text | a3ed67b69160746b03a5861bf5c1b7a5ba76a4e1 | html2text/utils.py | hn | (tag: str) | return 0 | 13 | 18 | def hn(tag: str) -> int:
if tag[0] == "h" and len(tag) == 2:
n = tag[1]
if "0" < n <= "9":
return int(n)
return 0 | https://github.com/Alir3z4/html2text/blob/a3ed67b69160746b03a5861bf5c1b7a5ba76a4e1/project48/html2text/utils.py#L13-L18 | 48 | [
0,
1,
2,
3,
4,
5
] | 100 | [] | 0 | true | 98.461538 | 6 | 4 | 100 | 0 | def hn(tag: str) -> int:
if tag[0] == "h" and len(tag) == 2:
n = tag[1]
if "0" < n <= "9":
return int(n)
return 0 | 29,729 |
||
Alir3z4/html2text | a3ed67b69160746b03a5861bf5c1b7a5ba76a4e1 | html2text/utils.py | dumb_property_dict | (style: str) | return {
x.strip().lower(): y.strip().lower()
for x, y in [z.split(":", 1) for z in style.split(";") if ":" in z]
} | :returns: A hash of css attributes | :returns: A hash of css attributes | 21 | 28 | def dumb_property_dict(style: str) -> Dict[str, str]:
"""
:returns: A hash of css attributes
"""
return {
x.strip().lower(): y.strip().lower()
for x, y in [z.split(":", 1) for z in style.split(";") if ":" in z]
} | https://github.com/Alir3z4/html2text/blob/a3ed67b69160746b03a5861bf5c1b7a5ba76a4e1/project48/html2text/utils.py#L21-L28 | 48 | [
0,
1,
2,
3,
4,
5,
6,
7
] | 100 | [] | 0 | true | 98.461538 | 8 | 2 | 100 | 1 | def dumb_property_dict(style: str) -> Dict[str, str]:
return {
x.strip().lower(): y.strip().lower()
for x, y in [z.split(":", 1) for z in style.split(";") if ":" in z]
} | 29,730 |
Alir3z4/html2text | a3ed67b69160746b03a5861bf5c1b7a5ba76a4e1 | html2text/utils.py | dumb_css_parser | (data: str) | return elements | :type data: str
:returns: A hash of css selectors, each of which contains a hash of
css attributes.
:rtype: dict | :type data: str | 31 | 54 | def dumb_css_parser(data: str) -> Dict[str, Dict[str, str]]:
"""
:type data: str
:returns: A hash of css selectors, each of which contains a hash of
css attributes.
:rtype: dict
"""
# remove @import sentences
data += ";"
importIndex = data.find("@import")
while importIndex != -1:
data = data[0:importIndex] + data[data.find(";", importIndex) + 1 :]
importIndex = data.find("@import")
# parse the css. reverted from dictionary comprehension in order to
# support older pythons
pairs = [x.split("{") for x in data.split("}") if "{" in x.strip()]
try:
elements = {a.strip(): dumb_property_dict(b) for a, b in pairs}
except ValueError:
elements = {} # not that important
return elements | https://github.com/Alir3z4/html2text/blob/a3ed67b69160746b03a5861bf5c1b7a5ba76a4e1/project48/html2text/utils.py#L31-L54 | 48 | [
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
16,
17,
18,
19,
22,
23
] | 91.666667 | [
20,
21
] | 8.333333 | false | 98.461538 | 24 | 4 | 91.666667 | 5 | def dumb_css_parser(data: str) -> Dict[str, Dict[str, str]]:
# remove @import sentences
data += ";"
importIndex = data.find("@import")
while importIndex != -1:
data = data[0:importIndex] + data[data.find(";", importIndex) + 1 :]
importIndex = data.find("@import")
# parse the css. reverted from dictionary comprehension in order to
# support older pythons
pairs = [x.split("{") for x in data.split("}") if "{" in x.strip()]
try:
elements = {a.strip(): dumb_property_dict(b) for a, b in pairs}
except ValueError:
elements = {} # not that important
return elements | 29,731 |
Alir3z4/html2text | a3ed67b69160746b03a5861bf5c1b7a5ba76a4e1 | html2text/utils.py | element_style | (
attrs: Dict[str, Optional[str]],
style_def: Dict[str, Dict[str, str]],
parent_style: Dict[str, str],
) | return style | :type attrs: dict
:type style_def: dict
:type style_def: dict
:returns: A hash of the 'final' style attributes of the element
:rtype: dict | :type attrs: dict
:type style_def: dict
:type style_def: dict | 57 | 81 | def element_style(
attrs: Dict[str, Optional[str]],
style_def: Dict[str, Dict[str, str]],
parent_style: Dict[str, str],
) -> Dict[str, str]:
"""
:type attrs: dict
:type style_def: dict
:type style_def: dict
:returns: A hash of the 'final' style attributes of the element
:rtype: dict
"""
style = parent_style.copy()
if "class" in attrs:
assert attrs["class"] is not None
for css_class in attrs["class"].split():
css_style = style_def.get("." + css_class, {})
style.update(css_style)
if "style" in attrs:
assert attrs["style"] is not None
immediate_style = dumb_property_dict(attrs["style"])
style.update(immediate_style)
return style | https://github.com/Alir3z4/html2text/blob/a3ed67b69160746b03a5861bf5c1b7a5ba76a4e1/project48/html2text/utils.py#L57-L81 | 48 | [
0,
12,
13,
14,
15,
16,
17,
18,
19,
20,
21,
22,
23,
24
] | 56 | [] | 0 | false | 98.461538 | 25 | 6 | 100 | 6 | def element_style(
attrs: Dict[str, Optional[str]],
style_def: Dict[str, Dict[str, str]],
parent_style: Dict[str, str],
) -> Dict[str, str]:
style = parent_style.copy()
if "class" in attrs:
assert attrs["class"] is not None
for css_class in attrs["class"].split():
css_style = style_def.get("." + css_class, {})
style.update(css_style)
if "style" in attrs:
assert attrs["style"] is not None
immediate_style = dumb_property_dict(attrs["style"])
style.update(immediate_style)
return style | 29,732 |
Alir3z4/html2text | a3ed67b69160746b03a5861bf5c1b7a5ba76a4e1 | html2text/utils.py | google_list_style | (style: Dict[str, str]) | return "ol" | Finds out whether this is an ordered or unordered list
:type style: dict
:rtype: str | Finds out whether this is an ordered or unordered list | 84 | 97 | def google_list_style(style: Dict[str, str]) -> str:
"""
Finds out whether this is an ordered or unordered list
:type style: dict
:rtype: str
"""
if "list-style-type" in style:
list_style = style["list-style-type"]
if list_style in ["disc", "circle", "square", "none"]:
return "ul"
return "ol" | https://github.com/Alir3z4/html2text/blob/a3ed67b69160746b03a5861bf5c1b7a5ba76a4e1/project48/html2text/utils.py#L84-L97 | 48 | [
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13
] | 100 | [] | 0 | true | 98.461538 | 14 | 3 | 100 | 5 | def google_list_style(style: Dict[str, str]) -> str:
if "list-style-type" in style:
list_style = style["list-style-type"]
if list_style in ["disc", "circle", "square", "none"]:
return "ul"
return "ol" | 29,733 |
Alir3z4/html2text | a3ed67b69160746b03a5861bf5c1b7a5ba76a4e1 | html2text/utils.py | google_has_height | (style: Dict[str, str]) | return "height" in style | Check if the style of the element has the 'height' attribute
explicitly defined
:type style: dict
:rtype: bool | Check if the style of the element has the 'height' attribute
explicitly defined | 100 | 109 | def google_has_height(style: Dict[str, str]) -> bool:
"""
Check if the style of the element has the 'height' attribute
explicitly defined
:type style: dict
:rtype: bool
"""
return "height" in style | https://github.com/Alir3z4/html2text/blob/a3ed67b69160746b03a5861bf5c1b7a5ba76a4e1/project48/html2text/utils.py#L100-L109 | 48 | [
0,
1,
2,
3,
4,
5,
6,
7,
8,
9
] | 100 | [] | 0 | true | 98.461538 | 10 | 1 | 100 | 6 | def google_has_height(style: Dict[str, str]) -> bool:
return "height" in style | 29,734 |
Alir3z4/html2text | a3ed67b69160746b03a5861bf5c1b7a5ba76a4e1 | html2text/utils.py | google_text_emphasis | (style: Dict[str, str]) | return emphasis | :type style: dict
:returns: A list of all emphasis modifiers of the element
:rtype: list | :type style: dict | 112 | 127 | def google_text_emphasis(style: Dict[str, str]) -> List[str]:
"""
:type style: dict
:returns: A list of all emphasis modifiers of the element
:rtype: list
"""
emphasis = []
if "text-decoration" in style:
emphasis.append(style["text-decoration"])
if "font-style" in style:
emphasis.append(style["font-style"])
if "font-weight" in style:
emphasis.append(style["font-weight"])
return emphasis | https://github.com/Alir3z4/html2text/blob/a3ed67b69160746b03a5861bf5c1b7a5ba76a4e1/project48/html2text/utils.py#L112-L127 | 48 | [
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15
] | 100 | [] | 0 | true | 98.461538 | 16 | 4 | 100 | 4 | def google_text_emphasis(style: Dict[str, str]) -> List[str]:
emphasis = []
if "text-decoration" in style:
emphasis.append(style["text-decoration"])
if "font-style" in style:
emphasis.append(style["font-style"])
if "font-weight" in style:
emphasis.append(style["font-weight"])
return emphasis | 29,735 |
Alir3z4/html2text | a3ed67b69160746b03a5861bf5c1b7a5ba76a4e1 | html2text/utils.py | google_fixed_width_font | (style: Dict[str, str]) | return "courier new" == font_family or "consolas" == font_family | Check if the css of the current element defines a fixed width font
:type style: dict
:rtype: bool | Check if the css of the current element defines a fixed width font | 130 | 141 | def google_fixed_width_font(style: Dict[str, str]) -> bool:
"""
Check if the css of the current element defines a fixed width font
:type style: dict
:rtype: bool
"""
font_family = ""
if "font-family" in style:
font_family = style["font-family"]
return "courier new" == font_family or "consolas" == font_family | https://github.com/Alir3z4/html2text/blob/a3ed67b69160746b03a5861bf5c1b7a5ba76a4e1/project48/html2text/utils.py#L130-L141 | 48 | [
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11
] | 100 | [] | 0 | true | 98.461538 | 12 | 3 | 100 | 5 | def google_fixed_width_font(style: Dict[str, str]) -> bool:
font_family = ""
if "font-family" in style:
font_family = style["font-family"]
return "courier new" == font_family or "consolas" == font_family | 29,736 |
Alir3z4/html2text | a3ed67b69160746b03a5861bf5c1b7a5ba76a4e1 | html2text/utils.py | list_numbering_start | (attrs: Dict[str, Optional[str]]) | return 0 | Extract numbering from list element attributes
:type attrs: dict
:rtype: int or None | Extract numbering from list element attributes | 144 | 159 | def list_numbering_start(attrs: Dict[str, Optional[str]]) -> int:
"""
Extract numbering from list element attributes
:type attrs: dict
:rtype: int or None
"""
if "start" in attrs:
assert attrs["start"] is not None
try:
return int(attrs["start"]) - 1
except ValueError:
pass
return 0 | https://github.com/Alir3z4/html2text/blob/a3ed67b69160746b03a5861bf5c1b7a5ba76a4e1/project48/html2text/utils.py#L144-L159 | 48 | [
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15
] | 100 | [] | 0 | true | 98.461538 | 16 | 4 | 100 | 5 | def list_numbering_start(attrs: Dict[str, Optional[str]]) -> int:
if "start" in attrs:
assert attrs["start"] is not None
try:
return int(attrs["start"]) - 1
except ValueError:
pass
return 0 | 29,737 |
Alir3z4/html2text | a3ed67b69160746b03a5861bf5c1b7a5ba76a4e1 | html2text/utils.py | skipwrap | (
para: str, wrap_links: bool, wrap_list_items: bool, wrap_tables: bool
) | return bool(
config.RE_ORDERED_LIST_MATCHER.match(stripped)
or config.RE_UNORDERED_LIST_MATCHER.match(stripped)
) | 162 | 196 | def skipwrap(
para: str, wrap_links: bool, wrap_list_items: bool, wrap_tables: bool
) -> bool:
# If it appears to contain a link
# don't wrap
if not wrap_links and config.RE_LINK.search(para):
return True
# If the text begins with four spaces or one tab, it's a code block;
# don't wrap
if para[0:4] == " " or para[0] == "\t":
return True
# If the text begins with only two "--", possibly preceded by
# whitespace, that's an emdash; so wrap.
stripped = para.lstrip()
if stripped[0:2] == "--" and len(stripped) > 2 and stripped[2] != "-":
return False
# I'm not sure what this is for; I thought it was to detect lists,
# but there's a <br>-inside-<span> case in one of the tests that
# also depends upon it.
if stripped[0:1] in ("-", "*") and not stripped[0:2] == "**":
return not wrap_list_items
# If text contains a pipe character it is likely a table
if not wrap_tables and config.RE_TABLE.search(para):
return True
# If the text begins with a single -, *, or +, followed by a space,
# or an integer, followed by a ., followed by a space (in either
# case optionally proceeded by whitespace), it's a list; don't wrap.
return bool(
config.RE_ORDERED_LIST_MATCHER.match(stripped)
or config.RE_UNORDERED_LIST_MATCHER.match(stripped)
) | https://github.com/Alir3z4/html2text/blob/a3ed67b69160746b03a5861bf5c1b7a5ba76a4e1/project48/html2text/utils.py#L162-L196 | 48 | [
0,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
16,
17,
18,
19,
20,
21,
22,
23,
24,
25,
26,
27,
28,
29,
30,
31
] | 82.857143 | [] | 0 | false | 98.461538 | 35 | 13 | 100 | 0 | def skipwrap(
para: str, wrap_links: bool, wrap_list_items: bool, wrap_tables: bool
) -> bool:
# If it appears to contain a link
# don't wrap
if not wrap_links and config.RE_LINK.search(para):
return True
# If the text begins with four spaces or one tab, it's a code block;
# don't wrap
if para[0:4] == " " or para[0] == "\t":
return True
# If the text begins with only two "--", possibly preceded by
# whitespace, that's an emdash; so wrap.
stripped = para.lstrip()
if stripped[0:2] == "--" and len(stripped) > 2 and stripped[2] != "-":
return False
# I'm not sure what this is for; I thought it was to detect lists,
# but there's a <br>-inside-<span> case in one of the tests that
# also depends upon it.
if stripped[0:1] in ("-", "*") and not stripped[0:2] == "**":
return not wrap_list_items
# If text contains a pipe character it is likely a table
if not wrap_tables and config.RE_TABLE.search(para):
return True
# If the text begins with a single -, *, or +, followed by a space,
# or an integer, followed by a ., followed by a space (in either
# case optionally proceeded by whitespace), it's a list; don't wrap.
return bool(
config.RE_ORDERED_LIST_MATCHER.match(stripped)
or config.RE_UNORDERED_LIST_MATCHER.match(stripped)
) | 29,738 |
||
Alir3z4/html2text | a3ed67b69160746b03a5861bf5c1b7a5ba76a4e1 | html2text/utils.py | escape_md | (text: str) | return config.RE_MD_CHARS_MATCHER.sub(r"\\\1", text) | Escapes markdown-sensitive characters within other markdown
constructs. | Escapes markdown-sensitive characters within other markdown
constructs. | 199 | 204 | def escape_md(text: str) -> str:
"""
Escapes markdown-sensitive characters within other markdown
constructs.
"""
return config.RE_MD_CHARS_MATCHER.sub(r"\\\1", text) | https://github.com/Alir3z4/html2text/blob/a3ed67b69160746b03a5861bf5c1b7a5ba76a4e1/project48/html2text/utils.py#L199-L204 | 48 | [
0,
1,
2,
3,
4,
5
] | 100 | [] | 0 | true | 98.461538 | 6 | 1 | 100 | 2 | def escape_md(text: str) -> str:
return config.RE_MD_CHARS_MATCHER.sub(r"\\\1", text) | 29,739 |
Alir3z4/html2text | a3ed67b69160746b03a5861bf5c1b7a5ba76a4e1 | html2text/utils.py | escape_md_section | (text: str, snob: bool = False) | return text | Escapes markdown-sensitive characters across whole document sections. | Escapes markdown-sensitive characters across whole document sections. | 207 | 220 | def escape_md_section(text: str, snob: bool = False) -> str:
"""
Escapes markdown-sensitive characters across whole document sections.
"""
text = config.RE_MD_BACKSLASH_MATCHER.sub(r"\\\1", text)
if snob:
text = config.RE_MD_CHARS_MATCHER_ALL.sub(r"\\\1", text)
text = config.RE_MD_DOT_MATCHER.sub(r"\1\\\2", text)
text = config.RE_MD_PLUS_MATCHER.sub(r"\1\\\2", text)
text = config.RE_MD_DASH_MATCHER.sub(r"\1\\\2", text)
return text | https://github.com/Alir3z4/html2text/blob/a3ed67b69160746b03a5861bf5c1b7a5ba76a4e1/project48/html2text/utils.py#L207-L220 | 48 | [
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13
] | 100 | [] | 0 | true | 98.461538 | 14 | 2 | 100 | 1 | def escape_md_section(text: str, snob: bool = False) -> str:
text = config.RE_MD_BACKSLASH_MATCHER.sub(r"\\\1", text)
if snob:
text = config.RE_MD_CHARS_MATCHER_ALL.sub(r"\\\1", text)
text = config.RE_MD_DOT_MATCHER.sub(r"\1\\\2", text)
text = config.RE_MD_PLUS_MATCHER.sub(r"\1\\\2", text)
text = config.RE_MD_DASH_MATCHER.sub(r"\1\\\2", text)
return text | 29,740 |
Alir3z4/html2text | a3ed67b69160746b03a5861bf5c1b7a5ba76a4e1 | html2text/utils.py | reformat_table | (lines: List[str], right_margin: int) | return new_lines | Given the lines of a table
padds the cells and returns the new lines | Given the lines of a table
padds the cells and returns the new lines | 223 | 264 | def reformat_table(lines: List[str], right_margin: int) -> List[str]:
"""
Given the lines of a table
padds the cells and returns the new lines
"""
# find the maximum width of the columns
max_width = [len(x.rstrip()) + right_margin for x in lines[0].split("|")]
max_cols = len(max_width)
for line in lines:
cols = [x.rstrip() for x in line.split("|")]
num_cols = len(cols)
# don't drop any data if colspan attributes result in unequal lengths
if num_cols < max_cols:
cols += [""] * (max_cols - num_cols)
elif max_cols < num_cols:
max_width += [len(x) + right_margin for x in cols[-(num_cols - max_cols) :]]
max_cols = num_cols
max_width = [
max(len(x) + right_margin, old_len) for x, old_len in zip(cols, max_width)
]
# reformat
new_lines = []
for line in lines:
cols = [x.rstrip() for x in line.split("|")]
if set(line.strip()) == set("-|"):
filler = "-"
new_cols = [
x.rstrip() + (filler * (M - len(x.rstrip())))
for x, M in zip(cols, max_width)
]
new_lines.append("|-" + "|".join(new_cols) + "|")
else:
filler = " "
new_cols = [
x.rstrip() + (filler * (M - len(x.rstrip())))
for x, M in zip(cols, max_width)
]
new_lines.append("| " + "|".join(new_cols) + "|")
return new_lines | https://github.com/Alir3z4/html2text/blob/a3ed67b69160746b03a5861bf5c1b7a5ba76a4e1/project48/html2text/utils.py#L223-L264 | 48 | [
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
16,
17,
18,
19,
20,
21,
22,
23,
24,
25,
26,
27,
28,
29,
30,
31,
32,
33,
34,
35,
36,
37,
38,
39,
40,
41
] | 100 | [] | 0 | true | 98.461538 | 42 | 13 | 100 | 2 | def reformat_table(lines: List[str], right_margin: int) -> List[str]:
# find the maximum width of the columns
max_width = [len(x.rstrip()) + right_margin for x in lines[0].split("|")]
max_cols = len(max_width)
for line in lines:
cols = [x.rstrip() for x in line.split("|")]
num_cols = len(cols)
# don't drop any data if colspan attributes result in unequal lengths
if num_cols < max_cols:
cols += [""] * (max_cols - num_cols)
elif max_cols < num_cols:
max_width += [len(x) + right_margin for x in cols[-(num_cols - max_cols) :]]
max_cols = num_cols
max_width = [
max(len(x) + right_margin, old_len) for x, old_len in zip(cols, max_width)
]
# reformat
new_lines = []
for line in lines:
cols = [x.rstrip() for x in line.split("|")]
if set(line.strip()) == set("-|"):
filler = "-"
new_cols = [
x.rstrip() + (filler * (M - len(x.rstrip())))
for x, M in zip(cols, max_width)
]
new_lines.append("|-" + "|".join(new_cols) + "|")
else:
filler = " "
new_cols = [
x.rstrip() + (filler * (M - len(x.rstrip())))
for x, M in zip(cols, max_width)
]
new_lines.append("| " + "|".join(new_cols) + "|")
return new_lines | 29,741 |
Alir3z4/html2text | a3ed67b69160746b03a5861bf5c1b7a5ba76a4e1 | html2text/utils.py | pad_tables_in_text | (text: str, right_margin: int = 1) | return "\n".join(new_lines) | Provide padding for tables in the text | Provide padding for tables in the text | 267 | 290 | def pad_tables_in_text(text: str, right_margin: int = 1) -> str:
"""
Provide padding for tables in the text
"""
lines = text.split("\n")
table_buffer = [] # type: List[str]
table_started = False
new_lines = []
for line in lines:
# Toggle table started
if config.TABLE_MARKER_FOR_PAD in line:
table_started = not table_started
if not table_started:
table = reformat_table(table_buffer, right_margin)
new_lines.extend(table)
table_buffer = []
new_lines.append("")
continue
# Process lines
if table_started:
table_buffer.append(line)
else:
new_lines.append(line)
return "\n".join(new_lines) | https://github.com/Alir3z4/html2text/blob/a3ed67b69160746b03a5861bf5c1b7a5ba76a4e1/project48/html2text/utils.py#L267-L290 | 48 | [
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
16,
17,
18,
19,
20,
21,
22,
23
] | 100 | [] | 0 | true | 98.461538 | 24 | 5 | 100 | 1 | def pad_tables_in_text(text: str, right_margin: int = 1) -> str:
lines = text.split("\n")
table_buffer = [] # type: List[str]
table_started = False
new_lines = []
for line in lines:
# Toggle table started
if config.TABLE_MARKER_FOR_PAD in line:
table_started = not table_started
if not table_started:
table = reformat_table(table_buffer, right_margin)
new_lines.extend(table)
table_buffer = []
new_lines.append("")
continue
# Process lines
if table_started:
table_buffer.append(line)
else:
new_lines.append(line)
return "\n".join(new_lines) | 29,742 |
Alir3z4/html2text | a3ed67b69160746b03a5861bf5c1b7a5ba76a4e1 | html2text/__init__.py | html2text | (html: str, baseurl: str = "", bodywidth: Optional[int] = None) | return h.handle(html) | 994 | 999 | def html2text(html: str, baseurl: str = "", bodywidth: Optional[int] = None) -> str:
if bodywidth is None:
bodywidth = config.BODY_WIDTH
h = HTML2Text(baseurl=baseurl, bodywidth=bodywidth)
return h.handle(html) | https://github.com/Alir3z4/html2text/blob/a3ed67b69160746b03a5861bf5c1b7a5ba76a4e1/project48/html2text/__init__.py#L994-L999 | 48 | [
0,
1,
2,
3,
4,
5
] | 100 | [] | 0 | true | 97.322835 | 6 | 2 | 100 | 0 | def html2text(html: str, baseurl: str = "", bodywidth: Optional[int] = None) -> str:
if bodywidth is None:
bodywidth = config.BODY_WIDTH
h = HTML2Text(baseurl=baseurl, bodywidth=bodywidth)
return h.handle(html) | 29,743 |
||
Alir3z4/html2text | a3ed67b69160746b03a5861bf5c1b7a5ba76a4e1 | html2text/__init__.py | HTML2Text.__init__ | (
self,
out: Optional[OutCallback] = None,
baseurl: str = "",
bodywidth: int = config.BODY_WIDTH,
) | Input parameters:
out: possible custom replacement for self.outtextf (which
appends lines of text).
baseurl: base URL of the document we process | Input parameters:
out: possible custom replacement for self.outtextf (which
appends lines of text).
baseurl: base URL of the document we process | 38 | 138 | def __init__(
self,
out: Optional[OutCallback] = None,
baseurl: str = "",
bodywidth: int = config.BODY_WIDTH,
) -> None:
"""
Input parameters:
out: possible custom replacement for self.outtextf (which
appends lines of text).
baseurl: base URL of the document we process
"""
super().__init__(convert_charrefs=False)
# Config options
self.split_next_td = False
self.td_count = 0
self.table_start = False
self.unicode_snob = config.UNICODE_SNOB # covered in cli
self.escape_snob = config.ESCAPE_SNOB # covered in cli
self.links_each_paragraph = config.LINKS_EACH_PARAGRAPH
self.body_width = bodywidth # covered in cli
self.skip_internal_links = config.SKIP_INTERNAL_LINKS # covered in cli
self.inline_links = config.INLINE_LINKS # covered in cli
self.protect_links = config.PROTECT_LINKS # covered in cli
self.google_list_indent = config.GOOGLE_LIST_INDENT # covered in cli
self.ignore_links = config.IGNORE_ANCHORS # covered in cli
self.ignore_mailto_links = config.IGNORE_MAILTO_LINKS # covered in cli
self.ignore_images = config.IGNORE_IMAGES # covered in cli
self.images_as_html = config.IMAGES_AS_HTML # covered in cli
self.images_to_alt = config.IMAGES_TO_ALT # covered in cli
self.images_with_size = config.IMAGES_WITH_SIZE # covered in cli
self.ignore_emphasis = config.IGNORE_EMPHASIS # covered in cli
self.bypass_tables = config.BYPASS_TABLES # covered in cli
self.ignore_tables = config.IGNORE_TABLES # covered in cli
self.google_doc = False # covered in cli
self.ul_item_mark = "*" # covered in cli
self.emphasis_mark = "_" # covered in cli
self.strong_mark = "**"
self.single_line_break = config.SINGLE_LINE_BREAK # covered in cli
self.use_automatic_links = config.USE_AUTOMATIC_LINKS # covered in cli
self.hide_strikethrough = False # covered in cli
self.mark_code = config.MARK_CODE
self.wrap_list_items = config.WRAP_LIST_ITEMS # covered in cli
self.wrap_links = config.WRAP_LINKS # covered in cli
self.wrap_tables = config.WRAP_TABLES
self.pad_tables = config.PAD_TABLES # covered in cli
self.default_image_alt = config.DEFAULT_IMAGE_ALT # covered in cli
self.tag_callback = None
self.open_quote = config.OPEN_QUOTE # covered in cli
self.close_quote = config.CLOSE_QUOTE # covered in cli
if out is None:
self.out = self.outtextf
else:
self.out = out
# empty list to store output characters before they are "joined"
self.outtextlist = [] # type: List[str]
self.quiet = 0
self.p_p = 0 # number of newline character to print before next output
self.outcount = 0
self.start = True
self.space = False
self.a = [] # type: List[AnchorElement]
self.astack = [] # type: List[Optional[Dict[str, Optional[str]]]]
self.maybe_automatic_link = None # type: Optional[str]
self.empty_link = False
self.absolute_url_matcher = re.compile(r"^[a-zA-Z+]+://")
self.acount = 0
self.list = [] # type: List[ListElement]
self.blockquote = 0
self.pre = False
self.startpre = False
self.code = False
self.quote = False
self.br_toggle = ""
self.lastWasNL = False
self.lastWasList = False
self.style = 0
self.style_def = {} # type: Dict[str, Dict[str, str]]
self.tag_stack = (
[]
) # type: List[Tuple[str, Dict[str, Optional[str]], Dict[str, str]]]
self.emphasis = 0
self.drop_white_space = 0
self.inheader = False
# Current abbreviation definition
self.abbr_title = None # type: Optional[str]
# Last inner HTML (for abbr being defined)
self.abbr_data = None # type: Optional[str]
# Stack of abbreviations to write later
self.abbr_list = {} # type: Dict[str, str]
self.baseurl = baseurl
self.stressed = False
self.preceding_stressed = False
self.preceding_data = ""
self.current_tag = ""
config.UNIFIABLE["nbsp"] = " _place_holder;" | https://github.com/Alir3z4/html2text/blob/a3ed67b69160746b03a5861bf5c1b7a5ba76a4e1/project48/html2text/__init__.py#L38-L138 | 48 | [
0,
11,
12,
13,
14,
15,
16,
17,
18,
19,
20,
21,
22,
23,
24,
25,
26,
27,
28,
29,
30,
31,
32,
33,
34,
35,
36,
37,
38,
39,
40,
41,
42,
43,
44,
45,
46,
47,
48,
49,
50,
51,
52,
53,
54,
57,
58,
59,
60,
61,
62,
63,
64,
65,
66,
67,
68,
69,
70,
71,
72,
73,
74,
75,
76,
77,
78,
79,
80,
81,
82,
83,
84,
85,
86,
87,
88,
89,
90,
91,
92,
93,
94,
95,
96,
97,
98,
99,
100
] | 88.118812 | [
55
] | 0.990099 | false | 97.322835 | 101 | 2 | 99.009901 | 4 | def __init__(
self,
out: Optional[OutCallback] = None,
baseurl: str = "",
bodywidth: int = config.BODY_WIDTH,
) -> None:
super().__init__(convert_charrefs=False)
# Config options
self.split_next_td = False
self.td_count = 0
self.table_start = False
self.unicode_snob = config.UNICODE_SNOB # covered in cli
self.escape_snob = config.ESCAPE_SNOB # covered in cli
self.links_each_paragraph = config.LINKS_EACH_PARAGRAPH
self.body_width = bodywidth # covered in cli
self.skip_internal_links = config.SKIP_INTERNAL_LINKS # covered in cli
self.inline_links = config.INLINE_LINKS # covered in cli
self.protect_links = config.PROTECT_LINKS # covered in cli
self.google_list_indent = config.GOOGLE_LIST_INDENT # covered in cli
self.ignore_links = config.IGNORE_ANCHORS # covered in cli
self.ignore_mailto_links = config.IGNORE_MAILTO_LINKS # covered in cli
self.ignore_images = config.IGNORE_IMAGES # covered in cli
self.images_as_html = config.IMAGES_AS_HTML # covered in cli
self.images_to_alt = config.IMAGES_TO_ALT # covered in cli
self.images_with_size = config.IMAGES_WITH_SIZE # covered in cli
self.ignore_emphasis = config.IGNORE_EMPHASIS # covered in cli
self.bypass_tables = config.BYPASS_TABLES # covered in cli
self.ignore_tables = config.IGNORE_TABLES # covered in cli
self.google_doc = False # covered in cli
self.ul_item_mark = "*" # covered in cli
self.emphasis_mark = "_" # covered in cli
self.strong_mark = "**"
self.single_line_break = config.SINGLE_LINE_BREAK # covered in cli
self.use_automatic_links = config.USE_AUTOMATIC_LINKS # covered in cli
self.hide_strikethrough = False # covered in cli
self.mark_code = config.MARK_CODE
self.wrap_list_items = config.WRAP_LIST_ITEMS # covered in cli
self.wrap_links = config.WRAP_LINKS # covered in cli
self.wrap_tables = config.WRAP_TABLES
self.pad_tables = config.PAD_TABLES # covered in cli
self.default_image_alt = config.DEFAULT_IMAGE_ALT # covered in cli
self.tag_callback = None
self.open_quote = config.OPEN_QUOTE # covered in cli
self.close_quote = config.CLOSE_QUOTE # covered in cli
if out is None:
self.out = self.outtextf
else:
self.out = out
# empty list to store output characters before they are "joined"
self.outtextlist = [] # type: List[str]
self.quiet = 0
self.p_p = 0 # number of newline character to print before next output
self.outcount = 0
self.start = True
self.space = False
self.a = [] # type: List[AnchorElement]
self.astack = [] # type: List[Optional[Dict[str, Optional[str]]]]
self.maybe_automatic_link = None # type: Optional[str]
self.empty_link = False
self.absolute_url_matcher = re.compile(r"^[a-zA-Z+]+://")
self.acount = 0
self.list = [] # type: List[ListElement]
self.blockquote = 0
self.pre = False
self.startpre = False
self.code = False
self.quote = False
self.br_toggle = ""
self.lastWasNL = False
self.lastWasList = False
self.style = 0
self.style_def = {} # type: Dict[str, Dict[str, str]]
self.tag_stack = (
[]
) # type: List[Tuple[str, Dict[str, Optional[str]], Dict[str, str]]]
self.emphasis = 0
self.drop_white_space = 0
self.inheader = False
# Current abbreviation definition
self.abbr_title = None # type: Optional[str]
# Last inner HTML (for abbr being defined)
self.abbr_data = None # type: Optional[str]
# Stack of abbreviations to write later
self.abbr_list = {} # type: Dict[str, str]
self.baseurl = baseurl
self.stressed = False
self.preceding_stressed = False
self.preceding_data = ""
self.current_tag = ""
config.UNIFIABLE["nbsp"] = " _place_holder;" | 29,744 |
|
Alir3z4/html2text | a3ed67b69160746b03a5861bf5c1b7a5ba76a4e1 | html2text/__init__.py | HTML2Text.feed | (self, data: str) | 140 | 142 | def feed(self, data: str) -> None:
data = data.replace("</' + 'script>", "</ignore>")
super().feed(data) | https://github.com/Alir3z4/html2text/blob/a3ed67b69160746b03a5861bf5c1b7a5ba76a4e1/project48/html2text/__init__.py#L140-L142 | 48 | [
0,
1,
2
] | 100 | [] | 0 | true | 97.322835 | 3 | 1 | 100 | 0 | def feed(self, data: str) -> None:
data = data.replace("</' + 'script>", "</ignore>")
super().feed(data) | 29,745 |
|||
Alir3z4/html2text | a3ed67b69160746b03a5861bf5c1b7a5ba76a4e1 | html2text/__init__.py | HTML2Text.handle | (self, data: str) | 144 | 151 | def handle(self, data: str) -> str:
self.feed(data)
self.feed("")
markdown = self.optwrap(self.finish())
if self.pad_tables:
return pad_tables_in_text(markdown)
else:
return markdown | https://github.com/Alir3z4/html2text/blob/a3ed67b69160746b03a5861bf5c1b7a5ba76a4e1/project48/html2text/__init__.py#L144-L151 | 48 | [
0,
1,
2,
3,
4,
5,
7
] | 87.5 | [] | 0 | false | 97.322835 | 8 | 2 | 100 | 0 | def handle(self, data: str) -> str:
self.feed(data)
self.feed("")
markdown = self.optwrap(self.finish())
if self.pad_tables:
return pad_tables_in_text(markdown)
else:
return markdown | 29,746 |
|||
Alir3z4/html2text | a3ed67b69160746b03a5861bf5c1b7a5ba76a4e1 | html2text/__init__.py | HTML2Text.outtextf | (self, s: str) | 153 | 156 | def outtextf(self, s: str) -> None:
self.outtextlist.append(s)
if s:
self.lastWasNL = s[-1] == "\n" | https://github.com/Alir3z4/html2text/blob/a3ed67b69160746b03a5861bf5c1b7a5ba76a4e1/project48/html2text/__init__.py#L153-L156 | 48 | [
0,
1,
2,
3
] | 100 | [] | 0 | true | 97.322835 | 4 | 2 | 100 | 0 | def outtextf(self, s: str) -> None:
self.outtextlist.append(s)
if s:
self.lastWasNL = s[-1] == "\n" | 29,747 |
|||
Alir3z4/html2text | a3ed67b69160746b03a5861bf5c1b7a5ba76a4e1 | html2text/__init__.py | HTML2Text.finish | (self) | return outtext | 158 | 176 | def finish(self) -> str:
self.close()
self.pbr()
self.o("", force="end")
outtext = "".join(self.outtextlist)
if self.unicode_snob:
nbsp = html.entities.html5["nbsp;"]
else:
nbsp = " "
outtext = outtext.replace(" _place_holder;", nbsp)
# Clear self.outtextlist to avoid memory leak of its content to
# the next handling.
self.outtextlist = []
return outtext | https://github.com/Alir3z4/html2text/blob/a3ed67b69160746b03a5861bf5c1b7a5ba76a4e1/project48/html2text/__init__.py#L158-L176 | 48 | [
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
11,
12,
13,
14,
15,
16,
17,
18
] | 94.736842 | [] | 0 | false | 97.322835 | 19 | 2 | 100 | 0 | def finish(self) -> str:
self.close()
self.pbr()
self.o("", force="end")
outtext = "".join(self.outtextlist)
if self.unicode_snob:
nbsp = html.entities.html5["nbsp;"]
else:
nbsp = " "
outtext = outtext.replace(" _place_holder;", nbsp)
# Clear self.outtextlist to avoid memory leak of its content to
# the next handling.
self.outtextlist = []
return outtext | 29,748 |
||
Alir3z4/html2text | a3ed67b69160746b03a5861bf5c1b7a5ba76a4e1 | html2text/__init__.py | HTML2Text.handle_charref | (self, c: str) | 178 | 179 | def handle_charref(self, c: str) -> None:
self.handle_data(self.charref(c), True) | https://github.com/Alir3z4/html2text/blob/a3ed67b69160746b03a5861bf5c1b7a5ba76a4e1/project48/html2text/__init__.py#L178-L179 | 48 | [
0,
1
] | 100 | [] | 0 | true | 97.322835 | 2 | 1 | 100 | 0 | def handle_charref(self, c: str) -> None:
self.handle_data(self.charref(c), True) | 29,749 |
|||
Alir3z4/html2text | a3ed67b69160746b03a5861bf5c1b7a5ba76a4e1 | html2text/__init__.py | HTML2Text.handle_entityref | (self, c: str) | 181 | 191 | def handle_entityref(self, c: str) -> None:
ref = self.entityref(c)
# ref may be an empty string (e.g. for ‎/‏ markers that should
# not contribute to the final output).
# self.handle_data cannot handle a zero-length string right after a
# stressed tag or mid-text within a stressed tag (text get split and
# self.stressed/self.preceding_stressed gets switched after the first
# part of that text).
if ref:
self.handle_data(ref, True) | https://github.com/Alir3z4/html2text/blob/a3ed67b69160746b03a5861bf5c1b7a5ba76a4e1/project48/html2text/__init__.py#L181-L191 | 48 | [
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10
] | 100 | [] | 0 | true | 97.322835 | 11 | 2 | 100 | 0 | def handle_entityref(self, c: str) -> None:
ref = self.entityref(c)
# ref may be an empty string (e.g. for ‎/‏ markers that should
# not contribute to the final output).
# self.handle_data cannot handle a zero-length string right after a
# stressed tag or mid-text within a stressed tag (text get split and
# self.stressed/self.preceding_stressed gets switched after the first
# part of that text).
if ref:
self.handle_data(ref, True) | 29,750 |
|||
Alir3z4/html2text | a3ed67b69160746b03a5861bf5c1b7a5ba76a4e1 | html2text/__init__.py | HTML2Text.handle_starttag | (self, tag: str, attrs: List[Tuple[str, Optional[str]]]) | 193 | 194 | def handle_starttag(self, tag: str, attrs: List[Tuple[str, Optional[str]]]) -> None:
self.handle_tag(tag, dict(attrs), start=True) | https://github.com/Alir3z4/html2text/blob/a3ed67b69160746b03a5861bf5c1b7a5ba76a4e1/project48/html2text/__init__.py#L193-L194 | 48 | [
0,
1
] | 100 | [] | 0 | true | 97.322835 | 2 | 1 | 100 | 0 | def handle_starttag(self, tag: str, attrs: List[Tuple[str, Optional[str]]]) -> None:
self.handle_tag(tag, dict(attrs), start=True) | 29,751 |
|||
Alir3z4/html2text | a3ed67b69160746b03a5861bf5c1b7a5ba76a4e1 | html2text/__init__.py | HTML2Text.handle_endtag | (self, tag: str) | 196 | 197 | def handle_endtag(self, tag: str) -> None:
self.handle_tag(tag, {}, start=False) | https://github.com/Alir3z4/html2text/blob/a3ed67b69160746b03a5861bf5c1b7a5ba76a4e1/project48/html2text/__init__.py#L196-L197 | 48 | [
0,
1
] | 100 | [] | 0 | true | 97.322835 | 2 | 1 | 100 | 0 | def handle_endtag(self, tag: str) -> None:
self.handle_tag(tag, {}, start=False) | 29,752 |
|||
Alir3z4/html2text | a3ed67b69160746b03a5861bf5c1b7a5ba76a4e1 | html2text/__init__.py | HTML2Text.previousIndex | (self, attrs: Dict[str, Optional[str]]) | return None | :type attrs: dict
:returns: The index of certain set of attributes (of a link) in the
self.a list. If the set of attributes is not found, returns None
:rtype: int | :type attrs: dict | 199 | 225 | def previousIndex(self, attrs: Dict[str, Optional[str]]) -> Optional[int]:
"""
:type attrs: dict
:returns: The index of certain set of attributes (of a link) in the
self.a list. If the set of attributes is not found, returns None
:rtype: int
"""
if "href" not in attrs:
return None
match = False
for i, a in enumerate(self.a):
if "href" in a.attrs and a.attrs["href"] == attrs["href"]:
if "title" in a.attrs or "title" in attrs:
if (
"title" in a.attrs
and "title" in attrs
and a.attrs["title"] == attrs["title"]
):
match = True
else:
match = True
if match:
return i
return None | https://github.com/Alir3z4/html2text/blob/a3ed67b69160746b03a5861bf5c1b7a5ba76a4e1/project48/html2text/__init__.py#L199-L225 | 48 | [
0,
1,
2,
3,
4,
5,
6,
7,
8,
10,
11,
12,
13,
14,
15,
16,
17,
18,
19,
20,
21,
22,
23,
24,
25,
26
] | 96.296296 | [
9
] | 3.703704 | false | 97.322835 | 27 | 11 | 96.296296 | 5 | def previousIndex(self, attrs: Dict[str, Optional[str]]) -> Optional[int]:
if "href" not in attrs:
return None
match = False
for i, a in enumerate(self.a):
if "href" in a.attrs and a.attrs["href"] == attrs["href"]:
if "title" in a.attrs or "title" in attrs:
if (
"title" in a.attrs
and "title" in attrs
and a.attrs["title"] == attrs["title"]
):
match = True
else:
match = True
if match:
return i
return None | 29,753 |
Alir3z4/html2text | a3ed67b69160746b03a5861bf5c1b7a5ba76a4e1 | html2text/__init__.py | HTML2Text.handle_emphasis | (
self, start: bool, tag_style: Dict[str, str], parent_style: Dict[str, str]
) | Handles various text emphases | Handles various text emphases | 227 | 298 | def handle_emphasis(
self, start: bool, tag_style: Dict[str, str], parent_style: Dict[str, str]
) -> None:
"""
Handles various text emphases
"""
tag_emphasis = google_text_emphasis(tag_style)
parent_emphasis = google_text_emphasis(parent_style)
# handle Google's text emphasis
strikethrough = "line-through" in tag_emphasis and self.hide_strikethrough
# google and others may mark a font's weight as `bold` or `700`
bold = False
for bold_marker in config.BOLD_TEXT_STYLE_VALUES:
bold = bold_marker in tag_emphasis and bold_marker not in parent_emphasis
if bold:
break
italic = "italic" in tag_emphasis and "italic" not in parent_emphasis
fixed = (
google_fixed_width_font(tag_style)
and not google_fixed_width_font(parent_style)
and not self.pre
)
if start:
# crossed-out text must be handled before other attributes
# in order not to output qualifiers unnecessarily
if bold or italic or fixed:
self.emphasis += 1
if strikethrough:
self.quiet += 1
if italic:
self.o(self.emphasis_mark)
self.drop_white_space += 1
if bold:
self.o(self.strong_mark)
self.drop_white_space += 1
if fixed:
self.o("`")
self.drop_white_space += 1
self.code = True
else:
if bold or italic or fixed:
# there must not be whitespace before closing emphasis mark
self.emphasis -= 1
self.space = False
if fixed:
if self.drop_white_space:
# empty emphasis, drop it
self.drop_white_space -= 1
else:
self.o("`")
self.code = False
if bold:
if self.drop_white_space:
# empty emphasis, drop it
self.drop_white_space -= 1
else:
self.o(self.strong_mark)
if italic:
if self.drop_white_space:
# empty emphasis, drop it
self.drop_white_space -= 1
else:
self.o(self.emphasis_mark)
# space is only allowed after *all* emphasis marks
if (bold or italic) and not self.emphasis:
self.o(" ")
if strikethrough:
self.quiet -= 1 | https://github.com/Alir3z4/html2text/blob/a3ed67b69160746b03a5861bf5c1b7a5ba76a4e1/project48/html2text/__init__.py#L227-L298 | 48 | [
0,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
16,
17,
18,
19,
20,
21,
22,
23,
24,
25,
26,
27,
28,
29,
30,
31,
32,
33,
34,
35,
36,
37,
38,
39,
40,
41,
42,
43,
44,
45,
46,
47,
48,
49,
50,
51,
52,
53,
54,
55,
56,
57,
58,
59,
60,
61,
62,
63,
64,
65,
66,
67,
68,
69,
70,
71
] | 94.444444 | [] | 0 | false | 97.322835 | 72 | 29 | 100 | 1 | def handle_emphasis(
self, start: bool, tag_style: Dict[str, str], parent_style: Dict[str, str]
) -> None:
tag_emphasis = google_text_emphasis(tag_style)
parent_emphasis = google_text_emphasis(parent_style)
# handle Google's text emphasis
strikethrough = "line-through" in tag_emphasis and self.hide_strikethrough
# google and others may mark a font's weight as `bold` or `700`
bold = False
for bold_marker in config.BOLD_TEXT_STYLE_VALUES:
bold = bold_marker in tag_emphasis and bold_marker not in parent_emphasis
if bold:
break
italic = "italic" in tag_emphasis and "italic" not in parent_emphasis
fixed = (
google_fixed_width_font(tag_style)
and not google_fixed_width_font(parent_style)
and not self.pre
)
if start:
# crossed-out text must be handled before other attributes
# in order not to output qualifiers unnecessarily
if bold or italic or fixed:
self.emphasis += 1
if strikethrough:
self.quiet += 1
if italic:
self.o(self.emphasis_mark)
self.drop_white_space += 1
if bold:
self.o(self.strong_mark)
self.drop_white_space += 1
if fixed:
self.o("`")
self.drop_white_space += 1
self.code = True
else:
if bold or italic or fixed:
# there must not be whitespace before closing emphasis mark
self.emphasis -= 1
self.space = False
if fixed:
if self.drop_white_space:
# empty emphasis, drop it
self.drop_white_space -= 1
else:
self.o("`")
self.code = False
if bold:
if self.drop_white_space:
# empty emphasis, drop it
self.drop_white_space -= 1
else:
self.o(self.strong_mark)
if italic:
if self.drop_white_space:
# empty emphasis, drop it
self.drop_white_space -= 1
else:
self.o(self.emphasis_mark)
# space is only allowed after *all* emphasis marks
if (bold or italic) and not self.emphasis:
self.o(" ")
if strikethrough:
self.quiet -= 1 | 29,754 |
|
Alir3z4/html2text | a3ed67b69160746b03a5861bf5c1b7a5ba76a4e1 | html2text/__init__.py | HTML2Text.handle_tag | (
self, tag: str, attrs: Dict[str, Optional[str]], start: bool
) | 300 | 721 | def handle_tag(
self, tag: str, attrs: Dict[str, Optional[str]], start: bool
) -> None:
self.current_tag = tag
if self.tag_callback is not None:
if self.tag_callback(self, tag, attrs, start) is True:
return
# first thing inside the anchor tag is another tag
# that produces some output
if (
start
and self.maybe_automatic_link is not None
and tag not in ["p", "div", "style", "dl", "dt"]
and (tag != "img" or self.ignore_images)
):
self.o("[")
self.maybe_automatic_link = None
self.empty_link = False
if self.google_doc:
# the attrs parameter is empty for a closing tag. in addition, we
# need the attributes of the parent nodes in order to get a
# complete style description for the current element. we assume
# that google docs export well formed html.
parent_style = {} # type: Dict[str, str]
if start:
if self.tag_stack:
parent_style = self.tag_stack[-1][2]
tag_style = element_style(attrs, self.style_def, parent_style)
self.tag_stack.append((tag, attrs, tag_style))
else:
dummy, attrs, tag_style = (
self.tag_stack.pop() if self.tag_stack else (None, {}, {})
)
if self.tag_stack:
parent_style = self.tag_stack[-1][2]
if hn(tag):
# check if nh is inside of an 'a' tag (incorrect but found in the wild)
if self.astack:
if start:
self.inheader = True
# are inside link name, so only add '#' if it can appear before '['
if self.outtextlist and self.outtextlist[-1] == "[":
self.outtextlist.pop()
self.space = False
self.o(hn(tag) * "#" + " ")
self.o("[")
else:
self.p_p = 0 # don't break up link name
self.inheader = False
return # prevent redundant emphasis marks on headers
else:
self.p()
if start:
self.inheader = True
self.o(hn(tag) * "#" + " ")
else:
self.inheader = False
return # prevent redundant emphasis marks on headers
if tag in ["p", "div"]:
if self.google_doc:
if start and google_has_height(tag_style):
self.p()
else:
self.soft_br()
elif self.astack:
pass
else:
self.p()
if tag == "br" and start:
if self.astack:
self.space = True
elif self.blockquote > 0:
self.o(" \n> ")
else:
self.o(" \n")
if tag == "hr" and start:
self.p()
self.o("* * *")
self.p()
if tag in ["head", "style", "script"]:
if start:
self.quiet += 1
else:
self.quiet -= 1
if tag == "style":
if start:
self.style += 1
else:
self.style -= 1
if tag in ["body"]:
self.quiet = 0 # sites like 9rules.com never close <head>
if tag == "blockquote":
if start:
self.p()
self.o("> ", force=True)
self.start = True
self.blockquote += 1
else:
self.blockquote -= 1
self.p()
if tag in ["em", "i", "u"] and not self.ignore_emphasis:
# Separate with a space if we immediately follow an alphanumeric
# character, since otherwise Markdown won't render the emphasis
# marks, and we'll be left with eg 'foo_bar_' visible.
# (Don't add a space otherwise, though, since there isn't one in the
# original HTML.)
if (
start
and self.preceding_data
and self.preceding_data[-1] not in string.whitespace
and self.preceding_data[-1] not in string.punctuation
):
emphasis = " " + self.emphasis_mark
self.preceding_data += " "
else:
emphasis = self.emphasis_mark
self.o(emphasis)
if start:
self.stressed = True
if tag in ["strong", "b"] and not self.ignore_emphasis:
# Separate with space if we immediately follow an * character, since
# without it, Markdown won't render the resulting *** correctly.
# (Don't add a space otherwise, though, since there isn't one in the
# original HTML.)
if (
start
and self.preceding_data
and self.preceding_data[-1] == self.strong_mark[0]
):
strong = " " + self.strong_mark
self.preceding_data += " "
else:
strong = self.strong_mark
self.o(strong)
if start:
self.stressed = True
if tag in ["del", "strike", "s"]:
if start and self.preceding_data and self.preceding_data[-1] == "~":
strike = " ~~"
self.preceding_data += " "
else:
strike = "~~"
self.o(strike)
if start:
self.stressed = True
if self.google_doc:
if not self.inheader:
# handle some font attributes, but leave headers clean
self.handle_emphasis(start, tag_style, parent_style)
if tag in ["kbd", "code", "tt"] and not self.pre:
self.o("`") # TODO: `` `this` ``
self.code = not self.code
if tag == "abbr":
if start:
self.abbr_title = None
self.abbr_data = ""
if "title" in attrs:
self.abbr_title = attrs["title"]
else:
if self.abbr_title is not None:
assert self.abbr_data is not None
self.abbr_list[self.abbr_data] = self.abbr_title
self.abbr_title = None
self.abbr_data = None
if tag == "q":
if not self.quote:
self.o(self.open_quote)
else:
self.o(self.close_quote)
self.quote = not self.quote
def link_url(self: HTML2Text, link: str, title: str = "") -> None:
url = urlparse.urljoin(self.baseurl, link)
title = ' "{}"'.format(title) if title.strip() else ""
self.o("]({url}{title})".format(url=escape_md(url), title=title))
if tag == "a" and not self.ignore_links:
if start:
if (
"href" in attrs
and attrs["href"] is not None
and not (self.skip_internal_links and attrs["href"].startswith("#"))
and not (
self.ignore_mailto_links and attrs["href"].startswith("mailto:")
)
):
self.astack.append(attrs)
self.maybe_automatic_link = attrs["href"]
self.empty_link = True
if self.protect_links:
attrs["href"] = "<" + attrs["href"] + ">"
else:
self.astack.append(None)
else:
if self.astack:
a = self.astack.pop()
if self.maybe_automatic_link and not self.empty_link:
self.maybe_automatic_link = None
elif a:
assert a["href"] is not None
if self.empty_link:
self.o("[")
self.empty_link = False
self.maybe_automatic_link = None
if self.inline_links:
self.p_p = 0
title = a.get("title") or ""
title = escape_md(title)
link_url(self, a["href"], title)
else:
i = self.previousIndex(a)
if i is not None:
a_props = self.a[i]
else:
self.acount += 1
a_props = AnchorElement(a, self.acount, self.outcount)
self.a.append(a_props)
self.o("][" + str(a_props.count) + "]")
if tag == "img" and start and not self.ignore_images:
if "src" in attrs:
assert attrs["src"] is not None
if not self.images_to_alt:
attrs["href"] = attrs["src"]
alt = attrs.get("alt") or self.default_image_alt
# If we have images_with_size, write raw html including width,
# height, and alt attributes
if self.images_as_html or (
self.images_with_size and ("width" in attrs or "height" in attrs)
):
self.o("<img src='" + attrs["src"] + "' ")
if "width" in attrs:
assert attrs["width"] is not None
self.o("width='" + attrs["width"] + "' ")
if "height" in attrs:
assert attrs["height"] is not None
self.o("height='" + attrs["height"] + "' ")
if alt:
self.o("alt='" + alt + "' ")
self.o("/>")
return
# If we have a link to create, output the start
if self.maybe_automatic_link is not None:
href = self.maybe_automatic_link
if (
self.images_to_alt
and escape_md(alt) == href
and self.absolute_url_matcher.match(href)
):
self.o("<" + escape_md(alt) + ">")
self.empty_link = False
return
else:
self.o("[")
self.maybe_automatic_link = None
self.empty_link = False
# If we have images_to_alt, we discard the image itself,
# considering only the alt text.
if self.images_to_alt:
self.o(escape_md(alt))
else:
self.o("![" + escape_md(alt) + "]")
if self.inline_links:
href = attrs.get("href") or ""
self.o(
"(" + escape_md(urlparse.urljoin(self.baseurl, href)) + ")"
)
else:
i = self.previousIndex(attrs)
if i is not None:
a_props = self.a[i]
else:
self.acount += 1
a_props = AnchorElement(attrs, self.acount, self.outcount)
self.a.append(a_props)
self.o("[" + str(a_props.count) + "]")
if tag == "dl" and start:
self.p()
if tag == "dt" and not start:
self.pbr()
if tag == "dd" and start:
self.o(" ")
if tag == "dd" and not start:
self.pbr()
if tag in ["ol", "ul"]:
# Google Docs create sub lists as top level lists
if not self.list and not self.lastWasList:
self.p()
if start:
if self.google_doc:
list_style = google_list_style(tag_style)
else:
list_style = tag
numbering_start = list_numbering_start(attrs)
self.list.append(ListElement(list_style, numbering_start))
else:
if self.list:
self.list.pop()
if not self.google_doc and not self.list:
self.o("\n")
self.lastWasList = True
else:
self.lastWasList = False
if tag == "li":
self.pbr()
if start:
if self.list:
li = self.list[-1]
else:
li = ListElement("ul", 0)
if self.google_doc:
self.o(" " * self.google_nest_count(tag_style))
else:
# Indent two spaces per list, except use three spaces for an
# unordered list inside an ordered list.
# https://spec.commonmark.org/0.28/#motivation
# TODO: line up <ol><li>s > 9 correctly.
parent_list = None
for list in self.list:
self.o(
" " if parent_list == "ol" and list.name == "ul" else " "
)
parent_list = list.name
if li.name == "ul":
self.o(self.ul_item_mark + " ")
elif li.name == "ol":
li.num += 1
self.o(str(li.num) + ". ")
self.start = True
if tag in ["table", "tr", "td", "th"]:
if self.ignore_tables:
if tag == "tr":
if start:
pass
else:
self.soft_br()
else:
pass
elif self.bypass_tables:
if start:
self.soft_br()
if tag in ["td", "th"]:
if start:
self.o("<{}>\n\n".format(tag))
else:
self.o("\n</{}>".format(tag))
else:
if start:
self.o("<{}>".format(tag))
else:
self.o("</{}>".format(tag))
else:
if tag == "table":
if start:
self.table_start = True
if self.pad_tables:
self.o("<" + config.TABLE_MARKER_FOR_PAD + ">")
self.o(" \n")
else:
if self.pad_tables:
# add break in case the table is empty or its 1 row table
self.soft_br()
self.o("</" + config.TABLE_MARKER_FOR_PAD + ">")
self.o(" \n")
if tag in ["td", "th"] and start:
if self.split_next_td:
self.o("| ")
self.split_next_td = True
if tag == "tr" and start:
self.td_count = 0
if tag == "tr" and not start:
self.split_next_td = False
self.soft_br()
if tag == "tr" and not start and self.table_start:
# Underline table header
self.o("|".join(["---"] * self.td_count))
self.soft_br()
self.table_start = False
if tag in ["td", "th"] and start:
self.td_count += 1
if tag == "pre":
if start:
self.startpre = True
self.pre = True
else:
self.pre = False
if self.mark_code:
self.out("\n[/code]")
self.p() | https://github.com/Alir3z4/html2text/blob/a3ed67b69160746b03a5861bf5c1b7a5ba76a4e1/project48/html2text/__init__.py#L300-L721 | 48 | [
0,
3,
4,
5,
6,
7,
8,
9,
10,
11,
17,
18,
19,
20,
21,
22,
23,
24,
25,
26,
27,
28,
29,
30,
31,
33,
36,
37,
38,
39,
40,
41,
55,
56,
57,
58,
60,
61,
62,
63,
64,
65,
66,
68,
69,
70,
72,
73,
74,
75,
76,
77,
78,
80,
81,
82,
83,
84,
85,
86,
87,
88,
89,
91,
92,
93,
94,
95,
97,
98,
99,
100,
101,
102,
103,
104,
105,
106,
107,
109,
110,
111,
112,
113,
114,
115,
116,
117,
118,
124,
125,
127,
128,
129,
130,
131,
132,
133,
134,
135,
136,
137,
138,
143,
144,
146,
147,
148,
149,
150,
151,
152,
153,
154,
155,
157,
158,
159,
160,
161,
162,
163,
164,
165,
166,
167,
168,
169,
170,
171,
172,
173,
174,
175,
176,
177,
179,
180,
181,
182,
183,
184,
185,
186,
187,
189,
190,
191,
192,
193,
194,
195,
196,
197,
198,
199,
207,
208,
209,
210,
211,
213,
215,
216,
217,
218,
219,
220,
221,
222,
223,
224,
225,
226,
227,
228,
229,
231,
232,
233,
235,
236,
237,
238,
239,
240,
241,
242,
243,
244,
245,
246,
247,
248,
249,
252,
253,
254,
255,
256,
257,
258,
259,
260,
261,
262,
263,
264,
265,
266,
267,
272,
273,
274,
276,
277,
278,
279,
280,
281,
282,
283,
285,
286,
287,
288,
292,
293,
294,
296,
297,
298,
299,
300,
301,
302,
303,
304,
305,
306,
307,
308,
309,
310,
311,
312,
313,
314,
315,
316,
318,
319,
320,
322,
323,
324,
325,
326,
328,
329,
330,
331,
332,
333,
334,
337,
338,
343,
344,
345,
346,
349,
350,
351,
352,
353,
354,
355,
356,
357,
358,
359,
360,
361,
362,
364,
366,
367,
368,
369,
370,
371,
372,
373,
375,
377,
378,
380,
381,
383,
384,
385,
386,
387,
388,
390,
391,
392,
393,
394,
395,
396,
397,
398,
399,
400,
401,
402,
403,
404,
405,
406,
407,
408,
409,
410,
411,
412,
413,
414,
415,
416,
418,
419,
420,
421
] | 79.620853 | [
42,
43,
45,
46,
47,
48,
49,
51,
52,
53,
336
] | 2.606635 | false | 97.322835 | 422 | 161 | 97.393365 | 0 | def handle_tag(
self, tag: str, attrs: Dict[str, Optional[str]], start: bool
) -> None:
self.current_tag = tag
if self.tag_callback is not None:
if self.tag_callback(self, tag, attrs, start) is True:
return
# first thing inside the anchor tag is another tag
# that produces some output
if (
start
and self.maybe_automatic_link is not None
and tag not in ["p", "div", "style", "dl", "dt"]
and (tag != "img" or self.ignore_images)
):
self.o("[")
self.maybe_automatic_link = None
self.empty_link = False
if self.google_doc:
# the attrs parameter is empty for a closing tag. in addition, we
# need the attributes of the parent nodes in order to get a
# complete style description for the current element. we assume
# that google docs export well formed html.
parent_style = {} # type: Dict[str, str]
if start:
if self.tag_stack:
parent_style = self.tag_stack[-1][2]
tag_style = element_style(attrs, self.style_def, parent_style)
self.tag_stack.append((tag, attrs, tag_style))
else:
dummy, attrs, tag_style = (
self.tag_stack.pop() if self.tag_stack else (None, {}, {})
)
if self.tag_stack:
parent_style = self.tag_stack[-1][2]
if hn(tag):
# check if nh is inside of an 'a' tag (incorrect but found in the wild)
if self.astack:
if start:
self.inheader = True
# are inside link name, so only add '#' if it can appear before '['
if self.outtextlist and self.outtextlist[-1] == "[":
self.outtextlist.pop()
self.space = False
self.o(hn(tag) * "#" + " ")
self.o("[")
else:
self.p_p = 0 # don't break up link name
self.inheader = False
return # prevent redundant emphasis marks on headers
else:
self.p()
if start:
self.inheader = True
self.o(hn(tag) * "#" + " ")
else:
self.inheader = False
return # prevent redundant emphasis marks on headers
if tag in ["p", "div"]:
if self.google_doc:
if start and google_has_height(tag_style):
self.p()
else:
self.soft_br()
elif self.astack:
pass
else:
self.p()
if tag == "br" and start:
if self.astack:
self.space = True
elif self.blockquote > 0:
self.o(" \n> ")
else:
self.o(" \n")
if tag == "hr" and start:
self.p()
self.o("* * *")
self.p()
if tag in ["head", "style", "script"]:
if start:
self.quiet += 1
else:
self.quiet -= 1
if tag == "style":
if start:
self.style += 1
else:
self.style -= 1
if tag in ["body"]:
self.quiet = 0 # sites like 9rules.com never close <head>
if tag == "blockquote":
if start:
self.p()
self.o("> ", force=True)
self.start = True
self.blockquote += 1
else:
self.blockquote -= 1
self.p()
if tag in ["em", "i", "u"] and not self.ignore_emphasis:
# Separate with a space if we immediately follow an alphanumeric
# character, since otherwise Markdown won't render the emphasis
# marks, and we'll be left with eg 'foo_bar_' visible.
# (Don't add a space otherwise, though, since there isn't one in the
# original HTML.)
if (
start
and self.preceding_data
and self.preceding_data[-1] not in string.whitespace
and self.preceding_data[-1] not in string.punctuation
):
emphasis = " " + self.emphasis_mark
self.preceding_data += " "
else:
emphasis = self.emphasis_mark
self.o(emphasis)
if start:
self.stressed = True
if tag in ["strong", "b"] and not self.ignore_emphasis:
# Separate with space if we immediately follow an * character, since
# without it, Markdown won't render the resulting *** correctly.
# (Don't add a space otherwise, though, since there isn't one in the
# original HTML.)
if (
start
and self.preceding_data
and self.preceding_data[-1] == self.strong_mark[0]
):
strong = " " + self.strong_mark
self.preceding_data += " "
else:
strong = self.strong_mark
self.o(strong)
if start:
self.stressed = True
if tag in ["del", "strike", "s"]:
if start and self.preceding_data and self.preceding_data[-1] == "~":
strike = " ~~"
self.preceding_data += " "
else:
strike = "~~"
self.o(strike)
if start:
self.stressed = True
if self.google_doc:
if not self.inheader:
# handle some font attributes, but leave headers clean
self.handle_emphasis(start, tag_style, parent_style)
if tag in ["kbd", "code", "tt"] and not self.pre:
self.o("`") # TODO: `` `this` ``
self.code = not self.code
if tag == "abbr":
if start:
self.abbr_title = None
self.abbr_data = ""
if "title" in attrs:
self.abbr_title = attrs["title"]
else:
if self.abbr_title is not None:
assert self.abbr_data is not None
self.abbr_list[self.abbr_data] = self.abbr_title
self.abbr_title = None
self.abbr_data = None
if tag == "q":
if not self.quote:
self.o(self.open_quote)
else:
self.o(self.close_quote)
self.quote = not self.quote
def link_url(self: HTML2Text, link: str, title: str = "") -> None:
url = urlparse.urljoin(self.baseurl, link)
title = ' "{}"'.format(title) if title.strip() else ""
self.o("]({url}{title})".format(url=escape_md(url), title=title))
if tag == "a" and not self.ignore_links:
if start:
if (
"href" in attrs
and attrs["href"] is not None
and not (self.skip_internal_links and attrs["href"].startswith("#"))
and not (
self.ignore_mailto_links and attrs["href"].startswith("mailto:")
)
):
self.astack.append(attrs)
self.maybe_automatic_link = attrs["href"]
self.empty_link = True
if self.protect_links:
attrs["href"] = "<" + attrs["href"] + ">"
else:
self.astack.append(None)
else:
if self.astack:
a = self.astack.pop()
if self.maybe_automatic_link and not self.empty_link:
self.maybe_automatic_link = None
elif a:
assert a["href"] is not None
if self.empty_link:
self.o("[")
self.empty_link = False
self.maybe_automatic_link = None
if self.inline_links:
self.p_p = 0
title = a.get("title") or ""
title = escape_md(title)
link_url(self, a["href"], title)
else:
i = self.previousIndex(a)
if i is not None:
a_props = self.a[i]
else:
self.acount += 1
a_props = AnchorElement(a, self.acount, self.outcount)
self.a.append(a_props)
self.o("][" + str(a_props.count) + "]")
if tag == "img" and start and not self.ignore_images:
if "src" in attrs:
assert attrs["src"] is not None
if not self.images_to_alt:
attrs["href"] = attrs["src"]
alt = attrs.get("alt") or self.default_image_alt
# If we have images_with_size, write raw html including width,
# height, and alt attributes
if self.images_as_html or (
self.images_with_size and ("width" in attrs or "height" in attrs)
):
self.o("<img src='" + attrs["src"] + "' ")
if "width" in attrs:
assert attrs["width"] is not None
self.o("width='" + attrs["width"] + "' ")
if "height" in attrs:
assert attrs["height"] is not None
self.o("height='" + attrs["height"] + "' ")
if alt:
self.o("alt='" + alt + "' ")
self.o("/>")
return
# If we have a link to create, output the start
if self.maybe_automatic_link is not None:
href = self.maybe_automatic_link
if (
self.images_to_alt
and escape_md(alt) == href
and self.absolute_url_matcher.match(href)
):
self.o("<" + escape_md(alt) + ">")
self.empty_link = False
return
else:
self.o("[")
self.maybe_automatic_link = None
self.empty_link = False
# If we have images_to_alt, we discard the image itself,
# considering only the alt text.
if self.images_to_alt:
self.o(escape_md(alt))
else:
self.o("![" + escape_md(alt) + "]")
if self.inline_links:
href = attrs.get("href") or ""
self.o(
"(" + escape_md(urlparse.urljoin(self.baseurl, href)) + ")"
)
else:
i = self.previousIndex(attrs)
if i is not None:
a_props = self.a[i]
else:
self.acount += 1
a_props = AnchorElement(attrs, self.acount, self.outcount)
self.a.append(a_props)
self.o("[" + str(a_props.count) + "]")
if tag == "dl" and start:
self.p()
if tag == "dt" and not start:
self.pbr()
if tag == "dd" and start:
self.o(" ")
if tag == "dd" and not start:
self.pbr()
if tag in ["ol", "ul"]:
# Google Docs create sub lists as top level lists
if not self.list and not self.lastWasList:
self.p()
if start:
if self.google_doc:
list_style = google_list_style(tag_style)
else:
list_style = tag
numbering_start = list_numbering_start(attrs)
self.list.append(ListElement(list_style, numbering_start))
else:
if self.list:
self.list.pop()
if not self.google_doc and not self.list:
self.o("\n")
self.lastWasList = True
else:
self.lastWasList = False
if tag == "li":
self.pbr()
if start:
if self.list:
li = self.list[-1]
else:
li = ListElement("ul", 0)
if self.google_doc:
self.o(" " * self.google_nest_count(tag_style))
else:
# Indent two spaces per list, except use three spaces for an
# unordered list inside an ordered list.
# https://spec.commonmark.org/0.28/#motivation
# TODO: line up <ol><li>s > 9 correctly.
parent_list = None
for list in self.list:
self.o(
" " if parent_list == "ol" and list.name == "ul" else " "
)
parent_list = list.name
if li.name == "ul":
self.o(self.ul_item_mark + " ")
elif li.name == "ol":
li.num += 1
self.o(str(li.num) + ". ")
self.start = True
if tag in ["table", "tr", "td", "th"]:
if self.ignore_tables:
if tag == "tr":
if start:
pass
else:
self.soft_br()
else:
pass
elif self.bypass_tables:
if start:
self.soft_br()
if tag in ["td", "th"]:
if start:
self.o("<{}>\n\n".format(tag))
else:
self.o("\n</{}>".format(tag))
else:
if start:
self.o("<{}>".format(tag))
else:
self.o("</{}>".format(tag))
else:
if tag == "table":
if start:
self.table_start = True
if self.pad_tables:
self.o("<" + config.TABLE_MARKER_FOR_PAD + ">")
self.o(" \n")
else:
if self.pad_tables:
# add break in case the table is empty or its 1 row table
self.soft_br()
self.o("</" + config.TABLE_MARKER_FOR_PAD + ">")
self.o(" \n")
if tag in ["td", "th"] and start:
if self.split_next_td:
self.o("| ")
self.split_next_td = True
if tag == "tr" and start:
self.td_count = 0
if tag == "tr" and not start:
self.split_next_td = False
self.soft_br()
if tag == "tr" and not start and self.table_start:
# Underline table header
self.o("|".join(["---"] * self.td_count))
self.soft_br()
self.table_start = False
if tag in ["td", "th"] and start:
self.td_count += 1
if tag == "pre":
if start:
self.startpre = True
self.pre = True
else:
self.pre = False
if self.mark_code:
self.out("\n[/code]")
self.p() | 29,755 |
|||
Alir3z4/html2text | a3ed67b69160746b03a5861bf5c1b7a5ba76a4e1 | html2text/__init__.py | HTML2Text.pbr | (self) | Pretty print has a line break | Pretty print has a line break | 724 | 727 | def pbr(self) -> None:
"Pretty print has a line break"
if self.p_p == 0:
self.p_p = 1 | https://github.com/Alir3z4/html2text/blob/a3ed67b69160746b03a5861bf5c1b7a5ba76a4e1/project48/html2text/__init__.py#L724-L727 | 48 | [
0,
2,
3
] | 75 | [] | 0 | false | 97.322835 | 4 | 2 | 100 | 1 | def pbr(self) -> None:
"Pretty print has a line break"
if self.p_p == 0:
self.p_p = 1 | 29,756 |
|
Alir3z4/html2text | a3ed67b69160746b03a5861bf5c1b7a5ba76a4e1 | html2text/__init__.py | HTML2Text.p | (self) | Set pretty print to 1 or 2 lines | Set pretty print to 1 or 2 lines | 729 | 731 | def p(self) -> None:
"Set pretty print to 1 or 2 lines"
self.p_p = 1 if self.single_line_break else 2 | https://github.com/Alir3z4/html2text/blob/a3ed67b69160746b03a5861bf5c1b7a5ba76a4e1/project48/html2text/__init__.py#L729-L731 | 48 | [
0,
2
] | 66.666667 | [] | 0 | false | 97.322835 | 3 | 1 | 100 | 1 | def p(self) -> None:
"Set pretty print to 1 or 2 lines"
self.p_p = 1 if self.single_line_break else 2 | 29,757 |
|
Alir3z4/html2text | a3ed67b69160746b03a5861bf5c1b7a5ba76a4e1 | html2text/__init__.py | HTML2Text.soft_br | (self) | Soft breaks | Soft breaks | 733 | 736 | def soft_br(self) -> None:
"Soft breaks"
self.pbr()
self.br_toggle = " " | https://github.com/Alir3z4/html2text/blob/a3ed67b69160746b03a5861bf5c1b7a5ba76a4e1/project48/html2text/__init__.py#L733-L736 | 48 | [
0,
2,
3
] | 75 | [] | 0 | false | 97.322835 | 4 | 1 | 100 | 1 | def soft_br(self) -> None:
"Soft breaks"
self.pbr()
self.br_toggle = " " | 29,758 |
|
Alir3z4/html2text | a3ed67b69160746b03a5861bf5c1b7a5ba76a4e1 | html2text/__init__.py | HTML2Text.o | (
self, data: str, puredata: bool = False, force: Union[bool, str] = False
) | Deal with indentation and whitespace | Deal with indentation and whitespace | 738 | 849 | def o(
self, data: str, puredata: bool = False, force: Union[bool, str] = False
) -> None:
"""
Deal with indentation and whitespace
"""
if self.abbr_data is not None:
self.abbr_data += data
if not self.quiet:
if self.google_doc:
# prevent white space immediately after 'begin emphasis'
# marks ('**' and '_')
lstripped_data = data.lstrip()
if self.drop_white_space and not (self.pre or self.code):
data = lstripped_data
if lstripped_data != "":
self.drop_white_space = 0
if puredata and not self.pre:
# This is a very dangerous call ... it could mess up
# all handling of when not handled properly
# (see entityref)
data = re.sub(r"\s+", r" ", data)
if data and data[0] == " ":
self.space = True
data = data[1:]
if not data and not force:
return
if self.startpre:
# self.out(" :") #TODO: not output when already one there
if not data.startswith("\n") and not data.startswith("\r\n"):
# <pre>stuff...
data = "\n" + data
if self.mark_code:
self.out("\n[code]")
self.p_p = 0
bq = ">" * self.blockquote
if not (force and data and data[0] == ">") and self.blockquote:
bq += " "
if self.pre:
if not self.list:
bq += " "
# else: list content is already partially indented
bq += " " * len(self.list)
data = data.replace("\n", "\n" + bq)
if self.startpre:
self.startpre = False
if self.list:
# use existing initial indentation
data = data.lstrip("\n")
if self.start:
self.space = False
self.p_p = 0
self.start = False
if force == "end":
# It's the end.
self.p_p = 0
self.out("\n")
self.space = False
if self.p_p:
self.out((self.br_toggle + "\n" + bq) * self.p_p)
self.space = False
self.br_toggle = ""
if self.space:
if not self.lastWasNL:
self.out(" ")
self.space = False
if self.a and (
(self.p_p == 2 and self.links_each_paragraph) or force == "end"
):
if force == "end":
self.out("\n")
newa = []
for link in self.a:
if self.outcount > link.outcount:
self.out(
" ["
+ str(link.count)
+ "]: "
+ urlparse.urljoin(self.baseurl, link.attrs["href"])
)
if "title" in link.attrs:
assert link.attrs["title"] is not None
self.out(" (" + link.attrs["title"] + ")")
self.out("\n")
else:
newa.append(link)
# Don't need an extra line when nothing was done.
if self.a != newa:
self.out("\n")
self.a = newa
if self.abbr_list and force == "end":
for abbr, definition in self.abbr_list.items():
self.out(" *[" + abbr + "]: " + definition + "\n")
self.p_p = 0
self.out(data)
self.outcount += 1 | https://github.com/Alir3z4/html2text/blob/a3ed67b69160746b03a5861bf5c1b7a5ba76a4e1/project48/html2text/__init__.py#L738-L849 | 48 | [
0,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
16,
17,
18,
19,
20,
21,
22,
23,
24,
25,
26,
27,
28,
29,
30,
31,
32,
33,
34,
35,
36,
37,
38,
39,
40,
41,
42,
43,
44,
45,
46,
47,
48,
49,
50,
51,
52,
53,
54,
55,
56,
57,
58,
59,
60,
61,
62,
63,
64,
65,
66,
67,
68,
69,
70,
71,
72,
73,
74,
75,
76,
77,
78,
79,
80,
81,
82,
83,
84,
85,
86,
87,
88,
89,
90,
91,
92,
93,
94,
95,
96,
99,
100,
101,
102,
103,
104,
105,
106,
107,
108,
109,
110,
111
] | 94.642857 | [
97
] | 0.892857 | false | 97.322835 | 112 | 44 | 99.107143 | 1 | def o(
self, data: str, puredata: bool = False, force: Union[bool, str] = False
) -> None:
if self.abbr_data is not None:
self.abbr_data += data
if not self.quiet:
if self.google_doc:
# prevent white space immediately after 'begin emphasis'
# marks ('**' and '_')
lstripped_data = data.lstrip()
if self.drop_white_space and not (self.pre or self.code):
data = lstripped_data
if lstripped_data != "":
self.drop_white_space = 0
if puredata and not self.pre:
# This is a very dangerous call ... it could mess up
# all handling of when not handled properly
# (see entityref)
data = re.sub(r"\s+", r" ", data)
if data and data[0] == " ":
self.space = True
data = data[1:]
if not data and not force:
return
if self.startpre:
# self.out(" :") #TODO: not output when already one there
if not data.startswith("\n") and not data.startswith("\r\n"):
# <pre>stuff...
data = "\n" + data
if self.mark_code:
self.out("\n[code]")
self.p_p = 0
bq = ">" * self.blockquote
if not (force and data and data[0] == ">") and self.blockquote:
bq += " "
if self.pre:
if not self.list:
bq += " "
# else: list content is already partially indented
bq += " " * len(self.list)
data = data.replace("\n", "\n" + bq)
if self.startpre:
self.startpre = False
if self.list:
# use existing initial indentation
data = data.lstrip("\n")
if self.start:
self.space = False
self.p_p = 0
self.start = False
if force == "end":
# It's the end.
self.p_p = 0
self.out("\n")
self.space = False
if self.p_p:
self.out((self.br_toggle + "\n" + bq) * self.p_p)
self.space = False
self.br_toggle = ""
if self.space:
if not self.lastWasNL:
self.out(" ")
self.space = False
if self.a and (
(self.p_p == 2 and self.links_each_paragraph) or force == "end"
):
if force == "end":
self.out("\n")
newa = []
for link in self.a:
if self.outcount > link.outcount:
self.out(
" ["
+ str(link.count)
+ "]: "
+ urlparse.urljoin(self.baseurl, link.attrs["href"])
)
if "title" in link.attrs:
assert link.attrs["title"] is not None
self.out(" (" + link.attrs["title"] + ")")
self.out("\n")
else:
newa.append(link)
# Don't need an extra line when nothing was done.
if self.a != newa:
self.out("\n")
self.a = newa
if self.abbr_list and force == "end":
for abbr, definition in self.abbr_list.items():
self.out(" *[" + abbr + "]: " + definition + "\n")
self.p_p = 0
self.out(data)
self.outcount += 1 | 29,759 |
|
Alir3z4/html2text | a3ed67b69160746b03a5861bf5c1b7a5ba76a4e1 | html2text/__init__.py | HTML2Text.handle_data | (self, data: str, entity_char: bool = False) | 851 | 892 | def handle_data(self, data: str, entity_char: bool = False) -> None:
if not data:
# Data may be empty for some HTML entities. For example,
# LEFT-TO-RIGHT MARK.
return
if self.stressed:
data = data.strip()
self.stressed = False
self.preceding_stressed = True
elif self.preceding_stressed:
if (
re.match(r"[^][(){}\s.!?]", data[0])
and not hn(self.current_tag)
and self.current_tag not in ["a", "code", "pre"]
):
# should match a letter or common punctuation
data = " " + data
self.preceding_stressed = False
if self.style:
self.style_def.update(dumb_css_parser(data))
if self.maybe_automatic_link is not None:
href = self.maybe_automatic_link
if (
href == data
and self.absolute_url_matcher.match(href)
and self.use_automatic_links
):
self.o("<" + data + ">")
self.empty_link = False
return
else:
self.o("[")
self.maybe_automatic_link = None
self.empty_link = False
if not self.code and not self.pre and not entity_char:
data = escape_md_section(data, snob=self.escape_snob)
self.preceding_data = data
self.o(data, puredata=True) | https://github.com/Alir3z4/html2text/blob/a3ed67b69160746b03a5861bf5c1b7a5ba76a4e1/project48/html2text/__init__.py#L851-L892 | 48 | [
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
16,
17,
18,
19,
20,
21,
22,
23,
24,
25,
30,
31,
32,
34,
35,
36,
37,
38,
39,
40,
41
] | 78.571429 | [] | 0 | false | 97.322835 | 42 | 15 | 100 | 0 | def handle_data(self, data: str, entity_char: bool = False) -> None:
if not data:
# Data may be empty for some HTML entities. For example,
# LEFT-TO-RIGHT MARK.
return
if self.stressed:
data = data.strip()
self.stressed = False
self.preceding_stressed = True
elif self.preceding_stressed:
if (
re.match(r"[^][(){}\s.!?]", data[0])
and not hn(self.current_tag)
and self.current_tag not in ["a", "code", "pre"]
):
# should match a letter or common punctuation
data = " " + data
self.preceding_stressed = False
if self.style:
self.style_def.update(dumb_css_parser(data))
if self.maybe_automatic_link is not None:
href = self.maybe_automatic_link
if (
href == data
and self.absolute_url_matcher.match(href)
and self.use_automatic_links
):
self.o("<" + data + ">")
self.empty_link = False
return
else:
self.o("[")
self.maybe_automatic_link = None
self.empty_link = False
if not self.code and not self.pre and not entity_char:
data = escape_md_section(data, snob=self.escape_snob)
self.preceding_data = data
self.o(data, puredata=True) | 29,760 |
|||
Alir3z4/html2text | a3ed67b69160746b03a5861bf5c1b7a5ba76a4e1 | html2text/__init__.py | HTML2Text.charref | (self, name: str) | 894 | 906 | def charref(self, name: str) -> str:
if name[0] in ["x", "X"]:
c = int(name[1:], 16)
else:
c = int(name)
if not self.unicode_snob and c in unifiable_n:
return unifiable_n[c]
else:
try:
return chr(c)
except ValueError: # invalid unicode
return "" | https://github.com/Alir3z4/html2text/blob/a3ed67b69160746b03a5861bf5c1b7a5ba76a4e1/project48/html2text/__init__.py#L894-L906 | 48 | [
0,
1,
4,
5,
6,
7,
9,
10,
11,
12
] | 76.923077 | [
2
] | 7.692308 | false | 97.322835 | 13 | 5 | 92.307692 | 0 | def charref(self, name: str) -> str:
if name[0] in ["x", "X"]:
c = int(name[1:], 16)
else:
c = int(name)
if not self.unicode_snob and c in unifiable_n:
return unifiable_n[c]
else:
try:
return chr(c)
except ValueError: # invalid unicode
return "" | 29,761 |
|||
Alir3z4/html2text | a3ed67b69160746b03a5861bf5c1b7a5ba76a4e1 | html2text/__init__.py | HTML2Text.entityref | (self, c: str) | return config.UNIFIABLE[c] if c == "nbsp" else ch | 908 | 915 | def entityref(self, c: str) -> str:
if not self.unicode_snob and c in config.UNIFIABLE:
return config.UNIFIABLE[c]
try:
ch = html.entities.html5[c + ";"]
except KeyError:
return "&" + c + ";"
return config.UNIFIABLE[c] if c == "nbsp" else ch | https://github.com/Alir3z4/html2text/blob/a3ed67b69160746b03a5861bf5c1b7a5ba76a4e1/project48/html2text/__init__.py#L908-L915 | 48 | [
0,
1,
2,
3,
4,
7
] | 75 | [
5,
6
] | 25 | false | 97.322835 | 8 | 4 | 75 | 0 | def entityref(self, c: str) -> str:
if not self.unicode_snob and c in config.UNIFIABLE:
return config.UNIFIABLE[c]
try:
ch = html.entities.html5[c + ";"]
except KeyError:
return "&" + c + ";"
return config.UNIFIABLE[c] if c == "nbsp" else ch | 29,762 |
||
Alir3z4/html2text | a3ed67b69160746b03a5861bf5c1b7a5ba76a4e1 | html2text/__init__.py | HTML2Text.google_nest_count | (self, style: Dict[str, str]) | return nest_count | Calculate the nesting count of google doc lists
:type style: dict
:rtype: int | Calculate the nesting count of google doc lists | 917 | 929 | def google_nest_count(self, style: Dict[str, str]) -> int:
"""
Calculate the nesting count of google doc lists
:type style: dict
:rtype: int
"""
nest_count = 0
if "margin-left" in style:
nest_count = int(style["margin-left"][:-2]) // self.google_list_indent
return nest_count | https://github.com/Alir3z4/html2text/blob/a3ed67b69160746b03a5861bf5c1b7a5ba76a4e1/project48/html2text/__init__.py#L917-L929 | 48 | [
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12
] | 100 | [] | 0 | true | 97.322835 | 13 | 2 | 100 | 5 | def google_nest_count(self, style: Dict[str, str]) -> int:
nest_count = 0
if "margin-left" in style:
nest_count = int(style["margin-left"][:-2]) // self.google_list_indent
return nest_count | 29,763 |
Alir3z4/html2text | a3ed67b69160746b03a5861bf5c1b7a5ba76a4e1 | html2text/__init__.py | HTML2Text.optwrap | (self, text: str) | return result | Wrap all paragraphs in the provided text.
:type text: str
:rtype: str | Wrap all paragraphs in the provided text. | 931 | 991 | def optwrap(self, text: str) -> str:
"""
Wrap all paragraphs in the provided text.
:type text: str
:rtype: str
"""
if not self.body_width:
return text
result = ""
newlines = 0
# I cannot think of a better solution for now.
# To avoid the non-wrap behaviour for entire paras
# because of the presence of a link in it
if not self.wrap_links:
self.inline_links = False
for para in text.split("\n"):
if len(para) > 0:
if not skipwrap(
para, self.wrap_links, self.wrap_list_items, self.wrap_tables
):
indent = ""
if para.startswith(" " + self.ul_item_mark):
# list item continuation: add a double indent to the
# new lines
indent = " "
elif para.startswith("> "):
# blockquote continuation: add the greater than symbol
# to the new lines
indent = "> "
wrapped = wrap(
para,
self.body_width,
break_long_words=False,
subsequent_indent=indent,
)
result += "\n".join(wrapped)
if para.endswith(" "):
result += " \n"
newlines = 1
elif indent:
result += "\n"
newlines = 1
else:
result += "\n\n"
newlines = 2
else:
# Warning for the tempted!!!
# Be aware that obvious replacement of this with
# line.isspace()
# DOES NOT work! Explanations are welcome.
if not config.RE_SPACE.match(para):
result += para + "\n"
newlines = 1
else:
if newlines < 2:
result += "\n"
newlines += 1
return result | https://github.com/Alir3z4/html2text/blob/a3ed67b69160746b03a5861bf5c1b7a5ba76a4e1/project48/html2text/__init__.py#L931-L991 | 48 | [
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
16,
17,
18,
19,
20,
21,
22,
23,
24,
25,
26,
27,
28,
29,
30,
31,
32,
33,
34,
35,
36,
37,
38,
39,
40,
41,
42,
43,
44,
45,
46,
47,
48,
49,
50,
51,
52,
53,
54,
55,
56,
57,
58,
59,
60
] | 100 | [] | 0 | true | 97.322835 | 61 | 12 | 100 | 5 | def optwrap(self, text: str) -> str:
if not self.body_width:
return text
result = ""
newlines = 0
# I cannot think of a better solution for now.
# To avoid the non-wrap behaviour for entire paras
# because of the presence of a link in it
if not self.wrap_links:
self.inline_links = False
for para in text.split("\n"):
if len(para) > 0:
if not skipwrap(
para, self.wrap_links, self.wrap_list_items, self.wrap_tables
):
indent = ""
if para.startswith(" " + self.ul_item_mark):
# list item continuation: add a double indent to the
# new lines
indent = " "
elif para.startswith("> "):
# blockquote continuation: add the greater than symbol
# to the new lines
indent = "> "
wrapped = wrap(
para,
self.body_width,
break_long_words=False,
subsequent_indent=indent,
)
result += "\n".join(wrapped)
if para.endswith(" "):
result += " \n"
newlines = 1
elif indent:
result += "\n"
newlines = 1
else:
result += "\n\n"
newlines = 2
else:
# Warning for the tempted!!!
# Be aware that obvious replacement of this with
# line.isspace()
# DOES NOT work! Explanations are welcome.
if not config.RE_SPACE.match(para):
result += para + "\n"
newlines = 1
else:
if newlines < 2:
result += "\n"
newlines += 1
return result | 29,764 |
Alir3z4/html2text | a3ed67b69160746b03a5861bf5c1b7a5ba76a4e1 | html2text/elements.py | AnchorElement.__init__ | (self, attrs: Dict[str, Optional[str]], count: int, outcount: int) | 7 | 10 | def __init__(self, attrs: Dict[str, Optional[str]], count: int, outcount: int):
self.attrs = attrs
self.count = count
self.outcount = outcount | https://github.com/Alir3z4/html2text/blob/a3ed67b69160746b03a5861bf5c1b7a5ba76a4e1/project48/html2text/elements.py#L7-L10 | 48 | [
0,
1,
2,
3
] | 100 | [] | 0 | true | 100 | 4 | 1 | 100 | 0 | def __init__(self, attrs: Dict[str, Optional[str]], count: int, outcount: int):
self.attrs = attrs
self.count = count
self.outcount = outcount | 29,765 |
|||
Alir3z4/html2text | a3ed67b69160746b03a5861bf5c1b7a5ba76a4e1 | html2text/elements.py | ListElement.__init__ | (self, name: str, num: int) | 16 | 18 | def __init__(self, name: str, num: int):
self.name = name
self.num = num | https://github.com/Alir3z4/html2text/blob/a3ed67b69160746b03a5861bf5c1b7a5ba76a4e1/project48/html2text/elements.py#L16-L18 | 48 | [
0,
1,
2
] | 100 | [] | 0 | true | 100 | 3 | 1 | 100 | 0 | def __init__(self, name: str, num: int):
self.name = name
self.num = num | 29,766 |
|||
Alir3z4/html2text | a3ed67b69160746b03a5861bf5c1b7a5ba76a4e1 | html2text/typing.py | OutCallback.__call__ | (self, s: str) | 2 | 3 | def __call__(self, s: str) -> None:
... | https://github.com/Alir3z4/html2text/blob/a3ed67b69160746b03a5861bf5c1b7a5ba76a4e1/project48/html2text/typing.py#L2-L3 | 48 | [
0
] | 50 | [
1
] | 50 | false | 66.666667 | 2 | 1 | 50 | 0 | def __call__(self, s: str) -> None:
... | 29,768 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.