3838SOURCE_DIR = Path (__file__ ).resolve ().parent
3939CONFIG_PATH = SOURCE_DIR / "media-compress.json"
4040DEFAULT_OUTPUT_DIR = "_compressed"
41+ LOG_SUFFIX = ".log"
42+ # 当前轮次打开着的日志文件;log() 在有它时同步落盘。None 表示不写日志。
43+ _log_file = None
44+ # stdout 被下游提前关闭(例如 `media-compress ... | head`)后置位,之后不再尝试写控制台。
45+ _console_dead = False
4146
4247# caesiumclt 1.5.0 读不了这些,实测每次都失败:
4348# .avif/.heic/.heif/.jxl -> 报错退出
4954VIDEO_EXTS = {".mp4" , ".m4v" , ".mov" , ".mkv" , ".webm" , ".avi" ,
5055 ".wmv" , ".flv" , ".mpg" , ".mpeg" , ".ts" , ".m2ts" , ".3gp" }
5156MODERN_VIDEO_CODECS = {"hevc" , "h265" , "av1" , "vp9" , "vp8" }
57+ # 图像最长边上限。0 = 不限制。只在源超出时才缩,永不放大。
58+ # 常见取值(按需自行改这一个数):
59+ # 1920 1080p 屏全屏
60+ # 2560 1440p
61+ # 3840 4K 原生
62+ # 5120 5K
63+ # 6144 6K
64+ # 7680 8K
65+ # 8192 常见扫描/相机输出的上限
66+ IMAGE_MAX_EDGE_CHOICES = (0 , 1920 , 2560 , 3840 , 5120 , 6144 , 7680 , 8192 )
67+ DEFAULT_IMAGE_MAX_EDGE = 5120
5268HDR_TRANSFERS = {"smpte2084" , "arib-std-b67" }
5369JUNK_NAMES = {"desktop.ini" , "thumbs.db" , "ehthumbs.db" , ".ds_store" , ".localized" }
5470# compress_video 返回这些原因表示"故意不动它",不是失败:算 SKIP 而不是 FAIL,
@@ -82,9 +98,54 @@ def log(message: str = "", file=None, **_ignored) -> None:
8298 各自带时间才知道那会儿在做什么。注意换行符在时间戳之前,续行才不会被污染。
8399 并发时也逐行加锁式打印,所以时间戳的顺序与实际写出顺序一致。
84100 总是 flush:后台运行或管道里被缓冲的话,时间戳就失去意义了。
101+
102+ 同时(若已分配日志文件)以同样格式落盘,所以日志就是屏幕内容的副本。
103+ 写失败一律吞掉:日志写不进去、或下游把管道关了(`| head`),都不该让整轮
104+ 任务半路崩掉——那会留下做了一半的输出和临时目录。
85105 """
106+ global _console_dead
86107 stamp = datetime .now ().strftime ("%Y-%m-%d %H:%M:%S" )
87- print (f"{ stamp } { message } " , file = file , flush = True )
108+ line = f"{ stamp } { message } "
109+ if not _console_dead :
110+ try :
111+ print (line , file = file , flush = True )
112+ except OSError :
113+ _console_dead = True # 管道被下游关闭,之后只写文件
114+ if _log_file is not None :
115+ try :
116+ _log_file .write (line + "\n " )
117+ _log_file .flush ()
118+ except (OSError , ValueError ):
119+ pass
120+
121+
122+ class Logger :
123+ """把整轮运行的输出写成一份日志文件。
124+
125+ 文件名带时间戳,放在输出根(-o 给的目录,或各源目录的 _compressed/),
126+ 方便事后回看"哪个文件当时执行了什么命令"。
127+ """
128+
129+ def __init__ (self , path : Path , fresh : bool ) -> None :
130+ self .path = path
131+ self .fresh = fresh
132+
133+ def open (self ) -> None :
134+ global _log_file
135+ self .path .parent .mkdir (parents = True , exist_ok = True )
136+ _log_file = self .path .open ("w" if self .fresh else "a" , encoding = "utf-8" )
137+ # 第一行是本次调用的原样命令行,第二行才是日志自己的位置。
138+ log ("command: " + invocation (sys .argv ))
139+ log (f"log file: { self .path } " )
140+
141+ def close (self ) -> None :
142+ global _log_file
143+ if _log_file is not None :
144+ try :
145+ _log_file .close ()
146+ except OSError :
147+ pass
148+ _log_file = None
88149
89150
90151def human (size : float ) -> str :
@@ -95,6 +156,16 @@ def human(size: float) -> str:
95156 return f"{ size :.1f} TB"
96157
97158
159+ def invocation (argv : list [str ]) -> str :
160+ """把本次调用的命令行还原成可复制粘贴的一行。
161+
162+ 直接用 sys.argv 而不是拿 argparse 的结果重建:重建会丢掉用户实际怎么写
163+ (--log=no 还是 --log no、路径带不带引号),而日志的第一价值就是"当时到底
164+ 敲了什么"。只有含空格或引号的参数才补引号。
165+ """
166+ return " " .join (f'"{ a } "' if (" " in a or '"' in a ) else a for a in argv )
167+
168+
98169# ------------------------------ 工具查找 ------------------------------
99170
100171def find_tool (names : list [str ], env_var : str , candidates : list [Path ]) -> str :
@@ -184,6 +255,25 @@ def problem(result: subprocess.CompletedProcess, limit: int = 300) -> str:
184255 return f"{ lines [0 ]} | … | { lines [- 1 ]} " [:limit ]
185256
186257
258+ def longest_edge (ffprobe : str , path : Path ) -> int :
259+ """源图的最长边(像素);读不出来返回 0。
260+
261+ 只用来决定"要不要下传 --long-edge":不加判断直接传也对(caesium 不会放大),
262+ 但显式判断能让 dry-run 打印出真正会执行的参数。
263+ """
264+ command = [ffprobe , "-v" , "error" , "-select_streams" , "v" ,
265+ "-show_entries" , "stream=width,height" , "-of" , "json" , str (path )]
266+ try :
267+ result = run (command )
268+ if result .returncode != 0 :
269+ return 0
270+ streams = (json .loads (result .stdout or "{}" ).get ("streams" ) or [{}])
271+ first = streams [0 ]
272+ return max (int (first .get ("width" ) or 0 ), int (first .get ("height" ) or 0 ))
273+ except (OSError , subprocess .TimeoutExpired , json .JSONDecodeError , IndexError , ValueError ):
274+ return 0
275+
276+
187277def probe (ffprobe : str , path : Path ) -> dict :
188278 """用 ffprobe 读视频流与容器信息;图像路径不走这里。"""
189279 command = [ffprobe , "-v" , "error" ,
@@ -240,7 +330,7 @@ def make_temp_dir(out_root: Path) -> Path:
240330
241331
242332def compress_image (caesium : str , src : Path , target : Path , quality : int , image_format : str ,
243- strip_exif : bool , dry_run : bool , tmp : Path ) -> tuple [int , str ]:
333+ strip_exif : bool , max_edge : int , tmp : Path ) -> tuple [int , str ]:
244334 """压缩单张图像,成功返回 (压缩后字节数, "");失败或省得不够返回 (0, 原因)。
245335
246336 caesiumclt 的 `-e` 是"保留 EXIF",所以 --image-strip-exif 是省掉该开关而
@@ -250,6 +340,9 @@ def compress_image(caesium: str, src: Path, target: Path, quality: int, image_fo
250340 临时目录由调用方按"输出根"建一个并登记清理;它不是按文件各建一个,所以
251341 输出镜像树里不会凭空多出目录。并发压缩时各文件用各自不同的文件名写进这个
252342 目录,再由 os.replace 原子改名到目标,彼此不冲突。
343+
344+ max_edge > 0 时按最长边缩放,配 --no-upscale:caesium 只在源超限时才缩,
345+ 不会把小图放大。缩放和编码在同一次调用里完成,不会二次有损。
253346 """
254347 command = [caesium , "-q" , str (quality ), "--keep-orientation" , "--keep-dates" ,
255348 "-O" , "all" , "--json" , "-o" , str (tmp )]
@@ -261,7 +354,10 @@ def compress_image(caesium: str, src: Path, target: Path, quality: int, image_fo
261354 # 传了反而会把本来能压的文件变成"失败后复制"。
262355 if image_format != "original" and target .suffix .lower () != src .suffix .lower ():
263356 command += ["--format" , image_format ]
357+ if max_edge > 0 :
358+ command += ["--long-edge" , str (max_edge ), "--no-upscale" ]
264359 command .append (str (src ))
360+ log ("exec: " + " " .join (command )) # 完整命令,方便事后单独复现
265361 result = run (command )
266362 try :
267363 payload = json .loads (result .stdout or "{}" )
@@ -304,7 +400,9 @@ def compress_video(handbrake: str, ffprobe: str, src: Path, target: Path,
304400 return 0 , "dry_run"
305401
306402 target .parent .mkdir (parents = True , exist_ok = True )
307- try : result = subprocess .run (command , stdout = subprocess .PIPE , stderr = subprocess .STDOUT ,
403+ log ("exec: " + " " .join (command )) # 完整命令,方便事后单独复现
404+ try :
405+ result = subprocess .run (command , stdout = subprocess .PIPE , stderr = subprocess .STDOUT ,
308406 encoding = "utf-8" , errors = "replace" )
309407 except OSError as exc :
310408 return 0 , str (exc )
@@ -445,20 +543,32 @@ def exit(self, status: int = 0, message: str | None = None) -> None:
445543 help = "image output format (default: original, keep source format)" )
446544 parser .add_argument ("--image-strip-exif" , action = "store_true" ,
447545 help = "strip image EXIF (including GPS and other private data)" )
546+ parser .add_argument ("--image-max-edge" , type = int , default = DEFAULT_IMAGE_MAX_EDGE ,
547+ help = "downscale images so the longest edge fits this many pixels "
548+ f"(default: { DEFAULT_IMAGE_MAX_EDGE } ; 0 = no limit). "
549+ "Never upscales. Common values: "
550+ + ", " .join (str (v ) for v in IMAGE_MAX_EDGE_CHOICES [1 :]))
448551 parser .add_argument ("--image-jobs" , type = int , default = 3 ,
449552 help = "parallel image compressions (default: 3; 1 = serial)" )
450553 parser .add_argument ("--copy-unprocessed" , choices = ("yes" , "no" ), default = "yes" ,
451554 help = "copy files left uncompressed into the output tree "
452555 "(default: yes). 'no' makes the output tree INCOMPLETE, "
453556 "so it can no longer replace the source folder." )
454557 parser .add_argument ("--dry-run" , action = "store_true" , help = "print commands only, write nothing" )
558+ parser .add_argument ("--log" , nargs = "?" , const = "auto" , default = "auto" , metavar = "no|FILE" ,
559+ help = "write a log next to the output (default: auto, i.e. "
560+ "<output>/media-compress-<timestamp>.log). 'no' disables it; "
561+ "a path writes/appends there instead." )
455562 args = parser .parse_args (argv [1 :])
456563 if not 0 <= args .image_quality <= 100 :
457564 log ("[ERROR] --image-quality must be between 0 and 100" , file = sys .stderr )
458565 return 2
459566 if args .image_jobs < 1 :
460567 log ("[ERROR] --image-jobs must be at least 1" , file = sys .stderr )
461568 return 2
569+ if args .image_max_edge != 0 and args .image_max_edge < 64 :
570+ log ("[ERROR] --image-max-edge must be 0 (no limit) or at least 64" , file = sys .stderr )
571+ return 2
462572
463573 preset_name , container_ext = load_preset (CONFIG_PATH )
464574 paths = [Path (p ).expanduser () for p in args .paths ]
@@ -468,6 +578,40 @@ def exit(self, status: int = 0, message: str | None = None) -> None:
468578 log (f"[ERROR] path not found: { path } " , file = sys .stderr )
469579 return 1
470580
581+ # 日志要在规划之前打开,"已存在则跳过"那些行才进得了日志。
582+ # 显式路径 -> 追加;auto -> 在输出根下新建带时间戳的文件。
583+ logger : Logger | None = None
584+ if args .log != "no" :
585+ # 时间戳带微秒:同一秒内连跑两次(脚本很快时很常见)文件名就不会撞,
586+ # 否则第二次会把第一次的日志截断覆盖。
587+ stamp = datetime .now ().strftime ("%Y%m%d-%H%M%S-%f" )
588+ if args .log == "auto" :
589+ # 与 collect 同一套规则:有 -o 就是它,否则各自源目录的 _compressed。
590+ base = Path (args .output ).expanduser ().resolve () if args .output else \
591+ (paths [0 ] if paths [0 ].is_dir () else paths [0 ].parent )
592+ log_path = (base if args .output else base / DEFAULT_OUTPUT_DIR ) / \
593+ f"media-compress-{ stamp } { LOG_SUFFIX } "
594+ fresh = True
595+ else :
596+ log_path = Path (args .log ).expanduser ()
597+ fresh = False
598+ try :
599+ logger = Logger (log_path , fresh )
600+ logger .open ()
601+ except OSError as exc :
602+ log (f"[ERROR] cannot open log file: { exc } " , file = sys .stderr )
603+ return 1
604+
605+ try :
606+ return compress_all (args , paths , preset_name , container_ext )
607+ finally :
608+ if logger is not None :
609+ logger .close ()
610+
611+
612+ def compress_all (args , paths : list [Path ], preset_name : str ,
613+ container_ext : str ) -> int :
614+ """打开日志之后的主体;单独成函数,好让日志在 finally 里可靠关闭。"""
471615 images , videos , passthrough = collect (paths , args .output )
472616 if args .only == "image" :
473617 videos = []
@@ -476,7 +620,10 @@ def exit(self, status: int = 0, message: str | None = None) -> None:
476620 passthrough = []
477621
478622 # 先算出真正需要哪些工具,再去解析它们;不处理的那一类连查找都不做。
479- needed = (["caesium" ] if images else []) + (["ffprobe" , "handbrake" ] if videos else [])
623+ # 图像也要 ffprobe:--image-max-edge 要先知道源的最长边才能决定是否下传
624+ # --long-edge(dry-run 打印的命令要如实反映这一点)。
625+ needed = (["caesium" , "ffprobe" ] if images else []) \
626+ + (["ffprobe" , "handbrake" ] if videos else [])
480627 found = tools (needed )
481628 absent = [name for name in needed if not found [name ]]
482629 if absent :
@@ -617,6 +764,13 @@ def process(index: int, kind: str, src: Path, target: Path, out_root: Path,
617764 return failed_copy or (tag , src , fallback , size , 0 , "COPY" ,
618765 "unsupported format, copied as is" )
619766 if kind == "IMAGE" :
767+ # 只有源超过上限才缩。caesium 本身不会放大,但先判断能让 dry-run
768+ # 打印出真正会执行的参数。
769+ shrink = 0
770+ if args .image_max_edge > 0 :
771+ edge = longest_edge (found ["ffprobe" ], src )
772+ if edge > args .image_max_edge :
773+ shrink = args .image_max_edge
620774 if args .dry_run :
621775 command = [found ["caesium" ], "-q" , str (args .image_quality ),
622776 "--keep-orientation" , "--keep-dates" , "-O" , "all" , "--json" ,
@@ -626,6 +780,8 @@ def process(index: int, kind: str, src: Path, target: Path, out_root: Path,
626780 if args .image_format != "original" \
627781 and src .suffix .lower () != target .suffix .lower ():
628782 command += ["--format" , args .image_format ]
783+ if shrink :
784+ command += ["--long-edge" , str (shrink ), "--no-upscale" ]
629785 log (" " + " " .join (command + [str (src )]), flush = True )
630786 return tag , src , target , size , 0 , "DRY" , ""
631787 try :
@@ -640,7 +796,7 @@ def process(index: int, kind: str, src: Path, target: Path, out_root: Path,
640796 tmp_dirs .add (tmp ) # 登记后即使中断也会被清理
641797 new_size , reason = compress_image (found ["caesium" ], src , target ,
642798 args .image_quality , args .image_format ,
643- args .image_strip_exif , False , tmp )
799+ args .image_strip_exif , shrink , tmp )
644800 else :
645801 new_size , reason = compress_video (found ["handbrake" ], found ["ffprobe" ], src ,
646802 target , preset_name , args .dry_run )
0 commit comments