File size: 3,656 Bytes
d4101a0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Shared streaming and chunk-stitching helpers for PyTorch and ONNX synthesizers."""
from __future__ import annotations

from collections.abc import Callable, Iterator

import numpy as np

from ..text.normalizer import normalize_ptbr_text
from ..text.phonemizer import phonemize
from ..utils.audio import finished, sentences, shorter


def _split_piece_by_tokens(piece: str, max_tokens: int) -> list[str]:
    phones = phonemize(piece)
    if len(phones) <= max_tokens:
        return [piece]
    halves = shorter(piece)
    if len(halves) > 1:
        out: list[str] = []
        for sub in halves:
            if sub.strip():
                out.extend(_split_piece_by_tokens(sub, max_tokens))
        return out
    raise ValueError(f"chunk exceeds max_tokens={max_tokens}: {piece[:80]!r}")


def iter_speakable_pieces(text: str, max_tokens: int, normalize: bool = True) -> list[str]:
    """Normalize text and split it into sentence/clause pieces fitting within ``max_tokens``."""
    if not text or not text.strip():
        raise ValueError("input text must not be empty")
    clean = normalize_ptbr_text(text) if normalize else text.strip()
    sent_list = [finished(s) for s in sentences(clean)] or [finished(clean)]
    pieces: list[str] = []
    for sent in sent_list:
        pieces.extend(_split_piece_by_tokens(sent, max_tokens))
    return pieces


def stream_vocoder_chunks(

    decode_mel_fn: Callable[[np.ndarray], np.ndarray],

    phys_mel: np.ndarray,

    hop: int = 256,

    chunk_frames: int = 36,

    context_frames: int = 8,

    fade_frames: int = 4,

) -> Iterator[np.ndarray]:
    """Yield click-free mono waveform chunks from physical log-mel ``[T, 100]``.



    Each chunk includes symmetrical convolutional lookback/lookahead ``context_frames`` when

    decoding and applies a raised-cosine Hann crossfade across ``fade_frames`` at boundaries so

    concatenating all yielded chunks matches exact length ``T * hop``.

    """
    mel = np.asarray(phys_mel, dtype=np.float32)
    if mel.ndim == 3:
        mel = mel[0]
    total_frames = int(mel.shape[0])
    if total_frames <= 0:
        return

    chunk = max(int(chunk_frames), 4)
    ctx = max(int(context_frames), 0)
    fade = min(max(int(fade_frames), 0), chunk // 2)
    pending_tail: np.ndarray | None = None
    start = 0

    while start < total_frames:
        end = min(total_frames, start + chunk)
        if total_frames - end <= max(fade, chunk // 3):
            end = total_frames

        out_start = start - fade if pending_tail is not None and fade > 0 else start
        in_start = max(0, out_start - ctx)
        in_end = min(total_frames, end + ctx)

        raw = np.asarray(decode_mel_fn(mel[in_start:in_end]), dtype=np.float32).reshape(-1)
        left_trim = (out_start - in_start) * hop
        out_samples = (end - out_start) * hop
        seg = raw[left_trim : left_trim + out_samples].copy()

        if pending_tail is not None and pending_tail.size > 0:
            n_fade = int(pending_tail.size)
            t = np.linspace(0.0, 1.0, n_fade, dtype=np.float32)
            w = 0.5 * (1.0 - np.cos(np.pi * t))
            seg[:n_fade] = (1.0 - w) * pending_tail + w * seg[:n_fade]

        if end < total_frames and fade > 0:
            tail_samples = fade * hop
            pending_tail = seg[-tail_samples:].copy()
            emit = seg[:-tail_samples]
        else:
            pending_tail = None
            emit = seg

        if emit.size > 0:
            yield np.clip(emit, -0.99, 0.99).astype(np.float32, copy=False)
        start = end