drewThomasson
commited on
Commit
•
33a5446
1
Parent(s):
67a6da3
Update ebook2audiobookXTTS/custom_model_ebook2audiobookXTTS.py
Browse files
ebook2audiobookXTTS/custom_model_ebook2audiobookXTTS.py
CHANGED
@@ -1,484 +1,486 @@
|
|
1 |
-
print("starting...")
|
2 |
-
|
3 |
-
import os
|
4 |
-
import shutil
|
5 |
-
import subprocess
|
6 |
-
import re
|
7 |
-
from pydub import AudioSegment
|
8 |
-
import tempfile
|
9 |
-
from pydub import AudioSegment
|
10 |
-
import os
|
11 |
-
import nltk
|
12 |
-
from nltk.tokenize import sent_tokenize
|
13 |
-
import sys
|
14 |
-
import torch
|
15 |
-
from TTS.api import TTS
|
16 |
-
from TTS.tts.configs.xtts_config import XttsConfig
|
17 |
-
from TTS.tts.models.xtts import Xtts
|
18 |
-
from tqdm import tqdm
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
return
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
print(f"
|
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 |
-
start_time
|
107 |
-
|
108 |
-
|
109 |
-
|
110 |
-
|
111 |
-
|
112 |
-
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
|
117 |
-
ffmpeg_cmd += ['-map', '0:a']
|
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 |
-
if os.path.exists(
|
144 |
-
os.remove(
|
145 |
-
if
|
146 |
-
os.remove(
|
147 |
-
|
148 |
-
|
149 |
-
|
150 |
-
|
151 |
-
|
152 |
-
|
153 |
-
|
154 |
-
|
155 |
-
|
156 |
-
|
157 |
-
|
158 |
-
|
159 |
-
import
|
160 |
-
|
161 |
-
|
162 |
-
import
|
163 |
-
import
|
164 |
-
import
|
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 |
-
print(f"
|
228 |
-
|
229 |
-
|
230 |
-
|
231 |
-
|
232 |
-
|
233 |
-
|
234 |
-
|
235 |
-
|
236 |
-
|
237 |
-
|
238 |
-
|
239 |
-
writer.
|
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 |
-
import
|
308 |
-
import
|
309 |
-
|
310 |
-
|
311 |
-
|
312 |
-
|
313 |
-
|
314 |
-
|
315 |
-
|
316 |
-
|
317 |
-
|
318 |
-
|
319 |
-
|
320 |
-
|
321 |
-
|
322 |
-
|
323 |
-
|
324 |
-
from
|
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 |
-
:param
|
365 |
-
:
|
366 |
-
|
367 |
-
parts
|
368 |
-
|
369 |
-
|
370 |
-
|
371 |
-
|
372 |
-
|
373 |
-
|
374 |
-
|
375 |
-
|
376 |
-
|
377 |
-
|
378 |
-
|
379 |
-
sentence
|
380 |
-
|
381 |
-
|
382 |
-
|
383 |
-
|
384 |
-
|
385 |
-
|
386 |
-
|
387 |
-
|
388 |
-
|
389 |
-
|
390 |
-
|
391 |
-
|
392 |
-
|
393 |
-
|
394 |
-
|
395 |
-
|
396 |
-
|
397 |
-
|
398 |
-
|
399 |
-
model.
|
400 |
-
|
401 |
-
|
402 |
-
|
403 |
-
|
404 |
-
|
405 |
-
|
406 |
-
|
407 |
-
|
408 |
-
|
409 |
-
|
410 |
-
|
411 |
-
|
412 |
-
|
413 |
-
|
414 |
-
|
415 |
-
|
416 |
-
|
417 |
-
|
418 |
-
|
419 |
-
|
420 |
-
|
421 |
-
|
422 |
-
os.
|
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 |
-
|
|
|
|
|
|
1 |
+
print("starting...")
|
2 |
+
|
3 |
+
import os
|
4 |
+
import shutil
|
5 |
+
import subprocess
|
6 |
+
import re
|
7 |
+
from pydub import AudioSegment
|
8 |
+
import tempfile
|
9 |
+
from pydub import AudioSegment
|
10 |
+
import os
|
11 |
+
import nltk
|
12 |
+
from nltk.tokenize import sent_tokenize
|
13 |
+
import sys
|
14 |
+
import torch
|
15 |
+
from TTS.api import TTS
|
16 |
+
from TTS.tts.configs.xtts_config import XttsConfig
|
17 |
+
from TTS.tts.models.xtts import Xtts
|
18 |
+
from tqdm import tqdm
|
19 |
+
|
20 |
+
from .. import import_all_files
|
21 |
+
|
22 |
+
#nltk.download('punkt') # Make sure to download the necessary models
|
23 |
+
def is_folder_empty(folder_path):
|
24 |
+
if os.path.exists(folder_path) and os.path.isdir(folder_path):
|
25 |
+
# List directory contents
|
26 |
+
if not os.listdir(folder_path):
|
27 |
+
return True # The folder is empty
|
28 |
+
else:
|
29 |
+
return False # The folder is not empty
|
30 |
+
else:
|
31 |
+
print(f"The path {folder_path} is not a valid folder.")
|
32 |
+
return None # The path is not a valid folder
|
33 |
+
|
34 |
+
def remove_folder_with_contents(folder_path):
|
35 |
+
try:
|
36 |
+
shutil.rmtree(folder_path)
|
37 |
+
print(f"Successfully removed {folder_path} and all of its contents.")
|
38 |
+
except Exception as e:
|
39 |
+
print(f"Error removing {folder_path}: {e}")
|
40 |
+
|
41 |
+
|
42 |
+
|
43 |
+
|
44 |
+
def wipe_folder(folder_path):
|
45 |
+
# Check if the folder exists
|
46 |
+
if not os.path.exists(folder_path):
|
47 |
+
print(f"The folder {folder_path} does not exist.")
|
48 |
+
return
|
49 |
+
|
50 |
+
# Iterate over all the items in the given folder
|
51 |
+
for item in os.listdir(folder_path):
|
52 |
+
item_path = os.path.join(folder_path, item)
|
53 |
+
# If it's a file, remove it and print a message
|
54 |
+
if os.path.isfile(item_path):
|
55 |
+
os.remove(item_path)
|
56 |
+
print(f"Removed file: {item_path}")
|
57 |
+
# If it's a directory, remove it recursively and print a message
|
58 |
+
elif os.path.isdir(item_path):
|
59 |
+
shutil.rmtree(item_path)
|
60 |
+
print(f"Removed directory and its contents: {item_path}")
|
61 |
+
|
62 |
+
print(f"All contents wiped from {folder_path}.")
|
63 |
+
|
64 |
+
|
65 |
+
# Example usage
|
66 |
+
# folder_to_wipe = 'path_to_your_folder'
|
67 |
+
# wipe_folder(folder_to_wipe)
|
68 |
+
|
69 |
+
|
70 |
+
def create_m4b_from_chapters(input_dir, ebook_file, output_dir):
|
71 |
+
# Function to sort chapters based on their numeric order
|
72 |
+
def sort_key(chapter_file):
|
73 |
+
numbers = re.findall(r'\d+', chapter_file)
|
74 |
+
return int(numbers[0]) if numbers else 0
|
75 |
+
|
76 |
+
# Extract metadata and cover image from the eBook file
|
77 |
+
def extract_metadata_and_cover(ebook_path):
|
78 |
+
try:
|
79 |
+
cover_path = ebook_path.rsplit('.', 1)[0] + '.jpg'
|
80 |
+
subprocess.run(['ebook-meta', ebook_path, '--get-cover', cover_path], check=True)
|
81 |
+
if os.path.exists(cover_path):
|
82 |
+
return cover_path
|
83 |
+
except Exception as e:
|
84 |
+
print(f"Error extracting eBook metadata or cover: {e}")
|
85 |
+
return None
|
86 |
+
# Combine WAV files into a single file
|
87 |
+
def combine_wav_files(chapter_files, output_path):
|
88 |
+
# Initialize an empty audio segment
|
89 |
+
combined_audio = AudioSegment.empty()
|
90 |
+
|
91 |
+
# Sequentially append each file to the combined_audio
|
92 |
+
for chapter_file in chapter_files:
|
93 |
+
audio_segment = AudioSegment.from_wav(chapter_file)
|
94 |
+
combined_audio += audio_segment
|
95 |
+
# Export the combined audio to the output file path
|
96 |
+
combined_audio.export(output_path, format='wav')
|
97 |
+
print(f"Combined audio saved to {output_path}")
|
98 |
+
|
99 |
+
# Function to generate metadata for M4B chapters
|
100 |
+
def generate_ffmpeg_metadata(chapter_files, metadata_file):
|
101 |
+
with open(metadata_file, 'w') as file:
|
102 |
+
file.write(';FFMETADATA1\n')
|
103 |
+
start_time = 0
|
104 |
+
for index, chapter_file in enumerate(chapter_files):
|
105 |
+
duration_ms = len(AudioSegment.from_wav(chapter_file))
|
106 |
+
file.write(f'[CHAPTER]\nTIMEBASE=1/1000\nSTART={start_time}\n')
|
107 |
+
file.write(f'END={start_time + duration_ms}\ntitle=Chapter {index + 1}\n')
|
108 |
+
start_time += duration_ms
|
109 |
+
|
110 |
+
# Generate the final M4B file using ffmpeg
|
111 |
+
def create_m4b(combined_wav, metadata_file, cover_image, output_m4b):
|
112 |
+
# Ensure the output directory exists
|
113 |
+
os.makedirs(os.path.dirname(output_m4b), exist_ok=True)
|
114 |
+
|
115 |
+
ffmpeg_cmd = ['ffmpeg', '-i', combined_wav, '-i', metadata_file]
|
116 |
+
if cover_image:
|
117 |
+
ffmpeg_cmd += ['-i', cover_image, '-map', '0:a', '-map', '2:v']
|
118 |
+
else:
|
119 |
+
ffmpeg_cmd += ['-map', '0:a']
|
120 |
+
|
121 |
+
ffmpeg_cmd += ['-map_metadata', '1', '-c:a', 'aac', '-b:a', '192k']
|
122 |
+
if cover_image:
|
123 |
+
ffmpeg_cmd += ['-c:v', 'png', '-disposition:v', 'attached_pic']
|
124 |
+
ffmpeg_cmd += [output_m4b]
|
125 |
+
|
126 |
+
subprocess.run(ffmpeg_cmd, check=True)
|
127 |
+
|
128 |
+
|
129 |
+
|
130 |
+
# Main logic
|
131 |
+
chapter_files = sorted([os.path.join(input_dir, f) for f in os.listdir(input_dir) if f.endswith('.wav')], key=sort_key)
|
132 |
+
temp_dir = tempfile.gettempdir()
|
133 |
+
temp_combined_wav = os.path.join(temp_dir, 'combined.wav')
|
134 |
+
metadata_file = os.path.join(temp_dir, 'metadata.txt')
|
135 |
+
cover_image = extract_metadata_and_cover(ebook_file)
|
136 |
+
output_m4b = os.path.join(output_dir, os.path.splitext(os.path.basename(ebook_file))[0] + '.m4b')
|
137 |
+
|
138 |
+
combine_wav_files(chapter_files, temp_combined_wav)
|
139 |
+
generate_ffmpeg_metadata(chapter_files, metadata_file)
|
140 |
+
create_m4b(temp_combined_wav, metadata_file, cover_image, output_m4b)
|
141 |
+
|
142 |
+
# Cleanup
|
143 |
+
if os.path.exists(temp_combined_wav):
|
144 |
+
os.remove(temp_combined_wav)
|
145 |
+
if os.path.exists(metadata_file):
|
146 |
+
os.remove(metadata_file)
|
147 |
+
if cover_image and os.path.exists(cover_image):
|
148 |
+
os.remove(cover_image)
|
149 |
+
|
150 |
+
# Example usage
|
151 |
+
# create_m4b_from_chapters('path_to_chapter_wavs', 'path_to_ebook_file', 'path_to_output_dir')
|
152 |
+
|
153 |
+
|
154 |
+
|
155 |
+
|
156 |
+
|
157 |
+
|
158 |
+
#this code right here isnt the book grabbing thing but its before to refrence in ordero to create the sepecial chapter labeled book thing with calibre idk some systems cant seem to get it so just in case but the next bit of code after this is the book grabbing code with booknlp
|
159 |
+
import os
|
160 |
+
import subprocess
|
161 |
+
import ebooklib
|
162 |
+
from ebooklib import epub
|
163 |
+
from bs4 import BeautifulSoup
|
164 |
+
import re
|
165 |
+
import csv
|
166 |
+
import nltk
|
167 |
+
|
168 |
+
# Only run the main script if Value is True
|
169 |
+
def create_chapter_labeled_book(ebook_file_path):
|
170 |
+
# Function to ensure the existence of a directory
|
171 |
+
def ensure_directory(directory_path):
|
172 |
+
if not os.path.exists(directory_path):
|
173 |
+
os.makedirs(directory_path)
|
174 |
+
print(f"Created directory: {directory_path}")
|
175 |
+
|
176 |
+
ensure_directory(os.path.join(".", 'Working_files', 'Book'))
|
177 |
+
|
178 |
+
def convert_to_epub(input_path, output_path):
|
179 |
+
# Convert the ebook to EPUB format using Calibre's ebook-convert
|
180 |
+
try:
|
181 |
+
subprocess.run(['ebook-convert', input_path, output_path], check=True)
|
182 |
+
except subprocess.CalledProcessError as e:
|
183 |
+
print(f"An error occurred while converting the eBook: {e}")
|
184 |
+
return False
|
185 |
+
return True
|
186 |
+
|
187 |
+
def save_chapters_as_text(epub_path):
|
188 |
+
# Create the directory if it doesn't exist
|
189 |
+
directory = os.path.join(".", "Working_files", "temp_ebook")
|
190 |
+
ensure_directory(directory)
|
191 |
+
|
192 |
+
# Open the EPUB file
|
193 |
+
book = epub.read_epub(epub_path)
|
194 |
+
|
195 |
+
previous_chapter_text = ''
|
196 |
+
previous_filename = ''
|
197 |
+
chapter_counter = 0
|
198 |
+
|
199 |
+
# Iterate through the items in the EPUB file
|
200 |
+
for item in book.get_items():
|
201 |
+
if item.get_type() == ebooklib.ITEM_DOCUMENT:
|
202 |
+
# Use BeautifulSoup to parse HTML content
|
203 |
+
soup = BeautifulSoup(item.get_content(), 'html.parser')
|
204 |
+
text = soup.get_text()
|
205 |
+
|
206 |
+
# Check if the text is not empty
|
207 |
+
if text.strip():
|
208 |
+
if len(text) < 2300 and previous_filename:
|
209 |
+
# Append text to the previous chapter if it's short
|
210 |
+
with open(previous_filename, 'a', encoding='utf-8') as file:
|
211 |
+
file.write('\n' + text)
|
212 |
+
else:
|
213 |
+
# Create a new chapter file and increment the counter
|
214 |
+
previous_filename = os.path.join(directory, f"chapter_{chapter_counter}.txt")
|
215 |
+
chapter_counter += 1
|
216 |
+
with open(previous_filename, 'w', encoding='utf-8') as file:
|
217 |
+
file.write(text)
|
218 |
+
print(f"Saved chapter: {previous_filename}")
|
219 |
+
|
220 |
+
# Example usage
|
221 |
+
input_ebook = ebook_file_path # Replace with your eBook file path
|
222 |
+
output_epub = os.path.join(".", "Working_files", "temp.epub")
|
223 |
+
|
224 |
+
|
225 |
+
if os.path.exists(output_epub):
|
226 |
+
os.remove(output_epub)
|
227 |
+
print(f"File {output_epub} has been removed.")
|
228 |
+
else:
|
229 |
+
print(f"The file {output_epub} does not exist.")
|
230 |
+
|
231 |
+
if convert_to_epub(input_ebook, output_epub):
|
232 |
+
save_chapters_as_text(output_epub)
|
233 |
+
|
234 |
+
# Download the necessary NLTK data (if not already present)
|
235 |
+
#nltk.download('punkt')
|
236 |
+
|
237 |
+
def process_chapter_files(folder_path, output_csv):
|
238 |
+
with open(output_csv, 'w', newline='', encoding='utf-8') as csvfile:
|
239 |
+
writer = csv.writer(csvfile)
|
240 |
+
# Write the header row
|
241 |
+
writer.writerow(['Text', 'Start Location', 'End Location', 'Is Quote', 'Speaker', 'Chapter'])
|
242 |
+
|
243 |
+
# Process each chapter file
|
244 |
+
chapter_files = sorted(os.listdir(folder_path), key=lambda x: int(x.split('_')[1].split('.')[0]))
|
245 |
+
for filename in chapter_files:
|
246 |
+
if filename.startswith('chapter_') and filename.endswith('.txt'):
|
247 |
+
chapter_number = int(filename.split('_')[1].split('.')[0])
|
248 |
+
file_path = os.path.join(folder_path, filename)
|
249 |
+
|
250 |
+
try:
|
251 |
+
with open(file_path, 'r', encoding='utf-8') as file:
|
252 |
+
text = file.read()
|
253 |
+
# Insert "NEWCHAPTERABC" at the beginning of each chapter's text
|
254 |
+
if text:
|
255 |
+
text = "NEWCHAPTERABC" + text
|
256 |
+
sentences = nltk.tokenize.sent_tokenize(text)
|
257 |
+
for sentence in sentences:
|
258 |
+
start_location = text.find(sentence)
|
259 |
+
end_location = start_location + len(sentence)
|
260 |
+
writer.writerow([sentence, start_location, end_location, 'True', 'Narrator', chapter_number])
|
261 |
+
except Exception as e:
|
262 |
+
print(f"Error processing file {filename}: {e}")
|
263 |
+
|
264 |
+
# Example usage
|
265 |
+
folder_path = os.path.join(".", "Working_files", "temp_ebook")
|
266 |
+
output_csv = os.path.join(".", "Working_files", "Book", "Other_book.csv")
|
267 |
+
|
268 |
+
process_chapter_files(folder_path, output_csv)
|
269 |
+
|
270 |
+
def sort_key(filename):
|
271 |
+
"""Extract chapter number for sorting."""
|
272 |
+
match = re.search(r'chapter_(\d+)\.txt', filename)
|
273 |
+
return int(match.group(1)) if match else 0
|
274 |
+
|
275 |
+
def combine_chapters(input_folder, output_file):
|
276 |
+
# Create the output folder if it doesn't exist
|
277 |
+
os.makedirs(os.path.dirname(output_file), exist_ok=True)
|
278 |
+
|
279 |
+
# List all txt files and sort them by chapter number
|
280 |
+
files = [f for f in os.listdir(input_folder) if f.endswith('.txt')]
|
281 |
+
sorted_files = sorted(files, key=sort_key)
|
282 |
+
|
283 |
+
with open(output_file, 'w', encoding='utf-8') as outfile: # Specify UTF-8 encoding here
|
284 |
+
for i, filename in enumerate(sorted_files):
|
285 |
+
with open(os.path.join(input_folder, filename), 'r', encoding='utf-8') as infile: # And here
|
286 |
+
outfile.write(infile.read())
|
287 |
+
# Add the marker unless it's the last file
|
288 |
+
if i < len(sorted_files) - 1:
|
289 |
+
outfile.write("\nNEWCHAPTERABC\n")
|
290 |
+
|
291 |
+
# Paths
|
292 |
+
input_folder = os.path.join(".", 'Working_files', 'temp_ebook')
|
293 |
+
output_file = os.path.join(".", 'Working_files', 'Book', 'Chapter_Book.txt')
|
294 |
+
|
295 |
+
|
296 |
+
# Combine the chapters
|
297 |
+
combine_chapters(input_folder, output_file)
|
298 |
+
|
299 |
+
ensure_directory(os.path.join(".", "Working_files", "Book"))
|
300 |
+
|
301 |
+
|
302 |
+
#create_chapter_labeled_book()
|
303 |
+
|
304 |
+
|
305 |
+
|
306 |
+
|
307 |
+
import os
|
308 |
+
import subprocess
|
309 |
+
import sys
|
310 |
+
import torchaudio
|
311 |
+
|
312 |
+
# Check if Calibre's ebook-convert tool is installed
|
313 |
+
def calibre_installed():
|
314 |
+
try:
|
315 |
+
subprocess.run(['ebook-convert', '--version'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
316 |
+
return True
|
317 |
+
except FileNotFoundError:
|
318 |
+
print("Calibre is not installed. Please install Calibre for this functionality.")
|
319 |
+
return False
|
320 |
+
|
321 |
+
|
322 |
+
import os
|
323 |
+
import torch
|
324 |
+
from TTS.api import TTS
|
325 |
+
from nltk.tokenize import sent_tokenize
|
326 |
+
from pydub import AudioSegment
|
327 |
+
# Assuming split_long_sentence and wipe_folder are defined elsewhere in your code
|
328 |
+
|
329 |
+
default_target_voice_path = "default_voice.wav" # Ensure this is a valid path
|
330 |
+
default_language_code = "en"
|
331 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
332 |
+
|
333 |
+
def combine_wav_files(input_directory, output_directory, file_name):
|
334 |
+
# Ensure that the output directory exists, create it if necessary
|
335 |
+
os.makedirs(output_directory, exist_ok=True)
|
336 |
+
|
337 |
+
# Specify the output file path
|
338 |
+
output_file_path = os.path.join(output_directory, file_name)
|
339 |
+
|
340 |
+
# Initialize an empty audio segment
|
341 |
+
combined_audio = AudioSegment.empty()
|
342 |
+
|
343 |
+
# Get a list of all .wav files in the specified input directory and sort them
|
344 |
+
input_file_paths = sorted(
|
345 |
+
[os.path.join(input_directory, f) for f in os.listdir(input_directory) if f.endswith(".wav")],
|
346 |
+
key=lambda f: int(''.join(filter(str.isdigit, f)))
|
347 |
+
)
|
348 |
+
|
349 |
+
# Sequentially append each file to the combined_audio
|
350 |
+
for input_file_path in input_file_paths:
|
351 |
+
audio_segment = AudioSegment.from_wav(input_file_path)
|
352 |
+
combined_audio += audio_segment
|
353 |
+
|
354 |
+
# Export the combined audio to the output file path
|
355 |
+
combined_audio.export(output_file_path, format='wav')
|
356 |
+
|
357 |
+
print(f"Combined audio saved to {output_file_path}")
|
358 |
+
|
359 |
+
# Function to split long strings into parts
|
360 |
+
def split_long_sentence(sentence, max_length=249, max_pauses=10):
|
361 |
+
"""
|
362 |
+
Splits a sentence into parts based on length or number of pauses without recursion.
|
363 |
+
|
364 |
+
:param sentence: The sentence to split.
|
365 |
+
:param max_length: Maximum allowed length of a sentence.
|
366 |
+
:param max_pauses: Maximum allowed number of pauses in a sentence.
|
367 |
+
:return: A list of sentence parts that meet the criteria.
|
368 |
+
"""
|
369 |
+
parts = []
|
370 |
+
while len(sentence) > max_length or sentence.count(',') + sentence.count(';') + sentence.count('.') > max_pauses:
|
371 |
+
possible_splits = [i for i, char in enumerate(sentence) if char in ',;.' and i < max_length]
|
372 |
+
if possible_splits:
|
373 |
+
# Find the best place to split the sentence, preferring the last possible split to keep parts longer
|
374 |
+
split_at = possible_splits[-1] + 1
|
375 |
+
else:
|
376 |
+
# If no punctuation to split on within max_length, split at max_length
|
377 |
+
split_at = max_length
|
378 |
+
|
379 |
+
# Split the sentence and add the first part to the list
|
380 |
+
parts.append(sentence[:split_at].strip())
|
381 |
+
sentence = sentence[split_at:].strip()
|
382 |
+
|
383 |
+
# Add the remaining part of the sentence
|
384 |
+
parts.append(sentence)
|
385 |
+
return parts
|
386 |
+
|
387 |
+
"""
|
388 |
+
if 'tts' not in locals():
|
389 |
+
tts = TTS(selected_tts_model, progress_bar=True).to(device)
|
390 |
+
"""
|
391 |
+
from tqdm import tqdm
|
392 |
+
|
393 |
+
# Convert chapters to audio using XTTS
|
394 |
+
def convert_chapters_to_audio(chapters_dir, output_audio_dir, target_voice_path=None, language=None, custom_model=None):
|
395 |
+
if custom_model:
|
396 |
+
print("Loading custom model...")
|
397 |
+
config = XttsConfig()
|
398 |
+
config.load_json(custom_model['config'])
|
399 |
+
model = Xtts.init_from_config(config)
|
400 |
+
model.load_checkpoint(config, checkpoint_path=custom_model['model'], vocab_path=custom_model['vocab'], use_deepspeed=False)
|
401 |
+
model.to(device)
|
402 |
+
print("Computing speaker latents...")
|
403 |
+
gpt_cond_latent, speaker_embedding = model.get_conditioning_latents(audio_path=[target_voice_path])
|
404 |
+
else:
|
405 |
+
selected_tts_model = "tts_models/multilingual/multi-dataset/xtts_v2"
|
406 |
+
tts = TTS(selected_tts_model, progress_bar=False).to(device)
|
407 |
+
|
408 |
+
if not os.path.exists(output_audio_dir):
|
409 |
+
os.makedirs(output_audio_dir)
|
410 |
+
|
411 |
+
for chapter_file in sorted(os.listdir(chapters_dir)):
|
412 |
+
if chapter_file.endswith('.txt'):
|
413 |
+
match = re.search(r"chapter_(\d+).txt", chapter_file)
|
414 |
+
if match:
|
415 |
+
chapter_num = int(match.group(1))
|
416 |
+
else:
|
417 |
+
print(f"Skipping file {chapter_file} as it does not match the expected format.")
|
418 |
+
continue
|
419 |
+
|
420 |
+
chapter_path = os.path.join(chapters_dir, chapter_file)
|
421 |
+
output_file_name = f"audio_chapter_{chapter_num}.wav"
|
422 |
+
output_file_path = os.path.join(output_audio_dir, output_file_name)
|
423 |
+
temp_audio_directory = os.path.join(".", "Working_files", "temp")
|
424 |
+
os.makedirs(temp_audio_directory, exist_ok=True)
|
425 |
+
temp_count = 0
|
426 |
+
|
427 |
+
with open(chapter_path, 'r', encoding='utf-8') as file:
|
428 |
+
chapter_text = file.read()
|
429 |
+
sentences = sent_tokenize(chapter_text, language='italian' if language == 'it' else 'english')
|
430 |
+
for sentence in tqdm(sentences, desc=f"Chapter {chapter_num}"):
|
431 |
+
fragments = split_long_sentence(sentence, max_length=249 if language == "en" else 213, max_pauses=10)
|
432 |
+
for fragment in fragments:
|
433 |
+
if fragment != "":
|
434 |
+
print(f"Generating fragment: {fragment}...")
|
435 |
+
fragment_file_path = os.path.join(temp_audio_directory, f"{temp_count}.wav")
|
436 |
+
if custom_model:
|
437 |
+
out = model.inference(fragment, language, gpt_cond_latent, speaker_embedding, temperature=0.7)
|
438 |
+
torchaudio.save(fragment_file_path, torch.tensor(out["wav"]).unsqueeze(0), 24000)
|
439 |
+
else:
|
440 |
+
speaker_wav_path = target_voice_path if target_voice_path else default_target_voice_path
|
441 |
+
language_code = language if language else default_language_code
|
442 |
+
tts.tts_to_file(text=fragment, file_path=fragment_file_path, speaker_wav=speaker_wav_path, language=language_code)
|
443 |
+
temp_count += 1
|
444 |
+
|
445 |
+
combine_wav_files(temp_audio_directory, output_audio_dir, output_file_name)
|
446 |
+
wipe_folder(temp_audio_directory)
|
447 |
+
print(f"Converted chapter {chapter_num} to audio.")
|
448 |
+
|
449 |
+
|
450 |
+
# Main execution flow
|
451 |
+
if __name__ == "__main__":
|
452 |
+
if len(sys.argv) < 2:
|
453 |
+
print("Usage: python script.py <ebook_file_path> [target_voice_file_path] [language] [custom_model_path] [custom_config_path] [custom_vocab_path]")
|
454 |
+
sys.exit(1)
|
455 |
+
|
456 |
+
ebook_file_path = sys.argv[1]
|
457 |
+
target_voice = sys.argv[2] if len(sys.argv) > 2 else None
|
458 |
+
language = sys.argv[3] if len(sys.argv) > 3 else None
|
459 |
+
|
460 |
+
custom_model = None
|
461 |
+
if len(sys.argv) > 6:
|
462 |
+
custom_model = {
|
463 |
+
'model': sys.argv[4],
|
464 |
+
'config': sys.argv[5],
|
465 |
+
'vocab': sys.argv[6]
|
466 |
+
}
|
467 |
+
|
468 |
+
if not calibre_installed():
|
469 |
+
sys.exit(1)
|
470 |
+
|
471 |
+
working_files = os.path.join(".", "Working_files", "temp_ebook")
|
472 |
+
full_folder_working_files = os.path.join(".", "Working_files")
|
473 |
+
chapters_directory = os.path.join(".", "Working_files", "temp_ebook")
|
474 |
+
output_audio_directory = os.path.join(".", 'Chapter_wav_files')
|
475 |
+
|
476 |
+
print("Wiping and removing Working_files folder...")
|
477 |
+
remove_folder_with_contents(full_folder_working_files)
|
478 |
+
|
479 |
+
print("Wiping and removing chapter_wav_files folder...")
|
480 |
+
remove_folder_with_contents(output_audio_directory)
|
481 |
+
|
482 |
+
create_chapter_labeled_book(ebook_file_path)
|
483 |
+
audiobook_output_path = os.path.join(".", "Audiobooks")
|
484 |
+
print(f"{chapters_directory}||||{output_audio_directory}|||||{target_voice}")
|
485 |
+
convert_chapters_to_audio(chapters_directory, output_audio_directory, target_voice, language, custom_model)
|
486 |
+
create_m4b_from_chapters(output_audio_directory, ebook_file_path, audiobook_output_path)
|