[+] formatting

This commit is contained in:
2025-09-08 22:54:21 +09:00
parent 6aeb691bf2
commit 60e745e69d
4 changed files with 95 additions and 17 deletions
+38 -15
View File
@@ -1,9 +1,10 @@
import glob
import traceback
from pathlib import Path
from subprocess import check_call
from subprocess import check_call, DEVNULL
from hypy_utils import printc
from rich.progress import track
defaults = {
'av1': {
@@ -34,6 +35,9 @@ defaults = {
'-c:a': 'flac',
'-compression_level': '7',
},
'wav': {
'-c:a': 'pcm_s16le',
}
}
suffixes = {
'av1': '.av1-{-crf}.mp4',
@@ -41,10 +45,13 @@ suffixes = {
'mp3': '.v{-q:a}.mp3',
'opus': '.v{-b:a}.opus',
'flac': '.flac',
'wav': '.wav',
}
def main(fmt: str, files: list[str], keep: bool, passthrough: list[str]):
def main(fmt: str, files: list[str], keep: bool, passthrough: list[str], quiet: bool = False, silent: bool = False):
printq = printc if not silent else lambda *a, **k: None
quiet = quiet or silent
# Process each file provided on the command line
files = [
Path(p)
@@ -52,16 +59,19 @@ def main(fmt: str, files: list[str], keep: bool, passthrough: list[str]):
for p in glob.glob(str(Path(pattern).expanduser()))
if Path(p).is_file()
]
total_orig_size, total_new_size = 0, 0
printc(f"&e> Using format: {fmt}")
printc(f"&e> Found {len(files)} files to process.")
printc(f"&e> Keep original files: {'Yes' if keep else 'No'}")
printc(f"&e> Passthrough parameters: {passthrough if passthrough else 'None'}")
print()
for inf in files:
printc("&e-----------------------------------------")
for inf in track(files):
printq("&e-----------------------------------------")
try:
params: dict[str, str | None] = defaults[fmt].copy()
old_size = inf.stat().st_size
if quiet:
params['-y'] = None # Overwrite output files without asking
# Check for any passthrough arguments and add them to params (overrides defaults)
i = 0
@@ -70,11 +80,11 @@ def main(fmt: str, files: list[str], keep: bool, passthrough: list[str]):
# Check if next item exists and is not a flag (i.e., it's a value)
if i + 1 < len(passthrough) and not passthrough[i+1].startswith('-'):
v = passthrough[i+1]
printc(f"&a> Overriding parameter: {k} {v} (was {params.get(k, 'not set')})")
printq(f"&a> Overriding parameter: {k} {v} (was {params.get(k, 'not set')})")
params[k] = v
i += 2
else: # It's a standalone flag
printc(f"&a> Overriding parameter: {k} (was {params.get(k, 'not set')})")
printq(f"&a> Overriding parameter: {k} (was {params.get(k, 'not set')})")
params[k] = None # Use None to signify a flag without a value
i += 1
@@ -84,35 +94,48 @@ def main(fmt: str, files: list[str], keep: bool, passthrough: list[str]):
end = ''.join(c for c in end if c.isalnum() or c in ' ._-+').rstrip()
if inf.name.endswith(end):
printc(f"&c> Error: File already has target suffix '{end}', skipping: {inf.name}")
printq(f"&c> Error: File already has target suffix '{end}', skipping: {inf.name}")
continue
ouf = inf.with_name(f'{inf.stem}{end}')
printc(f"&e+ Compressing '{inf.name}' > '{ouf.name}'")
printq(f"&e+ Compressing '{inf.name}' > '{ouf.name}'")
# Construct and run the ffmpeg command
cmd = ['ffmpeg', '-hide_banner', '-i',
str(inf),
*sum(([k] if v is None else [k, str(v)] for k, v in params.items()), []),
str(ouf)]
printc(f"&e> Running command: {' '.join(cmd)}")
printq(f"&e> Running command: {' '.join(cmd)}")
check_call(cmd)
printc(f"&a> Compression successful :)")
check_call(cmd) if not quiet else check_call(cmd, stdout=DEVNULL, stderr=DEVNULL)
printq(f"&a> Compression successful :)")
new_size = ouf.stat().st_size
ratio = new_size / old_size
printc(f"&a> Size: {old_size / 1_000_000:.2f} MB -> {new_size / 1_000_000:.2f} MB ({ratio:.2%})")
printq(f"&a> Size: {old_size / 1_000_000:.2f} MB -> {new_size / 1_000_000:.2f} MB ({ratio:.2%})")
total_orig_size += old_size
total_new_size += new_size
if not keep:
if new_size >= old_size:
printc(f"&c! Warning: Compressed file is not smaller than original. Keeping original file :(")
else:
printc(f"&e- Removing original file: '{inf.name}'")
printq(f"&e- Removing original file: '{inf.name}'")
inf.unlink()
printc(f"&a> Original file removed.")
printq(f"&a> Original file removed.")
print()
printq('')
except Exception as e:
printc(f"&c! An error occurred while processing {inf.name}: {e}")
printc("&c! Leaving original file intact.\n")
traceback.print_exc()
# Print summary
if total_orig_size > 0:
total_ratio = total_new_size / total_orig_size
printc("&a=========================================")
printc(f"&a> Processed {len(files)} files.")
printc(f"&a> Total size: {total_orig_size / 1_000_000:.2f} MB -> {total_new_size / 1_000_000:.2f} MB ({total_ratio:.2%})")
printc("&a=========================================")
else:
printc("&c! Nothing to do")
+7 -1
View File
@@ -9,9 +9,11 @@ def cli(fmt: str | None = None):
agupa.add_argument('format', choices=defaults.keys(), help="Compression format to use.")
agupa.add_argument('files', nargs='+', help="One or more files to compress.")
agupa.add_argument('--keep', action='store_true', help="Keep original files after compression.")
agupa.add_argument('--quiet', action='store_true', help="Suppress ffmpeg output.")
agupa.add_argument('--silent', action='store_true', help="Suppress all output except errors.")
args, passthrough = agupa.parse_known_args()
main(fmt or args.format, args.files, args.keep, passthrough)
main(fmt or args.format, args.files, args.keep, passthrough, args.quiet, args.silent)
def av1():
@@ -34,5 +36,9 @@ def flac():
cli('flac')
def wav():
cli('wav')
if __name__ == '__main__':
cli()