videopython 0.2.0__py3-none-any.whl → 0.3.0__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
@@ -67,7 +67,7 @@ class FadeTransition(Transition):
67
67
  ],
68
68
  fps=video_fps,
69
69
  )
70
- faded_videos.audio = videos[0].audio.append(videos[1].audio, crossfade=(effect_time_fps / video_fps) * 1000)
70
+ faded_videos.audio = videos[0].audio.concat(videos[1].audio, crossfade=(effect_time_fps / video_fps))
71
71
  return faded_videos
72
72
 
73
73
 
@@ -102,5 +102,5 @@ class BlurTransition(Transition):
102
102
  ],
103
103
  fps=video_fps,
104
104
  )
105
- blurred_videos.audio = videos[0].audio.append(videos[1].audio)
105
+ blurred_videos.audio = videos[0].audio.concat(videos[1].audio)
106
106
  return blurred_videos
videopython/base/video.py CHANGED
@@ -1,15 +1,18 @@
1
1
  from __future__ import annotations
2
2
 
3
- import shlex
4
3
  import subprocess
4
+ import tempfile
5
5
  from dataclasses import dataclass
6
6
  from pathlib import Path
7
+ from typing import Literal, get_args
7
8
 
8
9
  import cv2
9
10
  import numpy as np
10
- from pydub import AudioSegment
11
+ from soundpython import Audio
11
12
 
12
- from videopython.utils.common import check_path, generate_random_name
13
+ from videopython.utils.common import generate_random_name
14
+
15
+ ALLOWED_VIDEO_FORMATS = Literal["mp4", "avi", "mov", "mkv", "webm"]
13
16
 
14
17
 
15
18
  @dataclass
@@ -38,11 +41,7 @@ class VideoMetadata:
38
41
 
39
42
  @classmethod
40
43
  def from_path(cls, video_path: str) -> VideoMetadata:
41
- """Creates VideoMetadata object from video file.
42
-
43
- Args:
44
- video_path: Path to video file.
45
- """
44
+ """Creates VideoMetadata object from video file."""
46
45
  video = cv2.VideoCapture(video_path)
47
46
  frame_count = int(video.get(cv2.CAP_PROP_FRAME_COUNT))
48
47
  fps = round(video.get(cv2.CAP_PROP_FPS), 2)
@@ -60,13 +59,7 @@ class VideoMetadata:
60
59
 
61
60
  @classmethod
62
61
  def from_video(cls, video: Video) -> VideoMetadata:
63
- """Creates VideoMetadata object from frames.
64
-
65
- Args:
66
- frames: Frames of the video.
67
- fps: Frames per second of the video.
68
- """
69
-
62
+ """Creates VideoMetadata object from Video instance."""
70
63
  frame_count, height, width, _ = video.frames.shape
71
64
  total_seconds = round(frame_count / video.fps, 2)
72
65
 
@@ -112,11 +105,14 @@ class Video:
112
105
  def from_path(cls, path: str) -> Video:
113
106
  new_vid = cls()
114
107
  new_vid.frames, new_vid.fps = cls._load_video_from_path(path)
115
- audio = cls._load_audio_from_path(path)
116
- if not audio:
108
+
109
+ try:
110
+ new_vid.audio = Audio.from_file(path)
111
+ except Exception as e:
117
112
  print(f"No audio found for `{path}`, adding silent track!")
118
- audio = AudioSegment.silent(duration=round(new_vid.total_seconds * 1000))
119
- new_vid.audio = audio
113
+ new_vid.audio = Audio.create_silent(
114
+ duration_seconds=round(new_vid.total_seconds, 2), stereo=True, sample_rate=44100
115
+ )
120
116
  return new_vid
121
117
 
122
118
  @classmethod
@@ -130,7 +126,9 @@ class Video:
130
126
  raise ValueError(f"Unsupported number of dimensions: {frames.shape}!")
131
127
  new_vid.frames = frames
132
128
  new_vid.fps = fps
133
- new_vid.audio = AudioSegment.silent(duration=round(new_vid.total_seconds * 1000))
129
+ new_vid.audio = Audio.create_silent(
130
+ duration_seconds=round(new_vid.total_seconds, 2), stereo=True, sample_rate=44100
131
+ )
134
132
  return new_vid
135
133
 
136
134
  @classmethod
@@ -140,12 +138,12 @@ class Video:
140
138
  image = np.expand_dims(image, axis=0)
141
139
  new_vid.frames = np.repeat(image, round(length_seconds * fps), axis=0)
142
140
  new_vid.fps = fps
143
- new_vid.audio = AudioSegment.silent(duration=round(new_vid.total_seconds * 1000))
141
+ new_vid.audio = Audio.create_silent(duration_seconds=length_seconds, stereo=True, sample_rate=44100)
144
142
  return new_vid
145
143
 
146
144
  def copy(self) -> Video:
147
145
  copied = Video().from_frames(self.frames.copy(), self.fps)
148
- copied.audio = self.audio
146
+ copied.audio = self.audio # Audio objects are immutable, no need to copy
149
147
  return copied
150
148
 
151
149
  def is_loaded(self) -> bool:
@@ -161,87 +159,126 @@ class Video:
161
159
  self.from_frames(self.frames[:frame_idx], self.fps),
162
160
  self.from_frames(self.frames[frame_idx:], self.fps),
163
161
  )
164
- audio_midpoint = (frame_idx / self.fps) * 1000
165
- split_videos[0].audio = self.audio[:audio_midpoint]
166
- split_videos[1].audio = self.audio[audio_midpoint:]
167
- return split_videos
168
-
169
- def save(self, filename: str | None = None) -> str:
170
- """Saves the video.
171
-
172
- Args:
173
- filename: Name of the output video file. Generates random UUID name if not provided.
174
- """
175
- if not self.is_loaded():
176
- raise RuntimeError(f"Video is not loaded, cannot save!")
177
162
 
178
- if filename is None:
179
- filename = generate_random_name(suffix=".mp4")
180
- filename = check_path(filename, dir_exists=True, suffix=".mp4")
163
+ # Split audio at the corresponding time point
164
+ split_time = frame_idx / self.fps
165
+ split_videos[0].audio = self.audio.slice(start_seconds=0, end_seconds=split_time)
166
+ split_videos[1].audio = self.audio.slice(start_seconds=split_time)
181
167
 
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
- )
168
+ return split_videos
187
169
 
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
- )
170
+ def save(self, filename: str | Path | None = None, format: ALLOWED_VIDEO_FORMATS = "mp4") -> Path:
171
+ if not self.is_loaded():
172
+ raise RuntimeError("Video is not loaded, cannot save!")
193
173
 
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,
174
+ if format.lower() not in get_args(ALLOWED_VIDEO_FORMATS):
175
+ raise ValueError(
176
+ f"Unsupported format: {format}. Allowed formats are: {', '.join(get_args(ALLOWED_VIDEO_FORMATS))}"
201
177
  )
202
- except subprocess.CalledProcessError as e:
203
- print("Error saving frames to video!")
204
- raise e
205
178
 
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
-
215
- print(f"Video saved into `{filename}`!")
216
- return filename
217
-
218
- def add_audio_from_file(self, path: str, overlay: bool = True, overlay_gain: int = 0, loop: bool = False) -> None:
219
- new_audio = self._load_audio_from_path(path)
220
- if new_audio is None:
221
- print(f"Audio file `{path}` not found, skipping!")
222
- return
223
-
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)]
228
-
229
- if overlay:
230
- self.audio = self.audio.overlay(new_audio, loop=loop, gain_during_overlay=overlay_gain)
179
+ if filename is None:
180
+ filename = Path(generate_random_name(suffix=f".{format}"))
181
+ else:
182
+ filename = Path(filename).with_suffix(f".{format}")
183
+ filename.parent.mkdir(parents=True, exist_ok=True)
184
+
185
+ with tempfile.TemporaryDirectory() as temp_dir:
186
+ temp_dir_path = Path(temp_dir)
187
+
188
+ # Save frames as images
189
+ for i, frame in enumerate(self.frames):
190
+ frame_path = temp_dir_path / f"frame_{i:04d}.png"
191
+ cv2.imwrite(str(frame_path), cv2.cvtColor(frame, cv2.COLOR_RGB2BGR))
192
+
193
+ # Calculate exact video duration
194
+ video_duration = len(self.frames) / self.fps
195
+
196
+ # Ensure audio duration matches video duration
197
+ if (
198
+ abs(self.audio.metadata.duration_seconds - video_duration) > 0.001
199
+ ): # Small threshold for float comparison
200
+ if self.audio.metadata.duration_seconds < video_duration:
201
+ # Create silent audio for the remaining duration
202
+ remaining_duration = video_duration - self.audio.metadata.duration_seconds
203
+ silent_audio = Audio.create_silent(
204
+ duration_seconds=remaining_duration,
205
+ stereo=(self.audio.metadata.channels == 2),
206
+ sample_rate=self.audio.metadata.sample_rate,
207
+ sample_width=self.audio.metadata.sample_width,
208
+ )
209
+ # Concatenate original audio with silent padding
210
+ padded_audio = self.audio.concat(silent_audio)
211
+ else:
212
+ # Trim audio to match video duration
213
+ padded_audio = self.audio.slice(end_seconds=video_duration)
214
+ else:
215
+ padded_audio = self.audio
216
+
217
+ # Save audio to temporary WAV file
218
+ temp_audio = temp_dir_path / "temp_audio.wav"
219
+ padded_audio.save(str(temp_audio), format="wav")
220
+
221
+ # Construct FFmpeg command with explicit duration
222
+ ffmpeg_command = [
223
+ "ffmpeg",
224
+ "-y",
225
+ "-framerate",
226
+ str(self.fps), # Use -framerate instead of -r for input
227
+ "-i",
228
+ str(temp_dir_path / "frame_%04d.png"),
229
+ "-i",
230
+ str(temp_audio),
231
+ "-c:v",
232
+ "libx264",
233
+ "-preset",
234
+ "medium",
235
+ "-crf",
236
+ "23",
237
+ "-c:a",
238
+ "aac", # Use AAC instead of copy for more reliable audio
239
+ "-b:a",
240
+ "192k",
241
+ "-pix_fmt",
242
+ "yuv420p",
243
+ "-map",
244
+ "0:v:0", # Map video from first input
245
+ "-map",
246
+ "1:a:0", # Map audio from second input
247
+ "-vsync",
248
+ "cfr", # Force constant frame rate
249
+ str(filename),
250
+ ]
251
+
252
+ try:
253
+ subprocess.run(ffmpeg_command, check=True, capture_output=True, text=True)
254
+ return filename
255
+ except subprocess.CalledProcessError as e:
256
+ print(f"Error saving video: {e}")
257
+ print(f"FFmpeg stderr: {e.stderr}")
258
+ raise
259
+
260
+ def add_audio(self, audio: Audio, overlay: bool = True) -> None:
261
+ if self.audio.is_silent:
262
+ self.audio = audio
263
+ elif overlay:
264
+ self.audio = self.audio.overlay(audio, position=0.0)
231
265
  else:
232
- self.audio = new_audio
266
+ self.audio = audio
267
+
268
+ def add_audio_from_file(self, path: str, overlay: bool = True) -> None:
269
+ try:
270
+ new_audio = Audio.from_file(path)
271
+ self.add_audio(new_audio, overlay)
272
+ except Exception as e:
273
+ print(f"Audio file `{path}` not found or invalid, skipping!")
233
274
 
234
275
  def __add__(self, other: Video) -> Video:
235
- # TODO: Should it be class method? How to make it work with sum()?
236
276
  if self.fps != other.fps:
237
277
  raise ValueError("FPS of videos do not match!")
238
278
  elif self.frame_shape != other.frame_shape:
239
- raise ValueError(
240
- "Resolutions of the images do not match: "
241
- f"{self.frame_shape} not compatible with {other.frame_shape}."
242
- )
279
+ raise ValueError(f"Resolutions do not match: {self.frame_shape} vs {other.frame_shape}")
243
280
  new_video = self.from_frames(np.r_["0,2", self.frames, other.frames], fps=self.fps)
244
- new_video.audio = self.audio + other.audio
281
+ new_video.audio = self.audio.concat(other.audio)
245
282
  return new_video
246
283
 
247
284
  def __str__(self) -> str:
@@ -251,65 +288,58 @@ class Video:
251
288
  if not isinstance(val, slice):
252
289
  raise ValueError("Only slices are supported for video indexing!")
253
290
 
254
- # Sub-slice video if given a slice
291
+ # Sub-slice video frames
255
292
  sliced = self.from_frames(self.frames[val], fps=self.fps)
256
- # Handle slicing without value for audio
293
+
294
+ # Handle slicing bounds for audio
257
295
  start = val.start if val.start else 0
258
296
  stop = val.stop if val.stop else len(self.frames)
259
- # Handle negative values for audio slices
260
297
  if start < 0:
261
298
  start = len(self.frames) + start
262
299
  if stop < 0:
263
300
  stop = len(self.frames) + stop
264
- # Append audio to the slice
265
- audio_start = round(start / self.fps) * 1000
266
- audio_end = round(stop / self.fps) * 1000
267
- sliced.audio = self.audio[audio_start:audio_end]
268
- return sliced
269
301
 
270
- @staticmethod
271
- def _load_audio_from_path(path: str) -> AudioSegment | None:
272
- try:
273
- audio = AudioSegment.from_file(path)
274
- return audio
275
- except IndexError:
276
- return None
302
+ # Slice audio to match video duration
303
+ audio_start = start / self.fps
304
+ audio_end = stop / self.fps
305
+ sliced.audio = self.audio.slice(start_seconds=audio_start, end_seconds=audio_end)
306
+ return sliced
277
307
 
278
308
  @staticmethod
279
309
  def _load_video_from_path(path: str) -> tuple[np.ndarray, float]:
280
- """Loads frames and fps information from video file.
310
+ cap = cv2.VideoCapture(path)
311
+ if not cap.isOpened():
312
+ raise ValueError(f"Unable to open video file: {path}")
281
313
 
282
- Args:
283
- path: Path to video file.
284
- """
285
- metadata = VideoMetadata.from_path(path)
286
- ffmpeg_command = f"ffmpeg -i {path} -f rawvideo -pix_fmt rgb24 -loglevel quiet pipe:1"
314
+ fps = cap.get(cv2.CAP_PROP_FPS)
315
+ frames = []
316
+
317
+ while True:
318
+ ret, frame = cap.read()
319
+ if not ret:
320
+ break
321
+ frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
322
+ frames.append(frame)
323
+
324
+ cap.release()
287
325
 
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()
326
+ if not frames:
327
+ raise ValueError(f"No frames could be read from the video file: {path}")
291
328
 
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
329
+ return np.array(frames), fps
296
330
 
297
331
  @property
298
332
  def video_shape(self) -> tuple[int, int, int, int]:
299
- """Returns 4D video shape."""
300
333
  return self.frames.shape
301
334
 
302
335
  @property
303
336
  def frame_shape(self) -> tuple[int, int, int]:
304
- """Returns 3D frame shape."""
305
337
  return self.frames.shape[1:]
306
338
 
307
339
  @property
308
340
  def total_seconds(self) -> float:
309
- """Returns total seconds of the video."""
310
341
  return round(self.frames.shape[0] / self.fps, 4)
311
342
 
312
343
  @property
313
344
  def metadata(self) -> VideoMetadata:
314
- """Returns VideoMetadata object."""
315
345
  return VideoMetadata.from_video(self)
@@ -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,14 @@
1
- import numpy as np
2
1
  import torch
3
- from pydub import AudioSegment
4
- from transformers import AutoTokenizer, VitsModel
2
+ from soundpython import Audio, AudioMetadata
3
+ from transformers import (
4
+ AutoProcessor,
5
+ AutoTokenizer,
6
+ MusicgenForConditionalGeneration,
7
+ VitsModel,
8
+ )
5
9
 
6
10
  TEXT_TO_SPEECH_MODEL = "facebook/mms-tts-eng"
11
+ MUSIC_GENERATION_MODEL_SMALL = "facebook/musicgen-small"
7
12
 
8
13
 
9
14
  class TextToSpeech:
@@ -11,12 +16,53 @@ class TextToSpeech:
11
16
  self.pipeline = VitsModel.from_pretrained(TEXT_TO_SPEECH_MODEL)
12
17
  self.tokenizer = AutoTokenizer.from_pretrained(TEXT_TO_SPEECH_MODEL)
13
18
 
14
- def generate_audio(self, text: str) -> AudioSegment:
19
+ def generate_audio(self, text: str) -> Audio:
15
20
  tokenized = self.tokenizer(text, return_tensors="pt")
16
21
 
17
22
  with torch.no_grad():
18
23
  output = self.pipeline(**tokenized).waveform
19
24
 
20
- output = (output.T.float().numpy() * (2**31 - 1)).astype(np.int32)
21
- audio = AudioSegment(data=output, frame_rate=self.pipeline.config.sampling_rate, sample_width=4, channels=1)
22
- return audio
25
+ # Convert to float32 and normalize to [-1, 1]
26
+ audio_data = output.T.float().numpy()
27
+
28
+ metadata = AudioMetadata(
29
+ sample_rate=self.pipeline.config.sampling_rate,
30
+ channels=1,
31
+ sample_width=4,
32
+ duration_seconds=len(audio_data) / self.pipeline.config.sampling_rate,
33
+ frame_count=len(audio_data),
34
+ )
35
+
36
+ return Audio(audio_data, metadata)
37
+
38
+
39
+ class TextToMusic:
40
+ def __init__(self) -> None:
41
+ """
42
+ Generates music from text using the Musicgen model.
43
+ Check the license for the model before using it.
44
+ """
45
+ self.processor = AutoProcessor.from_pretrained(MUSIC_GENERATION_MODEL_SMALL)
46
+ self.model = MusicgenForConditionalGeneration.from_pretrained(MUSIC_GENERATION_MODEL_SMALL)
47
+
48
+ def generate_audio(self, text: str, max_new_tokens: int) -> Audio:
49
+ inputs = self.processor(
50
+ text=[text],
51
+ padding=True,
52
+ return_tensors="pt",
53
+ )
54
+ audio_values = self.model.generate(**inputs, max_new_tokens=max_new_tokens)
55
+ sampling_rate = self.model.config.audio_encoder.sampling_rate
56
+
57
+ # Convert to float32 and normalize to [-1, 1]
58
+ audio_data = audio_values[0, 0].float().numpy()
59
+
60
+ metadata = AudioMetadata(
61
+ sample_rate=sampling_rate,
62
+ channels=1,
63
+ sample_width=4,
64
+ duration_seconds=len(audio_data) / sampling_rate,
65
+ frame_count=len(audio_data),
66
+ )
67
+
68
+ return Audio(audio_data, metadata)
videopython/py.typed ADDED
File without changes
@@ -197,6 +197,10 @@ class ImageText:
197
197
  # Find bounding rectangle for written text
198
198
  box_slice = img[y:current_text_height, x : x + box_width]
199
199
  text_mask = np.any(box_slice != 0, axis=2).astype(np.uint8)
200
+ if not isinstance(text_mask, np.ndarray):
201
+ raise TypeError(
202
+ f"The returned text mask is of type {type(text_mask)}, " "but it should be numpy array!"
203
+ )
200
204
  xmin, xmax, ymin, ymax = self._find_smallest_bounding_rect(text_mask)
201
205
  # Get global bounding box position
202
206
  xmin += x - background_padding
@@ -0,0 +1,118 @@
1
+ Metadata-Version: 2.4
2
+ Name: videopython
3
+ Version: 0.3.0
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: soundpython>=0.1.9
23
+ Requires-Dist: tqdm>=4.66.3
24
+ Description-Content-Type: text/markdown
25
+
26
+ # About
27
+
28
+ Minimal video generation and processing library.
29
+
30
+ ## Setup
31
+
32
+ ### Install ffmpeg
33
+ ```bash
34
+ # Install with brew for MacOS:
35
+ brew install ffmpeg
36
+ # Install with apt-get for Ubuntu:
37
+ sudo apt-get install ffmpeg
38
+ ```
39
+
40
+ ### Install with pip
41
+ ```bash
42
+ pip install videopython[generation]
43
+ ```
44
+ > You can install without `[generation]` dependencies for basic video handling and processing.
45
+ > The funcionalities found in `videopython.generation` won't work.
46
+
47
+ ## Basic Usage
48
+
49
+ ### Video handling
50
+
51
+ ```python
52
+ from videopython.base.video import Video
53
+
54
+ # Load videos and print metadata
55
+ video1 = Video.from_path("tests/test_data/fast_benchmark.mp4")
56
+ print(video1)
57
+
58
+ video2 = Video.from_path("tests/test_data/slow_benchmark.mp4")
59
+ print(video2)
60
+
61
+ # Define the transformations
62
+ from videopython.base.transforms import CutSeconds, ResampleFPS, Resize, TransformationPipeline
63
+
64
+ pipeline = TransformationPipeline(
65
+ [CutSeconds(start=1.5, end=6.5), ResampleFPS(fps=30), Resize(width=1000, height=1000)]
66
+ )
67
+ video1 = pipeline.run(video1)
68
+ video2 = pipeline.run(video2)
69
+
70
+ # Combine videos, add audio and save
71
+ from videopython.base.transitions import FadeTransition
72
+
73
+ fade = FadeTransition(effect_time_seconds=3.0)
74
+ video = fade.apply(videos=(video1, video2))
75
+ video.add_audio_from_file("tests/test_data/test_audio.mp3")
76
+
77
+ savepath = video.save()
78
+ ```
79
+
80
+ ### Video Generation
81
+
82
+ > Using Nvidia A40 or better is recommended for the `videopython.generation` module.
83
+ ```python
84
+ # Generate image and animate it
85
+ from videopython.generation import ImageToVideo
86
+ from videopython.generation import TextToImage
87
+ from videopython.generation import TextToMusic
88
+
89
+ image = TextToImage().generate_image(prompt="Golden Retriever playing in the park")
90
+ video = ImageToVideo().generate_video(image=image, fps=24)
91
+
92
+ # Video generation directly from prompt
93
+ from videopython.generation import TextToVideo
94
+ video_gen = TextToVideo()
95
+ video = video_gen.generate_video("Dogs playing in the snow")
96
+ for _ in range(10):
97
+ video += video_gen.generate_video("Dogs playing in the snow")
98
+
99
+ # Cut the first 2 seconds
100
+ from videopython.base.transforms import CutSeconds
101
+ transformed_video = CutSeconds(start_second=0, end_second=2).apply(video.copy())
102
+
103
+ # Upsample to 30 FPS
104
+ from videopython.base.transforms import ResampleFPS
105
+ transformed_video = ResampleFPS(new_fps=30).apply(transformed_video)
106
+
107
+ # Resize to 1000x1000
108
+ from videopython.base.transforms import Resize
109
+ transformed_video = Resize(width=1000, height=1000).apply(transformed_video)
110
+
111
+ # Add generated music
112
+ # MusicGen cannot generate more than 1503 tokens (~30seconds of audio)
113
+ text_to_music = TextToMusic()
114
+ audio = text_to_music.generate_audio("Happy dogs playing together in a park", max_new_tokens=256)
115
+ transformed_video.add_audio(audio=audio)
116
+
117
+ filepath = transformed_video.save()
118
+ ```
@@ -0,0 +1,20 @@
1
+ videopython/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
+ videopython/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
3
+ videopython/base/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
4
+ videopython/base/compose.py,sha256=pti12VY3Yg7TZZiENPF6veM8POWssfsK8ePDdGlhAhA,1968
5
+ videopython/base/effects.py,sha256=ZFUWrgVWTn4uWpxPfTQSQQKEZN5ns4btMofOZNHCeQc,7540
6
+ videopython/base/exceptions.py,sha256=68_16lUPOR9_zhWdeBGS8_NFI32VbrcoDbN5KHHg0_w,44
7
+ videopython/base/transforms.py,sha256=VP8SGArokfXN-IE7tk-3i0oMM3HV5zpJa-GLj7BoeRo,5856
8
+ videopython/base/transitions.py,sha256=P1bBsxugf5i0JEtx7MoRgxWSIDcBli-0QucRwBIFGqs,3687
9
+ videopython/base/video.py,sha256=8hIIr-LzLktuPpNG3IvuqhSSDwT0jXbQmpv9wo7TMhc,12304
10
+ videopython/generation/__init__.py,sha256=5esJ7_PPSkqNXuPQWLLAyeQZY00BnYFc94WZIHi7pBU,233
11
+ videopython/generation/audio.py,sha256=CNf6ZeV3iU4CU0Kq8HtDLwLPP2ABq9AGQD1TBOSLyoQ,2230
12
+ videopython/generation/image.py,sha256=i8zJm0WXn_Pykby9Urw1kzDcla6ArYhRgG-ueRdoAJ0,675
13
+ videopython/generation/video.py,sha256=206YON_XjPTYyjIJ3j5uBgd_yHmCDg7SqbkIU9GzEgw,1831
14
+ videopython/utils/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
15
+ videopython/utils/common.py,sha256=F-30YoKUwWDI7HiJUWw0gRFUguhShSVaxT0aFfvpifg,936
16
+ videopython/utils/image.py,sha256=MAncPG_vY4ZnewIsjgkCCzKJm2XtZXPiNRv3Zyc0AYM,12298
17
+ videopython-0.3.0.dist-info/METADATA,sha256=YvNIxT652bGaoNbob_vrXVg9SJxnbpudCKkbdTfNfJo,3879
18
+ videopython-0.3.0.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
19
+ videopython-0.3.0.dist-info/licenses/LICENSE,sha256=nJL9jVOt2MSW7swNDq4Y6oD_n9bLI0B0afr8ougtZ6s,10832
20
+ videopython-0.3.0.dist-info/RECORD,,
@@ -1,5 +1,4 @@
1
1
  Wheel-Version: 1.0
2
- Generator: setuptools (70.1.1)
2
+ Generator: hatchling 1.27.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,20 +0,0 @@
1
- videopython/base/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
- videopython/base/compose.py,sha256=pti12VY3Yg7TZZiENPF6veM8POWssfsK8ePDdGlhAhA,1968
3
- videopython/base/effects.py,sha256=ZFUWrgVWTn4uWpxPfTQSQQKEZN5ns4btMofOZNHCeQc,7540
4
- videopython/base/exceptions.py,sha256=68_16lUPOR9_zhWdeBGS8_NFI32VbrcoDbN5KHHg0_w,44
5
- videopython/base/transforms.py,sha256=VP8SGArokfXN-IE7tk-3i0oMM3HV5zpJa-GLj7BoeRo,5856
6
- 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
10
- videopython/generation/image.py,sha256=i8zJm0WXn_Pykby9Urw1kzDcla6ArYhRgG-ueRdoAJ0,675
11
- videopython/generation/pipeline.py,sha256=v8GHkGNLErnQBjzNA8oem7fRv7YOx_NdduEC47kQkf0,773
12
- videopython/generation/video.py,sha256=206YON_XjPTYyjIJ3j5uBgd_yHmCDg7SqbkIU9GzEgw,1831
13
- videopython/utils/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
14
- videopython/utils/common.py,sha256=F-30YoKUwWDI7HiJUWw0gRFUguhShSVaxT0aFfvpifg,936
15
- 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,,
@@ -1 +0,0 @@
1
- videopython