visualkit 0.0.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.
visualkit/__init__.py ADDED
@@ -0,0 +1,6 @@
1
+ from .config import VideoConfig
2
+ from .editor import SimpleVideoEditor
3
+ from .enums import AnimationType
4
+ from .media_element import MediaElement
5
+ from .text_element import SubtitleElement, TextRenderer
6
+ from .transitions import TransitionElement
visualkit/__main__.py ADDED
@@ -0,0 +1,5 @@
1
+ # Entry point
2
+ from . import main
3
+
4
+ if __name__ == "__main__":
5
+ main()
visualkit/config.py ADDED
@@ -0,0 +1,26 @@
1
+ from dataclasses import dataclass
2
+
3
+
4
+ @dataclass
5
+ class VideoConfig:
6
+ """Video configuration for the video editor.
7
+ Attributes:
8
+ width (int): Width of the video in pixels.
9
+ height (int): Height of the video in pixels.
10
+ fps (int): Frames per second for the video.
11
+ codec (str): Codec to use for video encoding.
12
+ resize_method (str): Method to use for resizing images. [adaptive (default)] Options: smart, adaptive, gradual, aspect_ratio.
13
+ """ # noqa: E501
14
+
15
+ width: int = 1280
16
+ height: int = 720
17
+ fps: int = 30
18
+ codec: str = "avc1"
19
+ resize_method: str = "adaptive" # Options: smart, adaptive, gradual, aspect_ratio
20
+
21
+ def __post_init__(self):
22
+ """Validate configuration parameters"""
23
+ if self.width <= 0 or self.height <= 0:
24
+ raise ValueError("Width and height must be positive")
25
+ if self.fps <= 0:
26
+ raise ValueError("FPS must be positive")
visualkit/editor.py ADDED
@@ -0,0 +1,183 @@
1
+ from typing import Any, Dict
2
+
3
+ import cv2
4
+ import numpy as np
5
+
6
+ from visualkit.config import VideoConfig
7
+ from visualkit.enums import AnimationType
8
+ from visualkit.media_element import MediaElement
9
+ from visualkit.text_element import SubtitleElement, TextRenderer
10
+ from visualkit.timeline import Timeline
11
+ from visualkit.transitions import TransitionElement
12
+ from visualkit.utils import logger
13
+
14
+
15
+ class SimpleVideoEditor:
16
+ def __init__(self, config: VideoConfig | None = None):
17
+ self.config = config or VideoConfig()
18
+ self.text_renderer = TextRenderer(self.config)
19
+ self.timeline = Timeline()
20
+ self.subtitle_elements = []
21
+
22
+ def load_from_json(self, json_data: Dict[str, Any]):
23
+ try:
24
+ config_data = json_data.get("config", {})
25
+ self.config.width = config_data.get("width", self.config.width)
26
+ self.config.height = config_data.get("height", self.config.height)
27
+ self.config.fps = config_data.get("fps", self.config.fps)
28
+ self.config.codec = config_data.get("codec", self.config.codec)
29
+ self.config.resize_method = config_data.get(
30
+ "resize_method", self.config.resize_method
31
+ )
32
+ self.config.__post_init__()
33
+ self.text_renderer = TextRenderer(self.config)
34
+ assets = json_data.get("assets", {})
35
+ main_layer = json_data.get("main_layer", [])
36
+ current_time = 0.0
37
+ for element_data in main_layer:
38
+ element_type = element_data.get("type")
39
+ if element_type == "media":
40
+ media_id = element_data.get("media")
41
+ duration = element_data.get("duration", 5.0)
42
+ effect = element_data.get("effect", "none")
43
+ if media_id in assets:
44
+ asset_path = assets[media_id]["path"]
45
+ try:
46
+ media_element = MediaElement(asset_path, duration, effect)
47
+ self.timeline.add_element(
48
+ media_element, current_time, current_time + duration
49
+ )
50
+ current_time += duration
51
+ except Exception as e:
52
+ logger.error(f"Failed to load media {asset_path}: {e}")
53
+ continue
54
+ elif element_type == "transition":
55
+ duration = element_data.get("duration", 1.0)
56
+ transition_type = element_data.get("transition_type", "crossfade")
57
+ try:
58
+ transition_element = TransitionElement(
59
+ duration, transition_type
60
+ )
61
+ self.timeline.add_element(
62
+ transition_element, current_time, current_time + duration
63
+ )
64
+ current_time += duration
65
+ except Exception as e:
66
+ logger.error(f"Failed to create transition: {e}")
67
+ continue
68
+ subtitle_layers = json_data.get("subtitle_layers", [])
69
+ for layer_data in subtitle_layers:
70
+ for subtitle_data in layer_data.get("elements", []):
71
+ try:
72
+ start_time = self._parse_time(
73
+ subtitle_data.get("start_time", 0)
74
+ )
75
+ end_time = self._parse_time(subtitle_data.get("end_time", 5))
76
+ text = subtitle_data.get("text", "")
77
+ animation_type = AnimationType(
78
+ subtitle_data.get("animation_type", "typewriter")
79
+ )
80
+ typewriter_speed = subtitle_data.get("typewriter_speed", 20.0)
81
+ subtitle = SubtitleElement(
82
+ start_time, end_time, text, animation_type, typewriter_speed
83
+ )
84
+ self.subtitle_elements.append(subtitle)
85
+ except Exception as e:
86
+ logger.error(f"Failed to create subtitle: {e}")
87
+ continue
88
+ except Exception as e:
89
+ logger.error(f"Error loading project: {e}")
90
+ raise
91
+
92
+ def _parse_time(self, time_str) -> float:
93
+ if isinstance(time_str, (int, float)):
94
+ return float(time_str)
95
+ if ":" in str(time_str):
96
+ try:
97
+ parts = str(time_str).split(":")
98
+ if len(parts) == 2:
99
+ minutes = int(parts[0])
100
+ seconds = int(parts[1])
101
+ return minutes * 60 + seconds
102
+ except ValueError:
103
+ pass
104
+ return float(time_str)
105
+
106
+ def get_duration(self) -> float:
107
+ return self.timeline.get_duration()
108
+
109
+ def render_frame(self, timestamp: float) -> np.ndarray:
110
+ frame = np.zeros((self.config.height, self.config.width, 3), dtype=np.uint8)
111
+ active_element_info = self.timeline.get_active_element(timestamp)
112
+ if active_element_info:
113
+ element = active_element_info["element"]
114
+ local_time = timestamp - active_element_info["start_time"]
115
+ if isinstance(element, MediaElement):
116
+ frame = element.get_frame(local_time, self.config)
117
+ elif isinstance(element, TransitionElement):
118
+ prev_info = self.timeline.get_previous_media_element(
119
+ active_element_info["start_time"]
120
+ )
121
+ next_info = self.timeline.get_next_media_element(
122
+ active_element_info["end_time"]
123
+ )
124
+ prev_frame = frame
125
+ next_frame = frame
126
+ if prev_info:
127
+ prev_frame = prev_info["element"].get_frame(
128
+ prev_info["element"].duration - 0.001, self.config
129
+ )
130
+ if next_info:
131
+ next_frame = next_info["element"].get_frame(0.001, self.config)
132
+ frame = element.apply(prev_frame, next_frame, local_time)
133
+ for subtitle in self.subtitle_elements:
134
+ frame = self.text_renderer.render_subtitle(frame, subtitle, timestamp)
135
+ return frame
136
+
137
+ def render_video(self, output_path: str, show_progress: bool = True) -> bool:
138
+ duration = self.get_duration()
139
+ if duration <= 0:
140
+ logger.error("Project has no duration")
141
+ return False
142
+ total_frames = int(duration * self.config.fps)
143
+ if total_frames <= 0:
144
+ logger.error("Invalid frame count")
145
+ return False
146
+ fourcc = cv2.VideoWriter_fourcc(*self.config.codec)
147
+ out = cv2.VideoWriter(
148
+ output_path,
149
+ fourcc,
150
+ self.config.fps,
151
+ (self.config.width, self.config.height),
152
+ )
153
+ if not out.isOpened():
154
+ logger.error(f"Could not open video writer for {output_path}")
155
+ return False
156
+ try:
157
+ for frame_idx in range(total_frames):
158
+ timestamp = frame_idx / self.config.fps
159
+ frame = self.render_frame(timestamp)
160
+ if frame.shape[:2] != (self.config.height, self.config.width):
161
+ frame = cv2.resize(
162
+ frame,
163
+ (self.config.width, self.config.height),
164
+ interpolation=cv2.INTER_AREA,
165
+ )
166
+ out.write(frame)
167
+ if show_progress and frame_idx % 30 == 0:
168
+ progress = (frame_idx + 1) / total_frames
169
+ print(f"\rRendering: {progress:.1%}", end="", flush=True)
170
+ if show_progress:
171
+ print("\nRendering complete!")
172
+ return True
173
+ except Exception as e:
174
+ logger.error(f"Error during rendering: {e}")
175
+ return False
176
+ finally:
177
+ out.release()
178
+ self.cleanup()
179
+
180
+ def cleanup(self):
181
+ for elem_info in self.timeline.elements:
182
+ if isinstance(elem_info["element"], MediaElement):
183
+ elem_info["element"].cleanup()
visualkit/enums.py ADDED
@@ -0,0 +1,7 @@
1
+ from enum import Enum
2
+
3
+
4
+ class AnimationType(Enum):
5
+ TYPEWRITER = "typewriter"
6
+ FADE_IN = "fade_in"
7
+ SIMPLE = "simple"