gitmodelmujtaba commited on
Commit
441a757
·
verified ·
1 Parent(s): 54a2f26

Upload narrator.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. narrator.py +132 -0
narrator.py ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ narrator.py
4
+ -----------
5
+ Turnkey documentary voiceover generator for Kokoro Grounded Documentary.
6
+ Can be imported directly into any Python project or run via CLI.
7
+ """
8
+
9
+ import os
10
+ import subprocess
11
+ from pathlib import Path
12
+ from typing import Optional, Union
13
+ import numpy as np
14
+ import soundfile as sf
15
+ from kokoro_onnx import Kokoro
16
+
17
+ try:
18
+ from huggingface_hub import hf_hub_download
19
+ except ImportError:
20
+ hf_hub_download = None
21
+
22
+ DEFAULT_BROADCAST_FILTER = (
23
+ "highpass=f=80,"
24
+ "equalizer=f=160:t=q:w=1.0:g=2.8,"
25
+ "equalizer=f=260:t=q:w=1.2:g=2.0,"
26
+ "equalizer=f=450:t=q:w=2.0:g=-2.0,"
27
+ "equalizer=f=3200:t=q:w=2.0:g=-1.6,"
28
+ "equalizer=f=5800:t=q:w=2.5:g=-3.5,"
29
+ "equalizer=f=7200:t=q:w=2.5:g=-3.0,"
30
+ "lowpass=f=11000,"
31
+ "deesser=i=0.45:m=0.5:f=0.55:s=o,"
32
+ "compand=attacks=0.03:decays=0.3:points=-80/-80|-35/-25|-16/-13|0/-3,"
33
+ "loudnorm=I=-16:TP=-1.5:LRA=8.5"
34
+ )
35
+
36
+
37
+ class GroundedNarrator:
38
+ """
39
+ Broadcast-grade documentary narrator using Kokoro-ONNX and the Grounded Documentary profile.
40
+ """
41
+
42
+ def __init__(
43
+ self,
44
+ model_path: Optional[Union[str, Path]] = None,
45
+ voices_path: Optional[Union[str, Path]] = None,
46
+ profile_path: Optional[Union[str, Path]] = None,
47
+ repo_id: Optional[str] = None
48
+ ):
49
+ base_dir = Path(__file__).resolve().parent
50
+
51
+ if model_path is None:
52
+ local_model = base_dir / "kokoro-v1.0.onnx"
53
+ if local_model.exists():
54
+ model_path = local_model
55
+ elif repo_id and hf_hub_download:
56
+ model_path = hf_hub_download(repo_id=repo_id, filename="kokoro-v1.0.onnx")
57
+ else:
58
+ raise FileNotFoundError("kokoro-v1.0.onnx not found. Provide model_path or repo_id.")
59
+
60
+ if voices_path is None:
61
+ local_voices = base_dir / "voices-v1.0.bin"
62
+ if local_voices.exists():
63
+ voices_path = local_voices
64
+ elif repo_id and hf_hub_download:
65
+ voices_path = hf_hub_download(repo_id=repo_id, filename="voices-v1.0.bin")
66
+ else:
67
+ raise FileNotFoundError("voices-v1.0.bin not found. Provide voices_path or repo_id.")
68
+
69
+ if profile_path is None:
70
+ local_prof = base_dir / "grounded_documentary.npy"
71
+ if local_prof.exists():
72
+ profile_path = local_prof
73
+ elif repo_id and hf_hub_download:
74
+ profile_path = hf_hub_download(repo_id=repo_id, filename="grounded_documentary.npy")
75
+ else:
76
+ raise FileNotFoundError("grounded_documentary.npy not found.")
77
+
78
+ self.kokoro = Kokoro(str(model_path), str(voices_path))
79
+ self.voice_style = np.load(str(profile_path))
80
+
81
+ def synthesize(
82
+ self,
83
+ text: str,
84
+ output_path: Union[str, Path],
85
+ speed: float = 0.92,
86
+ sentence_pause: float = 0.42,
87
+ clause_pause: float = 0.20,
88
+ apply_mastering: bool = True
89
+ ) -> float:
90
+ """
91
+ Synthesizes text to WAV/MP3 with deliberate pacing and broadcast mastering.
92
+ """
93
+ out_p = Path(output_path)
94
+ out_p.parent.mkdir(parents=True, exist_ok=True)
95
+ wav_path = out_p.with_suffix(".wav")
96
+
97
+ audio, sr = self.kokoro.create(
98
+ text=text,
99
+ voice=self.voice_style,
100
+ speed=speed,
101
+ lang="en-gb",
102
+ sentence_pause=sentence_pause,
103
+ clause_pause=clause_pause,
104
+ continuous=False
105
+ )
106
+
107
+ sf.write(str(wav_path), audio, sr)
108
+ dur = len(audio) / sr
109
+
110
+ if out_p.suffix.lower() == ".mp3" or apply_mastering:
111
+ mp3_path = out_p.with_suffix(".mp3")
112
+ cmd = ["ffmpeg", "-y", "-i", str(wav_path)]
113
+ if apply_mastering:
114
+ cmd.extend(["-af", DEFAULT_BROADCAST_FILTER])
115
+ cmd.extend(["-c:a", "libmp3lame", "-b:a", "192k", str(mp3_path)])
116
+ subprocess.run(cmd, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
117
+ if out_p.suffix.lower() == ".mp3" and wav_path != out_p:
118
+ wav_path.unlink(missing_ok=True)
119
+
120
+ return dur
121
+
122
+
123
+ if __name__ == "__main__":
124
+ import argparse
125
+ parser = argparse.ArgumentParser(description="Generate broadcast documentary narration")
126
+ parser.add_argument("text", type=str, help="Text to speak")
127
+ parser.add_argument("-o", "--output", type=str, default="narration.mp3", help="Output path (.mp3 or .wav)")
128
+ args = parser.parse_args()
129
+
130
+ narrator = GroundedNarrator()
131
+ dur = narrator.synthesize(args.text, args.output)
132
+ print(f"Generated {dur:.2f}s of mastered voiceover -> {args.output}")