vidtoolz-colored-textclip 0.0.2__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,100 @@
1
+ Metadata-Version: 2.4
2
+ Name: vidtoolz-colored-textclip
3
+ Version: 0.0.2
4
+ Summary: Create a color clip with overlaid text
5
+ Author: Sukhbinder Singh
6
+ License: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/sukhbinder/vidtoolz-colored-textclip
8
+ Project-URL: Changelog, https://github.com/sukhbinder/vidtoolz-colored-textclip/releases
9
+ Project-URL: Issues, https://github.com/sukhbinder/vidtoolz-colored-textclip/issues
10
+ Project-URL: CI, https://github.com/sukhbinder/vidtoolz-colored-textclip/actions
11
+ Classifier: License :: OSI Approved :: Apache Software License
12
+ Description-Content-Type: text/markdown
13
+ License-File: LICENSE
14
+ Requires-Dist: vidtoolz
15
+ Requires-Dist: numpy
16
+ Provides-Extra: test
17
+ Requires-Dist: pytest; extra == "test"
18
+ Dynamic: license-file
19
+
20
+ # vidtoolz-colored-textclip
21
+
22
+ [![PyPI](https://img.shields.io/pypi/v/vidtoolz-colored-textclip.svg)](https://pypi.org/project/vidtoolz-colored-textclip/)
23
+ [![Changelog](https://img.shields.io/github/v/release/sukhbinder/vidtoolz-colored-textclip?include_prereleases&label=changelog)](https://github.com/sukhbinder/vidtoolz-colored-textclip/releases)
24
+ [![Tests](https://github.com/sukhbinder/vidtoolz-colored-textclip/workflows/Test/badge.svg)](https://github.com/sukhbinder/vidtoolz-colored-textclip/actions?query=workflow%3ATest)
25
+ [![License](https://img.shields.io/badge/license-Apache%202.0-blue.svg)](https://github.com/sukhbinder/vidtoolz-colored-textclip/blob/main/LICENSE)
26
+
27
+ Create a color clip with overlaid text
28
+
29
+ ## Installation
30
+
31
+ First install [vidtoolz](https://github.com/sukhbinder/vidtoolz).
32
+
33
+ ```bash
34
+ pip install vidtoolz
35
+ ```
36
+
37
+ Then install this plugin in the same environment as your vidtoolz application.
38
+
39
+ ```bash
40
+ vidtoolz install vidtoolz-colored-textclip
41
+ ```
42
+ ## Usage
43
+
44
+ type ``vid textclip --help`` to get help
45
+
46
+
47
+ ```
48
+ usage: vid textclip [-h] [-f FONT] [-fs FONTSIZE] [-d DURATION]
49
+ [-fd FADE_DURATION] [-tc TEXT_COLOR] [-bg BG_COLOR]
50
+ [-gc GRADIENT_COLORS] [-s SIZE] [-o OUTPUT] [--fps FPS]
51
+ [-p PADDING]
52
+ text
53
+
54
+ Create a color clip with overlaid text
55
+
56
+ positional arguments:
57
+ text Text to display.
58
+
59
+ optional arguments:
60
+ -h, --help show this help message and exit
61
+ -f FONT, --font FONT Font name to use. Ex Noteworthy, Melno, Papyrus,
62
+ Zapfino (default: Arial)
63
+ -fs FONTSIZE, --fontsize FONTSIZE
64
+ Font size. (default: 80)
65
+ -d DURATION, --duration DURATION
66
+ Duration of video in seconds. (default: 5.0)
67
+ -fd FADE_DURATION, --fade-duration FADE_DURATION
68
+ Fade-in/out duration. (default: 1.0)
69
+ -tc TEXT_COLOR, --text-color TEXT_COLOR
70
+ Text color. (default: white)
71
+ -bg BG_COLOR, --bg-color BG_COLOR
72
+ Background color as R,G,B. (default: (0, 0, 0))
73
+ -gc GRADIENT_COLORS, --gradient-colors GRADIENT_COLORS
74
+ Semicolon-separated list of R,G,B colors for the
75
+ gradient background. e.g. 255,0,0;0,0,255
76
+ -s SIZE, --size SIZE Video size as width,height. (default: 1920,1080)
77
+ -o OUTPUT, --output OUTPUT
78
+ Output video file name. (default: None)
79
+ --fps FPS Frames per second. (default: 60)
80
+ -p PADDING, --padding PADDING
81
+ Padding on text (default: 30)
82
+
83
+ ```
84
+
85
+ ## Development
86
+
87
+ To set up this plugin locally, first checkout the code. Then create a new virtual environment:
88
+ ```bash
89
+ cd vidtoolz-colored-textclip
90
+ python -m venv venv
91
+ source venv/bin/activate
92
+ ```
93
+ Now install the dependencies and test dependencies:
94
+ ```bash
95
+ pip install -e '.[test]'
96
+ ```
97
+ To run the tests:
98
+ ```bash
99
+ python -m pytest
100
+ ```
@@ -0,0 +1,81 @@
1
+ # vidtoolz-colored-textclip
2
+
3
+ [![PyPI](https://img.shields.io/pypi/v/vidtoolz-colored-textclip.svg)](https://pypi.org/project/vidtoolz-colored-textclip/)
4
+ [![Changelog](https://img.shields.io/github/v/release/sukhbinder/vidtoolz-colored-textclip?include_prereleases&label=changelog)](https://github.com/sukhbinder/vidtoolz-colored-textclip/releases)
5
+ [![Tests](https://github.com/sukhbinder/vidtoolz-colored-textclip/workflows/Test/badge.svg)](https://github.com/sukhbinder/vidtoolz-colored-textclip/actions?query=workflow%3ATest)
6
+ [![License](https://img.shields.io/badge/license-Apache%202.0-blue.svg)](https://github.com/sukhbinder/vidtoolz-colored-textclip/blob/main/LICENSE)
7
+
8
+ Create a color clip with overlaid text
9
+
10
+ ## Installation
11
+
12
+ First install [vidtoolz](https://github.com/sukhbinder/vidtoolz).
13
+
14
+ ```bash
15
+ pip install vidtoolz
16
+ ```
17
+
18
+ Then install this plugin in the same environment as your vidtoolz application.
19
+
20
+ ```bash
21
+ vidtoolz install vidtoolz-colored-textclip
22
+ ```
23
+ ## Usage
24
+
25
+ type ``vid textclip --help`` to get help
26
+
27
+
28
+ ```
29
+ usage: vid textclip [-h] [-f FONT] [-fs FONTSIZE] [-d DURATION]
30
+ [-fd FADE_DURATION] [-tc TEXT_COLOR] [-bg BG_COLOR]
31
+ [-gc GRADIENT_COLORS] [-s SIZE] [-o OUTPUT] [--fps FPS]
32
+ [-p PADDING]
33
+ text
34
+
35
+ Create a color clip with overlaid text
36
+
37
+ positional arguments:
38
+ text Text to display.
39
+
40
+ optional arguments:
41
+ -h, --help show this help message and exit
42
+ -f FONT, --font FONT Font name to use. Ex Noteworthy, Melno, Papyrus,
43
+ Zapfino (default: Arial)
44
+ -fs FONTSIZE, --fontsize FONTSIZE
45
+ Font size. (default: 80)
46
+ -d DURATION, --duration DURATION
47
+ Duration of video in seconds. (default: 5.0)
48
+ -fd FADE_DURATION, --fade-duration FADE_DURATION
49
+ Fade-in/out duration. (default: 1.0)
50
+ -tc TEXT_COLOR, --text-color TEXT_COLOR
51
+ Text color. (default: white)
52
+ -bg BG_COLOR, --bg-color BG_COLOR
53
+ Background color as R,G,B. (default: (0, 0, 0))
54
+ -gc GRADIENT_COLORS, --gradient-colors GRADIENT_COLORS
55
+ Semicolon-separated list of R,G,B colors for the
56
+ gradient background. e.g. 255,0,0;0,0,255
57
+ -s SIZE, --size SIZE Video size as width,height. (default: 1920,1080)
58
+ -o OUTPUT, --output OUTPUT
59
+ Output video file name. (default: None)
60
+ --fps FPS Frames per second. (default: 60)
61
+ -p PADDING, --padding PADDING
62
+ Padding on text (default: 30)
63
+
64
+ ```
65
+
66
+ ## Development
67
+
68
+ To set up this plugin locally, first checkout the code. Then create a new virtual environment:
69
+ ```bash
70
+ cd vidtoolz-colored-textclip
71
+ python -m venv venv
72
+ source venv/bin/activate
73
+ ```
74
+ Now install the dependencies and test dependencies:
75
+ ```bash
76
+ pip install -e '.[test]'
77
+ ```
78
+ To run the tests:
79
+ ```bash
80
+ python -m pytest
81
+ ```
@@ -0,0 +1,29 @@
1
+ [project]
2
+ name = "vidtoolz-colored-textclip"
3
+ version = "0.0.2"
4
+ description = "Create a color clip with overlaid text"
5
+ readme = "README.md"
6
+ authors = [{ name = "Sukhbinder Singh" }]
7
+ license = { text = "Apache-2.0" }
8
+ classifiers = ["License :: OSI Approved :: Apache Software License"]
9
+ dependencies = ["vidtoolz", "numpy"]
10
+
11
+ [project.urls]
12
+ Homepage = "https://github.com/sukhbinder/vidtoolz-colored-textclip"
13
+ Changelog = "https://github.com/sukhbinder/vidtoolz-colored-textclip/releases"
14
+ Issues = "https://github.com/sukhbinder/vidtoolz-colored-textclip/issues"
15
+ CI = "https://github.com/sukhbinder/vidtoolz-colored-textclip/actions"
16
+
17
+ [project.entry-points."vidtoolz_plugins"]
18
+ textclip = "vidtoolz_colored_textclip:textclip_plugin"
19
+
20
+
21
+ [project.optional-dependencies]
22
+ test = ["pytest"]
23
+
24
+ [tool.pytest.ini_options]
25
+ pythonpath = ["."]
26
+
27
+ [build-system]
28
+ requires = ["setuptools", "wheel"]
29
+ build-backend = "setuptools.build_meta"
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,87 @@
1
+ import platform
2
+ from argparse import ArgumentParser
3
+ from pathlib import Path
4
+
5
+ import pytest
6
+
7
+ import vidtoolz_colored_textclip as w
8
+
9
+
10
+ def test_create_parser():
11
+ subparser = ArgumentParser().add_subparsers()
12
+ parser = w.create_parser(subparser)
13
+
14
+ assert parser is not None
15
+ default_font = "Papyrus" if platform.system() == "Darwin" else "Arial"
16
+
17
+ result = parser.parse_args(["hello"])
18
+ assert result.text == "hello"
19
+ assert result.duration == 3.0
20
+ assert result.font == default_font
21
+ assert result.fontsize == 210
22
+ assert result.text_color == "white"
23
+ assert result.fade_duration == 0.5
24
+ assert result.bg_color == (0, 0, 0)
25
+ assert result.size == "1920,1080"
26
+ assert result.output is None
27
+ assert result.fps == 60
28
+
29
+
30
+ def test_plugin(capsys):
31
+ w.textclip_plugin.hello(None)
32
+ captured = capsys.readouterr()
33
+ assert "Hello! This is an example ``vidtoolz`` plugin." in captured.out
34
+
35
+
36
+ def test_generate_output_filename_with_output():
37
+ assert (
38
+ w.generate_output_filename("Some Text", "custom_name.mp4") == "custom_name.mp4"
39
+ )
40
+
41
+
42
+ def test_generate_output_filename_from_text_simple():
43
+ assert w.generate_output_filename("Hello World") == "Hello-World.mp4"
44
+
45
+
46
+ def test_generate_output_filename_with_special_chars():
47
+ text = "A title: with *weird* characters!"
48
+ expected = "A-title-with-weird-characters.mp4"
49
+ assert w.generate_output_filename(text) == expected
50
+
51
+
52
+ def test_generate_output_filename_with_leading_trailing_spaces():
53
+ text = " Clean this up "
54
+ expected = "Clean-this-up.mp4"
55
+ assert w.generate_output_filename(text) == expected
56
+
57
+
58
+ def test_parse_gradient_colors_valid():
59
+ assert w.parse_gradient_colors("255 0 0;0 255 0") == [(255, 0, 0), (0, 255, 0)]
60
+
61
+
62
+ def test_parse_gradient_colors_invalid():
63
+ with pytest.raises(Exception):
64
+ w.parse_gradient_colors("255,0,0;0,255")
65
+
66
+
67
+ def test_realcase(tmpdir):
68
+ outfile = tmpdir / "test.mp4"
69
+ fontpath = Path(__file__).parent / "Keyboard.ttf"
70
+ argv = [
71
+ "Sukhbinder Singh",
72
+ "-e",
73
+ "-ef",
74
+ "-o",
75
+ str(outfile),
76
+ "-d",
77
+ "2",
78
+ "--fps",
79
+ "10",
80
+ "-f",
81
+ str(fontpath),
82
+ ]
83
+ subparser = ArgumentParser().add_subparsers()
84
+ parser = w.create_parser(subparser)
85
+ args = parser.parse_args(argv)
86
+ w.textclip_plugin.run(args)
87
+ assert outfile.exists()
@@ -0,0 +1,363 @@
1
+ import argparse
2
+ import os
3
+ import platform
4
+ import re
5
+ import textwrap
6
+
7
+ import numpy as np
8
+ import vidtoolz
9
+ from moviepy import (
10
+ AudioFileClip,
11
+ ColorClip,
12
+ CompositeAudioClip,
13
+ CompositeVideoClip,
14
+ ImageClip,
15
+ TextClip,
16
+ vfx,
17
+ )
18
+ from PIL import Image, ImageDraw, ImageFont
19
+
20
+
21
+ def create_gradient_clip(size, colors, duration):
22
+ """
23
+ Create a video clip with a linear gradient background.
24
+ """
25
+ width, height = size
26
+ gradient = np.zeros((height, width, 3), dtype=np.uint8)
27
+ for y in range(height):
28
+ interp_factor = y / (height - 1)
29
+ color_index = int(interp_factor * (len(colors) - 1))
30
+ local_interp = (interp_factor * (len(colors) - 1)) - color_index
31
+
32
+ c1 = np.array(colors[color_index])
33
+ c2 = np.array(colors[min(color_index + 1, len(colors) - 1)])
34
+
35
+ color = c1 * (1 - local_interp) + c2 * local_interp
36
+ gradient[y, :, :] = color.astype(np.uint8)
37
+
38
+ return ImageClip(gradient).with_duration(duration)
39
+
40
+
41
+ def get_audio_clip(duration, audio_volume):
42
+ audio_path = os.path.join(os.path.dirname(__file__), "assets", "charkha.mp3")
43
+ audio_clip = AudioFileClip(audio_path).subclipped(0, duration)
44
+ audio_clip = audio_clip.with_volume_scaled(audio_volume)
45
+ return audio_clip
46
+
47
+
48
+ def get_effect_clip():
49
+ """
50
+ Load the Sharpwipereverb sound effect.
51
+ """
52
+ effect_path = os.path.join(
53
+ os.path.dirname(__file__), "assets", "Sharpwipereverb.m4a"
54
+ )
55
+ return AudioFileClip(effect_path)
56
+
57
+
58
+ def generate_output_filename(text, output=None):
59
+ """
60
+ Generate an output filename from the text if none is provided.
61
+
62
+ Args:
63
+ text (str): The input text to use in the filename.
64
+ output (str or None): The user-provided output filename, if any.
65
+
66
+ Returns:
67
+ str: A valid output filename.
68
+ """
69
+ if output:
70
+ return output
71
+
72
+ # Remove any characters not safe for filenames
73
+ safe_text = re.sub(r"[^\w\s-]", "", text)
74
+ filename = safe_text.strip().replace(" ", "-")
75
+ return f"{filename}.mp4"
76
+
77
+
78
+ def create_text_colorclip(
79
+ text,
80
+ size=(1920, 1080),
81
+ color=(0, 0, 0),
82
+ gradient_colors=None,
83
+ text_color="white",
84
+ font="Arial",
85
+ fontsize=50,
86
+ fade_duration=1.0,
87
+ duration=5.0,
88
+ audio_volume=0.01,
89
+ padding=30,
90
+ expand=False,
91
+ effect=False,
92
+ fps=60,
93
+ ):
94
+ """
95
+ Create a color clip with overlaid text, both fading in and out.
96
+ """
97
+
98
+ def scale_by_frame(get_frame, t):
99
+ total_frames = duration * fps
100
+ frame = int(round(t * fps))
101
+ progress = min(frame / total_frames, 1.0)
102
+ scale = 1.0 + 0.1 * progress
103
+ return scale
104
+
105
+ if gradient_colors:
106
+ bg_clip = create_gradient_clip(size, gradient_colors, duration)
107
+ else:
108
+ bg_clip = ColorClip(size, color=color, duration=duration)
109
+
110
+ bg_clip = bg_clip.with_effects(
111
+ [vfx.FadeIn(fade_duration), vfx.FadeOut(fade_duration)]
112
+ )
113
+
114
+ text_clip = (
115
+ TextClip(
116
+ text=text,
117
+ font_size=fontsize,
118
+ font=font,
119
+ color=text_color,
120
+ margin=(padding, padding),
121
+ method="caption",
122
+ size=size,
123
+ )
124
+ .with_duration(duration)
125
+ .with_effects([vfx.FadeIn(fade_duration), vfx.FadeOut(fade_duration)])
126
+ .with_position("center")
127
+ )
128
+
129
+ # Apply expanding effect if enabled
130
+ if expand:
131
+ # Slowly scale text from 90% to 110% of original size
132
+ text_clip = text_clip.resized(
133
+ # lambda t: 1.0 + 0.1 * (round(t * fps) / (duration * fps))
134
+ lambda t: scale_by_frame(None, t)
135
+ )
136
+
137
+ bg_clip = bg_clip.with_fps(fps)
138
+ text_clip = text_clip.with_fps(fps)
139
+ final_clip = CompositeVideoClip([bg_clip, text_clip]).with_fps(fps)
140
+ audio_clip = get_audio_clip(duration, audio_volume)
141
+ audio_clip = audio_clip.with_fps(44100)
142
+
143
+ # If effect is enabled, mix SFX at start
144
+ if effect:
145
+ effect_clip = get_effect_clip()
146
+ effect_clip.with_fps(44100)
147
+ # Combine both effect and background audio
148
+ audio_clip = CompositeAudioClip([effect_clip, audio_clip])
149
+
150
+ audio_clip = audio_clip.with_fps(44100)
151
+ final_clip = final_clip.with_audio(audio_clip)
152
+
153
+ return final_clip
154
+
155
+
156
+ def get_fitting_fontsize_multiline(
157
+ text, font_path, max_width, padding=0, max_fontsize=300, min_fontsize=10
158
+ ):
159
+ """
160
+ Determine the largest font size such that the multiline text fits within max_width.
161
+ """
162
+ for fontsize in range(max_fontsize, min_fontsize, -1):
163
+ try:
164
+ font = ImageFont.truetype(font_path, fontsize)
165
+ except OSError:
166
+ font = ImageFont.load_default()
167
+
168
+ # Create dummy image to measure text
169
+ image = Image.new("RGB", (max_width, 1000))
170
+ draw = ImageDraw.Draw(image)
171
+
172
+ wrapped_text = textwrap.fill(text, width=40)
173
+ lines = wrapped_text.splitlines()
174
+ max_line_width = 0
175
+ for line in lines:
176
+ bbox = draw.textbbox((0, 0), line, font=font)
177
+ line_width = bbox[2] - bbox[0]
178
+ max_line_width = max(max_line_width, line_width)
179
+
180
+ if max_line_width + 2 * padding <= max_width:
181
+ return fontsize
182
+ return min_fontsize
183
+
184
+
185
+ def parse_color(color_str):
186
+ """
187
+ Convert color string like "255,0,0" to RGB tuple.
188
+ """
189
+ try:
190
+ return tuple(map(int, color_str.split(",")))
191
+ except:
192
+ raise argparse.ArgumentTypeError("Color must be in R,G,B format (e.g. 255,0,0)")
193
+
194
+
195
+ def parse_gradient_colors(color_str):
196
+ """
197
+ Convert a string of semicolon-separated RGB colors to a list of tuples.
198
+ e.g., "255,0,0;0,255,0" -> [(255,0,0), (0,255,0)]
199
+ """
200
+ try:
201
+ colors = []
202
+ for c in color_str.split(";"):
203
+ rgb = tuple(map(int, c.split(" ")))
204
+ if len(rgb) != 3:
205
+ raise ValueError
206
+ colors.append(rgb)
207
+ return colors
208
+ except:
209
+ raise argparse.ArgumentTypeError(
210
+ "Gradient colors must be in R,G,B;R,G,B format (e.g. 255,0,0;0,255,0)"
211
+ )
212
+
213
+
214
+ def create_parser(subparser):
215
+ parser = subparser.add_parser(
216
+ "textclip", description="Create a color clip with overlaid text"
217
+ )
218
+ # Add subprser arguments here.
219
+ default_font = "Papyrus" if platform.system() == "Darwin" else "Arial"
220
+ parser.add_argument("text", type=str, help="Text to display.")
221
+ parser.add_argument(
222
+ "-f",
223
+ "--font",
224
+ type=str,
225
+ default=default_font,
226
+ help="Font name to use. Ex Noteworthy, Melno, Papyrus, Zapfino (default: %(default)s)",
227
+ )
228
+ parser.add_argument(
229
+ "-fs",
230
+ "--fontsize",
231
+ type=int,
232
+ default=210,
233
+ help="Font size. (default: %(default)s)",
234
+ )
235
+ parser.add_argument(
236
+ "-d",
237
+ "--duration",
238
+ type=float,
239
+ default=3.0,
240
+ help="Duration of video in seconds. (default: %(default)s)",
241
+ )
242
+ parser.add_argument(
243
+ "-fd",
244
+ "--fade-duration",
245
+ type=float,
246
+ default=0.5,
247
+ help="Fade-in/out duration. (default: %(default)s)",
248
+ )
249
+ parser.add_argument(
250
+ "-tc",
251
+ "--text-color",
252
+ type=str,
253
+ default="white",
254
+ help="Text color. (default: %(default)s)",
255
+ )
256
+ parser.add_argument(
257
+ "-bg",
258
+ "--bg-color",
259
+ type=parse_color,
260
+ default=(0, 0, 0),
261
+ help="Background color as R,G,B. (default: %(default)s)",
262
+ )
263
+ parser.add_argument(
264
+ "-gc",
265
+ "--gradient-colors",
266
+ type=parse_gradient_colors,
267
+ default=None,
268
+ help="Semicolon-separated list of R,G,B colors for the gradient background. e.g. 255,0,0;0,0,255",
269
+ )
270
+ parser.add_argument(
271
+ "-s",
272
+ "--size",
273
+ type=str,
274
+ default="1920,1080",
275
+ help="Video size as width,height. (default: %(default)s)",
276
+ )
277
+ parser.add_argument(
278
+ "-o",
279
+ "--output",
280
+ type=str,
281
+ default=None,
282
+ help="Output video file name. (default: %(default)s)",
283
+ )
284
+ parser.add_argument(
285
+ "--fps", type=int, default=60, help="Frames per second. (default: %(default)s)"
286
+ )
287
+
288
+ parser.add_argument(
289
+ "-p",
290
+ "--padding",
291
+ type=int,
292
+ default=30,
293
+ help="Padding on text (default: %(default)s)",
294
+ )
295
+
296
+ parser.add_argument(
297
+ "-e",
298
+ "--expand",
299
+ action="store_true",
300
+ help="If set, the text will slowly enlarge during the video.",
301
+ )
302
+
303
+ parser.add_argument(
304
+ "-ef",
305
+ "--effect",
306
+ action="store_true",
307
+ help="If set, adds Sharpwipereverb sound effect at the start.",
308
+ )
309
+ return parser
310
+
311
+
312
+ class ViztoolzPlugin:
313
+ """Create a color clip with overlaid text"""
314
+
315
+ __name__ = "textclip"
316
+
317
+ @vidtoolz.hookimpl
318
+ def register_commands(self, subparser):
319
+ self.parser = create_parser(subparser)
320
+ self.parser.set_defaults(func=self.run)
321
+
322
+ def run(self, args):
323
+ width, height = map(int, args.size.split(","))
324
+ output = generate_output_filename(args.text, args.output)
325
+
326
+ fontsize = get_fitting_fontsize_multiline(
327
+ text=args.text,
328
+ font_path=args.font,
329
+ max_width=width,
330
+ padding=args.padding,
331
+ max_fontsize=args.fontsize, # start from user's preferred size
332
+ )
333
+
334
+ clip = create_text_colorclip(
335
+ text=args.text,
336
+ size=(width, height),
337
+ color=args.bg_color,
338
+ gradient_colors=args.gradient_colors,
339
+ text_color=args.text_color,
340
+ font=args.font,
341
+ fontsize=fontsize,
342
+ fade_duration=args.fade_duration,
343
+ duration=args.duration,
344
+ padding=args.padding,
345
+ expand=args.expand,
346
+ effect=args.effect,
347
+ fps=args.fps,
348
+ )
349
+
350
+ clip.write_videofile(
351
+ output,
352
+ fps=args.fps,
353
+ audio_codec="aac",
354
+ codec="libx264",
355
+ ffmpeg_params=["-pix_fmt", "yuv420p"],
356
+ )
357
+
358
+ def hello(self, args):
359
+ # this routine will be called when "vidtoolz "textclip is called."
360
+ print("Hello! This is an example ``vidtoolz`` plugin.")
361
+
362
+
363
+ textclip_plugin = ViztoolzPlugin()
@@ -0,0 +1,100 @@
1
+ Metadata-Version: 2.4
2
+ Name: vidtoolz-colored-textclip
3
+ Version: 0.0.2
4
+ Summary: Create a color clip with overlaid text
5
+ Author: Sukhbinder Singh
6
+ License: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/sukhbinder/vidtoolz-colored-textclip
8
+ Project-URL: Changelog, https://github.com/sukhbinder/vidtoolz-colored-textclip/releases
9
+ Project-URL: Issues, https://github.com/sukhbinder/vidtoolz-colored-textclip/issues
10
+ Project-URL: CI, https://github.com/sukhbinder/vidtoolz-colored-textclip/actions
11
+ Classifier: License :: OSI Approved :: Apache Software License
12
+ Description-Content-Type: text/markdown
13
+ License-File: LICENSE
14
+ Requires-Dist: vidtoolz
15
+ Requires-Dist: numpy
16
+ Provides-Extra: test
17
+ Requires-Dist: pytest; extra == "test"
18
+ Dynamic: license-file
19
+
20
+ # vidtoolz-colored-textclip
21
+
22
+ [![PyPI](https://img.shields.io/pypi/v/vidtoolz-colored-textclip.svg)](https://pypi.org/project/vidtoolz-colored-textclip/)
23
+ [![Changelog](https://img.shields.io/github/v/release/sukhbinder/vidtoolz-colored-textclip?include_prereleases&label=changelog)](https://github.com/sukhbinder/vidtoolz-colored-textclip/releases)
24
+ [![Tests](https://github.com/sukhbinder/vidtoolz-colored-textclip/workflows/Test/badge.svg)](https://github.com/sukhbinder/vidtoolz-colored-textclip/actions?query=workflow%3ATest)
25
+ [![License](https://img.shields.io/badge/license-Apache%202.0-blue.svg)](https://github.com/sukhbinder/vidtoolz-colored-textclip/blob/main/LICENSE)
26
+
27
+ Create a color clip with overlaid text
28
+
29
+ ## Installation
30
+
31
+ First install [vidtoolz](https://github.com/sukhbinder/vidtoolz).
32
+
33
+ ```bash
34
+ pip install vidtoolz
35
+ ```
36
+
37
+ Then install this plugin in the same environment as your vidtoolz application.
38
+
39
+ ```bash
40
+ vidtoolz install vidtoolz-colored-textclip
41
+ ```
42
+ ## Usage
43
+
44
+ type ``vid textclip --help`` to get help
45
+
46
+
47
+ ```
48
+ usage: vid textclip [-h] [-f FONT] [-fs FONTSIZE] [-d DURATION]
49
+ [-fd FADE_DURATION] [-tc TEXT_COLOR] [-bg BG_COLOR]
50
+ [-gc GRADIENT_COLORS] [-s SIZE] [-o OUTPUT] [--fps FPS]
51
+ [-p PADDING]
52
+ text
53
+
54
+ Create a color clip with overlaid text
55
+
56
+ positional arguments:
57
+ text Text to display.
58
+
59
+ optional arguments:
60
+ -h, --help show this help message and exit
61
+ -f FONT, --font FONT Font name to use. Ex Noteworthy, Melno, Papyrus,
62
+ Zapfino (default: Arial)
63
+ -fs FONTSIZE, --fontsize FONTSIZE
64
+ Font size. (default: 80)
65
+ -d DURATION, --duration DURATION
66
+ Duration of video in seconds. (default: 5.0)
67
+ -fd FADE_DURATION, --fade-duration FADE_DURATION
68
+ Fade-in/out duration. (default: 1.0)
69
+ -tc TEXT_COLOR, --text-color TEXT_COLOR
70
+ Text color. (default: white)
71
+ -bg BG_COLOR, --bg-color BG_COLOR
72
+ Background color as R,G,B. (default: (0, 0, 0))
73
+ -gc GRADIENT_COLORS, --gradient-colors GRADIENT_COLORS
74
+ Semicolon-separated list of R,G,B colors for the
75
+ gradient background. e.g. 255,0,0;0,0,255
76
+ -s SIZE, --size SIZE Video size as width,height. (default: 1920,1080)
77
+ -o OUTPUT, --output OUTPUT
78
+ Output video file name. (default: None)
79
+ --fps FPS Frames per second. (default: 60)
80
+ -p PADDING, --padding PADDING
81
+ Padding on text (default: 30)
82
+
83
+ ```
84
+
85
+ ## Development
86
+
87
+ To set up this plugin locally, first checkout the code. Then create a new virtual environment:
88
+ ```bash
89
+ cd vidtoolz-colored-textclip
90
+ python -m venv venv
91
+ source venv/bin/activate
92
+ ```
93
+ Now install the dependencies and test dependencies:
94
+ ```bash
95
+ pip install -e '.[test]'
96
+ ```
97
+ To run the tests:
98
+ ```bash
99
+ python -m pytest
100
+ ```
@@ -0,0 +1,11 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ tests/test_vidtoolz_colored_textclip.py
5
+ vidtoolz_colored_textclip/__init__.py
6
+ vidtoolz_colored_textclip.egg-info/PKG-INFO
7
+ vidtoolz_colored_textclip.egg-info/SOURCES.txt
8
+ vidtoolz_colored_textclip.egg-info/dependency_links.txt
9
+ vidtoolz_colored_textclip.egg-info/entry_points.txt
10
+ vidtoolz_colored_textclip.egg-info/requires.txt
11
+ vidtoolz_colored_textclip.egg-info/top_level.txt
@@ -0,0 +1,2 @@
1
+ [vidtoolz_plugins]
2
+ textclip = vidtoolz_colored_textclip:textclip_plugin
@@ -0,0 +1,5 @@
1
+ vidtoolz
2
+ numpy
3
+
4
+ [test]
5
+ pytest
@@ -0,0 +1 @@
1
+ vidtoolz_colored_textclip