feat: log file generation optional

Log files are now only
generated when --save-log flag is set.
This commit is contained in:
Rémi Heredero 2025-04-27 16:34:20 +02:00
parent 3588d9ad14
commit 63cefacbfa
Signed by: Klagarge
GPG Key ID: 735B36B074A65F0F

View File

@ -14,7 +14,7 @@ def get_duration(file_path):
], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) ], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
return float(result.stdout.strip()) return float(result.stdout.strip())
def encode(input_file, codec, remove_source=False): def encode(input_file, codec, remove_source=False, save_log=False):
if codec == "x265": if codec == "x265":
ffmpeg_codec = "libx265" ffmpeg_codec = "libx265"
crf = 26 crf = 26
@ -46,7 +46,12 @@ def encode(input_file, codec, remove_source=False):
outdir = os.path.join(os.path.dirname(input_file), folder) outdir = os.path.join(os.path.dirname(input_file), folder)
os.makedirs(outdir, exist_ok=True) os.makedirs(outdir, exist_ok=True)
output_file = os.path.join(outdir, f"{name}.mkv") output_file = os.path.join(outdir, f"{name}.mkv")
log_file = os.path.join(outdir, f"{name}.log")
if save_log:
log_file = os.path.join(outdir, f"{name}.log")
log = open(log_file, "w")
else:
log = subprocess.DEVNULL # Pas de log
cmd = [ cmd = [
"ffmpeg", "ffmpeg",
@ -60,30 +65,35 @@ def encode(input_file, codec, remove_source=False):
] ]
print(f"\n🎬 Encoding {filename}{folder}/{name}.mkv with codec [{ffmpeg_codec}]") print(f"\n🎬 Encoding {filename}{folder}/{name}.mkv with codec [{ffmpeg_codec}]")
with open(log_file, "w") as log: process = subprocess.Popen(cmd, stderr=subprocess.PIPE, stdout=subprocess.PIPE, text=True)
process = subprocess.Popen(cmd, stderr=subprocess.PIPE, stdout=subprocess.PIPE, text=True)
time_re = re.compile(r"time=(\d+):(\d+):([\d.]+)") time_re = re.compile(r"time=(\d+):(\d+):([\d.]+)")
last_percent = -1 last_percent = -1
while True: while True:
line = process.stderr.readline() line = process.stderr.readline()
if not line: if not line:
break break
if save_log:
log.write(line) log.write(line)
match = time_re.search(line) match = time_re.search(line)
if match: if match:
h, m, s = map(float, match.groups()) h, m, s = map(float, match.groups())
current = h * 3600 + m * 60 + s current = h * 3600 + m * 60 + s
percent = int((current / duration) * 100) percent = int((current / duration) * 100)
if percent != last_percent: if percent != last_percent:
print(f"\r⏳ Progress: {percent}%", end='', flush=True) print(f"\r⏳ Progress: {percent}%", end='', flush=True)
last_percent = percent last_percent = percent
process.wait() process.wait()
if save_log:
log.close()
if process.returncode != 0: if process.returncode != 0:
print(f"\n❌ [Error] FFmpeg failed for {filename}. Check the log: {log_file}") print(f"\n❌ [Error] FFmpeg failed for {filename}.")
if save_log:
print(f" ➔ Check the log file: {log_file}")
if os.path.exists(output_file): if os.path.exists(output_file):
os.remove(output_file) os.remove(output_file)
else: else:
@ -91,11 +101,11 @@ def encode(input_file, codec, remove_source=False):
if remove_source: if remove_source:
try: try:
os.remove(input_file) os.remove(input_file)
print(f"🗑️ Source file {input_file} removed.") print(f"🗑️ Source file {input_file} removed.")
except Exception as e: except Exception as e:
print(f"⚠️ Could not delete source file {input_file}: {e}") print(f"⚠️ Could not delete source file {input_file}: {e}")
def encode_batch(directory, codec, remove_source=False): def encode_batch(directory, codec, remove_source=False, save_log=False):
if not os.path.isdir(directory): if not os.path.isdir(directory):
print(f"❌ Not a valid directory: {directory}") print(f"❌ Not a valid directory: {directory}")
return return
@ -105,7 +115,7 @@ def encode_batch(directory, codec, remove_source=False):
if file.lower().endswith(SUPPORTED_EXTENSIONS): if file.lower().endswith(SUPPORTED_EXTENSIONS):
filepath = os.path.join(root, file) filepath = os.path.join(root, file)
try: try:
encode(filepath, codec, remove_source) encode(filepath, codec, remove_source, save_log)
except Exception as e: except Exception as e:
print(f"\n❌ Error with file {file}: {e}") print(f"\n❌ Error with file {file}: {e}")
continue continue
@ -116,15 +126,16 @@ def main():
parser.add_argument("-d", "--directory", help="Path to a directory for batch encoding") parser.add_argument("-d", "--directory", help="Path to a directory for batch encoding")
parser.add_argument("--codec", choices=["x265", "x265-amd", "av1"], default="x265", help="Codec to use") parser.add_argument("--codec", choices=["x265", "x265-amd", "av1"], default="x265", help="Codec to use")
parser.add_argument("--remove-source", action="store_true", help="Remove the source file after successful encoding") parser.add_argument("--remove-source", action="store_true", help="Remove the source file after successful encoding")
parser.add_argument("--save-log", action="store_true", help="Save ffmpeg logs to a .log file")
args = parser.parse_args() args = parser.parse_args()
if args.directory: if args.directory:
encode_batch(args.directory, args.codec, args.remove_source) encode_batch(args.directory, args.codec, args.remove_source, args.save_log)
elif args.input: elif args.input:
if not os.path.isfile(args.input): if not os.path.isfile(args.input):
print(f"❌ File not found: {args.input}") print(f"❌ File not found: {args.input}")
sys.exit(1) sys.exit(1)
encode(args.input, args.codec, args.remove_source) encode(args.input, args.codec, args.remove_source, args.save_log)
else: else:
print("❌ Please provide a file path or use -d for a directory.") print("❌ Please provide a file path or use -d for a directory.")
parser.print_help() parser.print_help()