-
-
Notifications
You must be signed in to change notification settings - Fork 644
/
Copy pathfunctions.py
2781 lines (2662 loc) · 132 KB
/
functions.py
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
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# NOTE!!NOTE!!!NOTE!!NOTE!!!NOTE!!NOTE!!!NOTE!!NOTE!!!
# THE WORD "CHAPTER" IN THE CODE DOES NOT MEAN
# IT'S THE REAL CHAPTER OF THE EBOOK SINCE NO STANDARDS
# ARE DEFINING A CHAPTER ON .EPUB FORMAT. THE WORD "BLOCK"
# IS USED TO PRINT IT OUT TO THE TERMINAL, AND "CHAPTER" TO THE CODE
# WHICH IS LESS GENERIC FOR THE DEVELOPERS
import argparse
import asyncio
import csv
import ebooklib
import fnmatch
import gc
import gradio as gr
import hashlib
import json
import math
import os
import platform
import psutil
import pymupdf4llm
import random
import regex as re
import requests
import shutil
import socket
import subprocess
import sys
import threading
import time
import torch
import urllib.request
import uuid
import zipfile
import traceback
import lib.conf as conf
import lib.lang as lang
import lib.models as mod
from bs4 import BeautifulSoup
from collections import Counter
from collections.abc import Mapping
from collections.abc import MutableMapping
from datetime import datetime
from ebooklib import epub
from fastapi import FastAPI
from glob import glob
from iso639 import languages
from multiprocessing import Manager, Event
from multiprocessing.managers import DictProxy, ListProxy
from num2words import num2words
from pathlib import Path
from pydub import AudioSegment
from queue import Queue, Empty
from starlette.requests import ClientDisconnect
from tqdm import tqdm
from types import MappingProxyType
from urllib.parse import urlparse
from lib.classes.redirect_console import RedirectConsole
from lib.classes.voice_extractor import VoiceExtractor
from lib.classes.tts_manager import TTSManager
def inject_configs(target_namespace):
# Extract variables from both modules and inject them into the target namespace
for module in (conf, lang, mod):
target_namespace.update({k: v for k, v in vars(module).items() if not k.startswith('__')})
# Inject configurations into the global namespace of this module
inject_configs(globals())
class DependencyError(Exception):
def __init__(self, message=None):
super().__init__(message)
print(message)
# Automatically handle the exception when it's raised
self.handle_exception()
def handle_exception(self):
# Print the full traceback of the exception
traceback.print_exc()
# Print the exception message
print(f'Caught DependencyError: {self}')
# Exit the script if it's not a web process
if not is_gui_process:
sys.exit(1)
def recursive_proxy(data, manager=None):
if manager is None:
manager = Manager()
if isinstance(data, dict):
proxy_dict = manager.dict()
for key, value in data.items():
proxy_dict[key] = recursive_proxy(value, manager)
return proxy_dict
elif isinstance(data, list):
proxy_list = manager.list()
for item in data:
proxy_list.append(recursive_proxy(item, manager))
return proxy_list
elif isinstance(data, (str, int, float, bool, type(None))):
return data
else:
error = f"Unsupported data type: {type(data)}"
print(error)
return
class SessionContext:
def __init__(self):
self.manager = Manager()
self.sessions = self.manager.dict() # Store all session-specific contexts
self.cancellation_events = {} # Store multiprocessing.Event for each session
def get_session(self, id):
if id not in self.sessions:
self.sessions[id] = recursive_proxy({
"script_mode": NATIVE,
"id": id,
"process_id": None,
"device": default_device,
"system": None,
"client": None,
"language": default_language_code,
"language_iso1": None,
"audiobook": None,
"audiobooks_dir": None,
"process_dir": None,
"ebook": None,
"ebook_list": None,
"ebook_mode": "single",
"chapters_dir": None,
"chapters_dir_sentences": None,
"epub_path": None,
"filename_noext": None,
"tts_engine": default_tts_engine,
"fine_tuned": default_fine_tuned,
"voice": None,
"voice_dir": None,
"custom_model": None,
"custom_model_dir": None,
"toc": None,
"chapters": None,
"cover": None,
"status": None,
"progress": 0,
"time": None,
"cancellation_requested": False,
"temperature": default_xtts_settings['temperature'],
"length_penalty": default_xtts_settings['length_penalty'],
"num_beams": default_xtts_settings['num_beams'],
"repetition_penalty": default_xtts_settings['repetition_penalty'],
"top_k": default_xtts_settings['top_k'],
"top_p": default_xtts_settings['top_k'],
"speed": default_xtts_settings['speed'],
"enable_text_splitting": default_xtts_settings['enable_text_splitting'],
"event": None,
"output_format": default_output_format,
"metadata": {
"title": None,
"creator": None,
"contributor": None,
"language": None,
"identifier": None,
"publisher": None,
"date": None,
"description": None,
"subject": None,
"rights": None,
"format": None,
"type": None,
"coverage": None,
"relation": None,
"Source": None,
"Modified": None,
}
}, manager=self.manager)
return self.sessions[id]
app = FastAPI()
lock = threading.Lock()
context = SessionContext()
is_gui_process = False
def prepare_dirs(src, session):
try:
resume = False
os.makedirs(os.path.join(models_dir,'tts'), exist_ok=True)
os.makedirs(session['session_dir'], exist_ok=True)
os.makedirs(session['process_dir'], exist_ok=True)
os.makedirs(session['custom_model_dir'], exist_ok=True)
os.makedirs(session['voice_dir'], exist_ok=True)
os.makedirs(session['audiobooks_dir'], exist_ok=True)
session['ebook'] = os.path.join(session['process_dir'], os.path.basename(src))
if os.path.exists(session['ebook']):
if compare_files_by_hash(session['ebook'], src):
resume = True
if not resume:
shutil.rmtree(session['chapters_dir'], ignore_errors=True)
os.makedirs(session['chapters_dir'], exist_ok=True)
os.makedirs(session['chapters_dir_sentences'], exist_ok=True)
shutil.copy(src, session['ebook'])
return True
except Exception as e:
DependencyError(e)
return False
def check_programs(prog_name, command, options):
try:
subprocess.run(
[command, options],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
check=True,
text=True,
encoding='utf-8'
)
return True, None
except FileNotFoundError:
e = f'''********** Error: {prog_name} is not installed! if your OS calibre package version
is not compatible you still can run ebook2audiobook.sh (linux/mac) or ebook2audiobook.cmd (windows) **********'''
DependencyError(e)
return False, None
except subprocess.CalledProcessError:
e = f'Error: There was an issue running {prog_name}.'
DependencyError(e)
return False, None
def analyze_uploaded_file(zip_path, required_files):
try:
if not os.path.exists(zip_path):
error = f"The file does not exist: {os.path.basename(zip_path)}"
print(error)
return False
files_in_zip = {}
empty_files = set()
with zipfile.ZipFile(zip_path, 'r') as zf:
for file_info in zf.infolist():
file_name = file_info.filename
if file_info.is_dir():
continue
base_name = os.path.basename(file_name)
files_in_zip[base_name.lower()] = file_info.file_size
if file_info.file_size == 0:
empty_files.add(base_name.lower())
required_files = [file.lower() for file in required_files]
missing_files = [f for f in required_files if f not in files_in_zip]
required_empty_files = [f for f in required_files if f in empty_files]
if missing_files:
print(f"Missing required files: {missing_files}")
if required_empty_files:
print(f"Required files with 0 KB: {required_empty_files}")
return not missing_files and not required_empty_files
except zipfile.BadZipFile:
error = "The file is not a valid ZIP archive."
raise ValueError(error)
except Exception as e:
error = f"An error occurred: {e}"
raise RuntimeError(error)
def extract_custom_model(file_src, session, required_files=None):
try:
model_path = None
if required_files is None:
required_files = models[session['tts_engine']][default_fine_tuned]['files']
model_name = re.sub('.zip', '', os.path.basename(file_src), flags=re.IGNORECASE)
model_name = get_sanitized(model_name)
with zipfile.ZipFile(file_src, 'r') as zip_ref:
files = zip_ref.namelist()
files_length = len(files)
tts_dir = session['tts_engine']
model_path = os.path.join(session['custom_model_dir'], tts_dir, model_name)
if os.path.exists(model_path):
print(f'{model_path} already exists, bypassing files extraction')
return model_path
os.makedirs(model_path, exist_ok=True)
with tqdm(total=files_length, unit='files') as t:
for f in files:
if f in required_files:
zip_ref.extract(f, model_path)
t.update(1)
if is_gui_process:
os.remove(file_src)
if model_path is not None:
msg = f'Extracted files to {model_path}'
print(msg)
return model_name
else:
error = f'An error occured when unzip {file_src}'
return None
except asyncio.exceptions.CancelledError:
DependencyError(e)
if is_gui_process:
os.remove(file_src)
return None
except Exception as e:
DependencyError(e)
if is_gui_process:
os.remove(file_src)
return None
def hash_proxy_dict(proxy_dict):
return hashlib.md5(str(proxy_dict).encode('utf-8')).hexdigest()
def calculate_hash(filepath, hash_algorithm='sha256'):
hash_func = hashlib.new(hash_algorithm)
with open(filepath, 'rb') as f:
while chunk := f.read(8192): # Read in chunks to handle large files
hash_func.update(chunk)
return hash_func.hexdigest()
def compare_files_by_hash(file1, file2, hash_algorithm='sha256'):
return calculate_hash(file1, hash_algorithm) == calculate_hash(file2, hash_algorithm)
def compare_dict_keys(d1, d2):
if not isinstance(d1, Mapping) or not isinstance(d2, Mapping):
return d1 == d2
d1_keys = set(d1.keys())
d2_keys = set(d2.keys())
missing_in_d2 = d1_keys - d2_keys
missing_in_d1 = d2_keys - d1_keys
if missing_in_d2 or missing_in_d1:
return {
"missing_in_d2": missing_in_d2,
"missing_in_d1": missing_in_d1,
}
for key in d1_keys.intersection(d2_keys):
nested_result = compare_keys(d1[key], d2[key])
if nested_result:
return {key: nested_result}
return None
def proxy_to_dict(proxy_obj):
def recursive_copy(source, visited):
# Handle circular references by tracking visited objects
if id(source) in visited:
return None # Stop processing circular references
visited.add(id(source)) # Mark as visited
if isinstance(source, dict):
result = {}
for key, value in source.items():
result[key] = recursive_copy(value, visited)
return result
elif isinstance(source, list):
return [recursive_copy(item, visited) for item in source]
elif isinstance(source, set):
return list(source)
elif isinstance(source, (int, float, str, bool, type(None))):
return source
elif isinstance(source, DictProxy):
# Explicitly handle DictProxy objects
return recursive_copy(dict(source), visited) # Convert DictProxy to dict
else:
return str(source) # Convert non-serializable types to strings
return recursive_copy(proxy_obj, set())
def math2word(text, lang, lang_iso1, tts_engine):
def check_compat():
try:
num2words(1, lang=lang_iso1)
return True
except NotImplementedError:
return False
except Exception as e:
return False
def rep_num(match):
number = match.group().replace(",", "") # Remove commas for proper conversion
try:
if "." in number or "e" in number or "E" in number:
return num2words(float(number), lang=lang_iso1)
return num2words(int(number), lang=lang_iso1)
except ValueError:
return number # If conversion fails, return original number
def replace_ambiguous(match):
symbol2 = match.group(2)
symbol3 = match.group(3)
if symbol2 in ambiguous_replacements: # "num SYMBOL num" case
return f"{match.group(1)} {ambiguous_replacements[symbol2]} {match.group(3)}"
elif symbol3 in ambiguous_replacements: # "SYMBOL num" case
return f"{ambiguous_replacements[symbol3]} {match.group(4)}"
return match.group(0)
is_num2words_compat = check_compat()
phonemes_list = language_math_phonemes.get(lang, language_math_phonemes[default_language_code])
# Separate ambiguous and non-ambiguous symbols
ambiguous_symbols = {"-", "/", "*", "x"}
replacements = {k: v for k, v in phonemes_list.items() if not k.isdigit()} # Keep only math symbols
normal_replacements = {k: v for k, v in replacements.items() if k not in ambiguous_symbols}
ambiguous_replacements = {k: v for k, v in replacements.items() if k in ambiguous_symbols}
# Replace unambiguous math symbols normally
if normal_replacements:
math_pattern = r'(' + '|'.join(map(re.escape, normal_replacements.keys())) + r')'
text = re.sub(math_pattern, lambda m: f" {normal_replacements[m.group(0)]} ", text)
# Regex pattern for ambiguous symbols (match only valid equations)
ambiguous_pattern = (
r'(?<!\S)(\d+)\s*([-/*x])\s*(\d+)(?!\S)|' # Matches "num SYMBOL num" (e.g., "3 + 5", "7-2", "8 * 4")
r'(?<!\S)([-/*x])\s*(\d+)(?!\S)' # Matches "SYMBOL num" (e.g., "-4", "/ 9")
)
if ambiguous_replacements:
text = re.sub(ambiguous_pattern, replace_ambiguous, text)
# Regex pattern for detecting numbers (handles negatives, commas, decimals, scientific notation)
#number_pattern = r'(?<!\S)(-?\d{1,3}(?:,\d{3})*(?:\.\d+)?(?:[eE][-+]?\d+)?)(?!\S)'
number_pattern = r'(?<!\S)(-?\d{1,3}(?:,\d{3})*(?:\.\d+(?!\s|$))?(?:[eE][-+]?\d+)?)(?!\S)'
if tts_engine != XTTSv2:
if is_num2words_compat:
# Pattern 2: Split big numbers into groups of 4
text = re.sub(r'(\d{4})(?=\d{4}(?!\.\d))', r'\1 ', text)
text = re.sub(number_pattern, rep_num, text)
else:
# Pattern 2: Split big numbers into groups of 2
text = re.sub(r'(\d{2})(?=\d{2}(?!\.\d))', r'\1 ', text)
# Fallback: Replace numbers using phonemes dictionary
sorted_numbers = sorted((k for k in phonemes_list if k.isdigit()), key=len, reverse=True)
if sorted_numbers:
number_pattern = r'\b(' + '|'.join(map(re.escape, sorted_numbers)) + r')\b'
text = re.sub(number_pattern, lambda match: phonemes_list[match.group(0)], text)
return text.strip()
def normalize_text(text, lang, lang_iso1, tts_engine):
# Replace punctuations causing hallucinations
pattern = f"[{''.join(map(re.escape, punctuation_switch.keys()))}]"
text = re.sub(pattern, lambda match: punctuation_switch.get(match.group(), match.group()), text)
# Replace NBSP with a normal space
text = text.replace("\xa0", " ")
if lang in abbreviations_mapping:
pattern = r'\b(' + '|'.join(re.escape(k) for k in abbreviations_mapping[lang]) + r')\b'
text = re.sub(pattern, lambda match: abbreviations_mapping[lang].get(match.group(0), match.group(0)), text)
# Replace multiple newlines ("\n\n", "\r\r", "\n\r") with " . " as many times as they occur
#text = re.sub('(\r\n|\n\n|\r\r|\n\r)+', lambda m: ' . ' * (m.group().count("\n") // 2 + m.group().count("\r") // 2), text)
# Replace multiple newlines ("\n\n", "\r\r", "\n\r", etc.) with a single "\n"
text = re.sub(r'(\r\n|\r|\n)+', '\n', text)
# Replace single newlines ("\n" or "\r") with spaces
text = re.sub(r'[\r\n]', ' ', text)
# Replace tabs ("\t") with equivalent spaces
text = re.sub(r'\t+', lambda m: ' ' * len(m.group()), text)
# replace roman numbers by digits
text = replace_roman_numbers(text)
# Pattern 1: Add a space between UTF-8 characters and numbers
text = re.sub(r'(?<=[\p{L}])(?=\d)|(?<=\d)(?=[\p{L}])', ' ', text)
# Replace math symbols with words
text = math2word(text, lang, lang_iso1, tts_engine)
return text
def convert_to_epub(session):
if session['cancellation_requested']:
print('Cancel requested')
return False
try:
util_app = shutil.which('ebook-convert')
if not util_app:
error = "The 'ebook-convert' utility is not installed or not found."
print(error)
return False
file_input = session['ebook']
file_ext = os.path.splitext(session['ebook'])[1].lower()
if file_ext == '.pdf':
msg = 'File input is a PDF. flatten it in MD format...'
print(msg)
file_input = f"{os.path.splitext(session['epub_path'])[0]}.md"
markdown_text = pymupdf4llm.to_markdown(session['ebook'])
with open(file_input, "w", encoding="utf-8") as md_file:
md_file.write(markdown_text)
msg = f"Running command: {util_app} {file_input} {session['epub_path']}"
print(msg)
result = subprocess.run(
[
util_app, file_input, session['epub_path'],
'--input-encoding=utf-8',
'--output-profile=generic_eink',
'--epub-version=3',
'--flow-size=0',
'--chapter-mark=pagebreak',
'--page-breaks-before', "//*[name()='h1' or name()='h2']",
'--disable-font-rescaling',
'--pretty-print',
'--smarten-punctuation',
'--verbose'
],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
encoding='utf-8'
)
print(result.stdout)
return True
except subprocess.CalledProcessError as e:
print(f"Subprocess error: {e.stderr}")
DependencyError(e)
return False
except FileNotFoundError as e:
print(f"Utility not found: {e}")
DependencyError(e)
return False
def get_cover(epubBook, session):
try:
if session['cancellation_requested']:
print('Cancel requested')
return False
cover_image = False
cover_path = os.path.join(session['process_dir'], session['filename_noext'] + '.jpg')
for item in epubBook.get_items_of_type(ebooklib.ITEM_COVER):
cover_image = item.get_content()
break
if not cover_image:
for item in epubBook.get_items_of_type(ebooklib.ITEM_IMAGE):
if 'cover' in item.file_name.lower() or 'cover' in item.get_id().lower():
cover_image = item.get_content()
break
if cover_image:
with open(cover_path, 'wb') as cover_file:
cover_file.write(cover_image)
return cover_path
return True
except Exception as e:
DependencyError(e)
return False
def get_chapters(epubBook, session):
try:
if session['cancellation_requested']:
print('Cancel requested')
return False
# Step 1: Extract TOC (Table of Contents)
toc_list = []
try:
toc = epubBook.toc # Extract TOC
toc_list = [normalize_text(str(item.title), session['language'], session['language_iso1'], session['tts_engine'])
for item in toc if hasattr(item, 'title')] # Normalize TOC entries
except Exception as toc_error:
error = f"Error extracting TOC: {toc_error}"
print(error)
all_docs = list(epubBook.get_items_of_type(ebooklib.ITEM_DOCUMENT))
if not all_docs:
return [], []
all_docs = all_docs[1:] # Exclude the first document if needed
doc_cache = {}
msg = '******* NOTE: YOU CAN SAFELY IGNORE "Character xx not found in the vocabulary." *******'
print(msg)
for doc in all_docs:
doc_cache[doc] = filter_chapter(doc, session['language'], session['language_iso1'], session['tts_engine'])
# Step 4: Determine the most common pattern
doc_patterns = [filter_pattern(str(doc)) for doc in all_docs if filter_pattern(str(doc))]
most_common_pattern = filter_doc(doc_patterns)
# Step 5: Calculate average character length
char_length = [len(content) for content in doc_cache.values()]
average_char_length = sum(char_length) / len(char_length) if char_length else 0
# Step 6: Filter docs based on character length or pattern
final_selected_docs = [
doc for doc in all_docs
if doc in doc_cache and doc_cache[doc]
and (len(doc_cache[doc]) >= average_char_length or filter_pattern(str(doc)) == most_common_pattern)
]
# Step 7: Extract parts from the final selected docs
chapters = [doc_cache[doc] for doc in final_selected_docs]
# Step 8: Return both TOC and Chapters separately
return toc, chapters
except Exception as e:
error = f'Error extracting main content pages: {e}'
DependencyError(error)
return None, None
def filter_chapter(doc, lang, lang_iso1, tts_engine):
soup = BeautifulSoup(doc.get_body_content(), 'html.parser')
# Remove scripts and styles
for script in soup(["script", "style"]):
script.decompose()
# Normalize lines and remove unnecessary spaces and switch special chars
text = normalize_text(soup.get_text().strip(), lang, lang_iso1, tts_engine)
# Rule 1: Ensure spaces before & after punctuation
pattern_space = re.escape(''.join(punctuation_list))
# Step 1: Ensure space before and after punctuation (excluding `,` and `.`)
punctuation_pattern_space = r'\s*([{}])\s*'.format(pattern_space.replace(',', '').replace('.', ''))
text = re.sub(punctuation_pattern_space, r' \1 ', text)
# Rule 2: Ensure spaces before & after `,` and `.` ONLY when NOT between numbers
comma_dot_pattern = r'(?<!\d)\s*(\.{3}|[,.])\s*(?!\d)'
# Step 2: Ensure space before and after `,` and `.` only when NOT between numbers
text = re.sub(comma_dot_pattern, r' \1 ', text)
# Create regex pattern from punctuation list to split the phoneme_list
pattern_split = f"[^{re.escape(''.join(punctuation_split))}]+[{re.escape(''.join(punctuation_split))}]?|[{re.escape(''.join(punctuation_split))}]"
if not text.strip():
phoneme_list = []
else:
tmp_list = re.findall(pattern_split, text)
phoneme_list = [item.strip() for item in tmp_list if item and item.strip() and item != ' ']
# get the final sentence array according to the max_tokens limitation
max_tokens = language_mapping[lang]['max_tokens']
chapter_sentences = get_sentences(phoneme_list, max_tokens)
return chapter_sentences
def filter_doc(doc_patterns):
pattern_counter = Counter(doc_patterns)
# Returns a list with one tuple: [(pattern, count)]
most_common = pattern_counter.most_common(1)
return most_common[0][0] if most_common else None
def filter_pattern(doc_identifier):
docs = doc_identifier.split(':')
if len(docs) > 2:
segment = docs[1]
if re.search(r'[a-zA-Z]', segment) and re.search(r'\d', segment):
return ''.join([char for char in segment if char.isalpha()])
elif re.match(r'^[a-zA-Z]+$', segment):
return segment
elif re.match(r'^\d+$', segment):
return 'numbers'
return None
r"""
def get_sentences(phoneme_list, max_tokens):
sentences = []
current_sentence = ""
current_phoneme_count = 0
for phoneme in phoneme_list:
part_phoneme_count = len(phoneme.split())
# Always append to current sentence unless punctuation is hit
if current_phoneme_count + part_phoneme_count > max_tokens:
# Ensure we finalize the sentence at punctuation, not a space
if any(current_sentence.endswith(punc) for punc in punctuation_split):
sentences.append(current_sentence.strip())
current_sentence = phoneme
current_phoneme_count = part_phoneme_count
else:
# Look back and split at last punctuation instead of splitting randomly
last_punc_index = max(
(current_sentence.rfind(punc) for punc in punctuation_split if punc in current_sentence),
default=-1
)
if last_punc_index > -1:
sentences.append(current_sentence[:last_punc_index+1].strip()) # Keep punctuation
current_sentence = current_sentence[last_punc_index+1:].strip() + " " + phoneme
current_phoneme_count = len(current_sentence.split())
else:
sentences.append(current_sentence.strip())
current_sentence = phoneme
current_phoneme_count = part_phoneme_count
else:
current_sentence += (" " if current_sentence else "") + phoneme
current_phoneme_count += part_phoneme_count
if current_sentence:
sentences.append(current_sentence.strip())
return sentences
"""
def get_sentences(phoneme_list, max_tokens):
"""
Split a list of phoneme strings into sentences that do not exceed max_tokens.
If a sentence has no punctuation and exceeds max_tokens, it is split into chunks.
In normal cases, the sentence remains unchanged.
"""
sentences = []
current_sentence = ""
current_token_count = 0
# Basic splitting by token count.
def split_sentence_by_tokens(sentence, max_tokens):
words = sentence.split()
if len(words) <= max_tokens:
return [sentence]
return [" ".join(words[i:i+max_tokens]) for i in range(0, len(words), max_tokens)]
# Advanced splitting: only invoked if the sentence exceeds max_tokens.
def advanced_split(sentence):
words = sentence.split()
if len(words) <= max_tokens:
return [sentence]
# If punctuation exists, attempt to split at punctuation.
if any(p in sentence for p in punctuation_split):
# Find the last punctuation in the sentence.
last_punc_index = max(sentence.rfind(p) for p in punctuation_split if p in sentence)
if last_punc_index != -1:
part1 = sentence[:last_punc_index+1].strip()
part2 = sentence[last_punc_index+1:].strip()
# Recursively split each part if necessary.
return advanced_split(part1) + advanced_split(part2)
# Fallback: split by tokens.
return split_sentence_by_tokens(sentence, max_tokens)
for phoneme in phoneme_list:
tokens = phoneme.split()
token_count = len(tokens)
if current_token_count + token_count > max_tokens:
# Only apply advanced splitting if current_sentence exceeds the token limit.
if len(current_sentence.split()) > max_tokens:
sentences.extend(advanced_split(current_sentence.strip()))
else:
sentences.append(current_sentence.strip())
current_sentence = phoneme
current_token_count = token_count
else:
current_sentence = (current_sentence + " " + phoneme).strip() if current_sentence else phoneme
current_token_count += token_count
if current_sentence:
if len(current_sentence.split()) > max_tokens:
sentences.extend(advanced_split(current_sentence.strip()))
else:
sentences.append(current_sentence.strip())
return sentences
def get_vram():
os_name = platform.system()
# NVIDIA (Cross-Platform: Windows, Linux, macOS)
try:
from pynvml import nvmlInit, nvmlDeviceGetHandleByIndex, nvmlDeviceGetMemoryInfo
nvmlInit()
handle = nvmlDeviceGetHandleByIndex(0) # First GPU
info = nvmlDeviceGetMemoryInfo(handle)
vram = info.total
return int(vram / (1024 ** 3)) # Convert to GB
except ImportError:
pass
except Exception as e:
pass
# AMD (Windows)
if os_name == "Windows":
try:
cmd = 'wmic path Win32_VideoController get AdapterRAM'
output = subprocess.run(cmd, capture_output=True, text=True, shell=True)
lines = output.stdout.splitlines()
vram_values = [int(line.strip()) for line in lines if line.strip().isdigit()]
if vram_values:
return int(vram_values[0] / (1024 ** 3))
except Exception as e:
pass
# AMD (Linux)
if os_name == "Linux":
try:
cmd = "lspci -v | grep -i 'VGA' -A 12 | grep -i 'preallocated' | awk '{print $2}'"
output = subprocess.run(cmd, capture_output=True, text=True, shell=True)
if output.stdout.strip().isdigit():
return int(output.stdout.strip()) // 1024
except Exception as e:
pass
# Intel (Linux Only)
intel_vram_paths = [
"/sys/kernel/debug/dri/0/i915_vram_total", # Intel dedicated GPUs
"/sys/class/drm/card0/device/resource0" # Some integrated GPUs
]
for path in intel_vram_paths:
if os.path.exists(path):
try:
with open(path, "r") as f:
vram = int(f.read().strip()) // (1024 ** 3)
return vram
except Exception as e:
pass
# macOS (OpenGL Alternative)
if os_name == "Darwin":
try:
from OpenGL.GL import glGetIntegerv
from OpenGL.GLX import GLX_RENDERER_VIDEO_MEMORY_MB_MESA
vram = int(glGetIntegerv(GLX_RENDERER_VIDEO_MEMORY_MB_MESA) // 1024)
return vram
except ImportError:
pass
except Exception as e:
pass
return 0
def get_sanitized(str, replacement="_"):
str = str.replace('&', 'And')
forbidden_chars = r'[<>:"/\\|?*\x00-\x1F ()]'
sanitized = re.sub(r'\s+', replacement, str)
sanitized = re.sub(forbidden_chars, replacement, sanitized)
sanitized = sanitized.strip("_")
return sanitized
def convert_chapters_to_audio(session):
try:
if session['cancellation_requested']:
print('Cancel requested')
return False
progress_bar = None
if is_gui_process:
progress_bar = gr.Progress(track_tqdm=True)
tts_manager = TTSManager(session, is_gui_process)
if tts_manager.params['tts'] is None:
return False
resume_chapter = 0
missing_chapters = []
resume_sentence = 0
missing_sentences = []
existing_chapters = sorted(
[f for f in os.listdir(session['chapters_dir']) if f.endswith(f'.{default_audio_proc_format}')],
key=lambda x: int(re.search(r'\d+', x).group())
)
if existing_chapters:
resume_chapter = max(int(re.search(r'\d+', f).group()) for f in existing_chapters)
msg = f'Resuming from block {resume_chapter}'
print(msg)
existing_chapter_numbers = {int(re.search(r'\d+', f).group()) for f in existing_chapters}
missing_chapters = [
i for i in range(1, resume_chapter) if i not in existing_chapter_numbers
]
if resume_chapter not in missing_chapters:
missing_chapters.append(resume_chapter)
existing_sentences = sorted(
[f for f in os.listdir(session['chapters_dir_sentences']) if f.endswith(f'.{default_audio_proc_format}')],
key=lambda x: int(re.search(r'\d+', x).group())
)
if existing_sentences:
resume_sentence = max(int(re.search(r'\d+', f).group()) for f in existing_sentences)
msg = f"Resuming from sentence {resume_sentence}"
print(msg)
existing_sentence_numbers = {int(re.search(r'\d+', f).group()) for f in existing_sentences}
missing_sentences = [
i for i in range(1, resume_sentence) if i not in existing_sentence_numbers
]
if resume_sentence not in missing_sentences:
missing_sentences.append(resume_sentence)
total_chapters = len(session['chapters'])
total_sentences = sum(len(array) for array in session['chapters'])
sentence_number = 0
with tqdm(total=total_sentences, desc='convertsion 0.00%', bar_format='{desc}: {n_fmt}/{total_fmt} ', unit='step', initial=resume_sentence) as t:
msg = f'A total of {total_chapters} blocks and {total_sentences} sentences...'
for x in range(0, total_chapters):
chapter_num = x + 1
chapter_audio_file = f'chapter_{chapter_num}.{default_audio_proc_format}'
sentences = session['chapters'][x]
sentences_count = len(sentences)
start = sentence_number
msg = f'Block {chapter_num} containing {sentences_count} sentences...'
print(msg)
for i, sentence in enumerate(sentences):
if session['cancellation_requested']:
msg = 'Cancel requested'
print(msg)
return False
if sentence_number in missing_sentences or sentence_number > resume_sentence or (sentence_number == 0 and resume_sentence == 0):
if sentence_number <= resume_sentence and sentence_number > 0:
msg = f'**Recovering missing file sentence {sentence_number}'
print(msg)
tts_manager.params['sentence_audio_file'] = os.path.join(session['chapters_dir_sentences'], f'{sentence_number}.{default_audio_proc_format}')
if session['tts_engine'] == XTTSv2 or session['tts_engine'] == FAIRSEQ:
tts_manager.params['sentence'] = sentence.replace('.', '<pause>').replace(',', '<pause>')
else:
tts_manager.params['sentence'] = sentence
if tts_manager.params['sentence'] != "":
if tts_manager.convert_sentence_to_audio():
percentage = (sentence_number / total_sentences) * 100
t.set_description(f'Converting {percentage:.2f}%')
msg = f'\nSentence: {sentence}'
print(msg)
else:
return False
t.update(1)
if progress_bar is not None:
progress_bar(sentence_number / total_sentences)
sentence_number += 1
if progress_bar is not None:
progress_bar(sentence_number / total_sentences)
end = sentence_number - 1 if sentence_number > 1 else sentence_number
msg = f"End of Block {chapter_num}"
print(msg)
if chapter_num in missing_chapters or sentence_number > resume_sentence:
if chapter_num <= resume_chapter:
msg = f'**Recovering missing file block {chapter_num}'
print(msg)
if combine_audio_sentences(chapter_audio_file, start, end, session):
msg = f'Combining block {chapter_num} to audio, sentence {start} to {end}'
print(msg)
else:
msg = 'combine_audio_sentences() failed!'
print(msg)
return False
return True
except Exception as e:
DependencyError(e)
return False
def combine_audio_sentences(chapter_audio_file, start, end, session):
try:
chapter_audio_file = os.path.join(session['chapters_dir'], chapter_audio_file)
file_list = os.path.join(session['chapters_dir_sentences'], 'sentences.txt')
sentence_files = [f for f in os.listdir(session['chapters_dir_sentences']) if f.endswith(f'.{default_audio_proc_format}')]
sentences_dir_ordered = sorted(sentence_files, key=lambda x: int(re.search(r'\d+', x).group()))
selected_files = [
os.path.join(session['chapters_dir_sentences'], f)
for f in sentences_dir_ordered
if start <= int(''.join(filter(str.isdigit, os.path.basename(f)))) <= end
]
if not selected_files:
error = 'No audio files found in the specified range.'
print(error)
return False
with open(file_list, 'w') as f:
for file in selected_files:
file = file.replace("\\", "/")
f.write(f'file {file}\n')
ffmpeg_cmd = [
shutil.which('ffmpeg'), '-y', '-safe', '0', '-f', 'concat', '-i', file_list,
'-c:a', default_audio_proc_format, '-map_metadata', '-1', chapter_audio_file
]
try:
process = subprocess.Popen(
ffmpeg_cmd,
env={},
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
encoding='utf-8'
)
for line in process.stdout:
print(line, end='') # Print each line of stdout
process.wait()
if process.returncode == 0:
os.remove(file_list)
msg = f'********* Combined block audio file saved to {chapter_audio_file}'
print(msg)
return True
else:
error = process.returncode
print(error, ffmpeg_cmd)
return False
except subprocess.CalledProcessError as e:
DependencyError(e)
return False
except Exception as e:
DependencyError(e)
return False
def combine_audio_chapters(session):
def assemble_segments():
try:
file_list = os.path.join(session['chapters_dir'], 'chapters.txt')
chapter_files_ordered = sorted(chapter_files, key=lambda x: int(re.search(r'\d+', x).group()))
if not chapter_files_ordered:
error = 'No block files found.'
print(error)
return False
with open(file_list, "w") as f:
for file in chapter_files_ordered:
file = file.replace("\\", "/")
f.write(f"file '{file}'\n")
ffmpeg_cmd = [
shutil.which('ffmpeg'), '-y', '-safe', '0', '-f', 'concat', '-i', file_list,
'-c:a', default_audio_proc_format, '-map_metadata', '-1', combined_chapters_file
]
try:
process = subprocess.Popen(
ffmpeg_cmd,
env={},
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
encoding='utf-8'
)
for line in process.stdout:
print(line, end='') # Print each line of stdout
process.wait()
if process.returncode == 0:
os.remove(file_list)
msg = f'********* total audio blocks saved to {combined_chapters_file}'
print(msg)
return True
else:
error = process.returncode
print(error, ffmpeg_cmd)
return False
except subprocess.CalledProcessError as e:
DependencyError(e)
return False
except Exception as e:
DependencyError(e)
return False
def generate_ffmpeg_metadata():
try:
if session['cancellation_requested']:
print('Cancel requested')
return False
ffmpeg_metadata = ';FFMETADATA1\n'
if session['metadata'].get('title'):
ffmpeg_metadata += f"title={session['metadata']['title']}\n"
if session['metadata'].get('creator'):
ffmpeg_metadata += f"artist={session['metadata']['creator']}\n"
if session['metadata'].get('language'):
ffmpeg_metadata += f"language={session['metadata']['language']}\n\n"
if session['metadata'].get('publisher'):
ffmpeg_metadata += f"publisher={session['metadata']['publisher']}\n"
if session['metadata'].get('description'):
ffmpeg_metadata += f"description={session['metadata']['description']}\n"
if session['metadata'].get('published'):
# Check if the timestamp contains fractional seconds
if '.' in session['metadata']['published']:
# Parse with fractional seconds
year = datetime.strptime(session['metadata']['published'], '%Y-%m-%dT%H:%M:%S.%f%z').year
else:
# Parse without fractional seconds
year = datetime.strptime(session['metadata']['published'], '%Y-%m-%dT%H:%M:%S%z').year
else:
# If published is not provided, use the current year
year = datetime.now().year
ffmpeg_metadata += f'year={year}\n'
if session['metadata'].get('identifiers') and isinstance(session['metadata'].get('identifiers'), dict):