File size: 5,289 Bytes
93a133c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from __future__ import annotations

from pathlib import Path
import json
import re
import subprocess
import wave

from .voice_voxcpm import _background_creationflags


SUPPORTED_FORMATS = {"wav", "flac", "mp3"}


def finalize_audio(
    source: Path,
    destination: Path,
    *,
    sample_rate: int = 48000,
    loudness: float = -16.0,
    speed: float = 1.0,
    trim_silence: bool = False,
) -> Path:
    """Master a generated voice track without changing its natural pitch.

    The neural model remains responsible for expressiveness and pronunciation;
    this stage only performs transparent cleanup, loudness normalization, safe
    peak limiting, optional pitch-preserving speed adjustment, and delivery
    encoding.
    """
    if not source.exists():
        raise FileNotFoundError(f"Generated source audio is missing: {source}")
    fmt = destination.suffix.lower().lstrip(".")
    if fmt not in SUPPORTED_FORMATS:
        raise ValueError(f"Unsupported audio format: {fmt or 'none'}. Use WAV, FLAC, or MP3.")
    if not 16000 <= int(sample_rate) <= 96000:
        raise ValueError("Audio sample rate must be between 16,000 and 96,000 Hz.")
    if not 0.75 <= float(speed) <= 1.25:
        raise ValueError("Audio speed must be between 0.75x and 1.25x.")

    destination.parent.mkdir(parents=True, exist_ok=True)
    filters = ["highpass=f=65", "lowpass=f=16000"]
    if trim_silence:
        filters.append(
            "silenceremove=start_periods=1:start_duration=0.08:start_threshold=-50dB:"
            "stop_periods=1:stop_duration=0.20:stop_threshold=-50dB"
        )
    if abs(float(speed) - 1.0) > 0.001:
        filters.extend(_atempo_filters(float(speed)))
    filters.extend([f"loudnorm=I={float(loudness):.1f}:TP=-1.5:LRA=11", "alimiter=limit=0.95"])

    command = [
        "ffmpeg",
        "-hide_banner",
        "-loglevel",
        "error",
        "-y",
        "-i",
        str(source),
        "-af",
        ",".join(filters),
        "-ar",
        str(int(sample_rate)),
        "-ac",
        "1",
    ]
    if fmt == "wav":
        command.extend(["-c:a", "pcm_s24le"])
    elif fmt == "flac":
        command.extend(["-c:a", "flac", "-compression_level", "8"])
    else:
        command.extend(["-c:a", "libmp3lame", "-b:a", "320k", "-write_xing", "1"])
    command.append(str(destination))

    completed = subprocess.run(
        command,
        capture_output=True,
        text=True,
        timeout=180,
        creationflags=_background_creationflags(),
    )
    if completed.returncode != 0 or not destination.exists() or destination.stat().st_size < 1024:
        detail = (completed.stderr or completed.stdout or "FFmpeg failed to master the audio.").strip()
        raise RuntimeError(detail[-1600:])
    return destination


def audio_duration_seconds(path: Path) -> float:
    """Return duration for PCM WAV files, with ffprobe fallback for other formats."""
    if path.suffix.lower() == ".wav":
        try:
            with wave.open(str(path), "rb") as handle:
                return round(handle.getnframes() / float(handle.getframerate()), 3)
        except (OSError, wave.Error):
            pass
    completed = subprocess.run(
        [
            "ffprobe",
            "-v",
            "error",
            "-show_entries",
            "format=duration",
            "-of",
            "default=noprint_wrappers=1:nokey=1",
            str(path),
        ],
        capture_output=True,
        text=True,
        timeout=20,
        creationflags=_background_creationflags(),
    )
    try:
        return round(float(completed.stdout.strip()), 3)
    except (TypeError, ValueError):
        return 0.0


def nepali_word_count(text: str) -> int:
    return len(re.findall(r"[\w\u0900-\u097f]+", text, flags=re.UNICODE))


def speed_for_target_wpm(text: str, duration_seconds: float, target_wpm: float) -> float:
    """Return a safe pitch-preserving speed multiplier for reference pacing."""
    if duration_seconds <= 0 or target_wpm <= 0:
        return 1.0
    current_wpm = nepali_word_count(text) / duration_seconds * 60.0
    if current_wpm <= 0:
        return 1.0
    # atempo > 1.0 makes speech faster; to reach target WPM, use target/current.
    return max(0.75, min(1.25, float(target_wpm) / current_wpm))


def write_audio_manifest(path: Path, *, text: str, output: Path, engine: str, sample_rate: int, loudness: float, speed: float, duration: float, target_wpm: float = 0.0) -> Path:
    manifest = path.with_suffix(".json")
    manifest.write_text(
        json.dumps(
            {
                "text": text,
                "output": str(output),
                "engine": engine,
                "sample_rate_hz": int(sample_rate),
                "target_loudness_lufs": float(loudness),
                "speed": float(speed),
                "target_reference_wpm": float(target_wpm),
                "duration_seconds": float(duration),
                "open_source_pipeline": True,
            },
            ensure_ascii=False,
            indent=2,
        ),
        encoding="utf-8",
    )
    return manifest


def _atempo_filters(speed: float) -> list[str]:
    # FFmpeg accepts 0.5..2.0 per atempo filter; one filter is enough for the UI range.
    return [f"atempo={speed:.3f}"]