#!/usr/bin/env python3 import sys import os import subprocess import re from subprocess import check_output, STDOUT, CalledProcessError, Popen, PIPE import pexpect import time import datetime def path_rm_end_slash(string): string = re.sub("\/$", "", string) return(string) if len(sys.argv) >= 3 and len(sys.argv) <= 4: if len(sys.argv) == 3: sourcedir = sys.argv[1] outdir = sys.argv[2] arg = "-n" else: sourcedir = sys.argv[2] outdir = sys.argv[3] arg = sys.argv[1] if not os.path.isdir(sourcedir): print("No such file or directory: '"+str(sourcedir)+"'") sys.exit() else: print("Simple tool for convert mp4, mkv, webm, mod or xm file to mp3") print("Usage:\nconvert.py [-n|-y] [SOURCE] [DESTINATION]") print(" -n ffmpeg: Doesn't overwrite output files, and go to next file to be converted if the specified output file already exists. (Default option)") print(" -y ffmpeg: Overwrite output files.") sys.exit() def dirSize(path,ext1,ext2): list_dir = [] list_dir = os.listdir(path) count = 0 for file in list_dir: if file.endswith(ext1): count += 1 if file.endswith(ext2): count += 1 return count if not os.path.exists(outdir): os.makedirs(outdir) total = dirSize(sourcedir, ".mp4", ".mkv") count = 0 for file in sorted(os.listdir(sourcedir)): try: name = file[:file.rfind(".")] ext = [".mp4", ".mkv", ".webm", ".mod", ".xm"] if file.endswith(tuple(ext)): exist = False if os.path.isfile(outdir+"/"+name+".mp3") and arg == "-n": print("File "+path_rm_end_slash(outdir)+"/"+name+".mp3 already exist. Use -y for overwrite.") else: print("Converting : "+file) count += 0 cmd = 'ffmpeg '+arg+' -i "'+path_rm_end_slash(sourcedir)+'/'+file+'" -c:a libmp3lame "'+outdir+'/'+name+'.mp3"' thread = pexpect.spawn(cmd) cpl = thread.compile_pattern_list([pexpect.EOF,"frame= *\d+",'(.+)']) while True: i = thread.expect_list(cpl, timeout=None) if i == 0: # EOF break elif i == 1: time_number = thread.match.group(0) thread.close elif i == 2: unknown_line = thread.match.group(0) ffmpeg_time = re.search('(Duration: [0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9])', str(unknown_line), re.IGNORECASE) if ffmpeg_time: total = str(ffmpeg_time.group(0)).split(' ')[1] totalRange = time.strptime(total.split('.')[0],'%H:%M:%S') totalRangeS = datetime.timedelta(hours=totalRange.tm_hour,minutes=totalRange.tm_min,seconds=totalRange.tm_sec).total_seconds() ffmpeg_time = re.search('(time=[0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9])', str(unknown_line), re.IGNORECASE) if ffmpeg_time: timeRange = time.strptime(str(ffmpeg_time.group(0)).split('.')[0].split('=')[1],'%H:%M:%S') timeRangeS = datetime.timedelta(hours=timeRange.tm_hour,minutes=timeRange.tm_min,seconds=timeRange.tm_sec).total_seconds() print(str(round(100*timeRangeS/totalRangeS, 1))+"% / 100% "+str(exist), end='\r') thread.close except KeyboardInterrupt: # Read the comment here => https://stackoverflow.com/a/1112357 ! os.remove(outdir+"/"+name+".mp3") sys.exit()