#!/usr/bin/env python3

import os
import string
import glob
from multiprocessing import Process, Queue, cpu_count
from concurrent.futures import ThreadPoolExecutor

q = Queue()
installdir = '/usr/share/OtdRealPeopleTTS'

all_mp3 = glob.glob('*/*.mp3')
for mp3 in all_mp3:
    q.put(mp3)

def mkdir(d):
    if not os.path.exists(d):
        os.system('mkdir -p ' + d)

def doConvert(f):
    t = '%s/%s' % (installdir, f.lower())
    mkdir(os.path.dirname(t))

    cmd = 'mpg321 -w "%s" "%s" >>%s/install.log 2>&1 ' % (t.replace(' ', '').replace('.mp3', '.wav'), f, installdir)
    os.system(cmd)

def doWork(q, tid):
    while True:
        if q.qsize() == 0:
            break
        mp3 = q.get()
        remain = q.qsize()
        total = len(all_mp3)
        print("#%d Processing [%d/%d]: %s" % (tid, total - remain, total, mp3), end='                   \r')
        doConvert(mp3)


num_workers = cpu_count()
executor = ThreadPoolExecutor(max_workers=num_workers)
for i in range(num_workers):
    task = executor.submit(doWork, q, i)

