Delete fix_infer_zipvoice.py
Browse files- fix_infer_zipvoice.py +0 -741
fix_infer_zipvoice.py
DELETED
|
@@ -1,741 +0,0 @@
|
|
| 1 |
-
import argparse
|
| 2 |
-
import datetime as dt
|
| 3 |
-
import json
|
| 4 |
-
import os
|
| 5 |
-
from typing import Optional
|
| 6 |
-
|
| 7 |
-
import numpy as np
|
| 8 |
-
import safetensors.torch
|
| 9 |
-
import torch
|
| 10 |
-
import torchaudio
|
| 11 |
-
from lhotse.utils import fix_random_seed
|
| 12 |
-
from vocos import Vocos
|
| 13 |
-
|
| 14 |
-
from zipvoice.models.zipvoice import ZipVoice
|
| 15 |
-
from zipvoice.tokenizer.tokenizer import (
|
| 16 |
-
EspeakTokenizer,
|
| 17 |
-
)
|
| 18 |
-
from zipvoice.utils.checkpoint import load_checkpoint
|
| 19 |
-
from zipvoice.utils.common import AttributeDict
|
| 20 |
-
from zipvoice.utils.feature import VocosFbank
|
| 21 |
-
|
| 22 |
-
import sys
|
| 23 |
-
import matplotlib.pyplot as plt
|
| 24 |
-
|
| 25 |
-
from glob import glob
|
| 26 |
-
import torchaudio.functional as F
|
| 27 |
-
|
| 28 |
-
class AttrDict(dict):
|
| 29 |
-
def __init__(self, *args, **kwargs):
|
| 30 |
-
super(AttrDict, self).__init__(*args, **kwargs)
|
| 31 |
-
self.__dict__ = self
|
| 32 |
-
|
| 33 |
-
def get_parser():
|
| 34 |
-
parser = argparse.ArgumentParser(
|
| 35 |
-
formatter_class=argparse.ArgumentDefaultsHelpFormatter
|
| 36 |
-
)
|
| 37 |
-
|
| 38 |
-
parser.add_argument(
|
| 39 |
-
"--model-name",
|
| 40 |
-
type=str,
|
| 41 |
-
default="zipvoice",
|
| 42 |
-
choices=["zipvoice", "zipvoice_distill"],
|
| 43 |
-
help="The model used for inference",
|
| 44 |
-
)
|
| 45 |
-
|
| 46 |
-
parser.add_argument(
|
| 47 |
-
"--checkpoint",
|
| 48 |
-
type=str,
|
| 49 |
-
default=None,
|
| 50 |
-
help="The model checkpoint. "
|
| 51 |
-
"Will download pre-trained checkpoint from huggingface if not specified.",
|
| 52 |
-
)
|
| 53 |
-
|
| 54 |
-
parser.add_argument(
|
| 55 |
-
"--model-config",
|
| 56 |
-
type=str,
|
| 57 |
-
default=None,
|
| 58 |
-
help="The model configuration file. "
|
| 59 |
-
"Will download zipvoice_base.json from huggingface if not specified.",
|
| 60 |
-
)
|
| 61 |
-
|
| 62 |
-
parser.add_argument(
|
| 63 |
-
"--vocoder-path",
|
| 64 |
-
type=str,
|
| 65 |
-
default=None,
|
| 66 |
-
help="The vocoder checkpoint. "
|
| 67 |
-
"Will download pre-trained vocoder from huggingface if not specified.",
|
| 68 |
-
)
|
| 69 |
-
|
| 70 |
-
parser.add_argument(
|
| 71 |
-
"--token-file",
|
| 72 |
-
type=str,
|
| 73 |
-
default=None,
|
| 74 |
-
help="The file that contains information that maps tokens to ids,"
|
| 75 |
-
"which is a text file with '{token}\t{token_id}' per line. "
|
| 76 |
-
"Will download tokens_emilia.txt from huggingface if not specified.",
|
| 77 |
-
)
|
| 78 |
-
|
| 79 |
-
parser.add_argument(
|
| 80 |
-
"--tokenizer",
|
| 81 |
-
type=str,
|
| 82 |
-
default="emilia",
|
| 83 |
-
choices=["emilia", "libritts", "espeak", "simple"],
|
| 84 |
-
help="Tokenizer type.",
|
| 85 |
-
)
|
| 86 |
-
|
| 87 |
-
parser.add_argument(
|
| 88 |
-
"--lang",
|
| 89 |
-
type=str,
|
| 90 |
-
default="en-us",
|
| 91 |
-
help="Language identifier, used when tokenizer type is espeak. see"
|
| 92 |
-
"https://github.com/rhasspy/espeak-ng/blob/master/docs/languages.md",
|
| 93 |
-
)
|
| 94 |
-
|
| 95 |
-
parser.add_argument(
|
| 96 |
-
"--test-list",
|
| 97 |
-
type=str,
|
| 98 |
-
default="/data/private/ZipVoice/zzz.tsv",
|
| 99 |
-
help="The list of prompt speech, prompt_transcription, "
|
| 100 |
-
"and text to synthesizein the format of "
|
| 101 |
-
"'{wav_name}\t{prompt_transcription}\t{prompt_wav}\t{text}'.",
|
| 102 |
-
)
|
| 103 |
-
|
| 104 |
-
parser.add_argument(
|
| 105 |
-
"--prompt-wav",
|
| 106 |
-
type=str,
|
| 107 |
-
default=None,
|
| 108 |
-
help="The prompt wav to mimic",
|
| 109 |
-
)
|
| 110 |
-
|
| 111 |
-
parser.add_argument(
|
| 112 |
-
"--prompt-text",
|
| 113 |
-
type=str,
|
| 114 |
-
default=None,
|
| 115 |
-
help="The transcription of the prompt wav",
|
| 116 |
-
)
|
| 117 |
-
|
| 118 |
-
parser.add_argument(
|
| 119 |
-
"--text",
|
| 120 |
-
type=str,
|
| 121 |
-
default=None,
|
| 122 |
-
help="The text to synthesize",
|
| 123 |
-
)
|
| 124 |
-
|
| 125 |
-
parser.add_argument(
|
| 126 |
-
"--res-dir",
|
| 127 |
-
type=str,
|
| 128 |
-
default="results",
|
| 129 |
-
help="""
|
| 130 |
-
Path name of the generated wavs dir,
|
| 131 |
-
used when test-list is not None
|
| 132 |
-
""",
|
| 133 |
-
)
|
| 134 |
-
|
| 135 |
-
parser.add_argument(
|
| 136 |
-
"--res-wav-path",
|
| 137 |
-
type=str,
|
| 138 |
-
default="result.wav",
|
| 139 |
-
help="""
|
| 140 |
-
Path name of the generated wav path,
|
| 141 |
-
used when test-list is None
|
| 142 |
-
""",
|
| 143 |
-
)
|
| 144 |
-
|
| 145 |
-
parser.add_argument(
|
| 146 |
-
"--guidance-scale",
|
| 147 |
-
type=float,
|
| 148 |
-
default=None,
|
| 149 |
-
help="The scale of classifier-free guidance during inference.",
|
| 150 |
-
)
|
| 151 |
-
|
| 152 |
-
parser.add_argument(
|
| 153 |
-
"--num-step",
|
| 154 |
-
type=int,
|
| 155 |
-
default=None,
|
| 156 |
-
help="The number of sampling steps.",
|
| 157 |
-
)
|
| 158 |
-
|
| 159 |
-
parser.add_argument(
|
| 160 |
-
"--feat-scale",
|
| 161 |
-
type=float,
|
| 162 |
-
default=0.1,
|
| 163 |
-
help="The scale factor of fbank feature",
|
| 164 |
-
)
|
| 165 |
-
|
| 166 |
-
parser.add_argument(
|
| 167 |
-
"--speed",
|
| 168 |
-
type=float,
|
| 169 |
-
default=1.0,
|
| 170 |
-
help="Control speech speed, 1.0 means normal, >1.0 means speed up",
|
| 171 |
-
)
|
| 172 |
-
|
| 173 |
-
parser.add_argument(
|
| 174 |
-
"--t-shift",
|
| 175 |
-
type=float,
|
| 176 |
-
default=0.5,
|
| 177 |
-
help="Shift t to smaller ones if t_shift < 1.0",
|
| 178 |
-
)
|
| 179 |
-
|
| 180 |
-
parser.add_argument(
|
| 181 |
-
"--target-rms",
|
| 182 |
-
type=float,
|
| 183 |
-
default=0.1,
|
| 184 |
-
help="Target speech normalization rms value, set to 0 to disable normalization",
|
| 185 |
-
)
|
| 186 |
-
|
| 187 |
-
parser.add_argument(
|
| 188 |
-
"--seed",
|
| 189 |
-
type=int,
|
| 190 |
-
default=666,
|
| 191 |
-
help="Random seed",
|
| 192 |
-
)
|
| 193 |
-
|
| 194 |
-
return parser
|
| 195 |
-
|
| 196 |
-
def get_vocoder(vocos_local_path: Optional[str] = None):
|
| 197 |
-
vocoder = Vocos.from_hparams(f"{vocos_local_path}/config.yaml")
|
| 198 |
-
state_dict = torch.load(
|
| 199 |
-
f"{vocos_local_path}/pytorch_model.bin",
|
| 200 |
-
weights_only=True,
|
| 201 |
-
map_location="cpu",
|
| 202 |
-
)
|
| 203 |
-
vocoder.load_state_dict(state_dict)
|
| 204 |
-
|
| 205 |
-
return vocoder
|
| 206 |
-
|
| 207 |
-
def fix_sentence(
|
| 208 |
-
save_path,
|
| 209 |
-
prompt_text,
|
| 210 |
-
prompt_wav,
|
| 211 |
-
model: torch.nn.Module,
|
| 212 |
-
vocoder: torch.nn.Module,
|
| 213 |
-
tokenizer: EspeakTokenizer,
|
| 214 |
-
feature_extractor: VocosFbank,
|
| 215 |
-
device: torch.device,
|
| 216 |
-
num_step: int = 16,
|
| 217 |
-
guidance_scale: float = 1.0,
|
| 218 |
-
speed: float = 1.0,
|
| 219 |
-
t_shift: float = 0.5,
|
| 220 |
-
target_rms: float = 0.1,
|
| 221 |
-
feat_scale: float = 0.1,
|
| 222 |
-
sampling_rate: int = 24000,
|
| 223 |
-
mask_list: list = [[0,1]]
|
| 224 |
-
):
|
| 225 |
-
|
| 226 |
-
# Convert text to tokens
|
| 227 |
-
prompt_tokens = tokenizer.texts_to_token_ids([prompt_text])
|
| 228 |
-
|
| 229 |
-
# Load and preprocess prompt wav
|
| 230 |
-
#prompt_wav, prompt_sampling_rate = torchaudio.load(prompt_wav)
|
| 231 |
-
prompt_wav, prompt_sampling_rate = prompt_wav
|
| 232 |
-
|
| 233 |
-
prompt_rms = torch.sqrt(torch.mean(torch.square(prompt_wav)))
|
| 234 |
-
if prompt_rms < target_rms:
|
| 235 |
-
prompt_wav = prompt_wav * target_rms / prompt_rms
|
| 236 |
-
|
| 237 |
-
# Extract features from prompt wav
|
| 238 |
-
prompt_features = feature_extractor.extract(
|
| 239 |
-
prompt_wav, sampling_rate=sampling_rate
|
| 240 |
-
).to(device)
|
| 241 |
-
|
| 242 |
-
prompt_features = prompt_features.unsqueeze(0) * feat_scale
|
| 243 |
-
prompt_features_lens = torch.tensor([prompt_features.size(1)], device=device)
|
| 244 |
-
|
| 245 |
-
# Start timing
|
| 246 |
-
start_t = dt.datetime.now()
|
| 247 |
-
|
| 248 |
-
#batch 안됨.
|
| 249 |
-
pred_features = model.sample_fix(
|
| 250 |
-
prompt_tokens=prompt_tokens,
|
| 251 |
-
prompt_features=prompt_features,
|
| 252 |
-
prompt_features_lens=prompt_features_lens,
|
| 253 |
-
speed=speed,
|
| 254 |
-
t_shift=t_shift,
|
| 255 |
-
duration="predict",
|
| 256 |
-
num_step=num_step,
|
| 257 |
-
guidance_scale=guidance_scale,
|
| 258 |
-
mask_list=mask_list,
|
| 259 |
-
save_path=save_path
|
| 260 |
-
)
|
| 261 |
-
|
| 262 |
-
# Postprocess predicted features
|
| 263 |
-
pred_features = pred_features.permute(0, 2, 1) / feat_scale # (B, C, T)
|
| 264 |
-
|
| 265 |
-
# Start vocoder processing
|
| 266 |
-
start_vocoder_t = dt.datetime.now()
|
| 267 |
-
wav = vocoder.decode(pred_features).squeeze(1).clamp(-1, 1)
|
| 268 |
-
|
| 269 |
-
# Calculate processing times and real-time factors
|
| 270 |
-
t = (dt.datetime.now() - start_t).total_seconds()
|
| 271 |
-
t_no_vocoder = (start_vocoder_t - start_t).total_seconds()
|
| 272 |
-
t_vocoder = (dt.datetime.now() - start_vocoder_t).total_seconds()
|
| 273 |
-
wav_seconds = wav.shape[-1] / sampling_rate
|
| 274 |
-
rtf = t / wav_seconds
|
| 275 |
-
rtf_no_vocoder = t_no_vocoder / wav_seconds
|
| 276 |
-
rtf_vocoder = t_vocoder / wav_seconds
|
| 277 |
-
metrics = {
|
| 278 |
-
"t": t,
|
| 279 |
-
"t_no_vocoder": t_no_vocoder,
|
| 280 |
-
"t_vocoder": t_vocoder,
|
| 281 |
-
"wav_seconds": wav_seconds,
|
| 282 |
-
"rtf": rtf,
|
| 283 |
-
"rtf_no_vocoder": rtf_no_vocoder,
|
| 284 |
-
"rtf_vocoder": rtf_vocoder,
|
| 285 |
-
}
|
| 286 |
-
|
| 287 |
-
# Adjust wav volume if necessary
|
| 288 |
-
if prompt_rms < target_rms:
|
| 289 |
-
wav = wav * prompt_rms / target_rms
|
| 290 |
-
|
| 291 |
-
#torchaudio.save(save_path, wav.cpu(), sample_rate=sampling_rate)
|
| 292 |
-
|
| 293 |
-
return wav.cpu()
|
| 294 |
-
|
| 295 |
-
sr = 24000
|
| 296 |
-
hop_length = 256
|
| 297 |
-
|
| 298 |
-
def time_to_frame(t_sec):
|
| 299 |
-
return int(t_sec * sr / hop_length)
|
| 300 |
-
|
| 301 |
-
def has_pii_tag(text: str) -> bool:
|
| 302 |
-
return any(tag in text for tag in TAGS)
|
| 303 |
-
|
| 304 |
-
def has_pii_tag(text: str) -> bool:
|
| 305 |
-
TAGS = ["<NUMBER>", "<NAME>", "<RRN>", "<CARD>"]
|
| 306 |
-
return any(tag in text for tag in TAGS)
|
| 307 |
-
|
| 308 |
-
def collect_context_windows(data, window=5):
|
| 309 |
-
n = len(data)
|
| 310 |
-
tag_indices = [i for i, item in enumerate(data) if has_pii_tag(item["word"])]
|
| 311 |
-
|
| 312 |
-
ranges = []
|
| 313 |
-
for idx in tag_indices:
|
| 314 |
-
lo = max(0, idx - window)
|
| 315 |
-
hi = min(n - 1, idx + window)
|
| 316 |
-
ranges.append([lo, hi])
|
| 317 |
-
|
| 318 |
-
ranges.sort()
|
| 319 |
-
merged = []
|
| 320 |
-
for lo, hi in ranges:
|
| 321 |
-
if merged and lo <= merged[-1][1] + 1:
|
| 322 |
-
merged[-1][1] = max(merged[-1][1], hi)
|
| 323 |
-
else:
|
| 324 |
-
merged.append([lo, hi])
|
| 325 |
-
|
| 326 |
-
groups = []
|
| 327 |
-
for lo, hi in merged:
|
| 328 |
-
segment = data[lo:hi + 1]
|
| 329 |
-
merged_word = " ".join(item["word"] for item in segment)
|
| 330 |
-
|
| 331 |
-
tag_spans = [
|
| 332 |
-
{"word": item["word"], "start": item["start"], "end": item["end"]}
|
| 333 |
-
for item in segment
|
| 334 |
-
if has_pii_tag(item["word"])
|
| 335 |
-
]
|
| 336 |
-
|
| 337 |
-
groups.append({
|
| 338 |
-
"word": merged_word,
|
| 339 |
-
"start": segment[0]["start"],
|
| 340 |
-
"end": segment[-1]["end"],
|
| 341 |
-
"tags": tag_spans,
|
| 342 |
-
})
|
| 343 |
-
return groups
|
| 344 |
-
|
| 345 |
-
import re
|
| 346 |
-
|
| 347 |
-
def parse_segments(path):
|
| 348 |
-
seg_re = re.compile(r"^#seg\s+([\d.]+)-([\d.]+)")
|
| 349 |
-
word_re = re.compile(r"^([\d.]+)-([\d.]+)\s+(.*)$")
|
| 350 |
-
|
| 351 |
-
segments = []
|
| 352 |
-
current = None
|
| 353 |
-
|
| 354 |
-
with open(path, encoding="utf-8") as f:
|
| 355 |
-
for line in f:
|
| 356 |
-
line = line.rstrip("\n")
|
| 357 |
-
if not line.strip():
|
| 358 |
-
continue
|
| 359 |
-
|
| 360 |
-
m = seg_re.match(line)
|
| 361 |
-
if m:
|
| 362 |
-
current = {
|
| 363 |
-
"seg_start": float(m.group(1)),
|
| 364 |
-
"seg_end": float(m.group(2)),
|
| 365 |
-
"words": [],
|
| 366 |
-
}
|
| 367 |
-
segments.append(current)
|
| 368 |
-
continue
|
| 369 |
-
|
| 370 |
-
m = word_re.match(line)
|
| 371 |
-
if m and current is not None:
|
| 372 |
-
current["words"].append({
|
| 373 |
-
"start": float(m.group(1)),
|
| 374 |
-
"end": float(m.group(2)),
|
| 375 |
-
"text": m.group(3).strip(),
|
| 376 |
-
})
|
| 377 |
-
|
| 378 |
-
return segments
|
| 379 |
-
|
| 380 |
-
resampler = torchaudio.transforms.Resample(orig_freq=8000, new_freq=24000)
|
| 381 |
-
resampler_8K = torchaudio.transforms.Resample(orig_freq=24000, new_freq=8000)
|
| 382 |
-
|
| 383 |
-
|
| 384 |
-
@torch.inference_mode()
|
| 385 |
-
def main():
|
| 386 |
-
parser = get_parser()
|
| 387 |
-
args = parser.parse_args()
|
| 388 |
-
|
| 389 |
-
params = AttributeDict()
|
| 390 |
-
params.update(vars(args))
|
| 391 |
-
|
| 392 |
-
fix_random_seed(1234)
|
| 393 |
-
|
| 394 |
-
model_defaults = {
|
| 395 |
-
"zipvoice": {
|
| 396 |
-
"num_step": 16,
|
| 397 |
-
"guidance_scale": 1.0,
|
| 398 |
-
},
|
| 399 |
-
"zipvoice_distill": {
|
| 400 |
-
"num_step": 8,
|
| 401 |
-
"guidance_scale": 3.0,
|
| 402 |
-
},
|
| 403 |
-
}
|
| 404 |
-
|
| 405 |
-
model_specific_defaults = model_defaults.get(params.model_name, {})
|
| 406 |
-
|
| 407 |
-
for param, value in model_specific_defaults.items():
|
| 408 |
-
if getattr(params, param) is None:
|
| 409 |
-
setattr(params, param, value)
|
| 410 |
-
|
| 411 |
-
if torch.cuda.is_available():
|
| 412 |
-
params.device = torch.device("cuda", 0)
|
| 413 |
-
else:
|
| 414 |
-
params.device = torch.device("cpu")
|
| 415 |
-
|
| 416 |
-
print("Loading model...")
|
| 417 |
-
model_config = "./configs/zipvoice_base.json"
|
| 418 |
-
|
| 419 |
-
with open(model_config, "r") as f:
|
| 420 |
-
model_config = json.load(f)
|
| 421 |
-
|
| 422 |
-
token_file = "./configs/tokens.txt"
|
| 423 |
-
|
| 424 |
-
tokenizer = EspeakTokenizer(token_file=token_file, lang="ko")
|
| 425 |
-
|
| 426 |
-
tokenizer_config = {"vocab_size": tokenizer.vocab_size, "pad_id": tokenizer.pad_id}
|
| 427 |
-
|
| 428 |
-
model_ckpt = params.checkpoint
|
| 429 |
-
|
| 430 |
-
model = ZipVoice(
|
| 431 |
-
**model_config["model"],
|
| 432 |
-
**tokenizer_config,
|
| 433 |
-
)
|
| 434 |
-
|
| 435 |
-
load_checkpoint(filename=model_ckpt, model=model, strict=True)
|
| 436 |
-
|
| 437 |
-
model = model.to(params.device)
|
| 438 |
-
model.eval()
|
| 439 |
-
|
| 440 |
-
vocoder = get_vocoder("./zipvoice_checkpoint/vocos_checkpoint")
|
| 441 |
-
vocoder = vocoder.to(params.device)
|
| 442 |
-
vocoder.eval()
|
| 443 |
-
|
| 444 |
-
feature_extractor = VocosFbank()
|
| 445 |
-
|
| 446 |
-
params.sampling_rate = model_config["feature"]["sampling_rate"]
|
| 447 |
-
|
| 448 |
-
|
| 449 |
-
# 수정해야함.
|
| 450 |
-
#wav_list = glob("/data/private/ZipVoice/Sample_jh/mono/*.wav")
|
| 451 |
-
|
| 452 |
-
#wav_list = glob("/data/public/jiho/261123_420rejected_call/original/32290820231031101207/32290820231031101207_rx.wav")
|
| 453 |
-
wav_list = glob("/data/public/jiho/261123_check/32290420231031100727_rx.wav")
|
| 454 |
-
|
| 455 |
-
|
| 456 |
-
|
| 457 |
-
# zzz 폴더에 결과 저장.
|
| 458 |
-
|
| 459 |
-
with open("./zzz/result.txt", "w") as f:
|
| 460 |
-
f.write("")
|
| 461 |
-
|
| 462 |
-
with open("./zzz/danger.txt", "w") as f:
|
| 463 |
-
f.write("")
|
| 464 |
-
|
| 465 |
-
for num, total_wav_path in enumerate(wav_list):
|
| 466 |
-
# 0. data pair
|
| 467 |
-
|
| 468 |
-
wav_file_name = total_wav_path.split("/")[-1]
|
| 469 |
-
|
| 470 |
-
# 수정해야함.
|
| 471 |
-
|
| 472 |
-
#total_txt_path = "/data/private/ZipVoice/Sample_jh/transcript_koo_pii_final_filled_2/" + wav_file_name.replace(".wav", "_result.txt")
|
| 473 |
-
#total_txt_path = "/data/public/jiho/261123_420rejected_call/stage2/32290820231031101207/pii_filled/" + wav_file_name.replace(".wav", ".txt")
|
| 474 |
-
#total_txt_path = "/data/public/jiho/261123_check/new_261124/" + wav_file_name.replace(".wav", ".txt")
|
| 475 |
-
total_txt_path = "/data/public/jiho/261123_check/new_261124/" + "new.txt"
|
| 476 |
-
|
| 477 |
-
wav_8k, _ = torchaudio.load(total_wav_path)
|
| 478 |
-
|
| 479 |
-
total_wav = resampler(wav_8k)
|
| 480 |
-
|
| 481 |
-
total_sampling_rate = 24000
|
| 482 |
-
|
| 483 |
-
seg_list = parse_segments(total_txt_path)
|
| 484 |
-
|
| 485 |
-
# 1. save_data 저장 and <tag> 없으면 pass
|
| 486 |
-
# seg에 있는 데이터가 모두 <tag> 이면 참고 데이터가 없어 생성할 수 없음.
|
| 487 |
-
# 정보를 줄 수 있는 seg 를 save 분으로 저장하자.
|
| 488 |
-
|
| 489 |
-
'''
|
| 490 |
-
#기존 로직
|
| 491 |
-
save_wav = None
|
| 492 |
-
save_txt = ""
|
| 493 |
-
count = 0
|
| 494 |
-
for unit_seg in seg_list:
|
| 495 |
-
word_list = unit_seg["words"]
|
| 496 |
-
|
| 497 |
-
unit_script = ""
|
| 498 |
-
mask_list = []
|
| 499 |
-
for word in word_list:
|
| 500 |
-
unit_script += word["text"] + " "
|
| 501 |
-
|
| 502 |
-
if "<f>" in word["text"]:
|
| 503 |
-
mask_list.append([word["start"], word["end"]])
|
| 504 |
-
|
| 505 |
-
unit_script = unit_script.strip()
|
| 506 |
-
|
| 507 |
-
if "<f>" in unit_script:
|
| 508 |
-
count += 1
|
| 509 |
-
|
| 510 |
-
else:
|
| 511 |
-
if save_wav == None:
|
| 512 |
-
if (float(unit_seg["seg_end"])-float(unit_seg["seg_start"])) > 2:
|
| 513 |
-
save_wav = total_wav[:, int(unit_seg["seg_start"]*total_sampling_rate):int(unit_seg["seg_end"]*total_sampling_rate)]
|
| 514 |
-
save_txt = unit_script
|
| 515 |
-
'''
|
| 516 |
-
|
| 517 |
-
#새로운 로직
|
| 518 |
-
count = 0
|
| 519 |
-
|
| 520 |
-
save_wav_txt_pair = []
|
| 521 |
-
|
| 522 |
-
for unit_seg in seg_list:
|
| 523 |
-
word_list = unit_seg["words"]
|
| 524 |
-
|
| 525 |
-
unit_script = ""
|
| 526 |
-
mask_list = []
|
| 527 |
-
for word in word_list:
|
| 528 |
-
unit_script += word["text"] + " "
|
| 529 |
-
|
| 530 |
-
if "<f>" in word["text"]:
|
| 531 |
-
mask_list.append([word["start"], word["end"]])
|
| 532 |
-
|
| 533 |
-
unit_script = unit_script.strip()
|
| 534 |
-
|
| 535 |
-
if "<f>" in unit_script:
|
| 536 |
-
count += 1
|
| 537 |
-
|
| 538 |
-
else:
|
| 539 |
-
# 물리적인 2초 고정 X, 실제 음성 정보가 있는지 판단해야함.
|
| 540 |
-
unit_world_total = 0
|
| 541 |
-
for word_unit in word_list:
|
| 542 |
-
real_word_time = word_unit["end"] - word_unit["start"]
|
| 543 |
-
unit_world_total += real_word_time
|
| 544 |
-
|
| 545 |
-
|
| 546 |
-
save_wav = total_wav[:, int(unit_seg["seg_start"]*total_sampling_rate):int(unit_seg["seg_end"]*total_sampling_rate)]
|
| 547 |
-
save_txt = unit_script
|
| 548 |
-
|
| 549 |
-
save_wav_txt_pair.append([unit_world_total, save_wav, save_txt])
|
| 550 |
-
|
| 551 |
-
save_wav_txt_pair = sorted(save_wav_txt_pair, key=lambda x: x[0], reverse=True)
|
| 552 |
-
|
| 553 |
-
if len(save_wav_txt_pair) < 1:
|
| 554 |
-
save_wav = None
|
| 555 |
-
save_txt = ""
|
| 556 |
-
|
| 557 |
-
else:
|
| 558 |
-
save_wav = save_wav_txt_pair[0][1]
|
| 559 |
-
save_txt = save_wav_txt_pair[0][2]
|
| 560 |
-
|
| 561 |
-
|
| 562 |
-
if count > 0 and save_wav == None:
|
| 563 |
-
print(total_wav_path, " : 해당 음성은 데이터를 생성할 수 없습니다. tag가 없는 2초 이상의 데이터가 필요합니다.")
|
| 564 |
-
with open("./zzz/danger.txt", "a") as f:
|
| 565 |
-
f.write(total_wav_path)
|
| 566 |
-
f.write("\n")
|
| 567 |
-
|
| 568 |
-
else:
|
| 569 |
-
if count == 0:
|
| 570 |
-
print(total_wav_path, " : 해당 wav는 tag 없어서 채우지 않습니다.")
|
| 571 |
-
|
| 572 |
-
#그냥 저장해도 되고 원본 가져다 써도 되고
|
| 573 |
-
if 0:
|
| 574 |
-
save_path = os.path.join("./zzz/", wav_file_name)
|
| 575 |
-
torchaudio.save(save_path, total_wav.cpu(), sample_rate=24000)
|
| 576 |
-
|
| 577 |
-
else:
|
| 578 |
-
fix_total_list = []
|
| 579 |
-
|
| 580 |
-
# tag 채우기
|
| 581 |
-
for unit_num, unit_seg in enumerate(seg_list):
|
| 582 |
-
word_list = unit_seg["words"]
|
| 583 |
-
|
| 584 |
-
unit_script = ""
|
| 585 |
-
mask_list = []
|
| 586 |
-
zero_list = []
|
| 587 |
-
|
| 588 |
-
pre_word = {'start': 0, 'end': 0, 'text': ''}
|
| 589 |
-
|
| 590 |
-
for word in word_list:
|
| 591 |
-
unit_script += word["text"] + " "
|
| 592 |
-
|
| 593 |
-
if "<f>" in word["text"]:
|
| 594 |
-
mask_list.append([word["start"], word["end"]])
|
| 595 |
-
|
| 596 |
-
if ("<f>" in pre_word["text"]) and ("<f>" in word["text"]):
|
| 597 |
-
|
| 598 |
-
f_mid_time = word["start"] - pre_word["end"]
|
| 599 |
-
if f_mid_time > 0:
|
| 600 |
-
zero_list.append([pre_word["end"], word["start"]])
|
| 601 |
-
|
| 602 |
-
pre_word = word
|
| 603 |
-
|
| 604 |
-
#<f> 와 <f> 사이의 값 0로 밀어야함.
|
| 605 |
-
for zero_unit in zero_list:
|
| 606 |
-
zero_start, zero_end = zero_unit
|
| 607 |
-
total_wav[:,int(zero_start*total_sampling_rate):int(zero_end*total_sampling_rate)] = 0
|
| 608 |
-
|
| 609 |
-
unit_script = unit_script.strip()
|
| 610 |
-
|
| 611 |
-
if "<f>" in unit_script:
|
| 612 |
-
res_wav_path = "None" # 충돌 방지
|
| 613 |
-
# 1) bad case : save wav 를 써야하는 case
|
| 614 |
-
if len(unit_script.split(" "))-len(mask_list) < 3:
|
| 615 |
-
seg_start_time = float(unit_seg["seg_start"])
|
| 616 |
-
seg_end_time = float(unit_seg["seg_end"])
|
| 617 |
-
|
| 618 |
-
unit_wav = total_wav[:,int(seg_start_time*total_sampling_rate):int(seg_end_time*total_sampling_rate)]
|
| 619 |
-
prompt_text = unit_script.replace("<f>", "")
|
| 620 |
-
|
| 621 |
-
spec_mask_list = []
|
| 622 |
-
|
| 623 |
-
for unit_mask in mask_list:
|
| 624 |
-
mask_start_time = unit_mask[0] - seg_start_time
|
| 625 |
-
mask_end_time = unit_mask[1] - seg_start_time
|
| 626 |
-
|
| 627 |
-
start_frame = time_to_frame(mask_start_time)
|
| 628 |
-
end_frame = time_to_frame(mask_end_time)
|
| 629 |
-
|
| 630 |
-
spec_mask_list.append([start_frame, end_frame])
|
| 631 |
-
|
| 632 |
-
concat_wav = torch.cat((unit_wav, save_wav), dim=1)
|
| 633 |
-
|
| 634 |
-
concat_txt = prompt_text + " " + save_txt
|
| 635 |
-
|
| 636 |
-
fix_wav_add = fix_sentence(
|
| 637 |
-
save_path=res_wav_path,
|
| 638 |
-
prompt_text=concat_txt,
|
| 639 |
-
prompt_wav=(concat_wav, total_sampling_rate),
|
| 640 |
-
model=model,
|
| 641 |
-
vocoder=vocoder,
|
| 642 |
-
tokenizer=tokenizer,
|
| 643 |
-
feature_extractor=feature_extractor,
|
| 644 |
-
device=params.device,
|
| 645 |
-
num_step=params.num_step,
|
| 646 |
-
guidance_scale=params.guidance_scale,
|
| 647 |
-
speed=params.speed,
|
| 648 |
-
t_shift=params.t_shift,
|
| 649 |
-
target_rms=params.target_rms,
|
| 650 |
-
feat_scale=params.feat_scale,
|
| 651 |
-
sampling_rate=params.sampling_rate,
|
| 652 |
-
mask_list=spec_mask_list
|
| 653 |
-
)
|
| 654 |
-
|
| 655 |
-
fix_wav = fix_wav_add[:, :unit_wav.size(1)]
|
| 656 |
-
fix_total_list.append([fix_wav, int(seg_start_time*total_sampling_rate), int(seg_end_time*total_sampling_rate)])
|
| 657 |
-
|
| 658 |
-
# 2) good case : save wav 를 사용 안하는 case
|
| 659 |
-
else:
|
| 660 |
-
seg_start_time = float(unit_seg["seg_start"])
|
| 661 |
-
seg_end_time = float(unit_seg["seg_end"])
|
| 662 |
-
|
| 663 |
-
unit_wav = total_wav[:,int(seg_start_time*total_sampling_rate):int(seg_end_time*total_sampling_rate)]
|
| 664 |
-
|
| 665 |
-
prompt_text = unit_script.replace("<f>", "")
|
| 666 |
-
|
| 667 |
-
spec_mask_list = []
|
| 668 |
-
|
| 669 |
-
for unit_mask in mask_list:
|
| 670 |
-
|
| 671 |
-
mask_start_time = unit_mask[0] - seg_start_time
|
| 672 |
-
mask_end_time = unit_mask[1] - seg_start_time
|
| 673 |
-
|
| 674 |
-
print(mask_start_time, mask_end_time)
|
| 675 |
-
start_frame = time_to_frame(mask_start_time)
|
| 676 |
-
end_frame = time_to_frame(mask_end_time)
|
| 677 |
-
|
| 678 |
-
spec_mask_list.append([start_frame, end_frame])
|
| 679 |
-
|
| 680 |
-
fix_wav = fix_sentence(
|
| 681 |
-
save_path=res_wav_path,
|
| 682 |
-
prompt_text=prompt_text,
|
| 683 |
-
prompt_wav=(unit_wav, total_sampling_rate),
|
| 684 |
-
model=model,
|
| 685 |
-
vocoder=vocoder,
|
| 686 |
-
tokenizer=tokenizer,
|
| 687 |
-
feature_extractor=feature_extractor,
|
| 688 |
-
device=params.device,
|
| 689 |
-
num_step=params.num_step,
|
| 690 |
-
guidance_scale=params.guidance_scale,
|
| 691 |
-
speed=params.speed,
|
| 692 |
-
t_shift=params.t_shift,
|
| 693 |
-
target_rms=params.target_rms,
|
| 694 |
-
feat_scale=params.feat_scale,
|
| 695 |
-
sampling_rate=params.sampling_rate,
|
| 696 |
-
mask_list=spec_mask_list
|
| 697 |
-
)
|
| 698 |
-
|
| 699 |
-
fix_total_list.append([fix_wav, int(seg_start_time*total_sampling_rate), int(seg_end_time*total_sampling_rate)])
|
| 700 |
-
|
| 701 |
-
#살짝이라도 밀릴수 있으니까 리버스 하고 뒤에서 부터 채우기
|
| 702 |
-
fix_total_list_reverse = fix_total_list[::-1]
|
| 703 |
-
|
| 704 |
-
with open("./zzz/result.txt", "a") as f:
|
| 705 |
-
f.write(wav_file_name)
|
| 706 |
-
f.write("\n")
|
| 707 |
-
|
| 708 |
-
save_path = os.path.join("./zzz/", wav_file_name.replace(".wav", "_fix.wav"))
|
| 709 |
-
save_wav_path = os.path.join("./zzz/", wav_file_name.replace(".wav", "_save_wav.wav"))
|
| 710 |
-
|
| 711 |
-
for fix_wav, start, end in fix_total_list_reverse:
|
| 712 |
-
with open("./zzz/result.txt", "a") as f:
|
| 713 |
-
f.write("start = "+str(start/24000))
|
| 714 |
-
f.write("\n")
|
| 715 |
-
f.write("end = "+ str(end/24000))
|
| 716 |
-
f.write("\n")
|
| 717 |
-
|
| 718 |
-
unit_original = resampler_8K(total_wav[:, start:end].cpu())
|
| 719 |
-
|
| 720 |
-
total_wav = torch.cat((total_wav[:, :start], fix_wav, total_wav[:, end:]), dim=1)
|
| 721 |
-
|
| 722 |
-
unit_fix = resampler_8K(fix_wav.cpu())
|
| 723 |
-
|
| 724 |
-
torchaudio.save(save_path.replace(".wav", str(start/24000) +"_"+str(str(end/24000)) +".wav"), unit_fix.cpu(), sample_rate=8000)
|
| 725 |
-
torchaudio.save(save_path.replace(".wav", str(start/24000) +"_"+str(str(end/24000)) +"_origin.wav"), unit_original.cpu(), sample_rate=8000)
|
| 726 |
-
|
| 727 |
-
|
| 728 |
-
save_wav_8K = resampler_8K(save_wav.cpu())
|
| 729 |
-
torchaudio.save(save_wav_path, save_wav_8K.cpu(), sample_rate=8000)
|
| 730 |
-
|
| 731 |
-
total_wav_8K = resampler_8K(total_wav.cpu())
|
| 732 |
-
torchaudio.save(save_path, total_wav_8K.cpu(), sample_rate=8000)
|
| 733 |
-
|
| 734 |
-
#torchaudio.save(save_path, total_wav.cpu(), sample_rate=24000)
|
| 735 |
-
|
| 736 |
-
|
| 737 |
-
|
| 738 |
-
if __name__ == "__main__":
|
| 739 |
-
torch.set_num_threads(1)
|
| 740 |
-
torch.set_num_interop_threads(1)
|
| 741 |
-
main()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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