NeuralFalcon commited on
Commit
a60d441
·
verified ·
1 Parent(s): 49e2f1f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +308 -24
app.py CHANGED
@@ -56,7 +56,7 @@ def update_pipeline(Language):
56
  try:
57
  pipeline = KPipeline(lang_code=new_lang)
58
  last_used_language = new_lang # Update last used language
59
- print(f"Pipeline updated to {Language} ({new_lang})")
60
  except Exception as e:
61
  print(f"Error initializing KPipeline: {e}\nRetrying with default language...")
62
  pipeline = KPipeline(lang_code="a") # Fallback to English
@@ -158,39 +158,317 @@ def remove_silence_function(file_path,minimum_silence=50):
158
  combined += chunk
159
  combined.export(output_path, format=audio_format)
160
  return output_path
161
-
162
  def generate_and_save_audio(text, Language="American English",voice="af_bella", speed=1,remove_silence=False,keep_silence_up_to=0.05):
163
  text=clean_text(text)
164
  update_pipeline(Language)
165
  generator = pipeline(text, voice=voice, speed=speed, split_pattern=r'\n+')
166
  save_path=tts_file_name(text)
167
  # Open the WAV file for writing
 
168
  with wave.open(save_path, 'wb') as wav_file:
169
  # Set the WAV file parameters
170
  wav_file.setnchannels(1) # Mono audio
171
  wav_file.setsampwidth(2) # 2 bytes per sample (16-bit audio)
172
  wav_file.setframerate(24000) # Sample rate
173
-
174
- # Process each audio chunk
175
- for i, (gs, ps, audio) in enumerate(generator):
176
- # print(f"{i}. {gs}")
177
- # print(f"Phonetic Transcription: {ps}")
178
- # display(Audio(data=audio, rate=24000, autoplay=i==0))
179
- print("\n")
180
- # Convert the Tensor to a NumPy array
181
- audio_np = audio.numpy() # Convert Tensor to NumPy array
182
- audio_int16 = (audio_np * 32767).astype(np.int16) # Scale to 16-bit range
183
- audio_bytes = audio_int16.tobytes() # Convert to bytes
184
-
185
- # Write the audio chunk to the WAV file
186
- wav_file.writeframes(audio_bytes)
 
 
 
187
  if remove_silence:
188
  keep_silence = int(keep_silence_up_to * 1000)
189
  new_wave_file=remove_silence_function(save_path,minimum_silence=keep_silence)
190
- return new_wave_file,new_wave_file
191
- return save_path,save_path
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
192
 
 
 
 
 
 
 
 
193
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
194
 
195
 
196
 
@@ -225,7 +503,7 @@ def ui():
225
  language_name = gr.Dropdown(lang_list, label="Select Language", value=lang_list[0])
226
 
227
  with gr.Row():
228
- voice_name = gr.Dropdown(voice_names, label="Choose VoicePack", value=voice_names[0])
229
 
230
  with gr.Row():
231
  generate_btn = gr.Button('Generate', variant='primary')
@@ -237,13 +515,18 @@ def ui():
237
  with gr.Column():
238
  audio = gr.Audio(interactive=False, label='Output Audio', autoplay=True)
239
  audio_file = gr.File(label='Download Audio')
240
-
241
- with gr.Accordion('Enable Autoplay', open=False):
 
 
242
  autoplay = gr.Checkbox(value=True, label='Autoplay')
243
  autoplay.change(toggle_autoplay, inputs=[autoplay], outputs=[audio])
 
 
 
244
 
245
- text.submit(generate_and_save_audio, inputs=[text, language_name, voice_name, speed, remove_silence], outputs=[audio, audio_file])
246
- generate_btn.click(generate_and_save_audio, inputs=[text, language_name, voice_name, speed, remove_silence], outputs=[audio, audio_file])
247
 
248
  # Add examples to the interface
249
  gr.Examples(examples=dummy_examples, inputs=[text, language_name, voice_name])
@@ -289,7 +572,8 @@ def main(debug, share):
289
  demo1 = ui()
290
  demo2 = tutorial()
291
  demo = gr.TabbedInterface([demo1, demo2],["Multilingual TTS","VoicePack Explanation"],title="Kokoro TTS",theme='JohnSmith9982/small_and_pretty')
292
- demo.queue().launch(debug=debug, share=share)
 
293
  #Run on local network
294
  # laptop_ip="192.168.0.30"
295
  # port=8080
 
56
  try:
57
  pipeline = KPipeline(lang_code=new_lang)
58
  last_used_language = new_lang # Update last used language
59
+ # print(f"Pipeline updated to {Language} ({new_lang})")
60
  except Exception as e:
61
  print(f"Error initializing KPipeline: {e}\nRetrying with default language...")
62
  pipeline = KPipeline(lang_code="a") # Fallback to English
 
158
  combined += chunk
159
  combined.export(output_path, format=audio_format)
160
  return output_path
 
161
  def generate_and_save_audio(text, Language="American English",voice="af_bella", speed=1,remove_silence=False,keep_silence_up_to=0.05):
162
  text=clean_text(text)
163
  update_pipeline(Language)
164
  generator = pipeline(text, voice=voice, speed=speed, split_pattern=r'\n+')
165
  save_path=tts_file_name(text)
166
  # Open the WAV file for writing
167
+ timestamps={}
168
  with wave.open(save_path, 'wb') as wav_file:
169
  # Set the WAV file parameters
170
  wav_file.setnchannels(1) # Mono audio
171
  wav_file.setsampwidth(2) # 2 bytes per sample (16-bit audio)
172
  wav_file.setframerate(24000) # Sample rate
173
+ for i, result in enumerate(generator):
174
+ gs = result.graphemes # str
175
+ # print(f"\n{i}: {gs}")
176
+ ps = result.phonemes # str
177
+ # audio = result.audio.cpu().numpy()
178
+ audio = result.audio
179
+ tokens = result.tokens # List[en.MToken]
180
+ timestamps[i]={"text":gs,"words":[]}
181
+ if Language in ["American English", "British English"]:
182
+ for t in tokens:
183
+ # print(t.text, repr(t.whitespace), t.start_ts, t.end_ts)
184
+ timestamps[i]["words"].append({"word":t.text,"start":t.start_ts,"end":t.end_ts})
185
+ audio_np = audio.numpy() # Convert Tensor to NumPy array
186
+ audio_int16 = (audio_np * 32767).astype(np.int16) # Scale to 16-bit range
187
+ audio_bytes = audio_int16.tobytes() # Convert to bytes
188
+ # Write the audio chunk to the WAV file
189
+ wav_file.writeframes(audio_bytes)
190
  if remove_silence:
191
  keep_silence = int(keep_silence_up_to * 1000)
192
  new_wave_file=remove_silence_function(save_path,minimum_silence=keep_silence)
193
+ return new_wave_file,timestamps
194
+ return save_path,timestamps
195
+
196
+ def adjust_timestamps(timestamp_dict):
197
+ adjusted_timestamps = []
198
+ last_end_time = 0 # Tracks the last word's end time
199
+
200
+ for segment_id in sorted(timestamp_dict.keys()):
201
+ segment = timestamp_dict[segment_id]
202
+ words = segment["words"]
203
+
204
+ for word_entry in words:
205
+ # Skip word entries with start or end time as None or 0
206
+ if word_entry["start"] in [None, 0] and word_entry["end"] in [None, 0]:
207
+ continue
208
+
209
+ # Fill in None values with the last valid timestamp or use 0 as default
210
+ word_start = word_entry["start"] if word_entry["start"] is not None else last_end_time
211
+ word_end = word_entry["end"] if word_entry["end"] is not None else word_start # Use word_start if end is None
212
+
213
+ new_start = word_start + last_end_time
214
+ new_end = word_end + last_end_time
215
+
216
+ adjusted_timestamps.append({
217
+ "word": word_entry["word"],
218
+ "start": round(new_start, 3),
219
+ "end": round(new_end, 3)
220
+ })
221
+
222
+ # Update last_end_time to the last word's end time in this segment
223
+ if words:
224
+ last_end_time = adjusted_timestamps[-1]["end"]
225
+
226
+ return adjusted_timestamps
227
+
228
+
229
+ import string
230
+
231
+ def write_word_srt(word_level_timestamps, output_file="word.srt", skip_punctuation=True):
232
+ with open(output_file, "w", encoding="utf-8") as f:
233
+ index = 1 # Track subtitle numbering separately
234
+
235
+ for entry in word_level_timestamps:
236
+ word = entry["word"]
237
+
238
+ # Skip punctuation if enabled
239
+ if skip_punctuation and all(char in string.punctuation for char in word):
240
+ continue
241
+
242
+ start_time = entry["start"]
243
+ end_time = entry["end"]
244
+
245
+ # Convert seconds to SRT time format (HH:MM:SS,mmm)
246
+ def format_srt_time(seconds):
247
+ hours = int(seconds // 3600)
248
+ minutes = int((seconds % 3600) // 60)
249
+ sec = int(seconds % 60)
250
+ millisec = int((seconds % 1) * 1000)
251
+ return f"{hours:02}:{minutes:02}:{sec:02},{millisec:03}"
252
+
253
+ start_srt = format_srt_time(start_time)
254
+ end_srt = format_srt_time(end_time)
255
+
256
+ # Write entry to SRT file
257
+ f.write(f"{index}\n{start_srt} --> {end_srt}\n{word}\n\n")
258
+ index += 1 # Increment subtitle number
259
+
260
+ import string
261
+
262
+ def write_sentence_srt(word_level_timestamps, output_file="subtitles.srt", max_words=8, min_pause=0.1):
263
+ subtitles = [] # Stores subtitle blocks
264
+ subtitle_words = [] # Temporary list for words in the current subtitle
265
+ start_time = None # Tracks start time of current subtitle
266
+
267
+ remove_punctuation = ['"',"—"] # Add punctuations to remove if needed
268
+
269
+ for i, entry in enumerate(word_level_timestamps):
270
+ word = entry["word"]
271
+ word_start = entry["start"]
272
+ word_end = entry["end"]
273
+
274
+ # Skip selected punctuation from remove_punctuation list
275
+ if word in remove_punctuation:
276
+ continue
277
+
278
+ # Attach punctuation to the previous word
279
+ if word in string.punctuation:
280
+ if subtitle_words:
281
+ subtitle_words[-1] = (subtitle_words[-1][0] + word, subtitle_words[-1][1])
282
+ continue
283
+
284
+ # Start a new subtitle block if needed
285
+ if start_time is None:
286
+ start_time = word_start
287
+
288
+ # Calculate pause duration if this is not the first word
289
+ if subtitle_words:
290
+ last_word_end = subtitle_words[-1][1]
291
+ pause_duration = word_start - last_word_end
292
+ else:
293
+ pause_duration = 0
294
+
295
+ # **NEW FIX:** If pause is too long, create a new subtitle but ensure continuity
296
+ if (word.endswith(('.', '!', '?')) and len(subtitle_words) >= 5) or len(subtitle_words) >= max_words or pause_duration > min_pause:
297
+ end_time = subtitle_words[-1][1] # Use last word's end time
298
+ subtitle_text = " ".join(w[0] for w in subtitle_words)
299
+ subtitles.append((start_time, end_time, subtitle_text))
300
+
301
+ # Reset for the next subtitle, but **ensure continuity**
302
+ subtitle_words = [(word, word_end)] # **Carry the current word to avoid delay**
303
+ start_time = word_start # **Start at the current word, not None**
304
+
305
+ continue # Avoid adding the word twice
306
+
307
+ # Add the current word to the subtitle
308
+ subtitle_words.append((word, word_end))
309
+
310
+ # Ensure last subtitle is added if anything remains
311
+ if subtitle_words:
312
+ end_time = subtitle_words[-1][1]
313
+ subtitle_text = " ".join(w[0] for w in subtitle_words)
314
+ subtitles.append((start_time, end_time, subtitle_text))
315
 
316
+ # Function to format SRT timestamps
317
+ def format_srt_time(seconds):
318
+ hours = int(seconds // 3600)
319
+ minutes = int((seconds % 3600) // 60)
320
+ sec = int(seconds % 60)
321
+ millisec = int((seconds % 1) * 1000)
322
+ return f"{hours:02}:{minutes:02}:{sec:02},{millisec:03}"
323
 
324
+ # Write subtitles to SRT file
325
+ with open(output_file, "w", encoding="utf-8") as f:
326
+ for i, (start, end, text) in enumerate(subtitles, start=1):
327
+ f.write(f"{i}\n{format_srt_time(start)} --> {format_srt_time(end)}\n{text}\n\n")
328
+
329
+ # print(f"SRT file '{output_file}' created successfully!")
330
+
331
+
332
+ import json
333
+ import re
334
+
335
+ def fix_punctuation(text):
336
+ # Remove spaces before punctuation marks (., ?, !, ,)
337
+ text = re.sub(r'\s([.,?!])', r'\1', text)
338
+
339
+ # Handle quotation marks: remove spaces before and after them
340
+ text = text.replace('" ', '"')
341
+ text = text.replace(' "', '"')
342
+ text = text.replace('" ', '"')
343
+
344
+ # Track quotation marks to add space after closing quotes
345
+ track = 0
346
+ result = []
347
+
348
+ for index, char in enumerate(text):
349
+ if char == '"':
350
+ track += 1
351
+ result.append(char)
352
+ # If it's a closing quote (even number of quotes), add a space after it
353
+ if track % 2 == 0:
354
+ result.append(' ')
355
+ else:
356
+ result.append(char)
357
+ text=''.join(result)
358
+ return text.strip()
359
+
360
+
361
+
362
+ def make_json(word_timestamps, json_file_name):
363
+ data = {}
364
+ temp = []
365
+ inside_quote = False # Track if we are inside a quoted sentence
366
+ start_time = word_timestamps[0]['start'] # Initialize with the first word's start time
367
+ end_time = word_timestamps[0]['end'] # Initialize with the first word's end time
368
+ words_in_sentence = []
369
+ sentence_id = 0 # Initialize sentence ID
370
+
371
+ # Process each word in word_timestamps
372
+ for i, word_data in enumerate(word_timestamps):
373
+ word = word_data['word']
374
+ word_start = word_data['start']
375
+ word_end = word_data['end']
376
+
377
+ # Collect word info for JSON
378
+ words_in_sentence.append({'word': word, 'start': word_start, 'end': word_end})
379
+
380
+ # Update the end_time for the sentence based on the current word
381
+ end_time = word_end
382
+
383
+ # Properly handle opening and closing quotation marks
384
+ if word == '"':
385
+ if inside_quote:
386
+ temp[-1] += '"' # Attach closing quote to the last word
387
+ else:
388
+ temp.append('"') # Keep opening quote as a separate entry
389
+ inside_quote = not inside_quote # Toggle inside_quote state
390
+ else:
391
+ temp.append(word)
392
+
393
+ # Check if this is a sentence-ending punctuation
394
+ if word.endswith(('.', '?', '!')) and not inside_quote:
395
+ # Ensure the next word is NOT a dialogue tag before finalizing the sentence
396
+ if i + 1 < len(word_timestamps):
397
+ next_word = word_timestamps[i + 1]['word']
398
+ if next_word[0].islower(): # Likely a dialogue tag like "he said"
399
+ continue # Do not break the sentence yet
400
+
401
+ # Store the full sentence for JSON and reset word collection for next sentence
402
+ sentence = " ".join(temp)
403
+ sentence = fix_punctuation(sentence) # Fix punctuation in the sentence
404
+ data[sentence_id] = {
405
+ 'text': sentence,
406
+ 'duration': end_time - start_time,
407
+ 'start': start_time,
408
+ 'end': end_time,
409
+ 'words': words_in_sentence
410
+ }
411
+
412
+ # Reset for the next sentence
413
+ temp = []
414
+ words_in_sentence = []
415
+ start_time = word_data['start'] # Update the start time for the next sentence
416
+ sentence_id += 1 # Increment sentence ID
417
+
418
+ # Handle any remaining words if necessary
419
+ if temp:
420
+ sentence = " ".join(temp)
421
+ sentence = fix_punctuation(sentence) # Fix punctuation in the sentence
422
+ data[sentence_id] = {
423
+ 'text': sentence,
424
+ 'duration': end_time - start_time,
425
+ 'start': start_time,
426
+ 'end': end_time,
427
+ 'words': words_in_sentence
428
+ }
429
+
430
+ # Write data to JSON file
431
+ with open(json_file_name, 'w') as json_file:
432
+ json.dump(data, json_file, indent=4)
433
+ return json_file_name
434
+
435
+
436
+
437
+
438
+ import os
439
+
440
+ def modify_filename(save_path: str, prefix: str = ""):
441
+ directory, filename = os.path.split(save_path)
442
+ name, ext = os.path.splitext(filename)
443
+ new_filename = f"{prefix}{name}{ext}"
444
+ return os.path.join(directory, new_filename)
445
+ import shutil
446
+ def save_current_data():
447
+ if os.path.exists("./last"):
448
+ shutil.rmtree("./last")
449
+ os.makedirs("./last",exist_ok=True)
450
+
451
+
452
+ def subtile_update(text, Language="American English",voice="af_bella", speed=1,remove_silence=False,keep_silence_up_to=0.05):
453
+ save_path,timestamps=generate_and_save_audio(text=text, Language=Language,voice=voice, speed=speed,remove_silence=remove_silence,keep_silence_up_to=keep_silence_up_to)
454
+ if remove_silence==False:
455
+ if Language in ["American English", "British English"]:
456
+ word_level_timestamps=adjust_timestamps(timestamps)
457
+ word_level_srt = modify_filename(save_path.replace(".wav", ".srt"), prefix="word_level_")
458
+ normal_srt = modify_filename(save_path.replace(".wav", ".srt"), prefix="sentence_")
459
+ json_file = modify_filename(save_path.replace(".wav", ".json"), prefix="duration_")
460
+ write_word_srt(word_level_timestamps, output_file=word_level_srt, skip_punctuation=True)
461
+ write_sentence_srt(word_level_timestamps, output_file=normal_srt, min_pause=0.01)
462
+ make_json(word_level_timestamps, json_file)
463
+ save_current_data()
464
+ shutil.copy(save_path, "./last/")
465
+ shutil.copy(word_level_srt, "./last/")
466
+ shutil.copy(normal_srt, "./last/")
467
+ shutil.copy(json_file, "./last/")
468
+ return save_path,save_path,word_level_srt,normal_srt,json_file
469
+ return save_path,save_path,None,None,None
470
+
471
+
472
 
473
 
474
 
 
503
  language_name = gr.Dropdown(lang_list, label="Select Language", value=lang_list[0])
504
 
505
  with gr.Row():
506
+ voice_name = gr.Dropdown(voice_names, label="Choose VoicePack", value='af_heart')#voice_names[0])
507
 
508
  with gr.Row():
509
  generate_btn = gr.Button('Generate', variant='primary')
 
515
  with gr.Column():
516
  audio = gr.Audio(interactive=False, label='Output Audio', autoplay=True)
517
  audio_file = gr.File(label='Download Audio')
518
+ # word_level_srt_file = gr.File(label='Download Word-Level SRT')
519
+ # srt_file = gr.File(label='Download Sentence-Level SRT')
520
+ # sentence_duration_file = gr.File(label='Download Sentence Duration JSON')
521
+ with gr.Accordion('Autoplay, Subtitle, Timestamp', open=False):
522
  autoplay = gr.Checkbox(value=True, label='Autoplay')
523
  autoplay.change(toggle_autoplay, inputs=[autoplay], outputs=[audio])
524
+ word_level_srt_file = gr.File(label='Download Word-Level SRT')
525
+ srt_file = gr.File(label='Download Sentence-Level SRT')
526
+ sentence_duration_file = gr.File(label='Download Sentence Duration JSON')
527
 
528
+ text.submit(subtile_update, inputs=[text, language_name, voice_name, speed, remove_silence], outputs=[audio, audio_file,word_level_srt_file,srt_file,sentence_duration_file])
529
+ generate_btn.click(subtile_update, inputs=[text, language_name, voice_name, speed, remove_silence], outputs=[audio, audio_file,word_level_srt_file,srt_file,sentence_duration_file])
530
 
531
  # Add examples to the interface
532
  gr.Examples(examples=dummy_examples, inputs=[text, language_name, voice_name])
 
572
  demo1 = ui()
573
  demo2 = tutorial()
574
  demo = gr.TabbedInterface([demo1, demo2],["Multilingual TTS","VoicePack Explanation"],title="Kokoro TTS",theme='JohnSmith9982/small_and_pretty')
575
+ # demo.queue().launch(debug=debug, share=share)
576
+ demo.queue().launch(debug=debug, share=share,server_port=9000)
577
  #Run on local network
578
  # laptop_ip="192.168.0.30"
579
  # port=8080