aboutsummaryrefslogtreecommitdiff
path: root/convert.py
blob: 2782954f2e5cbd67397c151e3bd13825569718f2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
#!/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()