videopython 0.2.0__py3-none-any.whl → 0.2.1__py3-none-any.whl

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.

Potentially problematic release.


This version of videopython might be problematic. Click here for more details.

File without changes
videopython/base/video.py CHANGED
@@ -2,14 +2,18 @@ from __future__ import annotations
2
2
 
3
3
  import shlex
4
4
  import subprocess
5
+ import tempfile
5
6
  from dataclasses import dataclass
6
7
  from pathlib import Path
8
+ from typing import Literal, get_args
7
9
 
8
10
  import cv2
9
11
  import numpy as np
10
12
  from pydub import AudioSegment
11
13
 
12
- from videopython.utils.common import check_path, generate_random_name
14
+ from videopython.utils.common import generate_random_name
15
+
16
+ ALLOWED_VIDEO_FORMATS = Literal["mp4", "avi", "mov", "mkv", "webm"]
13
17
 
14
18
 
15
19
  @dataclass
@@ -166,54 +170,80 @@ class Video:
166
170
  split_videos[1].audio = self.audio[audio_midpoint:]
167
171
  return split_videos
168
172
 
169
- def save(self, filename: str | None = None) -> str:
170
- """Saves the video.
173
+ def save(self, filename: str | Path | None = None, format: ALLOWED_VIDEO_FORMATS = "mp4") -> Path:
174
+ """Saves the video with audio.
171
175
 
172
176
  Args:
173
- filename: Name of the output video file. Generates random UUID name if not provided.
177
+ filename: Name of the output video file. Generates random name if not provided.
178
+ format: Output format (default is 'mp4').
179
+
180
+ Returns:
181
+ Path to the saved video file.
174
182
  """
175
183
  if not self.is_loaded():
176
- raise RuntimeError(f"Video is not loaded, cannot save!")
177
-
178
- if filename is None:
179
- filename = generate_random_name(suffix=".mp4")
180
- filename = check_path(filename, dir_exists=True, suffix=".mp4")
184
+ raise RuntimeError("Video is not loaded, cannot save!")
181
185
 
182
- ffmpeg_video_command = (
183
- f"ffmpeg -loglevel error -y -framerate {self.fps} -f rawvideo -pix_fmt rgb24"
184
- f" -s {self.metadata.width}x{self.metadata.height} "
185
- f"-i pipe:0 -c:v libx264 -pix_fmt yuv420p {filename}"
186
- )
187
-
188
- ffmpeg_audio_command = (
189
- f"ffmpeg -loglevel error -y -i {filename} -f s16le -acodec pcm_s16le "
190
- f"-ar {self.audio.frame_rate} -ac {self.audio.channels} -i pipe:0 "
191
- f"-c:v copy -c:a aac -strict experimental {filename}_temp.mp4"
192
- )
193
-
194
- try:
195
- print("Saving frames to video...")
196
- subprocess.run(
197
- ffmpeg_video_command,
198
- input=self.frames.tobytes(),
199
- check=True,
200
- shell=True,
186
+ # Check if the format is allowed
187
+ if format.lower() not in get_args(ALLOWED_VIDEO_FORMATS):
188
+ raise ValueError(
189
+ f"Unsupported format: {format}. Allowed formats are: {', '.join(get_args(ALLOWED_VIDEO_FORMATS))}"
201
190
  )
202
- except subprocess.CalledProcessError as e:
203
- print("Error saving frames to video!")
204
- raise e
205
-
206
- try:
207
- print("Adding audio track...")
208
- subprocess.run(ffmpeg_audio_command, input=self.audio.raw_data, check=True, shell=True)
209
- Path(filename).unlink()
210
- Path(filename + "_temp.mp4").rename(filename)
211
- except subprocess.CalledProcessError as e:
212
- print(f"Error adding audio track!")
213
- raise e
214
191
 
215
- print(f"Video saved into `{filename}`!")
216
- return filename
192
+ if filename is None:
193
+ filename = Path(generate_random_name(suffix=f".{format}"))
194
+ else:
195
+ filename = Path(filename).with_suffix(f".{format}")
196
+ filename.parent.mkdir(parents=True, exist_ok=True)
197
+
198
+ with tempfile.TemporaryDirectory() as temp_dir:
199
+ temp_dir_path = Path(temp_dir)
200
+
201
+ # Save frames as images
202
+ for i, frame in enumerate(self.frames):
203
+ frame_path = temp_dir_path / f"frame_{i:04d}.png"
204
+ cv2.imwrite(str(frame_path), cv2.cvtColor(frame, cv2.COLOR_RGB2BGR))
205
+
206
+ # Save audio to a temporary file
207
+ temp_audio = temp_dir_path / "temp_audio.wav"
208
+ self.audio.export(str(temp_audio), format="adts", bitrate="192k")
209
+
210
+ # Construct FFmpeg command
211
+ ffmpeg_command = [
212
+ "ffmpeg",
213
+ "-y", # Overwrite output file if it exists
214
+ "-r",
215
+ str(self.fps), # Set the frame rate
216
+ "-i",
217
+ str(temp_dir_path / "frame_%04d.png"), # Input image sequence
218
+ "-i",
219
+ str(temp_audio), # Input audio file
220
+ "-c:v",
221
+ "libx264", # Video codec
222
+ "-preset",
223
+ "medium", # Encoding preset (tradeoff between encoding speed and compression)
224
+ "-crf",
225
+ "23", # Constant Rate Factor (lower means better quality, 23 is default)
226
+ "-c:a",
227
+ "copy", # Audio codec
228
+ "-b:a",
229
+ "192k", # Audio bitrate
230
+ "-pix_fmt",
231
+ "yuv420p", # Pixel format
232
+ "-shortest", # Finish encoding when the shortest input stream ends
233
+ str(filename),
234
+ ]
235
+
236
+ try:
237
+ subprocess.run(ffmpeg_command, check=True, capture_output=True, text=True)
238
+ print(f"Video saved successfully to: {filename}")
239
+ return filename
240
+ except subprocess.CalledProcessError as e:
241
+ print(f"Error saving video: {e}")
242
+ print(f"FFmpeg stderr: {e.stderr}")
243
+ raise
244
+
245
+ def add_audio(self, audio: AudioSegment, overlay: bool = True, overlay_gain: int = 0, loop: bool = False) -> None:
246
+ self.audio = self._process_audio(audio=audio, overlay=overlay, overlay_gain=overlay_gain, loop=loop)
217
247
 
218
248
  def add_audio_from_file(self, path: str, overlay: bool = True, overlay_gain: int = 0, loop: bool = False) -> None:
219
249
  new_audio = self._load_audio_from_path(path)
@@ -221,15 +251,19 @@ class Video:
221
251
  print(f"Audio file `{path}` not found, skipping!")
222
252
  return
223
253
 
224
- if (duration_diff := round(self.total_seconds - new_audio.duration_seconds)) > 0 and not loop:
225
- new_audio = new_audio + AudioSegment.silent(duration_diff * 1000)
226
- elif new_audio.duration_seconds > self.total_seconds:
227
- new_audio = new_audio[: round(self.total_seconds * 1000)]
254
+ self.audio = self._process_audio(audio=new_audio, overlay=overlay, overlay_gain=overlay_gain, loop=loop)
255
+
256
+ def _process_audio(
257
+ self, audio: AudioSegment, overlay: bool = True, overlay_gain: int = 0, loop: bool = False
258
+ ) -> AudioSegment:
259
+ if (duration_diff := round(self.total_seconds - audio.duration_seconds)) > 0 and not loop:
260
+ audio = audio + AudioSegment.silent(duration_diff * 1000)
261
+ elif audio.duration_seconds > self.total_seconds:
262
+ audio = audio[: round(self.total_seconds * 1000)]
228
263
 
229
264
  if overlay:
230
- self.audio = self.audio.overlay(new_audio, loop=loop, gain_during_overlay=overlay_gain)
231
- else:
232
- self.audio = new_audio
265
+ return self.audio.overlay(audio, loop=loop, gain_during_overlay=overlay_gain)
266
+ return audio
233
267
 
234
268
  def __add__(self, other: Video) -> Video:
235
269
  # TODO: Should it be class method? How to make it work with sum()?
@@ -282,17 +316,26 @@ class Video:
282
316
  Args:
283
317
  path: Path to video file.
284
318
  """
285
- metadata = VideoMetadata.from_path(path)
286
- ffmpeg_command = f"ffmpeg -i {path} -f rawvideo -pix_fmt rgb24 -loglevel quiet pipe:1"
319
+ cap = cv2.VideoCapture(path)
320
+ if not cap.isOpened():
321
+ raise ValueError(f"Unable to open video file: {path}")
322
+
323
+ fps = cap.get(cv2.CAP_PROP_FPS)
324
+ frames = []
325
+
326
+ while True:
327
+ ret, frame = cap.read()
328
+ if not ret:
329
+ break
330
+ frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
331
+ frames.append(frame)
332
+
333
+ cap.release()
287
334
 
288
- # Run the ffmpeg command and capture the stdout
289
- ffmpeg_process = subprocess.Popen(shlex.split(ffmpeg_command), stdout=subprocess.PIPE)
290
- ffmpeg_out, _ = ffmpeg_process.communicate()
335
+ if not frames:
336
+ raise ValueError(f"No frames could be read from the video file: {path}")
291
337
 
292
- # Convert the raw video data to a NumPy array
293
- frames = np.frombuffer(ffmpeg_out, dtype=np.uint8).reshape([-1, metadata.height, metadata.width, 3])
294
- fps = metadata.fps
295
- return frames, fps
338
+ return np.array(frames), fps
296
339
 
297
340
  @property
298
341
  def video_shape(self) -> tuple[int, int, int, int]:
@@ -1,4 +1,4 @@
1
- from .audio import TextToSpeech
1
+ from .audio import TextToMusic, TextToSpeech
2
2
  from .image import TextToImage
3
3
  from .video import ImageToVideo, TextToVideo
4
4
 
@@ -7,4 +7,5 @@ __all__ = [
7
7
  "TextToSpeech",
8
8
  "TextToImage",
9
9
  "TextToVideo",
10
+ "TextToMusic",
10
11
  ]
@@ -1,9 +1,15 @@
1
1
  import numpy as np
2
2
  import torch
3
3
  from pydub import AudioSegment
4
- from transformers import AutoTokenizer, VitsModel
4
+ from transformers import (
5
+ AutoProcessor,
6
+ AutoTokenizer,
7
+ MusicgenForConditionalGeneration,
8
+ VitsModel,
9
+ )
5
10
 
6
11
  TEXT_TO_SPEECH_MODEL = "facebook/mms-tts-eng"
12
+ MUSIC_GENERATION_MODEL_SMALL = "facebook/musicgen-small"
7
13
 
8
14
 
9
15
  class TextToSpeech:
@@ -20,3 +26,31 @@ class TextToSpeech:
20
26
  output = (output.T.float().numpy() * (2**31 - 1)).astype(np.int32)
21
27
  audio = AudioSegment(data=output, frame_rate=self.pipeline.config.sampling_rate, sample_width=4, channels=1)
22
28
  return audio
29
+
30
+
31
+ class TextToMusic:
32
+ def __init__(self) -> None:
33
+ """
34
+ Generates music from text using the Musicgen model.
35
+ Check the license for the model before using it.
36
+ """
37
+ self.processor = AutoProcessor.from_pretrained(MUSIC_GENERATION_MODEL_SMALL)
38
+ self.model = MusicgenForConditionalGeneration.from_pretrained(MUSIC_GENERATION_MODEL_SMALL)
39
+
40
+ def generate_audio(self, text: str, max_new_tokens: int) -> AudioSegment:
41
+ inputs = self.processor(
42
+ text=[text],
43
+ padding=True,
44
+ return_tensors="pt",
45
+ )
46
+ audio_values = self.model.generate(**inputs, max_new_tokens=max_new_tokens)
47
+ sampling_rate = self.model.config.audio_encoder.sampling_rate
48
+ output = (audio_values[0, 0].float().numpy() * (2**31 - 1)).astype(np.int32)
49
+
50
+ audio = AudioSegment(
51
+ data=output.tobytes(),
52
+ frame_rate=sampling_rate,
53
+ sample_width=4,
54
+ channels=1,
55
+ )
56
+ return audio
videopython/py.typed ADDED
File without changes
@@ -0,0 +1,130 @@
1
+ Metadata-Version: 2.3
2
+ Name: videopython
3
+ Version: 0.2.1
4
+ Summary: Minimal video generation and processing library.
5
+ Project-URL: Homepage, https://github.com/bartwojtowicz/videopython/
6
+ Project-URL: Repository, https://github.com/bartwojtowicz/videopython/
7
+ Project-URL: Documentation, https://github.com/bartwojtowicz/videopython/
8
+ Author-email: Bartosz Wójtowicz <bartoszwojtowicz@outlook.com>, Bartosz Rudnikowicz <bartoszrudnikowicz840@gmail.com>, Piotr Pukisz <piotr.pukisz@gmail.com>
9
+ License: Apache-2.0
10
+ License-File: LICENSE
11
+ Keywords: editing,generation,movie,opencv,python,video,videopython
12
+ Classifier: License :: OSI Approved :: Apache Software License
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.10
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Requires-Python: <3.13,>=3.10
18
+ Requires-Dist: numpy>=1.25.2
19
+ Requires-Dist: opencv-python>=4.9.0.80
20
+ Requires-Dist: pillow>=10.3.0
21
+ Requires-Dist: pydub>=0.25.1
22
+ Requires-Dist: tqdm>=4.66.3
23
+ Provides-Extra: dev
24
+ Requires-Dist: black==24.3.0; extra == 'dev'
25
+ Requires-Dist: isort==5.12.0; extra == 'dev'
26
+ Requires-Dist: mypy==1.8.0; extra == 'dev'
27
+ Requires-Dist: pydub-stubs==0.25.1.1; extra == 'dev'
28
+ Requires-Dist: pytest==7.4.0; extra == 'dev'
29
+ Requires-Dist: types-pillow==10.2.0.20240213; extra == 'dev'
30
+ Requires-Dist: types-tqdm==4.66.0.20240106; extra == 'dev'
31
+ Provides-Extra: generation
32
+ Requires-Dist: accelerate>=0.29.2; extra == 'generation'
33
+ Requires-Dist: diffusers>=0.26.3; extra == 'generation'
34
+ Requires-Dist: torch>=2.1.0; extra == 'generation'
35
+ Requires-Dist: transformers>=4.38.1; extra == 'generation'
36
+ Description-Content-Type: text/markdown
37
+
38
+ # About
39
+
40
+ Minimal video generation and processing library.
41
+
42
+ ## Setup
43
+
44
+ ### Install ffmpeg
45
+ ```bash
46
+ # Install with brew for MacOS:
47
+ brew install ffmpeg
48
+ # Install with apt-get for Ubuntu:
49
+ sudo apt-get install ffmpeg
50
+ ```
51
+
52
+ ### Install with pip
53
+ ```bash
54
+ pip install videopython[generation]
55
+ ```
56
+ > You can install without `[generation]` dependencies for basic video handling and processing.
57
+ > The funcionalities found in `videopython.generation` won't work.
58
+
59
+ ## Basic Usage
60
+
61
+ ### Video handling
62
+
63
+ ```python
64
+ from videopython.base.video import Video
65
+
66
+ # Load videos and print metadata
67
+ video1 = Video.from_path("tests/test_data/fast_benchmark.mp4")
68
+ print(video1)
69
+
70
+ video2 = Video.from_path("tests/test_data/slow_benchmark.mp4")
71
+ print(video2)
72
+
73
+ # Define the transformations
74
+ from videopython.base.transforms import CutSeconds, ResampleFPS, Resize, TransformationPipeline
75
+
76
+ pipeline = TransformationPipeline(
77
+ [CutSeconds(start=1.5, end=6.5), ResampleFPS(fps=30), Resize(width=1000, height=1000)]
78
+ )
79
+ video1 = pipeline.run(video1)
80
+ video2 = pipeline.run(video2)
81
+
82
+ # Combine videos, add audio and save
83
+ from videopython.base.transitions import FadeTransition
84
+
85
+ fade = FadeTransition(effect_time_seconds=3.0)
86
+ video = fade.apply(videos=(video1, video2))
87
+ video.add_audio_from_file("tests/test_data/test_audio.mp3")
88
+
89
+ savepath = video.save()
90
+ ```
91
+
92
+ ### Video Generation
93
+
94
+ > Using Nvidia A40 or better is recommended for the `videopython.generation` module.
95
+ ```python
96
+ # Generate image and animate it
97
+ from videopython.generation import ImageToVideo
98
+ from videopython.generation import TextToImage
99
+ from videopython.generation import TextToMusic
100
+
101
+ image = TextToImage().generate_image(prompt="Golden Retriever playing in the park")
102
+ video = ImageToVideo().generate_video(image=image, fps=24)
103
+
104
+ # Video generation directly from prompt
105
+ from videopython.generation import TextToVideo
106
+ video_gen = TextToVideo()
107
+ video = video_gen.generate_video("Dogs playing in the snow")
108
+ for _ in range(10):
109
+ video += video_gen.generate_video("Dogs playing in the snow")
110
+
111
+ # Cut the first 2 seconds
112
+ from videopython.base.transforms import CutSeconds
113
+ transformed_video = CutSeconds(start_second=0, end_second=2).apply(video.copy())
114
+
115
+ # Upsample to 30 FPS
116
+ from videopython.base.transforms import ResampleFPS
117
+ transformed_video = ResampleFPS(new_fps=30).apply(transformed_video)
118
+
119
+ # Resize to 1000x1000
120
+ from videopython.base.transforms import Resize
121
+ transformed_video = Resize(width=1000, height=1000).apply(transformed_video)
122
+
123
+ # Add generated music
124
+ # MusicGen cannot generate more than 1503 tokens (~30seconds of audio)
125
+ text_to_music = TextToMusic()
126
+ audio = text_to_music.generate_audio("Happy dogs playing together in a park", max_new_tokens=256)
127
+ transformed_video.add_audio(audio=audio)
128
+
129
+ filepath = transformed_video.save()
130
+ ```
@@ -1,20 +1,20 @@
1
+ videopython/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
+ videopython/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
1
3
  videopython/base/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
4
  videopython/base/compose.py,sha256=pti12VY3Yg7TZZiENPF6veM8POWssfsK8ePDdGlhAhA,1968
3
5
  videopython/base/effects.py,sha256=ZFUWrgVWTn4uWpxPfTQSQQKEZN5ns4btMofOZNHCeQc,7540
4
6
  videopython/base/exceptions.py,sha256=68_16lUPOR9_zhWdeBGS8_NFI32VbrcoDbN5KHHg0_w,44
5
7
  videopython/base/transforms.py,sha256=VP8SGArokfXN-IE7tk-3i0oMM3HV5zpJa-GLj7BoeRo,5856
6
8
  videopython/base/transitions.py,sha256=zYsxIgiVfN9P-CoGWUWRYFBr_0inX1sAJ02gyIEQ678,3694
7
- videopython/base/video.py,sha256=kG-juKN-da5NzV89YxZl5JkyMTJFkgPceh4yuAUnsQs,11099
8
- videopython/generation/__init__.py,sha256=Qse024UgiS9OxXzbbInyZ-9cpfI4enR2Dcds4lLDpNA,201
9
- videopython/generation/audio.py,sha256=BTc-3vJ5e6D0lt2OPo2hfOcUqhNXIcvRLNoo2oQ470M,777
9
+ videopython/base/video.py,sha256=4SWa6ULLNsnTmv-VIyVTIvg2tYnNZD6WQPBeLZe19vg,12735
10
+ videopython/generation/__init__.py,sha256=5esJ7_PPSkqNXuPQWLLAyeQZY00BnYFc94WZIHi7pBU,233
11
+ videopython/generation/audio.py,sha256=OOE0XsupCOoNq1yoQnfo0MfUcRvvndnrUt-MQjyXmwc,1915
10
12
  videopython/generation/image.py,sha256=i8zJm0WXn_Pykby9Urw1kzDcla6ArYhRgG-ueRdoAJ0,675
11
- videopython/generation/pipeline.py,sha256=v8GHkGNLErnQBjzNA8oem7fRv7YOx_NdduEC47kQkf0,773
12
13
  videopython/generation/video.py,sha256=206YON_XjPTYyjIJ3j5uBgd_yHmCDg7SqbkIU9GzEgw,1831
13
14
  videopython/utils/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
14
15
  videopython/utils/common.py,sha256=F-30YoKUwWDI7HiJUWw0gRFUguhShSVaxT0aFfvpifg,936
15
16
  videopython/utils/image.py,sha256=gng1by8ieYRVs1DlxHPMqYIPxKc1WWwBm8W5oASBKfY,12084
16
- videopython-0.2.0.dist-info/LICENSE,sha256=nJL9jVOt2MSW7swNDq4Y6oD_n9bLI0B0afr8ougtZ6s,10832
17
- videopython-0.2.0.dist-info/METADATA,sha256=W8FecvXP3eT7BSeUNjDKiykVPIrcwXsademTs9gl3MU,16531
18
- videopython-0.2.0.dist-info/WHEEL,sha256=mguMlWGMX-VHnMpKOjjQidIo1ssRlCFu4a4mBpz1s2M,91
19
- videopython-0.2.0.dist-info/top_level.txt,sha256=OikTGG8Swfw_syz--1atAn5KQ4GH9Pye17eATGred-Q,12
20
- videopython-0.2.0.dist-info/RECORD,,
17
+ videopython-0.2.1.dist-info/METADATA,sha256=3Em1dQGluch8yPUWR5PnZakhhXradrFzexOCEdd1W7E,4466
18
+ videopython-0.2.1.dist-info/WHEEL,sha256=1yFddiXMmvYK7QYTqtRNtX66WJ0Mz8PYEiEUoOUUxRY,87
19
+ videopython-0.2.1.dist-info/licenses/LICENSE,sha256=nJL9jVOt2MSW7swNDq4Y6oD_n9bLI0B0afr8ougtZ6s,10832
20
+ videopython-0.2.1.dist-info/RECORD,,
@@ -1,5 +1,4 @@
1
1
  Wheel-Version: 1.0
2
- Generator: setuptools (70.1.1)
2
+ Generator: hatchling 1.25.0
3
3
  Root-Is-Purelib: true
4
4
  Tag: py3-none-any
5
-
@@ -1,32 +0,0 @@
1
- import cv2
2
- import numpy as np
3
- from PIL import Image
4
-
5
- from videopython.base.transforms import Resize
6
- from videopython.generation import ImageToVideo, TextToImage
7
-
8
- N_ITERATIONS = 11
9
- PRMOPT = "Sunset at the sea, cimenatic view"
10
-
11
-
12
- def main():
13
- text_to_image = TextToImage()
14
- image_to_video = ImageToVideo()
15
-
16
- target_height = 576
17
- target_width = 1024
18
-
19
- base_image = text_to_image.generate_image(PRMOPT)
20
- image = cv2.resize(np.asarray(base_image), (target_width, target_height))
21
-
22
- video = image_to_video.generate_video(image)
23
-
24
- for i in range(N_ITERATIONS - 1):
25
- print(f"Generating {i+2}/{N_ITERATIONS}...")
26
- video += image_to_video.generate_video(Image.fromarray(video.frames[-1]))
27
-
28
- video.save()
29
-
30
-
31
- if __name__ == "__main__":
32
- main()
@@ -1,316 +0,0 @@
1
- Metadata-Version: 2.1
2
- Name: videopython
3
- Version: 0.2.0
4
- Summary: Minimal video generation and processing library.
5
- Author-email: Bartosz Wójtowicz <bartoszwojtowicz@outlook.com>, Bartosz Rudnikowicz <bartoszrudnikowicz840@gmail.com>, Piotr Pukisz <piotr.pukisz@gmail.com>
6
- License: Apache License
7
- Version 2.0, January 2004
8
- http://www.apache.org/licenses/
9
-
10
- TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
11
-
12
- 1. Definitions.
13
-
14
- "License" shall mean the terms and conditions for use, reproduction,
15
- and distribution as defined by Sections 1 through 9 of this document.
16
-
17
- "Licensor" shall mean the copyright owner or entity authorized by
18
- the copyright owner that is granting the License.
19
-
20
- "Legal Entity" shall mean the union of the acting entity and all
21
- other entities that control, are controlled by, or are under common
22
- control with that entity. For the purposes of this definition,
23
- "control" means (i) the power, direct or indirect, to cause the
24
- direction or management of such entity, whether by contract or
25
- otherwise, or (ii) ownership of fifty percent (50%) or more of the
26
- outstanding shares, or (iii) beneficial ownership of such entity.
27
-
28
- "You" (or "Your") shall mean an individual or Legal Entity
29
- exercising permissions granted by this License.
30
-
31
- "Source" form shall mean the preferred form for making modifications,
32
- including but not limited to software source code, documentation
33
- source, and configuration files.
34
-
35
- "Object" form shall mean any form resulting from mechanical
36
- transformation or translation of a Source form, including but
37
- not limited to compiled object code, generated documentation,
38
- and conversions to other media types.
39
-
40
- "Work" shall mean the work of authorship, whether in Source or
41
- Object form, made available under the License, as indicated by a
42
- copyright notice that is included in or attached to the work
43
- (an example is provided in the Appendix below).
44
-
45
- "Derivative Works" shall mean any work, whether in Source or Object
46
- form, that is based on (or derived from) the Work and for which the
47
- editorial revisions, annotations, elaborations, or other modifications
48
- represent, as a whole, an original work of authorship. For the purposes
49
- of this License, Derivative Works shall not include works that remain
50
- separable from, or merely link (or bind by name) to the interfaces of,
51
- the Work and Derivative Works thereof.
52
-
53
- "Contribution" shall mean any work of authorship, including
54
- the original version of the Work and any modifications or additions
55
- to that Work or Derivative Works thereof, that is intentionally
56
- submitted to Licensor for inclusion in the Work by the copyright owner
57
- or by an individual or Legal Entity authorized to submit on behalf of
58
- the copyright owner. For the purposes of this definition, "submitted"
59
- means any form of electronic, verbal, or written communication sent
60
- to the Licensor or its representatives, including but not limited to
61
- communication on electronic mailing lists, source code control systems,
62
- and issue tracking systems that are managed by, or on behalf of, the
63
- Licensor for the purpose of discussing and improving the Work, but
64
- excluding communication that is conspicuously marked or otherwise
65
- designated in writing by the copyright owner as "Not a Contribution."
66
-
67
- "Contributor" shall mean Licensor and any individual or Legal Entity
68
- on behalf of whom a Contribution has been received by Licensor and
69
- subsequently incorporated within the Work.
70
-
71
- 2. Grant of Copyright License. Subject to the terms and conditions of
72
- this License, each Contributor hereby grants to You a perpetual,
73
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
74
- copyright license to reproduce, prepare Derivative Works of,
75
- publicly display, publicly perform, sublicense, and distribute the
76
- Work and such Derivative Works in Source or Object form.
77
-
78
- 3. Grant of Patent License. Subject to the terms and conditions of
79
- this License, each Contributor hereby grants to You a perpetual,
80
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
81
- (except as stated in this section) patent license to make, have made,
82
- use, offer to sell, sell, import, and otherwise transfer the Work,
83
- where such license applies only to those patent claims licensable
84
- by such Contributor that are necessarily infringed by their
85
- Contribution(s) alone or by combination of their Contribution(s)
86
- with the Work to which such Contribution(s) was submitted. If You
87
- institute patent litigation against any entity (including a
88
- cross-claim or counterclaim in a lawsuit) alleging that the Work
89
- or a Contribution incorporated within the Work constitutes direct
90
- or contributory patent infringement, then any patent licenses
91
- granted to You under this License for that Work shall terminate
92
- as of the date such litigation is filed.
93
-
94
- 4. Redistribution. You may reproduce and distribute copies of the
95
- Work or Derivative Works thereof in any medium, with or without
96
- modifications, and in Source or Object form, provided that You
97
- meet the following conditions:
98
-
99
- (a) You must give any other recipients of the Work or
100
- Derivative Works a copy of this License; and
101
-
102
- (b) You must cause any modified files to carry prominent notices
103
- stating that You changed the files; and
104
-
105
- (c) You must retain, in the Source form of any Derivative Works
106
- that You distribute, all copyright, patent, trademark, and
107
- attribution notices from the Source form of the Work,
108
- excluding those notices that do not pertain to any part of
109
- the Derivative Works; and
110
-
111
- (d) If the Work includes a "NOTICE" text file as part of its
112
- distribution, then any Derivative Works that You distribute must
113
- include a readable copy of the attribution notices contained
114
- within such NOTICE file, excluding those notices that do not
115
- pertain to any part of the Derivative Works, in at least one
116
- of the following places: within a NOTICE text file distributed
117
- as part of the Derivative Works; within the Source form or
118
- documentation, if provided along with the Derivative Works; or,
119
- within a display generated by the Derivative Works, if and
120
- wherever such third-party notices normally appear. The contents
121
- of the NOTICE file are for informational purposes only and
122
- do not modify the License. You may add Your own attribution
123
- notices within Derivative Works that You distribute, alongside
124
- or as an addendum to the NOTICE text from the Work, provided
125
- that such additional attribution notices cannot be construed
126
- as modifying the License.
127
-
128
- You may add Your own copyright statement to Your modifications and
129
- may provide additional or different license terms and conditions
130
- for use, reproduction, or distribution of Your modifications, or
131
- for any such Derivative Works as a whole, provided Your use,
132
- reproduction, and distribution of the Work otherwise complies with
133
- the conditions stated in this License.
134
-
135
- 5. Submission of Contributions. Unless You explicitly state otherwise,
136
- any Contribution intentionally submitted for inclusion in the Work
137
- by You to the Licensor shall be under the terms and conditions of
138
- this License, without any additional terms or conditions.
139
- Notwithstanding the above, nothing herein shall supersede or modify
140
- the terms of any separate license agreement you may have executed
141
- with Licensor regarding such Contributions.
142
-
143
- 6. Trademarks. This License does not grant permission to use the trade
144
- names, trademarks, service marks, or product names of the Licensor,
145
- except as required for reasonable and customary use in describing the
146
- origin of the Work and reproducing the content of the NOTICE file.
147
-
148
- 7. Disclaimer of Warranty. Unless required by applicable law or
149
- agreed to in writing, Licensor provides the Work (and each
150
- Contributor provides its Contributions) on an "AS IS" BASIS,
151
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
152
- implied, including, without limitation, any warranties or conditions
153
- of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
154
- PARTICULAR PURPOSE. You are solely responsible for determining the
155
- appropriateness of using or redistributing the Work and assume any
156
- risks associated with Your exercise of permissions under this License.
157
-
158
- 8. Limitation of Liability. In no event and under no legal theory,
159
- whether in tort (including negligence), contract, or otherwise,
160
- unless required by applicable law (such as deliberate and grossly
161
- negligent acts) or agreed to in writing, shall any Contributor be
162
- liable to You for damages, including any direct, indirect, special,
163
- incidental, or consequential damages of any character arising as a
164
- result of this License or out of the use or inability to use the
165
- Work (including but not limited to damages for loss of goodwill,
166
- work stoppage, computer failure or malfunction, or any and all
167
- other commercial damages or losses), even if such Contributor
168
- has been advised of the possibility of such damages.
169
-
170
- 9. Accepting Warranty or Additional Liability. While redistributing
171
- the Work or Derivative Works thereof, You may choose to offer,
172
- and charge a fee for, acceptance of support, warranty, indemnity,
173
- or other liability obligations and/or rights consistent with this
174
- License. However, in accepting such obligations, You may act only
175
- on Your own behalf and on Your sole responsibility, not on behalf
176
- of any other Contributor, and only if You agree to indemnify,
177
- defend, and hold each Contributor harmless for any liability
178
- incurred by, or claims asserted against, such Contributor by reason
179
- of your accepting any such warranty or additional liability.
180
-
181
- END OF TERMS AND CONDITIONS
182
-
183
- Copyright 2023 Bartosz Wójtowicz
184
- Copyright 2023 Bartosz Rudnikowicz
185
- Copyright 2023 Piotr Pukisz
186
-
187
- Licensed under the Apache License, Version 2.0 (the "License");
188
- you may not use this file except in compliance with the License.
189
- You may obtain a copy of the License at
190
-
191
- http://www.apache.org/licenses/LICENSE-2.0
192
-
193
- Unless required by applicable law or agreed to in writing, software
194
- distributed under the License is distributed on an "AS IS" BASIS,
195
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
196
- See the License for the specific language governing permissions and
197
- limitations under the License.
198
-
199
- Project-URL: Homepage, https://github.com/bartwojtowicz/videopython/
200
- Project-URL: Bug Reports, https://github.com/bartwojtowicz/videopython/issues
201
- Project-URL: Source, https://github.com/bartwojtowicz/videopython/
202
- Keywords: python,videopython,video,movie,opencv,generation,editing
203
- Classifier: License :: OSI Approved :: Apache Software License
204
- Classifier: Programming Language :: Python :: 3
205
- Classifier: Programming Language :: Python :: 3.10
206
- Classifier: Programming Language :: Python :: 3.11
207
- Classifier: Operating System :: OS Independent
208
- Requires-Python: >=3.10
209
- Description-Content-Type: text/markdown
210
- License-File: LICENSE
211
- Requires-Dist: click >=8.1.7
212
- Requires-Dist: numpy >=1.25.2
213
- Requires-Dist: opencv-python >=4.9.0.80
214
- Requires-Dist: pillow >=10.3.0
215
- Requires-Dist: pydub >=0.25.1
216
- Requires-Dist: tqdm >=4.66.3
217
- Provides-Extra: dev
218
- Requires-Dist: black ==24.3.0 ; extra == 'dev'
219
- Requires-Dist: isort ==5.12.0 ; extra == 'dev'
220
- Requires-Dist: mypy ==1.8.0 ; extra == 'dev'
221
- Requires-Dist: pytest ==7.4.0 ; extra == 'dev'
222
- Requires-Dist: types-Pillow ==10.2.0.20240213 ; extra == 'dev'
223
- Requires-Dist: types-tqdm ==4.66.0.20240106 ; extra == 'dev'
224
- Requires-Dist: pydub-stubs ==0.25.1.1 ; extra == 'dev'
225
- Provides-Extra: generation
226
- Requires-Dist: accelerate >=0.29.2 ; extra == 'generation'
227
- Requires-Dist: diffusers >=0.26.3 ; extra == 'generation'
228
- Requires-Dist: torch >=2.1.0 ; extra == 'generation'
229
- Requires-Dist: transformers >=4.38.1 ; extra == 'generation'
230
-
231
- # About
232
-
233
- Minimal video generation and processing library.
234
-
235
- ## Setup
236
-
237
- ### Install ffmpeg
238
- ```bash
239
- # Install with brew for MacOS:
240
- brew install ffmpeg
241
- # Install with apt-get for Ubuntu:
242
- sudo apt-get install ffmpeg
243
- ```
244
-
245
- ### Install with pip
246
- ```bash
247
- pip install videopython[generation]
248
- ```
249
- > You can install without `[generation]` dependencies for basic video handling and processing.
250
- > The funcionalities found in `videopython.generation` won't work.
251
-
252
- ## Basic Usage
253
-
254
- ### Video handling
255
-
256
- ```python
257
- from videopython.base.video import Video
258
-
259
- # Load videos and print metadata
260
- video1 = Video.from_path("tests/test_data/fast_benchmark.mp4")
261
- print(video1)
262
-
263
- video2 = Video.from_path("tests/test_data/slow_benchmark.mp4")
264
- print(video2)
265
-
266
- # Define the transformations
267
- from videopython.base.transforms import CutSeconds, ResampleFPS, Resize, TransformationPipeline
268
-
269
- pipeline = TransformationPipeline(
270
- [CutSeconds(start=1.5, end=6.5), ResampleFPS(fps=30), Resize(width=1000, height=1000)]
271
- )
272
- video1 = pipeline.run(video1)
273
- video2 = pipeline.run(video2)
274
-
275
- # Combine videos, add audio and save
276
- from videopython.base.transitions import FadeTransition
277
-
278
- fade = FadeTransition(effect_time_seconds=3.0)
279
- video = fade.apply(videos=(video1, video2))
280
- video.add_audio_from_file("tests/test_data/test_audio.mp3")
281
-
282
- savepath = video.save()
283
- ```
284
-
285
- ### Video Generation
286
-
287
- > Using Nvidia A40 or better is recommended for the `videopython.generation` module.
288
- ```python
289
- # Generate image and animate it
290
- from videopython.generation import ImageToVideo
291
- from videopython.generation import TextToImage
292
-
293
- image = TextToImage().generate_image(prompt="Golden Retriever playing in the park")
294
- video = ImageToVideo().generate_video(image=image, fps=24)
295
-
296
- # Video generation directly from prompt
297
- from videopython.generation import TextToVideo
298
- video_gen = TextToVideo()
299
- video = video_gen.generate_video("Dogs playing in the snow")
300
- for _ in range(10):
301
- video += video_gen.generate_video("Dogs playing in the snow")
302
-
303
- # Cut the first 2 seconds
304
- from videopython.base.transforms import CutSeconds
305
- transformed_video = CutSeconds(start_second=0, end_second=2).apply(video.copy())
306
-
307
- # Upsample to 30 FPS
308
- from videopython.base.transforms import ResampleFPS
309
- transformed_video = ResampleFPS(new_fps=30).apply(transformed_video)
310
-
311
- # Resize to 1000x1000
312
- from videopython.base.transforms import Resize
313
- transformed_video = Resize(width=1000, height=1000).apply(transformed_video)
314
-
315
- filepath = transformed_video.save()
316
- ```
@@ -1 +0,0 @@
1
- videopython