File size: 5,567 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
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
"""Audio post-processing, PCM16 conversion, and text segmentation helpers."""
from __future__ import annotations

import math
import re

import numpy as np
import torch

PEAK = 0.99
DEFAULT_TARGET_RMS_DB = -14.5
DEFAULT_FADE_MS = 5.0

_SPACE = re.compile(r"[\s\ufeff]+")
_SENTENCE_END = re.compile(r"""(?:(?<=[.!?…])|(?<=[.!?…]["')\]]))\s+(?=["'(\[]?[A-ZÀ-Ý0-9])""")
_NOT_AN_END = re.compile(
    r"(?:\b(?:mr|mrs|ms|dr|dra|sr|sra|srta|prof|profa|jr|st|sto|sta|vs|etc|no|inc|ltd|ltda|co|pág|cap|fig|art|e\.g|i\.e|a\.m|p\.m)|\b[A-ZÀ-Ý])\.$",
    re.IGNORECASE,
)
_CLAUSE_END = re.compile(r"(?<=[,;:—])\s+")
_TEXT_END = re.compile(r"[\s\ufeff]+$")
_CLOSING = "\"'”’)]»"


def pcm16(wave: np.ndarray | torch.Tensor) -> tuple[np.ndarray, float]:
    """Scale samples into [-1, 1] when peak > 1.0 and return ``(samples, attenuation_db)``."""
    arr = wave.detach().cpu().numpy() if isinstance(wave, torch.Tensor) else wave
    arr = np.asarray(arr, dtype=np.float64)
    peak = float(np.abs(arr).max()) if arr.size else 0.0
    if peak <= 1.0:
        return arr, 0.0
    return arr / peak, round(20.0 * float(np.log10(peak)), 2)


def limit_peak(wave: torch.Tensor, peak: float = PEAK) -> torch.Tensor:
    """Scale ``wave`` down as a whole only when its peak amplitude exceeds ``peak``."""
    loudest = float(wave.abs().max()) if wave.numel() else 0.0
    return wave * (peak / loudest) if loudest > peak else wave


def _postprocess_numpy(

    arr: np.ndarray,

    sample_rate: int,

    target_rms_db: float | None,

    peak: float | None,

    fade_ms: float,

) -> np.ndarray:
    if not arr.size:
        return arr
    out = np.asarray(arr, dtype=np.float32)
    if target_rms_db is not None:
        loudest = float(np.abs(out).max())
        if loudest > 1e-7:
            frame_len = max(1, int(round(sample_rate * 0.02)))
            usable = (out.size // frame_len) * frame_len
            if usable >= frame_len:
                f_rms = np.sqrt((out[:usable].reshape(-1, frame_len) ** 2).mean(axis=1))
                active = f_rms[f_rms > loudest * (10.0 ** (-35.0 / 20.0))]
                rms = float(np.sqrt((active ** 2).mean())) if active.size else float(np.sqrt((out ** 2).mean()))
            else:
                rms = float(np.sqrt((out ** 2).mean()))
            target_rms = 10.0 ** (float(target_rms_db) / 20.0)
            gain = max(0.25, min(4.0, target_rms / max(rms, 1e-8)))
            out = out * np.float32(gain)
    if fade_ms and fade_ms > 0:
        n = min(int(round(sample_rate * fade_ms / 1000.0)), out.size // 2)
        if n > 1:
            out = out.copy()
            ramp = (0.5 * (1.0 - np.cos(np.linspace(0.0, math.pi, n, dtype=np.float32)))).astype(np.float32)
            out[:n] *= ramp
            out[-n:] *= ramp[::-1]
    if peak is not None:
        loudest = float(np.abs(out).max())
        if loudest > peak:
            out = out * np.float32(peak / loudest)
    return out


def postprocess_audio(

    wave: np.ndarray | torch.Tensor,

    sample_rate: int = 24000,

    target_rms_db: float | None = DEFAULT_TARGET_RMS_DB,

    peak: float | None = PEAK,

    fade_ms: float = DEFAULT_FADE_MS,

) -> np.ndarray | torch.Tensor:
    """Normalize active-speech RMS, apply short cosine edge fades, and limit peaks."""
    if isinstance(wave, torch.Tensor):
        if not wave.numel():
            return wave
        processed = _postprocess_numpy(wave.detach().cpu().numpy(), sample_rate, target_rms_db, peak, fade_ms)
        return torch.from_numpy(processed).to(device=wave.device, dtype=wave.dtype)
    return _postprocess_numpy(np.asarray(wave, dtype=np.float32), sample_rate, target_rms_db, peak, fade_ms)


def sentences(text: str) -> list[str]:
    """Split text into natural sentences without breaking on common abbreviations."""
    parts, current = [], ""
    for piece in _SENTENCE_END.split(_SPACE.sub(" ", text).strip()):
        current = f"{current} {piece}" if current else piece
        if not _NOT_AN_END.search(current):
            parts.append(current)
            current = ""
    if current:
        parts.append(current)
    return [part for part in parts if any(ch.isalnum() for ch in part)]


def finished(text: str) -> str:
    """Append a final period when text ends without terminal or clause punctuation."""
    body = _TEXT_END.sub("", text)
    if not body:
        return text
    last = _SPACE.split(body)[-1]
    if any(ch.isalnum() for ch in last):
        marked = last.rstrip(_CLOSING)[-1:] in tuple(".!?…,;:")
    else:
        marked = any(ch in ".!?…" for ch in last) or last in (",", ";", ":")
    return text if marked else body + "."


def shorter(text: str) -> list[str]:
    """Split an overly long sentence on clause punctuation, or at its middle word."""
    pieces = _CLAUSE_END.split(text)
    if len(pieces) > 1:
        return pieces
    words = text.split(" ")
    if len(words) < 2:
        return []
    half = (len(words) + 1) // 2
    return [" ".join(words[:half]), " ".join(words[half:])]


def split_clauses(text: str) -> list[str]:
    """Split text into sentences and clause-level chunks with terminal punctuation."""
    chunks: list[str] = []
    for sent in sentences(text):
        for clause in _CLAUSE_END.split(finished(sent)):
            clean = clause.strip()
            if clean:
                chunks.append(clean)
    return chunks or ([text.strip()] if text.strip() else [])