-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
550 lines (453 loc) · 17.8 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
#!/usr/bin/env python3
import os
import re
import sys
import shutil
import zipfile
from pathlib import Path
from typing import Tuple
try:
from rich.console import Console
from rich.progress import Progress, BarColumn, TimeRemainingColumn
from rich.prompt import Prompt, Confirm
from rich.table import Table
from PIL import Image
from moviepy import VideoFileClip, ImageSequenceClip
except ImportError as e:
print(
f"Error: {e}\nPlease install requirements with: pip install -r requirements.txt"
)
sys.exit(1)
console = Console()
error_console = Console(stderr=True, style="bold red")
def clear_screen():
"""
Clear the console screen.
"""
console.print("\033c", end="")
def show_help():
"""
Display a help message with available commands.
"""
table = Table(title="Available Commands", show_header=True)
table.add_column("Command", style="cyan")
table.add_column("Description", style="magenta")
commands = [
("help", "Show this help message"),
("getinfo", "Get video file information"),
("vid2jpg", "Convert video to JPG sequence"),
("pic2jpg", "Convert images in folder to JPG format (supports sections)"),
("zip2vid", "Convert bootanimation ZIP to video"),
("resize", "Resize video while preserving aspect ratio"),
("sort", "Organize JPG sequence into sections"),
("unsort", "Revert sorted sections back to main folder"),
("compress", "Compress folder using ZIP Store mode"),
("uncompress", "Extract ZIP archive"),
("exit", "Exit the application"),
]
for cmd, desc in commands:
table.add_row(cmd, desc)
console.print(table)
def get_video_info(file_path: Path) -> dict:
"""
Retrieve information about a video file, including duration, FPS, width, and height.
:param file_path: Path object pointing to the video file.
:return: Dictionary containing video metadata.
"""
try:
with VideoFileClip(str(file_path)) as clip:
return {
"path": clip.filename,
"duration": clip.duration,
"fps": clip.fps,
"width": clip.w,
"height": clip.h,
}
except Exception as e:
raise RuntimeError(f"Failed to get video info: {e}")
def handle_getinfo():
"""
Prompt for a video file path and print its information.
"""
file_path = Prompt.ask("Enter video file path", console=console)
if not Path(file_path).exists():
error_console.print("File not found!")
return
try:
info = get_video_info(Path(file_path))
table = Table(title="Video Information", show_header=True)
table.add_column("Property", style="cyan")
table.add_column("Value", style="green")
for key, value in info.items():
table.add_row(key.upper(), str(value))
console.print(table)
except Exception as e:
error_console.print(f"Error: {e}")
def handle_vid2jpg():
"""
Prompt for a video file path and convert it to a sequence of JPG images.
"""
file_path = Prompt.ask("Enter video file path", console=console)
if not Path(file_path).exists():
error_console.print("File not found!")
return
output_dir = Path(Path(file_path).stem)
output_dir.mkdir(exist_ok=True)
try:
with VideoFileClip(str(file_path)) as clip:
fps = clip.fps
duration = clip.duration
total_frames = int(fps * duration)
digits = len(str(total_frames))
with Progress(
"[progress.description]{task.description}",
BarColumn(),
"[progress.percentage]{task.percentage:>3.0f}%",
TimeRemainingColumn(),
console=console,
) as progress:
task = progress.add_task(
"[cyan]Converting frames...", total=total_frames
)
for i, frame in enumerate(clip.iter_frames()):
img = Image.fromarray(frame)
img.save(
output_dir / f"{i:0{digits}d}.jpg",
quality=100,
optimize=False,
)
progress.update(task, advance=1)
with open(output_dir / "desc.txt", "w") as f:
f.write(f"{clip.w} {clip.h} {int(fps)}")
console.print(f"[green]Success![/] JPG sequence created in {output_dir}/")
except Exception as e:
error_console.print(f"Error: {e}")
shutil.rmtree(output_dir, ignore_errors=True)
def handle_resize():
"""
Prompt for a video file path, dimension type (width/height), and resize the video accordingly.
"""
file_path = Prompt.ask("Enter video file path", console=console)
if not Path(file_path).exists():
error_console.print("File not found!")
return
dimension = Prompt.ask(
"Resize by (width/height)", choices=["width", "height"], console=console
)
target = int(Prompt.ask(f"Enter target {dimension}", console=console))
fps = Prompt.ask("Enter FPS (Leave empty for original)", default=None, console=console)
fps = int(fps) if fps else None
try:
with VideoFileClip(str(file_path)) as clip:
if dimension == "width":
new_height = int(target * clip.h / clip.w)
new_size = (target, new_height)
else:
new_width = int(target * clip.w / clip.h)
new_size = (new_width, target)
resized = clip.resized(new_size)
output_path = (
f"{Path(file_path).stem}_{new_size[0]}x{new_size[1]}"
f"{Path(file_path).suffix}"
)
resized.write_videofile(output_path, fps=fps, logger=None)
console.print(f"[green]Success![/] Resized video saved as {output_path}")
except Exception as e:
error_console.print(f"Error: {e}")
def detect_prefix(folder: Path) -> Tuple[str, int]:
"""
Detect the file prefix and digit count for a sequence of JPG files in a given folder.
:param folder: Path to the folder containing JPG files.
:return: A tuple of (prefix, digit_count).
"""
files = list(folder.glob("*.jpg"))
if not files:
raise ValueError("No JPG files found in folder")
sample = files[0].stem
prefix = re.sub(r"\d+$", "", sample)
digits = len(sample) - len(prefix)
return prefix, digits
def handle_sort():
"""
Prompt for a folder containing a JPG sequence. Sort images into sections, updating desc.txt with the new sections.
"""
folder = Prompt.ask("Enter JPG sequence folder", console=console)
folder = Path(folder)
try:
with open(folder / "desc.txt") as f:
_, _, fps = map(int, f.readline().split())
prefix, digits = detect_prefix(folder)
sections = int(Prompt.ask("Number of sections", console=console))
sections_info = []
current_frame = 0
for i in range(1, sections + 1):
console.rule(f"Section {i}")
end_time = Prompt.ask(
"End time (seconds/(r for remaining part))", console=console
)
end_frame = (
int(sorted(folder.glob("*.jpg"))[-1].stem[-digits:])
if end_time == "r"
else int(float(end_time) * fps)
)
section_type = Prompt.ask("Type (c/p)", choices=["c", "p"], console=console)
looped = Confirm.ask("Loop section?", console=console)
count = 0 if looped else int(Prompt.ask("Play count", console=console))
section_folder = folder / f"S{i}"
section_folder.mkdir(exist_ok=True)
for frame in range(current_frame, end_frame + 1):
src = folder / f"{prefix}{frame:0{digits}d}.jpg"
dest = section_folder / src.name
src.rename(dest)
sections_info.append(f"{section_type} {count} 0 S{i}")
current_frame = end_frame + 1
with open(folder / "desc.txt", "a") as f:
f.write("\n" + "\n".join(sections_info) + "\n")
console.print("[green]Sorting completed successfully![/]")
except Exception as e:
error_console.print(f"Error: {e}")
def get_section_names(folder: Path) -> list:
"""Extract section names from desc.txt"""
try:
with open(folder / "desc.txt") as f:
# Skip first line (resolution info)
lines = f.read().splitlines()[1:]
return [line.split()[3] for line in lines if line.strip()]
except Exception as e:
raise RuntimeError(f"Error reading desc.txt: {e}")
def handle_unsort():
"""
Prompt for a folder containing sorted JPG sections. Move files back to the main folder and remove section dirs.
"""
folder = Prompt.ask("Enter sorted folder", console=console)
folder = Path(folder)
try:
sections = get_section_names(folder)
for section in sections:
section_dir = folder / section
if not section_dir.exists():
error_console.print(
f"Warning: Section folder {section} not found, skipping"
)
continue
for file in section_dir.iterdir():
if file.suffix == ".jpg":
dest = folder / file.name
if dest.exists():
error_console.print(
f"Conflict: {file.name} exists in main folder! Aborting."
)
return
file.rename(dest)
section_dir.rmdir()
console.print("[green]Unsort completed successfully![/]")
except Exception as e:
error_console.print(f"Error: {e}")
def handle_compress():
"""
Prompt for a folder and compress it into a ZIP file using the ZIP_STORED compression mode.
"""
folder = Prompt.ask("Enter folder to compress", console=console)
folder = Path(folder)
zip_name = f"{folder.name}.zip"
try:
with zipfile.ZipFile(zip_name, "w", compression=zipfile.ZIP_STORED) as zipf:
for root, _, files in os.walk(folder):
for file in files:
zipf.write(
os.path.join(root, file),
arcname=os.path.relpath(os.path.join(root, file), folder),
)
console.print(f"[green]Compression completed![/]\nPath - {zip_name}")
except Exception as e:
error_console.print(f"Error: {e}")
def handle_uncompress():
"""
Prompt for a ZIP file path and extract its contents.
"""
zip_file = Prompt.ask("Enter ZIP file path", console=console)
zip_folder = Path(Path(zip_file).stem)
zip_folder.mkdir(exist_ok=True)
try:
with zipfile.ZipFile(zip_file, "r") as zipf:
zipf.extractall(zip_folder)
console.print("[green]Extraction completed successfully![/]")
except Exception as e:
error_console.print(f"Error: {e}")
def handle_pic2jpg():
"""
Convert all non-JPG images in a bootanimation folder (including subdirectories) to JPG format, preserving directory structure and filenames.
"""
folder = Prompt.ask("Enter bootanimation folder path", console=console)
folder = Path(folder)
if not folder.exists() or not folder.is_dir():
error_console.print("Invalid folder path!")
return
supported_extensions = (".png", ".jpeg", ".bmp", ".gif", ".webp")
image_paths = []
for img_path in folder.rglob("*"):
if img_path.is_file() and img_path.suffix.lower() in supported_extensions:
image_paths.append(img_path)
total_files = len(image_paths)
if total_files == 0:
console.print("[yellow]No convertible image files found.[/]")
return
converted = 0
errors = 0
with Progress(
"[progress.description]{task.description}",
BarColumn(),
"[progress.percentage]{task.percentage:>3.0f}%",
TimeRemainingColumn(),
console=console,
) as progress:
task = progress.add_task("[cyan]Converting images...", total=total_files)
for img_path in image_paths:
try:
new_path = img_path.with_suffix(".jpg")
if new_path.exists():
error_console.print(
f"Warning: {new_path} already exists, skipping."
)
errors += 1
progress.update(task, advance=1)
continue
with Image.open(img_path) as img:
rgb_img = img.convert("RGB")
rgb_img.save(new_path, quality=100, optimize=False)
img_path.unlink() # Delete original file
converted += 1
except Exception as e:
error_console.print(f"Error converting {img_path}: {e}")
errors += 1
finally:
progress.update(task, advance=1)
console.print(f"[green]Conversion complete![/] Converted {converted} images.")
if errors > 0:
error_console.print(f"Encountered {errors} errors during conversion.")
def handle_zip2vid():
"""
Convert a bootanimation ZIP to a video by extracting JPG frames and creating a final MP4 file.
"""
zip_file = Prompt.ask("Enter bootanimation ZIP path", console=console)
if not Path(zip_file).exists():
error_console.print("ZIP file not found!")
return
output_folder = Path(zip_file).stem
try:
with zipfile.ZipFile(zip_file, "r") as zipf:
zipf.extractall(output_folder)
console.print(f"[green]Extracted to {output_folder}/[/]")
except Exception as e:
error_console.print(f"Error extracting ZIP: {e}")
return
folder = Path(output_folder)
try:
# Get sections from desc.txt
sections = get_section_names(folder)
if sections:
console.print("[yellow]Found sorted sections, unsorting...[/]")
for section in sections:
section_dir = folder / section
if not section_dir.exists():
error_console.print(
f"Warning: Section folder {section} missing, skipping"
)
continue
for img_file in section_dir.glob("*.jpg"):
dest = folder / img_file.name
if dest.exists():
error_console.print(
f"Conflict: {img_file.name} already exists! Aborting."
)
return
img_file.rename(dest)
section_dir.rmdir()
except Exception as e:
error_console.print(f"Error during unsorting: {e}")
return
try:
with open(folder / "desc.txt", "r") as f:
_, _, fps = map(int, f.readline().strip().split())
except Exception as e:
error_console.print(f"Error reading desc.txt: {e}")
return
try:
jpg_files = list(folder.glob("*.jpg"))
if not jpg_files:
error_console.print("No JPG files found in folder!")
return
jpg_files.sort(key=lambda x: int(re.search(r"\d+", x.stem).group()))
except Exception as e:
error_console.print(f"Error sorting JPG files: {e}")
return
output_path = f"{folder.name}_converted.mp4"
try:
with console.status("[bold green]Preparing frames...[/]", spinner="dots"):
clip = ImageSequenceClip([str(img) for img in jpg_files], fps=fps)
with Progress(
"[progress.description]{task.description}",
BarColumn(),
"[progress.percentage]{task.percentage:>3.0f}%",
TimeRemainingColumn(),
console=console,
) as progress:
rendering_task = progress.add_task(
"[cyan]Rendering video...", total=len(jpg_files)
)
def make_frame(gf, t):
progress.update(rendering_task, advance=1)
return gf(t)
clip = clip.transform(make_frame, apply_to=["video"])
clip.write_videofile(
output_path,
threads=8,
codec="libx264",
fps=fps,
logger=None,
)
shutil.rmtree(folder)
console.print(
f"[green]Video created successfully![/]\nPath: [cyan]{output_path}[/]"
)
except Exception as e:
error_console.print(f"Error creating video: {e}")
return
def main():
"""
Main entry point for the application. Clears the screen, prints a welcome message, and handles user commands in a loop.
"""
clear_screen()
console.print("[bold magenta]Boot Animation Creator[/]\n", justify="center")
console.print("Type 'help' for available commands\n")
handlers = {
"help": show_help,
"getinfo": handle_getinfo,
"pic2jpg": handle_pic2jpg,
"vid2jpg": handle_vid2jpg,
"resize": handle_resize,
"sort": handle_sort,
"unsort": handle_unsort,
"compress": handle_compress,
"uncompress": handle_uncompress,
"zip2vid": handle_zip2vid,
}
while True:
try:
cmd = Prompt.ask(">>", console=console).strip().lower()
if cmd == "exit":
console.print("[bold]Goodbye![/]")
break
elif cmd in handlers:
handlers[cmd]()
else:
error_console.print(
"Invalid command! Type 'help' for available commands"
)
except KeyboardInterrupt:
console.print("\n[bold]Goodbye![/]")
break
except Exception as e:
error_console.print(f"Unexpected error: {e}")
if __name__ == "__main__":
main()