voice-aligner / utils.py
d-ragon's picture
Upload 3 files
e5841a9 verified
Raw History Blame Contribute Delete
19 kB
import os
from dataclasses import dataclass
from typing import Any, Dict, List, Optional, Tuple
import numpy as np
import soundfile as sf
from faster_whisper.audio import decode_audio
PUBLIC_MODEL_ID = os.environ.get("PUBLIC_MODEL_ID", "openai/whisper-large-v3")
SAMPLE_RATE = int(os.environ.get("SAMPLE_RATE", "16000"))
DEFAULT_SILENCE_THRESHOLD_DB = float(os.environ.get("DEFAULT_SILENCE_THRESHOLD_DB", "-40"))
DEFAULT_MIN_SILENCE_SEC = float(os.environ.get("DEFAULT_MIN_SILENCE_SEC", "0.30"))
DEFAULT_KEEP_PADDING_SEC = float(os.environ.get("DEFAULT_KEEP_PADDING_SEC", "0.05"))
SILENCE_ANALYSIS_WINDOW_MS = int(os.environ.get("SILENCE_ANALYSIS_WINDOW_MS", "10"))
MAX_SILENCE_MS = int(os.environ.get("MAX_SILENCE_MS", "5000"))
@dataclass
class SilenceTrimOptions:
enabled: bool
threshold_db: float
min_silence_sec: float
keep_padding_sec: float
@dataclass
class TrimRequestCompat:
trim_silence: Optional[bool] = True
silence_threshold_db: Optional[float] = None
min_silence_sec: Optional[float] = None
keep_padding_sec: Optional[float] = None
def _seconds_from_samples(sample_count: int) -> float:
return sample_count / SAMPLE_RATE
def _samples_from_ms(duration_ms: int) -> int:
return int(round((duration_ms / 1000.0) * SAMPLE_RATE))
def _round_sec(value: float) -> float:
return round(value, 4)
def _clamp(value: float, minimum: float, maximum: float) -> float:
return max(minimum, min(maximum, value))
def _db_to_amplitude(db_value: float) -> float:
return float(10.0 ** (db_value / 20.0))
def _resolve_trim_options(req: "TrimRequestCompat", default_enabled: bool = False) -> SilenceTrimOptions:
enabled = default_enabled if req.trim_silence is None else bool(req.trim_silence)
threshold_db = _clamp(
float(req.silence_threshold_db if req.silence_threshold_db is not None else DEFAULT_SILENCE_THRESHOLD_DB),
-80.0,
-5.0,
)
min_silence_sec = _clamp(
float(req.min_silence_sec if req.min_silence_sec is not None else DEFAULT_MIN_SILENCE_SEC),
0.02,
MAX_SILENCE_MS / 1000.0,
)
keep_padding_sec = _clamp(
float(req.keep_padding_sec if req.keep_padding_sec is not None else DEFAULT_KEEP_PADDING_SEC),
0.0,
min_silence_sec,
)
return SilenceTrimOptions(
enabled=enabled,
threshold_db=threshold_db,
min_silence_sec=min_silence_sec,
keep_padding_sec=keep_padding_sec,
)
def _detect_silence_runs(
audio: np.ndarray,
threshold_db: float,
min_silence_sec: float,
) -> List[Tuple[int, int]]:
if audio.size == 0:
return []
threshold = _db_to_amplitude(threshold_db)
window_samples = max(1, _samples_from_ms(SILENCE_ANALYSIS_WINDOW_MS))
min_silence_samples = max(1, int(round(min_silence_sec * SAMPLE_RATE)))
mono_audio = np.asarray(audio, dtype=np.float32)
frame_ranges: List[Tuple[int, int]] = []
frame_silence: List[bool] = []
for start in range(0, len(mono_audio), window_samples):
end = min(len(mono_audio), start + window_samples)
frame_ranges.append((start, end))
if end <= start:
rms = 0.0
else:
window = mono_audio[start:end]
rms = float(np.sqrt(np.mean(np.square(window, dtype=np.float32))))
frame_silence.append(rms < threshold)
runs: List[Tuple[int, int]] = []
run_start_frame: Optional[int] = None
for index, is_silent in enumerate(frame_silence):
if is_silent and run_start_frame is None:
run_start_frame = index
elif not is_silent and run_start_frame is not None:
start_sample = frame_ranges[run_start_frame][0]
end_sample = frame_ranges[index - 1][1]
if end_sample - start_sample >= min_silence_samples:
runs.append((start_sample, end_sample))
run_start_frame = None
if run_start_frame is not None:
start_sample = frame_ranges[run_start_frame][0]
end_sample = frame_ranges[-1][1]
if end_sample - start_sample >= min_silence_samples:
runs.append((start_sample, end_sample))
return runs
def _build_trimmed_intervals(
silence_runs: List[Tuple[int, int]],
keep_padding_sec: float,
) -> List[Tuple[int, int]]:
keep_padding_samples = max(0, int(round(keep_padding_sec * SAMPLE_RATE)))
removed: List[Tuple[int, int]] = []
for start_sample, end_sample in silence_runs:
remove_start = min(end_sample, start_sample + keep_padding_samples)
remove_end = max(start_sample, end_sample - keep_padding_samples)
if remove_end > remove_start:
removed.append((remove_start, remove_end))
return removed
def _remap_sample(sample: int, removed_intervals: List[Tuple[int, int]]) -> int:
removed_before = 0
for start_sample, end_sample in removed_intervals:
if sample >= end_sample:
removed_before += end_sample - start_sample
continue
if sample > start_sample:
removed_before += sample - start_sample
break
return max(0, sample - removed_before)
def _remap_timed_items(items: List[Dict[str, Any]], removed_intervals: List[Tuple[int, int]]) -> List[Dict[str, Any]]:
remapped: List[Dict[str, Any]] = []
for item in items:
updated = dict(item)
if "start_sample" in item and "end_sample" in item:
new_start = _remap_sample(int(item["start_sample"]), removed_intervals)
new_end = _remap_sample(int(item["end_sample"]), removed_intervals)
if item["end_sample"] > item["start_sample"] and new_end <= new_start + 2:
new_end = new_start + 3
updated["start_sample"] = new_start
updated["end_sample"] = new_end
updated["start_sec"] = _round_sec(_seconds_from_samples(new_start))
updated["end_sec"] = _round_sec(_seconds_from_samples(new_end))
updated["duration_sec"] = _round_sec(_seconds_from_samples(max(0, new_end - new_start)))
elif "start_sec" in item and "end_sec" in item:
start_sample = int(round(float(item["start_sec"]) * SAMPLE_RATE))
end_sample = int(round(float(item["end_sec"]) * SAMPLE_RATE))
new_start = _remap_sample(start_sample, removed_intervals)
new_end = _remap_sample(end_sample, removed_intervals)
if end_sample > start_sample and new_end <= new_start + 2:
new_end = new_start + 3
updated["start_sec"] = _round_sec(_seconds_from_samples(new_start))
updated["end_sec"] = _round_sec(_seconds_from_samples(new_end))
updated["duration_sec"] = _round_sec(_seconds_from_samples(max(0, new_end - new_start)))
remapped.append(updated)
return remapped
def _refresh_pause_after_ms(items: List[Dict[str, Any]]) -> None:
for index, item in enumerate(items):
if "pause_after_ms" not in item:
continue
if index == len(items) - 1:
item["pause_after_ms"] = 0
continue
current_end = int(item.get("end_sample", 0))
next_start = int(items[index + 1].get("start_sample", current_end))
pause_samples = max(0, next_start - current_end)
item["pause_after_ms"] = int(round((pause_samples / SAMPLE_RATE) * 1000.0))
def _apply_silence_trimming(
result: Dict[str, Any],
trim_options: SilenceTrimOptions,
) -> Dict[str, Any]:
processed = dict(result)
audio = np.asarray(result["audio"], dtype=np.float32)
raw_duration_sec = _round_sec(_seconds_from_samples(len(audio)))
if not trim_options.enabled:
processed["silence_processing"] = {
"enabled": False,
"threshold_db": trim_options.threshold_db,
"min_silence_sec": trim_options.min_silence_sec,
"keep_padding_sec": trim_options.keep_padding_sec,
"analysis_window_ms": SILENCE_ANALYSIS_WINDOW_MS,
"detected_runs": [],
"removed_runs": [],
"removed_silence_sec": 0.0,
"raw_duration_sec": raw_duration_sec,
"processed_duration_sec": raw_duration_sec,
}
return processed
silence_runs = _detect_silence_runs(audio, trim_options.threshold_db, trim_options.min_silence_sec)
removed_intervals = _build_trimmed_intervals(silence_runs, trim_options.keep_padding_sec)
if not removed_intervals:
processed["silence_processing"] = {
"enabled": True,
"threshold_db": trim_options.threshold_db,
"min_silence_sec": trim_options.min_silence_sec,
"keep_padding_sec": trim_options.keep_padding_sec,
"analysis_window_ms": SILENCE_ANALYSIS_WINDOW_MS,
"detected_runs": [
{
"start_sample": start_sample,
"end_sample": end_sample,
"start_sec": _round_sec(_seconds_from_samples(start_sample)),
"end_sec": _round_sec(_seconds_from_samples(end_sample)),
"duration_sec": _round_sec(_seconds_from_samples(end_sample - start_sample)),
}
for start_sample, end_sample in silence_runs
],
"removed_runs": [],
"removed_silence_sec": 0.0,
"raw_duration_sec": raw_duration_sec,
"processed_duration_sec": raw_duration_sec,
}
return processed
kept_chunks: List[np.ndarray] = []
cursor = 0
for start_sample, end_sample in removed_intervals:
if start_sample > cursor:
kept_chunks.append(audio[cursor:start_sample])
cursor = end_sample
if cursor < len(audio):
kept_chunks.append(audio[cursor:])
trimmed_audio = np.concatenate(kept_chunks) if kept_chunks else np.zeros(0, dtype=np.float32)
processed["audio"] = trimmed_audio
processed["segments"] = _remap_timed_items(result["segments"], removed_intervals)
processed["sentences"] = _remap_timed_items(result["sentences"], removed_intervals)
processed["words"] = _remap_timed_items(result["words"], removed_intervals)
processed["transcript"] = _remap_timed_items(result["transcript"], removed_intervals)
_refresh_pause_after_ms(processed["segments"])
_refresh_pause_after_ms(processed["sentences"])
processed["speech_duration_sec"] = _round_sec(
_seconds_from_samples(sum(max(0, item["end_sample"] - item["start_sample"]) for item in processed["segments"]))
)
processed["duration_sec"] = _round_sec(_seconds_from_samples(len(trimmed_audio)))
removed_total_samples = sum(end_sample - start_sample for start_sample, end_sample in removed_intervals)
processed["silence_processing"] = {
"enabled": True,
"threshold_db": trim_options.threshold_db,
"min_silence_sec": trim_options.min_silence_sec,
"keep_padding_sec": trim_options.keep_padding_sec,
"analysis_window_ms": SILENCE_ANALYSIS_WINDOW_MS,
"detected_runs": [
{
"start_sample": start_sample,
"end_sample": end_sample,
"start_sec": _round_sec(_seconds_from_samples(start_sample)),
"end_sec": _round_sec(_seconds_from_samples(end_sample)),
"duration_sec": _round_sec(_seconds_from_samples(end_sample - start_sample)),
}
for start_sample, end_sample in silence_runs
],
"removed_runs": [
{
"start_sample": start_sample,
"end_sample": end_sample,
"start_sec": _round_sec(_seconds_from_samples(start_sample)),
"end_sec": _round_sec(_seconds_from_samples(end_sample)),
"duration_sec": _round_sec(_seconds_from_samples(end_sample - start_sample)),
}
for start_sample, end_sample in removed_intervals
],
"removed_silence_sec": _round_sec(_seconds_from_samples(removed_total_samples)),
"raw_duration_sec": raw_duration_sec,
"processed_duration_sec": processed["duration_sec"],
}
processed["alignment"] = dict(processed["alignment"])
processed["alignment"]["notes"] = list(processed["alignment"].get("notes", [])) + [
"Silence trimming was applied to the synthesized waveform and all timestamps were remapped to the processed audio."
]
processed["alignment"]["silence_trimmed"] = True
return processed
def ensure_wav(audio_path: str, working_dir: str) -> Tuple[str, np.ndarray, bool]:
ext = os.path.splitext(audio_path)[1].lower()
audio = decode_audio(audio_path, sampling_rate=SAMPLE_RATE)
wav_path = os.path.join(working_dir, "input.wav")
sf.write(wav_path, audio, SAMPLE_RATE, subtype="PCM_16")
return wav_path, np.asarray(audio, dtype=np.float32), ext == ".mp3"
def trim_audio_only(audio: np.ndarray, trim_options: SilenceTrimOptions) -> Tuple[np.ndarray, Dict[str, Any], List[Tuple[int, int]]]:
raw_duration_sec = _round_sec(_seconds_from_samples(len(audio)))
if not trim_options.enabled:
silence_processing = {
"enabled": False,
"threshold_db": trim_options.threshold_db,
"min_silence_sec": trim_options.min_silence_sec,
"keep_padding_sec": trim_options.keep_padding_sec,
"analysis_window_ms": SILENCE_ANALYSIS_WINDOW_MS,
"detected_runs": [],
"removed_runs": [],
"removed_silence_sec": 0.0,
"raw_duration_sec": raw_duration_sec,
"processed_duration_sec": raw_duration_sec,
}
return audio, silence_processing, []
silence_runs = _detect_silence_runs(audio, trim_options.threshold_db, trim_options.min_silence_sec)
removed_intervals = _build_trimmed_intervals(silence_runs, trim_options.keep_padding_sec)
if not removed_intervals:
silence_processing = {
"enabled": True,
"threshold_db": trim_options.threshold_db,
"min_silence_sec": trim_options.min_silence_sec,
"keep_padding_sec": trim_options.keep_padding_sec,
"analysis_window_ms": SILENCE_ANALYSIS_WINDOW_MS,
"detected_runs": [
{
"start_sample": start_sample,
"end_sample": end_sample,
"start_sec": _round_sec(_seconds_from_samples(start_sample)),
"end_sec": _round_sec(_seconds_from_samples(end_sample)),
"duration_sec": _round_sec(_seconds_from_samples(end_sample - start_sample)),
}
for start_sample, end_sample in silence_runs
],
"removed_runs": [],
"removed_silence_sec": 0.0,
"raw_duration_sec": raw_duration_sec,
"processed_duration_sec": raw_duration_sec,
}
return audio, silence_processing, []
kept_chunks: List[np.ndarray] = []
cursor = 0
for start_sample, end_sample in removed_intervals:
if start_sample > cursor:
kept_chunks.append(audio[cursor:start_sample])
cursor = end_sample
if cursor < len(audio):
kept_chunks.append(audio[cursor:])
trimmed_audio = np.concatenate(kept_chunks) if kept_chunks else np.zeros(0, dtype=np.float32)
removed_total_samples = sum(end_sample - start_sample for start_sample, end_sample in removed_intervals)
silence_processing = {
"enabled": True,
"threshold_db": trim_options.threshold_db,
"min_silence_sec": trim_options.min_silence_sec,
"keep_padding_sec": trim_options.keep_padding_sec,
"analysis_window_ms": SILENCE_ANALYSIS_WINDOW_MS,
"detected_runs": [
{
"start_sample": start_sample,
"end_sample": end_sample,
"start_sec": _round_sec(_seconds_from_samples(start_sample)),
"end_sec": _round_sec(_seconds_from_samples(end_sample)),
"duration_sec": _round_sec(_seconds_from_samples(end_sample - start_sample)),
}
for start_sample, end_sample in silence_runs
],
"removed_runs": [
{
"start_sample": start_sample,
"end_sample": end_sample,
"start_sec": _round_sec(_seconds_from_samples(start_sample)),
"end_sec": _round_sec(_seconds_from_samples(end_sample)),
"duration_sec": _round_sec(_seconds_from_samples(end_sample - start_sample)),
}
for start_sample, end_sample in removed_intervals
],
"removed_silence_sec": _round_sec(_seconds_from_samples(removed_total_samples)),
"raw_duration_sec": raw_duration_sec,
"processed_duration_sec": _round_sec(_seconds_from_samples(len(trimmed_audio))),
}
return trimmed_audio, silence_processing, removed_intervals
def save_wav(audio: np.ndarray, wav_path: str) -> None:
sf.write(wav_path, np.asarray(audio, dtype=np.float32), SAMPLE_RATE, subtype="PCM_16")
def _build_json_speech_response(req_id: str, voice_id: str, result: Dict[str, Any]) -> Dict[str, Any]:
import time
response: Dict[str, Any] = {
"id": req_id,
"object": "audio.speech",
"created": int(time.time()),
"model": PUBLIC_MODEL_ID,
"voice": voice_id,
"language": result["language"],
"voice_language": result["voice_language"],
"language_source": result["language_source"],
"accent": result["voice"]["accent"],
"gender": result["voice"]["gender"],
"format": "wav",
"sample_rate": result["sample_rate"],
"char_count": result["char_count"],
"word_count": result["word_count"],
"duration_sec": result["duration_sec"],
"speech_duration_sec": result["speech_duration_sec"],
"leading_silence_ms": result["leading_silence_ms"],
"trailing_silence_ms": result["trailing_silence_ms"],
"style": result["style"],
"pause_bias": result["pause_bias"],
"sentence_break_strength": result["sentence_break_strength"],
"emphasis_words": result["emphasis_words"],
"segments": result["segments"],
"sentences": result["sentences"],
"words": result["words"],
"transcript": result["transcript"],
"alignment": result["alignment"],
}
if "silence_processing" in result:
response["silence_processing"] = result["silence_processing"]
return response