File size: 6,135 Bytes
c8be32d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
"""Common utility functions for the backend."""

from typing import Any
from typings.extra import StrOrBytesPath

import hashlib
import json
import os
import shutil

import gradio as gr

from backend.exceptions import PathNotFoundError

from common import AUDIO_DIR, RVC_MODELS_DIR

INTERMEDIATE_AUDIO_DIR = os.path.join(AUDIO_DIR, "intermediate")
OUTPUT_AUDIO_DIR = os.path.join(AUDIO_DIR, "output")


def display_progress(
    message: str,
    percentage: float | None = None,
    progress_bar: gr.Progress | None = None,
) -> None:
    """
    Display progress message and percentage in console or Gradio progress bar.

    Parameters
    ----------
    message : str
        Message to display.
    percentage : float, optional
        Percentage to display.
    progress_bar : gr.Progress, optional
        The Gradio progress bar to update.
    """
    if progress_bar is None:
        print(message)
    else:
        progress_bar(percentage, desc=message)


def remove_suffix_after(text: str, occurrence: str) -> str:
    """
    Remove suffix after the first occurrence of a substring in a string.

    Parameters
    ----------
    text : str
        The string to remove the suffix from.
    occurrence : str
        The substring to remove the suffix after.

    Returns
    -------
    str
        The string with the suffix removed.
    """
    location = text.rfind(occurrence)
    if location == -1:
        return text
    else:
        return text[: location + len(occurrence)]


def copy_files_to_new_folder(file_paths: list[str], folder_path: str) -> None:
    """
    Copy files to a new folder.

    Parameters
    ----------
    file_paths : list[str]
        List of file paths to copy.
    folder_path : str
        Path of the folder to copy the files to.

    Raises
    ------
    PathNotFoundError
        If a file does not exist.
    """
    os.makedirs(folder_path)
    for file_path in file_paths:
        if not os.path.exists(file_path):
            raise PathNotFoundError(f"File not found: {file_path}")
        shutil.copyfile(
            file_path, os.path.join(folder_path, os.path.basename(file_path))
        )


def get_path_stem(path: str) -> str:
    """
    Get the stem of a file path.

    The stem is the name of the file that the path points to,
    not including its extension.

    Parameters
    ----------
    path : str
        The file path.

    Returns
    -------
    str
        The stem of the file path.
    """
    return os.path.splitext(os.path.basename(path))[0]


def json_dumps(thing: Any) -> str:
    """
    Dump a Python object to a JSON string.

    Parameters
    ----------
    thing : Any
        The object to dump.

    Returns
    -------
    str
        The JSON string representation of the object.
    """
    return json.dumps(
        thing, ensure_ascii=False, sort_keys=True, indent=4, separators=(",", ": ")
    )


def json_dump(thing: Any, path: StrOrBytesPath) -> None:
    """
    Dump a Python object to a JSON file.

    Parameters
    ----------
    thing : Any
        The object to dump.
    path : str
        The path of the JSON file.
    """
    with open(path, "w", encoding="utf-8") as file:
        json.dump(
            thing,
            file,
            ensure_ascii=False,
            sort_keys=True,
            indent=4,
            separators=(",", ": "),
        )


def json_load(path: StrOrBytesPath, encoding: str = "utf-8") -> Any:
    """
    Load a Python object from a JSON file.

    Parameters
    ----------
    path : str
        The path of the JSON file.
    encoding : str, default='utf-8'
        The encoding of the file.

    Returns
    -------
    Any
        The Python object loaded from the JSON file.
    """
    with open(path, encoding=encoding) as file:
        return json.load(file)


def get_hash(thing: Any, size: int = 5) -> str:
    """
    Get a hash of a Python object.

    Parameters
    ----------
    thing : Any
        The object to hash.
    size : int, default=5
        The size of the hash in bytes.

    Returns
    -------
    str
        The hash of the object.
    """
    return hashlib.blake2b(
        json_dumps(thing).encode("utf-8"), digest_size=size
    ).hexdigest()


# TODO consider increasing size to 16
# otherwise we might have problems with hash collisions
def get_file_hash(filepath: StrOrBytesPath, size: int = 5) -> str:
    """
    Get the hash of a file.

    Parameters
    ----------
    filepath : str
        The path of the file.
    size : int, default=5
        The size of the hash in bytes.

    Returns
    -------
    str
        The hash of the file.
    """
    with open(filepath, "rb") as f:
        file_hash = hashlib.file_digest(f, lambda: hashlib.blake2b(digest_size=size))
    return file_hash.hexdigest()


def get_rvc_model(voice_model: str) -> tuple[str, str]:
    """
    Get the RVC model file and optional index file for a voice model.

    When no index file exists, an empty string is returned.

    Parameters
    ----------
    voice_model : str
        The name of the voice model.

    Returns
    -------
    model_path : str
        The path of the RVC model file.
    index_path : str
        The path of the RVC index file.

    Raises
    ------
    PathNotFoundError
        If the directory of the voice model does not exist or
        if no model file exists in the directory.
    """
    rvc_model_filename, rvc_index_filename = None, None
    model_dir = os.path.join(RVC_MODELS_DIR, voice_model)
    if not os.path.exists(model_dir):
        raise PathNotFoundError(
            f"Voice model directory '{voice_model}' does not exist."
        )
    for file in os.listdir(model_dir):
        ext = os.path.splitext(file)[1]
        if ext == ".pth":
            rvc_model_filename = file
        if ext == ".index":
            rvc_index_filename = file

    if rvc_model_filename is None:
        raise PathNotFoundError(f"No model file exists in {model_dir}.")

    return os.path.join(model_dir, rvc_model_filename), (
        os.path.join(model_dir, rvc_index_filename) if rvc_index_filename else ""
    )