CoolFace
Apppublic

dthomas84/RVC_RULE1

sourceHugging Facelgpl-3.0updated 3y agoView on Hugging Face
0likes
utils.py154 linesDownload Raw Back to root
1import ffmpeg2import numpy as np3 4# import praatio5# import praatio.praat_scripts6import os7import sys8 9import random10 11import csv12 13platform_stft_mapping = {14    "linux": "stftpitchshift",15    "darwin": "stftpitchshift",16    "win32": "stftpitchshift.exe",17}18 19stft = platform_stft_mapping.get(sys.platform)20# praatEXE = join('.',os.path.abspath(os.getcwd()) + r"\Praat.exe")21 22 23def CSVutil(file, rw, type, *args):24    if type == "formanting":25        if rw == "r":26            with open(file) as fileCSVread:27                csv_reader = list(csv.reader(fileCSVread))28                return (29                    (csv_reader[0][0], csv_reader[0][1], csv_reader[0][2])30                    if csv_reader is not None31                    else (lambda: exec('raise ValueError("No data")'))()32                )33        else:34            if args:35                doformnt = args[0]36            else:37                doformnt = False38            qfr = args[1] if len(args) > 1 else 1.039            tmb = args[2] if len(args) > 2 else 1.040            with open(file, rw, newline="") as fileCSVwrite:41                csv_writer = csv.writer(fileCSVwrite, delimiter=",")42                csv_writer.writerow([doformnt, qfr, tmb])43    elif type == "stop":44        stop = args[0] if args else False45        with open(file, rw, newline="") as fileCSVwrite:46            csv_writer = csv.writer(fileCSVwrite, delimiter=",")47            csv_writer.writerow([stop])48 49 50def load_audio(file, sr, DoFormant, Quefrency, Timbre):51    converted = False52    DoFormant, Quefrency, Timbre = CSVutil("csvdb/formanting.csv", "r", "formanting")53    try:54        # https://github.com/openai/whisper/blob/main/whisper/audio.py#L2655        # This launches a subprocess to decode audio while down-mixing and resampling as necessary.56        # Requires the ffmpeg CLI and `ffmpeg-python` package to be installed.57        file = (58            file.strip(" ").strip('"').strip("\n").strip('"').strip(" ")59        )  # The search feature accounts for the "and" and carriage return60        # ratios that prevent small white copy paths with spaces at the end and ends61        file_formanted = file.strip(" ").strip('"').strip("\n").strip('"').strip(" ")62 63        # print(f"dofor={bool(DoFormant)} timbr={Timbre} quef={Quefrency}\n")64 65        if (66            lambda DoFormant: True67            if DoFormant.lower() == "true"68            else (False if DoFormant.lower() == "false" else DoFormant)69        )(DoFormant):70            numerator = round(random.uniform(1, 4), 4)71            # os.system(f"stftpitchshift -i {file} -q {Quefrency} -t {Timbre} -o {file_formanted}")72            # print('stftpitchshift -i "%s" -p 1.0 --rms -w 128 -v 8 -q %s -t %s -o "%s"' % (file, Quefrency, Timbre, file_formanted))73 74            if not file.endswith(".wav"):75                if not os.path.isfile(f"{file_formanted}.wav"):76                    converted = True77                    # print(f"\nfile = {file}\n")78                    # print(f"\nfile_formanted = {file_formanted}\n")79                    converting = (80                        ffmpeg.input(file_formanted, threads=0)81                        .output(f"{file_formanted}.wav")82                        .run(83                            cmd=["ffmpeg", "-nostdin"],84                            capture_stdout=True,85                            capture_stderr=True,86                        )87                    )88                else:89                    pass90 91            file_formanted = (92                f"{file_formanted}.wav"93                if not file_formanted.endswith(".wav")94                else file_formanted95            )96 97            print(f" · Formanting {file_formanted}...\n")98 99            os.system(100                '%s -i "%s" -q "%s" -t "%s" -o "%sFORMANTED_%s.wav"'101                % (102                    stft,103                    file_formanted,104                    Quefrency,105                    Timbre,106                    file_formanted,107                    str(numerator),108                )109            )110 111            print(f" · Formanted {file_formanted}!\n")112 113            # filepraat = (os.path.abspath(os.getcwd()) + '\\' + file).replace('/','\\')114            # file_formantedpraat = ('"' + os.path.abspath(os.getcwd()) + '/' + 'formanted'.join(file_formanted) + '"').replace('/','\\')115            # print("%sFORMANTED_%s.wav" % (file_formanted, str(numerator)))116 117            out, _ = (118                ffmpeg.input(119                    "%sFORMANTED_%s.wav" % (file_formanted, str(numerator)), threads=0120                )121                .output("-", format="f32le", acodec="pcm_f32le", ac=1, ar=sr)122                .run(123                    cmd=["ffmpeg", "-nostdin"], capture_stdout=True, capture_stderr=True124                )125            )126 127            try:128                os.remove("%sFORMANTED_%s.wav" % (file_formanted, str(numerator)))129            except Exception:130                pass131                print("couldn't remove formanted type of file")132 133        else:134            out, _ = (135                ffmpeg.input(file, threads=0)136                .output("-", format="f32le", acodec="pcm_f32le", ac=1, ar=sr)137                .run(138                    cmd=["ffmpeg", "-nostdin"], capture_stdout=True, capture_stderr=True139                )140            )141    except Exception as e:142        raise RuntimeError(f"Failed to load audio: {e}")143 144    if converted:145        try:146            os.remove(file_formanted)147        except Exception:148            pass149            print("couldn't remove converted type of file")150        converted = False151 152    return np.frombuffer(out, np.float32).flatten()153 154