diff --git a/convert.py b/convert.py index 5bfabea..84244d5 100644 --- a/convert.py +++ b/convert.py @@ -136,7 +136,7 @@ def convert_to_simai_folder(result,output_folder): # 示例调用 if __name__ == "__main__": - music_ids = [111516] + music_ids = [834,799] output_folder = "result" max_workers = 6 # 根据 CPU 和硬盘负载合理设置线程数 diff --git a/pv_convert.py b/pv_convert.py index 6fbf306..09e9504 100644 --- a/pv_convert.py +++ b/pv_convert.py @@ -1,6 +1,24 @@ -import os import subprocess import sys +from fractions import Fraction + +from loguru import logger + + +def ratio_to_str(width, height, max_denominator=20): + """将宽高比转换为 a:b 的形式""" + # 确保分子 > 分母 + if width >= height: + ratio = Fraction(width, height).limit_denominator(max_denominator) + else: + ratio = Fraction(height, width).limit_denominator(max_denominator) + + a, b = ratio.numerator, ratio.denominator + # 由于上面取了 max(width, height),要对应宽:高 + if width >= height: + return f"{a}:{b}" + else: + return f"{b}:{a}" def get_video_resolution(video_path): """获取视频的宽高信息""" @@ -13,7 +31,15 @@ def get_video_resolution(video_path): return width, height def calculate_padding(width, height): - """计算填充黑边,使其变成 1:1(正方形)""" + """计算填充黑边,使其变成 1:1(正方形)。 + 如果接近4:3或1:1比例(90%以内),则直接返回0。 + """ + aspect_ratio = width / height if width >= height else height / width + + # 如果接近 4:3 或 1:1,就不填充 + if (0.9 <= aspect_ratio <= 1.1) or (1.3 <= aspect_ratio <= 1.5): + return max(width, height), 0, 0 + max_side = max(width, height) # 以最大边长作为正方形边长 pad_x = (max_side - width) // 2 pad_y = (max_side - height) // 2 @@ -25,7 +51,7 @@ def process_video(input_file, output_file): target_size, pad_x, pad_y = calculate_padding(width, height) if pad_x == 0 and pad_y == 0: - print("视频已经是 1:1,无需填充。") + logger.info(f"视频比例是 {ratio_to_str(width,height)},无需填充。") ffmpeg_cmd = [ "ffmpeg", "-i", input_file, "-c:v", "h264_videotoolbox", @@ -34,7 +60,7 @@ def process_video(input_file, output_file): output_file ] else: - print(f"填充黑边,使视频变为 {target_size}x{target_size}") + logger.info(f"视频比例是 {ratio_to_str(width,height)},填充黑边,使视频变为 {target_size}x{target_size}") ffmpeg_cmd = [ "ffmpeg", "-i", input_file, "-vf", f"pad={target_size}:{target_size}:{pad_x}:{pad_y}:black", @@ -48,7 +74,7 @@ def process_video(input_file, output_file): if __name__ == "__main__": if len(sys.argv) < 3: - print("用法: python pv_convert.py 输入文件 输出文件") + logger.info("用法: python pv_convert.py 输入文件 输出文件") sys.exit(1) input_file = sys.argv[1]