drewThomasson
commited on
Commit
•
d1fa884
1
Parent(s):
235af27
Upload 14 files
Browse files- Notebooks/Kaggel Archive Code/4.wav +0 -0
- Notebooks/Kaggel Archive Code/LICENSE +21 -0
- Notebooks/Kaggel Archive Code/README.md +118 -0
- Notebooks/Kaggel Archive Code/Worker_2T4.sh +59 -0
- Notebooks/Kaggel Archive Code/default_voice.wav +0 -0
- Notebooks/Kaggel Archive Code/demo_mini_story_chapters_Drew.epub +0 -0
- Notebooks/Kaggel Archive Code/ebook2audiobook.py +462 -0
- Notebooks/Kaggel Archive Code/kaggle-ebook2audiobook-demo.ipynb +1 -0
- Notebooks/Kaggel Archive Code/p1.py +462 -0
- Notebooks/Kaggel Archive Code/p2a_worker_gpu1.py +465 -0
- Notebooks/Kaggel Archive Code/p2a_worker_gpu2.py +465 -0
- Notebooks/Kaggel Archive Code/p3.py +462 -0
- Notebooks/colab_ebook2audiobookxtts.ipynb +105 -0
- Notebooks/kaggle-beta-of-ebook2audiobookxtts-ipynb.ipynb +1 -0
Notebooks/Kaggel Archive Code/4.wav
ADDED
Binary file (543 kB). View file
|
|
Notebooks/Kaggel Archive Code/LICENSE
ADDED
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
MIT License
|
2 |
+
|
3 |
+
Copyright (c) 2024 Drew Thomasson
|
4 |
+
|
5 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
6 |
+
of this software and associated documentation files (the "Software"), to deal
|
7 |
+
in the Software without restriction, including without limitation the rights
|
8 |
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
9 |
+
copies of the Software, and to permit persons to whom the Software is
|
10 |
+
furnished to do so, subject to the following conditions:
|
11 |
+
|
12 |
+
The above copyright notice and this permission notice shall be included in all
|
13 |
+
copies or substantial portions of the Software.
|
14 |
+
|
15 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
16 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
17 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
18 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
19 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
20 |
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
21 |
+
SOFTWARE.
|
Notebooks/Kaggel Archive Code/README.md
ADDED
@@ -0,0 +1,118 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# this is a sample for running on kaggle and it may not be updated frequently
|
2 |
+
|
3 |
+
# ebook2audiobook kaggle eddition
|
4 |
+
Generates an audiobook with chapters and ebook metadata using Calibre and Xtts from Coqui tts, and with optional voice cloning, and supports multiple languages
|
5 |
+
|
6 |
+
# import this notebook to kaggle
|
7 |
+
https://github.com/Rihcus/ebook2audiobookXTTS/blob/main/kaggle-ebook2audiobook-demo.ipynb
|
8 |
+
|
9 |
+
## Features
|
10 |
+
|
11 |
+
- Converts eBooks to text format using Calibre's `ebook-convert` tool.
|
12 |
+
- Splits the eBook into chapters for structured audio conversion.
|
13 |
+
- Uses XTTS from Coqui TTS for high-quality text-to-speech conversion.
|
14 |
+
- Optional voice cloning feature using a provided voice file.
|
15 |
+
- Supports different languages for text-to-speech conversion, with English as the default.
|
16 |
+
- Confirmed to run on only 4 gb ram
|
17 |
+
|
18 |
+
## Requirements
|
19 |
+
|
20 |
+
- Python 3.x
|
21 |
+
- `coqui-tts` Python package
|
22 |
+
- Calibre (for eBook conversion)
|
23 |
+
- FFmpeg (for audiobook file creation)
|
24 |
+
- Optional: Custom voice file for voice cloning
|
25 |
+
|
26 |
+
### Installation Instructions for Dependencies
|
27 |
+
|
28 |
+
Install Python 3.x from [Python.org](https://www.python.org/downloads/).
|
29 |
+
|
30 |
+
Install Calibre:
|
31 |
+
- Ubuntu: `sudo apt-get install -y calibre`
|
32 |
+
- macOS: `brew install calibre`
|
33 |
+
- Windows(Powershell in Administrator mode): `choco install calibre`
|
34 |
+
|
35 |
+
Install FFmpeg:
|
36 |
+
- Ubuntu: `sudo apt-get install -y ffmpeg`
|
37 |
+
- macOS: `brew install ffmpeg`
|
38 |
+
- Windows(Powershell in Administrator mode): `choco install ffmpeg`
|
39 |
+
|
40 |
+
Install Mecab for (Non Latin-based Languages tts support)(Optional):
|
41 |
+
- Ubuntu: `sudo apt-get install -y mecab libmecab-dev mecab-ipadic-utf8`
|
42 |
+
- macOS: `brew install mecab`, `brew install mecab-ipadic`
|
43 |
+
- Windows(Powershell in Administrator mode no support for mecab-ipadic easy install so no Japanese for windows :/): `choco install mecab `
|
44 |
+
|
45 |
+
Install Python packages:
|
46 |
+
```bash
|
47 |
+
pip install tts pydub nltk beautifulsoup4 ebooklib tqdm
|
48 |
+
```
|
49 |
+
(For non Latin-based Languages tts support)(Optional)
|
50 |
+
`python -m unidic download`
|
51 |
+
```bash
|
52 |
+
pip install mecab mecab-python3 unidic
|
53 |
+
```
|
54 |
+
|
55 |
+
### Supported Languages
|
56 |
+
|
57 |
+
The script supports the following languages for text-to-speech conversion:
|
58 |
+
|
59 |
+
English (en),
|
60 |
+
Spanish (es),
|
61 |
+
French (fr),
|
62 |
+
German (de),
|
63 |
+
Italian (it),
|
64 |
+
Portuguese (pt),
|
65 |
+
Polish (pl),
|
66 |
+
Turkish (tr),
|
67 |
+
Russian (ru),
|
68 |
+
Dutch (nl),
|
69 |
+
Czech (cs),
|
70 |
+
Arabic (ar),
|
71 |
+
Chinese (zh-cn),
|
72 |
+
Japanese (ja),
|
73 |
+
Hungarian (hu),
|
74 |
+
Korean (ko)
|
75 |
+
|
76 |
+
Specify the language code when running the script to use these languages.
|
77 |
+
|
78 |
+
### Usage
|
79 |
+
|
80 |
+
Navigate to the script's directory in the terminal and execute one of the following commands:
|
81 |
+
If you have any trouble getting it to run in Windows then it should run fine in WSL2
|
82 |
+
|
83 |
+
Basic Usage: ALL PARAMETERS ARE MANDATORY WHEN CALLED THE SCRIPT
|
84 |
+
|
85 |
+
```bash
|
86 |
+
python ebook2audiobook.py <path_to_ebook_file> [path_to_voice_file] [language_code]
|
87 |
+
```
|
88 |
+
Replace <path_to_ebook_file> with the path to your eBook file.
|
89 |
+
include <path_to_voice_file> for voice cloning.
|
90 |
+
include <language_code> to specify the language
|
91 |
+
|
92 |
+
|
93 |
+
## Demo
|
94 |
+
|
95 |
+
|
96 |
+
|
97 |
+
https://github.com/DrewThomasson/ebook2audiobookXTTS/assets/126999465/bccd7240-f967-4d27-a87d-445034db7d21
|
98 |
+
|
99 |
+
|
100 |
+
|
101 |
+
### Supported ebook File Types:
|
102 |
+
.epub, .pdf, .mobi, .txt, .html, .rtf, .chm, .lit, .pdb, .fb2, .odt, .cbr, .cbz, .prc, .lrf, .pml, .snb, .cbc, .rb, and .tcr,
|
103 |
+
(Best results are from using epub or mobi for auto chapter detection)
|
104 |
+
|
105 |
+
### outputs as a m4b with all book metadata and chapters, example output file in an audiobook player app
|
106 |
+
![Example_of_output_in_audiobook_program](https://github.com/DrewThomasson/VoxNovel/blob/dc5197dff97252fa44c391dc0596902d71278a88/readme_files/example_in_app.jpeg)
|
107 |
+
|
108 |
+
A special thanks to the creaters of:
|
109 |
+
|
110 |
+
|
111 |
+
-Coqui TTS
|
112 |
+
|
113 |
+
-https://github.com/coqui-ai/TTS
|
114 |
+
|
115 |
+
|
116 |
+
-Calibre
|
117 |
+
|
118 |
+
-https://calibre-ebook.com
|
Notebooks/Kaggel Archive Code/Worker_2T4.sh
ADDED
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/bin/bash
|
2 |
+
|
3 |
+
workers=$1
|
4 |
+
|
5 |
+
# Clean up operator directory
|
6 |
+
rm -rf "./Operator"
|
7 |
+
rm -rf "./Chapter_wav_files"
|
8 |
+
mkdir "./Operator"
|
9 |
+
mkdir "./Chapter_wav_files"
|
10 |
+
|
11 |
+
|
12 |
+
# Make appropriate temp directories
|
13 |
+
for i in $(seq 1 $workers); do
|
14 |
+
mkdir "./Operator/$i"
|
15 |
+
mkdir "./Operator/$i/temp"
|
16 |
+
mkdir "./Operator/$i/temp_ebook"
|
17 |
+
done
|
18 |
+
|
19 |
+
echo "Created $workers directories"
|
20 |
+
|
21 |
+
#Divide the chapters
|
22 |
+
share=1
|
23 |
+
for FILE in ./Working_files/temp_ebook/*; do
|
24 |
+
cp $FILE "./Operator/$share/temp_ebook/"
|
25 |
+
if [ $share -lt $workers ];
|
26 |
+
then
|
27 |
+
share=$((share+1))
|
28 |
+
else
|
29 |
+
share=1
|
30 |
+
fi
|
31 |
+
done
|
32 |
+
|
33 |
+
echo "Split chapters into operator"
|
34 |
+
|
35 |
+
#Run audio generation
|
36 |
+
#for i in $(seq 1 $workers); do
|
37 |
+
# echo "Starting Worker $i"
|
38 |
+
# python p2a_worker.py $i &
|
39 |
+
#done
|
40 |
+
|
41 |
+
gpu=1
|
42 |
+
for i in $(seq 1 $workers); do
|
43 |
+
if [ $gpu -lt 2 ];
|
44 |
+
then
|
45 |
+
echo "Starting Worker $i on GPU 1"
|
46 |
+
python p2a_worker_gpu1.py $i & #Run audio generation GPU 1 T4
|
47 |
+
gpu=2 # switch to gpu 2 on next loop
|
48 |
+
else
|
49 |
+
echo "Starting Worker $i on GPU 2"
|
50 |
+
python p2a_worker_gpu2.py $i & #Run audio generation GPU 2 T4
|
51 |
+
gpu=1 # switch to gpu 1 on next loop
|
52 |
+
fi
|
53 |
+
done
|
54 |
+
|
55 |
+
|
56 |
+
|
57 |
+
echo "All workers started waiting for completion...."
|
58 |
+
wait
|
59 |
+
echo "Done!"
|
Notebooks/Kaggel Archive Code/default_voice.wav
ADDED
Binary file (291 kB). View file
|
|
Notebooks/Kaggel Archive Code/demo_mini_story_chapters_Drew.epub
ADDED
Binary file (415 kB). View file
|
|
Notebooks/Kaggel Archive Code/ebook2audiobook.py
ADDED
@@ -0,0 +1,462 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
nltk.download('punkt') # Make sure to download the necessary models
|
14 |
+
def is_folder_empty(folder_path):
|
15 |
+
if os.path.exists(folder_path) and os.path.isdir(folder_path):
|
16 |
+
# List directory contents
|
17 |
+
if not os.listdir(folder_path):
|
18 |
+
return True # The folder is empty
|
19 |
+
else:
|
20 |
+
return False # The folder is not empty
|
21 |
+
else:
|
22 |
+
print(f"The path {folder_path} is not a valid folder.")
|
23 |
+
return None # The path is not a valid folder
|
24 |
+
|
25 |
+
def remove_folder_with_contents(folder_path):
|
26 |
+
try:
|
27 |
+
shutil.rmtree(folder_path)
|
28 |
+
print(f"Successfully removed {folder_path} and all of its contents.")
|
29 |
+
except Exception as e:
|
30 |
+
print(f"Error removing {folder_path}: {e}")
|
31 |
+
|
32 |
+
|
33 |
+
|
34 |
+
|
35 |
+
def wipe_folder(folder_path):
|
36 |
+
# Check if the folder exists
|
37 |
+
if not os.path.exists(folder_path):
|
38 |
+
print(f"The folder {folder_path} does not exist.")
|
39 |
+
return
|
40 |
+
|
41 |
+
# Iterate over all the items in the given folder
|
42 |
+
for item in os.listdir(folder_path):
|
43 |
+
item_path = os.path.join(folder_path, item)
|
44 |
+
# If it's a file, remove it and print a message
|
45 |
+
if os.path.isfile(item_path):
|
46 |
+
os.remove(item_path)
|
47 |
+
print(f"Removed file: {item_path}")
|
48 |
+
# If it's a directory, remove it recursively and print a message
|
49 |
+
elif os.path.isdir(item_path):
|
50 |
+
shutil.rmtree(item_path)
|
51 |
+
print(f"Removed directory and its contents: {item_path}")
|
52 |
+
|
53 |
+
print(f"All contents wiped from {folder_path}.")
|
54 |
+
|
55 |
+
|
56 |
+
# Example usage
|
57 |
+
# folder_to_wipe = 'path_to_your_folder'
|
58 |
+
# wipe_folder(folder_to_wipe)
|
59 |
+
|
60 |
+
|
61 |
+
def create_m4b_from_chapters(input_dir, ebook_file, output_dir):
|
62 |
+
# Function to sort chapters based on their numeric order
|
63 |
+
def sort_key(chapter_file):
|
64 |
+
numbers = re.findall(r'\d+', chapter_file)
|
65 |
+
return int(numbers[0]) if numbers else 0
|
66 |
+
|
67 |
+
# Extract metadata and cover image from the eBook file
|
68 |
+
def extract_metadata_and_cover(ebook_path):
|
69 |
+
try:
|
70 |
+
cover_path = ebook_path.rsplit('.', 1)[0] + '.jpg'
|
71 |
+
subprocess.run(['ebook-meta', ebook_path, '--get-cover', cover_path], check=True)
|
72 |
+
if os.path.exists(cover_path):
|
73 |
+
return cover_path
|
74 |
+
except Exception as e:
|
75 |
+
print(f"Error extracting eBook metadata or cover: {e}")
|
76 |
+
return None
|
77 |
+
# Combine WAV files into a single file
|
78 |
+
def combine_wav_files(chapter_files, output_path):
|
79 |
+
# Initialize an empty audio segment
|
80 |
+
combined_audio = AudioSegment.empty()
|
81 |
+
|
82 |
+
# Sequentially append each file to the combined_audio
|
83 |
+
for chapter_file in chapter_files:
|
84 |
+
audio_segment = AudioSegment.from_wav(chapter_file)
|
85 |
+
combined_audio += audio_segment
|
86 |
+
# Export the combined audio to the output file path
|
87 |
+
combined_audio.export(output_path, format='wav')
|
88 |
+
print(f"Combined audio saved to {output_path}")
|
89 |
+
|
90 |
+
# Function to generate metadata for M4B chapters
|
91 |
+
def generate_ffmpeg_metadata(chapter_files, metadata_file):
|
92 |
+
with open(metadata_file, 'w') as file:
|
93 |
+
file.write(';FFMETADATA1\n')
|
94 |
+
start_time = 0
|
95 |
+
for index, chapter_file in enumerate(chapter_files):
|
96 |
+
duration_ms = len(AudioSegment.from_wav(chapter_file))
|
97 |
+
file.write(f'[CHAPTER]\nTIMEBASE=1/1000\nSTART={start_time}\n')
|
98 |
+
file.write(f'END={start_time + duration_ms}\ntitle=Chapter {index + 1}\n')
|
99 |
+
start_time += duration_ms
|
100 |
+
|
101 |
+
# Generate the final M4B file using ffmpeg
|
102 |
+
def create_m4b(combined_wav, metadata_file, cover_image, output_m4b):
|
103 |
+
# Ensure the output directory exists
|
104 |
+
os.makedirs(os.path.dirname(output_m4b), exist_ok=True)
|
105 |
+
|
106 |
+
ffmpeg_cmd = ['ffmpeg', '-i', combined_wav, '-i', metadata_file]
|
107 |
+
if cover_image:
|
108 |
+
ffmpeg_cmd += ['-i', cover_image, '-map', '0:a', '-map', '2:v']
|
109 |
+
else:
|
110 |
+
ffmpeg_cmd += ['-map', '0:a']
|
111 |
+
|
112 |
+
ffmpeg_cmd += ['-map_metadata', '1', '-c:a', 'aac', '-b:a', '192k']
|
113 |
+
if cover_image:
|
114 |
+
ffmpeg_cmd += ['-c:v', 'png', '-disposition:v', 'attached_pic']
|
115 |
+
ffmpeg_cmd += [output_m4b]
|
116 |
+
|
117 |
+
subprocess.run(ffmpeg_cmd, check=True)
|
118 |
+
|
119 |
+
|
120 |
+
|
121 |
+
# Main logic
|
122 |
+
chapter_files = sorted([os.path.join(input_dir, f) for f in os.listdir(input_dir) if f.endswith('.wav')], key=sort_key)
|
123 |
+
temp_dir = tempfile.gettempdir()
|
124 |
+
temp_combined_wav = os.path.join(temp_dir, 'combined.wav')
|
125 |
+
metadata_file = os.path.join(temp_dir, 'metadata.txt')
|
126 |
+
cover_image = extract_metadata_and_cover(ebook_file)
|
127 |
+
output_m4b = os.path.join(output_dir, os.path.splitext(os.path.basename(ebook_file))[0] + '.m4b')
|
128 |
+
|
129 |
+
combine_wav_files(chapter_files, temp_combined_wav)
|
130 |
+
generate_ffmpeg_metadata(chapter_files, metadata_file)
|
131 |
+
create_m4b(temp_combined_wav, metadata_file, cover_image, output_m4b)
|
132 |
+
|
133 |
+
# Cleanup
|
134 |
+
if os.path.exists(temp_combined_wav):
|
135 |
+
os.remove(temp_combined_wav)
|
136 |
+
if os.path.exists(metadata_file):
|
137 |
+
os.remove(metadata_file)
|
138 |
+
if cover_image and os.path.exists(cover_image):
|
139 |
+
os.remove(cover_image)
|
140 |
+
|
141 |
+
# Example usage
|
142 |
+
# create_m4b_from_chapters('path_to_chapter_wavs', 'path_to_ebook_file', 'path_to_output_dir')
|
143 |
+
|
144 |
+
|
145 |
+
|
146 |
+
|
147 |
+
|
148 |
+
|
149 |
+
#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
|
150 |
+
import os
|
151 |
+
import subprocess
|
152 |
+
import ebooklib
|
153 |
+
from ebooklib import epub
|
154 |
+
from bs4 import BeautifulSoup
|
155 |
+
import re
|
156 |
+
import csv
|
157 |
+
import nltk
|
158 |
+
|
159 |
+
# Only run the main script if Value is True
|
160 |
+
def create_chapter_labeled_book(ebook_file_path):
|
161 |
+
# Function to ensure the existence of a directory
|
162 |
+
def ensure_directory(directory_path):
|
163 |
+
if not os.path.exists(directory_path):
|
164 |
+
os.makedirs(directory_path)
|
165 |
+
print(f"Created directory: {directory_path}")
|
166 |
+
|
167 |
+
ensure_directory(os.path.join(".", 'Working_files', 'Book'))
|
168 |
+
|
169 |
+
def convert_to_epub(input_path, output_path):
|
170 |
+
# Convert the ebook to EPUB format using Calibre's ebook-convert
|
171 |
+
try:
|
172 |
+
subprocess.run(['ebook-convert', input_path, output_path], check=True)
|
173 |
+
except subprocess.CalledProcessError as e:
|
174 |
+
print(f"An error occurred while converting the eBook: {e}")
|
175 |
+
return False
|
176 |
+
return True
|
177 |
+
|
178 |
+
def save_chapters_as_text(epub_path):
|
179 |
+
# Create the directory if it doesn't exist
|
180 |
+
directory = os.path.join(".", "Working_files", "temp_ebook")
|
181 |
+
ensure_directory(directory)
|
182 |
+
|
183 |
+
# Open the EPUB file
|
184 |
+
book = epub.read_epub(epub_path)
|
185 |
+
|
186 |
+
previous_chapter_text = ''
|
187 |
+
previous_filename = ''
|
188 |
+
chapter_counter = 0
|
189 |
+
|
190 |
+
# Iterate through the items in the EPUB file
|
191 |
+
for item in book.get_items():
|
192 |
+
if item.get_type() == ebooklib.ITEM_DOCUMENT:
|
193 |
+
# Use BeautifulSoup to parse HTML content
|
194 |
+
soup = BeautifulSoup(item.get_content(), 'html.parser')
|
195 |
+
text = soup.get_text()
|
196 |
+
|
197 |
+
# Check if the text is not empty
|
198 |
+
if text.strip():
|
199 |
+
if len(text) < 2300 and previous_filename:
|
200 |
+
# Append text to the previous chapter if it's short
|
201 |
+
with open(previous_filename, 'a', encoding='utf-8') as file:
|
202 |
+
file.write('\n' + text)
|
203 |
+
else:
|
204 |
+
# Create a new chapter file and increment the counter
|
205 |
+
previous_filename = os.path.join(directory, f"chapter_{chapter_counter}.txt")
|
206 |
+
chapter_counter += 1
|
207 |
+
with open(previous_filename, 'w', encoding='utf-8') as file:
|
208 |
+
file.write(text)
|
209 |
+
print(f"Saved chapter: {previous_filename}")
|
210 |
+
|
211 |
+
# Example usage
|
212 |
+
input_ebook = ebook_file_path # Replace with your eBook file path
|
213 |
+
output_epub = os.path.join(".", "Working_files", "temp.epub")
|
214 |
+
|
215 |
+
|
216 |
+
if os.path.exists(output_epub):
|
217 |
+
os.remove(output_epub)
|
218 |
+
print(f"File {output_epub} has been removed.")
|
219 |
+
else:
|
220 |
+
print(f"The file {output_epub} does not exist.")
|
221 |
+
|
222 |
+
if convert_to_epub(input_ebook, output_epub):
|
223 |
+
save_chapters_as_text(output_epub)
|
224 |
+
|
225 |
+
# Download the necessary NLTK data (if not already present)
|
226 |
+
nltk.download('punkt')
|
227 |
+
|
228 |
+
def process_chapter_files(folder_path, output_csv):
|
229 |
+
with open(output_csv, 'w', newline='', encoding='utf-8') as csvfile:
|
230 |
+
writer = csv.writer(csvfile)
|
231 |
+
# Write the header row
|
232 |
+
writer.writerow(['Text', 'Start Location', 'End Location', 'Is Quote', 'Speaker', 'Chapter'])
|
233 |
+
|
234 |
+
# Process each chapter file
|
235 |
+
chapter_files = sorted(os.listdir(folder_path), key=lambda x: int(x.split('_')[1].split('.')[0]))
|
236 |
+
for filename in chapter_files:
|
237 |
+
if filename.startswith('chapter_') and filename.endswith('.txt'):
|
238 |
+
chapter_number = int(filename.split('_')[1].split('.')[0])
|
239 |
+
file_path = os.path.join(folder_path, filename)
|
240 |
+
|
241 |
+
try:
|
242 |
+
with open(file_path, 'r', encoding='utf-8') as file:
|
243 |
+
text = file.read()
|
244 |
+
# Insert "NEWCHAPTERABC" at the beginning of each chapter's text
|
245 |
+
if text:
|
246 |
+
text = "NEWCHAPTERABC" + text
|
247 |
+
sentences = nltk.tokenize.sent_tokenize(text)
|
248 |
+
for sentence in sentences:
|
249 |
+
start_location = text.find(sentence)
|
250 |
+
end_location = start_location + len(sentence)
|
251 |
+
writer.writerow([sentence, start_location, end_location, 'True', 'Narrator', chapter_number])
|
252 |
+
except Exception as e:
|
253 |
+
print(f"Error processing file {filename}: {e}")
|
254 |
+
|
255 |
+
# Example usage
|
256 |
+
folder_path = os.path.join(".", "Working_files", "temp_ebook")
|
257 |
+
output_csv = os.path.join(".", "Working_files", "Book", "Other_book.csv")
|
258 |
+
|
259 |
+
process_chapter_files(folder_path, output_csv)
|
260 |
+
|
261 |
+
def sort_key(filename):
|
262 |
+
"""Extract chapter number for sorting."""
|
263 |
+
match = re.search(r'chapter_(\d+)\.txt', filename)
|
264 |
+
return int(match.group(1)) if match else 0
|
265 |
+
|
266 |
+
def combine_chapters(input_folder, output_file):
|
267 |
+
# Create the output folder if it doesn't exist
|
268 |
+
os.makedirs(os.path.dirname(output_file), exist_ok=True)
|
269 |
+
|
270 |
+
# List all txt files and sort them by chapter number
|
271 |
+
files = [f for f in os.listdir(input_folder) if f.endswith('.txt')]
|
272 |
+
sorted_files = sorted(files, key=sort_key)
|
273 |
+
|
274 |
+
with open(output_file, 'w', encoding='utf-8') as outfile: # Specify UTF-8 encoding here
|
275 |
+
for i, filename in enumerate(sorted_files):
|
276 |
+
with open(os.path.join(input_folder, filename), 'r', encoding='utf-8') as infile: # And here
|
277 |
+
outfile.write(infile.read())
|
278 |
+
# Add the marker unless it's the last file
|
279 |
+
if i < len(sorted_files) - 1:
|
280 |
+
outfile.write("\nNEWCHAPTERABC\n")
|
281 |
+
|
282 |
+
# Paths
|
283 |
+
input_folder = os.path.join(".", 'Working_files', 'temp_ebook')
|
284 |
+
output_file = os.path.join(".", 'Working_files', 'Book', 'Chapter_Book.txt')
|
285 |
+
|
286 |
+
|
287 |
+
# Combine the chapters
|
288 |
+
combine_chapters(input_folder, output_file)
|
289 |
+
|
290 |
+
ensure_directory(os.path.join(".", "Working_files", "Book"))
|
291 |
+
|
292 |
+
|
293 |
+
#create_chapter_labeled_book()
|
294 |
+
|
295 |
+
|
296 |
+
|
297 |
+
|
298 |
+
import os
|
299 |
+
import subprocess
|
300 |
+
import sys
|
301 |
+
import torchaudio
|
302 |
+
|
303 |
+
# Check if Calibre's ebook-convert tool is installed
|
304 |
+
def calibre_installed():
|
305 |
+
try:
|
306 |
+
subprocess.run(['ebook-convert', '--version'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
307 |
+
return True
|
308 |
+
except FileNotFoundError:
|
309 |
+
print("Calibre is not installed. Please install Calibre for this functionality.")
|
310 |
+
return False
|
311 |
+
|
312 |
+
|
313 |
+
import os
|
314 |
+
import torch
|
315 |
+
from TTS.api import TTS
|
316 |
+
from nltk.tokenize import sent_tokenize
|
317 |
+
from pydub import AudioSegment
|
318 |
+
# Assuming split_long_sentence and wipe_folder are defined elsewhere in your code
|
319 |
+
|
320 |
+
default_target_voice_path = "default_voice.wav" # Ensure this is a valid path
|
321 |
+
default_language_code = "en"
|
322 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
323 |
+
|
324 |
+
def combine_wav_files(input_directory, output_directory, file_name):
|
325 |
+
# Ensure that the output directory exists, create it if necessary
|
326 |
+
os.makedirs(output_directory, exist_ok=True)
|
327 |
+
|
328 |
+
# Specify the output file path
|
329 |
+
output_file_path = os.path.join(output_directory, file_name)
|
330 |
+
|
331 |
+
# Initialize an empty audio segment
|
332 |
+
combined_audio = AudioSegment.empty()
|
333 |
+
|
334 |
+
# Get a list of all .wav files in the specified input directory and sort them
|
335 |
+
input_file_paths = sorted(
|
336 |
+
[os.path.join(input_directory, f) for f in os.listdir(input_directory) if f.endswith(".wav")],
|
337 |
+
key=lambda f: int(''.join(filter(str.isdigit, f)))
|
338 |
+
)
|
339 |
+
|
340 |
+
# Sequentially append each file to the combined_audio
|
341 |
+
for input_file_path in input_file_paths:
|
342 |
+
audio_segment = AudioSegment.from_wav(input_file_path)
|
343 |
+
combined_audio += audio_segment
|
344 |
+
|
345 |
+
# Export the combined audio to the output file path
|
346 |
+
combined_audio.export(output_file_path, format='wav')
|
347 |
+
|
348 |
+
print(f"Combined audio saved to {output_file_path}")
|
349 |
+
|
350 |
+
# Function to split long strings into parts
|
351 |
+
def split_long_sentence(sentence, max_length=249, max_pauses=10):
|
352 |
+
"""
|
353 |
+
Splits a sentence into parts based on length or number of pauses without recursion.
|
354 |
+
|
355 |
+
:param sentence: The sentence to split.
|
356 |
+
:param max_length: Maximum allowed length of a sentence.
|
357 |
+
:param max_pauses: Maximum allowed number of pauses in a sentence.
|
358 |
+
:return: A list of sentence parts that meet the criteria.
|
359 |
+
"""
|
360 |
+
parts = []
|
361 |
+
while len(sentence) > max_length or sentence.count(',') + sentence.count(';') + sentence.count('.') > max_pauses:
|
362 |
+
possible_splits = [i for i, char in enumerate(sentence) if char in ',;.' and i < max_length]
|
363 |
+
if possible_splits:
|
364 |
+
# Find the best place to split the sentence, preferring the last possible split to keep parts longer
|
365 |
+
split_at = possible_splits[-1] + 1
|
366 |
+
else:
|
367 |
+
# If no punctuation to split on within max_length, split at max_length
|
368 |
+
split_at = max_length
|
369 |
+
|
370 |
+
# Split the sentence and add the first part to the list
|
371 |
+
parts.append(sentence[:split_at].strip())
|
372 |
+
sentence = sentence[split_at:].strip()
|
373 |
+
|
374 |
+
# Add the remaining part of the sentence
|
375 |
+
parts.append(sentence)
|
376 |
+
return parts
|
377 |
+
|
378 |
+
"""
|
379 |
+
if 'tts' not in locals():
|
380 |
+
tts = TTS(selected_tts_model, progress_bar=True).to(device)
|
381 |
+
"""
|
382 |
+
from tqdm import tqdm
|
383 |
+
|
384 |
+
# Convert chapters to audio using XTTS
|
385 |
+
def convert_chapters_to_audio(chapters_dir, output_audio_dir, target_voice_path=None, language=None):
|
386 |
+
selected_tts_model = "tts_models/multilingual/multi-dataset/xtts_v2"
|
387 |
+
tts = TTS(selected_tts_model, progress_bar=False).to(device) # Set progress_bar to False to avoid nested progress bars
|
388 |
+
|
389 |
+
if not os.path.exists(output_audio_dir):
|
390 |
+
os.makedirs(output_audio_dir)
|
391 |
+
|
392 |
+
for chapter_file in sorted(os.listdir(chapters_dir)):
|
393 |
+
if chapter_file.endswith('.txt'):
|
394 |
+
# Extract chapter number from the filename
|
395 |
+
match = re.search(r"chapter_(\d+).txt", chapter_file)
|
396 |
+
if match:
|
397 |
+
chapter_num = int(match.group(1))
|
398 |
+
else:
|
399 |
+
print(f"Skipping file {chapter_file} as it does not match the expected format.")
|
400 |
+
continue
|
401 |
+
|
402 |
+
chapter_path = os.path.join(chapters_dir, chapter_file)
|
403 |
+
output_file_name = f"audio_chapter_{chapter_num}.wav"
|
404 |
+
output_file_path = os.path.join(output_audio_dir, output_file_name)
|
405 |
+
temp_audio_directory = os.path.join(".", "Working_files", "temp")
|
406 |
+
os.makedirs(temp_audio_directory, exist_ok=True)
|
407 |
+
temp_count = 0
|
408 |
+
|
409 |
+
with open(chapter_path, 'r', encoding='utf-8') as file:
|
410 |
+
chapter_text = file.read()
|
411 |
+
# Use the specified language model for sentence tokenization
|
412 |
+
sentences = sent_tokenize(chapter_text, language='italian' if language == 'it' else 'english')
|
413 |
+
for sentence in tqdm(sentences, desc=f"Chapter {chapter_num}"):
|
414 |
+
fragments = []
|
415 |
+
if language == "en":
|
416 |
+
fragments = split_long_sentence(sentence, max_length=249, max_pauses=10)
|
417 |
+
if language == "it":
|
418 |
+
fragments = split_long_sentence(sentence, max_length=213, max_pauses=10)
|
419 |
+
for fragment in fragments:
|
420 |
+
if fragment != "": #a hot fix to avoid blank fragments
|
421 |
+
print(f"Generating fragment: {fragment}...")
|
422 |
+
fragment_file_path = os.path.join(temp_audio_directory, f"{temp_count}.wav")
|
423 |
+
speaker_wav_path = target_voice_path if target_voice_path else default_target_voice_path
|
424 |
+
language_code = language if language else default_language_code
|
425 |
+
tts.tts_to_file(text=fragment, file_path=fragment_file_path, speaker_wav=speaker_wav_path, language=language_code)
|
426 |
+
temp_count += 1
|
427 |
+
|
428 |
+
combine_wav_files(temp_audio_directory, output_audio_dir, output_file_name)
|
429 |
+
wipe_folder(temp_audio_directory)
|
430 |
+
print(f"Converted chapter {chapter_num} to audio.")
|
431 |
+
|
432 |
+
|
433 |
+
|
434 |
+
# Main execution flow
|
435 |
+
if __name__ == "__main__":
|
436 |
+
if len(sys.argv) < 2:
|
437 |
+
print("Usage: python script.py <ebook_file_path> [target_voice_file_path]")
|
438 |
+
sys.exit(1)
|
439 |
+
|
440 |
+
ebook_file_path = sys.argv[1]
|
441 |
+
target_voice = sys.argv[2] if len(sys.argv) > 2 else None
|
442 |
+
language = sys.argv[3] if len(sys.argv) > 3 else None
|
443 |
+
|
444 |
+
if not calibre_installed():
|
445 |
+
sys.exit(1)
|
446 |
+
|
447 |
+
working_files = os.path.join(".","Working_files", "temp_ebook")
|
448 |
+
full_folder_working_files =os.path.join(".","Working_files")
|
449 |
+
chapters_directory = os.path.join(".","Working_files", "temp_ebook")
|
450 |
+
output_audio_directory = os.path.join(".", 'Chapter_wav_files')
|
451 |
+
|
452 |
+
print("Wiping and removeing Working_files folder...")
|
453 |
+
remove_folder_with_contents(full_folder_working_files)
|
454 |
+
|
455 |
+
print("Wiping and and removeing chapter_wav_files folder...")
|
456 |
+
remove_folder_with_contents(output_audio_directory)
|
457 |
+
|
458 |
+
create_chapter_labeled_book(ebook_file_path)
|
459 |
+
audiobook_output_path = os.path.join(".", "Audiobooks")
|
460 |
+
print(f"{chapters_directory}||||{output_audio_directory}|||||{target_voice}")
|
461 |
+
convert_chapters_to_audio(chapters_directory, output_audio_directory, target_voice, language)
|
462 |
+
create_m4b_from_chapters(output_audio_directory, ebook_file_path, audiobook_output_path)
|
Notebooks/Kaggel Archive Code/kaggle-ebook2audiobook-demo.ipynb
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.13","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"nvidiaTeslaT4","dataSources":[],"dockerImageVersionId":30733,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"Install depdenencies","metadata":{}},{"cell_type":"code","source":"#!DEBIAN_FRONTEND=noninteractive\n!sudo apt-get update # && sudo apt-get -y upgrade\n!sudo apt-get -y install libegl1 \n!sudo apt-get -y install libopengl0\n!sudo apt-get -y install libxcb-cursor0\n!sudo -v && wget -nv -O- https://download.calibre-ebook.com/linux-installer.sh | sudo sh /dev/stdin\n!sudo apt-get install -y ffmpeg\n!pip install tts pydub nltk beautifulsoup4 ebooklib tqdm\n!pip install numpy==1.26.4","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2024-06-17T21:17:43.474429Z","iopub.execute_input":"2024-06-17T21:17:43.474679Z","iopub.status.idle":"2024-06-17T21:20:20.992799Z","shell.execute_reply.started":"2024-06-17T21:17:43.474655Z","shell.execute_reply":"2024-06-17T21:20:20.991791Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Download modified ebook2audiobookXTTS\nhttps://github.com/Rihcus/ebook2audiobookXTTS\n\nOrigional unmodified version\nhttps://github.com/DrewThomasson/ebook2audiobookXTTS","metadata":{}},{"cell_type":"code","source":"!git clone https://github.com/Rihcus/ebook2audiobookXTTS","metadata":{"execution":{"iopub.status.busy":"2024-03-25T23:22:24.156772Z","iopub.execute_input":"2024-03-25T23:22:24.157618Z","iopub.status.idle":"2024-03-25T23:22:26.202486Z","shell.execute_reply.started":"2024-03-25T23:22:24.157577Z","shell.execute_reply":"2024-03-25T23:22:26.201179Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"(optional) Uploading your own epub book.\n\nBy default this notebook will use a sample epub book for testing/demo. \n\nIf you want to use your own book you will need to create a private kaggle data set, upload your epub to it, attach it to this notebook, and uncomment the two lines of code bellow, and update the data set path","metadata":{}},{"cell_type":"code","source":"# !cp -r /kaggle/input/<name of your attached dataset>/*.epub /kaggle/working/ebook2audiobookXTTS #copy your custom book\n# !rm /kaggle/working/ebook2audiobookXTTS/demo_mini_story_chapters_Drew.epub #remove default sample book","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"This to install xtts_v2 models","metadata":{}},{"cell_type":"code","source":"import os\nos.environ[\"COQUI_TOS_AGREED\"] = \"1\"\n\n!cd /kaggle/working/ebook2audiobookXTTS && tts --model_name tts_models/multilingual/multi-dataset/xtts_v2 --text \"test\" --speaker_wav ./4.wav --language_idx en --use_cuda true","metadata":{"execution":{"iopub.status.busy":"2024-03-25T23:23:15.626677Z","iopub.execute_input":"2024-03-25T23:23:15.627585Z","iopub.status.idle":"2024-03-25T23:27:40.712856Z","shell.execute_reply.started":"2024-03-25T23:23:15.627548Z","shell.execute_reply":"2024-03-25T23:27:40.711852Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"This is a modified version of ebook2audiobookXTTS. \n\n- p1.py only runs the first part ebook2audiobookXTTS and generates chapter txts (I commented out other parts)\n - https://github.com/Rihcus/ebook2audiobookXTTS/blob/main/p1.py\n- Worker_2T4.sh as a basic attempt at multigpu support. The 4 argument processes of ebook2audiobook will be run in parallel\n - Worker_2T4 will try to divide the chapter in even groups based on number of workers (ex 4 group 4 workers)\n - It will try to divy up the work between kaggles two T4 GPUS\n - I'm not sure how much of a difference it makes since kaggles cpu limitations\n \nhttps://github.com/Rihcus/ebook2audiobookXTTS/blob/main/Worker_2T4.sh\n\nhttps://github.com/Rihcus/ebook2audiobookXTTS/blob/main/p2a_worker_gpu1.py\n\nhttps://github.com/Rihcus/ebook2audiobookXTTS/blob/main/p2a_worker_gpu2.py","metadata":{}},{"cell_type":"code","source":"!cd /kaggle/working/ebook2audiobookXTTS && python p1.py \"$(ls ./*.epub)\" \"4.wav\" \"en\"\n!cd /kaggle/working/ebook2audiobookXTTS && bash Worker_2T4.sh 4","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"p3.py runs the final ffmpeg command. ffmpeg has been a bit buggy\nhttps://github.com/Rihcus/ebook2audiobookXTTS/blob/main/p3.py","metadata":{}},{"cell_type":"code","source":"!cd /kaggle/working/ebook2audiobookXTTS && python p3.py \"$(ls ./*.epub)\" \"4.wav\" \"en\"","metadata":{},"execution_count":null,"outputs":[]}]}
|
Notebooks/Kaggel Archive Code/p1.py
ADDED
@@ -0,0 +1,462 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
nltk.download('punkt') # Make sure to download the necessary models
|
14 |
+
def is_folder_empty(folder_path):
|
15 |
+
if os.path.exists(folder_path) and os.path.isdir(folder_path):
|
16 |
+
# List directory contents
|
17 |
+
if not os.listdir(folder_path):
|
18 |
+
return True # The folder is empty
|
19 |
+
else:
|
20 |
+
return False # The folder is not empty
|
21 |
+
else:
|
22 |
+
print(f"The path {folder_path} is not a valid folder.")
|
23 |
+
return None # The path is not a valid folder
|
24 |
+
|
25 |
+
def remove_folder_with_contents(folder_path):
|
26 |
+
try:
|
27 |
+
shutil.rmtree(folder_path)
|
28 |
+
print(f"Successfully removed {folder_path} and all of its contents.")
|
29 |
+
except Exception as e:
|
30 |
+
print(f"Error removing {folder_path}: {e}")
|
31 |
+
|
32 |
+
|
33 |
+
|
34 |
+
|
35 |
+
def wipe_folder(folder_path):
|
36 |
+
# Check if the folder exists
|
37 |
+
if not os.path.exists(folder_path):
|
38 |
+
print(f"The folder {folder_path} does not exist.")
|
39 |
+
return
|
40 |
+
|
41 |
+
# Iterate over all the items in the given folder
|
42 |
+
for item in os.listdir(folder_path):
|
43 |
+
item_path = os.path.join(folder_path, item)
|
44 |
+
# If it's a file, remove it and print a message
|
45 |
+
if os.path.isfile(item_path):
|
46 |
+
os.remove(item_path)
|
47 |
+
print(f"Removed file: {item_path}")
|
48 |
+
# If it's a directory, remove it recursively and print a message
|
49 |
+
elif os.path.isdir(item_path):
|
50 |
+
shutil.rmtree(item_path)
|
51 |
+
print(f"Removed directory and its contents: {item_path}")
|
52 |
+
|
53 |
+
print(f"All contents wiped from {folder_path}.")
|
54 |
+
|
55 |
+
|
56 |
+
# Example usage
|
57 |
+
# folder_to_wipe = 'path_to_your_folder'
|
58 |
+
# wipe_folder(folder_to_wipe)
|
59 |
+
|
60 |
+
|
61 |
+
def create_m4b_from_chapters(input_dir, ebook_file, output_dir):
|
62 |
+
# Function to sort chapters based on their numeric order
|
63 |
+
def sort_key(chapter_file):
|
64 |
+
numbers = re.findall(r'\d+', chapter_file)
|
65 |
+
return int(numbers[0]) if numbers else 0
|
66 |
+
|
67 |
+
# Extract metadata and cover image from the eBook file
|
68 |
+
def extract_metadata_and_cover(ebook_path):
|
69 |
+
try:
|
70 |
+
cover_path = ebook_path.rsplit('.', 1)[0] + '.jpg'
|
71 |
+
subprocess.run(['ebook-meta', ebook_path, '--get-cover', cover_path], check=True)
|
72 |
+
if os.path.exists(cover_path):
|
73 |
+
return cover_path
|
74 |
+
except Exception as e:
|
75 |
+
print(f"Error extracting eBook metadata or cover: {e}")
|
76 |
+
return None
|
77 |
+
# Combine WAV files into a single file
|
78 |
+
def combine_wav_files(chapter_files, output_path):
|
79 |
+
# Initialize an empty audio segment
|
80 |
+
combined_audio = AudioSegment.empty()
|
81 |
+
|
82 |
+
# Sequentially append each file to the combined_audio
|
83 |
+
for chapter_file in chapter_files:
|
84 |
+
audio_segment = AudioSegment.from_wav(chapter_file)
|
85 |
+
combined_audio += audio_segment
|
86 |
+
# Export the combined audio to the output file path
|
87 |
+
combined_audio.export(output_path, format='wav')
|
88 |
+
print(f"Combined audio saved to {output_path}")
|
89 |
+
|
90 |
+
# Function to generate metadata for M4B chapters
|
91 |
+
def generate_ffmpeg_metadata(chapter_files, metadata_file):
|
92 |
+
with open(metadata_file, 'w') as file:
|
93 |
+
file.write(';FFMETADATA1\n')
|
94 |
+
start_time = 0
|
95 |
+
for index, chapter_file in enumerate(chapter_files):
|
96 |
+
duration_ms = len(AudioSegment.from_wav(chapter_file))
|
97 |
+
file.write(f'[CHAPTER]\nTIMEBASE=1/1000\nSTART={start_time}\n')
|
98 |
+
file.write(f'END={start_time + duration_ms}\ntitle=Chapter {index + 1}\n')
|
99 |
+
start_time += duration_ms
|
100 |
+
|
101 |
+
# Generate the final M4B file using ffmpeg
|
102 |
+
def create_m4b(combined_wav, metadata_file, cover_image, output_m4b):
|
103 |
+
# Ensure the output directory exists
|
104 |
+
os.makedirs(os.path.dirname(output_m4b), exist_ok=True)
|
105 |
+
|
106 |
+
ffmpeg_cmd = ['ffmpeg', '-i', combined_wav, '-i', metadata_file]
|
107 |
+
if cover_image:
|
108 |
+
ffmpeg_cmd += ['-i', cover_image, '-map', '0:a', '-map', '2:v']
|
109 |
+
else:
|
110 |
+
ffmpeg_cmd += ['-map', '0:a']
|
111 |
+
|
112 |
+
ffmpeg_cmd += ['-map_metadata', '1', '-c:a', 'aac', '-b:a', '192k']
|
113 |
+
if cover_image:
|
114 |
+
ffmpeg_cmd += ['-c:v', 'png', '-disposition:v', 'attached_pic']
|
115 |
+
ffmpeg_cmd += [output_m4b]
|
116 |
+
|
117 |
+
subprocess.run(ffmpeg_cmd, check=True)
|
118 |
+
|
119 |
+
|
120 |
+
|
121 |
+
# Main logic
|
122 |
+
chapter_files = sorted([os.path.join(input_dir, f) for f in os.listdir(input_dir) if f.endswith('.wav')], key=sort_key)
|
123 |
+
temp_dir = tempfile.gettempdir()
|
124 |
+
temp_combined_wav = os.path.join(temp_dir, 'combined.wav')
|
125 |
+
metadata_file = os.path.join(temp_dir, 'metadata.txt')
|
126 |
+
cover_image = extract_metadata_and_cover(ebook_file)
|
127 |
+
output_m4b = os.path.join(output_dir, os.path.splitext(os.path.basename(ebook_file))[0] + '.m4b')
|
128 |
+
|
129 |
+
combine_wav_files(chapter_files, temp_combined_wav)
|
130 |
+
generate_ffmpeg_metadata(chapter_files, metadata_file)
|
131 |
+
create_m4b(temp_combined_wav, metadata_file, cover_image, output_m4b)
|
132 |
+
|
133 |
+
# Cleanup
|
134 |
+
if os.path.exists(temp_combined_wav):
|
135 |
+
os.remove(temp_combined_wav)
|
136 |
+
if os.path.exists(metadata_file):
|
137 |
+
os.remove(metadata_file)
|
138 |
+
if cover_image and os.path.exists(cover_image):
|
139 |
+
os.remove(cover_image)
|
140 |
+
|
141 |
+
# Example usage
|
142 |
+
# create_m4b_from_chapters('path_to_chapter_wavs', 'path_to_ebook_file', 'path_to_output_dir')
|
143 |
+
|
144 |
+
|
145 |
+
|
146 |
+
|
147 |
+
|
148 |
+
|
149 |
+
#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
|
150 |
+
import os
|
151 |
+
import subprocess
|
152 |
+
import ebooklib
|
153 |
+
from ebooklib import epub
|
154 |
+
from bs4 import BeautifulSoup
|
155 |
+
import re
|
156 |
+
import csv
|
157 |
+
import nltk
|
158 |
+
|
159 |
+
# Only run the main script if Value is True
|
160 |
+
def create_chapter_labeled_book(ebook_file_path):
|
161 |
+
# Function to ensure the existence of a directory
|
162 |
+
def ensure_directory(directory_path):
|
163 |
+
if not os.path.exists(directory_path):
|
164 |
+
os.makedirs(directory_path)
|
165 |
+
print(f"Created directory: {directory_path}")
|
166 |
+
|
167 |
+
ensure_directory(os.path.join(".", 'Working_files', 'Book'))
|
168 |
+
|
169 |
+
def convert_to_epub(input_path, output_path):
|
170 |
+
# Convert the ebook to EPUB format using Calibre's ebook-convert
|
171 |
+
try:
|
172 |
+
subprocess.run(['ebook-convert', input_path, output_path], check=True)
|
173 |
+
except subprocess.CalledProcessError as e:
|
174 |
+
print(f"An error occurred while converting the eBook: {e}")
|
175 |
+
return False
|
176 |
+
return True
|
177 |
+
|
178 |
+
def save_chapters_as_text(epub_path):
|
179 |
+
# Create the directory if it doesn't exist
|
180 |
+
directory = os.path.join(".", "Working_files", "temp_ebook")
|
181 |
+
ensure_directory(directory)
|
182 |
+
|
183 |
+
# Open the EPUB file
|
184 |
+
book = epub.read_epub(epub_path)
|
185 |
+
|
186 |
+
previous_chapter_text = ''
|
187 |
+
previous_filename = ''
|
188 |
+
chapter_counter = 0
|
189 |
+
|
190 |
+
# Iterate through the items in the EPUB file
|
191 |
+
for item in book.get_items():
|
192 |
+
if item.get_type() == ebooklib.ITEM_DOCUMENT:
|
193 |
+
# Use BeautifulSoup to parse HTML content
|
194 |
+
soup = BeautifulSoup(item.get_content(), 'html.parser')
|
195 |
+
text = soup.get_text()
|
196 |
+
|
197 |
+
# Check if the text is not empty
|
198 |
+
if text.strip():
|
199 |
+
if len(text) < 2300 and previous_filename:
|
200 |
+
# Append text to the previous chapter if it's short
|
201 |
+
with open(previous_filename, 'a', encoding='utf-8') as file:
|
202 |
+
file.write('\n' + text)
|
203 |
+
else:
|
204 |
+
# Create a new chapter file and increment the counter
|
205 |
+
previous_filename = os.path.join(directory, f"chapter_{chapter_counter}.txt")
|
206 |
+
chapter_counter += 1
|
207 |
+
with open(previous_filename, 'w', encoding='utf-8') as file:
|
208 |
+
file.write(text)
|
209 |
+
print(f"Saved chapter: {previous_filename}")
|
210 |
+
|
211 |
+
# Example usage
|
212 |
+
input_ebook = ebook_file_path # Replace with your eBook file path
|
213 |
+
output_epub = os.path.join(".", "Working_files", "temp.epub")
|
214 |
+
|
215 |
+
|
216 |
+
if os.path.exists(output_epub):
|
217 |
+
os.remove(output_epub)
|
218 |
+
print(f"File {output_epub} has been removed.")
|
219 |
+
else:
|
220 |
+
print(f"The file {output_epub} does not exist.")
|
221 |
+
|
222 |
+
if convert_to_epub(input_ebook, output_epub):
|
223 |
+
save_chapters_as_text(output_epub)
|
224 |
+
|
225 |
+
# Download the necessary NLTK data (if not already present)
|
226 |
+
nltk.download('punkt')
|
227 |
+
|
228 |
+
def process_chapter_files(folder_path, output_csv):
|
229 |
+
with open(output_csv, 'w', newline='', encoding='utf-8') as csvfile:
|
230 |
+
writer = csv.writer(csvfile)
|
231 |
+
# Write the header row
|
232 |
+
writer.writerow(['Text', 'Start Location', 'End Location', 'Is Quote', 'Speaker', 'Chapter'])
|
233 |
+
|
234 |
+
# Process each chapter file
|
235 |
+
chapter_files = sorted(os.listdir(folder_path), key=lambda x: int(x.split('_')[1].split('.')[0]))
|
236 |
+
for filename in chapter_files:
|
237 |
+
if filename.startswith('chapter_') and filename.endswith('.txt'):
|
238 |
+
chapter_number = int(filename.split('_')[1].split('.')[0])
|
239 |
+
file_path = os.path.join(folder_path, filename)
|
240 |
+
|
241 |
+
try:
|
242 |
+
with open(file_path, 'r', encoding='utf-8') as file:
|
243 |
+
text = file.read()
|
244 |
+
# Insert "NEWCHAPTERABC" at the beginning of each chapter's text
|
245 |
+
if text:
|
246 |
+
text = "NEWCHAPTERABC" + text
|
247 |
+
sentences = nltk.tokenize.sent_tokenize(text)
|
248 |
+
for sentence in sentences:
|
249 |
+
start_location = text.find(sentence)
|
250 |
+
end_location = start_location + len(sentence)
|
251 |
+
writer.writerow([sentence, start_location, end_location, 'True', 'Narrator', chapter_number])
|
252 |
+
except Exception as e:
|
253 |
+
print(f"Error processing file {filename}: {e}")
|
254 |
+
|
255 |
+
# Example usage
|
256 |
+
folder_path = os.path.join(".", "Working_files", "temp_ebook")
|
257 |
+
output_csv = os.path.join(".", "Working_files", "Book", "Other_book.csv")
|
258 |
+
|
259 |
+
process_chapter_files(folder_path, output_csv)
|
260 |
+
|
261 |
+
def sort_key(filename):
|
262 |
+
"""Extract chapter number for sorting."""
|
263 |
+
match = re.search(r'chapter_(\d+)\.txt', filename)
|
264 |
+
return int(match.group(1)) if match else 0
|
265 |
+
|
266 |
+
def combine_chapters(input_folder, output_file):
|
267 |
+
# Create the output folder if it doesn't exist
|
268 |
+
os.makedirs(os.path.dirname(output_file), exist_ok=True)
|
269 |
+
|
270 |
+
# List all txt files and sort them by chapter number
|
271 |
+
files = [f for f in os.listdir(input_folder) if f.endswith('.txt')]
|
272 |
+
sorted_files = sorted(files, key=sort_key)
|
273 |
+
|
274 |
+
with open(output_file, 'w', encoding='utf-8') as outfile: # Specify UTF-8 encoding here
|
275 |
+
for i, filename in enumerate(sorted_files):
|
276 |
+
with open(os.path.join(input_folder, filename), 'r', encoding='utf-8') as infile: # And here
|
277 |
+
outfile.write(infile.read())
|
278 |
+
# Add the marker unless it's the last file
|
279 |
+
if i < len(sorted_files) - 1:
|
280 |
+
outfile.write("\nNEWCHAPTERABC\n")
|
281 |
+
|
282 |
+
# Paths
|
283 |
+
input_folder = os.path.join(".", 'Working_files', 'temp_ebook')
|
284 |
+
output_file = os.path.join(".", 'Working_files', 'Book', 'Chapter_Book.txt')
|
285 |
+
|
286 |
+
|
287 |
+
# Combine the chapters
|
288 |
+
combine_chapters(input_folder, output_file)
|
289 |
+
|
290 |
+
ensure_directory(os.path.join(".", "Working_files", "Book"))
|
291 |
+
|
292 |
+
|
293 |
+
#create_chapter_labeled_book()
|
294 |
+
|
295 |
+
|
296 |
+
|
297 |
+
|
298 |
+
import os
|
299 |
+
import subprocess
|
300 |
+
import sys
|
301 |
+
import torchaudio
|
302 |
+
|
303 |
+
# Check if Calibre's ebook-convert tool is installed
|
304 |
+
def calibre_installed():
|
305 |
+
try:
|
306 |
+
subprocess.run(['ebook-convert', '--version'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
307 |
+
return True
|
308 |
+
except FileNotFoundError:
|
309 |
+
print("Calibre is not installed. Please install Calibre for this functionality.")
|
310 |
+
return False
|
311 |
+
|
312 |
+
|
313 |
+
import os
|
314 |
+
import torch
|
315 |
+
from TTS.api import TTS
|
316 |
+
from nltk.tokenize import sent_tokenize
|
317 |
+
from pydub import AudioSegment
|
318 |
+
# Assuming split_long_sentence and wipe_folder are defined elsewhere in your code
|
319 |
+
|
320 |
+
default_target_voice_path = "default_voice.wav" # Ensure this is a valid path
|
321 |
+
default_language_code = "en"
|
322 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
323 |
+
|
324 |
+
def combine_wav_files(input_directory, output_directory, file_name):
|
325 |
+
# Ensure that the output directory exists, create it if necessary
|
326 |
+
os.makedirs(output_directory, exist_ok=True)
|
327 |
+
|
328 |
+
# Specify the output file path
|
329 |
+
output_file_path = os.path.join(output_directory, file_name)
|
330 |
+
|
331 |
+
# Initialize an empty audio segment
|
332 |
+
combined_audio = AudioSegment.empty()
|
333 |
+
|
334 |
+
# Get a list of all .wav files in the specified input directory and sort them
|
335 |
+
input_file_paths = sorted(
|
336 |
+
[os.path.join(input_directory, f) for f in os.listdir(input_directory) if f.endswith(".wav")],
|
337 |
+
key=lambda f: int(''.join(filter(str.isdigit, f)))
|
338 |
+
)
|
339 |
+
|
340 |
+
# Sequentially append each file to the combined_audio
|
341 |
+
for input_file_path in input_file_paths:
|
342 |
+
audio_segment = AudioSegment.from_wav(input_file_path)
|
343 |
+
combined_audio += audio_segment
|
344 |
+
|
345 |
+
# Export the combined audio to the output file path
|
346 |
+
combined_audio.export(output_file_path, format='wav')
|
347 |
+
|
348 |
+
print(f"Combined audio saved to {output_file_path}")
|
349 |
+
|
350 |
+
# Function to split long strings into parts
|
351 |
+
def split_long_sentence(sentence, max_length=249, max_pauses=10):
|
352 |
+
"""
|
353 |
+
Splits a sentence into parts based on length or number of pauses without recursion.
|
354 |
+
|
355 |
+
:param sentence: The sentence to split.
|
356 |
+
:param max_length: Maximum allowed length of a sentence.
|
357 |
+
:param max_pauses: Maximum allowed number of pauses in a sentence.
|
358 |
+
:return: A list of sentence parts that meet the criteria.
|
359 |
+
"""
|
360 |
+
parts = []
|
361 |
+
while len(sentence) > max_length or sentence.count(',') + sentence.count(';') + sentence.count('.') > max_pauses:
|
362 |
+
possible_splits = [i for i, char in enumerate(sentence) if char in ',;.' and i < max_length]
|
363 |
+
if possible_splits:
|
364 |
+
# Find the best place to split the sentence, preferring the last possible split to keep parts longer
|
365 |
+
split_at = possible_splits[-1] + 1
|
366 |
+
else:
|
367 |
+
# If no punctuation to split on within max_length, split at max_length
|
368 |
+
split_at = max_length
|
369 |
+
|
370 |
+
# Split the sentence and add the first part to the list
|
371 |
+
parts.append(sentence[:split_at].strip())
|
372 |
+
sentence = sentence[split_at:].strip()
|
373 |
+
|
374 |
+
# Add the remaining part of the sentence
|
375 |
+
parts.append(sentence)
|
376 |
+
return parts
|
377 |
+
|
378 |
+
"""
|
379 |
+
if 'tts' not in locals():
|
380 |
+
tts = TTS(selected_tts_model, progress_bar=True).to(device)
|
381 |
+
"""
|
382 |
+
from tqdm import tqdm
|
383 |
+
|
384 |
+
# Convert chapters to audio using XTTS
|
385 |
+
def convert_chapters_to_audio(chapters_dir, output_audio_dir, target_voice_path=None, language=None):
|
386 |
+
selected_tts_model = "tts_models/multilingual/multi-dataset/xtts_v2"
|
387 |
+
tts = TTS(selected_tts_model, progress_bar=False).to(device) # Set progress_bar to False to avoid nested progress bars
|
388 |
+
|
389 |
+
if not os.path.exists(output_audio_dir):
|
390 |
+
os.makedirs(output_audio_dir)
|
391 |
+
|
392 |
+
for chapter_file in sorted(os.listdir(chapters_dir)):
|
393 |
+
if chapter_file.endswith('.txt'):
|
394 |
+
# Extract chapter number from the filename
|
395 |
+
match = re.search(r"chapter_(\d+).txt", chapter_file)
|
396 |
+
if match:
|
397 |
+
chapter_num = int(match.group(1))
|
398 |
+
else:
|
399 |
+
print(f"Skipping file {chapter_file} as it does not match the expected format.")
|
400 |
+
continue
|
401 |
+
|
402 |
+
chapter_path = os.path.join(chapters_dir, chapter_file)
|
403 |
+
output_file_name = f"audio_chapter_{chapter_num}.wav"
|
404 |
+
output_file_path = os.path.join(output_audio_dir, output_file_name)
|
405 |
+
temp_audio_directory = os.path.join(".", "Working_files", "temp")
|
406 |
+
os.makedirs(temp_audio_directory, exist_ok=True)
|
407 |
+
temp_count = 0
|
408 |
+
|
409 |
+
with open(chapter_path, 'r', encoding='utf-8') as file:
|
410 |
+
chapter_text = file.read()
|
411 |
+
# Use the specified language model for sentence tokenization
|
412 |
+
sentences = sent_tokenize(chapter_text, language='italian' if language == 'it' else 'english')
|
413 |
+
for sentence in tqdm(sentences, desc=f"Chapter {chapter_num}"):
|
414 |
+
fragments = []
|
415 |
+
if language == "en":
|
416 |
+
fragments = split_long_sentence(sentence, max_length=249, max_pauses=10)
|
417 |
+
if language == "it":
|
418 |
+
fragments = split_long_sentence(sentence, max_length=213, max_pauses=10)
|
419 |
+
for fragment in fragments:
|
420 |
+
if fragment != "": #a hot fix to avoid blank fragments
|
421 |
+
print(f"Generating fragment: {fragment}...")
|
422 |
+
fragment_file_path = os.path.join(temp_audio_directory, f"{temp_count}.wav")
|
423 |
+
speaker_wav_path = target_voice_path if target_voice_path else default_target_voice_path
|
424 |
+
language_code = language if language else default_language_code
|
425 |
+
tts.tts_to_file(text=fragment, file_path=fragment_file_path, speaker_wav=speaker_wav_path, language=language_code)
|
426 |
+
temp_count += 1
|
427 |
+
|
428 |
+
combine_wav_files(temp_audio_directory, output_audio_dir, output_file_name)
|
429 |
+
wipe_folder(temp_audio_directory)
|
430 |
+
print(f"Converted chapter {chapter_num} to audio.")
|
431 |
+
|
432 |
+
|
433 |
+
|
434 |
+
# Main execution flow
|
435 |
+
if __name__ == "__main__":
|
436 |
+
if len(sys.argv) < 2:
|
437 |
+
print("Usage: python script.py <ebook_file_path> [target_voice_file_path]")
|
438 |
+
sys.exit(1)
|
439 |
+
|
440 |
+
ebook_file_path = sys.argv[1]
|
441 |
+
target_voice = sys.argv[2] if len(sys.argv) > 2 else None
|
442 |
+
language = sys.argv[3] if len(sys.argv) > 3 else None
|
443 |
+
|
444 |
+
if not calibre_installed():
|
445 |
+
sys.exit(1)
|
446 |
+
|
447 |
+
working_files = os.path.join(".","Working_files", "temp_ebook")
|
448 |
+
full_folder_working_files =os.path.join(".","Working_files")
|
449 |
+
chapters_directory = os.path.join(".","Working_files", "temp_ebook")
|
450 |
+
output_audio_directory = os.path.join(".", 'Chapter_wav_files')
|
451 |
+
|
452 |
+
print("Wiping and removeing Working_files folder...")
|
453 |
+
remove_folder_with_contents(full_folder_working_files)
|
454 |
+
|
455 |
+
print("Wiping and and removeing chapter_wav_files folder...")
|
456 |
+
remove_folder_with_contents(output_audio_directory)
|
457 |
+
|
458 |
+
create_chapter_labeled_book(ebook_file_path)
|
459 |
+
# audiobook_output_path = os.path.join(".", "Audiobooks")
|
460 |
+
# print(f"{chapters_directory}||||{output_audio_directory}|||||{target_voice}")
|
461 |
+
# convert_chapters_to_audio(chapters_directory, output_audio_directory, target_voice, language)
|
462 |
+
# create_m4b_from_chapters(output_audio_directory, ebook_file_path, audiobook_output_path)
|
Notebooks/Kaggel Archive Code/p2a_worker_gpu1.py
ADDED
@@ -0,0 +1,465 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
nltk.download('punkt') # Make sure to download the necessary models
|
14 |
+
def is_folder_empty(folder_path):
|
15 |
+
if os.path.exists(folder_path) and os.path.isdir(folder_path):
|
16 |
+
# List directory contents
|
17 |
+
if not os.listdir(folder_path):
|
18 |
+
return True # The folder is empty
|
19 |
+
else:
|
20 |
+
return False # The folder is not empty
|
21 |
+
else:
|
22 |
+
print(f"The path {folder_path} is not a valid folder.")
|
23 |
+
return None # The path is not a valid folder
|
24 |
+
|
25 |
+
def remove_folder_with_contents(folder_path):
|
26 |
+
try:
|
27 |
+
shutil.rmtree(folder_path)
|
28 |
+
print(f"Successfully removed {folder_path} and all of its contents.")
|
29 |
+
except Exception as e:
|
30 |
+
print(f"Error removing {folder_path}: {e}")
|
31 |
+
|
32 |
+
|
33 |
+
|
34 |
+
|
35 |
+
def wipe_folder(folder_path):
|
36 |
+
# Check if the folder exists
|
37 |
+
if not os.path.exists(folder_path):
|
38 |
+
print(f"The folder {folder_path} does not exist.")
|
39 |
+
return
|
40 |
+
|
41 |
+
# Iterate over all the items in the given folder
|
42 |
+
for item in os.listdir(folder_path):
|
43 |
+
item_path = os.path.join(folder_path, item)
|
44 |
+
# If it's a file, remove it and print a message
|
45 |
+
if os.path.isfile(item_path):
|
46 |
+
os.remove(item_path)
|
47 |
+
print(f"Removed file: {item_path}")
|
48 |
+
# If it's a directory, remove it recursively and print a message
|
49 |
+
elif os.path.isdir(item_path):
|
50 |
+
shutil.rmtree(item_path)
|
51 |
+
print(f"Removed directory and its contents: {item_path}")
|
52 |
+
|
53 |
+
print(f"All contents wiped from {folder_path}.")
|
54 |
+
|
55 |
+
|
56 |
+
# Example usage
|
57 |
+
# folder_to_wipe = 'path_to_your_folder'
|
58 |
+
# wipe_folder(folder_to_wipe)
|
59 |
+
|
60 |
+
|
61 |
+
def create_m4b_from_chapters(input_dir, ebook_file, output_dir):
|
62 |
+
# Function to sort chapters based on their numeric order
|
63 |
+
def sort_key(chapter_file):
|
64 |
+
numbers = re.findall(r'\d+', chapter_file)
|
65 |
+
return int(numbers[0]) if numbers else 0
|
66 |
+
|
67 |
+
# Extract metadata and cover image from the eBook file
|
68 |
+
def extract_metadata_and_cover(ebook_path):
|
69 |
+
try:
|
70 |
+
cover_path = ebook_path.rsplit('.', 1)[0] + '.jpg'
|
71 |
+
subprocess.run(['ebook-meta', ebook_path, '--get-cover', cover_path], check=True)
|
72 |
+
if os.path.exists(cover_path):
|
73 |
+
return cover_path
|
74 |
+
except Exception as e:
|
75 |
+
print(f"Error extracting eBook metadata or cover: {e}")
|
76 |
+
return None
|
77 |
+
# Combine WAV files into a single file
|
78 |
+
def combine_wav_files(chapter_files, output_path):
|
79 |
+
# Initialize an empty audio segment
|
80 |
+
combined_audio = AudioSegment.empty()
|
81 |
+
|
82 |
+
# Sequentially append each file to the combined_audio
|
83 |
+
for chapter_file in chapter_files:
|
84 |
+
audio_segment = AudioSegment.from_wav(chapter_file)
|
85 |
+
combined_audio += audio_segment
|
86 |
+
# Export the combined audio to the output file path
|
87 |
+
combined_audio.export(output_path, format='wav')
|
88 |
+
print(f"Combined audio saved to {output_path}")
|
89 |
+
|
90 |
+
# Function to generate metadata for M4B chapters
|
91 |
+
def generate_ffmpeg_metadata(chapter_files, metadata_file):
|
92 |
+
with open(metadata_file, 'w') as file:
|
93 |
+
file.write(';FFMETADATA1\n')
|
94 |
+
start_time = 0
|
95 |
+
for index, chapter_file in enumerate(chapter_files):
|
96 |
+
duration_ms = len(AudioSegment.from_wav(chapter_file))
|
97 |
+
file.write(f'[CHAPTER]\nTIMEBASE=1/1000\nSTART={start_time}\n')
|
98 |
+
file.write(f'END={start_time + duration_ms}\ntitle=Chapter {index + 1}\n')
|
99 |
+
start_time += duration_ms
|
100 |
+
|
101 |
+
# Generate the final M4B file using ffmpeg
|
102 |
+
def create_m4b(combined_wav, metadata_file, cover_image, output_m4b):
|
103 |
+
# Ensure the output directory exists
|
104 |
+
os.makedirs(os.path.dirname(output_m4b), exist_ok=True)
|
105 |
+
|
106 |
+
ffmpeg_cmd = ['ffmpeg', '-i', combined_wav, '-i', metadata_file]
|
107 |
+
if cover_image:
|
108 |
+
ffmpeg_cmd += ['-i', cover_image, '-map', '0:a', '-map', '2:v']
|
109 |
+
else:
|
110 |
+
ffmpeg_cmd += ['-map', '0:a']
|
111 |
+
|
112 |
+
ffmpeg_cmd += ['-map_metadata', '1', '-c:a', 'aac', '-b:a', '192k']
|
113 |
+
if cover_image:
|
114 |
+
ffmpeg_cmd += ['-c:v', 'png', '-disposition:v', 'attached_pic']
|
115 |
+
ffmpeg_cmd += [output_m4b]
|
116 |
+
|
117 |
+
subprocess.run(ffmpeg_cmd, check=True)
|
118 |
+
|
119 |
+
|
120 |
+
|
121 |
+
# Main logic
|
122 |
+
chapter_files = sorted([os.path.join(input_dir, f) for f in os.listdir(input_dir) if f.endswith('.wav')], key=sort_key)
|
123 |
+
temp_dir = tempfile.gettempdir()
|
124 |
+
temp_combined_wav = os.path.join(temp_dir, 'combined.wav')
|
125 |
+
metadata_file = os.path.join(temp_dir, 'metadata.txt')
|
126 |
+
cover_image = extract_metadata_and_cover(ebook_file)
|
127 |
+
output_m4b = os.path.join(output_dir, os.path.splitext(os.path.basename(ebook_file))[0] + '.m4b')
|
128 |
+
|
129 |
+
combine_wav_files(chapter_files, temp_combined_wav)
|
130 |
+
generate_ffmpeg_metadata(chapter_files, metadata_file)
|
131 |
+
create_m4b(temp_combined_wav, metadata_file, cover_image, output_m4b)
|
132 |
+
|
133 |
+
# Cleanup
|
134 |
+
if os.path.exists(temp_combined_wav):
|
135 |
+
os.remove(temp_combined_wav)
|
136 |
+
if os.path.exists(metadata_file):
|
137 |
+
os.remove(metadata_file)
|
138 |
+
if cover_image and os.path.exists(cover_image):
|
139 |
+
os.remove(cover_image)
|
140 |
+
|
141 |
+
# Example usage
|
142 |
+
# create_m4b_from_chapters('path_to_chapter_wavs', 'path_to_ebook_file', 'path_to_output_dir')
|
143 |
+
|
144 |
+
|
145 |
+
|
146 |
+
|
147 |
+
|
148 |
+
|
149 |
+
#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
|
150 |
+
#import os
|
151 |
+
#import subprocess
|
152 |
+
#import ebooklib
|
153 |
+
#from ebooklib import epub
|
154 |
+
#from bs4 import BeautifulSoup
|
155 |
+
#import re
|
156 |
+
#import csv
|
157 |
+
#import nltk
|
158 |
+
|
159 |
+
# Only run the main script if Value is True
|
160 |
+
def create_chapter_labeled_book(ebook_file_path):
|
161 |
+
# Function to ensure the existence of a directory
|
162 |
+
def ensure_directory(directory_path):
|
163 |
+
if not os.path.exists(directory_path):
|
164 |
+
os.makedirs(directory_path)
|
165 |
+
print(f"Created directory: {directory_path}")
|
166 |
+
|
167 |
+
ensure_directory(os.path.join(".", 'Working_files', 'Book'))
|
168 |
+
|
169 |
+
def convert_to_epub(input_path, output_path):
|
170 |
+
# Convert the ebook to EPUB format using Calibre's ebook-convert
|
171 |
+
try:
|
172 |
+
subprocess.run(['ebook-convert', input_path, output_path], check=True)
|
173 |
+
except subprocess.CalledProcessError as e:
|
174 |
+
print(f"An error occurred while converting the eBook: {e}")
|
175 |
+
return False
|
176 |
+
return True
|
177 |
+
|
178 |
+
def save_chapters_as_text(epub_path):
|
179 |
+
# Create the directory if it doesn't exist
|
180 |
+
directory = os.path.join(".", "Working_files", "temp_ebook")
|
181 |
+
ensure_directory(directory)
|
182 |
+
|
183 |
+
# Open the EPUB file
|
184 |
+
book = epub.read_epub(epub_path)
|
185 |
+
|
186 |
+
previous_chapter_text = ''
|
187 |
+
previous_filename = ''
|
188 |
+
chapter_counter = 0
|
189 |
+
|
190 |
+
# Iterate through the items in the EPUB file
|
191 |
+
for item in book.get_items():
|
192 |
+
if item.get_type() == ebooklib.ITEM_DOCUMENT:
|
193 |
+
# Use BeautifulSoup to parse HTML content
|
194 |
+
soup = BeautifulSoup(item.get_content(), 'html.parser')
|
195 |
+
text = soup.get_text()
|
196 |
+
|
197 |
+
# Check if the text is not empty
|
198 |
+
if text.strip():
|
199 |
+
if len(text) < 2300 and previous_filename:
|
200 |
+
# Append text to the previous chapter if it's short
|
201 |
+
with open(previous_filename, 'a', encoding='utf-8') as file:
|
202 |
+
file.write('\n' + text)
|
203 |
+
else:
|
204 |
+
# Create a new chapter file and increment the counter
|
205 |
+
previous_filename = os.path.join(directory, f"chapter_{chapter_counter}.txt")
|
206 |
+
chapter_counter += 1
|
207 |
+
with open(previous_filename, 'w', encoding='utf-8') as file:
|
208 |
+
file.write(text)
|
209 |
+
print(f"Saved chapter: {previous_filename}")
|
210 |
+
|
211 |
+
# Example usage
|
212 |
+
input_ebook = ebook_file_path # Replace with your eBook file path
|
213 |
+
output_epub = os.path.join(".", "Working_files", "temp.epub")
|
214 |
+
|
215 |
+
|
216 |
+
if os.path.exists(output_epub):
|
217 |
+
os.remove(output_epub)
|
218 |
+
print(f"File {output_epub} has been removed.")
|
219 |
+
else:
|
220 |
+
print(f"The file {output_epub} does not exist.")
|
221 |
+
|
222 |
+
if convert_to_epub(input_ebook, output_epub):
|
223 |
+
save_chapters_as_text(output_epub)
|
224 |
+
|
225 |
+
# Download the necessary NLTK data (if not already present)
|
226 |
+
nltk.download('punkt')
|
227 |
+
|
228 |
+
def process_chapter_files(folder_path, output_csv):
|
229 |
+
with open(output_csv, 'w', newline='', encoding='utf-8') as csvfile:
|
230 |
+
writer = csv.writer(csvfile)
|
231 |
+
# Write the header row
|
232 |
+
writer.writerow(['Text', 'Start Location', 'End Location', 'Is Quote', 'Speaker', 'Chapter'])
|
233 |
+
|
234 |
+
# Process each chapter file
|
235 |
+
chapter_files = sorted(os.listdir(folder_path), key=lambda x: int(x.split('_')[1].split('.')[0]))
|
236 |
+
for filename in chapter_files:
|
237 |
+
if filename.startswith('chapter_') and filename.endswith('.txt'):
|
238 |
+
chapter_number = int(filename.split('_')[1].split('.')[0])
|
239 |
+
file_path = os.path.join(folder_path, filename)
|
240 |
+
|
241 |
+
try:
|
242 |
+
with open(file_path, 'r', encoding='utf-8') as file:
|
243 |
+
text = file.read()
|
244 |
+
# Insert "NEWCHAPTERABC" at the beginning of each chapter's text
|
245 |
+
if text:
|
246 |
+
text = "NEWCHAPTERABC" + text
|
247 |
+
sentences = nltk.tokenize.sent_tokenize(text)
|
248 |
+
for sentence in sentences:
|
249 |
+
start_location = text.find(sentence)
|
250 |
+
end_location = start_location + len(sentence)
|
251 |
+
writer.writerow([sentence, start_location, end_location, 'True', 'Narrator', chapter_number])
|
252 |
+
except Exception as e:
|
253 |
+
print(f"Error processing file {filename}: {e}")
|
254 |
+
|
255 |
+
# Example usage
|
256 |
+
folder_path = os.path.join(".", "Working_files", "temp_ebook")
|
257 |
+
output_csv = os.path.join(".", "Working_files", "Book", "Other_book.csv")
|
258 |
+
|
259 |
+
process_chapter_files(folder_path, output_csv)
|
260 |
+
|
261 |
+
def sort_key(filename):
|
262 |
+
"""Extract chapter number for sorting."""
|
263 |
+
match = re.search(r'chapter_(\d+)\.txt', filename)
|
264 |
+
return int(match.group(1)) if match else 0
|
265 |
+
|
266 |
+
def combine_chapters(input_folder, output_file):
|
267 |
+
# Create the output folder if it doesn't exist
|
268 |
+
os.makedirs(os.path.dirname(output_file), exist_ok=True)
|
269 |
+
|
270 |
+
# List all txt files and sort them by chapter number
|
271 |
+
files = [f for f in os.listdir(input_folder) if f.endswith('.txt')]
|
272 |
+
sorted_files = sorted(files, key=sort_key)
|
273 |
+
|
274 |
+
with open(output_file, 'w', encoding='utf-8') as outfile: # Specify UTF-8 encoding here
|
275 |
+
for i, filename in enumerate(sorted_files):
|
276 |
+
with open(os.path.join(input_folder, filename), 'r', encoding='utf-8') as infile: # And here
|
277 |
+
outfile.write(infile.read())
|
278 |
+
# Add the marker unless it's the last file
|
279 |
+
if i < len(sorted_files) - 1:
|
280 |
+
outfile.write("\nNEWCHAPTERABC\n")
|
281 |
+
|
282 |
+
# Paths
|
283 |
+
input_folder = os.path.join(".", 'Working_files', 'temp_ebook')
|
284 |
+
output_file = os.path.join(".", 'Working_files', 'Book', 'Chapter_Book.txt')
|
285 |
+
|
286 |
+
|
287 |
+
# Combine the chapters
|
288 |
+
combine_chapters(input_folder, output_file)
|
289 |
+
|
290 |
+
ensure_directory(os.path.join(".", "Working_files", "Book"))
|
291 |
+
|
292 |
+
|
293 |
+
#create_chapter_labeled_book()
|
294 |
+
|
295 |
+
|
296 |
+
|
297 |
+
|
298 |
+
#import os
|
299 |
+
import subprocess
|
300 |
+
import sys
|
301 |
+
import torchaudio # not sure if this is needed
|
302 |
+
|
303 |
+
# Check if Calibre's ebook-convert tool is installed
|
304 |
+
def calibre_installed():
|
305 |
+
try:
|
306 |
+
subprocess.run(['ebook-convert', '--version'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
307 |
+
return True
|
308 |
+
except FileNotFoundError:
|
309 |
+
print("Calibre is not installed. Please install Calibre for this functionality.")
|
310 |
+
return False
|
311 |
+
|
312 |
+
|
313 |
+
import os
|
314 |
+
import torch
|
315 |
+
from TTS.api import TTS
|
316 |
+
from nltk.tokenize import sent_tokenize
|
317 |
+
from pydub import AudioSegment
|
318 |
+
# Assuming split_long_sentence and wipe_folder are defined elsewhere in your code
|
319 |
+
|
320 |
+
default_target_voice_path = "default_voice.wav" # Ensure this is a valid path
|
321 |
+
default_language_code = "en"
|
322 |
+
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
|
323 |
+
|
324 |
+
def combine_wav_files(input_directory, output_directory, file_name):
|
325 |
+
# Ensure that the output directory exists, create it if necessary
|
326 |
+
os.makedirs(output_directory, exist_ok=True)
|
327 |
+
|
328 |
+
# Specify the output file path
|
329 |
+
output_file_path = os.path.join(output_directory, file_name)
|
330 |
+
|
331 |
+
# Initialize an empty audio segment
|
332 |
+
combined_audio = AudioSegment.empty()
|
333 |
+
|
334 |
+
# Get a list of all .wav files in the specified input directory and sort them
|
335 |
+
input_file_paths = sorted(
|
336 |
+
[os.path.join(input_directory, f) for f in os.listdir(input_directory) if f.endswith(".wav")],
|
337 |
+
key=lambda f: int(''.join(filter(str.isdigit, f)))
|
338 |
+
)
|
339 |
+
|
340 |
+
# Sequentially append each file to the combined_audio
|
341 |
+
for input_file_path in input_file_paths:
|
342 |
+
audio_segment = AudioSegment.from_wav(input_file_path)
|
343 |
+
combined_audio += audio_segment
|
344 |
+
|
345 |
+
# Export the combined audio to the output file path
|
346 |
+
combined_audio.export(output_file_path, format='wav')
|
347 |
+
|
348 |
+
print(f"Combined audio saved to {output_file_path}")
|
349 |
+
|
350 |
+
# Function to split long strings into parts
|
351 |
+
def split_long_sentence(sentence, max_length=249, max_pauses=10):
|
352 |
+
"""
|
353 |
+
Splits a sentence into parts based on length or number of pauses without recursion.
|
354 |
+
|
355 |
+
:param sentence: The sentence to split.
|
356 |
+
:param max_length: Maximum allowed length of a sentence.
|
357 |
+
:param max_pauses: Maximum allowed number of pauses in a sentence.
|
358 |
+
:return: A list of sentence parts that meet the criteria.
|
359 |
+
"""
|
360 |
+
parts = []
|
361 |
+
while len(sentence) > max_length or sentence.count(',') + sentence.count(';') + sentence.count('.') > max_pauses:
|
362 |
+
possible_splits = [i for i, char in enumerate(sentence) if char in ',;.' and i < max_length]
|
363 |
+
if possible_splits:
|
364 |
+
# Find the best place to split the sentence, preferring the last possible split to keep parts longer
|
365 |
+
split_at = possible_splits[-1] + 1
|
366 |
+
else:
|
367 |
+
# If no punctuation to split on within max_length, split at max_length
|
368 |
+
split_at = max_length
|
369 |
+
|
370 |
+
# Split the sentence and add the first part to the list
|
371 |
+
parts.append(sentence[:split_at].strip())
|
372 |
+
sentence = sentence[split_at:].strip()
|
373 |
+
|
374 |
+
# Add the remaining part of the sentence
|
375 |
+
parts.append(sentence)
|
376 |
+
return parts
|
377 |
+
|
378 |
+
"""
|
379 |
+
if 'tts' not in locals():
|
380 |
+
tts = TTS(selected_tts_model, progress_bar=True).to(device)
|
381 |
+
"""
|
382 |
+
from tqdm import tqdm
|
383 |
+
|
384 |
+
# Convert chapters to audio using XTTS
|
385 |
+
def convert_chapters_to_audio(chapters_dir, output_audio_dir, target_voice_path=None, language=None):
|
386 |
+
selected_tts_model = "tts_models/multilingual/multi-dataset/xtts_v2"
|
387 |
+
tts = TTS(selected_tts_model, progress_bar=False).to(device) # Set progress_bar to False to avoid nested progress bars
|
388 |
+
|
389 |
+
if not os.path.exists(output_audio_dir):
|
390 |
+
os.makedirs(output_audio_dir)
|
391 |
+
|
392 |
+
for chapter_file in sorted(os.listdir(chapters_dir)):
|
393 |
+
if chapter_file.endswith('.txt'):
|
394 |
+
# Extract chapter number from the filename
|
395 |
+
match = re.search(r"chapter_(\d+).txt", chapter_file)
|
396 |
+
if match:
|
397 |
+
chapter_num = int(match.group(1))
|
398 |
+
else:
|
399 |
+
print(f"Skipping file {chapter_file} as it does not match the expected format.")
|
400 |
+
continue
|
401 |
+
|
402 |
+
chapter_path = os.path.join(chapters_dir, chapter_file)
|
403 |
+
output_file_name = f"audio_chapter_{chapter_num}.wav"
|
404 |
+
output_file_path = os.path.join(output_audio_dir, output_file_name)
|
405 |
+
# temp_audio_directory = os.path.join(".", "Working_files", "temp")
|
406 |
+
temp_audio_directory = os.path.join(".", "Operator",worker_num, "temp")
|
407 |
+
os.makedirs(temp_audio_directory, exist_ok=True)
|
408 |
+
temp_count = 0
|
409 |
+
|
410 |
+
with open(chapter_path, 'r', encoding='utf-8') as file:
|
411 |
+
chapter_text = file.read()
|
412 |
+
# Use the specified language model for sentence tokenization
|
413 |
+
sentences = sent_tokenize(chapter_text, language='italian' if language == 'it' else 'english')
|
414 |
+
for sentence in tqdm(sentences, desc=f"Chapter {chapter_num}"):
|
415 |
+
fragments = []
|
416 |
+
if language == "en":
|
417 |
+
fragments = split_long_sentence(sentence, max_length=249, max_pauses=10)
|
418 |
+
if language == "it":
|
419 |
+
fragments = split_long_sentence(sentence, max_length=213, max_pauses=10)
|
420 |
+
for fragment in fragments:
|
421 |
+
if fragment != "": #a hot fix to avoid blank fragments
|
422 |
+
print(f"Generating fragment: {fragment}...")
|
423 |
+
fragment_file_path = os.path.join(temp_audio_directory, f"{temp_count}.wav")
|
424 |
+
speaker_wav_path = target_voice_path if target_voice_path else default_target_voice_path
|
425 |
+
language_code = language if language else default_language_code
|
426 |
+
tts.tts_to_file(text=fragment, file_path=fragment_file_path, speaker_wav=speaker_wav_path, language=language_code)
|
427 |
+
temp_count += 1
|
428 |
+
|
429 |
+
combine_wav_files(temp_audio_directory, output_audio_dir, output_file_name)
|
430 |
+
wipe_folder(temp_audio_directory)
|
431 |
+
print(f"Converted chapter {chapter_num} to audio.")
|
432 |
+
|
433 |
+
|
434 |
+
|
435 |
+
# Main execution flow
|
436 |
+
if __name__ == "__main__":
|
437 |
+
# if len(sys.argv) < 2:
|
438 |
+
# print("Usage: python script.py <ebook_file_path> [target_voice_file_path]")
|
439 |
+
# sys.exit(1)
|
440 |
+
|
441 |
+
worker_num = sys.argv[1] #to let the script know which temp dir its using in operator
|
442 |
+
# ebook_file_path = sys.argv[1]
|
443 |
+
target_voice = "./4.wav" # sys.argv[2] if len(sys.argv) > 2 else None
|
444 |
+
language = "en" # sys.argv[3] if len(sys.argv) > 3 else None
|
445 |
+
|
446 |
+
# if not calibre_installed():
|
447 |
+
# sys.exit(1)
|
448 |
+
|
449 |
+
working_files = os.path.join(".","Working_files", "temp_ebook")
|
450 |
+
full_folder_working_files =os.path.join(".","Working_files")
|
451 |
+
# chapters_directory = os.path.join(".","Working_files", "temp_ebook")
|
452 |
+
chapters_directory = os.path.join(".","Operator",worker_num, "temp_ebook")
|
453 |
+
output_audio_directory = os.path.join(".", 'Chapter_wav_files')
|
454 |
+
|
455 |
+
# print("Wiping and removeing Working_files folder...")
|
456 |
+
# remove_folder_with_contents(full_folder_working_files)
|
457 |
+
#
|
458 |
+
# print("Wiping and and removeing chapter_wav_files folder...")
|
459 |
+
# remove_folder_with_contents(output_audio_directory)
|
460 |
+
|
461 |
+
# create_chapter_labeled_book(ebook_file_path)
|
462 |
+
audiobook_output_path = os.path.join(".", "Audiobooks")
|
463 |
+
print(f"{chapters_directory}||||{output_audio_directory}|||||{target_voice}")
|
464 |
+
convert_chapters_to_audio(chapters_directory, output_audio_directory, target_voice, language)
|
465 |
+
# create_m4b_from_chapters(output_audio_directory, ebook_file_path, audiobook_output_path)
|
Notebooks/Kaggel Archive Code/p2a_worker_gpu2.py
ADDED
@@ -0,0 +1,465 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
nltk.download('punkt') # Make sure to download the necessary models
|
14 |
+
def is_folder_empty(folder_path):
|
15 |
+
if os.path.exists(folder_path) and os.path.isdir(folder_path):
|
16 |
+
# List directory contents
|
17 |
+
if not os.listdir(folder_path):
|
18 |
+
return True # The folder is empty
|
19 |
+
else:
|
20 |
+
return False # The folder is not empty
|
21 |
+
else:
|
22 |
+
print(f"The path {folder_path} is not a valid folder.")
|
23 |
+
return None # The path is not a valid folder
|
24 |
+
|
25 |
+
def remove_folder_with_contents(folder_path):
|
26 |
+
try:
|
27 |
+
shutil.rmtree(folder_path)
|
28 |
+
print(f"Successfully removed {folder_path} and all of its contents.")
|
29 |
+
except Exception as e:
|
30 |
+
print(f"Error removing {folder_path}: {e}")
|
31 |
+
|
32 |
+
|
33 |
+
|
34 |
+
|
35 |
+
def wipe_folder(folder_path):
|
36 |
+
# Check if the folder exists
|
37 |
+
if not os.path.exists(folder_path):
|
38 |
+
print(f"The folder {folder_path} does not exist.")
|
39 |
+
return
|
40 |
+
|
41 |
+
# Iterate over all the items in the given folder
|
42 |
+
for item in os.listdir(folder_path):
|
43 |
+
item_path = os.path.join(folder_path, item)
|
44 |
+
# If it's a file, remove it and print a message
|
45 |
+
if os.path.isfile(item_path):
|
46 |
+
os.remove(item_path)
|
47 |
+
print(f"Removed file: {item_path}")
|
48 |
+
# If it's a directory, remove it recursively and print a message
|
49 |
+
elif os.path.isdir(item_path):
|
50 |
+
shutil.rmtree(item_path)
|
51 |
+
print(f"Removed directory and its contents: {item_path}")
|
52 |
+
|
53 |
+
print(f"All contents wiped from {folder_path}.")
|
54 |
+
|
55 |
+
|
56 |
+
# Example usage
|
57 |
+
# folder_to_wipe = 'path_to_your_folder'
|
58 |
+
# wipe_folder(folder_to_wipe)
|
59 |
+
|
60 |
+
|
61 |
+
def create_m4b_from_chapters(input_dir, ebook_file, output_dir):
|
62 |
+
# Function to sort chapters based on their numeric order
|
63 |
+
def sort_key(chapter_file):
|
64 |
+
numbers = re.findall(r'\d+', chapter_file)
|
65 |
+
return int(numbers[0]) if numbers else 0
|
66 |
+
|
67 |
+
# Extract metadata and cover image from the eBook file
|
68 |
+
def extract_metadata_and_cover(ebook_path):
|
69 |
+
try:
|
70 |
+
cover_path = ebook_path.rsplit('.', 1)[0] + '.jpg'
|
71 |
+
subprocess.run(['ebook-meta', ebook_path, '--get-cover', cover_path], check=True)
|
72 |
+
if os.path.exists(cover_path):
|
73 |
+
return cover_path
|
74 |
+
except Exception as e:
|
75 |
+
print(f"Error extracting eBook metadata or cover: {e}")
|
76 |
+
return None
|
77 |
+
# Combine WAV files into a single file
|
78 |
+
def combine_wav_files(chapter_files, output_path):
|
79 |
+
# Initialize an empty audio segment
|
80 |
+
combined_audio = AudioSegment.empty()
|
81 |
+
|
82 |
+
# Sequentially append each file to the combined_audio
|
83 |
+
for chapter_file in chapter_files:
|
84 |
+
audio_segment = AudioSegment.from_wav(chapter_file)
|
85 |
+
combined_audio += audio_segment
|
86 |
+
# Export the combined audio to the output file path
|
87 |
+
combined_audio.export(output_path, format='wav')
|
88 |
+
print(f"Combined audio saved to {output_path}")
|
89 |
+
|
90 |
+
# Function to generate metadata for M4B chapters
|
91 |
+
def generate_ffmpeg_metadata(chapter_files, metadata_file):
|
92 |
+
with open(metadata_file, 'w') as file:
|
93 |
+
file.write(';FFMETADATA1\n')
|
94 |
+
start_time = 0
|
95 |
+
for index, chapter_file in enumerate(chapter_files):
|
96 |
+
duration_ms = len(AudioSegment.from_wav(chapter_file))
|
97 |
+
file.write(f'[CHAPTER]\nTIMEBASE=1/1000\nSTART={start_time}\n')
|
98 |
+
file.write(f'END={start_time + duration_ms}\ntitle=Chapter {index + 1}\n')
|
99 |
+
start_time += duration_ms
|
100 |
+
|
101 |
+
# Generate the final M4B file using ffmpeg
|
102 |
+
def create_m4b(combined_wav, metadata_file, cover_image, output_m4b):
|
103 |
+
# Ensure the output directory exists
|
104 |
+
os.makedirs(os.path.dirname(output_m4b), exist_ok=True)
|
105 |
+
|
106 |
+
ffmpeg_cmd = ['ffmpeg', '-i', combined_wav, '-i', metadata_file]
|
107 |
+
if cover_image:
|
108 |
+
ffmpeg_cmd += ['-i', cover_image, '-map', '0:a', '-map', '2:v']
|
109 |
+
else:
|
110 |
+
ffmpeg_cmd += ['-map', '0:a']
|
111 |
+
|
112 |
+
ffmpeg_cmd += ['-map_metadata', '1', '-c:a', 'aac', '-b:a', '192k']
|
113 |
+
if cover_image:
|
114 |
+
ffmpeg_cmd += ['-c:v', 'png', '-disposition:v', 'attached_pic']
|
115 |
+
ffmpeg_cmd += [output_m4b]
|
116 |
+
|
117 |
+
subprocess.run(ffmpeg_cmd, check=True)
|
118 |
+
|
119 |
+
|
120 |
+
|
121 |
+
# Main logic
|
122 |
+
chapter_files = sorted([os.path.join(input_dir, f) for f in os.listdir(input_dir) if f.endswith('.wav')], key=sort_key)
|
123 |
+
temp_dir = tempfile.gettempdir()
|
124 |
+
temp_combined_wav = os.path.join(temp_dir, 'combined.wav')
|
125 |
+
metadata_file = os.path.join(temp_dir, 'metadata.txt')
|
126 |
+
cover_image = extract_metadata_and_cover(ebook_file)
|
127 |
+
output_m4b = os.path.join(output_dir, os.path.splitext(os.path.basename(ebook_file))[0] + '.m4b')
|
128 |
+
|
129 |
+
combine_wav_files(chapter_files, temp_combined_wav)
|
130 |
+
generate_ffmpeg_metadata(chapter_files, metadata_file)
|
131 |
+
create_m4b(temp_combined_wav, metadata_file, cover_image, output_m4b)
|
132 |
+
|
133 |
+
# Cleanup
|
134 |
+
if os.path.exists(temp_combined_wav):
|
135 |
+
os.remove(temp_combined_wav)
|
136 |
+
if os.path.exists(metadata_file):
|
137 |
+
os.remove(metadata_file)
|
138 |
+
if cover_image and os.path.exists(cover_image):
|
139 |
+
os.remove(cover_image)
|
140 |
+
|
141 |
+
# Example usage
|
142 |
+
# create_m4b_from_chapters('path_to_chapter_wavs', 'path_to_ebook_file', 'path_to_output_dir')
|
143 |
+
|
144 |
+
|
145 |
+
|
146 |
+
|
147 |
+
|
148 |
+
|
149 |
+
#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
|
150 |
+
#import os
|
151 |
+
#import subprocess
|
152 |
+
#import ebooklib
|
153 |
+
#from ebooklib import epub
|
154 |
+
#from bs4 import BeautifulSoup
|
155 |
+
#import re
|
156 |
+
#import csv
|
157 |
+
#import nltk
|
158 |
+
|
159 |
+
# Only run the main script if Value is True
|
160 |
+
def create_chapter_labeled_book(ebook_file_path):
|
161 |
+
# Function to ensure the existence of a directory
|
162 |
+
def ensure_directory(directory_path):
|
163 |
+
if not os.path.exists(directory_path):
|
164 |
+
os.makedirs(directory_path)
|
165 |
+
print(f"Created directory: {directory_path}")
|
166 |
+
|
167 |
+
ensure_directory(os.path.join(".", 'Working_files', 'Book'))
|
168 |
+
|
169 |
+
def convert_to_epub(input_path, output_path):
|
170 |
+
# Convert the ebook to EPUB format using Calibre's ebook-convert
|
171 |
+
try:
|
172 |
+
subprocess.run(['ebook-convert', input_path, output_path], check=True)
|
173 |
+
except subprocess.CalledProcessError as e:
|
174 |
+
print(f"An error occurred while converting the eBook: {e}")
|
175 |
+
return False
|
176 |
+
return True
|
177 |
+
|
178 |
+
def save_chapters_as_text(epub_path):
|
179 |
+
# Create the directory if it doesn't exist
|
180 |
+
directory = os.path.join(".", "Working_files", "temp_ebook")
|
181 |
+
ensure_directory(directory)
|
182 |
+
|
183 |
+
# Open the EPUB file
|
184 |
+
book = epub.read_epub(epub_path)
|
185 |
+
|
186 |
+
previous_chapter_text = ''
|
187 |
+
previous_filename = ''
|
188 |
+
chapter_counter = 0
|
189 |
+
|
190 |
+
# Iterate through the items in the EPUB file
|
191 |
+
for item in book.get_items():
|
192 |
+
if item.get_type() == ebooklib.ITEM_DOCUMENT:
|
193 |
+
# Use BeautifulSoup to parse HTML content
|
194 |
+
soup = BeautifulSoup(item.get_content(), 'html.parser')
|
195 |
+
text = soup.get_text()
|
196 |
+
|
197 |
+
# Check if the text is not empty
|
198 |
+
if text.strip():
|
199 |
+
if len(text) < 2300 and previous_filename:
|
200 |
+
# Append text to the previous chapter if it's short
|
201 |
+
with open(previous_filename, 'a', encoding='utf-8') as file:
|
202 |
+
file.write('\n' + text)
|
203 |
+
else:
|
204 |
+
# Create a new chapter file and increment the counter
|
205 |
+
previous_filename = os.path.join(directory, f"chapter_{chapter_counter}.txt")
|
206 |
+
chapter_counter += 1
|
207 |
+
with open(previous_filename, 'w', encoding='utf-8') as file:
|
208 |
+
file.write(text)
|
209 |
+
print(f"Saved chapter: {previous_filename}")
|
210 |
+
|
211 |
+
# Example usage
|
212 |
+
input_ebook = ebook_file_path # Replace with your eBook file path
|
213 |
+
output_epub = os.path.join(".", "Working_files", "temp.epub")
|
214 |
+
|
215 |
+
|
216 |
+
if os.path.exists(output_epub):
|
217 |
+
os.remove(output_epub)
|
218 |
+
print(f"File {output_epub} has been removed.")
|
219 |
+
else:
|
220 |
+
print(f"The file {output_epub} does not exist.")
|
221 |
+
|
222 |
+
if convert_to_epub(input_ebook, output_epub):
|
223 |
+
save_chapters_as_text(output_epub)
|
224 |
+
|
225 |
+
# Download the necessary NLTK data (if not already present)
|
226 |
+
nltk.download('punkt')
|
227 |
+
|
228 |
+
def process_chapter_files(folder_path, output_csv):
|
229 |
+
with open(output_csv, 'w', newline='', encoding='utf-8') as csvfile:
|
230 |
+
writer = csv.writer(csvfile)
|
231 |
+
# Write the header row
|
232 |
+
writer.writerow(['Text', 'Start Location', 'End Location', 'Is Quote', 'Speaker', 'Chapter'])
|
233 |
+
|
234 |
+
# Process each chapter file
|
235 |
+
chapter_files = sorted(os.listdir(folder_path), key=lambda x: int(x.split('_')[1].split('.')[0]))
|
236 |
+
for filename in chapter_files:
|
237 |
+
if filename.startswith('chapter_') and filename.endswith('.txt'):
|
238 |
+
chapter_number = int(filename.split('_')[1].split('.')[0])
|
239 |
+
file_path = os.path.join(folder_path, filename)
|
240 |
+
|
241 |
+
try:
|
242 |
+
with open(file_path, 'r', encoding='utf-8') as file:
|
243 |
+
text = file.read()
|
244 |
+
# Insert "NEWCHAPTERABC" at the beginning of each chapter's text
|
245 |
+
if text:
|
246 |
+
text = "NEWCHAPTERABC" + text
|
247 |
+
sentences = nltk.tokenize.sent_tokenize(text)
|
248 |
+
for sentence in sentences:
|
249 |
+
start_location = text.find(sentence)
|
250 |
+
end_location = start_location + len(sentence)
|
251 |
+
writer.writerow([sentence, start_location, end_location, 'True', 'Narrator', chapter_number])
|
252 |
+
except Exception as e:
|
253 |
+
print(f"Error processing file {filename}: {e}")
|
254 |
+
|
255 |
+
# Example usage
|
256 |
+
folder_path = os.path.join(".", "Working_files", "temp_ebook")
|
257 |
+
output_csv = os.path.join(".", "Working_files", "Book", "Other_book.csv")
|
258 |
+
|
259 |
+
process_chapter_files(folder_path, output_csv)
|
260 |
+
|
261 |
+
def sort_key(filename):
|
262 |
+
"""Extract chapter number for sorting."""
|
263 |
+
match = re.search(r'chapter_(\d+)\.txt', filename)
|
264 |
+
return int(match.group(1)) if match else 0
|
265 |
+
|
266 |
+
def combine_chapters(input_folder, output_file):
|
267 |
+
# Create the output folder if it doesn't exist
|
268 |
+
os.makedirs(os.path.dirname(output_file), exist_ok=True)
|
269 |
+
|
270 |
+
# List all txt files and sort them by chapter number
|
271 |
+
files = [f for f in os.listdir(input_folder) if f.endswith('.txt')]
|
272 |
+
sorted_files = sorted(files, key=sort_key)
|
273 |
+
|
274 |
+
with open(output_file, 'w', encoding='utf-8') as outfile: # Specify UTF-8 encoding here
|
275 |
+
for i, filename in enumerate(sorted_files):
|
276 |
+
with open(os.path.join(input_folder, filename), 'r', encoding='utf-8') as infile: # And here
|
277 |
+
outfile.write(infile.read())
|
278 |
+
# Add the marker unless it's the last file
|
279 |
+
if i < len(sorted_files) - 1:
|
280 |
+
outfile.write("\nNEWCHAPTERABC\n")
|
281 |
+
|
282 |
+
# Paths
|
283 |
+
input_folder = os.path.join(".", 'Working_files', 'temp_ebook')
|
284 |
+
output_file = os.path.join(".", 'Working_files', 'Book', 'Chapter_Book.txt')
|
285 |
+
|
286 |
+
|
287 |
+
# Combine the chapters
|
288 |
+
combine_chapters(input_folder, output_file)
|
289 |
+
|
290 |
+
ensure_directory(os.path.join(".", "Working_files", "Book"))
|
291 |
+
|
292 |
+
|
293 |
+
#create_chapter_labeled_book()
|
294 |
+
|
295 |
+
|
296 |
+
|
297 |
+
|
298 |
+
#import os
|
299 |
+
import subprocess
|
300 |
+
import sys
|
301 |
+
import torchaudio # not sure if this is needed
|
302 |
+
|
303 |
+
# Check if Calibre's ebook-convert tool is installed
|
304 |
+
def calibre_installed():
|
305 |
+
try:
|
306 |
+
subprocess.run(['ebook-convert', '--version'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
307 |
+
return True
|
308 |
+
except FileNotFoundError:
|
309 |
+
print("Calibre is not installed. Please install Calibre for this functionality.")
|
310 |
+
return False
|
311 |
+
|
312 |
+
|
313 |
+
import os
|
314 |
+
import torch
|
315 |
+
from TTS.api import TTS
|
316 |
+
from nltk.tokenize import sent_tokenize
|
317 |
+
from pydub import AudioSegment
|
318 |
+
# Assuming split_long_sentence and wipe_folder are defined elsewhere in your code
|
319 |
+
|
320 |
+
default_target_voice_path = "default_voice.wav" # Ensure this is a valid path
|
321 |
+
default_language_code = "en"
|
322 |
+
device = torch.device("cuda:1" if torch.cuda.is_available() else "cpu")
|
323 |
+
|
324 |
+
def combine_wav_files(input_directory, output_directory, file_name):
|
325 |
+
# Ensure that the output directory exists, create it if necessary
|
326 |
+
os.makedirs(output_directory, exist_ok=True)
|
327 |
+
|
328 |
+
# Specify the output file path
|
329 |
+
output_file_path = os.path.join(output_directory, file_name)
|
330 |
+
|
331 |
+
# Initialize an empty audio segment
|
332 |
+
combined_audio = AudioSegment.empty()
|
333 |
+
|
334 |
+
# Get a list of all .wav files in the specified input directory and sort them
|
335 |
+
input_file_paths = sorted(
|
336 |
+
[os.path.join(input_directory, f) for f in os.listdir(input_directory) if f.endswith(".wav")],
|
337 |
+
key=lambda f: int(''.join(filter(str.isdigit, f)))
|
338 |
+
)
|
339 |
+
|
340 |
+
# Sequentially append each file to the combined_audio
|
341 |
+
for input_file_path in input_file_paths:
|
342 |
+
audio_segment = AudioSegment.from_wav(input_file_path)
|
343 |
+
combined_audio += audio_segment
|
344 |
+
|
345 |
+
# Export the combined audio to the output file path
|
346 |
+
combined_audio.export(output_file_path, format='wav')
|
347 |
+
|
348 |
+
print(f"Combined audio saved to {output_file_path}")
|
349 |
+
|
350 |
+
# Function to split long strings into parts
|
351 |
+
def split_long_sentence(sentence, max_length=249, max_pauses=10):
|
352 |
+
"""
|
353 |
+
Splits a sentence into parts based on length or number of pauses without recursion.
|
354 |
+
|
355 |
+
:param sentence: The sentence to split.
|
356 |
+
:param max_length: Maximum allowed length of a sentence.
|
357 |
+
:param max_pauses: Maximum allowed number of pauses in a sentence.
|
358 |
+
:return: A list of sentence parts that meet the criteria.
|
359 |
+
"""
|
360 |
+
parts = []
|
361 |
+
while len(sentence) > max_length or sentence.count(',') + sentence.count(';') + sentence.count('.') > max_pauses:
|
362 |
+
possible_splits = [i for i, char in enumerate(sentence) if char in ',;.' and i < max_length]
|
363 |
+
if possible_splits:
|
364 |
+
# Find the best place to split the sentence, preferring the last possible split to keep parts longer
|
365 |
+
split_at = possible_splits[-1] + 1
|
366 |
+
else:
|
367 |
+
# If no punctuation to split on within max_length, split at max_length
|
368 |
+
split_at = max_length
|
369 |
+
|
370 |
+
# Split the sentence and add the first part to the list
|
371 |
+
parts.append(sentence[:split_at].strip())
|
372 |
+
sentence = sentence[split_at:].strip()
|
373 |
+
|
374 |
+
# Add the remaining part of the sentence
|
375 |
+
parts.append(sentence)
|
376 |
+
return parts
|
377 |
+
|
378 |
+
"""
|
379 |
+
if 'tts' not in locals():
|
380 |
+
tts = TTS(selected_tts_model, progress_bar=True).to(device)
|
381 |
+
"""
|
382 |
+
from tqdm import tqdm
|
383 |
+
|
384 |
+
# Convert chapters to audio using XTTS
|
385 |
+
def convert_chapters_to_audio(chapters_dir, output_audio_dir, target_voice_path=None, language=None):
|
386 |
+
selected_tts_model = "tts_models/multilingual/multi-dataset/xtts_v2"
|
387 |
+
tts = TTS(selected_tts_model, progress_bar=False).to(device) # Set progress_bar to False to avoid nested progress bars
|
388 |
+
|
389 |
+
if not os.path.exists(output_audio_dir):
|
390 |
+
os.makedirs(output_audio_dir)
|
391 |
+
|
392 |
+
for chapter_file in sorted(os.listdir(chapters_dir)):
|
393 |
+
if chapter_file.endswith('.txt'):
|
394 |
+
# Extract chapter number from the filename
|
395 |
+
match = re.search(r"chapter_(\d+).txt", chapter_file)
|
396 |
+
if match:
|
397 |
+
chapter_num = int(match.group(1))
|
398 |
+
else:
|
399 |
+
print(f"Skipping file {chapter_file} as it does not match the expected format.")
|
400 |
+
continue
|
401 |
+
|
402 |
+
chapter_path = os.path.join(chapters_dir, chapter_file)
|
403 |
+
output_file_name = f"audio_chapter_{chapter_num}.wav"
|
404 |
+
output_file_path = os.path.join(output_audio_dir, output_file_name)
|
405 |
+
# temp_audio_directory = os.path.join(".", "Working_files", "temp")
|
406 |
+
temp_audio_directory = os.path.join(".", "Operator",worker_num, "temp")
|
407 |
+
os.makedirs(temp_audio_directory, exist_ok=True)
|
408 |
+
temp_count = 0
|
409 |
+
|
410 |
+
with open(chapter_path, 'r', encoding='utf-8') as file:
|
411 |
+
chapter_text = file.read()
|
412 |
+
# Use the specified language model for sentence tokenization
|
413 |
+
sentences = sent_tokenize(chapter_text, language='italian' if language == 'it' else 'english')
|
414 |
+
for sentence in tqdm(sentences, desc=f"Chapter {chapter_num}"):
|
415 |
+
fragments = []
|
416 |
+
if language == "en":
|
417 |
+
fragments = split_long_sentence(sentence, max_length=249, max_pauses=10)
|
418 |
+
if language == "it":
|
419 |
+
fragments = split_long_sentence(sentence, max_length=213, max_pauses=10)
|
420 |
+
for fragment in fragments:
|
421 |
+
if fragment != "": #a hot fix to avoid blank fragments
|
422 |
+
print(f"Generating fragment: {fragment}...")
|
423 |
+
fragment_file_path = os.path.join(temp_audio_directory, f"{temp_count}.wav")
|
424 |
+
speaker_wav_path = target_voice_path if target_voice_path else default_target_voice_path
|
425 |
+
language_code = language if language else default_language_code
|
426 |
+
tts.tts_to_file(text=fragment, file_path=fragment_file_path, speaker_wav=speaker_wav_path, language=language_code)
|
427 |
+
temp_count += 1
|
428 |
+
|
429 |
+
combine_wav_files(temp_audio_directory, output_audio_dir, output_file_name)
|
430 |
+
wipe_folder(temp_audio_directory)
|
431 |
+
print(f"Converted chapter {chapter_num} to audio.")
|
432 |
+
|
433 |
+
|
434 |
+
|
435 |
+
# Main execution flow
|
436 |
+
if __name__ == "__main__":
|
437 |
+
# if len(sys.argv) < 2:
|
438 |
+
# print("Usage: python script.py <ebook_file_path> [target_voice_file_path]")
|
439 |
+
# sys.exit(1)
|
440 |
+
|
441 |
+
worker_num = sys.argv[1] #to let the script know which temp dir its using in operator
|
442 |
+
# ebook_file_path = sys.argv[1]
|
443 |
+
target_voice = "./4.wav" # sys.argv[2] if len(sys.argv) > 2 else None
|
444 |
+
language = "en" # sys.argv[3] if len(sys.argv) > 3 else None
|
445 |
+
|
446 |
+
# if not calibre_installed():
|
447 |
+
# sys.exit(1)
|
448 |
+
|
449 |
+
working_files = os.path.join(".","Working_files", "temp_ebook")
|
450 |
+
full_folder_working_files =os.path.join(".","Working_files")
|
451 |
+
# chapters_directory = os.path.join(".","Working_files", "temp_ebook")
|
452 |
+
chapters_directory = os.path.join(".","Operator",worker_num, "temp_ebook")
|
453 |
+
output_audio_directory = os.path.join(".", 'Chapter_wav_files')
|
454 |
+
|
455 |
+
# print("Wiping and removeing Working_files folder...")
|
456 |
+
# remove_folder_with_contents(full_folder_working_files)
|
457 |
+
#
|
458 |
+
# print("Wiping and and removeing chapter_wav_files folder...")
|
459 |
+
# remove_folder_with_contents(output_audio_directory)
|
460 |
+
|
461 |
+
# create_chapter_labeled_book(ebook_file_path)
|
462 |
+
audiobook_output_path = os.path.join(".", "Audiobooks")
|
463 |
+
print(f"{chapters_directory}||||{output_audio_directory}|||||{target_voice}")
|
464 |
+
convert_chapters_to_audio(chapters_directory, output_audio_directory, target_voice, language)
|
465 |
+
# create_m4b_from_chapters(output_audio_directory, ebook_file_path, audiobook_output_path)
|
Notebooks/Kaggel Archive Code/p3.py
ADDED
@@ -0,0 +1,462 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
nltk.download('punkt') # Make sure to download the necessary models
|
14 |
+
def is_folder_empty(folder_path):
|
15 |
+
if os.path.exists(folder_path) and os.path.isdir(folder_path):
|
16 |
+
# List directory contents
|
17 |
+
if not os.listdir(folder_path):
|
18 |
+
return True # The folder is empty
|
19 |
+
else:
|
20 |
+
return False # The folder is not empty
|
21 |
+
else:
|
22 |
+
print(f"The path {folder_path} is not a valid folder.")
|
23 |
+
return None # The path is not a valid folder
|
24 |
+
|
25 |
+
def remove_folder_with_contents(folder_path):
|
26 |
+
try:
|
27 |
+
shutil.rmtree(folder_path)
|
28 |
+
print(f"Successfully removed {folder_path} and all of its contents.")
|
29 |
+
except Exception as e:
|
30 |
+
print(f"Error removing {folder_path}: {e}")
|
31 |
+
|
32 |
+
|
33 |
+
|
34 |
+
|
35 |
+
def wipe_folder(folder_path):
|
36 |
+
# Check if the folder exists
|
37 |
+
if not os.path.exists(folder_path):
|
38 |
+
print(f"The folder {folder_path} does not exist.")
|
39 |
+
return
|
40 |
+
|
41 |
+
# Iterate over all the items in the given folder
|
42 |
+
for item in os.listdir(folder_path):
|
43 |
+
item_path = os.path.join(folder_path, item)
|
44 |
+
# If it's a file, remove it and print a message
|
45 |
+
if os.path.isfile(item_path):
|
46 |
+
os.remove(item_path)
|
47 |
+
print(f"Removed file: {item_path}")
|
48 |
+
# If it's a directory, remove it recursively and print a message
|
49 |
+
elif os.path.isdir(item_path):
|
50 |
+
shutil.rmtree(item_path)
|
51 |
+
print(f"Removed directory and its contents: {item_path}")
|
52 |
+
|
53 |
+
print(f"All contents wiped from {folder_path}.")
|
54 |
+
|
55 |
+
|
56 |
+
# Example usage
|
57 |
+
# folder_to_wipe = 'path_to_your_folder'
|
58 |
+
# wipe_folder(folder_to_wipe)
|
59 |
+
|
60 |
+
|
61 |
+
def create_m4b_from_chapters(input_dir, ebook_file, output_dir):
|
62 |
+
# Function to sort chapters based on their numeric order
|
63 |
+
def sort_key(chapter_file):
|
64 |
+
numbers = re.findall(r'\d+', chapter_file)
|
65 |
+
return int(numbers[0]) if numbers else 0
|
66 |
+
|
67 |
+
# Extract metadata and cover image from the eBook file
|
68 |
+
def extract_metadata_and_cover(ebook_path):
|
69 |
+
try:
|
70 |
+
cover_path = ebook_path.rsplit('.', 1)[0] + '.jpg'
|
71 |
+
subprocess.run(['ebook-meta', ebook_path, '--get-cover', cover_path], check=True)
|
72 |
+
if os.path.exists(cover_path):
|
73 |
+
return cover_path
|
74 |
+
except Exception as e:
|
75 |
+
print(f"Error extracting eBook metadata or cover: {e}")
|
76 |
+
return None
|
77 |
+
# Combine WAV files into a single file
|
78 |
+
def combine_wav_files(chapter_files, output_path):
|
79 |
+
# Initialize an empty audio segment
|
80 |
+
combined_audio = AudioSegment.empty()
|
81 |
+
|
82 |
+
# Sequentially append each file to the combined_audio
|
83 |
+
for chapter_file in chapter_files:
|
84 |
+
audio_segment = AudioSegment.from_wav(chapter_file)
|
85 |
+
combined_audio += audio_segment
|
86 |
+
# Export the combined audio to the output file path
|
87 |
+
combined_audio.export(output_path, format='wav')
|
88 |
+
print(f"Combined audio saved to {output_path}")
|
89 |
+
|
90 |
+
# Function to generate metadata for M4B chapters
|
91 |
+
def generate_ffmpeg_metadata(chapter_files, metadata_file):
|
92 |
+
with open(metadata_file, 'w') as file:
|
93 |
+
file.write(';FFMETADATA1\n')
|
94 |
+
start_time = 0
|
95 |
+
for index, chapter_file in enumerate(chapter_files):
|
96 |
+
duration_ms = len(AudioSegment.from_wav(chapter_file))
|
97 |
+
file.write(f'[CHAPTER]\nTIMEBASE=1/1000\nSTART={start_time}\n')
|
98 |
+
file.write(f'END={start_time + duration_ms}\ntitle=Chapter {index + 1}\n')
|
99 |
+
start_time += duration_ms
|
100 |
+
|
101 |
+
# Generate the final M4B file using ffmpeg
|
102 |
+
def create_m4b(combined_wav, metadata_file, cover_image, output_m4b):
|
103 |
+
# Ensure the output directory exists
|
104 |
+
os.makedirs(os.path.dirname(output_m4b), exist_ok=True)
|
105 |
+
|
106 |
+
ffmpeg_cmd = ['ffmpeg', '-i', combined_wav, '-i', metadata_file]
|
107 |
+
if cover_image:
|
108 |
+
ffmpeg_cmd += ['-i', cover_image, '-map', '0:a', '-map', '2:v']
|
109 |
+
else:
|
110 |
+
ffmpeg_cmd += ['-map', '0:a']
|
111 |
+
|
112 |
+
ffmpeg_cmd += ['-map_metadata', '1', '-c:a', 'aac', '-b:a', '192k']
|
113 |
+
if cover_image:
|
114 |
+
ffmpeg_cmd += ['-c:v', 'png', '-disposition:v', 'attached_pic']
|
115 |
+
ffmpeg_cmd += [output_m4b]
|
116 |
+
|
117 |
+
subprocess.run(ffmpeg_cmd, check=True)
|
118 |
+
|
119 |
+
|
120 |
+
|
121 |
+
# Main logic
|
122 |
+
chapter_files = sorted([os.path.join(input_dir, f) for f in os.listdir(input_dir) if f.endswith('.wav')], key=sort_key)
|
123 |
+
temp_dir = tempfile.gettempdir()
|
124 |
+
temp_combined_wav = os.path.join(temp_dir, 'combined.wav')
|
125 |
+
metadata_file = os.path.join(temp_dir, 'metadata.txt')
|
126 |
+
cover_image = extract_metadata_and_cover(ebook_file)
|
127 |
+
output_m4b = os.path.join(output_dir, os.path.splitext(os.path.basename(ebook_file))[0] + '.m4b')
|
128 |
+
|
129 |
+
combine_wav_files(chapter_files, temp_combined_wav)
|
130 |
+
generate_ffmpeg_metadata(chapter_files, metadata_file)
|
131 |
+
create_m4b(temp_combined_wav, metadata_file, cover_image, output_m4b)
|
132 |
+
|
133 |
+
# Cleanup
|
134 |
+
if os.path.exists(temp_combined_wav):
|
135 |
+
os.remove(temp_combined_wav)
|
136 |
+
if os.path.exists(metadata_file):
|
137 |
+
os.remove(metadata_file)
|
138 |
+
if cover_image and os.path.exists(cover_image):
|
139 |
+
os.remove(cover_image)
|
140 |
+
|
141 |
+
# Example usage
|
142 |
+
# create_m4b_from_chapters('path_to_chapter_wavs', 'path_to_ebook_file', 'path_to_output_dir')
|
143 |
+
|
144 |
+
|
145 |
+
|
146 |
+
|
147 |
+
|
148 |
+
|
149 |
+
#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
|
150 |
+
import os
|
151 |
+
import subprocess
|
152 |
+
import ebooklib
|
153 |
+
from ebooklib import epub
|
154 |
+
from bs4 import BeautifulSoup
|
155 |
+
import re
|
156 |
+
import csv
|
157 |
+
import nltk
|
158 |
+
|
159 |
+
# Only run the main script if Value is True
|
160 |
+
def create_chapter_labeled_book(ebook_file_path):
|
161 |
+
# Function to ensure the existence of a directory
|
162 |
+
def ensure_directory(directory_path):
|
163 |
+
if not os.path.exists(directory_path):
|
164 |
+
os.makedirs(directory_path)
|
165 |
+
print(f"Created directory: {directory_path}")
|
166 |
+
|
167 |
+
ensure_directory(os.path.join(".", 'Working_files', 'Book'))
|
168 |
+
|
169 |
+
def convert_to_epub(input_path, output_path):
|
170 |
+
# Convert the ebook to EPUB format using Calibre's ebook-convert
|
171 |
+
try:
|
172 |
+
subprocess.run(['ebook-convert', input_path, output_path], check=True)
|
173 |
+
except subprocess.CalledProcessError as e:
|
174 |
+
print(f"An error occurred while converting the eBook: {e}")
|
175 |
+
return False
|
176 |
+
return True
|
177 |
+
|
178 |
+
def save_chapters_as_text(epub_path):
|
179 |
+
# Create the directory if it doesn't exist
|
180 |
+
directory = os.path.join(".", "Working_files", "temp_ebook")
|
181 |
+
ensure_directory(directory)
|
182 |
+
|
183 |
+
# Open the EPUB file
|
184 |
+
book = epub.read_epub(epub_path)
|
185 |
+
|
186 |
+
previous_chapter_text = ''
|
187 |
+
previous_filename = ''
|
188 |
+
chapter_counter = 0
|
189 |
+
|
190 |
+
# Iterate through the items in the EPUB file
|
191 |
+
for item in book.get_items():
|
192 |
+
if item.get_type() == ebooklib.ITEM_DOCUMENT:
|
193 |
+
# Use BeautifulSoup to parse HTML content
|
194 |
+
soup = BeautifulSoup(item.get_content(), 'html.parser')
|
195 |
+
text = soup.get_text()
|
196 |
+
|
197 |
+
# Check if the text is not empty
|
198 |
+
if text.strip():
|
199 |
+
if len(text) < 2300 and previous_filename:
|
200 |
+
# Append text to the previous chapter if it's short
|
201 |
+
with open(previous_filename, 'a', encoding='utf-8') as file:
|
202 |
+
file.write('\n' + text)
|
203 |
+
else:
|
204 |
+
# Create a new chapter file and increment the counter
|
205 |
+
previous_filename = os.path.join(directory, f"chapter_{chapter_counter}.txt")
|
206 |
+
chapter_counter += 1
|
207 |
+
with open(previous_filename, 'w', encoding='utf-8') as file:
|
208 |
+
file.write(text)
|
209 |
+
print(f"Saved chapter: {previous_filename}")
|
210 |
+
|
211 |
+
# Example usage
|
212 |
+
input_ebook = ebook_file_path # Replace with your eBook file path
|
213 |
+
output_epub = os.path.join(".", "Working_files", "temp.epub")
|
214 |
+
|
215 |
+
|
216 |
+
if os.path.exists(output_epub):
|
217 |
+
os.remove(output_epub)
|
218 |
+
print(f"File {output_epub} has been removed.")
|
219 |
+
else:
|
220 |
+
print(f"The file {output_epub} does not exist.")
|
221 |
+
|
222 |
+
if convert_to_epub(input_ebook, output_epub):
|
223 |
+
save_chapters_as_text(output_epub)
|
224 |
+
|
225 |
+
# Download the necessary NLTK data (if not already present)
|
226 |
+
nltk.download('punkt')
|
227 |
+
|
228 |
+
def process_chapter_files(folder_path, output_csv):
|
229 |
+
with open(output_csv, 'w', newline='', encoding='utf-8') as csvfile:
|
230 |
+
writer = csv.writer(csvfile)
|
231 |
+
# Write the header row
|
232 |
+
writer.writerow(['Text', 'Start Location', 'End Location', 'Is Quote', 'Speaker', 'Chapter'])
|
233 |
+
|
234 |
+
# Process each chapter file
|
235 |
+
chapter_files = sorted(os.listdir(folder_path), key=lambda x: int(x.split('_')[1].split('.')[0]))
|
236 |
+
for filename in chapter_files:
|
237 |
+
if filename.startswith('chapter_') and filename.endswith('.txt'):
|
238 |
+
chapter_number = int(filename.split('_')[1].split('.')[0])
|
239 |
+
file_path = os.path.join(folder_path, filename)
|
240 |
+
|
241 |
+
try:
|
242 |
+
with open(file_path, 'r', encoding='utf-8') as file:
|
243 |
+
text = file.read()
|
244 |
+
# Insert "NEWCHAPTERABC" at the beginning of each chapter's text
|
245 |
+
if text:
|
246 |
+
text = "NEWCHAPTERABC" + text
|
247 |
+
sentences = nltk.tokenize.sent_tokenize(text)
|
248 |
+
for sentence in sentences:
|
249 |
+
start_location = text.find(sentence)
|
250 |
+
end_location = start_location + len(sentence)
|
251 |
+
writer.writerow([sentence, start_location, end_location, 'True', 'Narrator', chapter_number])
|
252 |
+
except Exception as e:
|
253 |
+
print(f"Error processing file {filename}: {e}")
|
254 |
+
|
255 |
+
# Example usage
|
256 |
+
folder_path = os.path.join(".", "Working_files", "temp_ebook")
|
257 |
+
output_csv = os.path.join(".", "Working_files", "Book", "Other_book.csv")
|
258 |
+
|
259 |
+
process_chapter_files(folder_path, output_csv)
|
260 |
+
|
261 |
+
def sort_key(filename):
|
262 |
+
"""Extract chapter number for sorting."""
|
263 |
+
match = re.search(r'chapter_(\d+)\.txt', filename)
|
264 |
+
return int(match.group(1)) if match else 0
|
265 |
+
|
266 |
+
def combine_chapters(input_folder, output_file):
|
267 |
+
# Create the output folder if it doesn't exist
|
268 |
+
os.makedirs(os.path.dirname(output_file), exist_ok=True)
|
269 |
+
|
270 |
+
# List all txt files and sort them by chapter number
|
271 |
+
files = [f for f in os.listdir(input_folder) if f.endswith('.txt')]
|
272 |
+
sorted_files = sorted(files, key=sort_key)
|
273 |
+
|
274 |
+
with open(output_file, 'w', encoding='utf-8') as outfile: # Specify UTF-8 encoding here
|
275 |
+
for i, filename in enumerate(sorted_files):
|
276 |
+
with open(os.path.join(input_folder, filename), 'r', encoding='utf-8') as infile: # And here
|
277 |
+
outfile.write(infile.read())
|
278 |
+
# Add the marker unless it's the last file
|
279 |
+
if i < len(sorted_files) - 1:
|
280 |
+
outfile.write("\nNEWCHAPTERABC\n")
|
281 |
+
|
282 |
+
# Paths
|
283 |
+
input_folder = os.path.join(".", 'Working_files', 'temp_ebook')
|
284 |
+
output_file = os.path.join(".", 'Working_files', 'Book', 'Chapter_Book.txt')
|
285 |
+
|
286 |
+
|
287 |
+
# Combine the chapters
|
288 |
+
combine_chapters(input_folder, output_file)
|
289 |
+
|
290 |
+
ensure_directory(os.path.join(".", "Working_files", "Book"))
|
291 |
+
|
292 |
+
|
293 |
+
#create_chapter_labeled_book()
|
294 |
+
|
295 |
+
|
296 |
+
|
297 |
+
|
298 |
+
import os
|
299 |
+
import subprocess
|
300 |
+
import sys
|
301 |
+
import torchaudio
|
302 |
+
|
303 |
+
# Check if Calibre's ebook-convert tool is installed
|
304 |
+
def calibre_installed():
|
305 |
+
try:
|
306 |
+
subprocess.run(['ebook-convert', '--version'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
307 |
+
return True
|
308 |
+
except FileNotFoundError:
|
309 |
+
print("Calibre is not installed. Please install Calibre for this functionality.")
|
310 |
+
return False
|
311 |
+
|
312 |
+
|
313 |
+
import os
|
314 |
+
import torch
|
315 |
+
from TTS.api import TTS
|
316 |
+
from nltk.tokenize import sent_tokenize
|
317 |
+
from pydub import AudioSegment
|
318 |
+
# Assuming split_long_sentence and wipe_folder are defined elsewhere in your code
|
319 |
+
|
320 |
+
default_target_voice_path = "default_voice.wav" # Ensure this is a valid path
|
321 |
+
default_language_code = "en"
|
322 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
323 |
+
|
324 |
+
def combine_wav_files(input_directory, output_directory, file_name):
|
325 |
+
# Ensure that the output directory exists, create it if necessary
|
326 |
+
os.makedirs(output_directory, exist_ok=True)
|
327 |
+
|
328 |
+
# Specify the output file path
|
329 |
+
output_file_path = os.path.join(output_directory, file_name)
|
330 |
+
|
331 |
+
# Initialize an empty audio segment
|
332 |
+
combined_audio = AudioSegment.empty()
|
333 |
+
|
334 |
+
# Get a list of all .wav files in the specified input directory and sort them
|
335 |
+
input_file_paths = sorted(
|
336 |
+
[os.path.join(input_directory, f) for f in os.listdir(input_directory) if f.endswith(".wav")],
|
337 |
+
key=lambda f: int(''.join(filter(str.isdigit, f)))
|
338 |
+
)
|
339 |
+
|
340 |
+
# Sequentially append each file to the combined_audio
|
341 |
+
for input_file_path in input_file_paths:
|
342 |
+
audio_segment = AudioSegment.from_wav(input_file_path)
|
343 |
+
combined_audio += audio_segment
|
344 |
+
|
345 |
+
# Export the combined audio to the output file path
|
346 |
+
combined_audio.export(output_file_path, format='wav')
|
347 |
+
|
348 |
+
print(f"Combined audio saved to {output_file_path}")
|
349 |
+
|
350 |
+
# Function to split long strings into parts
|
351 |
+
def split_long_sentence(sentence, max_length=249, max_pauses=10):
|
352 |
+
"""
|
353 |
+
Splits a sentence into parts based on length or number of pauses without recursion.
|
354 |
+
|
355 |
+
:param sentence: The sentence to split.
|
356 |
+
:param max_length: Maximum allowed length of a sentence.
|
357 |
+
:param max_pauses: Maximum allowed number of pauses in a sentence.
|
358 |
+
:return: A list of sentence parts that meet the criteria.
|
359 |
+
"""
|
360 |
+
parts = []
|
361 |
+
while len(sentence) > max_length or sentence.count(',') + sentence.count(';') + sentence.count('.') > max_pauses:
|
362 |
+
possible_splits = [i for i, char in enumerate(sentence) if char in ',;.' and i < max_length]
|
363 |
+
if possible_splits:
|
364 |
+
# Find the best place to split the sentence, preferring the last possible split to keep parts longer
|
365 |
+
split_at = possible_splits[-1] + 1
|
366 |
+
else:
|
367 |
+
# If no punctuation to split on within max_length, split at max_length
|
368 |
+
split_at = max_length
|
369 |
+
|
370 |
+
# Split the sentence and add the first part to the list
|
371 |
+
parts.append(sentence[:split_at].strip())
|
372 |
+
sentence = sentence[split_at:].strip()
|
373 |
+
|
374 |
+
# Add the remaining part of the sentence
|
375 |
+
parts.append(sentence)
|
376 |
+
return parts
|
377 |
+
|
378 |
+
"""
|
379 |
+
if 'tts' not in locals():
|
380 |
+
tts = TTS(selected_tts_model, progress_bar=True).to(device)
|
381 |
+
"""
|
382 |
+
from tqdm import tqdm
|
383 |
+
|
384 |
+
# Convert chapters to audio using XTTS
|
385 |
+
def convert_chapters_to_audio(chapters_dir, output_audio_dir, target_voice_path=None, language=None):
|
386 |
+
selected_tts_model = "tts_models/multilingual/multi-dataset/xtts_v2"
|
387 |
+
tts = TTS(selected_tts_model, progress_bar=False).to(device) # Set progress_bar to False to avoid nested progress bars
|
388 |
+
|
389 |
+
if not os.path.exists(output_audio_dir):
|
390 |
+
os.makedirs(output_audio_dir)
|
391 |
+
|
392 |
+
for chapter_file in sorted(os.listdir(chapters_dir)):
|
393 |
+
if chapter_file.endswith('.txt'):
|
394 |
+
# Extract chapter number from the filename
|
395 |
+
match = re.search(r"chapter_(\d+).txt", chapter_file)
|
396 |
+
if match:
|
397 |
+
chapter_num = int(match.group(1))
|
398 |
+
else:
|
399 |
+
print(f"Skipping file {chapter_file} as it does not match the expected format.")
|
400 |
+
continue
|
401 |
+
|
402 |
+
chapter_path = os.path.join(chapters_dir, chapter_file)
|
403 |
+
output_file_name = f"audio_chapter_{chapter_num}.wav"
|
404 |
+
output_file_path = os.path.join(output_audio_dir, output_file_name)
|
405 |
+
temp_audio_directory = os.path.join(".", "Working_files", "temp")
|
406 |
+
os.makedirs(temp_audio_directory, exist_ok=True)
|
407 |
+
temp_count = 0
|
408 |
+
|
409 |
+
with open(chapter_path, 'r', encoding='utf-8') as file:
|
410 |
+
chapter_text = file.read()
|
411 |
+
# Use the specified language model for sentence tokenization
|
412 |
+
sentences = sent_tokenize(chapter_text, language='italian' if language == 'it' else 'english')
|
413 |
+
for sentence in tqdm(sentences, desc=f"Chapter {chapter_num}"):
|
414 |
+
fragments = []
|
415 |
+
if language == "en":
|
416 |
+
fragments = split_long_sentence(sentence, max_length=249, max_pauses=10)
|
417 |
+
if language == "it":
|
418 |
+
fragments = split_long_sentence(sentence, max_length=213, max_pauses=10)
|
419 |
+
for fragment in fragments:
|
420 |
+
if fragment != "": #a hot fix to avoid blank fragments
|
421 |
+
print(f"Generating fragment: {fragment}...")
|
422 |
+
fragment_file_path = os.path.join(temp_audio_directory, f"{temp_count}.wav")
|
423 |
+
speaker_wav_path = target_voice_path if target_voice_path else default_target_voice_path
|
424 |
+
language_code = language if language else default_language_code
|
425 |
+
tts.tts_to_file(text=fragment, file_path=fragment_file_path, speaker_wav=speaker_wav_path, language=language_code)
|
426 |
+
temp_count += 1
|
427 |
+
|
428 |
+
combine_wav_files(temp_audio_directory, output_audio_dir, output_file_name)
|
429 |
+
wipe_folder(temp_audio_directory)
|
430 |
+
print(f"Converted chapter {chapter_num} to audio.")
|
431 |
+
|
432 |
+
|
433 |
+
|
434 |
+
# Main execution flow
|
435 |
+
if __name__ == "__main__":
|
436 |
+
if len(sys.argv) < 2:
|
437 |
+
print("Usage: python script.py <ebook_file_path> [target_voice_file_path]")
|
438 |
+
sys.exit(1)
|
439 |
+
|
440 |
+
ebook_file_path = sys.argv[1]
|
441 |
+
target_voice = sys.argv[2] if len(sys.argv) > 2 else None
|
442 |
+
language = sys.argv[3] if len(sys.argv) > 3 else None
|
443 |
+
|
444 |
+
if not calibre_installed():
|
445 |
+
sys.exit(1)
|
446 |
+
|
447 |
+
working_files = os.path.join(".","Working_files", "temp_ebook")
|
448 |
+
full_folder_working_files =os.path.join(".","Working_files")
|
449 |
+
chapters_directory = os.path.join(".","Working_files", "temp_ebook")
|
450 |
+
output_audio_directory = os.path.join(".", 'Chapter_wav_files')
|
451 |
+
|
452 |
+
# print("Wiping and removeing Working_files folder...")
|
453 |
+
# remove_folder_with_contents(full_folder_working_files)
|
454 |
+
#
|
455 |
+
# print("Wiping and and removeing chapter_wav_files folder...")
|
456 |
+
# remove_folder_with_contents(output_audio_directory)
|
457 |
+
|
458 |
+
# create_chapter_labeled_book(ebook_file_path)
|
459 |
+
audiobook_output_path = os.path.join(".", "Audiobooks")
|
460 |
+
# print(f"{chapters_directory}||||{output_audio_directory}|||||{target_voice}")
|
461 |
+
# convert_chapters_to_audio(chapters_directory, output_audio_directory, target_voice, language)
|
462 |
+
create_m4b_from_chapters(output_audio_directory, ebook_file_path, audiobook_output_path)
|
Notebooks/colab_ebook2audiobookxtts.ipynb
ADDED
@@ -0,0 +1,105 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"nbformat": 4,
|
3 |
+
"nbformat_minor": 0,
|
4 |
+
"metadata": {
|
5 |
+
"colab": {
|
6 |
+
"provenance": [],
|
7 |
+
"gpuType": "T4",
|
8 |
+
"include_colab_link": true
|
9 |
+
},
|
10 |
+
"kernelspec": {
|
11 |
+
"name": "python3",
|
12 |
+
"display_name": "Python 3"
|
13 |
+
},
|
14 |
+
"language_info": {
|
15 |
+
"name": "python"
|
16 |
+
},
|
17 |
+
"accelerator": "GPU"
|
18 |
+
},
|
19 |
+
"cells": [
|
20 |
+
{
|
21 |
+
"cell_type": "markdown",
|
22 |
+
"metadata": {
|
23 |
+
"id": "view-in-github",
|
24 |
+
"colab_type": "text"
|
25 |
+
},
|
26 |
+
"source": [
|
27 |
+
"<a href=\"https://colab.research.google.com/github/DrewThomasson/ebook2audiobookXTTS/blob/main/Notebooks/colab_ebook2audiobookxtts.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
|
28 |
+
]
|
29 |
+
},
|
30 |
+
{
|
31 |
+
"cell_type": "markdown",
|
32 |
+
"source": [
|
33 |
+
"## Welcome to the ebook2audiobookxtts free google colab!\n",
|
34 |
+
"## 🌟 Features\n",
|
35 |
+
"\n",
|
36 |
+
"- 📖 Converts eBooks to text format with Calibre.\n",
|
37 |
+
"- 📚 Splits eBook into chapters for organized audio.\n",
|
38 |
+
"- 🎙️ High-quality text-to-speech with Coqui XTTS.\n",
|
39 |
+
"- 🗣️ Optional voice cloning with your own voice file.\n",
|
40 |
+
"- 🌍 Supports multiple languages! (English (en), Spanish (es), French (fr), German (de), Italian (it), Portuguese (pt), Polish (pl), Turkish (tr), Russian (ru), Dutch (nl), Czech (cs), Arabic (ar), Chinese (zh-cn), Japanese (ja), Hungarian (hu), Korean (ko)).\n",
|
41 |
+
"## Want to run locally for free? ⬇\n",
|
42 |
+
"## [Check out the ebook2audiobookxtts github!](https://github.com/DrewThomasson/ebook2audiobookXTTS)"
|
43 |
+
],
|
44 |
+
"metadata": {
|
45 |
+
"id": "DKNNnwD-HJwQ"
|
46 |
+
}
|
47 |
+
},
|
48 |
+
{
|
49 |
+
"cell_type": "code",
|
50 |
+
"source": [
|
51 |
+
"# @title 🛠️ Install requirments\n",
|
52 |
+
"#!DEBIAN_FRONTEND=noninteractive\n",
|
53 |
+
"!sudo apt-get update # && sudo apt-get -y upgrade\n",
|
54 |
+
"!sudo apt-get -y install libegl1\n",
|
55 |
+
"!sudo apt-get -y install libopengl0\n",
|
56 |
+
"!sudo apt-get -y install libxcb-cursor0\n",
|
57 |
+
"!sudo -v && wget -nv -O- https://download.calibre-ebook.com/linux-installer.sh | sudo sh /dev/stdin\n",
|
58 |
+
"!sudo apt-get install -y ffmpeg\n",
|
59 |
+
"#!sudo apt-get install -y calibre\n",
|
60 |
+
"!pip install ebook2audiobook-install-counter\n",
|
61 |
+
"!pip install ebooklib\n",
|
62 |
+
"!pip install pydub\n",
|
63 |
+
"!pip install nltk\n",
|
64 |
+
"!pip install beautifulsoup4\n",
|
65 |
+
"!pip install tqdm\n",
|
66 |
+
"!pip install gradio\n",
|
67 |
+
"!pip install coqui-tts"
|
68 |
+
],
|
69 |
+
"metadata": {
|
70 |
+
"id": "Edxj355K0rUz",
|
71 |
+
"collapsed": true,
|
72 |
+
"cellView": "form"
|
73 |
+
},
|
74 |
+
"execution_count": null,
|
75 |
+
"outputs": []
|
76 |
+
},
|
77 |
+
{
|
78 |
+
"cell_type": "code",
|
79 |
+
"source": [
|
80 |
+
"# @title 🚀 Run ebook2audiobookxtts! (Make sure to set the runtime to have gpu to have faster generation speeds! :)\n",
|
81 |
+
"#ntlk error fix\n",
|
82 |
+
"#https://github.com/delip/PyTorchNLPBook/issues/14\n",
|
83 |
+
"import nltk\n",
|
84 |
+
"nltk.download('punkt')\n",
|
85 |
+
"\n",
|
86 |
+
"#Auto agree to xtts\n",
|
87 |
+
"import os\n",
|
88 |
+
"os.environ[\"COQUI_TOS_AGREED\"] = \"1\"\n",
|
89 |
+
"\n",
|
90 |
+
"# To download the app.py and the Default_voice wav if not seen locally\n",
|
91 |
+
"!wget -O /content/app.py https://raw.githubusercontent.com/DrewThomasson/ebook2audiobookXTTS/main/app.py\n",
|
92 |
+
"!wget -O /content/default_voice.wav https://raw.githubusercontent.com/DrewThomasson/ebook2audiobookXTTS/main/default_voice.wav\n",
|
93 |
+
"\n",
|
94 |
+
"# Start the app with Share=True for the gradio interface\n",
|
95 |
+
"!python /content/app.py --share True"
|
96 |
+
],
|
97 |
+
"metadata": {
|
98 |
+
"id": "658BTHueyLMo",
|
99 |
+
"cellView": "form"
|
100 |
+
},
|
101 |
+
"execution_count": null,
|
102 |
+
"outputs": []
|
103 |
+
}
|
104 |
+
]
|
105 |
+
}
|
Notebooks/kaggle-beta-of-ebook2audiobookxtts-ipynb.ipynb
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
{"metadata":{"kernelspec":{"name":"python3","display_name":"Python 3","language":"python"},"language_info":{"name":"python","version":"3.10.14","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"colab":{"provenance":[],"gpuType":"T4"},"accelerator":"GPU","kaggle":{"accelerator":"gpu","dataSources":[],"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"# IGNORE THESE ITS OLD LOL\n\n# install needed packages\n\n##!apt-get update\n\n##!apt-get install wget unzip git ffmpeg calibre\n\n\n\n# pip install requirments\n\n##!pip install tts==0.21.3 pydub nltk beautifulsoup4 ebooklib tqdm gradio\n\n\n\n##!pip install numpy==1.23\n\n##!pip install --no-binary lxml lxml\n\n##import os\n\n##os.kill(os.getpid(), 9)\n","metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"gh3HEhmzuqVA","outputId":"81217d71-7576-43db-d56c-07ce11ea6517","jupyter":{"source_hidden":true},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#!DEBIAN_FRONTEND=noninteractive\n\n!sudo apt-get update # && sudo apt-get -y upgrade\n\n!sudo apt-get -y install libegl1\n\n!sudo apt-get -y install libopengl0\n\n!sudo apt-get -y install libxcb-cursor0\n\n!sudo -v && wget -nv -O- https://download.calibre-ebook.com/linux-installer.sh | sudo sh /dev/stdin\n\n!sudo apt-get install -y ffmpeg\n\n!pip install tts pydub nltk beautifulsoup4 ebooklib tqdm\n\n!pip install numpy==1.26.4\n\n!pip install gradio","metadata":{"colab":{"base_uri":"https://localhost:8080/","height":1000},"id":"Edxj355K0rUz","outputId":"9fc5f4e1-1ba2-4814-a477-496f626c2772","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Start the app with Share=True for the gradio interface\n\n\n\n#ntlk error fix\n\n#https://github.com/delip/PyTorchNLPBook/issues/14\n\nimport nltk\n\nnltk.download('punkt')\n\n\n\n#Auto agree to xtts\n\nimport os\n\nos.environ[\"COQUI_TOS_AGREED\"] = \"1\"\n\n\n\n!python /kaggle/working/app.py --share True","metadata":{"id":"EZIZva9Tvdbb","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#ntlk error fix\n\n#https://github.com/delip/PyTorchNLPBook/issues/14\n\nimport nltk\n\nnltk.download('punkt')\n\n\n\n#Auto agree to xtts\n\nimport os\n\nos.environ[\"COQUI_TOS_AGREED\"] = \"1\"\n\n\n\n# To download the app.py and the Default_voice wav if not seen locally\n\n!wget -O /kaggle/working/app.py https://raw.githubusercontent.com/DrewThomasson/ebook2audiobookXTTS/main/app.py\n\n!wget -O /kaggle/working/default_voice.wav https://raw.githubusercontent.com/DrewThomasson/ebook2audiobookXTTS/main/default_voice.wav\n\n\n\n# Start the app with Share=True for the gradio interface\n\n!python /kaggle/working/app.py --share True","metadata":{"id":"658BTHueyLMo","colab":{"base_uri":"https://localhost:8080/"},"outputId":"e293e70d-b25a-41bc-dbac-7ca1ddf1d3d2","trusted":true},"execution_count":null,"outputs":[]}]}
|