summaryrefslogtreecommitdiff
path: root/convert.py
blob: 235591c9b5420246ae2f5a2b196721584407f135 (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
98
99
100
#!/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 or webm file to mp3")
    print("Usage:\nconvert.py [-n|-y] [SOURCE] [DESTINATION]")
    print("  -n ffmpeg: Do not overwrite output files, and exit immediately if a specified output file already exists. (Default option)")
    print("  -y ffmpeg: Overwrite output files without asking.")
    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"]
    if file.endswith(tuple(ext)):
      exist = False
      if os.path.isfile(outdir+"/"+name+".mp3"):
        if os.path.getsize(path_rm_end_slash(sourcedir)+"/"+file) == os.path.getsize(outdir+"/"+name+".mp3"):
          print("File "+path_rm_end_slash(sourcedir)+"/"+name+".mp3 already exist. Use -y for overwrite.")
      else:
        print("Converting : "+file)
      count += 1
      #cmd = ["ffmpeg", "-n", "-i", sourcedir+"/"+name+".mp4", "-c:a", "libmp3lame", outdir+"/"+name+".mp3"]²
      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)
          print(time_number)
          thread.close
        elif i == 2:
          unknown_line = thread.match.group(0)
          if re.match(r'.*Duration.*', str(unknown_line)):
            count = 0
            for element in unknown_line.split():
              count += 1
              if re.match(r"^b'Duration:'$", str(element)):
                break
            total = str(unknown_line.split()[count]).split("'")[1].split(',')[0]
            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()
          if re.match(r'.*time=.*', str(unknown_line)):
            timeRange = time.strptime(str(unknown_line).partition("time=")[2].split('.')[0],'%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()