udayl commited on
Commit
61caafb
·
1 Parent(s): 299e4e9

fix: revert back to old version

Browse files
Files changed (2) hide show
  1. gradio_app.py +233 -207
  2. notebook_lm_kokoro.py +5 -87
gradio_app.py CHANGED
@@ -1,255 +1,281 @@
 
1
  import os
2
  import tempfile
3
- import shutil
4
- import ast
5
- import numpy as np
6
  import soundfile as sf
 
 
 
7
  import warnings
8
- import multiprocessing
9
- import concurrent.futures
10
- import urllib.request
11
- import pathlib
12
-
13
- try:
14
- from moshi.models.tts import TTSModel
15
- except ImportError:
16
- print("Moshi TTSModel not available — install Kyutai’s version via pip.")
17
- TTSModel = None
18
-
19
- from notebook_lm_kokoro import (
20
- generate_podcast_script,
21
- generate_audio_from_script,
22
- generate_audio_kyutai,
23
- KPipeline,
24
- )
25
-
26
- import sys
27
-
28
- # Diagnostic: where is ~/.cache pointing?
29
- print(f"[DEBUG] HOME = {os.environ.get('HOME')}")
30
- print(f"[DEBUG] XDG_CACHE_HOME = {os.environ.get('XDG_CACHE_HOME')}")
31
- print(f"[DEBUG] Trying to create /.cache/test.txt")
32
-
33
- try:
34
- os.makedirs("/.cache", exist_ok=True)
35
- with open("/.cache/test.txt", "w") as f:
36
- f.write("test")
37
- print("[DEBUG] Successfully wrote to /.cache")
38
- except Exception as e:
39
- print(f"[DEBUG] ❌ Failed to write to /.cache: {e}")
40
-
41
- # Set cache dirs BEFORE importing torch, transformers, or moshi
42
- os.environ["HF_HOME"] = "/tmp/huggingface"
43
- os.environ["TRANSFORMERS_CACHE"] = "/tmp/huggingface/transformers"
44
- os.environ["XDG_CACHE_HOME"] = "/tmp/huggingface"
45
- os.environ["TORCH_HOME"] = "/tmp/torch"
46
- os.environ["MOSHI_CACHE_DIR"] = "/tmp/moshi"
47
-
48
- # Explicitly override ~/.cache
49
- os.environ["HOME"] = "/tmp/home"
50
- os.makedirs("/tmp/home", exist_ok=True)
51
-
52
- for path in [
53
- "/tmp/.cache",
54
- "/tmp/huggingface",
55
- "/tmp/huggingface/transformers",
56
- "/tmp/torch",
57
- "/tmp/moshi",
58
- ]:
59
- os.makedirs(path, exist_ok=True)
60
-
61
- if not os.path.exists("/.cache"):
62
- try:
63
- os.symlink("/tmp/.cache", "/.cache")
64
- print("[DEBUG] Symlinked /.cache to /tmp/.cache")
65
- except Exception as e:
66
- print(f"[DEBUG] Couldn't symlink /.cache: {e}")
67
-
68
  import gradio as gr
69
-
 
 
70
  warnings.filterwarnings("ignore")
71
- NUM_WORKERS = multiprocessing.cpu_count()
72
 
73
- def ensure_gradio_frpc():
74
- """
75
- Ensures the frpc binary is present in the location Gradio expects.
76
- Avoids /.cache symlinks (which are not writable in HF Spaces).
77
- """
78
- gradio_temp_dir = os.environ.get("GRADIO_TEMP_DIR", "/tmp/gradio")
79
- target_dir = os.path.join(gradio_temp_dir, "frpc")
80
- os.makedirs(target_dir, exist_ok=True)
81
-
82
- frpc_file = os.path.join(target_dir, "frpc_linux_amd64_v0.3")
83
-
84
- if not os.path.exists(frpc_file):
85
- print(f"[INFO] Downloading frpc binary to: {frpc_file}")
86
- try:
87
- url = "https://cdn-media.huggingface.co/frpc-gradio-0.3/frpc_linux_amd64"
88
- urllib.request.urlretrieve(url, frpc_file)
89
- os.chmod(frpc_file, 0o755) # Make it executable
90
- print("[SUCCESS] frpc binary downloaded and made executable.")
91
- except Exception as e:
92
- print(f"[ERROR] Failed to download frpc binary: {e}")
93
- else:
94
- print("[INFO] frpc binary already exists at expected path.")
95
 
96
  def process_segment(entry_and_voice_map):
97
- entry, voice_map = entry_and_voice_map
98
  speaker, dialogue = entry
99
  chosen_voice = voice_map.get(speaker, "af_heart")
 
 
100
  pipeline = KPipeline(lang_code="a", repo_id="hexgrad/Kokoro-82M")
101
  generator = pipeline(dialogue, voice=chosen_voice)
102
- return np.concatenate([audio for _, _, audio in generator], axis=0) if generator else None
 
 
 
 
 
 
 
103
 
104
  def generate_audio_from_script_with_voices(script, speaker1_voice, speaker2_voice, output_file):
105
- print("[DEBUG] Raw transcript string:")
106
- print(script)
107
-
108
  voice_map = {"Speaker 1": speaker1_voice, "Speaker 2": speaker2_voice}
 
 
 
 
 
 
 
109
  try:
110
  transcript_list = ast.literal_eval(script)
111
  if not isinstance(transcript_list, list):
112
  raise ValueError("Transcript is not a list")
113
 
114
- results = []
115
- for entry in transcript_list:
116
- audio = process_segment((entry, voice_map))
117
- if audio is not None:
118
- results.append(audio)
119
- if not results:
 
 
 
 
 
 
 
 
 
 
 
 
 
120
  return None
 
 
121
  sample_rate = 24000
122
  pause = np.zeros(sample_rate, dtype=np.float32)
123
- final_audio = results[0]
124
- for seg in results[1:]:
125
  final_audio = np.concatenate((final_audio, pause, seg), axis=0)
 
126
  sf.write(output_file, final_audio, sample_rate)
 
127
  return output_file
 
128
  except Exception as e:
129
- print(f"Transcript parse error: {e}")
130
  return None
131
 
132
- def process_pdf(pdf_file, speaker1_voice, speaker2_voice, kyutai_voice1, kyutai_voice2,
133
- provider, openai_key=None, openrouter_key=None, openrouter_base=None, tts_engine=None):
134
- try:
135
- if provider == "openai" and not openai_key:
136
- return "OpenAI API key is required", None
137
- if provider == "openrouter" and not openrouter_key:
138
- return "OpenRouter API key is required", None
139
 
140
- if provider in ["openai", "kyutai"]:
141
- os.environ["OPENAI_API_KEY"] = openai_key or ""
 
 
 
 
 
142
  os.environ["OPENROUTER_API_BASE"] = "https://api.openai.com/v1"
143
- if provider in ["openrouter", "kyutai"]:
144
- os.environ["OPENAI_API_KEY"] = openrouter_key or ""
145
  os.environ["OPENROUTER_API_BASE"] = openrouter_base or "https://openrouter.ai/api/v1"
146
-
147
  if pdf_file is None:
148
  return "No file uploaded", None
149
-
150
- tmp_path = pdf_file.name
151
-
152
- script_provider = "openrouter" if provider == "kyutai" and openrouter_key else provider
153
- transcript, _ = generate_podcast_script(pdf_file.name, provider=script_provider)
154
-
 
 
 
 
 
155
  if transcript is None:
156
- return "Transcript generation failed: got None", None
157
- if not transcript.strip().startswith("["):
158
- return f"Malformed transcript:\n{transcript}", None
159
-
160
- audio_path = os.path.join(os.path.dirname(tmp_path), f"audio_{os.path.basename(tmp_path).replace('.pdf', '.wav')}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
161
 
162
- if tts_engine == "kyutai":
163
- result = generate_audio_kyutai(transcript, kyutai_voice1, kyutai_voice2, audio_path)
164
- else:
165
- result = generate_audio_from_script_with_voices(transcript, speaker1_voice, speaker2_voice, audio_path)
 
 
 
 
166
 
167
- return ("Process complete!", result) if result else ("Error generating audio", None)
168
  except Exception as e:
169
- print(f"process_pdf error: {e}")
170
- return f"Error: {e}", None
171
-
172
- def update_ui(provider, tts_engine):
173
- return [
174
- gr.update(visible=tts_engine == "kokoro"),
175
- gr.update(visible=tts_engine == "kokoro"),
176
- gr.update(visible=tts_engine == "kyutai"),
177
- gr.update(visible=tts_engine == "kyutai"),
178
- gr.update(visible=provider in ["openai", "kyutai"]),
179
- gr.update(visible=provider in ["openrouter", "kyutai"]),
180
- gr.update(visible=provider == "openrouter"),
181
- ]
182
 
183
  def create_gradio_app():
184
- css = ".gradio-container {max-width: 900px !important}"
 
 
 
 
185
  with gr.Blocks(css=css, theme=gr.themes.Soft()) as app:
186
- gr.Markdown("# 🎧 PDF to Podcast — NotebookLM + Kokoro/Kyutai")
187
-
 
 
 
 
 
188
  with gr.Row():
189
- with gr.Column(scale=1.5):
190
- pdf_input = gr.File(file_types=[".pdf"], type="filepath", label="📄 Upload your PDF")
191
- provider = gr.Radio(["openai", "openrouter"], value="openrouter", label="🧠 API Provider")
192
- tts_engine = gr.Radio(["kokoro", "kyutai"], value="kokoro", label="🎤 TTS Engine")
193
-
194
- speaker1_voice = gr.Dropdown(["af_heart","af_bella","hf_beta"], value="af_heart", label="Speaker 1 Voice", visible=True)
195
- speaker2_voice = gr.Dropdown(["af_nicole","af_heart","bf_emma"], value="bf_emma", label="Speaker 2 Voice", visible=True)
196
- kyutai_voice1 = gr.Dropdown(
197
- [
198
- "expresso/ex03-ex01_happy_001_channel1_334s.wav",
199
- "expresso/ex03-ex02_narration_001_channel1_674s.wav",
200
- "vctk/p226_023_mic1.wav"
201
- ],
202
- value="expresso/ex03-ex01_happy_001_channel1_334s.wav",
203
- label="Kyutai Voice 1",
204
- visible=True
205
  )
206
-
207
- kyutai_voice2 = gr.Dropdown(
208
- [
209
- "expresso/ex03-ex01_happy_001_channel1_334s.wav",
210
- "expresso/ex03-ex02_narration_001_channel1_674s.wav",
211
- "vctk/p225_023_mic1.wav"
212
- ],
213
- value="expresso/ex03-ex02_narration_001_channel1_674s.wav",
214
- label="Kyutai Voice 2",
215
- visible=True
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
216
  )
217
-
218
- with gr.Accordion("🔐 API Keys", open=True):
219
- openai_key = gr.Textbox(type="password", label="OpenAI Key", show_label=True, visible=True)
220
- openrouter_key = gr.Textbox(type="password", label="OpenRouter Key", show_label=True, visible=True)
221
- openrouter_base = gr.Textbox(placeholder="https://openrouter.ai/api/v1", label="OpenRouter Base URL", visible=True)
222
-
223
- submit_btn = gr.Button("🎙️ Generate Podcast", variant="primary")
224
-
225
- with gr.Column(scale=1):
226
- status_output = gr.Textbox(label="📝 Status", interactive=False)
227
- audio_output = gr.Audio(type="filepath", label="🎵 Your Podcast")
228
-
229
- submit_btn.click(
230
- process_pdf,
231
- inputs=[pdf_input, speaker1_voice, speaker2_voice, kyutai_voice1, kyutai_voice2,
232
- provider, openai_key, openrouter_key, openrouter_base, tts_engine],
233
- outputs=[status_output, audio_output]
234
- )
235
-
236
- provider.change(update_ui, [provider, tts_engine],
237
- [speaker1_voice, speaker2_voice, kyutai_voice1, kyutai_voice2,
238
- openai_key, openrouter_key, openrouter_base])
239
- tts_engine.change(update_ui, [provider, tts_engine],
240
- [speaker1_voice, speaker2_voice, kyutai_voice1, kyutai_voice2,
241
- openai_key, openrouter_key, openrouter_base])
242
-
243
- gr.Markdown("""
244
- **📌 Tips**
245
- - Pick your API provider and then set appropriate keys.
246
- - Choose **TTS Engine** (Kokoro/Kyutai) to reveal relevant voice options.
247
- - Works well with clean, structured PDFs.
248
- """)
249
-
 
 
 
 
 
 
250
  return app
251
 
252
-
253
- ensure_gradio_frpc()
254
  if __name__ == "__main__":
255
- create_gradio_app().queue().launch(server_name="0.0.0.0", server_port=7860, share=True, debug=True, pwa=True)
 
 
 
 
 
 
 
 
1
+ # filepath: /Users/udaylunawat/Downloads/Data-Science-Projects/NotebookLM_clone/gradio_app.py
2
  import os
3
  import tempfile
4
+ import gradio as gr
5
+ from notebook_lm_kokoro import generate_podcast_script, KPipeline
 
6
  import soundfile as sf
7
+ import numpy as np
8
+ import ast
9
+ import shutil
10
  import warnings
11
+ import os
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12
  import gradio as gr
13
+ import concurrent.futures
14
+ import multiprocessing
15
+ from notebook_lm_kokoro import generate_podcast_script, generate_audio_from_script
16
  warnings.filterwarnings("ignore")
 
17
 
18
+ # Define number of workers based on CPU cores
19
+ NUM_WORKERS = multiprocessing.cpu_count() # Gets total CPU cores
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
 
21
  def process_segment(entry_and_voice_map):
22
+ entry, voice_map = entry_and_voice_map # Unpack the tuple
23
  speaker, dialogue = entry
24
  chosen_voice = voice_map.get(speaker, "af_heart")
25
+ print(f"Generating audio for {speaker} with voice '{chosen_voice}'...")
26
+
27
  pipeline = KPipeline(lang_code="a", repo_id="hexgrad/Kokoro-82M")
28
  generator = pipeline(dialogue, voice=chosen_voice)
29
+
30
+ segment_audio = []
31
+ for _, _, audio in generator:
32
+ segment_audio.append(audio)
33
+
34
+ if segment_audio:
35
+ return np.concatenate(segment_audio, axis=0)
36
+ return None
37
 
38
  def generate_audio_from_script_with_voices(script, speaker1_voice, speaker2_voice, output_file):
 
 
 
39
  voice_map = {"Speaker 1": speaker1_voice, "Speaker 2": speaker2_voice}
40
+
41
+ # Clean up the script string if needed
42
+ script = script.strip()
43
+ if not script.startswith("[") or not script.endswith("]"):
44
+ print("Invalid transcript format. Expected a list of tuples.")
45
+ return None
46
+
47
  try:
48
  transcript_list = ast.literal_eval(script)
49
  if not isinstance(transcript_list, list):
50
  raise ValueError("Transcript is not a list")
51
 
52
+ all_audio_segments = []
53
+ # Prepare input data with voice_map for each entry
54
+ entries_with_voice_map = [(entry, voice_map) for entry in transcript_list]
55
+
56
+ try:
57
+ # Process segments in parallel
58
+ with concurrent.futures.ProcessPoolExecutor(max_workers=NUM_WORKERS) as executor:
59
+ # Map the processing function across all dialogue entries
60
+ results = list(executor.map(process_segment, entries_with_voice_map))
61
+
62
+ # Filter out None results and combine audio segments
63
+ all_audio_segments = [r for r in results if r is not None]
64
+
65
+ except Exception as e:
66
+ print(f"Error during audio generation: {e}")
67
+ return None
68
+
69
+ if not all_audio_segments:
70
+ print("No audio segments were generated")
71
  return None
72
+
73
+ # Add a pause between segments
74
  sample_rate = 24000
75
  pause = np.zeros(sample_rate, dtype=np.float32)
76
+ final_audio = all_audio_segments[0]
77
+ for seg in all_audio_segments[1:]:
78
  final_audio = np.concatenate((final_audio, pause, seg), axis=0)
79
+
80
  sf.write(output_file, final_audio, sample_rate)
81
+ print(f"Saved final audio as {output_file}")
82
  return output_file
83
+
84
  except Exception as e:
85
+ print(f"Error processing transcript: {e}")
86
  return None
87
 
 
 
 
 
 
 
 
88
 
89
+ def process_pdf(pdf_file, speaker1_voice, speaker2_voice, provider, api_key, openrouter_base=None):
90
+ """Process the uploaded PDF file and generate audio"""
91
+ try:
92
+
93
+ # Set API configuration based on provider
94
+ if provider == "openai":
95
+ os.environ["OPENAI_API_KEY"] = api_key
96
  os.environ["OPENROUTER_API_BASE"] = "https://api.openai.com/v1"
97
+ else:
98
+ os.environ["OPENAI_API_KEY"] = api_key
99
  os.environ["OPENROUTER_API_BASE"] = openrouter_base or "https://openrouter.ai/api/v1"
100
+ # Check if we received a valid file
101
  if pdf_file is None:
102
  return "No file uploaded", None
103
+
104
+ # Create a temporary file with .pdf extension
105
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as tmp:
106
+ # For Gradio uploads, we need to copy the file
107
+ shutil.copy2(pdf_file.name, tmp.name)
108
+ tmp_path = tmp.name
109
+
110
+ print(f"Uploaded PDF saved at {tmp_path}")
111
+
112
+ # Generate transcript using your existing function
113
+ transcript, transcript_path = generate_podcast_script(tmp_path, provider=provider)
114
  if transcript is None:
115
+ return "Error generating transcript", None
116
+
117
+ # Define an output file path for the generated audio
118
+ audio_output_path = os.path.join(
119
+ os.path.dirname(tmp_path),
120
+ f"audio_{os.path.basename(tmp_path).replace('.pdf', '.wav')}"
121
+ )
122
+
123
+ # result = generate_audio_from_script_with_voices(
124
+ # transcript,
125
+ # speaker1_voice,
126
+ # speaker2_voice,
127
+ # output_file=audio_output_path
128
+ # )
129
+
130
+ # Use ProcessPoolExecutor with explicit number of workers
131
+ with concurrent.futures.ProcessPoolExecutor(max_workers=NUM_WORKERS) as executor:
132
+ print(f"Processing with {NUM_WORKERS} CPU cores")
133
+ # Submit audio generation task to the executor
134
+ future = executor.submit(
135
+ generate_audio_from_script_with_voices,
136
+ transcript, speaker1_voice, speaker2_voice, audio_output_path
137
+ )
138
+ result = future.result()
139
+
140
+ if result is None:
141
+ return "Error generating audio", None
142
+
143
+ return "Process complete!", result
144
 
145
+ except Exception as e:
146
+ print(f"Error in process_pdf: {str(e)}")
147
+ return f"Error processing file: {str(e)}", None
148
+
149
+ if result is None:
150
+ return "Error generating audio", None
151
+
152
+ return "Process complete!", result
153
 
 
154
  except Exception as e:
155
+ print(f"Error in process_pdf: {str(e)}")
156
+ return f"Error processing file: {str(e)}", None
157
+
 
 
 
 
 
 
 
 
 
 
158
 
159
  def create_gradio_app():
160
+ # Add CSS for better styling
161
+ css = """
162
+ .gradio-container {max-width: 900px !important}
163
+ """
164
+
165
  with gr.Blocks(css=css, theme=gr.themes.Soft()) as app:
166
+ gr.Markdown(
167
+ """
168
+ # 📚 NotebookLM-Kokoro TTS App
169
+ Upload a PDF, choose voices, and generate conversational audio using Kokoro TTS.
170
+ """
171
+ )
172
+
173
  with gr.Row():
174
+ with gr.Column(scale=2):
175
+ pdf_input = gr.File(
176
+ label="Upload PDF Document",
177
+ file_types=[".pdf"],
178
+ type="filepath"
 
 
 
 
 
 
 
 
 
 
 
179
  )
180
+
181
+ with gr.Row():
182
+ speaker1_voice = gr.Dropdown(
183
+ choices=["af_heart", "af_bella", "hf_beta"],
184
+ value="af_heart",
185
+ label="Speaker 1 Voice"
186
+ )
187
+ speaker2_voice = gr.Dropdown(
188
+ choices=["af_nicole", "af_heart", "bf_emma"],
189
+ value="bf_emma",
190
+ label="Speaker 2 Voice"
191
+ )
192
+
193
+
194
+ with gr.Group():
195
+ provider = gr.Radio(
196
+ choices=["openai", "openrouter"],
197
+ value="openrouter",
198
+ label="API Provider"
199
+ )
200
+
201
+ api_key = gr.Textbox(
202
+ label="API Key",
203
+ placeholder="Enter your API key here...",
204
+ type="password",
205
+ elem_classes="api-input"
206
+ )
207
+
208
+ openrouter_base = gr.Textbox(
209
+ label="OpenRouter Base URL (optional)",
210
+ placeholder="https://openrouter.ai/api/v1",
211
+ visible=False,
212
+ elem_classes="api-input"
213
+ )
214
+
215
+ # Show/hide OpenRouter base URL based on provider selection
216
+ def toggle_openrouter_base(provider_choice):
217
+ return gr.update(visible=provider_choice == "openrouter")
218
+
219
+ provider.change(
220
+ fn=toggle_openrouter_base,
221
+ inputs=[provider],
222
+ outputs=[openrouter_base]
223
+ )
224
+
225
+ submit_btn = gr.Button("🎙️ Generate Audio", variant="primary")
226
+
227
+ with gr.Column(scale=2):
228
+ status_output = gr.Textbox(
229
+ label="Status",
230
+ placeholder="Processing status will appear here..."
231
  )
232
+ audio_output = gr.Audio(
233
+ label="Generated Audio",
234
+ type="filepath"
235
+ )
236
+
237
+ # # Examples section
238
+ # gr.Examples(
239
+ # examples=[
240
+ # ["sample.pdf", "af_heart", "af_nicole", "openrouter", "your-api-key-here", "https://openrouter.ai/api/v1"],
241
+ # ],
242
+ # inputs=[pdf_input, speaker1_voice, speaker2_voice, provider, api_key, openrouter_base],
243
+ # outputs=[status_output, audio_output],
244
+ # fn=process_pdf,
245
+ # cache_examples=True,
246
+ # )
247
+
248
+ submit_btn.click(
249
+ fn=process_pdf,
250
+ inputs=[
251
+ pdf_input,
252
+ speaker1_voice,
253
+ speaker2_voice,
254
+ provider,
255
+ api_key,
256
+ openrouter_base
257
+ ],
258
+ outputs=[status_output, audio_output],
259
+ api_name="generate"
260
+ )
261
+
262
+ gr.Markdown(
263
+ """
264
+ ### 📝 Notes
265
+ - Make sure your PDF is readable and contains text (not scanned images)
266
+ - Processing large PDFs may take a few minutes
267
+ - You need a valid OpenAI/OpenRouter API key set as environment variable
268
+ """
269
+ )
270
+
271
  return app
272
 
 
 
273
  if __name__ == "__main__":
274
+ demo = create_gradio_app()
275
+ demo.queue().launch(
276
+ server_name="0.0.0.0",
277
+ server_port=7860,
278
+ share=True,
279
+ debug=True,
280
+ pwa=True
281
+ )
notebook_lm_kokoro.py CHANGED
@@ -23,14 +23,6 @@ import asyncio
23
  import ast
24
  import json
25
  import warnings
26
- import torch
27
- import time
28
- try:
29
- from moshi.models.loaders import CheckpointInfo
30
- from moshi.models.tts import DEFAULT_DSM_TTS_REPO, DEFAULT_DSM_TTS_VOICE_REPO, TTSModel
31
- except ImportError:
32
- CheckpointInfo = None
33
- TTSModel = None
34
  warnings.filterwarnings("ignore")
35
 
36
  # Set your OpenAI (or OpenRouter) API key from the environment
@@ -38,17 +30,6 @@ openai.api_key = os.getenv("OPENAI_API_KEY")
38
  # For OpenRouter compatibility, set the API base if provided.
39
  openai.api_base = os.getenv("OPENROUTER_API_BASE", "https://api.openai.com/v1")
40
 
41
- # Set cache dirs BEFORE importing torch, transformers, or moshi
42
- os.environ["HF_HOME"] = "/tmp/huggingface"
43
- os.environ["TRANSFORMERS_CACHE"] = "/tmp/huggingface/transformers"
44
- os.environ["XDG_CACHE_HOME"] = "/tmp/huggingface"
45
- os.environ["TORCH_HOME"] = "/tmp/torch"
46
- os.environ["MOSHI_CACHE_DIR"] = "/tmp/moshi"
47
-
48
- # Explicitly override ~/.cache
49
- os.environ["HOME"] = "/tmp/home"
50
- os.makedirs("/tmp/home", exist_ok=True)
51
-
52
  pdf = "1706.03762v7.pdf"
53
 
54
 
@@ -173,8 +154,7 @@ def generate_audio_from_script(script, output_file="podcast_audio.wav"):
173
  chosen_voice = voice_map.get(speaker, "af_heart")
174
  print(f"Generating audio for {speaker} with voice '{chosen_voice}'...")
175
 
176
- # Updated KPipeline initialization with explicit repo_id
177
- pipeline = KPipeline(lang_code="a", repo_id="hexgrad/Kokoro-82M")
178
  generator = pipeline(dialogue, voice=chosen_voice)
179
 
180
  segment_audio = []
@@ -206,67 +186,6 @@ def generate_audio_from_script(script, output_file="podcast_audio.wav"):
206
  print(f"Error processing transcript: {e}")
207
  return
208
 
209
- def generate_audio_kyutai(script, speaker1_voice=None, speaker2_voice=None, output_file="kyutai_audio.wav"):
210
- if TTSModel is None:
211
- print("Moshi is not installed.")
212
- return None
213
-
214
- try:
215
- print(f"[INFO] Requested Kyutai voices: {speaker1_voice=}, {speaker2_voice=}")
216
- # Reject absolute/local paths
217
- if os.path.isabs(speaker1_voice) or os.path.isfile(speaker1_voice):
218
- raise ValueError(f"❌ Invalid voice path for speaker1: {speaker1_voice}")
219
- if os.path.isabs(speaker2_voice) or os.path.isfile(speaker2_voice):
220
- raise ValueError(f"❌ Invalid voice path for speaker2: {speaker2_voice}")
221
-
222
- transcript_list = ast.literal_eval(script)
223
-
224
- # Load TTS model
225
- checkpoint_info = CheckpointInfo.from_hf_repo(DEFAULT_DSM_TTS_REPO)
226
- tts_model = TTSModel.from_checkpoint_info(
227
- checkpoint_info,
228
- n_q=32,
229
- temp=0.6,
230
- device=torch.device("cuda" if torch.cuda.is_available() else "cpu")
231
- )
232
-
233
- # Use voice names directly from dropdown
234
- print("[INFO] Resolving voice paths...")
235
-
236
- start = time.time()
237
- voice1_path = tts_model.get_voice_path(speaker1_voice)
238
- print(f"[INFO] Got voice1_path in {time.time() - start:.2f}s")
239
-
240
- start = time.time()
241
- voice2_path = tts_model.get_voice_path(speaker2_voice)
242
- print(f"[INFO] Got voice2_path in {time.time() - start:.2f}s")
243
-
244
- texts = [dialogue for _, dialogue in transcript_list]
245
- entries = tts_model.prepare_script(texts, padding_between=1)
246
-
247
- condition_attributes = tts_model.make_condition_attributes([voice1_path, voice2_path], cfg_coef=2.0)
248
-
249
- pcms = []
250
- def _on_frame(frame):
251
- if (frame != -1).all():
252
- pcm = tts_model.mimi.decode(frame[:, 1:, :]).cpu().numpy()
253
- pcms.append(np.clip(pcm[0, 0], -1, 1))
254
-
255
- with tts_model.mimi.streaming(1):
256
- tts_model.generate([entries], [condition_attributes], on_frame=_on_frame)
257
-
258
- if pcms:
259
- audio = np.concatenate(pcms, axis=-1)
260
- sf.write(output_file, audio, tts_model.mimi.sample_rate)
261
- print(f"[SUCCESS] Audio saved to: {output_file}")
262
- return output_file
263
-
264
- print("[WARNING] No audio segments were produced.")
265
- return None
266
-
267
- except Exception as e:
268
- print(f"[ERROR] Kyutai TTS error: {e}")
269
- return None
270
 
271
  def generate_tts():
272
  pipeline = KPipeline(lang_code="a")
@@ -303,16 +222,15 @@ def generate_podcast_script(
303
  Set provider="openrouter" to use OpenRouter, otherwise uses OpenAI.
304
  """
305
  pdf_basename = os.path.splitext(os.path.basename(pdf_path))[0]
306
- folder = os.path.join("/tmp", pdf_basename)
307
  os.makedirs(folder, exist_ok=True)
308
 
309
  destination_pdf = os.path.join(folder, os.path.basename(pdf_path))
310
- try:
311
  shutil.copy(pdf_path, destination_pdf)
312
  print(f"Copied {pdf_path} to {destination_pdf}")
313
- except PermissionError:
314
- print(f"[WARNING] Cannot copy PDF to {destination_pdf}, using original path.")
315
- destination_pdf = pdf_path # fallback
316
 
317
  transcript_path = os.path.join(folder, output_file)
318
  # If transcript exists, load and return it without calling the API.
 
23
  import ast
24
  import json
25
  import warnings
 
 
 
 
 
 
 
 
26
  warnings.filterwarnings("ignore")
27
 
28
  # Set your OpenAI (or OpenRouter) API key from the environment
 
30
  # For OpenRouter compatibility, set the API base if provided.
31
  openai.api_base = os.getenv("OPENROUTER_API_BASE", "https://api.openai.com/v1")
32
 
 
 
 
 
 
 
 
 
 
 
 
33
  pdf = "1706.03762v7.pdf"
34
 
35
 
 
154
  chosen_voice = voice_map.get(speaker, "af_heart")
155
  print(f"Generating audio for {speaker} with voice '{chosen_voice}'...")
156
 
157
+ pipeline = KPipeline(lang_code="a")
 
158
  generator = pipeline(dialogue, voice=chosen_voice)
159
 
160
  segment_audio = []
 
186
  print(f"Error processing transcript: {e}")
187
  return
188
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
189
 
190
  def generate_tts():
191
  pipeline = KPipeline(lang_code="a")
 
222
  Set provider="openrouter" to use OpenRouter, otherwise uses OpenAI.
223
  """
224
  pdf_basename = os.path.splitext(os.path.basename(pdf_path))[0]
225
+ folder = os.path.join(os.getcwd(), pdf_basename)
226
  os.makedirs(folder, exist_ok=True)
227
 
228
  destination_pdf = os.path.join(folder, os.path.basename(pdf_path))
229
+ if not os.path.exists(destination_pdf):
230
  shutil.copy(pdf_path, destination_pdf)
231
  print(f"Copied {pdf_path} to {destination_pdf}")
232
+ else:
233
+ print(f"PDF already copied at {destination_pdf}")
 
234
 
235
  transcript_path = os.path.join(folder, output_file)
236
  # If transcript exists, load and return it without calling the API.