drewThomasson
commited on
Commit
•
adad39b
1
Parent(s):
3c0bc7a
Upload 62 files
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- .gitattributes +1 -0
- legacy/v1.0/Dockerfile +93 -0
- legacy/v1.0/LICENSE +21 -0
- legacy/v1.0/Notebooks/Kaggel Archive Code/4.wav +0 -0
- legacy/v1.0/Notebooks/Kaggel Archive Code/LICENSE +21 -0
- legacy/v1.0/Notebooks/Kaggel Archive Code/README.md +118 -0
- legacy/v1.0/Notebooks/Kaggel Archive Code/Worker_2T4.sh +59 -0
- legacy/v1.0/Notebooks/Kaggel Archive Code/default_voice.wav +0 -0
- legacy/v1.0/Notebooks/Kaggel Archive Code/demo_mini_story_chapters_Drew.epub +0 -0
- legacy/v1.0/Notebooks/Kaggel Archive Code/ebook2audiobook.py +462 -0
- legacy/v1.0/Notebooks/Kaggel Archive Code/kaggle-ebook2audiobook-demo.ipynb +1 -0
- legacy/v1.0/Notebooks/Kaggel Archive Code/p1.py +462 -0
- legacy/v1.0/Notebooks/Kaggel Archive Code/p2a_worker_gpu1.py +465 -0
- legacy/v1.0/Notebooks/Kaggel Archive Code/p2a_worker_gpu2.py +465 -0
- legacy/v1.0/Notebooks/Kaggel Archive Code/p3.py +462 -0
- legacy/v1.0/Notebooks/colab_ebook2audiobookxtts.ipynb +106 -0
- legacy/v1.0/Notebooks/kaggle-beta-of-ebook2audiobookxtts-ipynb.ipynb +1 -0
- legacy/v1.0/README.md +478 -0
- legacy/v1.0/app.py +1041 -0
- legacy/v1.0/default_voice.wav +0 -0
- legacy/v1.0/demo_mini_story_chapters_Drew.epub +0 -0
- legacy/v1.0/demo_web_gui.gif +3 -0
- legacy/v1.0/legacy/custom_model_ebook2audiobookXTTS.py +484 -0
- legacy/v1.0/legacy/custom_model_ebook2audiobookXTTS_gradio.py +609 -0
- legacy/v1.0/legacy/custom_model_ebook2audiobookXTTS_with_link_gradio.py +700 -0
- legacy/v1.0/legacy/ebook2audiobook.py +462 -0
- legacy/v1.0/legacy/gradio_gui_with_email_and_que.py +614 -0
- legacy/v1.0/legacy/install.bat +18 -0
- legacy/v1.0/legacy/install.ps1 +255 -0
- legacy/v1.0/legacy/install.sh +171 -0
- legacy/v1.0/readme/README_CN.md +428 -0
- legacy/v1.0/readme/README_RU.md +387 -0
- legacy/v1.0/samples/Supported_language_sample__generated_outputs/ar.m4b +0 -0
- legacy/v1.0/samples/Supported_language_sample__generated_outputs/cs.m4b +0 -0
- legacy/v1.0/samples/Supported_language_sample__generated_outputs/de.m4b +0 -0
- legacy/v1.0/samples/Supported_language_sample__generated_outputs/en.m4b +0 -0
- legacy/v1.0/samples/Supported_language_sample__generated_outputs/es.m4b +0 -0
- legacy/v1.0/samples/Supported_language_sample__generated_outputs/fr.m4b +0 -0
- legacy/v1.0/samples/Supported_language_sample__generated_outputs/hu.m4b +0 -0
- legacy/v1.0/samples/Supported_language_sample__generated_outputs/it.m4b +0 -0
- legacy/v1.0/samples/Supported_language_sample__generated_outputs/ko.m4b +0 -0
- legacy/v1.0/samples/Supported_language_sample__generated_outputs/nl.m4b +0 -0
- legacy/v1.0/samples/Supported_language_sample__generated_outputs/pl.m4b +0 -0
- legacy/v1.0/samples/Supported_language_sample__generated_outputs/pt.m4b +0 -0
- legacy/v1.0/samples/Supported_language_sample__generated_outputs/ru.m4b +0 -0
- legacy/v1.0/samples/Supported_language_sample__generated_outputs/tr.m4b +0 -0
- legacy/v1.0/samples/Supported_language_sample__generated_outputs/zh-cn.m4b +0 -0
- legacy/v1.0/samples/Supported_language_sample_texts/ar.txt +1 -0
- legacy/v1.0/samples/Supported_language_sample_texts/cs.txt +1 -0
- legacy/v1.0/samples/Supported_language_sample_texts/de.txt +1 -0
.gitattributes
CHANGED
@@ -43,3 +43,4 @@ voices/eng/elder/male/JhonButlerASMR_22khz.wav filter=lfs diff=lfs merge=lfs -te
|
|
43 |
voices/eng/elder/male/JhonButlerASMR_24khz.wav filter=lfs diff=lfs merge=lfs -text
|
44 |
voices/fra/elder/male/default_voice.wav filter=lfs diff=lfs merge=lfs -text
|
45 |
voices/eng/adult/male/BryanCranston_16khz.wav filter=lfs diff=lfs merge=lfs -text
|
|
|
|
43 |
voices/eng/elder/male/JhonButlerASMR_24khz.wav filter=lfs diff=lfs merge=lfs -text
|
44 |
voices/fra/elder/male/default_voice.wav filter=lfs diff=lfs merge=lfs -text
|
45 |
voices/eng/adult/male/BryanCranston_16khz.wav filter=lfs diff=lfs merge=lfs -text
|
46 |
+
legacy/v1.0/demo_web_gui.gif filter=lfs diff=lfs merge=lfs -text
|
legacy/v1.0/Dockerfile
ADDED
@@ -0,0 +1,93 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Use an official NVIDIA CUDA image with cudnn8 and Ubuntu 20.04 as the base
|
2 |
+
FROM nvidia/cuda:11.8.0-cudnn8-runtime-ubuntu20.04
|
3 |
+
|
4 |
+
# Set non-interactive installation to avoid timezone and other prompts
|
5 |
+
ENV DEBIAN_FRONTEND=noninteractive
|
6 |
+
|
7 |
+
# Install necessary packages including Miniconda
|
8 |
+
RUN apt-get update && apt-get install -y --no-install-recommends \
|
9 |
+
wget \
|
10 |
+
git \
|
11 |
+
espeak \
|
12 |
+
espeak-ng \
|
13 |
+
ffmpeg \
|
14 |
+
tk \
|
15 |
+
mecab \
|
16 |
+
libmecab-dev \
|
17 |
+
mecab-ipadic-utf8 \
|
18 |
+
build-essential \
|
19 |
+
calibre \
|
20 |
+
&& rm -rf /var/lib/apt/lists/*
|
21 |
+
|
22 |
+
RUN ebook-convert --version
|
23 |
+
|
24 |
+
# Install Miniconda
|
25 |
+
RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O ~/miniconda.sh && \
|
26 |
+
bash ~/miniconda.sh -b -p /opt/conda && \
|
27 |
+
rm ~/miniconda.sh
|
28 |
+
|
29 |
+
|
30 |
+
|
31 |
+
# Set PATH to include conda
|
32 |
+
ENV PATH=/opt/conda/bin:$PATH
|
33 |
+
|
34 |
+
# Create a conda environment with Python 3.10
|
35 |
+
RUN conda create -n ebookenv python=3.10 -y
|
36 |
+
|
37 |
+
# Activate the conda environment
|
38 |
+
SHELL ["conda", "run", "-n", "ebookenv", "/bin/bash", "-c"]
|
39 |
+
|
40 |
+
# Install Python dependencies using conda and pip
|
41 |
+
RUN conda install -n ebookenv -c conda-forge \
|
42 |
+
pydub \
|
43 |
+
nltk \
|
44 |
+
mecab-python3 \
|
45 |
+
&& pip install --no-cache-dir \
|
46 |
+
bs4 \
|
47 |
+
beautifulsoup4 \
|
48 |
+
ebooklib \
|
49 |
+
tqdm \
|
50 |
+
tts==0.21.3 \
|
51 |
+
unidic \
|
52 |
+
gradio
|
53 |
+
|
54 |
+
# Download unidic
|
55 |
+
RUN python -m unidic download
|
56 |
+
|
57 |
+
# Set the working directory in the container
|
58 |
+
WORKDIR /ebook2audiobookXTTS
|
59 |
+
|
60 |
+
# Clone the ebook2audiobookXTTS repository
|
61 |
+
RUN git clone https://github.com/DrewThomasson/ebook2audiobookXTTS.git .
|
62 |
+
|
63 |
+
# Copy test audio file
|
64 |
+
COPY default_voice.wav /ebook2audiobookXTTS/
|
65 |
+
|
66 |
+
# Run a test to set up XTTS
|
67 |
+
RUN echo "import torch" > /tmp/script1.py && \
|
68 |
+
echo "from TTS.api import TTS" >> /tmp/script1.py && \
|
69 |
+
echo "device = 'cuda' if torch.cuda.is_available() else 'cpu'" >> /tmp/script1.py && \
|
70 |
+
echo "print(TTS().list_models())" >> /tmp/script1.py && \
|
71 |
+
echo "tts = TTS('tts_models/multilingual/multi-dataset/xtts_v2').to(device)" >> /tmp/script1.py && \
|
72 |
+
echo "wav = tts.tts(text='Hello world!', speaker_wav='default_voice.wav', language='en')" >> /tmp/script1.py && \
|
73 |
+
echo "tts.tts_to_file(text='Hello world!', speaker_wav='default_voice.wav', language='en', file_path='output.wav')" >> /tmp/script1.py && \
|
74 |
+
yes | python /tmp/script1.py
|
75 |
+
|
76 |
+
# Remove the test audio file
|
77 |
+
RUN rm -f /ebook2audiobookXTTS/output.wav
|
78 |
+
|
79 |
+
# Verify that the script exists and has the correct permissions
|
80 |
+
RUN ls -la /ebook2audiobookXTTS/
|
81 |
+
|
82 |
+
# Check if the script exists and log its presence
|
83 |
+
RUN if [ -f /ebook2audiobookXTTS/custom_model_ebook2audiobookXTTS_with_link_gradio.py ]; then echo "Script found."; else echo "Script not found."; exit 1; fi
|
84 |
+
|
85 |
+
# Modify the Python script to set share=True
|
86 |
+
RUN sed -i 's/demo.launch(share=False)/demo.launch(share=True)/' /ebook2audiobookXTTS/custom_model_ebook2audiobookXTTS_with_link_gradio.py
|
87 |
+
|
88 |
+
# Download the punkt package for nltk
|
89 |
+
RUN python -m nltk.downloader punkt
|
90 |
+
|
91 |
+
# Set the command to run your GUI application using the conda environment
|
92 |
+
CMD ["conda", "run", "--no-capture-output", "-n", "ebookenv", "python", "/ebook2audiobookXTTS/custom_model_ebook2audiobookXTTS_with_link_gradio.py"]
|
93 |
+
|
legacy/v1.0/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.
|
legacy/v1.0/Notebooks/Kaggel Archive Code/4.wav
ADDED
Binary file (543 kB). View file
|
|
legacy/v1.0/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.
|
legacy/v1.0/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
|
legacy/v1.0/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!"
|
legacy/v1.0/Notebooks/Kaggel Archive Code/default_voice.wav
ADDED
Binary file (291 kB). View file
|
|
legacy/v1.0/Notebooks/Kaggel Archive Code/demo_mini_story_chapters_Drew.epub
ADDED
Binary file (415 kB). View file
|
|
legacy/v1.0/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)
|
legacy/v1.0/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":[]}]}
|
legacy/v1.0/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)
|
legacy/v1.0/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)
|
legacy/v1.0/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)
|
legacy/v1.0/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)
|
legacy/v1.0/Notebooks/colab_ebook2audiobookxtts.ipynb
ADDED
@@ -0,0 +1,106 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
"nltk.download('punkt_tab')\n",
|
86 |
+
"\n",
|
87 |
+
"#Auto agree to xtts\n",
|
88 |
+
"import os\n",
|
89 |
+
"os.environ[\"COQUI_TOS_AGREED\"] = \"1\"\n",
|
90 |
+
"\n",
|
91 |
+
"# To download the app.py and the Default_voice wav if not seen locally\n",
|
92 |
+
"!wget -O /content/app.py https://raw.githubusercontent.com/DrewThomasson/ebook2audiobookXTTS/main/app.py\n",
|
93 |
+
"!wget -O /content/default_voice.wav https://raw.githubusercontent.com/DrewThomasson/ebook2audiobookXTTS/main/default_voice.wav\n",
|
94 |
+
"\n",
|
95 |
+
"# Start the app with Share=True for the gradio interface\n",
|
96 |
+
"!python /content/app.py --share True"
|
97 |
+
],
|
98 |
+
"metadata": {
|
99 |
+
"id": "658BTHueyLMo",
|
100 |
+
"cellView": "form"
|
101 |
+
},
|
102 |
+
"execution_count": null,
|
103 |
+
"outputs": []
|
104 |
+
}
|
105 |
+
]
|
106 |
+
}
|
legacy/v1.0/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":[]}]}
|
legacy/v1.0/README.md
ADDED
@@ -0,0 +1,478 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# 📚 ebook2audiobook
|
2 |
+
|
3 |
+
Convert eBooks to audiobooks with chapters and metadata using Calibre and Coqui XTTS. Supports optional voice cloning and multiple languages!
|
4 |
+
|
5 |
+
|
6 |
+
#### 🖥️ Web GUI Interface
|
7 |
+
![demo_web_gui](https://github.com/user-attachments/assets/85af88a7-05dd-4a29-91de-76a14cf5ef06)
|
8 |
+
|
9 |
+
<details>
|
10 |
+
<summary>Click to see images of Web GUI</summary>
|
11 |
+
<img width="1728" alt="image" src="https://github.com/user-attachments/assets/b36c71cf-8e06-484c-a252-934e6b1d0c2f">
|
12 |
+
<img width="1728" alt="image" src="https://github.com/user-attachments/assets/c0dab57a-d2d4-4658-bff9-3842ec90cb40">
|
13 |
+
<img width="1728" alt="image" src="https://github.com/user-attachments/assets/0a99eeac-c521-4b21-8656-e064c1adc528">
|
14 |
+
</details>
|
15 |
+
|
16 |
+
## README.md
|
17 |
+
- en [English](README.md)
|
18 |
+
- zh_CN [简体中文](readme/README_CN.md)
|
19 |
+
- ru [Русский](readme/README_RU.md)
|
20 |
+
|
21 |
+
|
22 |
+
## 🌟 Features
|
23 |
+
|
24 |
+
- 📖 Converts eBooks to text format with Calibre.
|
25 |
+
- 📚 Splits eBook into chapters for organized audio.
|
26 |
+
- 🎙️ High-quality text-to-speech with Coqui XTTS.
|
27 |
+
- 🗣️ Optional voice cloning with your own voice file.
|
28 |
+
- 🌍 Supports multiple languages (English by default).
|
29 |
+
- 🖥️ Designed to run on 4GB RAM.
|
30 |
+
|
31 |
+
## 🤗 [Huggingface space demo](https://huggingface.co/spaces/drewThomasson/ebook2audiobookXTTS)
|
32 |
+
- Huggingface space is running on free cpu tier so expect very slow or timeout lol, just don't give it giant files is all
|
33 |
+
- Best to duplicate space or run locally.
|
34 |
+
|
35 |
+
## Free Google Colab [![Free Google Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/DrewThomasson/ebook2audiobookXTTS/blob/main/Notebooks/colab_ebook2audiobookxtts.ipynb)
|
36 |
+
|
37 |
+
|
38 |
+
## 🛠️ Requirements
|
39 |
+
|
40 |
+
- Python 3.10
|
41 |
+
- `coqui-tts` Python package
|
42 |
+
- Calibre (for eBook conversion)
|
43 |
+
- FFmpeg (for audiobook creation)
|
44 |
+
- Optional: Custom voice file for voice cloning
|
45 |
+
|
46 |
+
|
47 |
+
### 🔧 Installation Instructions
|
48 |
+
|
49 |
+
1. **Install Python 3.x** from [Python.org](https://www.python.org/downloads/).
|
50 |
+
|
51 |
+
2. **Install Calibre**:
|
52 |
+
- **Ubuntu**: `sudo apt-get install -y calibre`
|
53 |
+
- **macOS**: `brew install calibre`
|
54 |
+
- **Windows** (Admin Powershell): `choco install calibre`
|
55 |
+
|
56 |
+
3. **Install FFmpeg**:
|
57 |
+
- **Ubuntu**: `sudo apt-get install -y ffmpeg`
|
58 |
+
- **macOS**: `brew install ffmpeg`
|
59 |
+
- **Windows** (Admin Powershell): `choco install ffmpeg`
|
60 |
+
|
61 |
+
4. **Optional: Install Mecab** (for non-Latin languages):
|
62 |
+
- **Ubuntu**: `sudo apt-get install -y mecab libmecab-dev mecab-ipadic-utf8`
|
63 |
+
- **macOS**: `brew install mecab`, `brew install mecab-ipadic`
|
64 |
+
- **Windows**: [mecab-website-to-install-manually](https://taku910.github.io/mecab/#download) (Note: Japanese support is limited)
|
65 |
+
|
66 |
+
5. **Install Python packages**:
|
67 |
+
```bash
|
68 |
+
pip install coqui-tts==0.24.2 pydub nltk beautifulsoup4 ebooklib tqdm gradio==4.44.0
|
69 |
+
|
70 |
+
python -m nltk.downloader punkt
|
71 |
+
python -m nltk.downloader punkt_tab
|
72 |
+
```
|
73 |
+
|
74 |
+
**For non-Latin languages**:
|
75 |
+
```bash
|
76 |
+
pip install mecab mecab-python3 unidic
|
77 |
+
|
78 |
+
python -m unidic download
|
79 |
+
```
|
80 |
+
|
81 |
+
## 🌐 Supported Languages
|
82 |
+
|
83 |
+
- **English (en)**
|
84 |
+
- **Spanish (es)**
|
85 |
+
- **French (fr)**
|
86 |
+
- **German (de)**
|
87 |
+
- **Italian (it)**
|
88 |
+
- **Portuguese (pt)**
|
89 |
+
- **Polish (pl)**
|
90 |
+
- **Turkish (tr)**
|
91 |
+
- **Russian (ru)**
|
92 |
+
- **Dutch (nl)**
|
93 |
+
- **Czech (cs)**
|
94 |
+
- **Arabic (ar)**
|
95 |
+
- **Chinese (zh-cn)**
|
96 |
+
- **Japanese (ja)**
|
97 |
+
- **Hungarian (hu)**
|
98 |
+
- **Korean (ko)**
|
99 |
+
|
100 |
+
Specify the language code when running the script in headless mode.
|
101 |
+
## 🚀 Usage
|
102 |
+
|
103 |
+
### 🖥️ Launching Gradio Web Interface
|
104 |
+
|
105 |
+
1. **Run the Script**:
|
106 |
+
```bash
|
107 |
+
python app.py
|
108 |
+
```
|
109 |
+
|
110 |
+
2. **Open the Web App**: Click the URL provided in the terminal to access the web app and convert eBooks.
|
111 |
+
3. **For Public Link**: Add `--share True` to the end of it like this: `python app.py --share True`
|
112 |
+
- **[For More Parameters]**: use the `-h` parameter like this `python app.py -h`
|
113 |
+
|
114 |
+
### 📝 Basic Headless Usage
|
115 |
+
|
116 |
+
```bash
|
117 |
+
python app.py --headless True --ebook <path_to_ebook_file> --voice [path_to_voice_file] --language [language_code]
|
118 |
+
```
|
119 |
+
|
120 |
+
- **<path_to_ebook_file>**: Path to your eBook file.
|
121 |
+
- **[path_to_voice_file]**: Optional for voice cloning.
|
122 |
+
- **[language_code]**: Optional to specify language.
|
123 |
+
- **[For More Parameters]**: use the `-h` parameter like this `python app.py -h`
|
124 |
+
|
125 |
+
### 🧩 Headless Custom XTTS Model Usage
|
126 |
+
|
127 |
+
```bash
|
128 |
+
python app.py --headless True --use_custom_model True --ebook <ebook_file_path> --voice <target_voice_file_path> --language <language> --custom_model <custom_model_path> --custom_config <custom_config_path> --custom_vocab <custom_vocab_path>
|
129 |
+
```
|
130 |
+
|
131 |
+
- **<ebook_file_path>**: Path to your eBook file.
|
132 |
+
- **<target_voice_file_path>**: Optional for voice cloning.
|
133 |
+
- **<language>**: Optional to specify language.
|
134 |
+
- **<custom_model_path>**: Path to `model.pth`.
|
135 |
+
- **<custom_config_path>**: Path to `config.json`.
|
136 |
+
- **<custom_vocab_path>**: Path to `vocab.json`.
|
137 |
+
- **[For More Parameters]**: use the `-h` parameter like this `python app.py -h`
|
138 |
+
|
139 |
+
|
140 |
+
### 🧩 Headless Custom XTTS Model Usage With Zip link to XTTS Fine-Tune Model 🌐
|
141 |
+
|
142 |
+
```bash
|
143 |
+
python app.py --headless True --use_custom_model True --ebook <ebook_file_path> --voice <target_voice_file_path> --language <language> --custom_model_url <custom_model_URL_ZIP_path>
|
144 |
+
```
|
145 |
+
|
146 |
+
- **<ebook_file_path>**: Path to your eBook file.
|
147 |
+
- **<target_voice_file_path>**: Optional for voice cloning.
|
148 |
+
- **<language>**: Optional to specify language.
|
149 |
+
- **<custom_model_URL_ZIP_path>**: URL Path to zip of Model folder. For Example this for the [xtts_David_Attenborough_fine_tune](https://huggingface.co/drewThomasson/xtts_David_Attenborough_fine_tune/tree/main) `https://huggingface.co/drewThomasson/xtts_David_Attenborough_fine_tune/resolve/main/Finished_model_files.zip?download=true`
|
150 |
+
- For a custom model a ref audio clip of the voice will also be needed:
|
151 |
+
[ref audio clip of David Attenborough](https://huggingface.co/drewThomasson/xtts_David_Attenborough_fine_tune/blob/main/ref.wav)
|
152 |
+
- **[For More Parameters]**: use the `-h` parameter like this `python app.py -h`
|
153 |
+
|
154 |
+
### 🔍 For Detailed Guide with list of all Parameters to use
|
155 |
+
```bash
|
156 |
+
python app.py -h
|
157 |
+
```
|
158 |
+
- This will output the following:
|
159 |
+
```bash
|
160 |
+
usage: app.py [-h] [--share SHARE] [--headless HEADLESS] [--ebook EBOOK] [--voice VOICE]
|
161 |
+
[--language LANGUAGE] [--use_custom_model USE_CUSTOM_MODEL]
|
162 |
+
[--custom_model CUSTOM_MODEL] [--custom_config CUSTOM_CONFIG]
|
163 |
+
[--custom_vocab CUSTOM_VOCAB] [--custom_model_url CUSTOM_MODEL_URL]
|
164 |
+
[--temperature TEMPERATURE] [--length_penalty LENGTH_PENALTY]
|
165 |
+
[--repetition_penalty REPETITION_PENALTY] [--top_k TOP_K] [--top_p TOP_P]
|
166 |
+
[--speed SPEED] [--enable_text_splitting ENABLE_TEXT_SPLITTING]
|
167 |
+
|
168 |
+
Convert eBooks to Audiobooks using a Text-to-Speech model. You can either launch the
|
169 |
+
Gradio interface or run the script in headless mode for direct conversion.
|
170 |
+
|
171 |
+
options:
|
172 |
+
-h, --help show this help message and exit
|
173 |
+
--share SHARE Set to True to enable a public shareable Gradio link. Defaults
|
174 |
+
to False.
|
175 |
+
--headless HEADLESS Set to True to run in headless mode without the Gradio
|
176 |
+
interface. Defaults to False.
|
177 |
+
--ebook EBOOK Path to the ebook file for conversion. Required in headless
|
178 |
+
mode.
|
179 |
+
--voice VOICE Path to the target voice file for TTS. Optional, uses a default
|
180 |
+
voice if not provided.
|
181 |
+
--language LANGUAGE Language for the audiobook conversion. Options: en, es, fr, de,
|
182 |
+
it, pt, pl, tr, ru, nl, cs, ar, zh-cn, ja, hu, ko. Defaults to
|
183 |
+
English (en).
|
184 |
+
--use_custom_model USE_CUSTOM_MODEL
|
185 |
+
Set to True to use a custom TTS model. Defaults to False. Must
|
186 |
+
be True to use custom models, otherwise you'll get an error.
|
187 |
+
--custom_model CUSTOM_MODEL
|
188 |
+
Path to the custom model file (.pth). Required if using a custom
|
189 |
+
model.
|
190 |
+
--custom_config CUSTOM_CONFIG
|
191 |
+
Path to the custom config file (config.json). Required if using
|
192 |
+
a custom model.
|
193 |
+
--custom_vocab CUSTOM_VOCAB
|
194 |
+
Path to the custom vocab file (vocab.json). Required if using a
|
195 |
+
custom model.
|
196 |
+
--custom_model_url CUSTOM_MODEL_URL
|
197 |
+
URL to download the custom model as a zip file. Optional, but
|
198 |
+
will be used if provided. Examples include David Attenborough's
|
199 |
+
model: 'https://huggingface.co/drewThomasson/xtts_David_Attenbor
|
200 |
+
ough_fine_tune/resolve/main/Finished_model_files.zip?download=tr
|
201 |
+
ue'. More XTTS fine-tunes can be found on my Hugging Face at
|
202 |
+
'https://huggingface.co/drewThomasson'.
|
203 |
+
--temperature TEMPERATURE
|
204 |
+
Temperature for the model. Defaults to 0.65. Higher Tempatures
|
205 |
+
will lead to more creative outputs IE: more Hallucinations.
|
206 |
+
Lower Tempatures will be more monotone outputs IE: less
|
207 |
+
Hallucinations.
|
208 |
+
--length_penalty LENGTH_PENALTY
|
209 |
+
A length penalty applied to the autoregressive decoder. Defaults
|
210 |
+
to 1.0. Not applied to custom models.
|
211 |
+
--repetition_penalty REPETITION_PENALTY
|
212 |
+
A penalty that prevents the autoregressive decoder from
|
213 |
+
repeating itself. Defaults to 2.0.
|
214 |
+
--top_k TOP_K Top-k sampling. Lower values mean more likely outputs and
|
215 |
+
increased audio generation speed. Defaults to 50.
|
216 |
+
--top_p TOP_P Top-p sampling. Lower values mean more likely outputs and
|
217 |
+
increased audio generation speed. Defaults to 0.8.
|
218 |
+
--speed SPEED Speed factor for the speech generation. IE: How fast the
|
219 |
+
Narrerator will speak. Defaults to 1.0.
|
220 |
+
--enable_text_splitting ENABLE_TEXT_SPLITTING
|
221 |
+
Enable splitting text into sentences. Defaults to True.
|
222 |
+
|
223 |
+
Example: python script.py --headless --ebook path_to_ebook --voice path_to_voice
|
224 |
+
--language en --use_custom_model True --custom_model model.pth --custom_config
|
225 |
+
config.json --custom_vocab vocab.json
|
226 |
+
```
|
227 |
+
|
228 |
+
|
229 |
+
<details>
|
230 |
+
<summary>⚠️ Legacy-Depricated Old Use Instructions</summary>
|
231 |
+
|
232 |
+
## 🚀 Usage
|
233 |
+
|
234 |
+
## Legacy files have been moved to `ebook2audiobookXTTS/legacy/`
|
235 |
+
|
236 |
+
### 🖥️ Gradio Web Interface
|
237 |
+
|
238 |
+
1. **Run the Script**:
|
239 |
+
```bash
|
240 |
+
python custom_model_ebook2audiobookXTTS_gradio.py
|
241 |
+
```
|
242 |
+
|
243 |
+
2. **Open the Web App**: Click the URL provided in the terminal to access the web app and convert eBooks.
|
244 |
+
|
245 |
+
### 📝 Basic Usage
|
246 |
+
|
247 |
+
```bash
|
248 |
+
python ebook2audiobook.py <path_to_ebook_file> [path_to_voice_file] [language_code]
|
249 |
+
```
|
250 |
+
|
251 |
+
- **<path_to_ebook_file>**: Path to your eBook file.
|
252 |
+
- **[path_to_voice_file]**: Optional for voice cloning.
|
253 |
+
- **[language_code]**: Optional to specify language.
|
254 |
+
|
255 |
+
### 🧩 Custom XTTS Model
|
256 |
+
|
257 |
+
```bash
|
258 |
+
python custom_model_ebook2audiobookXTTS.py <ebook_file_path> <target_voice_file_path> <language> <custom_model_path> <custom_config_path> <custom_vocab_path>
|
259 |
+
```
|
260 |
+
|
261 |
+
- **<ebook_file_path>**: Path to your eBook file.
|
262 |
+
- **<target_voice_file_path>**: Optional for voice cloning.
|
263 |
+
- **<language>**: Optional to specify language.
|
264 |
+
- **<custom_model_path>**: Path to `model.pth`.
|
265 |
+
- **<custom_config_path>**: Path to `config.json`.
|
266 |
+
- **<custom_vocab_path>**: Path to `vocab.json`.
|
267 |
+
</details>
|
268 |
+
|
269 |
+
### 🐳 Using Docker
|
270 |
+
|
271 |
+
You can also use Docker to run the eBook to Audiobook converter. This method ensures consistency across different environments and simplifies setup.
|
272 |
+
|
273 |
+
#### 🚀 Running the Docker Container
|
274 |
+
|
275 |
+
To run the Docker container and start the Gradio interface, use the following command:
|
276 |
+
|
277 |
+
-Run with CPU only
|
278 |
+
```powershell
|
279 |
+
docker run -it --rm -p 7860:7860 --platform=linux/amd64 athomasson2/ebook2audiobookxtts:huggingface python app.py
|
280 |
+
```
|
281 |
+
-Run with GPU Speedup (Nvida graphics cards only)
|
282 |
+
```powershell
|
283 |
+
docker run -it --rm --gpus all -p 7860:7860 --platform=linux/amd64 athomasson2/ebook2audiobookxtts:huggingface python app.py
|
284 |
+
```
|
285 |
+
|
286 |
+
This command will start the Gradio interface on port 7860.(localhost:7860)
|
287 |
+
- For more options like running the docker in headless mode or making the gradio link public add the `-h` parameter after the `app.py` in the docker launch command
|
288 |
+
<details>
|
289 |
+
<summary><strong>Example of using docker in headless mode or modifying anything with the extra parameters + Full guide</strong></summary>
|
290 |
+
|
291 |
+
## Example of using docker in headless mode
|
292 |
+
|
293 |
+
first for a docker pull of the latest with
|
294 |
+
```bash
|
295 |
+
docker pull athomasson2/ebook2audiobookxtts:huggingface
|
296 |
+
```
|
297 |
+
|
298 |
+
- Before you do run this you need to create a dir named "input-folder" in your current dir which will be linked, This is where you can put your input files for the docker image to see
|
299 |
+
```bash
|
300 |
+
mkdir input-folder && mkdir Audiobooks
|
301 |
+
```
|
302 |
+
|
303 |
+
- In the command below swap out **YOUR_INPUT_FILE.TXT** with the name of your input file
|
304 |
+
|
305 |
+
```bash
|
306 |
+
docker run -it --rm \
|
307 |
+
-v $(pwd)/input-folder:/home/user/app/input_folder \
|
308 |
+
-v $(pwd)/Audiobooks:/home/user/app/Audiobooks \
|
309 |
+
--platform linux/amd64 \
|
310 |
+
athomasson2/ebook2audiobookxtts:huggingface \
|
311 |
+
python app.py --headless True --ebook /home/user/app/input_folder/YOUR_INPUT_FILE.TXT
|
312 |
+
```
|
313 |
+
|
314 |
+
- And that should be it!
|
315 |
+
|
316 |
+
- The output Audiobooks will be found in the Audiobook folder which will also be located in your local dir you ran this docker command in
|
317 |
+
|
318 |
+
|
319 |
+
## To get the help command for the other parameters this program has you can run this
|
320 |
+
|
321 |
+
```bash
|
322 |
+
docker run -it --rm \
|
323 |
+
--platform linux/amd64 \
|
324 |
+
athomasson2/ebook2audiobookxtts:huggingface \
|
325 |
+
python app.py -h
|
326 |
+
|
327 |
+
```
|
328 |
+
|
329 |
+
|
330 |
+
and that will output this
|
331 |
+
|
332 |
+
```bash
|
333 |
+
user/app/ebook2audiobookXTTS/input-folder -v $(pwd)/Audiobooks:/home/user/app/ebook2audiobookXTTS/Audiobooks --memory="4g" --network none --platform linux/amd64 athomasson2/ebook2audiobookxtts:huggingface python app.py -h
|
334 |
+
starting...
|
335 |
+
usage: app.py [-h] [--share SHARE] [--headless HEADLESS] [--ebook EBOOK] [--voice VOICE]
|
336 |
+
[--language LANGUAGE] [--use_custom_model USE_CUSTOM_MODEL]
|
337 |
+
[--custom_model CUSTOM_MODEL] [--custom_config CUSTOM_CONFIG]
|
338 |
+
[--custom_vocab CUSTOM_VOCAB] [--custom_model_url CUSTOM_MODEL_URL]
|
339 |
+
[--temperature TEMPERATURE] [--length_penalty LENGTH_PENALTY]
|
340 |
+
[--repetition_penalty REPETITION_PENALTY] [--top_k TOP_K] [--top_p TOP_P]
|
341 |
+
[--speed SPEED] [--enable_text_splitting ENABLE_TEXT_SPLITTING]
|
342 |
+
|
343 |
+
Convert eBooks to Audiobooks using a Text-to-Speech model. You can either launch the
|
344 |
+
Gradio interface or run the script in headless mode for direct conversion.
|
345 |
+
|
346 |
+
options:
|
347 |
+
-h, --help show this help message and exit
|
348 |
+
--share SHARE Set to True to enable a public shareable Gradio link. Defaults
|
349 |
+
to False.
|
350 |
+
--headless HEADLESS Set to True to run in headless mode without the Gradio
|
351 |
+
interface. Defaults to False.
|
352 |
+
--ebook EBOOK Path to the ebook file for conversion. Required in headless
|
353 |
+
mode.
|
354 |
+
--voice VOICE Path to the target voice file for TTS. Optional, uses a default
|
355 |
+
voice if not provided.
|
356 |
+
--language LANGUAGE Language for the audiobook conversion. Options: en, es, fr, de,
|
357 |
+
it, pt, pl, tr, ru, nl, cs, ar, zh-cn, ja, hu, ko. Defaults to
|
358 |
+
English (en).
|
359 |
+
--use_custom_model USE_CUSTOM_MODEL
|
360 |
+
Set to True to use a custom TTS model. Defaults to False. Must
|
361 |
+
be True to use custom models, otherwise you'll get an error.
|
362 |
+
--custom_model CUSTOM_MODEL
|
363 |
+
Path to the custom model file (.pth). Required if using a custom
|
364 |
+
model.
|
365 |
+
--custom_config CUSTOM_CONFIG
|
366 |
+
Path to the custom config file (config.json). Required if using
|
367 |
+
a custom model.
|
368 |
+
--custom_vocab CUSTOM_VOCAB
|
369 |
+
Path to the custom vocab file (vocab.json). Required if using a
|
370 |
+
custom model.
|
371 |
+
--custom_model_url CUSTOM_MODEL_URL
|
372 |
+
URL to download the custom model as a zip file. Optional, but
|
373 |
+
will be used if provided. Examples include David Attenborough's
|
374 |
+
model: 'https://huggingface.co/drewThomasson/xtts_David_Attenbor
|
375 |
+
ough_fine_tune/resolve/main/Finished_model_files.zip?download=tr
|
376 |
+
ue'. More XTTS fine-tunes can be found on my Hugging Face at
|
377 |
+
'https://huggingface.co/drewThomasson'.
|
378 |
+
--temperature TEMPERATURE
|
379 |
+
Temperature for the model. Defaults to 0.65. Higher Tempatures
|
380 |
+
will lead to more creative outputs IE: more Hallucinations.
|
381 |
+
Lower Tempatures will be more monotone outputs IE: less
|
382 |
+
Hallucinations.
|
383 |
+
--length_penalty LENGTH_PENALTY
|
384 |
+
A length penalty applied to the autoregressive decoder. Defaults
|
385 |
+
to 1.0. Not applied to custom models.
|
386 |
+
--repetition_penalty REPETITION_PENALTY
|
387 |
+
A penalty that prevents the autoregressive decoder from
|
388 |
+
repeating itself. Defaults to 2.0.
|
389 |
+
--top_k TOP_K Top-k sampling. Lower values mean more likely outputs and
|
390 |
+
increased audio generation speed. Defaults to 50.
|
391 |
+
--top_p TOP_P Top-p sampling. Lower values mean more likely outputs and
|
392 |
+
increased audio generation speed. Defaults to 0.8.
|
393 |
+
--speed SPEED Speed factor for the speech generation. IE: How fast the
|
394 |
+
Narrerator will speak. Defaults to 1.0.
|
395 |
+
--enable_text_splitting ENABLE_TEXT_SPLITTING
|
396 |
+
Enable splitting text into sentences. Defaults to True.
|
397 |
+
|
398 |
+
Example: python script.py --headless --ebook path_to_ebook --voice path_to_voice
|
399 |
+
--language en --use_custom_model True --custom_model model.pth --custom_config
|
400 |
+
config.json --custom_vocab vocab.json
|
401 |
+
```
|
402 |
+
</details>
|
403 |
+
|
404 |
+
#### 🖥️ Docker GUI
|
405 |
+
![demo_web_gui](https://github.com/user-attachments/assets/85af88a7-05dd-4a29-91de-76a14cf5ef06)
|
406 |
+
|
407 |
+
<details>
|
408 |
+
<summary>Click to see images of Web GUI</summary>
|
409 |
+
<img width="1728" alt="image" src="https://github.com/user-attachments/assets/b36c71cf-8e06-484c-a252-934e6b1d0c2f">
|
410 |
+
<img width="1728" alt="image" src="https://github.com/user-attachments/assets/c0dab57a-d2d4-4658-bff9-3842ec90cb40">
|
411 |
+
<img width="1728" alt="image" src="https://github.com/user-attachments/assets/0a99eeac-c521-4b21-8656-e064c1adc528">
|
412 |
+
</details>
|
413 |
+
### 🛠️ For Custom Xtts Models
|
414 |
+
|
415 |
+
Models built to be better at a specific voice. Check out my Hugging Face page [here](https://huggingface.co/drewThomasson).
|
416 |
+
|
417 |
+
To use a custom model, paste the link of the `Finished_model_files.zip` file like this:
|
418 |
+
|
419 |
+
[David Attenborough fine tuned Finished_model_files.zip](https://huggingface.co/drewThomasson/xtts_David_Attenborough_fine_tune/resolve/main/Finished_model_files.zip?download=true)
|
420 |
+
|
421 |
+
For a custom model a ref audio clip of the voice will also be needed:
|
422 |
+
[ref audio clip of David Attenborough](https://huggingface.co/drewThomasson/xtts_David_Attenborough_fine_tune/blob/main/ref.wav)
|
423 |
+
|
424 |
+
|
425 |
+
|
426 |
+
More details can be found at the [Dockerfile Hub Page]([https://github.com/DrewThomasson/ebook2audiobookXTTS](https://hub.docker.com/repository/docker/athomasson2/ebook2audiobookxtts/general)).
|
427 |
+
|
428 |
+
## 🌐 Fine Tuned Xtts models
|
429 |
+
|
430 |
+
To find already fine-tuned XTTS models, visit [this Hugging Face link](https://huggingface.co/drewThomasson) 🌐. Search for models that include "xtts fine tune" in their names.
|
431 |
+
|
432 |
+
## 🎥 Demos
|
433 |
+
|
434 |
+
Rainy day voice
|
435 |
+
|
436 |
+
https://github.com/user-attachments/assets/8486603c-38b1-43ce-9639-73757dfb1031
|
437 |
+
|
438 |
+
David Attenborough voice
|
439 |
+
|
440 |
+
https://github.com/user-attachments/assets/47c846a7-9e51-4eb9-844a-7460402a20a8
|
441 |
+
|
442 |
+
|
443 |
+
## �� [Huggingface space demo](https://huggingface.co/spaces/drewThomasson/ebook2audiobookXTTS)
|
444 |
+
- Huggingface space is running on free cpu tier so expect very slow or timeout lol, just don't give it giant files is all
|
445 |
+
- Best to duplicate space or run locally.
|
446 |
+
|
447 |
+
## Free Google Colab [![Free Google Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/DrewThomasson/ebook2audiobookXTTS/blob/main/Notebooks/colab_ebook2audiobookxtts.ipynb)
|
448 |
+
|
449 |
+
|
450 |
+
|
451 |
+
## 📚 Supported eBook Formats
|
452 |
+
|
453 |
+
- `.epub`, `.pdf`, `.mobi`, `.txt`, `.html`, `.rtf`, `.chm`, `.lit`, `.pdb`, `.fb2`, `.odt`, `.cbr`, `.cbz`, `.prc`, `.lrf`, `.pml`, `.snb`, `.cbc`, `.rb`, `.tcr`
|
454 |
+
- **Best results**: `.epub` or `.mobi` for automatic chapter detection
|
455 |
+
|
456 |
+
## 📂 Output
|
457 |
+
|
458 |
+
- Creates an `.m4b` file with metadata and chapters.
|
459 |
+
- **Example Output**: ![Example](https://github.com/DrewThomasson/VoxNovel/blob/dc5197dff97252fa44c391dc0596902d71278a88/readme_files/example_in_app.jpeg)
|
460 |
+
|
461 |
+
## 🛠️ Common Issues:
|
462 |
+
- "It's slow!" - On CPU only this is very slow, and you can only get speedups though a NVIDIA GPU. [Discussion about this](https://github.com/DrewThomasson/ebook2audiobookXTTS/discussions/19#discussioncomment-10879846) For faster multilingual generation I would suggest my other [project that uses piper-tts](https://github.com/DrewThomasson/ebook2audiobookpiper-tts) instead(It doesn't have zero-shot voice cloning though, and is siri quality voices, but it is much faster on cpu.)
|
463 |
+
- "I'm having dependency issues" - Just use the docker, its fully self contained and has a headless mode, add `-h` parameter after the `app.py` in the docker run command for more information.
|
464 |
+
- "Im getting a truncated audio issue!" - PLEASE MAKE AN ISSUE OF THIS, I don't speak every language and I need advise from each person to fine tune my sentense splitting function on any other languages.😊
|
465 |
+
- "The loading bar is stuck at 30% in the web gui!" - The web gui loading bar is extreamly basic as its just split between the three loading steps, refer to the terminal and what sentense it's on for a more accurate gauge on where is it progress wise.
|
466 |
+
|
467 |
+
## What I need help with! 🙌
|
468 |
+
## [Full list of things can be found here](https://github.com/DrewThomasson/ebook2audiobookXTTS/issues/32)
|
469 |
+
- Any help from people speaking any of the supported langues to help with proper sentence splitting methods
|
470 |
+
- Potentially creating readme Guides for Multiple languages(Becuase the only language I know is English 😔)
|
471 |
+
|
472 |
+
## 🙏 Special Thanks
|
473 |
+
|
474 |
+
- **Coqui TTS**: [Coqui TTS GitHub](https://github.com/coqui-ai/TTS)
|
475 |
+
- **Calibre**: [Calibre Website](https://calibre-ebook.com)
|
476 |
+
|
477 |
+
- [@shakenbake15 for better chapter saving method](https://github.com/DrewThomasson/ebook2audiobookXTTS/issues/8)
|
478 |
+
|
legacy/v1.0/app.py
ADDED
@@ -0,0 +1,1041 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
print("starting...")
|
2 |
+
|
3 |
+
import argparse
|
4 |
+
|
5 |
+
language_options = [
|
6 |
+
"en", "es", "fr", "de", "it", "pt", "pl", "tr", "ru", "nl", "cs", "ar", "zh-cn", "ja", "hu", "ko"
|
7 |
+
]
|
8 |
+
char_limits = {
|
9 |
+
"en": 250, # English
|
10 |
+
"es": 239, # Spanish
|
11 |
+
"fr": 273, # French
|
12 |
+
"de": 253, # German
|
13 |
+
"it": 213, # Italian
|
14 |
+
"pt": 203, # Portuguese
|
15 |
+
"pl": 224, # Polish
|
16 |
+
"tr": 226, # Turkish
|
17 |
+
"ru": 182, # Russian
|
18 |
+
"nl": 251, # Dutch
|
19 |
+
"cs": 186, # Czech
|
20 |
+
"ar": 166, # Arabic
|
21 |
+
"zh-cn": 82, # Chinese (Simplified)
|
22 |
+
"ja": 71, # Japanese
|
23 |
+
"hu": 224, # Hungarian
|
24 |
+
"ko": 95, # Korean
|
25 |
+
}
|
26 |
+
|
27 |
+
# Mapping of language codes to NLTK's supported language names
|
28 |
+
language_mapping = {
|
29 |
+
"en": "english",
|
30 |
+
"de": "german",
|
31 |
+
"fr": "french",
|
32 |
+
"es": "spanish",
|
33 |
+
"it": "italian",
|
34 |
+
"pt": "portuguese",
|
35 |
+
"nl": "dutch",
|
36 |
+
"pl": "polish",
|
37 |
+
"cs": "czech",
|
38 |
+
"ru": "russian",
|
39 |
+
"tr": "turkish",
|
40 |
+
"el": "greek",
|
41 |
+
"et": "estonian",
|
42 |
+
"no": "norwegian",
|
43 |
+
"ml": "malayalam",
|
44 |
+
"sl": "slovene",
|
45 |
+
"da": "danish",
|
46 |
+
"fi": "finnish",
|
47 |
+
"sv": "swedish"
|
48 |
+
}
|
49 |
+
|
50 |
+
|
51 |
+
# Convert the list of languages to a string to display in the help text
|
52 |
+
language_options_str = ", ".join(language_options)
|
53 |
+
|
54 |
+
# Argument parser to handle optional parameters with descriptions
|
55 |
+
parser = argparse.ArgumentParser(
|
56 |
+
description="Convert eBooks to Audiobooks using a Text-to-Speech model. You can either launch the Gradio interface or run the script in headless mode for direct conversion.",
|
57 |
+
epilog="Example: python script.py --headless --ebook path_to_ebook --voice path_to_voice --language en --use_custom_model True --custom_model model.pth --custom_config config.json --custom_vocab vocab.json"
|
58 |
+
)
|
59 |
+
parser.add_argument("--share", type=bool, default=False, help="Set to True to enable a public shareable Gradio link. Defaults to False.")
|
60 |
+
parser.add_argument("--headless", type=bool, default=False, help="Set to True to run in headless mode without the Gradio interface. Defaults to False.")
|
61 |
+
parser.add_argument("--ebook", type=str, help="Path to the ebook file for conversion. Required in headless mode.")
|
62 |
+
parser.add_argument("--voice", type=str, help="Path to the target voice file for TTS. Optional, uses a default voice if not provided.")
|
63 |
+
parser.add_argument("--language", type=str, default="en",
|
64 |
+
help=f"Language for the audiobook conversion. Options: {language_options_str}. Defaults to English (en).")
|
65 |
+
parser.add_argument("--use_custom_model", type=bool, default=False,
|
66 |
+
help="Set to True to use a custom TTS model. Defaults to False. Must be True to use custom models, otherwise you'll get an error.")
|
67 |
+
parser.add_argument("--custom_model", type=str, help="Path to the custom model file (.pth). Required if using a custom model.")
|
68 |
+
parser.add_argument("--custom_config", type=str, help="Path to the custom config file (config.json). Required if using a custom model.")
|
69 |
+
parser.add_argument("--custom_vocab", type=str, help="Path to the custom vocab file (vocab.json). Required if using a custom model.")
|
70 |
+
parser.add_argument("--custom_model_url", type=str,
|
71 |
+
help=("URL to download the custom model as a zip file. Optional, but will be used if provided. "
|
72 |
+
"Examples include David Attenborough's model: "
|
73 |
+
"'https://huggingface.co/drewThomasson/xtts_David_Attenborough_fine_tune/resolve/main/Finished_model_files.zip?download=true'. "
|
74 |
+
"More XTTS fine-tunes can be found on my Hugging Face at 'https://huggingface.co/drewThomasson'."))
|
75 |
+
parser.add_argument("--temperature", type=float, default=0.65, help="Temperature for the model. Defaults to 0.65. Higher Tempatures will lead to more creative outputs IE: more Hallucinations. Lower Tempatures will be more monotone outputs IE: less Hallucinations.")
|
76 |
+
parser.add_argument("--length_penalty", type=float, default=1.0, help="A length penalty applied to the autoregressive decoder. Defaults to 1.0. Not applied to custom models.")
|
77 |
+
parser.add_argument("--repetition_penalty", type=float, default=2.0, help="A penalty that prevents the autoregressive decoder from repeating itself. Defaults to 2.0.")
|
78 |
+
parser.add_argument("--top_k", type=int, default=50, help="Top-k sampling. Lower values mean more likely outputs and increased audio generation speed. Defaults to 50.")
|
79 |
+
parser.add_argument("--top_p", type=float, default=0.8, help="Top-p sampling. Lower values mean more likely outputs and increased audio generation speed. Defaults to 0.8.")
|
80 |
+
parser.add_argument("--speed", type=float, default=1.0, help="Speed factor for the speech generation. IE: How fast the Narrerator will speak. Defaults to 1.0.")
|
81 |
+
parser.add_argument("--enable_text_splitting", type=bool, default=False, help="Enable splitting text into sentences. Defaults to True.")
|
82 |
+
|
83 |
+
args = parser.parse_args()
|
84 |
+
|
85 |
+
|
86 |
+
|
87 |
+
import os
|
88 |
+
import shutil
|
89 |
+
import subprocess
|
90 |
+
import re
|
91 |
+
from pydub import AudioSegment
|
92 |
+
import tempfile
|
93 |
+
from pydub import AudioSegment
|
94 |
+
import nltk
|
95 |
+
from nltk.tokenize import sent_tokenize
|
96 |
+
import sys
|
97 |
+
import torch
|
98 |
+
from TTS.api import TTS
|
99 |
+
from TTS.tts.configs.xtts_config import XttsConfig
|
100 |
+
from TTS.tts.models.xtts import Xtts
|
101 |
+
from tqdm import tqdm
|
102 |
+
import gradio as gr
|
103 |
+
from gradio import Progress
|
104 |
+
import urllib.request
|
105 |
+
import zipfile
|
106 |
+
import socket
|
107 |
+
#import MeCab
|
108 |
+
#import unidic
|
109 |
+
|
110 |
+
#nltk.download('punkt_tab')
|
111 |
+
|
112 |
+
# Import the locally stored Xtts default model
|
113 |
+
#import import_locally_stored_tts_model_files
|
114 |
+
|
115 |
+
#make the nltk folder point to the nltk folder in the app dir
|
116 |
+
#nltk.data.path.append('/home/user/app/nltk_data')
|
117 |
+
|
118 |
+
# Download UniDic if it's not already installed
|
119 |
+
#unidic.download()
|
120 |
+
|
121 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
122 |
+
print(f"Device selected is: {device}")
|
123 |
+
|
124 |
+
#nltk.download('punkt') # Make sure to download the necessary models
|
125 |
+
|
126 |
+
|
127 |
+
def download_and_extract_zip(url, extract_to='.'):
|
128 |
+
try:
|
129 |
+
# Ensure the directory exists
|
130 |
+
os.makedirs(extract_to, exist_ok=True)
|
131 |
+
|
132 |
+
zip_path = os.path.join(extract_to, 'model.zip')
|
133 |
+
|
134 |
+
# Download with progress bar
|
135 |
+
with tqdm(unit='B', unit_scale=True, miniters=1, desc="Downloading Model") as t:
|
136 |
+
def reporthook(blocknum, blocksize, totalsize):
|
137 |
+
t.total = totalsize
|
138 |
+
t.update(blocknum * blocksize - t.n)
|
139 |
+
|
140 |
+
urllib.request.urlretrieve(url, zip_path, reporthook=reporthook)
|
141 |
+
print(f"Downloaded zip file to {zip_path}")
|
142 |
+
|
143 |
+
# Unzipping with progress bar
|
144 |
+
with zipfile.ZipFile(zip_path, 'r') as zip_ref:
|
145 |
+
files = zip_ref.namelist()
|
146 |
+
with tqdm(total=len(files), unit="file", desc="Extracting Files") as t:
|
147 |
+
for file in files:
|
148 |
+
if not file.endswith('/'): # Skip directories
|
149 |
+
# Extract the file to the temporary directory
|
150 |
+
extracted_path = zip_ref.extract(file, extract_to)
|
151 |
+
# Move the file to the base directory
|
152 |
+
base_file_path = os.path.join(extract_to, os.path.basename(file))
|
153 |
+
os.rename(extracted_path, base_file_path)
|
154 |
+
t.update(1)
|
155 |
+
|
156 |
+
# Cleanup: Remove the ZIP file and any empty folders
|
157 |
+
os.remove(zip_path)
|
158 |
+
for root, dirs, files in os.walk(extract_to, topdown=False):
|
159 |
+
for name in dirs:
|
160 |
+
os.rmdir(os.path.join(root, name))
|
161 |
+
print(f"Extracted files to {extract_to}")
|
162 |
+
|
163 |
+
# Check if all required files are present
|
164 |
+
required_files = ['model.pth', 'config.json', 'vocab.json_']
|
165 |
+
missing_files = [file for file in required_files if not os.path.exists(os.path.join(extract_to, file))]
|
166 |
+
|
167 |
+
if not missing_files:
|
168 |
+
print("All required files (model.pth, config.json, vocab.json_) found.")
|
169 |
+
else:
|
170 |
+
print(f"Missing files: {', '.join(missing_files)}")
|
171 |
+
|
172 |
+
except Exception as e:
|
173 |
+
print(f"Failed to download or extract zip file: {e}")
|
174 |
+
|
175 |
+
|
176 |
+
|
177 |
+
def is_folder_empty(folder_path):
|
178 |
+
if os.path.exists(folder_path) and os.path.isdir(folder_path):
|
179 |
+
# List directory contents
|
180 |
+
if not os.listdir(folder_path):
|
181 |
+
return True # The folder is empty
|
182 |
+
else:
|
183 |
+
return False # The folder is not empty
|
184 |
+
else:
|
185 |
+
print(f"The path {folder_path} is not a valid folder.")
|
186 |
+
return None # The path is not a valid folder
|
187 |
+
|
188 |
+
def remove_folder_with_contents(folder_path):
|
189 |
+
try:
|
190 |
+
shutil.rmtree(folder_path)
|
191 |
+
print(f"Successfully removed {folder_path} and all of its contents.")
|
192 |
+
except Exception as e:
|
193 |
+
print(f"Error removing {folder_path}: {e}")
|
194 |
+
|
195 |
+
|
196 |
+
|
197 |
+
|
198 |
+
def wipe_folder(folder_path):
|
199 |
+
# Check if the folder exists
|
200 |
+
if not os.path.exists(folder_path):
|
201 |
+
print(f"The folder {folder_path} does not exist.")
|
202 |
+
return
|
203 |
+
|
204 |
+
# Iterate over all the items in the given folder
|
205 |
+
for item in os.listdir(folder_path):
|
206 |
+
item_path = os.path.join(folder_path, item)
|
207 |
+
# If it's a file, remove it and print a message
|
208 |
+
if os.path.isfile(item_path):
|
209 |
+
os.remove(item_path)
|
210 |
+
print(f"Removed file: {item_path}")
|
211 |
+
# If it's a directory, remove it recursively and print a message
|
212 |
+
elif os.path.isdir(item_path):
|
213 |
+
shutil.rmtree(item_path)
|
214 |
+
print(f"Removed directory and its contents: {item_path}")
|
215 |
+
|
216 |
+
print(f"All contents wiped from {folder_path}.")
|
217 |
+
|
218 |
+
|
219 |
+
# Example usage
|
220 |
+
# folder_to_wipe = 'path_to_your_folder'
|
221 |
+
# wipe_folder(folder_to_wipe)
|
222 |
+
|
223 |
+
|
224 |
+
def create_m4b_from_chapters(input_dir, ebook_file, output_dir):
|
225 |
+
# Function to sort chapters based on their numeric order
|
226 |
+
def sort_key(chapter_file):
|
227 |
+
numbers = re.findall(r'\d+', chapter_file)
|
228 |
+
return int(numbers[0]) if numbers else 0
|
229 |
+
|
230 |
+
# Extract metadata and cover image from the eBook file
|
231 |
+
def extract_metadata_and_cover(ebook_path):
|
232 |
+
try:
|
233 |
+
cover_path = ebook_path.rsplit('.', 1)[0] + '.jpg'
|
234 |
+
subprocess.run(['ebook-meta', ebook_path, '--get-cover', cover_path], check=True)
|
235 |
+
if os.path.exists(cover_path):
|
236 |
+
return cover_path
|
237 |
+
except Exception as e:
|
238 |
+
print(f"Error extracting eBook metadata or cover: {e}")
|
239 |
+
return None
|
240 |
+
# Combine WAV files into a single file
|
241 |
+
def combine_wav_files(chapter_files, output_path, batch_size=256):
|
242 |
+
# Initialize an empty audio segment
|
243 |
+
combined_audio = AudioSegment.empty()
|
244 |
+
|
245 |
+
# Process the chapter files in batches
|
246 |
+
for i in range(0, len(chapter_files), batch_size):
|
247 |
+
batch_files = chapter_files[i:i + batch_size]
|
248 |
+
batch_audio = AudioSegment.empty() # Initialize an empty AudioSegment for the batch
|
249 |
+
|
250 |
+
# Sequentially append each file in the current batch to the batch_audio
|
251 |
+
for chapter_file in batch_files:
|
252 |
+
audio_segment = AudioSegment.from_wav(chapter_file)
|
253 |
+
batch_audio += audio_segment
|
254 |
+
|
255 |
+
# Combine the batch audio with the overall combined_audio
|
256 |
+
combined_audio += batch_audio
|
257 |
+
|
258 |
+
# Export the combined audio to the output file path
|
259 |
+
combined_audio.export(output_path, format='wav')
|
260 |
+
print(f"Combined audio saved to {output_path}")
|
261 |
+
|
262 |
+
# Function to generate metadata for M4B chapters
|
263 |
+
def generate_ffmpeg_metadata(chapter_files, metadata_file):
|
264 |
+
with open(metadata_file, 'w') as file:
|
265 |
+
file.write(';FFMETADATA1\n')
|
266 |
+
start_time = 0
|
267 |
+
for index, chapter_file in enumerate(chapter_files):
|
268 |
+
duration_ms = len(AudioSegment.from_wav(chapter_file))
|
269 |
+
file.write(f'[CHAPTER]\nTIMEBASE=1/1000\nSTART={start_time}\n')
|
270 |
+
file.write(f'END={start_time + duration_ms}\ntitle=Chapter {index + 1}\n')
|
271 |
+
start_time += duration_ms
|
272 |
+
|
273 |
+
# Generate the final M4B file using ffmpeg
|
274 |
+
def create_m4b(combined_wav, metadata_file, cover_image, output_m4b):
|
275 |
+
# Ensure the output directory exists
|
276 |
+
os.makedirs(os.path.dirname(output_m4b), exist_ok=True)
|
277 |
+
|
278 |
+
ffmpeg_cmd = ['ffmpeg', '-i', combined_wav, '-i', metadata_file]
|
279 |
+
if cover_image:
|
280 |
+
ffmpeg_cmd += ['-i', cover_image, '-map', '0:a', '-map', '2:v']
|
281 |
+
else:
|
282 |
+
ffmpeg_cmd += ['-map', '0:a']
|
283 |
+
|
284 |
+
ffmpeg_cmd += ['-map_metadata', '1', '-c:a', 'aac', '-b:a', '192k']
|
285 |
+
if cover_image:
|
286 |
+
ffmpeg_cmd += ['-c:v', 'png', '-disposition:v', 'attached_pic']
|
287 |
+
ffmpeg_cmd += [output_m4b]
|
288 |
+
|
289 |
+
subprocess.run(ffmpeg_cmd, check=True)
|
290 |
+
|
291 |
+
|
292 |
+
|
293 |
+
# Main logic
|
294 |
+
chapter_files = sorted([os.path.join(input_dir, f) for f in os.listdir(input_dir) if f.endswith('.wav')], key=sort_key)
|
295 |
+
temp_dir = tempfile.gettempdir()
|
296 |
+
temp_combined_wav = os.path.join(temp_dir, 'combined.wav')
|
297 |
+
metadata_file = os.path.join(temp_dir, 'metadata.txt')
|
298 |
+
cover_image = extract_metadata_and_cover(ebook_file)
|
299 |
+
output_m4b = os.path.join(output_dir, os.path.splitext(os.path.basename(ebook_file))[0] + '.m4b')
|
300 |
+
|
301 |
+
combine_wav_files(chapter_files, temp_combined_wav)
|
302 |
+
generate_ffmpeg_metadata(chapter_files, metadata_file)
|
303 |
+
create_m4b(temp_combined_wav, metadata_file, cover_image, output_m4b)
|
304 |
+
|
305 |
+
# Cleanup
|
306 |
+
if os.path.exists(temp_combined_wav):
|
307 |
+
os.remove(temp_combined_wav)
|
308 |
+
if os.path.exists(metadata_file):
|
309 |
+
os.remove(metadata_file)
|
310 |
+
if cover_image and os.path.exists(cover_image):
|
311 |
+
os.remove(cover_image)
|
312 |
+
|
313 |
+
# Example usage
|
314 |
+
# create_m4b_from_chapters('path_to_chapter_wavs', 'path_to_ebook_file', 'path_to_output_dir')
|
315 |
+
|
316 |
+
|
317 |
+
|
318 |
+
|
319 |
+
|
320 |
+
|
321 |
+
#this code right here isnt the book grabbing thing but its before to refrence in order 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
|
322 |
+
import os
|
323 |
+
import subprocess
|
324 |
+
import ebooklib
|
325 |
+
from ebooklib import epub
|
326 |
+
from bs4 import BeautifulSoup
|
327 |
+
import re
|
328 |
+
import csv
|
329 |
+
import nltk
|
330 |
+
|
331 |
+
# Only run the main script if Value is True
|
332 |
+
def create_chapter_labeled_book(ebook_file_path):
|
333 |
+
# Function to ensure the existence of a directory
|
334 |
+
def ensure_directory(directory_path):
|
335 |
+
if not os.path.exists(directory_path):
|
336 |
+
os.makedirs(directory_path)
|
337 |
+
print(f"Created directory: {directory_path}")
|
338 |
+
|
339 |
+
ensure_directory(os.path.join(".", 'Working_files', 'Book'))
|
340 |
+
|
341 |
+
def convert_to_epub(input_path, output_path):
|
342 |
+
# Convert the ebook to EPUB format using Calibre's ebook-convert
|
343 |
+
try:
|
344 |
+
subprocess.run(['ebook-convert', input_path, output_path], check=True)
|
345 |
+
except subprocess.CalledProcessError as e:
|
346 |
+
print(f"An error occurred while converting the eBook: {e}")
|
347 |
+
return False
|
348 |
+
return True
|
349 |
+
|
350 |
+
def save_chapters_as_text(epub_path):
|
351 |
+
# Create the directory if it doesn't exist
|
352 |
+
directory = os.path.join(".", "Working_files", "temp_ebook")
|
353 |
+
ensure_directory(directory)
|
354 |
+
|
355 |
+
# Open the EPUB file
|
356 |
+
book = epub.read_epub(epub_path)
|
357 |
+
|
358 |
+
previous_chapter_text = ''
|
359 |
+
previous_filename = ''
|
360 |
+
chapter_counter = 0
|
361 |
+
|
362 |
+
# Iterate through the items in the EPUB file
|
363 |
+
for item in book.get_items():
|
364 |
+
if item.get_type() == ebooklib.ITEM_DOCUMENT:
|
365 |
+
# Use BeautifulSoup to parse HTML content
|
366 |
+
soup = BeautifulSoup(item.get_content(), 'html.parser')
|
367 |
+
text = soup.get_text()
|
368 |
+
|
369 |
+
# Check if the text is not empty
|
370 |
+
if text.strip():
|
371 |
+
if len(text) < 2300 and previous_filename:
|
372 |
+
# Append text to the previous chapter if it's short
|
373 |
+
with open(previous_filename, 'a', encoding='utf-8') as file:
|
374 |
+
file.write('\n' + text)
|
375 |
+
else:
|
376 |
+
# Create a new chapter file and increment the counter
|
377 |
+
previous_filename = os.path.join(directory, f"chapter_{chapter_counter}.txt")
|
378 |
+
chapter_counter += 1
|
379 |
+
with open(previous_filename, 'w', encoding='utf-8') as file:
|
380 |
+
file.write(text)
|
381 |
+
print(f"Saved chapter: {previous_filename}")
|
382 |
+
|
383 |
+
# Example usage
|
384 |
+
input_ebook = ebook_file_path # Replace with your eBook file path
|
385 |
+
output_epub = os.path.join(".", "Working_files", "temp.epub")
|
386 |
+
|
387 |
+
|
388 |
+
if os.path.exists(output_epub):
|
389 |
+
os.remove(output_epub)
|
390 |
+
print(f"File {output_epub} has been removed.")
|
391 |
+
else:
|
392 |
+
print(f"The file {output_epub} does not exist.")
|
393 |
+
|
394 |
+
if convert_to_epub(input_ebook, output_epub):
|
395 |
+
save_chapters_as_text(output_epub)
|
396 |
+
|
397 |
+
# Download the necessary NLTK data (if not already present)
|
398 |
+
#nltk.download('punkt')
|
399 |
+
|
400 |
+
def process_chapter_files(folder_path, output_csv):
|
401 |
+
with open(output_csv, 'w', newline='', encoding='utf-8') as csvfile:
|
402 |
+
writer = csv.writer(csvfile)
|
403 |
+
# Write the header row
|
404 |
+
writer.writerow(['Text', 'Start Location', 'End Location', 'Is Quote', 'Speaker', 'Chapter'])
|
405 |
+
|
406 |
+
# Process each chapter file
|
407 |
+
chapter_files = sorted(os.listdir(folder_path), key=lambda x: int(x.split('_')[1].split('.')[0]))
|
408 |
+
for filename in chapter_files:
|
409 |
+
if filename.startswith('chapter_') and filename.endswith('.txt'):
|
410 |
+
chapter_number = int(filename.split('_')[1].split('.')[0])
|
411 |
+
file_path = os.path.join(folder_path, filename)
|
412 |
+
|
413 |
+
try:
|
414 |
+
with open(file_path, 'r', encoding='utf-8') as file:
|
415 |
+
text = file.read()
|
416 |
+
# Insert "NEWCHAPTERABC" at the beginning of each chapter's text
|
417 |
+
if text:
|
418 |
+
text = "NEWCHAPTERABC" + text
|
419 |
+
sentences = nltk.tokenize.sent_tokenize(text)
|
420 |
+
for sentence in sentences:
|
421 |
+
start_location = text.find(sentence)
|
422 |
+
end_location = start_location + len(sentence)
|
423 |
+
writer.writerow([sentence, start_location, end_location, 'True', 'Narrator', chapter_number])
|
424 |
+
except Exception as e:
|
425 |
+
print(f"Error processing file {filename}: {e}")
|
426 |
+
|
427 |
+
# Example usage
|
428 |
+
folder_path = os.path.join(".", "Working_files", "temp_ebook")
|
429 |
+
output_csv = os.path.join(".", "Working_files", "Book", "Other_book.csv")
|
430 |
+
|
431 |
+
process_chapter_files(folder_path, output_csv)
|
432 |
+
|
433 |
+
def sort_key(filename):
|
434 |
+
"""Extract chapter number for sorting."""
|
435 |
+
match = re.search(r'chapter_(\d+)\.txt', filename)
|
436 |
+
return int(match.group(1)) if match else 0
|
437 |
+
|
438 |
+
def combine_chapters(input_folder, output_file):
|
439 |
+
# Create the output folder if it doesn't exist
|
440 |
+
os.makedirs(os.path.dirname(output_file), exist_ok=True)
|
441 |
+
|
442 |
+
# List all txt files and sort them by chapter number
|
443 |
+
files = [f for f in os.listdir(input_folder) if f.endswith('.txt')]
|
444 |
+
sorted_files = sorted(files, key=sort_key)
|
445 |
+
|
446 |
+
with open(output_file, 'w', encoding='utf-8') as outfile: # Specify UTF-8 encoding here
|
447 |
+
for i, filename in enumerate(sorted_files):
|
448 |
+
with open(os.path.join(input_folder, filename), 'r', encoding='utf-8') as infile: # And here
|
449 |
+
outfile.write(infile.read())
|
450 |
+
# Add the marker unless it's the last file
|
451 |
+
if i < len(sorted_files) - 1:
|
452 |
+
outfile.write("\nNEWCHAPTERABC\n")
|
453 |
+
|
454 |
+
# Paths
|
455 |
+
input_folder = os.path.join(".", 'Working_files', 'temp_ebook')
|
456 |
+
output_file = os.path.join(".", 'Working_files', 'Book', 'Chapter_Book.txt')
|
457 |
+
|
458 |
+
|
459 |
+
# Combine the chapters
|
460 |
+
combine_chapters(input_folder, output_file)
|
461 |
+
|
462 |
+
ensure_directory(os.path.join(".", "Working_files", "Book"))
|
463 |
+
|
464 |
+
|
465 |
+
#create_chapter_labeled_book()
|
466 |
+
|
467 |
+
|
468 |
+
|
469 |
+
|
470 |
+
import os
|
471 |
+
import subprocess
|
472 |
+
import sys
|
473 |
+
import torchaudio
|
474 |
+
|
475 |
+
# Check if Calibre's ebook-convert tool is installed
|
476 |
+
def calibre_installed():
|
477 |
+
try:
|
478 |
+
subprocess.run(['ebook-convert', '--version'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
479 |
+
return True
|
480 |
+
except FileNotFoundError:
|
481 |
+
print("Calibre is not installed. Please install Calibre for this functionality.")
|
482 |
+
return False
|
483 |
+
|
484 |
+
|
485 |
+
import os
|
486 |
+
import torch
|
487 |
+
from TTS.api import TTS
|
488 |
+
from nltk.tokenize import sent_tokenize
|
489 |
+
from pydub import AudioSegment
|
490 |
+
|
491 |
+
default_target_voice_path = "default_voice.wav" # Ensure this is a valid path
|
492 |
+
default_language_code = "en"
|
493 |
+
|
494 |
+
|
495 |
+
# Function to check if vocab.json exists and rename it
|
496 |
+
def rename_vocab_file_if_exists(directory):
|
497 |
+
vocab_path = os.path.join(directory, 'vocab.json')
|
498 |
+
new_vocab_path = os.path.join(directory, 'vocab.json_')
|
499 |
+
|
500 |
+
# Check if vocab.json exists
|
501 |
+
if os.path.exists(vocab_path):
|
502 |
+
# Rename the file
|
503 |
+
os.rename(vocab_path, new_vocab_path)
|
504 |
+
print(f"Renamed {vocab_path} to {new_vocab_path}")
|
505 |
+
return True # Return True if the file was found and renamed
|
506 |
+
|
507 |
+
|
508 |
+
def combine_wav_files(input_directory, output_directory, file_name):
|
509 |
+
# Ensure that the output directory exists, create it if necessary
|
510 |
+
os.makedirs(output_directory, exist_ok=True)
|
511 |
+
|
512 |
+
# Specify the output file path
|
513 |
+
output_file_path = os.path.join(output_directory, file_name)
|
514 |
+
|
515 |
+
# Initialize an empty audio segment
|
516 |
+
combined_audio = AudioSegment.empty()
|
517 |
+
|
518 |
+
# Get a list of all .wav files in the specified input directory and sort them
|
519 |
+
input_file_paths = sorted(
|
520 |
+
[os.path.join(input_directory, f) for f in os.listdir(input_directory) if f.endswith(".wav")],
|
521 |
+
key=lambda f: int(''.join(filter(str.isdigit, f)))
|
522 |
+
)
|
523 |
+
|
524 |
+
# Sequentially append each file to the combined_audio
|
525 |
+
for input_file_path in input_file_paths:
|
526 |
+
audio_segment = AudioSegment.from_wav(input_file_path)
|
527 |
+
combined_audio += audio_segment
|
528 |
+
|
529 |
+
# Export the combined audio to the output file path
|
530 |
+
combined_audio.export(output_file_path, format='wav')
|
531 |
+
|
532 |
+
print(f"Combined audio saved to {output_file_path}")
|
533 |
+
|
534 |
+
# Function to split long strings into parts
|
535 |
+
# Modify the function to handle special cases for Chinese, Italian, and default for others
|
536 |
+
def split_long_sentence(sentence, language='en', max_pauses=10):
|
537 |
+
"""
|
538 |
+
Splits a sentence into parts based on length or number of pauses without recursion.
|
539 |
+
|
540 |
+
:param sentence: The sentence to split.
|
541 |
+
:param language: The language of the sentence (default is English).
|
542 |
+
:param max_pauses: Maximum allowed number of pauses in a sentence.
|
543 |
+
:return: A list of sentence parts that meet the criteria.
|
544 |
+
"""
|
545 |
+
#Get the Max character length for the selected language -2 : with a default of 248 if no language is found
|
546 |
+
max_length = (char_limits.get(language, 250)-2)
|
547 |
+
|
548 |
+
# Adjust the pause punctuation symbols based on language
|
549 |
+
if language == 'zh-cn':
|
550 |
+
punctuation = [',', '。', ';', '?', '!'] # Chinese-specific pause punctuation including sentence-ending marks
|
551 |
+
elif language == 'ja':
|
552 |
+
punctuation = ['、', '。', ';', '?', '!'] # Japanese-specific pause punctuation
|
553 |
+
elif language == 'ko':
|
554 |
+
punctuation = [',', '。', ';', '?', '!'] # Korean-specific pause punctuation
|
555 |
+
elif language == 'ar':
|
556 |
+
punctuation = ['،', '؛', '؟', '!', '·', '؛', '.'] # Arabic-specific punctuation
|
557 |
+
elif language == 'en':
|
558 |
+
punctuation = [',', ';', '.'] # English-specific pause punctuation
|
559 |
+
else:
|
560 |
+
# Default pause punctuation for other languages (es, fr, de, it, pt, pl, cs, ru, nl, tr, hu)
|
561 |
+
punctuation = [',', '.', ';', ':', '?', '!']
|
562 |
+
|
563 |
+
|
564 |
+
|
565 |
+
parts = []
|
566 |
+
while len(sentence) > max_length or sum(sentence.count(p) for p in punctuation) > max_pauses:
|
567 |
+
possible_splits = [i for i, char in enumerate(sentence) if char in punctuation and i < max_length]
|
568 |
+
if possible_splits:
|
569 |
+
# Find the best place to split the sentence, preferring the last possible split to keep parts longer
|
570 |
+
split_at = possible_splits[-1] + 1
|
571 |
+
else:
|
572 |
+
# If no punctuation to split on within max_length, split at max_length
|
573 |
+
split_at = max_length
|
574 |
+
|
575 |
+
# Split the sentence and add the first part to the list
|
576 |
+
parts.append(sentence[:split_at].strip())
|
577 |
+
sentence = sentence[split_at:].strip()
|
578 |
+
|
579 |
+
# Add the remaining part of the sentence
|
580 |
+
parts.append(sentence)
|
581 |
+
return parts
|
582 |
+
|
583 |
+
"""
|
584 |
+
if 'tts' not in locals():
|
585 |
+
tts = TTS(selected_tts_model, progress_bar=True).to(device)
|
586 |
+
"""
|
587 |
+
from tqdm import tqdm
|
588 |
+
|
589 |
+
# Convert chapters to audio using XTTS
|
590 |
+
|
591 |
+
def convert_chapters_to_audio_custom_model(chapters_dir, output_audio_dir, temperature, length_penalty, repetition_penalty, top_k, top_p, speed, enable_text_splitting, target_voice_path=None, language=None, custom_model=None):
|
592 |
+
|
593 |
+
if target_voice_path==None:
|
594 |
+
target_voice_path = default_target_voice_path
|
595 |
+
|
596 |
+
if custom_model:
|
597 |
+
print("Loading custom model...")
|
598 |
+
config = XttsConfig()
|
599 |
+
config.load_json(custom_model['config'])
|
600 |
+
model = Xtts.init_from_config(config)
|
601 |
+
model.load_checkpoint(config, checkpoint_path=custom_model['model'], vocab_path=custom_model['vocab'], use_deepspeed=False)
|
602 |
+
model.to(device)
|
603 |
+
print("Computing speaker latents...")
|
604 |
+
gpt_cond_latent, speaker_embedding = model.get_conditioning_latents(audio_path=[target_voice_path])
|
605 |
+
else:
|
606 |
+
selected_tts_model = "tts_models/multilingual/multi-dataset/xtts_v2"
|
607 |
+
tts = TTS(selected_tts_model, progress_bar=False).to(device)
|
608 |
+
|
609 |
+
if not os.path.exists(output_audio_dir):
|
610 |
+
os.makedirs(output_audio_dir)
|
611 |
+
|
612 |
+
for chapter_file in sorted(os.listdir(chapters_dir)):
|
613 |
+
if chapter_file.endswith('.txt'):
|
614 |
+
match = re.search(r"chapter_(\d+).txt", chapter_file)
|
615 |
+
if match:
|
616 |
+
chapter_num = int(match.group(1))
|
617 |
+
else:
|
618 |
+
print(f"Skipping file {chapter_file} as it does not match the expected format.")
|
619 |
+
continue
|
620 |
+
|
621 |
+
chapter_path = os.path.join(chapters_dir, chapter_file)
|
622 |
+
output_file_name = f"audio_chapter_{chapter_num}.wav"
|
623 |
+
output_file_path = os.path.join(output_audio_dir, output_file_name)
|
624 |
+
temp_audio_directory = os.path.join(".", "Working_files", "temp")
|
625 |
+
os.makedirs(temp_audio_directory, exist_ok=True)
|
626 |
+
temp_count = 0
|
627 |
+
|
628 |
+
with open(chapter_path, 'r', encoding='utf-8') as file:
|
629 |
+
chapter_text = file.read()
|
630 |
+
# Check if the language code is supported
|
631 |
+
nltk_language = language_mapping.get(language)
|
632 |
+
if nltk_language:
|
633 |
+
# If the language is supported, tokenize using sent_tokenize
|
634 |
+
sentences = sent_tokenize(chapter_text, language=nltk_language)
|
635 |
+
else:
|
636 |
+
# If the language is not supported, handle it (e.g., return the text unchanged)
|
637 |
+
sentences = [chapter_text] # No tokenization, just wrap the text in a list
|
638 |
+
#sentences = sent_tokenize(chapter_text, language='italian' if language == 'it' else 'english')
|
639 |
+
for sentence in tqdm(sentences, desc=f"Chapter {chapter_num}"):
|
640 |
+
fragments = split_long_sentence(sentence, language=language)
|
641 |
+
for fragment in fragments:
|
642 |
+
if fragment != "":
|
643 |
+
print(f"Generating fragment: {fragment}...")
|
644 |
+
fragment_file_path = os.path.join(temp_audio_directory, f"{temp_count}.wav")
|
645 |
+
if custom_model:
|
646 |
+
# length penalty will not apply for custome models, its just too much of a headache perhaps if someone else can do it for me lol, im just one man :(
|
647 |
+
out = model.inference(fragment, language, gpt_cond_latent, speaker_embedding, temperature=temperature, repetition_penalty=repetition_penalty, top_k=top_k, top_p=top_p, speed=speed, enable_text_splitting=enable_text_splitting)
|
648 |
+
#out = model.inference(fragment, language, gpt_cond_latent, speaker_embedding, temperature, length_penalty, repetition_penalty, top_k, top_p, speed, enable_text_splitting)
|
649 |
+
torchaudio.save(fragment_file_path, torch.tensor(out["wav"]).unsqueeze(0), 24000)
|
650 |
+
else:
|
651 |
+
speaker_wav_path = target_voice_path if target_voice_path else default_target_voice_path
|
652 |
+
language_code = language if language else default_language_code
|
653 |
+
tts.tts_to_file(text=fragment, file_path=fragment_file_path, speaker_wav=speaker_wav_path, language=language_code, temperature=temperature, length_penalty=length_penalty, repetition_penalty=repetition_penalty, top_k=top_k, top_p=top_p, speed=speed, enable_text_splitting=enable_text_splitting)
|
654 |
+
|
655 |
+
temp_count += 1
|
656 |
+
|
657 |
+
combine_wav_files(temp_audio_directory, output_audio_dir, output_file_name)
|
658 |
+
wipe_folder(temp_audio_directory)
|
659 |
+
print(f"Converted chapter {chapter_num} to audio.")
|
660 |
+
|
661 |
+
|
662 |
+
|
663 |
+
def convert_chapters_to_audio_standard_model(chapters_dir, output_audio_dir, temperature, length_penalty, repetition_penalty, top_k, top_p, speed, enable_text_splitting, target_voice_path=None, language="en"):
|
664 |
+
selected_tts_model = "tts_models/multilingual/multi-dataset/xtts_v2"
|
665 |
+
tts = TTS(selected_tts_model, progress_bar=False).to(device)
|
666 |
+
|
667 |
+
if not os.path.exists(output_audio_dir):
|
668 |
+
os.makedirs(output_audio_dir)
|
669 |
+
|
670 |
+
for chapter_file in sorted(os.listdir(chapters_dir)):
|
671 |
+
if chapter_file.endswith('.txt'):
|
672 |
+
match = re.search(r"chapter_(\d+).txt", chapter_file)
|
673 |
+
if match:
|
674 |
+
chapter_num = int(match.group(1))
|
675 |
+
else:
|
676 |
+
print(f"Skipping file {chapter_file} as it does not match the expected format.")
|
677 |
+
continue
|
678 |
+
|
679 |
+
chapter_path = os.path.join(chapters_dir, chapter_file)
|
680 |
+
output_file_name = f"audio_chapter_{chapter_num}.wav"
|
681 |
+
output_file_path = os.path.join(output_audio_dir, output_file_name)
|
682 |
+
temp_audio_directory = os.path.join(".", "Working_files", "temp")
|
683 |
+
os.makedirs(temp_audio_directory, exist_ok=True)
|
684 |
+
temp_count = 0
|
685 |
+
|
686 |
+
with open(chapter_path, 'r', encoding='utf-8') as file:
|
687 |
+
chapter_text = file.read()
|
688 |
+
# Check if the language code is supported
|
689 |
+
nltk_language = language_mapping.get(language)
|
690 |
+
if nltk_language:
|
691 |
+
# If the language is supported, tokenize using sent_tokenize
|
692 |
+
sentences = sent_tokenize(chapter_text, language=nltk_language)
|
693 |
+
else:
|
694 |
+
# If the language is not supported, handle it (e.g., return the text unchanged)
|
695 |
+
sentences = [chapter_text] # No tokenization, just wrap the text in a list
|
696 |
+
#sentences = sent_tokenize(chapter_text, language='italian' if language == 'it' else 'english')
|
697 |
+
for sentence in tqdm(sentences, desc=f"Chapter {chapter_num}"):
|
698 |
+
fragments = split_long_sentence(sentence, language=language)
|
699 |
+
for fragment in fragments:
|
700 |
+
if fragment != "":
|
701 |
+
print(f"Generating fragment: {fragment}...")
|
702 |
+
fragment_file_path = os.path.join(temp_audio_directory, f"{temp_count}.wav")
|
703 |
+
speaker_wav_path = target_voice_path if target_voice_path else default_target_voice_path
|
704 |
+
tts.tts_to_file(
|
705 |
+
text=fragment,
|
706 |
+
file_path=fragment_file_path,
|
707 |
+
speaker_wav=speaker_wav_path,
|
708 |
+
language=language,
|
709 |
+
temperature=temperature,
|
710 |
+
length_penalty=length_penalty,
|
711 |
+
repetition_penalty=repetition_penalty,
|
712 |
+
top_k=top_k,
|
713 |
+
top_p=top_p,
|
714 |
+
speed=speed,
|
715 |
+
enable_text_splitting=enable_text_splitting
|
716 |
+
)
|
717 |
+
|
718 |
+
temp_count += 1
|
719 |
+
|
720 |
+
combine_wav_files(temp_audio_directory, output_audio_dir, output_file_name)
|
721 |
+
wipe_folder(temp_audio_directory)
|
722 |
+
print(f"Converted chapter {chapter_num} to audio.")
|
723 |
+
|
724 |
+
|
725 |
+
|
726 |
+
# Define the functions to be used in the Gradio interface
|
727 |
+
def convert_ebook_to_audio(ebook_file, target_voice_file, language, use_custom_model, custom_model_file, custom_config_file, custom_vocab_file, temperature, length_penalty, repetition_penalty, top_k, top_p, speed, enable_text_splitting, custom_model_url=None, progress=gr.Progress()):
|
728 |
+
|
729 |
+
ebook_file_path = args.ebook if args.ebook else ebook_file.name
|
730 |
+
target_voice = args.voice if args.voice else target_voice_file.name if target_voice_file else None
|
731 |
+
custom_model = None
|
732 |
+
|
733 |
+
|
734 |
+
working_files = os.path.join(".", "Working_files", "temp_ebook")
|
735 |
+
full_folder_working_files = os.path.join(".", "Working_files")
|
736 |
+
chapters_directory = os.path.join(".", "Working_files", "temp_ebook")
|
737 |
+
output_audio_directory = os.path.join(".", 'Chapter_wav_files')
|
738 |
+
remove_folder_with_contents(full_folder_working_files)
|
739 |
+
remove_folder_with_contents(output_audio_directory)
|
740 |
+
|
741 |
+
# If running in headless mode, use the language from args
|
742 |
+
if args.headless and args.language:
|
743 |
+
language = args.language
|
744 |
+
else:
|
745 |
+
language = language # Gradio dropdown value
|
746 |
+
|
747 |
+
# If headless is used with the custom model arguments
|
748 |
+
if args.use_custom_model and args.custom_model and args.custom_config and args.custom_vocab:
|
749 |
+
custom_model = {
|
750 |
+
'model': args.custom_model,
|
751 |
+
'config': args.custom_config,
|
752 |
+
'vocab': args.custom_vocab
|
753 |
+
}
|
754 |
+
|
755 |
+
elif use_custom_model and custom_model_file and custom_config_file and custom_vocab_file:
|
756 |
+
custom_model = {
|
757 |
+
'model': custom_model_file.name,
|
758 |
+
'config': custom_config_file.name,
|
759 |
+
'vocab': custom_vocab_file.name
|
760 |
+
}
|
761 |
+
if (use_custom_model and custom_model_url) or (args.use_custom_model and custom_model_url):
|
762 |
+
print(f"Received custom model URL: {custom_model_url}")
|
763 |
+
download_dir = os.path.join(".", "Working_files", "custom_model")
|
764 |
+
download_and_extract_zip(custom_model_url, download_dir)
|
765 |
+
|
766 |
+
# Check if vocab.json exists and rename it
|
767 |
+
if rename_vocab_file_if_exists(download_dir):
|
768 |
+
print("vocab.json file was found and renamed.")
|
769 |
+
|
770 |
+
custom_model = {
|
771 |
+
'model': os.path.join(download_dir, 'model.pth'),
|
772 |
+
'config': os.path.join(download_dir, 'config.json'),
|
773 |
+
'vocab': os.path.join(download_dir, 'vocab.json_')
|
774 |
+
}
|
775 |
+
|
776 |
+
try:
|
777 |
+
progress(0, desc="Starting conversion")
|
778 |
+
except Exception as e:
|
779 |
+
print(f"Error updating progress: {e}")
|
780 |
+
|
781 |
+
if not calibre_installed():
|
782 |
+
return "Calibre is not installed."
|
783 |
+
|
784 |
+
|
785 |
+
try:
|
786 |
+
progress(0.1, desc="Creating chapter-labeled book")
|
787 |
+
except Exception as e:
|
788 |
+
print(f"Error updating progress: {e}")
|
789 |
+
|
790 |
+
create_chapter_labeled_book(ebook_file_path)
|
791 |
+
audiobook_output_path = os.path.join(".", "Audiobooks")
|
792 |
+
|
793 |
+
try:
|
794 |
+
progress(0.3, desc="Converting chapters to audio")
|
795 |
+
except Exception as e:
|
796 |
+
print(f"Error updating progress: {e}")
|
797 |
+
|
798 |
+
if use_custom_model:
|
799 |
+
convert_chapters_to_audio_custom_model(chapters_directory, output_audio_directory, temperature, length_penalty, repetition_penalty, top_k, top_p, speed, enable_text_splitting, target_voice, language, custom_model)
|
800 |
+
else:
|
801 |
+
convert_chapters_to_audio_standard_model(chapters_directory, output_audio_directory, temperature, length_penalty, repetition_penalty, top_k, top_p, speed, enable_text_splitting, target_voice, language)
|
802 |
+
|
803 |
+
try:
|
804 |
+
progress(0.9, desc="Creating M4B from chapters")
|
805 |
+
except Exception as e:
|
806 |
+
print(f"Error updating progress: {e}")
|
807 |
+
|
808 |
+
create_m4b_from_chapters(output_audio_directory, ebook_file_path, audiobook_output_path)
|
809 |
+
|
810 |
+
# Get the name of the created M4B file
|
811 |
+
m4b_filename = os.path.splitext(os.path.basename(ebook_file_path))[0] + '.m4b'
|
812 |
+
m4b_filepath = os.path.join(audiobook_output_path, m4b_filename)
|
813 |
+
|
814 |
+
try:
|
815 |
+
progress(1.0, desc="Conversion complete")
|
816 |
+
except Exception as e:
|
817 |
+
print(f"Error updating progress: {e}")
|
818 |
+
print(f"Audiobook created at {m4b_filepath}")
|
819 |
+
return f"Audiobook created at {m4b_filepath}", m4b_filepath
|
820 |
+
|
821 |
+
|
822 |
+
def list_audiobook_files(audiobook_folder):
|
823 |
+
# List all files in the audiobook folder
|
824 |
+
files = []
|
825 |
+
for filename in os.listdir(audiobook_folder):
|
826 |
+
if filename.endswith('.m4b'): # Adjust the file extension as needed
|
827 |
+
files.append(os.path.join(audiobook_folder, filename))
|
828 |
+
return files
|
829 |
+
|
830 |
+
def download_audiobooks():
|
831 |
+
audiobook_output_path = os.path.join(".", "Audiobooks")
|
832 |
+
return list_audiobook_files(audiobook_output_path)
|
833 |
+
|
834 |
+
|
835 |
+
# Gradio UI setup
|
836 |
+
def run_gradio_interface():
|
837 |
+
language_options = [
|
838 |
+
"en", "es", "fr", "de", "it", "pt", "pl", "tr", "ru", "nl", "cs", "ar", "zh-cn", "ja", "hu", "ko"
|
839 |
+
]
|
840 |
+
|
841 |
+
theme = gr.themes.Soft(
|
842 |
+
primary_hue="blue",
|
843 |
+
secondary_hue="blue",
|
844 |
+
neutral_hue="blue",
|
845 |
+
text_size=gr.themes.sizes.text_md,
|
846 |
+
)
|
847 |
+
|
848 |
+
# Gradio UI setup
|
849 |
+
def run_gradio_interface():
|
850 |
+
language_options = [
|
851 |
+
"en", "es", "fr", "de", "it", "pt", "pl", "tr", "ru", "nl", "cs", "ar", "zh-cn", "ja", "hu", "ko"
|
852 |
+
]
|
853 |
+
|
854 |
+
theme = gr.themes.Soft(
|
855 |
+
primary_hue="blue",
|
856 |
+
secondary_hue="blue",
|
857 |
+
neutral_hue="blue",
|
858 |
+
text_size=gr.themes.sizes.text_md,
|
859 |
+
)
|
860 |
+
|
861 |
+
with gr.Blocks(theme=theme) as demo:
|
862 |
+
gr.Markdown(
|
863 |
+
"""
|
864 |
+
# eBook to Audiobook Converter
|
865 |
+
|
866 |
+
Transform your eBooks into immersive audiobooks with optional custom TTS models.
|
867 |
+
|
868 |
+
This interface is based on [Ebook2AudioBookXTTS](https://github.com/DrewThomasson/ebook2audiobookXTTS).
|
869 |
+
"""
|
870 |
+
)
|
871 |
+
|
872 |
+
with gr.Tabs(): # Create tabs for better UI organization
|
873 |
+
with gr.TabItem("Input Options"):
|
874 |
+
with gr.Row():
|
875 |
+
with gr.Column(scale=3):
|
876 |
+
ebook_file = gr.File(label="eBook File")
|
877 |
+
target_voice_file = gr.File(label="Target Voice File (Optional)")
|
878 |
+
language = gr.Dropdown(label="Language", choices=language_options, value="en")
|
879 |
+
|
880 |
+
with gr.Column(scale=3):
|
881 |
+
use_custom_model = gr.Checkbox(label="Use Custom Model")
|
882 |
+
custom_model_file = gr.File(label="Custom Model File (Optional)", visible=False)
|
883 |
+
custom_config_file = gr.File(label="Custom Config File (Optional)", visible=False)
|
884 |
+
custom_vocab_file = gr.File(label="Custom Vocab File (Optional)", visible=False)
|
885 |
+
custom_model_url = gr.Textbox(label="Custom Model Zip URL (Optional)", visible=False)
|
886 |
+
|
887 |
+
with gr.TabItem("Audio Generation Preferences"): # New tab for preferences
|
888 |
+
gr.Markdown(
|
889 |
+
"""
|
890 |
+
### Customize Audio Generation Parameters
|
891 |
+
|
892 |
+
Adjust the settings below to influence how the audio is generated. You can control the creativity, speed, repetition, and more.
|
893 |
+
"""
|
894 |
+
)
|
895 |
+
temperature = gr.Slider(
|
896 |
+
label="Temperature",
|
897 |
+
minimum=0.1,
|
898 |
+
maximum=10.0,
|
899 |
+
step=0.1,
|
900 |
+
value=0.65,
|
901 |
+
info="Higher values lead to more creative, unpredictable outputs. Lower values make it more monotone."
|
902 |
+
)
|
903 |
+
length_penalty = gr.Slider(
|
904 |
+
label="Length Penalty",
|
905 |
+
minimum=0.5,
|
906 |
+
maximum=10.0,
|
907 |
+
step=0.1,
|
908 |
+
value=1.0,
|
909 |
+
info="Penalize longer sequences. Higher values produce shorter outputs. Not applied to custom models."
|
910 |
+
)
|
911 |
+
repetition_penalty = gr.Slider(
|
912 |
+
label="Repetition Penalty",
|
913 |
+
minimum=1.0,
|
914 |
+
maximum=10.0,
|
915 |
+
step=0.1,
|
916 |
+
value=2.0,
|
917 |
+
info="Penalizes repeated phrases. Higher values reduce repetition."
|
918 |
+
)
|
919 |
+
top_k = gr.Slider(
|
920 |
+
label="Top-k Sampling",
|
921 |
+
minimum=10,
|
922 |
+
maximum=100,
|
923 |
+
step=1,
|
924 |
+
value=50,
|
925 |
+
info="Lower values restrict outputs to more likely words and increase speed at which audio generates. "
|
926 |
+
)
|
927 |
+
top_p = gr.Slider(
|
928 |
+
label="Top-p Sampling",
|
929 |
+
minimum=0.1,
|
930 |
+
maximum=1.0,
|
931 |
+
step=.01,
|
932 |
+
value=0.8,
|
933 |
+
info="Controls cumulative probability for word selection. Lower values make the output more predictable and increase speed at which audio generates."
|
934 |
+
)
|
935 |
+
speed = gr.Slider(
|
936 |
+
label="Speed",
|
937 |
+
minimum=0.5,
|
938 |
+
maximum=3.0,
|
939 |
+
step=0.1,
|
940 |
+
value=1.0,
|
941 |
+
info="Adjusts How fast the narrator will speak."
|
942 |
+
)
|
943 |
+
enable_text_splitting = gr.Checkbox(
|
944 |
+
label="Enable Text Splitting",
|
945 |
+
value=False,
|
946 |
+
info="Splits long texts into sentences to generate audio in chunks. Useful for very long inputs."
|
947 |
+
)
|
948 |
+
|
949 |
+
convert_btn = gr.Button("Convert to Audiobook", variant="primary")
|
950 |
+
output = gr.Textbox(label="Conversion Status")
|
951 |
+
audio_player = gr.Audio(label="Audiobook Player", type="filepath")
|
952 |
+
download_btn = gr.Button("Download Audiobook Files")
|
953 |
+
download_files = gr.File(label="Download Files", interactive=False)
|
954 |
+
|
955 |
+
convert_btn.click(
|
956 |
+
lambda *args: convert_ebook_to_audio(
|
957 |
+
*args[:7],
|
958 |
+
float(args[7]), # Ensure temperature is float
|
959 |
+
float(args[8]), # Ensure length_penalty is float
|
960 |
+
float(args[9]), # Ensure repetition_penalty is float
|
961 |
+
int(args[10]), # Ensure top_k is int
|
962 |
+
float(args[11]), # Ensure top_p is float
|
963 |
+
float(args[12]), # Ensure speed is float
|
964 |
+
*args[13:]
|
965 |
+
),
|
966 |
+
inputs=[
|
967 |
+
ebook_file, target_voice_file, language, use_custom_model, custom_model_file, custom_config_file,
|
968 |
+
custom_vocab_file, temperature, length_penalty, repetition_penalty,
|
969 |
+
top_k, top_p, speed, enable_text_splitting, custom_model_url
|
970 |
+
],
|
971 |
+
outputs=[output, audio_player]
|
972 |
+
)
|
973 |
+
|
974 |
+
|
975 |
+
use_custom_model.change(
|
976 |
+
lambda x: [gr.update(visible=x)] * 4,
|
977 |
+
inputs=[use_custom_model],
|
978 |
+
outputs=[custom_model_file, custom_config_file, custom_vocab_file, custom_model_url]
|
979 |
+
)
|
980 |
+
|
981 |
+
download_btn.click(
|
982 |
+
download_audiobooks,
|
983 |
+
outputs=[download_files]
|
984 |
+
)
|
985 |
+
|
986 |
+
# Get the correct local IP or localhost
|
987 |
+
hostname = socket.gethostname()
|
988 |
+
local_ip = socket.gethostbyname(hostname)
|
989 |
+
|
990 |
+
# Ensure Gradio runs and prints the correct local IP
|
991 |
+
print(f"Running on local URL: http://{local_ip}:7860")
|
992 |
+
print(f"Running on local URL: http://localhost:7860")
|
993 |
+
|
994 |
+
# Launch Gradio app
|
995 |
+
demo.launch(server_name="0.0.0.0", server_port=7860, share=args.share)
|
996 |
+
|
997 |
+
|
998 |
+
|
999 |
+
|
1000 |
+
|
1001 |
+
# Check if running in headless mode
|
1002 |
+
if args.headless:
|
1003 |
+
# If the arg.custom_model_url exists then use it as the custom_model_url lol
|
1004 |
+
custom_model_url = args.custom_model_url if args.custom_model_url else None
|
1005 |
+
|
1006 |
+
if not args.ebook:
|
1007 |
+
print("Error: In headless mode, you must specify an ebook file using --ebook.")
|
1008 |
+
exit(1)
|
1009 |
+
|
1010 |
+
ebook_file_path = args.ebook
|
1011 |
+
target_voice = args.voice if args.voice else None
|
1012 |
+
custom_model = None
|
1013 |
+
|
1014 |
+
if args.use_custom_model:
|
1015 |
+
# Check if custom_model_url is provided
|
1016 |
+
if args.custom_model_url:
|
1017 |
+
# Download the custom model from the provided URL
|
1018 |
+
custom_model_url = args.custom_model_url
|
1019 |
+
else:
|
1020 |
+
# If no URL is provided, ensure all custom model files are provided
|
1021 |
+
if not args.custom_model or not args.custom_config or not args.custom_vocab:
|
1022 |
+
print("Error: You must provide either a --custom_model_url or all of the following arguments:")
|
1023 |
+
print("--custom_model, --custom_config, and --custom_vocab")
|
1024 |
+
exit(1)
|
1025 |
+
else:
|
1026 |
+
# Assign the custom model files
|
1027 |
+
custom_model = {
|
1028 |
+
'model': args.custom_model,
|
1029 |
+
'config': args.custom_config,
|
1030 |
+
'vocab': args.custom_vocab
|
1031 |
+
}
|
1032 |
+
|
1033 |
+
|
1034 |
+
|
1035 |
+
# Example headless execution
|
1036 |
+
convert_ebook_to_audio(ebook_file_path, target_voice, args.language, args.use_custom_model, args.custom_model, args.custom_config, args.custom_vocab, args.temperature, args.length_penalty, args.repetition_penalty, args.top_k, args.top_p, args.speed, args.enable_text_splitting, custom_model_url)
|
1037 |
+
|
1038 |
+
|
1039 |
+
else:
|
1040 |
+
# Launch Gradio UI
|
1041 |
+
run_gradio_interface()
|
legacy/v1.0/default_voice.wav
ADDED
Binary file (291 kB). View file
|
|
legacy/v1.0/demo_mini_story_chapters_Drew.epub
ADDED
Binary file (415 kB). View file
|
|
legacy/v1.0/demo_web_gui.gif
ADDED
Git LFS Details
|
legacy/v1.0/legacy/custom_model_ebook2audiobookXTTS.py
ADDED
@@ -0,0 +1,484 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
print("starting...")
|
2 |
+
|
3 |
+
import os
|
4 |
+
import shutil
|
5 |
+
import subprocess
|
6 |
+
import re
|
7 |
+
from pydub import AudioSegment
|
8 |
+
import tempfile
|
9 |
+
from pydub import AudioSegment
|
10 |
+
import os
|
11 |
+
import nltk
|
12 |
+
from nltk.tokenize import sent_tokenize
|
13 |
+
import sys
|
14 |
+
import torch
|
15 |
+
from TTS.api import TTS
|
16 |
+
from TTS.tts.configs.xtts_config import XttsConfig
|
17 |
+
from TTS.tts.models.xtts import Xtts
|
18 |
+
from tqdm import tqdm
|
19 |
+
|
20 |
+
nltk.download('punkt') # Make sure to download the necessary models
|
21 |
+
def is_folder_empty(folder_path):
|
22 |
+
if os.path.exists(folder_path) and os.path.isdir(folder_path):
|
23 |
+
# List directory contents
|
24 |
+
if not os.listdir(folder_path):
|
25 |
+
return True # The folder is empty
|
26 |
+
else:
|
27 |
+
return False # The folder is not empty
|
28 |
+
else:
|
29 |
+
print(f"The path {folder_path} is not a valid folder.")
|
30 |
+
return None # The path is not a valid folder
|
31 |
+
|
32 |
+
def remove_folder_with_contents(folder_path):
|
33 |
+
try:
|
34 |
+
shutil.rmtree(folder_path)
|
35 |
+
print(f"Successfully removed {folder_path} and all of its contents.")
|
36 |
+
except Exception as e:
|
37 |
+
print(f"Error removing {folder_path}: {e}")
|
38 |
+
|
39 |
+
|
40 |
+
|
41 |
+
|
42 |
+
def wipe_folder(folder_path):
|
43 |
+
# Check if the folder exists
|
44 |
+
if not os.path.exists(folder_path):
|
45 |
+
print(f"The folder {folder_path} does not exist.")
|
46 |
+
return
|
47 |
+
|
48 |
+
# Iterate over all the items in the given folder
|
49 |
+
for item in os.listdir(folder_path):
|
50 |
+
item_path = os.path.join(folder_path, item)
|
51 |
+
# If it's a file, remove it and print a message
|
52 |
+
if os.path.isfile(item_path):
|
53 |
+
os.remove(item_path)
|
54 |
+
print(f"Removed file: {item_path}")
|
55 |
+
# If it's a directory, remove it recursively and print a message
|
56 |
+
elif os.path.isdir(item_path):
|
57 |
+
shutil.rmtree(item_path)
|
58 |
+
print(f"Removed directory and its contents: {item_path}")
|
59 |
+
|
60 |
+
print(f"All contents wiped from {folder_path}.")
|
61 |
+
|
62 |
+
|
63 |
+
# Example usage
|
64 |
+
# folder_to_wipe = 'path_to_your_folder'
|
65 |
+
# wipe_folder(folder_to_wipe)
|
66 |
+
|
67 |
+
|
68 |
+
def create_m4b_from_chapters(input_dir, ebook_file, output_dir):
|
69 |
+
# Function to sort chapters based on their numeric order
|
70 |
+
def sort_key(chapter_file):
|
71 |
+
numbers = re.findall(r'\d+', chapter_file)
|
72 |
+
return int(numbers[0]) if numbers else 0
|
73 |
+
|
74 |
+
# Extract metadata and cover image from the eBook file
|
75 |
+
def extract_metadata_and_cover(ebook_path):
|
76 |
+
try:
|
77 |
+
cover_path = ebook_path.rsplit('.', 1)[0] + '.jpg'
|
78 |
+
subprocess.run(['ebook-meta', ebook_path, '--get-cover', cover_path], check=True)
|
79 |
+
if os.path.exists(cover_path):
|
80 |
+
return cover_path
|
81 |
+
except Exception as e:
|
82 |
+
print(f"Error extracting eBook metadata or cover: {e}")
|
83 |
+
return None
|
84 |
+
# Combine WAV files into a single file
|
85 |
+
def combine_wav_files(chapter_files, output_path):
|
86 |
+
# Initialize an empty audio segment
|
87 |
+
combined_audio = AudioSegment.empty()
|
88 |
+
|
89 |
+
# Sequentially append each file to the combined_audio
|
90 |
+
for chapter_file in chapter_files:
|
91 |
+
audio_segment = AudioSegment.from_wav(chapter_file)
|
92 |
+
combined_audio += audio_segment
|
93 |
+
# Export the combined audio to the output file path
|
94 |
+
combined_audio.export(output_path, format='wav')
|
95 |
+
print(f"Combined audio saved to {output_path}")
|
96 |
+
|
97 |
+
# Function to generate metadata for M4B chapters
|
98 |
+
def generate_ffmpeg_metadata(chapter_files, metadata_file):
|
99 |
+
with open(metadata_file, 'w') as file:
|
100 |
+
file.write(';FFMETADATA1\n')
|
101 |
+
start_time = 0
|
102 |
+
for index, chapter_file in enumerate(chapter_files):
|
103 |
+
duration_ms = len(AudioSegment.from_wav(chapter_file))
|
104 |
+
file.write(f'[CHAPTER]\nTIMEBASE=1/1000\nSTART={start_time}\n')
|
105 |
+
file.write(f'END={start_time + duration_ms}\ntitle=Chapter {index + 1}\n')
|
106 |
+
start_time += duration_ms
|
107 |
+
|
108 |
+
# Generate the final M4B file using ffmpeg
|
109 |
+
def create_m4b(combined_wav, metadata_file, cover_image, output_m4b):
|
110 |
+
# Ensure the output directory exists
|
111 |
+
os.makedirs(os.path.dirname(output_m4b), exist_ok=True)
|
112 |
+
|
113 |
+
ffmpeg_cmd = ['ffmpeg', '-i', combined_wav, '-i', metadata_file]
|
114 |
+
if cover_image:
|
115 |
+
ffmpeg_cmd += ['-i', cover_image, '-map', '0:a', '-map', '2:v']
|
116 |
+
else:
|
117 |
+
ffmpeg_cmd += ['-map', '0:a']
|
118 |
+
|
119 |
+
ffmpeg_cmd += ['-map_metadata', '1', '-c:a', 'aac', '-b:a', '192k']
|
120 |
+
if cover_image:
|
121 |
+
ffmpeg_cmd += ['-c:v', 'png', '-disposition:v', 'attached_pic']
|
122 |
+
ffmpeg_cmd += [output_m4b]
|
123 |
+
|
124 |
+
subprocess.run(ffmpeg_cmd, check=True)
|
125 |
+
|
126 |
+
|
127 |
+
|
128 |
+
# Main logic
|
129 |
+
chapter_files = sorted([os.path.join(input_dir, f) for f in os.listdir(input_dir) if f.endswith('.wav')], key=sort_key)
|
130 |
+
temp_dir = tempfile.gettempdir()
|
131 |
+
temp_combined_wav = os.path.join(temp_dir, 'combined.wav')
|
132 |
+
metadata_file = os.path.join(temp_dir, 'metadata.txt')
|
133 |
+
cover_image = extract_metadata_and_cover(ebook_file)
|
134 |
+
output_m4b = os.path.join(output_dir, os.path.splitext(os.path.basename(ebook_file))[0] + '.m4b')
|
135 |
+
|
136 |
+
combine_wav_files(chapter_files, temp_combined_wav)
|
137 |
+
generate_ffmpeg_metadata(chapter_files, metadata_file)
|
138 |
+
create_m4b(temp_combined_wav, metadata_file, cover_image, output_m4b)
|
139 |
+
|
140 |
+
# Cleanup
|
141 |
+
if os.path.exists(temp_combined_wav):
|
142 |
+
os.remove(temp_combined_wav)
|
143 |
+
if os.path.exists(metadata_file):
|
144 |
+
os.remove(metadata_file)
|
145 |
+
if cover_image and os.path.exists(cover_image):
|
146 |
+
os.remove(cover_image)
|
147 |
+
|
148 |
+
# Example usage
|
149 |
+
# create_m4b_from_chapters('path_to_chapter_wavs', 'path_to_ebook_file', 'path_to_output_dir')
|
150 |
+
|
151 |
+
|
152 |
+
|
153 |
+
|
154 |
+
|
155 |
+
|
156 |
+
#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
|
157 |
+
import os
|
158 |
+
import subprocess
|
159 |
+
import ebooklib
|
160 |
+
from ebooklib import epub
|
161 |
+
from bs4 import BeautifulSoup
|
162 |
+
import re
|
163 |
+
import csv
|
164 |
+
import nltk
|
165 |
+
|
166 |
+
# Only run the main script if Value is True
|
167 |
+
def create_chapter_labeled_book(ebook_file_path):
|
168 |
+
# Function to ensure the existence of a directory
|
169 |
+
def ensure_directory(directory_path):
|
170 |
+
if not os.path.exists(directory_path):
|
171 |
+
os.makedirs(directory_path)
|
172 |
+
print(f"Created directory: {directory_path}")
|
173 |
+
|
174 |
+
ensure_directory(os.path.join(".", 'Working_files', 'Book'))
|
175 |
+
|
176 |
+
def convert_to_epub(input_path, output_path):
|
177 |
+
# Convert the ebook to EPUB format using Calibre's ebook-convert
|
178 |
+
try:
|
179 |
+
subprocess.run(['ebook-convert', input_path, output_path], check=True)
|
180 |
+
except subprocess.CalledProcessError as e:
|
181 |
+
print(f"An error occurred while converting the eBook: {e}")
|
182 |
+
return False
|
183 |
+
return True
|
184 |
+
|
185 |
+
def save_chapters_as_text(epub_path):
|
186 |
+
# Create the directory if it doesn't exist
|
187 |
+
directory = os.path.join(".", "Working_files", "temp_ebook")
|
188 |
+
ensure_directory(directory)
|
189 |
+
|
190 |
+
# Open the EPUB file
|
191 |
+
book = epub.read_epub(epub_path)
|
192 |
+
|
193 |
+
previous_chapter_text = ''
|
194 |
+
previous_filename = ''
|
195 |
+
chapter_counter = 0
|
196 |
+
|
197 |
+
# Iterate through the items in the EPUB file
|
198 |
+
for item in book.get_items():
|
199 |
+
if item.get_type() == ebooklib.ITEM_DOCUMENT:
|
200 |
+
# Use BeautifulSoup to parse HTML content
|
201 |
+
soup = BeautifulSoup(item.get_content(), 'html.parser')
|
202 |
+
text = soup.get_text()
|
203 |
+
|
204 |
+
# Check if the text is not empty
|
205 |
+
if text.strip():
|
206 |
+
if len(text) < 2300 and previous_filename:
|
207 |
+
# Append text to the previous chapter if it's short
|
208 |
+
with open(previous_filename, 'a', encoding='utf-8') as file:
|
209 |
+
file.write('\n' + text)
|
210 |
+
else:
|
211 |
+
# Create a new chapter file and increment the counter
|
212 |
+
previous_filename = os.path.join(directory, f"chapter_{chapter_counter}.txt")
|
213 |
+
chapter_counter += 1
|
214 |
+
with open(previous_filename, 'w', encoding='utf-8') as file:
|
215 |
+
file.write(text)
|
216 |
+
print(f"Saved chapter: {previous_filename}")
|
217 |
+
|
218 |
+
# Example usage
|
219 |
+
input_ebook = ebook_file_path # Replace with your eBook file path
|
220 |
+
output_epub = os.path.join(".", "Working_files", "temp.epub")
|
221 |
+
|
222 |
+
|
223 |
+
if os.path.exists(output_epub):
|
224 |
+
os.remove(output_epub)
|
225 |
+
print(f"File {output_epub} has been removed.")
|
226 |
+
else:
|
227 |
+
print(f"The file {output_epub} does not exist.")
|
228 |
+
|
229 |
+
if convert_to_epub(input_ebook, output_epub):
|
230 |
+
save_chapters_as_text(output_epub)
|
231 |
+
|
232 |
+
# Download the necessary NLTK data (if not already present)
|
233 |
+
nltk.download('punkt')
|
234 |
+
|
235 |
+
def process_chapter_files(folder_path, output_csv):
|
236 |
+
with open(output_csv, 'w', newline='', encoding='utf-8') as csvfile:
|
237 |
+
writer = csv.writer(csvfile)
|
238 |
+
# Write the header row
|
239 |
+
writer.writerow(['Text', 'Start Location', 'End Location', 'Is Quote', 'Speaker', 'Chapter'])
|
240 |
+
|
241 |
+
# Process each chapter file
|
242 |
+
chapter_files = sorted(os.listdir(folder_path), key=lambda x: int(x.split('_')[1].split('.')[0]))
|
243 |
+
for filename in chapter_files:
|
244 |
+
if filename.startswith('chapter_') and filename.endswith('.txt'):
|
245 |
+
chapter_number = int(filename.split('_')[1].split('.')[0])
|
246 |
+
file_path = os.path.join(folder_path, filename)
|
247 |
+
|
248 |
+
try:
|
249 |
+
with open(file_path, 'r', encoding='utf-8') as file:
|
250 |
+
text = file.read()
|
251 |
+
# Insert "NEWCHAPTERABC" at the beginning of each chapter's text
|
252 |
+
if text:
|
253 |
+
text = "NEWCHAPTERABC" + text
|
254 |
+
sentences = nltk.tokenize.sent_tokenize(text)
|
255 |
+
for sentence in sentences:
|
256 |
+
start_location = text.find(sentence)
|
257 |
+
end_location = start_location + len(sentence)
|
258 |
+
writer.writerow([sentence, start_location, end_location, 'True', 'Narrator', chapter_number])
|
259 |
+
except Exception as e:
|
260 |
+
print(f"Error processing file {filename}: {e}")
|
261 |
+
|
262 |
+
# Example usage
|
263 |
+
folder_path = os.path.join(".", "Working_files", "temp_ebook")
|
264 |
+
output_csv = os.path.join(".", "Working_files", "Book", "Other_book.csv")
|
265 |
+
|
266 |
+
process_chapter_files(folder_path, output_csv)
|
267 |
+
|
268 |
+
def sort_key(filename):
|
269 |
+
"""Extract chapter number for sorting."""
|
270 |
+
match = re.search(r'chapter_(\d+)\.txt', filename)
|
271 |
+
return int(match.group(1)) if match else 0
|
272 |
+
|
273 |
+
def combine_chapters(input_folder, output_file):
|
274 |
+
# Create the output folder if it doesn't exist
|
275 |
+
os.makedirs(os.path.dirname(output_file), exist_ok=True)
|
276 |
+
|
277 |
+
# List all txt files and sort them by chapter number
|
278 |
+
files = [f for f in os.listdir(input_folder) if f.endswith('.txt')]
|
279 |
+
sorted_files = sorted(files, key=sort_key)
|
280 |
+
|
281 |
+
with open(output_file, 'w', encoding='utf-8') as outfile: # Specify UTF-8 encoding here
|
282 |
+
for i, filename in enumerate(sorted_files):
|
283 |
+
with open(os.path.join(input_folder, filename), 'r', encoding='utf-8') as infile: # And here
|
284 |
+
outfile.write(infile.read())
|
285 |
+
# Add the marker unless it's the last file
|
286 |
+
if i < len(sorted_files) - 1:
|
287 |
+
outfile.write("\nNEWCHAPTERABC\n")
|
288 |
+
|
289 |
+
# Paths
|
290 |
+
input_folder = os.path.join(".", 'Working_files', 'temp_ebook')
|
291 |
+
output_file = os.path.join(".", 'Working_files', 'Book', 'Chapter_Book.txt')
|
292 |
+
|
293 |
+
|
294 |
+
# Combine the chapters
|
295 |
+
combine_chapters(input_folder, output_file)
|
296 |
+
|
297 |
+
ensure_directory(os.path.join(".", "Working_files", "Book"))
|
298 |
+
|
299 |
+
|
300 |
+
#create_chapter_labeled_book()
|
301 |
+
|
302 |
+
|
303 |
+
|
304 |
+
|
305 |
+
import os
|
306 |
+
import subprocess
|
307 |
+
import sys
|
308 |
+
import torchaudio
|
309 |
+
|
310 |
+
# Check if Calibre's ebook-convert tool is installed
|
311 |
+
def calibre_installed():
|
312 |
+
try:
|
313 |
+
subprocess.run(['ebook-convert', '--version'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
314 |
+
return True
|
315 |
+
except FileNotFoundError:
|
316 |
+
print("Calibre is not installed. Please install Calibre for this functionality.")
|
317 |
+
return False
|
318 |
+
|
319 |
+
|
320 |
+
import os
|
321 |
+
import torch
|
322 |
+
from TTS.api import TTS
|
323 |
+
from nltk.tokenize import sent_tokenize
|
324 |
+
from pydub import AudioSegment
|
325 |
+
# Assuming split_long_sentence and wipe_folder are defined elsewhere in your code
|
326 |
+
|
327 |
+
default_target_voice_path = "default_voice.wav" # Ensure this is a valid path
|
328 |
+
default_language_code = "en"
|
329 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
330 |
+
|
331 |
+
def combine_wav_files(input_directory, output_directory, file_name):
|
332 |
+
# Ensure that the output directory exists, create it if necessary
|
333 |
+
os.makedirs(output_directory, exist_ok=True)
|
334 |
+
|
335 |
+
# Specify the output file path
|
336 |
+
output_file_path = os.path.join(output_directory, file_name)
|
337 |
+
|
338 |
+
# Initialize an empty audio segment
|
339 |
+
combined_audio = AudioSegment.empty()
|
340 |
+
|
341 |
+
# Get a list of all .wav files in the specified input directory and sort them
|
342 |
+
input_file_paths = sorted(
|
343 |
+
[os.path.join(input_directory, f) for f in os.listdir(input_directory) if f.endswith(".wav")],
|
344 |
+
key=lambda f: int(''.join(filter(str.isdigit, f)))
|
345 |
+
)
|
346 |
+
|
347 |
+
# Sequentially append each file to the combined_audio
|
348 |
+
for input_file_path in input_file_paths:
|
349 |
+
audio_segment = AudioSegment.from_wav(input_file_path)
|
350 |
+
combined_audio += audio_segment
|
351 |
+
|
352 |
+
# Export the combined audio to the output file path
|
353 |
+
combined_audio.export(output_file_path, format='wav')
|
354 |
+
|
355 |
+
print(f"Combined audio saved to {output_file_path}")
|
356 |
+
|
357 |
+
# Function to split long strings into parts
|
358 |
+
def split_long_sentence(sentence, max_length=249, max_pauses=10):
|
359 |
+
"""
|
360 |
+
Splits a sentence into parts based on length or number of pauses without recursion.
|
361 |
+
|
362 |
+
:param sentence: The sentence to split.
|
363 |
+
:param max_length: Maximum allowed length of a sentence.
|
364 |
+
:param max_pauses: Maximum allowed number of pauses in a sentence.
|
365 |
+
:return: A list of sentence parts that meet the criteria.
|
366 |
+
"""
|
367 |
+
parts = []
|
368 |
+
while len(sentence) > max_length or sentence.count(',') + sentence.count(';') + sentence.count('.') > max_pauses:
|
369 |
+
possible_splits = [i for i, char in enumerate(sentence) if char in ',;.' and i < max_length]
|
370 |
+
if possible_splits:
|
371 |
+
# Find the best place to split the sentence, preferring the last possible split to keep parts longer
|
372 |
+
split_at = possible_splits[-1] + 1
|
373 |
+
else:
|
374 |
+
# If no punctuation to split on within max_length, split at max_length
|
375 |
+
split_at = max_length
|
376 |
+
|
377 |
+
# Split the sentence and add the first part to the list
|
378 |
+
parts.append(sentence[:split_at].strip())
|
379 |
+
sentence = sentence[split_at:].strip()
|
380 |
+
|
381 |
+
# Add the remaining part of the sentence
|
382 |
+
parts.append(sentence)
|
383 |
+
return parts
|
384 |
+
|
385 |
+
"""
|
386 |
+
if 'tts' not in locals():
|
387 |
+
tts = TTS(selected_tts_model, progress_bar=True).to(device)
|
388 |
+
"""
|
389 |
+
from tqdm import tqdm
|
390 |
+
|
391 |
+
# Convert chapters to audio using XTTS
|
392 |
+
def convert_chapters_to_audio(chapters_dir, output_audio_dir, target_voice_path=None, language=None, custom_model=None):
|
393 |
+
if custom_model:
|
394 |
+
print("Loading custom model...")
|
395 |
+
config = XttsConfig()
|
396 |
+
config.load_json(custom_model['config'])
|
397 |
+
model = Xtts.init_from_config(config)
|
398 |
+
model.load_checkpoint(config, checkpoint_path=custom_model['model'], vocab_path=custom_model['vocab'], use_deepspeed=False)
|
399 |
+
model.to(device)
|
400 |
+
print("Computing speaker latents...")
|
401 |
+
gpt_cond_latent, speaker_embedding = model.get_conditioning_latents(audio_path=[target_voice_path])
|
402 |
+
else:
|
403 |
+
selected_tts_model = "tts_models/multilingual/multi-dataset/xtts_v2"
|
404 |
+
tts = TTS(selected_tts_model, progress_bar=False).to(device)
|
405 |
+
|
406 |
+
if not os.path.exists(output_audio_dir):
|
407 |
+
os.makedirs(output_audio_dir)
|
408 |
+
|
409 |
+
for chapter_file in sorted(os.listdir(chapters_dir)):
|
410 |
+
if chapter_file.endswith('.txt'):
|
411 |
+
match = re.search(r"chapter_(\d+).txt", chapter_file)
|
412 |
+
if match:
|
413 |
+
chapter_num = int(match.group(1))
|
414 |
+
else:
|
415 |
+
print(f"Skipping file {chapter_file} as it does not match the expected format.")
|
416 |
+
continue
|
417 |
+
|
418 |
+
chapter_path = os.path.join(chapters_dir, chapter_file)
|
419 |
+
output_file_name = f"audio_chapter_{chapter_num}.wav"
|
420 |
+
output_file_path = os.path.join(output_audio_dir, output_file_name)
|
421 |
+
temp_audio_directory = os.path.join(".", "Working_files", "temp")
|
422 |
+
os.makedirs(temp_audio_directory, exist_ok=True)
|
423 |
+
temp_count = 0
|
424 |
+
|
425 |
+
with open(chapter_path, 'r', encoding='utf-8') as file:
|
426 |
+
chapter_text = file.read()
|
427 |
+
sentences = sent_tokenize(chapter_text, language='italian' if language == 'it' else 'english')
|
428 |
+
for sentence in tqdm(sentences, desc=f"Chapter {chapter_num}"):
|
429 |
+
fragments = split_long_sentence(sentence, max_length=249 if language == "en" else 213, max_pauses=10)
|
430 |
+
for fragment in fragments:
|
431 |
+
if fragment != "":
|
432 |
+
print(f"Generating fragment: {fragment}...")
|
433 |
+
fragment_file_path = os.path.join(temp_audio_directory, f"{temp_count}.wav")
|
434 |
+
if custom_model:
|
435 |
+
out = model.inference(fragment, language, gpt_cond_latent, speaker_embedding, temperature=0.7)
|
436 |
+
torchaudio.save(fragment_file_path, torch.tensor(out["wav"]).unsqueeze(0), 24000)
|
437 |
+
else:
|
438 |
+
speaker_wav_path = target_voice_path if target_voice_path else default_target_voice_path
|
439 |
+
language_code = language if language else default_language_code
|
440 |
+
tts.tts_to_file(text=fragment, file_path=fragment_file_path, speaker_wav=speaker_wav_path, language=language_code)
|
441 |
+
temp_count += 1
|
442 |
+
|
443 |
+
combine_wav_files(temp_audio_directory, output_audio_dir, output_file_name)
|
444 |
+
wipe_folder(temp_audio_directory)
|
445 |
+
print(f"Converted chapter {chapter_num} to audio.")
|
446 |
+
|
447 |
+
|
448 |
+
# Main execution flow
|
449 |
+
if __name__ == "__main__":
|
450 |
+
if len(sys.argv) < 2:
|
451 |
+
print("Usage: python script.py <ebook_file_path> [target_voice_file_path] [language] [custom_model_path] [custom_config_path] [custom_vocab_path]")
|
452 |
+
sys.exit(1)
|
453 |
+
|
454 |
+
ebook_file_path = sys.argv[1]
|
455 |
+
target_voice = sys.argv[2] if len(sys.argv) > 2 else None
|
456 |
+
language = sys.argv[3] if len(sys.argv) > 3 else None
|
457 |
+
|
458 |
+
custom_model = None
|
459 |
+
if len(sys.argv) > 6:
|
460 |
+
custom_model = {
|
461 |
+
'model': sys.argv[4],
|
462 |
+
'config': sys.argv[5],
|
463 |
+
'vocab': sys.argv[6]
|
464 |
+
}
|
465 |
+
|
466 |
+
if not calibre_installed():
|
467 |
+
sys.exit(1)
|
468 |
+
|
469 |
+
working_files = os.path.join(".", "Working_files", "temp_ebook")
|
470 |
+
full_folder_working_files = os.path.join(".", "Working_files")
|
471 |
+
chapters_directory = os.path.join(".", "Working_files", "temp_ebook")
|
472 |
+
output_audio_directory = os.path.join(".", 'Chapter_wav_files')
|
473 |
+
|
474 |
+
print("Wiping and removing Working_files folder...")
|
475 |
+
remove_folder_with_contents(full_folder_working_files)
|
476 |
+
|
477 |
+
print("Wiping and removing chapter_wav_files folder...")
|
478 |
+
remove_folder_with_contents(output_audio_directory)
|
479 |
+
|
480 |
+
create_chapter_labeled_book(ebook_file_path)
|
481 |
+
audiobook_output_path = os.path.join(".", "Audiobooks")
|
482 |
+
print(f"{chapters_directory}||||{output_audio_directory}|||||{target_voice}")
|
483 |
+
convert_chapters_to_audio(chapters_directory, output_audio_directory, target_voice, language, custom_model)
|
484 |
+
create_m4b_from_chapters(output_audio_directory, ebook_file_path, audiobook_output_path)
|
legacy/v1.0/legacy/custom_model_ebook2audiobookXTTS_gradio.py
ADDED
@@ -0,0 +1,609 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
print("starting...")
|
2 |
+
|
3 |
+
import os
|
4 |
+
import shutil
|
5 |
+
import subprocess
|
6 |
+
import re
|
7 |
+
from pydub import AudioSegment
|
8 |
+
import tempfile
|
9 |
+
from pydub import AudioSegment
|
10 |
+
import os
|
11 |
+
import nltk
|
12 |
+
from nltk.tokenize import sent_tokenize
|
13 |
+
import sys
|
14 |
+
import torch
|
15 |
+
from TTS.api import TTS
|
16 |
+
from TTS.tts.configs.xtts_config import XttsConfig
|
17 |
+
from TTS.tts.models.xtts import Xtts
|
18 |
+
from tqdm import tqdm
|
19 |
+
|
20 |
+
nltk.download('punkt') # Make sure to download the necessary models
|
21 |
+
|
22 |
+
import gradio as gr
|
23 |
+
from gradio import Progress
|
24 |
+
|
25 |
+
|
26 |
+
def is_folder_empty(folder_path):
|
27 |
+
if os.path.exists(folder_path) and os.path.isdir(folder_path):
|
28 |
+
# List directory contents
|
29 |
+
if not os.listdir(folder_path):
|
30 |
+
return True # The folder is empty
|
31 |
+
else:
|
32 |
+
return False # The folder is not empty
|
33 |
+
else:
|
34 |
+
print(f"The path {folder_path} is not a valid folder.")
|
35 |
+
return None # The path is not a valid folder
|
36 |
+
|
37 |
+
def remove_folder_with_contents(folder_path):
|
38 |
+
try:
|
39 |
+
shutil.rmtree(folder_path)
|
40 |
+
print(f"Successfully removed {folder_path} and all of its contents.")
|
41 |
+
except Exception as e:
|
42 |
+
print(f"Error removing {folder_path}: {e}")
|
43 |
+
|
44 |
+
|
45 |
+
|
46 |
+
|
47 |
+
def wipe_folder(folder_path):
|
48 |
+
# Check if the folder exists
|
49 |
+
if not os.path.exists(folder_path):
|
50 |
+
print(f"The folder {folder_path} does not exist.")
|
51 |
+
return
|
52 |
+
|
53 |
+
# Iterate over all the items in the given folder
|
54 |
+
for item in os.listdir(folder_path):
|
55 |
+
item_path = os.path.join(folder_path, item)
|
56 |
+
# If it's a file, remove it and print a message
|
57 |
+
if os.path.isfile(item_path):
|
58 |
+
os.remove(item_path)
|
59 |
+
print(f"Removed file: {item_path}")
|
60 |
+
# If it's a directory, remove it recursively and print a message
|
61 |
+
elif os.path.isdir(item_path):
|
62 |
+
shutil.rmtree(item_path)
|
63 |
+
print(f"Removed directory and its contents: {item_path}")
|
64 |
+
|
65 |
+
print(f"All contents wiped from {folder_path}.")
|
66 |
+
|
67 |
+
|
68 |
+
# Example usage
|
69 |
+
# folder_to_wipe = 'path_to_your_folder'
|
70 |
+
# wipe_folder(folder_to_wipe)
|
71 |
+
|
72 |
+
|
73 |
+
def create_m4b_from_chapters(input_dir, ebook_file, output_dir):
|
74 |
+
# Function to sort chapters based on their numeric order
|
75 |
+
def sort_key(chapter_file):
|
76 |
+
numbers = re.findall(r'\d+', chapter_file)
|
77 |
+
return int(numbers[0]) if numbers else 0
|
78 |
+
|
79 |
+
# Extract metadata and cover image from the eBook file
|
80 |
+
def extract_metadata_and_cover(ebook_path):
|
81 |
+
try:
|
82 |
+
cover_path = ebook_path.rsplit('.', 1)[0] + '.jpg'
|
83 |
+
subprocess.run(['ebook-meta', ebook_path, '--get-cover', cover_path], check=True)
|
84 |
+
if os.path.exists(cover_path):
|
85 |
+
return cover_path
|
86 |
+
except Exception as e:
|
87 |
+
print(f"Error extracting eBook metadata or cover: {e}")
|
88 |
+
return None
|
89 |
+
# Combine WAV files into a single file
|
90 |
+
def combine_wav_files(chapter_files, output_path):
|
91 |
+
# Initialize an empty audio segment
|
92 |
+
combined_audio = AudioSegment.empty()
|
93 |
+
|
94 |
+
# Sequentially append each file to the combined_audio
|
95 |
+
for chapter_file in chapter_files:
|
96 |
+
audio_segment = AudioSegment.from_wav(chapter_file)
|
97 |
+
combined_audio += audio_segment
|
98 |
+
# Export the combined audio to the output file path
|
99 |
+
combined_audio.export(output_path, format='wav')
|
100 |
+
print(f"Combined audio saved to {output_path}")
|
101 |
+
|
102 |
+
# Function to generate metadata for M4B chapters
|
103 |
+
def generate_ffmpeg_metadata(chapter_files, metadata_file):
|
104 |
+
with open(metadata_file, 'w') as file:
|
105 |
+
file.write(';FFMETADATA1\n')
|
106 |
+
start_time = 0
|
107 |
+
for index, chapter_file in enumerate(chapter_files):
|
108 |
+
duration_ms = len(AudioSegment.from_wav(chapter_file))
|
109 |
+
file.write(f'[CHAPTER]\nTIMEBASE=1/1000\nSTART={start_time}\n')
|
110 |
+
file.write(f'END={start_time + duration_ms}\ntitle=Chapter {index + 1}\n')
|
111 |
+
start_time += duration_ms
|
112 |
+
|
113 |
+
# Generate the final M4B file using ffmpeg
|
114 |
+
def create_m4b(combined_wav, metadata_file, cover_image, output_m4b):
|
115 |
+
# Ensure the output directory exists
|
116 |
+
os.makedirs(os.path.dirname(output_m4b), exist_ok=True)
|
117 |
+
|
118 |
+
ffmpeg_cmd = ['ffmpeg', '-i', combined_wav, '-i', metadata_file]
|
119 |
+
if cover_image:
|
120 |
+
ffmpeg_cmd += ['-i', cover_image, '-map', '0:a', '-map', '2:v']
|
121 |
+
else:
|
122 |
+
ffmpeg_cmd += ['-map', '0:a']
|
123 |
+
|
124 |
+
ffmpeg_cmd += ['-map_metadata', '1', '-c:a', 'aac', '-b:a', '192k']
|
125 |
+
if cover_image:
|
126 |
+
ffmpeg_cmd += ['-c:v', 'png', '-disposition:v', 'attached_pic']
|
127 |
+
ffmpeg_cmd += [output_m4b]
|
128 |
+
|
129 |
+
subprocess.run(ffmpeg_cmd, check=True)
|
130 |
+
|
131 |
+
|
132 |
+
|
133 |
+
# Main logic
|
134 |
+
chapter_files = sorted([os.path.join(input_dir, f) for f in os.listdir(input_dir) if f.endswith('.wav')], key=sort_key)
|
135 |
+
temp_dir = tempfile.gettempdir()
|
136 |
+
temp_combined_wav = os.path.join(temp_dir, 'combined.wav')
|
137 |
+
metadata_file = os.path.join(temp_dir, 'metadata.txt')
|
138 |
+
cover_image = extract_metadata_and_cover(ebook_file)
|
139 |
+
output_m4b = os.path.join(output_dir, os.path.splitext(os.path.basename(ebook_file))[0] + '.m4b')
|
140 |
+
|
141 |
+
combine_wav_files(chapter_files, temp_combined_wav)
|
142 |
+
generate_ffmpeg_metadata(chapter_files, metadata_file)
|
143 |
+
create_m4b(temp_combined_wav, metadata_file, cover_image, output_m4b)
|
144 |
+
|
145 |
+
# Cleanup
|
146 |
+
if os.path.exists(temp_combined_wav):
|
147 |
+
os.remove(temp_combined_wav)
|
148 |
+
if os.path.exists(metadata_file):
|
149 |
+
os.remove(metadata_file)
|
150 |
+
if cover_image and os.path.exists(cover_image):
|
151 |
+
os.remove(cover_image)
|
152 |
+
|
153 |
+
# Example usage
|
154 |
+
# create_m4b_from_chapters('path_to_chapter_wavs', 'path_to_ebook_file', 'path_to_output_dir')
|
155 |
+
|
156 |
+
|
157 |
+
|
158 |
+
|
159 |
+
|
160 |
+
|
161 |
+
#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
|
162 |
+
import os
|
163 |
+
import subprocess
|
164 |
+
import ebooklib
|
165 |
+
from ebooklib import epub
|
166 |
+
from bs4 import BeautifulSoup
|
167 |
+
import re
|
168 |
+
import csv
|
169 |
+
import nltk
|
170 |
+
|
171 |
+
# Only run the main script if Value is True
|
172 |
+
def create_chapter_labeled_book(ebook_file_path):
|
173 |
+
# Function to ensure the existence of a directory
|
174 |
+
def ensure_directory(directory_path):
|
175 |
+
if not os.path.exists(directory_path):
|
176 |
+
os.makedirs(directory_path)
|
177 |
+
print(f"Created directory: {directory_path}")
|
178 |
+
|
179 |
+
ensure_directory(os.path.join(".", 'Working_files', 'Book'))
|
180 |
+
|
181 |
+
def convert_to_epub(input_path, output_path):
|
182 |
+
# Convert the ebook to EPUB format using Calibre's ebook-convert
|
183 |
+
try:
|
184 |
+
subprocess.run(['ebook-convert', input_path, output_path], check=True)
|
185 |
+
except subprocess.CalledProcessError as e:
|
186 |
+
print(f"An error occurred while converting the eBook: {e}")
|
187 |
+
return False
|
188 |
+
return True
|
189 |
+
|
190 |
+
def save_chapters_as_text(epub_path):
|
191 |
+
# Create the directory if it doesn't exist
|
192 |
+
directory = os.path.join(".", "Working_files", "temp_ebook")
|
193 |
+
ensure_directory(directory)
|
194 |
+
|
195 |
+
# Open the EPUB file
|
196 |
+
book = epub.read_epub(epub_path)
|
197 |
+
|
198 |
+
previous_chapter_text = ''
|
199 |
+
previous_filename = ''
|
200 |
+
chapter_counter = 0
|
201 |
+
|
202 |
+
# Iterate through the items in the EPUB file
|
203 |
+
for item in book.get_items():
|
204 |
+
if item.get_type() == ebooklib.ITEM_DOCUMENT:
|
205 |
+
# Use BeautifulSoup to parse HTML content
|
206 |
+
soup = BeautifulSoup(item.get_content(), 'html.parser')
|
207 |
+
text = soup.get_text()
|
208 |
+
|
209 |
+
# Check if the text is not empty
|
210 |
+
if text.strip():
|
211 |
+
if len(text) < 2300 and previous_filename:
|
212 |
+
# Append text to the previous chapter if it's short
|
213 |
+
with open(previous_filename, 'a', encoding='utf-8') as file:
|
214 |
+
file.write('\n' + text)
|
215 |
+
else:
|
216 |
+
# Create a new chapter file and increment the counter
|
217 |
+
previous_filename = os.path.join(directory, f"chapter_{chapter_counter}.txt")
|
218 |
+
chapter_counter += 1
|
219 |
+
with open(previous_filename, 'w', encoding='utf-8') as file:
|
220 |
+
file.write(text)
|
221 |
+
print(f"Saved chapter: {previous_filename}")
|
222 |
+
|
223 |
+
# Example usage
|
224 |
+
input_ebook = ebook_file_path # Replace with your eBook file path
|
225 |
+
output_epub = os.path.join(".", "Working_files", "temp.epub")
|
226 |
+
|
227 |
+
|
228 |
+
if os.path.exists(output_epub):
|
229 |
+
os.remove(output_epub)
|
230 |
+
print(f"File {output_epub} has been removed.")
|
231 |
+
else:
|
232 |
+
print(f"The file {output_epub} does not exist.")
|
233 |
+
|
234 |
+
if convert_to_epub(input_ebook, output_epub):
|
235 |
+
save_chapters_as_text(output_epub)
|
236 |
+
|
237 |
+
# Download the necessary NLTK data (if not already present)
|
238 |
+
nltk.download('punkt')
|
239 |
+
|
240 |
+
def process_chapter_files(folder_path, output_csv):
|
241 |
+
with open(output_csv, 'w', newline='', encoding='utf-8') as csvfile:
|
242 |
+
writer = csv.writer(csvfile)
|
243 |
+
# Write the header row
|
244 |
+
writer.writerow(['Text', 'Start Location', 'End Location', 'Is Quote', 'Speaker', 'Chapter'])
|
245 |
+
|
246 |
+
# Process each chapter file
|
247 |
+
chapter_files = sorted(os.listdir(folder_path), key=lambda x: int(x.split('_')[1].split('.')[0]))
|
248 |
+
for filename in chapter_files:
|
249 |
+
if filename.startswith('chapter_') and filename.endswith('.txt'):
|
250 |
+
chapter_number = int(filename.split('_')[1].split('.')[0])
|
251 |
+
file_path = os.path.join(folder_path, filename)
|
252 |
+
|
253 |
+
try:
|
254 |
+
with open(file_path, 'r', encoding='utf-8') as file:
|
255 |
+
text = file.read()
|
256 |
+
# Insert "NEWCHAPTERABC" at the beginning of each chapter's text
|
257 |
+
if text:
|
258 |
+
text = "NEWCHAPTERABC" + text
|
259 |
+
sentences = nltk.tokenize.sent_tokenize(text)
|
260 |
+
for sentence in sentences:
|
261 |
+
start_location = text.find(sentence)
|
262 |
+
end_location = start_location + len(sentence)
|
263 |
+
writer.writerow([sentence, start_location, end_location, 'True', 'Narrator', chapter_number])
|
264 |
+
except Exception as e:
|
265 |
+
print(f"Error processing file {filename}: {e}")
|
266 |
+
|
267 |
+
# Example usage
|
268 |
+
folder_path = os.path.join(".", "Working_files", "temp_ebook")
|
269 |
+
output_csv = os.path.join(".", "Working_files", "Book", "Other_book.csv")
|
270 |
+
|
271 |
+
process_chapter_files(folder_path, output_csv)
|
272 |
+
|
273 |
+
def sort_key(filename):
|
274 |
+
"""Extract chapter number for sorting."""
|
275 |
+
match = re.search(r'chapter_(\d+)\.txt', filename)
|
276 |
+
return int(match.group(1)) if match else 0
|
277 |
+
|
278 |
+
def combine_chapters(input_folder, output_file):
|
279 |
+
# Create the output folder if it doesn't exist
|
280 |
+
os.makedirs(os.path.dirname(output_file), exist_ok=True)
|
281 |
+
|
282 |
+
# List all txt files and sort them by chapter number
|
283 |
+
files = [f for f in os.listdir(input_folder) if f.endswith('.txt')]
|
284 |
+
sorted_files = sorted(files, key=sort_key)
|
285 |
+
|
286 |
+
with open(output_file, 'w', encoding='utf-8') as outfile: # Specify UTF-8 encoding here
|
287 |
+
for i, filename in enumerate(sorted_files):
|
288 |
+
with open(os.path.join(input_folder, filename), 'r', encoding='utf-8') as infile: # And here
|
289 |
+
outfile.write(infile.read())
|
290 |
+
# Add the marker unless it's the last file
|
291 |
+
if i < len(sorted_files) - 1:
|
292 |
+
outfile.write("\nNEWCHAPTERABC\n")
|
293 |
+
|
294 |
+
# Paths
|
295 |
+
input_folder = os.path.join(".", 'Working_files', 'temp_ebook')
|
296 |
+
output_file = os.path.join(".", 'Working_files', 'Book', 'Chapter_Book.txt')
|
297 |
+
|
298 |
+
|
299 |
+
# Combine the chapters
|
300 |
+
combine_chapters(input_folder, output_file)
|
301 |
+
|
302 |
+
ensure_directory(os.path.join(".", "Working_files", "Book"))
|
303 |
+
|
304 |
+
|
305 |
+
#create_chapter_labeled_book()
|
306 |
+
|
307 |
+
|
308 |
+
|
309 |
+
|
310 |
+
import os
|
311 |
+
import subprocess
|
312 |
+
import sys
|
313 |
+
import torchaudio
|
314 |
+
|
315 |
+
# Check if Calibre's ebook-convert tool is installed
|
316 |
+
def calibre_installed():
|
317 |
+
try:
|
318 |
+
subprocess.run(['ebook-convert', '--version'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
319 |
+
return True
|
320 |
+
except FileNotFoundError:
|
321 |
+
print("Calibre is not installed. Please install Calibre for this functionality.")
|
322 |
+
return False
|
323 |
+
|
324 |
+
|
325 |
+
import os
|
326 |
+
import torch
|
327 |
+
from TTS.api import TTS
|
328 |
+
from nltk.tokenize import sent_tokenize
|
329 |
+
from pydub import AudioSegment
|
330 |
+
# Assuming split_long_sentence and wipe_folder are defined elsewhere in your code
|
331 |
+
|
332 |
+
default_target_voice_path = "default_voice.wav" # Ensure this is a valid path
|
333 |
+
default_language_code = "en"
|
334 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
335 |
+
|
336 |
+
def combine_wav_files(input_directory, output_directory, file_name):
|
337 |
+
# Ensure that the output directory exists, create it if necessary
|
338 |
+
os.makedirs(output_directory, exist_ok=True)
|
339 |
+
|
340 |
+
# Specify the output file path
|
341 |
+
output_file_path = os.path.join(output_directory, file_name)
|
342 |
+
|
343 |
+
# Initialize an empty audio segment
|
344 |
+
combined_audio = AudioSegment.empty()
|
345 |
+
|
346 |
+
# Get a list of all .wav files in the specified input directory and sort them
|
347 |
+
input_file_paths = sorted(
|
348 |
+
[os.path.join(input_directory, f) for f in os.listdir(input_directory) if f.endswith(".wav")],
|
349 |
+
key=lambda f: int(''.join(filter(str.isdigit, f)))
|
350 |
+
)
|
351 |
+
|
352 |
+
# Sequentially append each file to the combined_audio
|
353 |
+
for input_file_path in input_file_paths:
|
354 |
+
audio_segment = AudioSegment.from_wav(input_file_path)
|
355 |
+
combined_audio += audio_segment
|
356 |
+
|
357 |
+
# Export the combined audio to the output file path
|
358 |
+
combined_audio.export(output_file_path, format='wav')
|
359 |
+
|
360 |
+
print(f"Combined audio saved to {output_file_path}")
|
361 |
+
|
362 |
+
# Function to split long strings into parts
|
363 |
+
def split_long_sentence(sentence, max_length=249, max_pauses=10):
|
364 |
+
"""
|
365 |
+
Splits a sentence into parts based on length or number of pauses without recursion.
|
366 |
+
|
367 |
+
:param sentence: The sentence to split.
|
368 |
+
:param max_length: Maximum allowed length of a sentence.
|
369 |
+
:param max_pauses: Maximum allowed number of pauses in a sentence.
|
370 |
+
:return: A list of sentence parts that meet the criteria.
|
371 |
+
"""
|
372 |
+
parts = []
|
373 |
+
while len(sentence) > max_length or sentence.count(',') + sentence.count(';') + sentence.count('.') > max_pauses:
|
374 |
+
possible_splits = [i for i, char in enumerate(sentence) if char in ',;.' and i < max_length]
|
375 |
+
if possible_splits:
|
376 |
+
# Find the best place to split the sentence, preferring the last possible split to keep parts longer
|
377 |
+
split_at = possible_splits[-1] + 1
|
378 |
+
else:
|
379 |
+
# If no punctuation to split on within max_length, split at max_length
|
380 |
+
split_at = max_length
|
381 |
+
|
382 |
+
# Split the sentence and add the first part to the list
|
383 |
+
parts.append(sentence[:split_at].strip())
|
384 |
+
sentence = sentence[split_at:].strip()
|
385 |
+
|
386 |
+
# Add the remaining part of the sentence
|
387 |
+
parts.append(sentence)
|
388 |
+
return parts
|
389 |
+
|
390 |
+
"""
|
391 |
+
if 'tts' not in locals():
|
392 |
+
tts = TTS(selected_tts_model, progress_bar=True).to(device)
|
393 |
+
"""
|
394 |
+
from tqdm import tqdm
|
395 |
+
|
396 |
+
# Convert chapters to audio using XTTS
|
397 |
+
|
398 |
+
def convert_chapters_to_audio_custom_model(chapters_dir, output_audio_dir, target_voice_path=None, language=None, custom_model=None):
|
399 |
+
if custom_model:
|
400 |
+
print("Loading custom model...")
|
401 |
+
config = XttsConfig()
|
402 |
+
config.load_json(custom_model['config'])
|
403 |
+
model = Xtts.init_from_config(config)
|
404 |
+
model.load_checkpoint(config, checkpoint_path=custom_model['model'], vocab_path=custom_model['vocab'], use_deepspeed=False)
|
405 |
+
model.to(device)
|
406 |
+
print("Computing speaker latents...")
|
407 |
+
gpt_cond_latent, speaker_embedding = model.get_conditioning_latents(audio_path=[target_voice_path])
|
408 |
+
else:
|
409 |
+
selected_tts_model = "tts_models/multilingual/multi-dataset/xtts_v2"
|
410 |
+
tts = TTS(selected_tts_model, progress_bar=False).to(device)
|
411 |
+
|
412 |
+
if not os.path.exists(output_audio_dir):
|
413 |
+
os.makedirs(output_audio_dir)
|
414 |
+
|
415 |
+
for chapter_file in sorted(os.listdir(chapters_dir)):
|
416 |
+
if chapter_file.endswith('.txt'):
|
417 |
+
match = re.search(r"chapter_(\d+).txt", chapter_file)
|
418 |
+
if match:
|
419 |
+
chapter_num = int(match.group(1))
|
420 |
+
else:
|
421 |
+
print(f"Skipping file {chapter_file} as it does not match the expected format.")
|
422 |
+
continue
|
423 |
+
|
424 |
+
chapter_path = os.path.join(chapters_dir, chapter_file)
|
425 |
+
output_file_name = f"audio_chapter_{chapter_num}.wav"
|
426 |
+
output_file_path = os.path.join(output_audio_dir, output_file_name)
|
427 |
+
temp_audio_directory = os.path.join(".", "Working_files", "temp")
|
428 |
+
os.makedirs(temp_audio_directory, exist_ok=True)
|
429 |
+
temp_count = 0
|
430 |
+
|
431 |
+
with open(chapter_path, 'r', encoding='utf-8') as file:
|
432 |
+
chapter_text = file.read()
|
433 |
+
sentences = sent_tokenize(chapter_text, language='italian' if language == 'it' else 'english')
|
434 |
+
for sentence in tqdm(sentences, desc=f"Chapter {chapter_num}"):
|
435 |
+
fragments = split_long_sentence(sentence, max_length=249 if language == "en" else 213, max_pauses=10)
|
436 |
+
for fragment in fragments:
|
437 |
+
if fragment != "":
|
438 |
+
print(f"Generating fragment: {fragment}...")
|
439 |
+
fragment_file_path = os.path.join(temp_audio_directory, f"{temp_count}.wav")
|
440 |
+
if custom_model:
|
441 |
+
out = model.inference(fragment, language, gpt_cond_latent, speaker_embedding, temperature=0.7)
|
442 |
+
torchaudio.save(fragment_file_path, torch.tensor(out["wav"]).unsqueeze(0), 24000)
|
443 |
+
else:
|
444 |
+
speaker_wav_path = target_voice_path if target_voice_path else default_target_voice_path
|
445 |
+
language_code = language if language else default_language_code
|
446 |
+
tts.tts_to_file(text=fragment, file_path=fragment_file_path, speaker_wav=speaker_wav_path, language=language_code)
|
447 |
+
temp_count += 1
|
448 |
+
|
449 |
+
combine_wav_files(temp_audio_directory, output_audio_dir, output_file_name)
|
450 |
+
wipe_folder(temp_audio_directory)
|
451 |
+
print(f"Converted chapter {chapter_num} to audio.")
|
452 |
+
|
453 |
+
|
454 |
+
|
455 |
+
def convert_chapters_to_audio_standard_model(chapters_dir, output_audio_dir, target_voice_path=None, language=None):
|
456 |
+
selected_tts_model = "tts_models/multilingual/multi-dataset/xtts_v2"
|
457 |
+
tts = TTS(selected_tts_model, progress_bar=False).to(device)
|
458 |
+
|
459 |
+
if not os.path.exists(output_audio_dir):
|
460 |
+
os.makedirs(output_audio_dir)
|
461 |
+
|
462 |
+
for chapter_file in sorted(os.listdir(chapters_dir)):
|
463 |
+
if chapter_file.endswith('.txt'):
|
464 |
+
match = re.search(r"chapter_(\d+).txt", chapter_file)
|
465 |
+
if match:
|
466 |
+
chapter_num = int(match.group(1))
|
467 |
+
else:
|
468 |
+
print(f"Skipping file {chapter_file} as it does not match the expected format.")
|
469 |
+
continue
|
470 |
+
|
471 |
+
chapter_path = os.path.join(chapters_dir, chapter_file)
|
472 |
+
output_file_name = f"audio_chapter_{chapter_num}.wav"
|
473 |
+
output_file_path = os.path.join(output_audio_dir, output_file_name)
|
474 |
+
temp_audio_directory = os.path.join(".", "Working_files", "temp")
|
475 |
+
os.makedirs(temp_audio_directory, exist_ok=True)
|
476 |
+
temp_count = 0
|
477 |
+
|
478 |
+
with open(chapter_path, 'r', encoding='utf-8') as file:
|
479 |
+
chapter_text = file.read()
|
480 |
+
sentences = sent_tokenize(chapter_text, language='italian' if language == 'it' else 'english')
|
481 |
+
for sentence in tqdm(sentences, desc=f"Chapter {chapter_num}"):
|
482 |
+
fragments = split_long_sentence(sentence, max_length=249 if language == "en" else 213, max_pauses=10)
|
483 |
+
for fragment in fragments:
|
484 |
+
if fragment != "":
|
485 |
+
print(f"Generating fragment: {fragment}...")
|
486 |
+
fragment_file_path = os.path.join(temp_audio_directory, f"{temp_count}.wav")
|
487 |
+
speaker_wav_path = target_voice_path if target_voice_path else default_target_voice_path
|
488 |
+
language_code = language if language else default_language_code
|
489 |
+
tts.tts_to_file(text=fragment, file_path=fragment_file_path, speaker_wav=speaker_wav_path, language=language_code)
|
490 |
+
temp_count += 1
|
491 |
+
|
492 |
+
combine_wav_files(temp_audio_directory, output_audio_dir, output_file_name)
|
493 |
+
wipe_folder(temp_audio_directory)
|
494 |
+
print(f"Converted chapter {chapter_num} to audio.")
|
495 |
+
|
496 |
+
|
497 |
+
|
498 |
+
# Define the functions to be used in the Gradio interface
|
499 |
+
def convert_ebook_to_audio(ebook_file, target_voice_file, language, use_custom_model, custom_model_file, custom_config_file, custom_vocab_file, progress=gr.Progress()):
|
500 |
+
ebook_file_path = ebook_file.name
|
501 |
+
target_voice = target_voice_file.name if target_voice_file else None
|
502 |
+
custom_model = None
|
503 |
+
if use_custom_model and custom_model_file and custom_config_file and custom_vocab_file:
|
504 |
+
custom_model = {
|
505 |
+
'model': custom_model_file.name,
|
506 |
+
'config': custom_config_file.name,
|
507 |
+
'vocab': custom_vocab_file.name
|
508 |
+
}
|
509 |
+
|
510 |
+
try:
|
511 |
+
progress(0, desc="Starting conversion")
|
512 |
+
except Exception as e:
|
513 |
+
print(f"Error updating progress: {e}")
|
514 |
+
|
515 |
+
if not calibre_installed():
|
516 |
+
return "Calibre is not installed."
|
517 |
+
|
518 |
+
working_files = os.path.join(".", "Working_files", "temp_ebook")
|
519 |
+
full_folder_working_files = os.path.join(".", "Working_files")
|
520 |
+
chapters_directory = os.path.join(".", "Working_files", "temp_ebook")
|
521 |
+
output_audio_directory = os.path.join(".", 'Chapter_wav_files')
|
522 |
+
remove_folder_with_contents(full_folder_working_files)
|
523 |
+
remove_folder_with_contents(output_audio_directory)
|
524 |
+
|
525 |
+
try:
|
526 |
+
progress(0.1, desc="Creating chapter-labeled book")
|
527 |
+
except Exception as e:
|
528 |
+
print(f"Error updating progress: {e}")
|
529 |
+
|
530 |
+
create_chapter_labeled_book(ebook_file_path)
|
531 |
+
audiobook_output_path = os.path.join(".", "Audiobooks")
|
532 |
+
|
533 |
+
try:
|
534 |
+
progress(0.3, desc="Converting chapters to audio")
|
535 |
+
except Exception as e:
|
536 |
+
print(f"Error updating progress: {e}")
|
537 |
+
|
538 |
+
if use_custom_model:
|
539 |
+
convert_chapters_to_audio_custom_model(chapters_directory, output_audio_directory, target_voice, language, custom_model)
|
540 |
+
else:
|
541 |
+
convert_chapters_to_audio_standard_model(chapters_directory, output_audio_directory, target_voice, language)
|
542 |
+
|
543 |
+
try:
|
544 |
+
progress(0.9, desc="Creating M4B from chapters")
|
545 |
+
except Exception as e:
|
546 |
+
print(f"Error updating progress: {e}")
|
547 |
+
|
548 |
+
create_m4b_from_chapters(output_audio_directory, ebook_file_path, audiobook_output_path)
|
549 |
+
|
550 |
+
# Get the name of the created M4B file
|
551 |
+
m4b_filename = os.path.splitext(os.path.basename(ebook_file_path))[0] + '.m4b'
|
552 |
+
m4b_filepath = os.path.join(audiobook_output_path, m4b_filename)
|
553 |
+
|
554 |
+
try:
|
555 |
+
progress(1.0, desc="Conversion complete")
|
556 |
+
except Exception as e:
|
557 |
+
print(f"Error updating progress: {e}")
|
558 |
+
|
559 |
+
return f"Audiobook created at {m4b_filepath}", m4b_filepath
|
560 |
+
|
561 |
+
language_options = [
|
562 |
+
"en", "es", "fr", "de", "it", "pt", "pl", "tr", "ru", "nl", "cs", "ar", "zh-cn", "ja", "hu", "ko"
|
563 |
+
]
|
564 |
+
|
565 |
+
theme = gr.themes.Soft(
|
566 |
+
primary_hue="blue",
|
567 |
+
secondary_hue="blue",
|
568 |
+
neutral_hue="blue",
|
569 |
+
text_size=gr.themes.sizes.text_md,
|
570 |
+
)
|
571 |
+
|
572 |
+
with gr.Blocks(theme=theme) as demo:
|
573 |
+
gr.Markdown(
|
574 |
+
"""
|
575 |
+
# eBook to Audiobook Converter
|
576 |
+
|
577 |
+
Transform your eBooks into immersive audiobooks with optional custom TTS models.
|
578 |
+
"""
|
579 |
+
)
|
580 |
+
|
581 |
+
with gr.Row():
|
582 |
+
with gr.Column(scale=3):
|
583 |
+
ebook_file = gr.File(label="eBook File")
|
584 |
+
target_voice_file = gr.File(label="Target Voice File (Optional)")
|
585 |
+
language = gr.Dropdown(label="Language", choices=language_options, value="en")
|
586 |
+
|
587 |
+
with gr.Column(scale=3):
|
588 |
+
use_custom_model = gr.Checkbox(label="Use Custom Model")
|
589 |
+
custom_model_file = gr.File(label="Custom Model File (Optional)", visible=False)
|
590 |
+
custom_config_file = gr.File(label="Custom Config File (Optional)", visible=False)
|
591 |
+
custom_vocab_file = gr.File(label="Custom Vocab File (Optional)", visible=False)
|
592 |
+
|
593 |
+
convert_btn = gr.Button("Convert to Audiobook", variant="primary")
|
594 |
+
output = gr.Textbox(label="Conversion Status")
|
595 |
+
audio_player = gr.Audio(label="Audiobook Player", type="filepath")
|
596 |
+
|
597 |
+
convert_btn.click(
|
598 |
+
convert_ebook_to_audio,
|
599 |
+
inputs=[ebook_file, target_voice_file, language, use_custom_model, custom_model_file, custom_config_file, custom_vocab_file],
|
600 |
+
outputs=[output, audio_player]
|
601 |
+
)
|
602 |
+
|
603 |
+
use_custom_model.change(
|
604 |
+
lambda x: [gr.update(visible=x)] * 3,
|
605 |
+
inputs=[use_custom_model],
|
606 |
+
outputs=[custom_model_file, custom_config_file, custom_vocab_file]
|
607 |
+
)
|
608 |
+
|
609 |
+
demo.launch(share=False)
|
legacy/v1.0/legacy/custom_model_ebook2audiobookXTTS_with_link_gradio.py
ADDED
@@ -0,0 +1,700 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
print("starting...")
|
2 |
+
|
3 |
+
import os
|
4 |
+
import shutil
|
5 |
+
import subprocess
|
6 |
+
import re
|
7 |
+
from pydub import AudioSegment
|
8 |
+
import tempfile
|
9 |
+
from pydub import AudioSegment
|
10 |
+
import os
|
11 |
+
import nltk
|
12 |
+
from nltk.tokenize import sent_tokenize
|
13 |
+
import sys
|
14 |
+
import torch
|
15 |
+
from TTS.api import TTS
|
16 |
+
from TTS.tts.configs.xtts_config import XttsConfig
|
17 |
+
from TTS.tts.models.xtts import Xtts
|
18 |
+
from tqdm import tqdm
|
19 |
+
import gradio as gr
|
20 |
+
from gradio import Progress
|
21 |
+
import urllib.request
|
22 |
+
import zipfile
|
23 |
+
|
24 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
25 |
+
print(f"Device selected is: {device}")
|
26 |
+
|
27 |
+
nltk.download('punkt') # Make sure to download the necessary models
|
28 |
+
|
29 |
+
|
30 |
+
def download_and_extract_zip(url, extract_to='.'):
|
31 |
+
try:
|
32 |
+
# Ensure the directory exists
|
33 |
+
os.makedirs(extract_to, exist_ok=True)
|
34 |
+
|
35 |
+
zip_path = os.path.join(extract_to, 'model.zip')
|
36 |
+
|
37 |
+
# Download with progress bar
|
38 |
+
with tqdm(unit='B', unit_scale=True, miniters=1, desc="Downloading Model") as t:
|
39 |
+
def reporthook(blocknum, blocksize, totalsize):
|
40 |
+
t.total = totalsize
|
41 |
+
t.update(blocknum * blocksize - t.n)
|
42 |
+
|
43 |
+
urllib.request.urlretrieve(url, zip_path, reporthook=reporthook)
|
44 |
+
print(f"Downloaded zip file to {zip_path}")
|
45 |
+
|
46 |
+
# Unzipping with progress bar
|
47 |
+
with zipfile.ZipFile(zip_path, 'r') as zip_ref:
|
48 |
+
files = zip_ref.namelist()
|
49 |
+
with tqdm(total=len(files), unit="file", desc="Extracting Files") as t:
|
50 |
+
for file in files:
|
51 |
+
if not file.endswith('/'): # Skip directories
|
52 |
+
# Extract the file to the temporary directory
|
53 |
+
extracted_path = zip_ref.extract(file, extract_to)
|
54 |
+
# Move the file to the base directory
|
55 |
+
base_file_path = os.path.join(extract_to, os.path.basename(file))
|
56 |
+
os.rename(extracted_path, base_file_path)
|
57 |
+
t.update(1)
|
58 |
+
|
59 |
+
# Cleanup: Remove the ZIP file and any empty folders
|
60 |
+
os.remove(zip_path)
|
61 |
+
for root, dirs, files in os.walk(extract_to, topdown=False):
|
62 |
+
for name in dirs:
|
63 |
+
os.rmdir(os.path.join(root, name))
|
64 |
+
print(f"Extracted files to {extract_to}")
|
65 |
+
|
66 |
+
# Check if all required files are present
|
67 |
+
required_files = ['model.pth', 'config.json', 'vocab.json_']
|
68 |
+
missing_files = [file for file in required_files if not os.path.exists(os.path.join(extract_to, file))]
|
69 |
+
|
70 |
+
if not missing_files:
|
71 |
+
print("All required files (model.pth, config.json, vocab.json_) found.")
|
72 |
+
else:
|
73 |
+
print(f"Missing files: {', '.join(missing_files)}")
|
74 |
+
|
75 |
+
except Exception as e:
|
76 |
+
print(f"Failed to download or extract zip file: {e}")
|
77 |
+
|
78 |
+
|
79 |
+
|
80 |
+
def is_folder_empty(folder_path):
|
81 |
+
if os.path.exists(folder_path) and os.path.isdir(folder_path):
|
82 |
+
# List directory contents
|
83 |
+
if not os.listdir(folder_path):
|
84 |
+
return True # The folder is empty
|
85 |
+
else:
|
86 |
+
return False # The folder is not empty
|
87 |
+
else:
|
88 |
+
print(f"The path {folder_path} is not a valid folder.")
|
89 |
+
return None # The path is not a valid folder
|
90 |
+
|
91 |
+
def remove_folder_with_contents(folder_path):
|
92 |
+
try:
|
93 |
+
shutil.rmtree(folder_path)
|
94 |
+
print(f"Successfully removed {folder_path} and all of its contents.")
|
95 |
+
except Exception as e:
|
96 |
+
print(f"Error removing {folder_path}: {e}")
|
97 |
+
|
98 |
+
|
99 |
+
|
100 |
+
|
101 |
+
def wipe_folder(folder_path):
|
102 |
+
# Check if the folder exists
|
103 |
+
if not os.path.exists(folder_path):
|
104 |
+
print(f"The folder {folder_path} does not exist.")
|
105 |
+
return
|
106 |
+
|
107 |
+
# Iterate over all the items in the given folder
|
108 |
+
for item in os.listdir(folder_path):
|
109 |
+
item_path = os.path.join(folder_path, item)
|
110 |
+
# If it's a file, remove it and print a message
|
111 |
+
if os.path.isfile(item_path):
|
112 |
+
os.remove(item_path)
|
113 |
+
print(f"Removed file: {item_path}")
|
114 |
+
# If it's a directory, remove it recursively and print a message
|
115 |
+
elif os.path.isdir(item_path):
|
116 |
+
shutil.rmtree(item_path)
|
117 |
+
print(f"Removed directory and its contents: {item_path}")
|
118 |
+
|
119 |
+
print(f"All contents wiped from {folder_path}.")
|
120 |
+
|
121 |
+
|
122 |
+
# Example usage
|
123 |
+
# folder_to_wipe = 'path_to_your_folder'
|
124 |
+
# wipe_folder(folder_to_wipe)
|
125 |
+
|
126 |
+
|
127 |
+
def create_m4b_from_chapters(input_dir, ebook_file, output_dir):
|
128 |
+
# Function to sort chapters based on their numeric order
|
129 |
+
def sort_key(chapter_file):
|
130 |
+
numbers = re.findall(r'\d+', chapter_file)
|
131 |
+
return int(numbers[0]) if numbers else 0
|
132 |
+
|
133 |
+
# Extract metadata and cover image from the eBook file
|
134 |
+
def extract_metadata_and_cover(ebook_path):
|
135 |
+
try:
|
136 |
+
cover_path = ebook_path.rsplit('.', 1)[0] + '.jpg'
|
137 |
+
subprocess.run(['ebook-meta', ebook_path, '--get-cover', cover_path], check=True)
|
138 |
+
if os.path.exists(cover_path):
|
139 |
+
return cover_path
|
140 |
+
except Exception as e:
|
141 |
+
print(f"Error extracting eBook metadata or cover: {e}")
|
142 |
+
return None
|
143 |
+
# Combine WAV files into a single file
|
144 |
+
def combine_wav_files(chapter_files, output_path):
|
145 |
+
# Initialize an empty audio segment
|
146 |
+
combined_audio = AudioSegment.empty()
|
147 |
+
|
148 |
+
# Sequentially append each file to the combined_audio
|
149 |
+
for chapter_file in chapter_files:
|
150 |
+
audio_segment = AudioSegment.from_wav(chapter_file)
|
151 |
+
combined_audio += audio_segment
|
152 |
+
# Export the combined audio to the output file path
|
153 |
+
combined_audio.export(output_path, format='wav')
|
154 |
+
print(f"Combined audio saved to {output_path}")
|
155 |
+
|
156 |
+
# Function to generate metadata for M4B chapters
|
157 |
+
def generate_ffmpeg_metadata(chapter_files, metadata_file):
|
158 |
+
with open(metadata_file, 'w') as file:
|
159 |
+
file.write(';FFMETADATA1\n')
|
160 |
+
start_time = 0
|
161 |
+
for index, chapter_file in enumerate(chapter_files):
|
162 |
+
duration_ms = len(AudioSegment.from_wav(chapter_file))
|
163 |
+
file.write(f'[CHAPTER]\nTIMEBASE=1/1000\nSTART={start_time}\n')
|
164 |
+
file.write(f'END={start_time + duration_ms}\ntitle=Chapter {index + 1}\n')
|
165 |
+
start_time += duration_ms
|
166 |
+
|
167 |
+
# Generate the final M4B file using ffmpeg
|
168 |
+
def create_m4b(combined_wav, metadata_file, cover_image, output_m4b):
|
169 |
+
# Ensure the output directory exists
|
170 |
+
os.makedirs(os.path.dirname(output_m4b), exist_ok=True)
|
171 |
+
|
172 |
+
ffmpeg_cmd = ['ffmpeg', '-i', combined_wav, '-i', metadata_file]
|
173 |
+
if cover_image:
|
174 |
+
ffmpeg_cmd += ['-i', cover_image, '-map', '0:a', '-map', '2:v']
|
175 |
+
else:
|
176 |
+
ffmpeg_cmd += ['-map', '0:a']
|
177 |
+
|
178 |
+
ffmpeg_cmd += ['-map_metadata', '1', '-c:a', 'aac', '-b:a', '192k']
|
179 |
+
if cover_image:
|
180 |
+
ffmpeg_cmd += ['-c:v', 'png', '-disposition:v', 'attached_pic']
|
181 |
+
ffmpeg_cmd += [output_m4b]
|
182 |
+
|
183 |
+
subprocess.run(ffmpeg_cmd, check=True)
|
184 |
+
|
185 |
+
|
186 |
+
|
187 |
+
# Main logic
|
188 |
+
chapter_files = sorted([os.path.join(input_dir, f) for f in os.listdir(input_dir) if f.endswith('.wav')], key=sort_key)
|
189 |
+
temp_dir = tempfile.gettempdir()
|
190 |
+
temp_combined_wav = os.path.join(temp_dir, 'combined.wav')
|
191 |
+
metadata_file = os.path.join(temp_dir, 'metadata.txt')
|
192 |
+
cover_image = extract_metadata_and_cover(ebook_file)
|
193 |
+
output_m4b = os.path.join(output_dir, os.path.splitext(os.path.basename(ebook_file))[0] + '.m4b')
|
194 |
+
|
195 |
+
combine_wav_files(chapter_files, temp_combined_wav)
|
196 |
+
generate_ffmpeg_metadata(chapter_files, metadata_file)
|
197 |
+
create_m4b(temp_combined_wav, metadata_file, cover_image, output_m4b)
|
198 |
+
|
199 |
+
# Cleanup
|
200 |
+
if os.path.exists(temp_combined_wav):
|
201 |
+
os.remove(temp_combined_wav)
|
202 |
+
if os.path.exists(metadata_file):
|
203 |
+
os.remove(metadata_file)
|
204 |
+
if cover_image and os.path.exists(cover_image):
|
205 |
+
os.remove(cover_image)
|
206 |
+
|
207 |
+
# Example usage
|
208 |
+
# create_m4b_from_chapters('path_to_chapter_wavs', 'path_to_ebook_file', 'path_to_output_dir')
|
209 |
+
|
210 |
+
|
211 |
+
|
212 |
+
|
213 |
+
|
214 |
+
|
215 |
+
#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
|
216 |
+
import os
|
217 |
+
import subprocess
|
218 |
+
import ebooklib
|
219 |
+
from ebooklib import epub
|
220 |
+
from bs4 import BeautifulSoup
|
221 |
+
import re
|
222 |
+
import csv
|
223 |
+
import nltk
|
224 |
+
|
225 |
+
# Only run the main script if Value is True
|
226 |
+
def create_chapter_labeled_book(ebook_file_path):
|
227 |
+
# Function to ensure the existence of a directory
|
228 |
+
def ensure_directory(directory_path):
|
229 |
+
if not os.path.exists(directory_path):
|
230 |
+
os.makedirs(directory_path)
|
231 |
+
print(f"Created directory: {directory_path}")
|
232 |
+
|
233 |
+
ensure_directory(os.path.join(".", 'Working_files', 'Book'))
|
234 |
+
|
235 |
+
def convert_to_epub(input_path, output_path):
|
236 |
+
# Convert the ebook to EPUB format using Calibre's ebook-convert
|
237 |
+
try:
|
238 |
+
subprocess.run(['ebook-convert', input_path, output_path], check=True)
|
239 |
+
except subprocess.CalledProcessError as e:
|
240 |
+
print(f"An error occurred while converting the eBook: {e}")
|
241 |
+
return False
|
242 |
+
return True
|
243 |
+
|
244 |
+
def save_chapters_as_text(epub_path):
|
245 |
+
# Create the directory if it doesn't exist
|
246 |
+
directory = os.path.join(".", "Working_files", "temp_ebook")
|
247 |
+
ensure_directory(directory)
|
248 |
+
|
249 |
+
# Open the EPUB file
|
250 |
+
book = epub.read_epub(epub_path)
|
251 |
+
|
252 |
+
previous_chapter_text = ''
|
253 |
+
previous_filename = ''
|
254 |
+
chapter_counter = 0
|
255 |
+
|
256 |
+
# Iterate through the items in the EPUB file
|
257 |
+
for item in book.get_items():
|
258 |
+
if item.get_type() == ebooklib.ITEM_DOCUMENT:
|
259 |
+
# Use BeautifulSoup to parse HTML content
|
260 |
+
soup = BeautifulSoup(item.get_content(), 'html.parser')
|
261 |
+
text = soup.get_text()
|
262 |
+
|
263 |
+
# Check if the text is not empty
|
264 |
+
if text.strip():
|
265 |
+
if len(text) < 2300 and previous_filename:
|
266 |
+
# Append text to the previous chapter if it's short
|
267 |
+
with open(previous_filename, 'a', encoding='utf-8') as file:
|
268 |
+
file.write('\n' + text)
|
269 |
+
else:
|
270 |
+
# Create a new chapter file and increment the counter
|
271 |
+
previous_filename = os.path.join(directory, f"chapter_{chapter_counter}.txt")
|
272 |
+
chapter_counter += 1
|
273 |
+
with open(previous_filename, 'w', encoding='utf-8') as file:
|
274 |
+
file.write(text)
|
275 |
+
print(f"Saved chapter: {previous_filename}")
|
276 |
+
|
277 |
+
# Example usage
|
278 |
+
input_ebook = ebook_file_path # Replace with your eBook file path
|
279 |
+
output_epub = os.path.join(".", "Working_files", "temp.epub")
|
280 |
+
|
281 |
+
|
282 |
+
if os.path.exists(output_epub):
|
283 |
+
os.remove(output_epub)
|
284 |
+
print(f"File {output_epub} has been removed.")
|
285 |
+
else:
|
286 |
+
print(f"The file {output_epub} does not exist.")
|
287 |
+
|
288 |
+
if convert_to_epub(input_ebook, output_epub):
|
289 |
+
save_chapters_as_text(output_epub)
|
290 |
+
|
291 |
+
# Download the necessary NLTK data (if not already present)
|
292 |
+
nltk.download('punkt')
|
293 |
+
|
294 |
+
def process_chapter_files(folder_path, output_csv):
|
295 |
+
with open(output_csv, 'w', newline='', encoding='utf-8') as csvfile:
|
296 |
+
writer = csv.writer(csvfile)
|
297 |
+
# Write the header row
|
298 |
+
writer.writerow(['Text', 'Start Location', 'End Location', 'Is Quote', 'Speaker', 'Chapter'])
|
299 |
+
|
300 |
+
# Process each chapter file
|
301 |
+
chapter_files = sorted(os.listdir(folder_path), key=lambda x: int(x.split('_')[1].split('.')[0]))
|
302 |
+
for filename in chapter_files:
|
303 |
+
if filename.startswith('chapter_') and filename.endswith('.txt'):
|
304 |
+
chapter_number = int(filename.split('_')[1].split('.')[0])
|
305 |
+
file_path = os.path.join(folder_path, filename)
|
306 |
+
|
307 |
+
try:
|
308 |
+
with open(file_path, 'r', encoding='utf-8') as file:
|
309 |
+
text = file.read()
|
310 |
+
# Insert "NEWCHAPTERABC" at the beginning of each chapter's text
|
311 |
+
if text:
|
312 |
+
text = "NEWCHAPTERABC" + text
|
313 |
+
sentences = nltk.tokenize.sent_tokenize(text)
|
314 |
+
for sentence in sentences:
|
315 |
+
start_location = text.find(sentence)
|
316 |
+
end_location = start_location + len(sentence)
|
317 |
+
writer.writerow([sentence, start_location, end_location, 'True', 'Narrator', chapter_number])
|
318 |
+
except Exception as e:
|
319 |
+
print(f"Error processing file {filename}: {e}")
|
320 |
+
|
321 |
+
# Example usage
|
322 |
+
folder_path = os.path.join(".", "Working_files", "temp_ebook")
|
323 |
+
output_csv = os.path.join(".", "Working_files", "Book", "Other_book.csv")
|
324 |
+
|
325 |
+
process_chapter_files(folder_path, output_csv)
|
326 |
+
|
327 |
+
def sort_key(filename):
|
328 |
+
"""Extract chapter number for sorting."""
|
329 |
+
match = re.search(r'chapter_(\d+)\.txt', filename)
|
330 |
+
return int(match.group(1)) if match else 0
|
331 |
+
|
332 |
+
def combine_chapters(input_folder, output_file):
|
333 |
+
# Create the output folder if it doesn't exist
|
334 |
+
os.makedirs(os.path.dirname(output_file), exist_ok=True)
|
335 |
+
|
336 |
+
# List all txt files and sort them by chapter number
|
337 |
+
files = [f for f in os.listdir(input_folder) if f.endswith('.txt')]
|
338 |
+
sorted_files = sorted(files, key=sort_key)
|
339 |
+
|
340 |
+
with open(output_file, 'w', encoding='utf-8') as outfile: # Specify UTF-8 encoding here
|
341 |
+
for i, filename in enumerate(sorted_files):
|
342 |
+
with open(os.path.join(input_folder, filename), 'r', encoding='utf-8') as infile: # And here
|
343 |
+
outfile.write(infile.read())
|
344 |
+
# Add the marker unless it's the last file
|
345 |
+
if i < len(sorted_files) - 1:
|
346 |
+
outfile.write("\nNEWCHAPTERABC\n")
|
347 |
+
|
348 |
+
# Paths
|
349 |
+
input_folder = os.path.join(".", 'Working_files', 'temp_ebook')
|
350 |
+
output_file = os.path.join(".", 'Working_files', 'Book', 'Chapter_Book.txt')
|
351 |
+
|
352 |
+
|
353 |
+
# Combine the chapters
|
354 |
+
combine_chapters(input_folder, output_file)
|
355 |
+
|
356 |
+
ensure_directory(os.path.join(".", "Working_files", "Book"))
|
357 |
+
|
358 |
+
|
359 |
+
#create_chapter_labeled_book()
|
360 |
+
|
361 |
+
|
362 |
+
|
363 |
+
|
364 |
+
import os
|
365 |
+
import subprocess
|
366 |
+
import sys
|
367 |
+
import torchaudio
|
368 |
+
|
369 |
+
# Check if Calibre's ebook-convert tool is installed
|
370 |
+
def calibre_installed():
|
371 |
+
try:
|
372 |
+
subprocess.run(['ebook-convert', '--version'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
373 |
+
return True
|
374 |
+
except FileNotFoundError:
|
375 |
+
print("Calibre is not installed. Please install Calibre for this functionality.")
|
376 |
+
return False
|
377 |
+
|
378 |
+
|
379 |
+
import os
|
380 |
+
import torch
|
381 |
+
from TTS.api import TTS
|
382 |
+
from nltk.tokenize import sent_tokenize
|
383 |
+
from pydub import AudioSegment
|
384 |
+
# Assuming split_long_sentence and wipe_folder are defined elsewhere in your code
|
385 |
+
|
386 |
+
default_target_voice_path = "default_voice.wav" # Ensure this is a valid path
|
387 |
+
default_language_code = "en"
|
388 |
+
def combine_wav_files(input_directory, output_directory, file_name):
|
389 |
+
# Ensure that the output directory exists, create it if necessary
|
390 |
+
os.makedirs(output_directory, exist_ok=True)
|
391 |
+
|
392 |
+
# Specify the output file path
|
393 |
+
output_file_path = os.path.join(output_directory, file_name)
|
394 |
+
|
395 |
+
# Initialize an empty audio segment
|
396 |
+
combined_audio = AudioSegment.empty()
|
397 |
+
|
398 |
+
# Get a list of all .wav files in the specified input directory and sort them
|
399 |
+
input_file_paths = sorted(
|
400 |
+
[os.path.join(input_directory, f) for f in os.listdir(input_directory) if f.endswith(".wav")],
|
401 |
+
key=lambda f: int(''.join(filter(str.isdigit, f)))
|
402 |
+
)
|
403 |
+
|
404 |
+
# Sequentially append each file to the combined_audio
|
405 |
+
for input_file_path in input_file_paths:
|
406 |
+
audio_segment = AudioSegment.from_wav(input_file_path)
|
407 |
+
combined_audio += audio_segment
|
408 |
+
|
409 |
+
# Export the combined audio to the output file path
|
410 |
+
combined_audio.export(output_file_path, format='wav')
|
411 |
+
|
412 |
+
print(f"Combined audio saved to {output_file_path}")
|
413 |
+
|
414 |
+
# Function to split long strings into parts
|
415 |
+
def split_long_sentence(sentence, max_length=249, max_pauses=10):
|
416 |
+
"""
|
417 |
+
Splits a sentence into parts based on length or number of pauses without recursion.
|
418 |
+
|
419 |
+
:param sentence: The sentence to split.
|
420 |
+
:param max_length: Maximum allowed length of a sentence.
|
421 |
+
:param max_pauses: Maximum allowed number of pauses in a sentence.
|
422 |
+
:return: A list of sentence parts that meet the criteria.
|
423 |
+
"""
|
424 |
+
parts = []
|
425 |
+
while len(sentence) > max_length or sentence.count(',') + sentence.count(';') + sentence.count('.') > max_pauses:
|
426 |
+
possible_splits = [i for i, char in enumerate(sentence) if char in ',;.' and i < max_length]
|
427 |
+
if possible_splits:
|
428 |
+
# Find the best place to split the sentence, preferring the last possible split to keep parts longer
|
429 |
+
split_at = possible_splits[-1] + 1
|
430 |
+
else:
|
431 |
+
# If no punctuation to split on within max_length, split at max_length
|
432 |
+
split_at = max_length
|
433 |
+
|
434 |
+
# Split the sentence and add the first part to the list
|
435 |
+
parts.append(sentence[:split_at].strip())
|
436 |
+
sentence = sentence[split_at:].strip()
|
437 |
+
|
438 |
+
# Add the remaining part of the sentence
|
439 |
+
parts.append(sentence)
|
440 |
+
return parts
|
441 |
+
|
442 |
+
"""
|
443 |
+
if 'tts' not in locals():
|
444 |
+
tts = TTS(selected_tts_model, progress_bar=True).to(device)
|
445 |
+
"""
|
446 |
+
from tqdm import tqdm
|
447 |
+
|
448 |
+
# Convert chapters to audio using XTTS
|
449 |
+
|
450 |
+
def convert_chapters_to_audio_custom_model(chapters_dir, output_audio_dir, target_voice_path=None, language=None, custom_model=None):
|
451 |
+
|
452 |
+
if target_voice_path==None:
|
453 |
+
target_voice_path = default_target_voice_path
|
454 |
+
|
455 |
+
if custom_model:
|
456 |
+
print("Loading custom model...")
|
457 |
+
config = XttsConfig()
|
458 |
+
config.load_json(custom_model['config'])
|
459 |
+
model = Xtts.init_from_config(config)
|
460 |
+
model.load_checkpoint(config, checkpoint_path=custom_model['model'], vocab_path=custom_model['vocab'], use_deepspeed=False)
|
461 |
+
model.to(device)
|
462 |
+
print("Computing speaker latents...")
|
463 |
+
gpt_cond_latent, speaker_embedding = model.get_conditioning_latents(audio_path=[target_voice_path])
|
464 |
+
else:
|
465 |
+
selected_tts_model = "tts_models/multilingual/multi-dataset/xtts_v2"
|
466 |
+
tts = TTS(selected_tts_model, progress_bar=False).to(device)
|
467 |
+
|
468 |
+
if not os.path.exists(output_audio_dir):
|
469 |
+
os.makedirs(output_audio_dir)
|
470 |
+
|
471 |
+
for chapter_file in sorted(os.listdir(chapters_dir)):
|
472 |
+
if chapter_file.endswith('.txt'):
|
473 |
+
match = re.search(r"chapter_(\d+).txt", chapter_file)
|
474 |
+
if match:
|
475 |
+
chapter_num = int(match.group(1))
|
476 |
+
else:
|
477 |
+
print(f"Skipping file {chapter_file} as it does not match the expected format.")
|
478 |
+
continue
|
479 |
+
|
480 |
+
chapter_path = os.path.join(chapters_dir, chapter_file)
|
481 |
+
output_file_name = f"audio_chapter_{chapter_num}.wav"
|
482 |
+
output_file_path = os.path.join(output_audio_dir, output_file_name)
|
483 |
+
temp_audio_directory = os.path.join(".", "Working_files", "temp")
|
484 |
+
os.makedirs(temp_audio_directory, exist_ok=True)
|
485 |
+
temp_count = 0
|
486 |
+
|
487 |
+
with open(chapter_path, 'r', encoding='utf-8') as file:
|
488 |
+
chapter_text = file.read()
|
489 |
+
sentences = sent_tokenize(chapter_text, language='italian' if language == 'it' else 'english')
|
490 |
+
for sentence in tqdm(sentences, desc=f"Chapter {chapter_num}"):
|
491 |
+
fragments = split_long_sentence(sentence, max_length=249 if language == "en" else 213, max_pauses=10)
|
492 |
+
for fragment in fragments:
|
493 |
+
if fragment != "":
|
494 |
+
print(f"Generating fragment: {fragment}...")
|
495 |
+
fragment_file_path = os.path.join(temp_audio_directory, f"{temp_count}.wav")
|
496 |
+
if custom_model:
|
497 |
+
out = model.inference(fragment, language, gpt_cond_latent, speaker_embedding, temperature=0.7)
|
498 |
+
torchaudio.save(fragment_file_path, torch.tensor(out["wav"]).unsqueeze(0), 24000)
|
499 |
+
else:
|
500 |
+
speaker_wav_path = target_voice_path if target_voice_path else default_target_voice_path
|
501 |
+
language_code = language if language else default_language_code
|
502 |
+
tts.tts_to_file(text=fragment, file_path=fragment_file_path, speaker_wav=speaker_wav_path, language=language_code)
|
503 |
+
temp_count += 1
|
504 |
+
|
505 |
+
combine_wav_files(temp_audio_directory, output_audio_dir, output_file_name)
|
506 |
+
wipe_folder(temp_audio_directory)
|
507 |
+
print(f"Converted chapter {chapter_num} to audio.")
|
508 |
+
|
509 |
+
|
510 |
+
|
511 |
+
def convert_chapters_to_audio_standard_model(chapters_dir, output_audio_dir, target_voice_path=None, language=None):
|
512 |
+
selected_tts_model = "tts_models/multilingual/multi-dataset/xtts_v2"
|
513 |
+
tts = TTS(selected_tts_model, progress_bar=False).to(device)
|
514 |
+
|
515 |
+
if not os.path.exists(output_audio_dir):
|
516 |
+
os.makedirs(output_audio_dir)
|
517 |
+
|
518 |
+
for chapter_file in sorted(os.listdir(chapters_dir)):
|
519 |
+
if chapter_file.endswith('.txt'):
|
520 |
+
match = re.search(r"chapter_(\d+).txt", chapter_file)
|
521 |
+
if match:
|
522 |
+
chapter_num = int(match.group(1))
|
523 |
+
else:
|
524 |
+
print(f"Skipping file {chapter_file} as it does not match the expected format.")
|
525 |
+
continue
|
526 |
+
|
527 |
+
chapter_path = os.path.join(chapters_dir, chapter_file)
|
528 |
+
output_file_name = f"audio_chapter_{chapter_num}.wav"
|
529 |
+
output_file_path = os.path.join(output_audio_dir, output_file_name)
|
530 |
+
temp_audio_directory = os.path.join(".", "Working_files", "temp")
|
531 |
+
os.makedirs(temp_audio_directory, exist_ok=True)
|
532 |
+
temp_count = 0
|
533 |
+
|
534 |
+
with open(chapter_path, 'r', encoding='utf-8') as file:
|
535 |
+
chapter_text = file.read()
|
536 |
+
sentences = sent_tokenize(chapter_text, language='italian' if language == 'it' else 'english')
|
537 |
+
for sentence in tqdm(sentences, desc=f"Chapter {chapter_num}"):
|
538 |
+
fragments = split_long_sentence(sentence, max_length=249 if language == "en" else 213, max_pauses=10)
|
539 |
+
for fragment in fragments:
|
540 |
+
if fragment != "":
|
541 |
+
print(f"Generating fragment: {fragment}...")
|
542 |
+
fragment_file_path = os.path.join(temp_audio_directory, f"{temp_count}.wav")
|
543 |
+
speaker_wav_path = target_voice_path if target_voice_path else default_target_voice_path
|
544 |
+
language_code = language if language else default_language_code
|
545 |
+
tts.tts_to_file(text=fragment, file_path=fragment_file_path, speaker_wav=speaker_wav_path, language=language_code)
|
546 |
+
temp_count += 1
|
547 |
+
|
548 |
+
combine_wav_files(temp_audio_directory, output_audio_dir, output_file_name)
|
549 |
+
wipe_folder(temp_audio_directory)
|
550 |
+
print(f"Converted chapter {chapter_num} to audio.")
|
551 |
+
|
552 |
+
|
553 |
+
|
554 |
+
# Define the functions to be used in the Gradio interface
|
555 |
+
def convert_ebook_to_audio(ebook_file, target_voice_file, language, use_custom_model, custom_model_file, custom_config_file, custom_vocab_file, custom_model_url=None, progress=gr.Progress()):
|
556 |
+
ebook_file_path = ebook_file.name
|
557 |
+
target_voice = target_voice_file.name if target_voice_file else None
|
558 |
+
custom_model = None
|
559 |
+
|
560 |
+
|
561 |
+
working_files = os.path.join(".", "Working_files", "temp_ebook")
|
562 |
+
full_folder_working_files = os.path.join(".", "Working_files")
|
563 |
+
chapters_directory = os.path.join(".", "Working_files", "temp_ebook")
|
564 |
+
output_audio_directory = os.path.join(".", 'Chapter_wav_files')
|
565 |
+
remove_folder_with_contents(full_folder_working_files)
|
566 |
+
remove_folder_with_contents(output_audio_directory)
|
567 |
+
|
568 |
+
if use_custom_model and custom_model_file and custom_config_file and custom_vocab_file:
|
569 |
+
custom_model = {
|
570 |
+
'model': custom_model_file.name,
|
571 |
+
'config': custom_config_file.name,
|
572 |
+
'vocab': custom_vocab_file.name
|
573 |
+
}
|
574 |
+
if use_custom_model and custom_model_url:
|
575 |
+
print(f"Received custom model URL: {custom_model_url}")
|
576 |
+
download_dir = os.path.join(".", "Working_files", "custom_model")
|
577 |
+
download_and_extract_zip(custom_model_url, download_dir)
|
578 |
+
custom_model = {
|
579 |
+
'model': os.path.join(download_dir, 'model.pth'),
|
580 |
+
'config': os.path.join(download_dir, 'config.json'),
|
581 |
+
'vocab': os.path.join(download_dir, 'vocab.json_')
|
582 |
+
}
|
583 |
+
|
584 |
+
try:
|
585 |
+
progress(0, desc="Starting conversion")
|
586 |
+
except Exception as e:
|
587 |
+
print(f"Error updating progress: {e}")
|
588 |
+
|
589 |
+
if not calibre_installed():
|
590 |
+
return "Calibre is not installed."
|
591 |
+
|
592 |
+
|
593 |
+
try:
|
594 |
+
progress(0.1, desc="Creating chapter-labeled book")
|
595 |
+
except Exception as e:
|
596 |
+
print(f"Error updating progress: {e}")
|
597 |
+
|
598 |
+
create_chapter_labeled_book(ebook_file_path)
|
599 |
+
audiobook_output_path = os.path.join(".", "Audiobooks")
|
600 |
+
|
601 |
+
try:
|
602 |
+
progress(0.3, desc="Converting chapters to audio")
|
603 |
+
except Exception as e:
|
604 |
+
print(f"Error updating progress: {e}")
|
605 |
+
|
606 |
+
if use_custom_model:
|
607 |
+
convert_chapters_to_audio_custom_model(chapters_directory, output_audio_directory, target_voice, language, custom_model)
|
608 |
+
else:
|
609 |
+
convert_chapters_to_audio_standard_model(chapters_directory, output_audio_directory, target_voice, language)
|
610 |
+
|
611 |
+
try:
|
612 |
+
progress(0.9, desc="Creating M4B from chapters")
|
613 |
+
except Exception as e:
|
614 |
+
print(f"Error updating progress: {e}")
|
615 |
+
|
616 |
+
create_m4b_from_chapters(output_audio_directory, ebook_file_path, audiobook_output_path)
|
617 |
+
|
618 |
+
# Get the name of the created M4B file
|
619 |
+
m4b_filename = os.path.splitext(os.path.basename(ebook_file_path))[0] + '.m4b'
|
620 |
+
m4b_filepath = os.path.join(audiobook_output_path, m4b_filename)
|
621 |
+
|
622 |
+
try:
|
623 |
+
progress(1.0, desc="Conversion complete")
|
624 |
+
except Exception as e:
|
625 |
+
print(f"Error updating progress: {e}")
|
626 |
+
print(f"Audiobook created at {m4b_filepath}")
|
627 |
+
return f"Audiobook created at {m4b_filepath}", m4b_filepath
|
628 |
+
|
629 |
+
|
630 |
+
def list_audiobook_files(audiobook_folder):
|
631 |
+
# List all files in the audiobook folder
|
632 |
+
files = []
|
633 |
+
for filename in os.listdir(audiobook_folder):
|
634 |
+
if filename.endswith('.m4b'): # Adjust the file extension as needed
|
635 |
+
files.append(os.path.join(audiobook_folder, filename))
|
636 |
+
return files
|
637 |
+
|
638 |
+
def download_audiobooks():
|
639 |
+
audiobook_output_path = os.path.join(".", "Audiobooks")
|
640 |
+
return list_audiobook_files(audiobook_output_path)
|
641 |
+
|
642 |
+
|
643 |
+
language_options = [
|
644 |
+
"en", "es", "fr", "de", "it", "pt", "pl", "tr", "ru", "nl", "cs", "ar", "zh-cn", "ja", "hu", "ko"
|
645 |
+
]
|
646 |
+
|
647 |
+
theme = gr.themes.Soft(
|
648 |
+
primary_hue="blue",
|
649 |
+
secondary_hue="blue",
|
650 |
+
neutral_hue="blue",
|
651 |
+
text_size=gr.themes.sizes.text_md,
|
652 |
+
)
|
653 |
+
|
654 |
+
# Gradio UI setup
|
655 |
+
with gr.Blocks(theme=theme) as demo:
|
656 |
+
gr.Markdown(
|
657 |
+
"""
|
658 |
+
# eBook to Audiobook Converter
|
659 |
+
|
660 |
+
Transform your eBooks into immersive audiobooks with optional custom TTS models.
|
661 |
+
"""
|
662 |
+
)
|
663 |
+
|
664 |
+
with gr.Row():
|
665 |
+
with gr.Column(scale=3):
|
666 |
+
ebook_file = gr.File(label="eBook File")
|
667 |
+
target_voice_file = gr.File(label="Target Voice File (Optional)")
|
668 |
+
language = gr.Dropdown(label="Language", choices=language_options, value="en")
|
669 |
+
|
670 |
+
with gr.Column(scale=3):
|
671 |
+
use_custom_model = gr.Checkbox(label="Use Custom Model")
|
672 |
+
custom_model_file = gr.File(label="Custom Model File (Optional)", visible=False)
|
673 |
+
custom_config_file = gr.File(label="Custom Config File (Optional)", visible=False)
|
674 |
+
custom_vocab_file = gr.File(label="Custom Vocab File (Optional)", visible=False)
|
675 |
+
custom_model_url = gr.Textbox(label="Custom Model Zip URL (Optional)", visible=False)
|
676 |
+
|
677 |
+
convert_btn = gr.Button("Convert to Audiobook", variant="primary")
|
678 |
+
output = gr.Textbox(label="Conversion Status")
|
679 |
+
audio_player = gr.Audio(label="Audiobook Player", type="filepath")
|
680 |
+
download_btn = gr.Button("Download Audiobook Files")
|
681 |
+
download_files = gr.File(label="Download Files", interactive=False)
|
682 |
+
|
683 |
+
convert_btn.click(
|
684 |
+
convert_ebook_to_audio,
|
685 |
+
inputs=[ebook_file, target_voice_file, language, use_custom_model, custom_model_file, custom_config_file, custom_vocab_file, custom_model_url],
|
686 |
+
outputs=[output, audio_player]
|
687 |
+
)
|
688 |
+
|
689 |
+
use_custom_model.change(
|
690 |
+
lambda x: [gr.update(visible=x)] * 4,
|
691 |
+
inputs=[use_custom_model],
|
692 |
+
outputs=[custom_model_file, custom_config_file, custom_vocab_file, custom_model_url]
|
693 |
+
)
|
694 |
+
|
695 |
+
download_btn.click(
|
696 |
+
download_audiobooks,
|
697 |
+
outputs=[download_files]
|
698 |
+
)
|
699 |
+
|
700 |
+
demo.launch(share=True)
|
legacy/v1.0/legacy/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)
|
legacy/v1.0/legacy/gradio_gui_with_email_and_que.py
ADDED
@@ -0,0 +1,614 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
print("starting...")
|
2 |
+
import ebooklib
|
3 |
+
from ebooklib import epub
|
4 |
+
|
5 |
+
import os
|
6 |
+
import subprocess
|
7 |
+
import ebooklib
|
8 |
+
from ebooklib import epub
|
9 |
+
from bs4 import BeautifulSoup
|
10 |
+
import re
|
11 |
+
import csv
|
12 |
+
import nltk
|
13 |
+
|
14 |
+
import os
|
15 |
+
import subprocess
|
16 |
+
import sys
|
17 |
+
import torchaudio
|
18 |
+
|
19 |
+
import os
|
20 |
+
import torch
|
21 |
+
from TTS.api import TTS
|
22 |
+
from nltk.tokenize import sent_tokenize
|
23 |
+
from pydub import AudioSegment
|
24 |
+
|
25 |
+
from tqdm import tqdm
|
26 |
+
|
27 |
+
|
28 |
+
|
29 |
+
import os
|
30 |
+
import subprocess
|
31 |
+
import ebooklib
|
32 |
+
from ebooklib import epub
|
33 |
+
from bs4 import BeautifulSoup
|
34 |
+
import re
|
35 |
+
import csv
|
36 |
+
import nltk
|
37 |
+
|
38 |
+
from bs4 import BeautifulSoup
|
39 |
+
import os
|
40 |
+
import shutil
|
41 |
+
import subprocess
|
42 |
+
import re
|
43 |
+
from pydub import AudioSegment
|
44 |
+
import tempfile
|
45 |
+
import urllib.request
|
46 |
+
import zipfile
|
47 |
+
import requests
|
48 |
+
from tqdm import tqdm
|
49 |
+
import nltk
|
50 |
+
from nltk.tokenize import sent_tokenize
|
51 |
+
import torch
|
52 |
+
import torchaudio
|
53 |
+
import gradio as gr
|
54 |
+
from threading import Lock, Thread
|
55 |
+
from queue import Queue
|
56 |
+
import smtplib
|
57 |
+
from email.mime.text import MIMEText
|
58 |
+
|
59 |
+
|
60 |
+
import os
|
61 |
+
import shutil
|
62 |
+
import subprocess
|
63 |
+
import re
|
64 |
+
from pydub import AudioSegment
|
65 |
+
import tempfile
|
66 |
+
from pydub import AudioSegment
|
67 |
+
import os
|
68 |
+
import nltk
|
69 |
+
from nltk.tokenize import sent_tokenize
|
70 |
+
import sys
|
71 |
+
import torch
|
72 |
+
from TTS.api import TTS
|
73 |
+
from TTS.tts.configs.xtts_config import XttsConfig
|
74 |
+
from TTS.tts.models.xtts import Xtts
|
75 |
+
from tqdm import tqdm
|
76 |
+
import gradio as gr
|
77 |
+
from gradio import Progress
|
78 |
+
import urllib.request
|
79 |
+
import zipfile
|
80 |
+
|
81 |
+
|
82 |
+
default_target_voice_path = "default_voice.wav" # Ensure this is a valid path
|
83 |
+
default_language_code = "en"
|
84 |
+
|
85 |
+
|
86 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
87 |
+
print(f"Device selected is: {device}")
|
88 |
+
|
89 |
+
nltk.download('punkt') # Ensure necessary models are downloaded
|
90 |
+
|
91 |
+
# Global variables for queue management
|
92 |
+
queue = Queue()
|
93 |
+
queue_lock = Lock()
|
94 |
+
|
95 |
+
# Function to send an email with the download link
|
96 |
+
def send_email(to_address, download_link):
|
97 |
+
from_address = "your_email@example.com" # Replace with your email
|
98 |
+
subject = "Your Audiobook is Ready"
|
99 |
+
body = f"Your audiobook has been processed. You can download it from the following link: {download_link}"
|
100 |
+
|
101 |
+
msg = MIMEText(body)
|
102 |
+
msg['Subject'] = subject
|
103 |
+
msg['From'] = from_address
|
104 |
+
msg['To'] = to_address
|
105 |
+
|
106 |
+
try:
|
107 |
+
with smtplib.SMTP('smtp.example.com', 587) as server: # Replace with your SMTP server details
|
108 |
+
server.starttls()
|
109 |
+
server.login(from_address, "your_password") # Replace with your email password
|
110 |
+
server.sendmail(from_address, [to_address], msg.as_string())
|
111 |
+
print(f"Email sent to {to_address}")
|
112 |
+
except Exception as e:
|
113 |
+
print(f"Failed to send email: {e}")
|
114 |
+
|
115 |
+
# Function to download and extract the custom model
|
116 |
+
def download_and_extract_zip(url, extract_to='.'):
|
117 |
+
try:
|
118 |
+
os.makedirs(extract_to, exist_ok=True)
|
119 |
+
zip_path = os.path.join(extract_to, 'model.zip')
|
120 |
+
|
121 |
+
with tqdm(unit='B', unit_scale=True, miniters=1, desc="Downloading Model") as t:
|
122 |
+
def reporthook(blocknum, blocksize, totalsize):
|
123 |
+
t.total = totalsize
|
124 |
+
t.update(blocknum * blocksize - t.n)
|
125 |
+
urllib.request.urlretrieve(url, zip_path, reporthook=reporthook)
|
126 |
+
print(f"Downloaded zip file to {zip_path}")
|
127 |
+
|
128 |
+
with zipfile.ZipFile(zip_path, 'r') as zip_ref:
|
129 |
+
files = zip_ref.namelist()
|
130 |
+
with tqdm(total=len(files), unit="file", desc="Extracting Files") as t:
|
131 |
+
for file in files:
|
132 |
+
if not file.endswith('/'):
|
133 |
+
extracted_path = zip_ref.extract(file, extract_to)
|
134 |
+
base_file_path = os.path.join(extract_to, os.path.basename(file))
|
135 |
+
os.rename(extracted_path, base_file_path)
|
136 |
+
t.update(1)
|
137 |
+
|
138 |
+
os.remove(zip_path)
|
139 |
+
for root, dirs, files in os.walk(extract_to, topdown=False):
|
140 |
+
for name in dirs:
|
141 |
+
os.rmdir(os.path.join(root, name))
|
142 |
+
print(f"Extracted files to {extract_to}")
|
143 |
+
|
144 |
+
required_files = ['model.pth', 'config.json', 'vocab.json_']
|
145 |
+
missing_files = [file for file in required_files if not os.path.exists(os.path.join(extract_to, file))]
|
146 |
+
|
147 |
+
if not missing_files:
|
148 |
+
print("All required files (model.pth, config.json, vocab.json_) found.")
|
149 |
+
else:
|
150 |
+
print(f"Missing files: {', '.join(missing_files)}")
|
151 |
+
|
152 |
+
except Exception as e:
|
153 |
+
print(f"Failed to download or extract zip file: {e}")
|
154 |
+
|
155 |
+
# Function to check if a folder is empty
|
156 |
+
def is_folder_empty(folder_path):
|
157 |
+
if os.path.exists(folder_path) and os.path.isdir(folder_path):
|
158 |
+
return not os.listdir(folder_path)
|
159 |
+
else:
|
160 |
+
print(f"The path {folder_path} is not a valid folder.")
|
161 |
+
return None
|
162 |
+
|
163 |
+
# Function to remove a folder and its contents
|
164 |
+
def remove_folder_with_contents(folder_path):
|
165 |
+
try:
|
166 |
+
shutil.rmtree(folder_path)
|
167 |
+
print(f"Successfully removed {folder_path} and all of its contents.")
|
168 |
+
except Exception as e:
|
169 |
+
print(f"Error removing {folder_path}: {e}")
|
170 |
+
|
171 |
+
# Function to wipe the contents of a folder
|
172 |
+
def wipe_folder(folder_path):
|
173 |
+
if not os.path.exists(folder_path):
|
174 |
+
print(f"The folder {folder_path} does not exist.")
|
175 |
+
return
|
176 |
+
|
177 |
+
for item in os.listdir(folder_path):
|
178 |
+
item_path = os.path.join(folder_path, item)
|
179 |
+
if os.path.isfile(item_path):
|
180 |
+
os.remove(item_path)
|
181 |
+
print(f"Removed file: {item_path}")
|
182 |
+
elif os.path.isdir(item_path):
|
183 |
+
shutil.rmtree(item_path)
|
184 |
+
print(f"Removed directory and its contents: {item_path}")
|
185 |
+
|
186 |
+
print(f"All contents wiped from {folder_path}.")
|
187 |
+
|
188 |
+
# Function to create M4B from chapters
|
189 |
+
def create_m4b_from_chapters(input_dir, ebook_file, output_dir):
|
190 |
+
def sort_key(chapter_file):
|
191 |
+
numbers = re.findall(r'\d+', chapter_file)
|
192 |
+
return int(numbers[0]) if numbers else 0
|
193 |
+
|
194 |
+
def extract_metadata_and_cover(ebook_path):
|
195 |
+
try:
|
196 |
+
cover_path = ebook_path.rsplit('.', 1)[0] + '.jpg'
|
197 |
+
subprocess.run(['ebook-meta', ebook_path, '--get-cover', cover_path], check=True)
|
198 |
+
if os.path.exists(cover_path):
|
199 |
+
return cover_path
|
200 |
+
except Exception as e:
|
201 |
+
print(f"Error extracting eBook metadata or cover: {e}")
|
202 |
+
return None
|
203 |
+
|
204 |
+
def combine_wav_files(chapter_files, output_path):
|
205 |
+
combined_audio = AudioSegment.empty()
|
206 |
+
for chapter_file in chapter_files:
|
207 |
+
audio_segment = AudioSegment.from_wav(chapter_file)
|
208 |
+
combined_audio += audio_segment
|
209 |
+
combined_audio.export(output_path, format='wav')
|
210 |
+
print(f"Combined audio saved to {output_path}")
|
211 |
+
|
212 |
+
def generate_ffmpeg_metadata(chapter_files, metadata_file):
|
213 |
+
with open(metadata_file, 'w') as file:
|
214 |
+
file.write(';FFMETADATA1\n')
|
215 |
+
start_time = 0
|
216 |
+
for index, chapter_file in enumerate(chapter_files):
|
217 |
+
duration_ms = len(AudioSegment.from_wav(chapter_file))
|
218 |
+
file.write(f'[CHAPTER]\nTIMEBASE=1/1000\nSTART={start_time}\n')
|
219 |
+
file.write(f'END={start_time + duration_ms}\ntitle=Chapter {index + 1}\n')
|
220 |
+
start_time += duration_ms
|
221 |
+
|
222 |
+
def create_m4b(combined_wav, metadata_file, cover_image, output_m4b):
|
223 |
+
os.makedirs(os.path.dirname(output_m4b), exist_ok=True)
|
224 |
+
|
225 |
+
ffmpeg_cmd = ['ffmpeg', '-i', combined_wav, '-i', metadata_file]
|
226 |
+
if cover_image:
|
227 |
+
ffmpeg_cmd += ['-i', cover_image, '-map', '0:a', '-map', '2:v']
|
228 |
+
else:
|
229 |
+
ffmpeg_cmd += ['-map', '0:a']
|
230 |
+
|
231 |
+
ffmpeg_cmd += ['-map_metadata', '1', '-c:a', 'aac', '-b:a', '192k']
|
232 |
+
if cover_image:
|
233 |
+
ffmpeg_cmd += ['-c:v', 'png', '-disposition:v', 'attached_pic']
|
234 |
+
ffmpeg_cmd += [output_m4b]
|
235 |
+
|
236 |
+
subprocess.run(ffmpeg_cmd, check=True)
|
237 |
+
|
238 |
+
chapter_files = sorted([os.path.join(input_dir, f) for f in os.listdir(input_dir) if f.endswith('.wav')], key=sort_key)
|
239 |
+
temp_dir = tempfile.gettempdir()
|
240 |
+
temp_combined_wav = os.path.join(temp_dir, 'combined.wav')
|
241 |
+
metadata_file = os.path.join(temp_dir, 'metadata.txt')
|
242 |
+
cover_image = extract_metadata_and_cover(ebook_file)
|
243 |
+
output_m4b = os.path.join(output_dir, os.path.splitext(os.path.basename(ebook_file))[0] + '.m4b')
|
244 |
+
|
245 |
+
combine_wav_files(chapter_files, temp_combined_wav)
|
246 |
+
generate_ffmpeg_metadata(chapter_files, metadata_file)
|
247 |
+
create_m4b(temp_combined_wav, metadata_file, cover_image, output_m4b)
|
248 |
+
|
249 |
+
if os.path.exists(temp_combined_wav):
|
250 |
+
os.remove(temp_combined_wav)
|
251 |
+
if os.path.exists(metadata_file):
|
252 |
+
os.remove(metadata_file)
|
253 |
+
if cover_image and os.path.exists(cover_image):
|
254 |
+
os.remove(cover_image)
|
255 |
+
|
256 |
+
# Function to create chapter-labeled book
|
257 |
+
def create_chapter_labeled_book(ebook_file_path):
|
258 |
+
def ensure_directory(directory_path):
|
259 |
+
if not os.path.exists(directory_path):
|
260 |
+
os.makedirs(directory_path)
|
261 |
+
print(f"Created directory: {directory_path}")
|
262 |
+
|
263 |
+
ensure_directory(os.path.join(".", 'Working_files', 'Book'))
|
264 |
+
|
265 |
+
def convert_to_epub(input_path, output_path):
|
266 |
+
try:
|
267 |
+
subprocess.run(['ebook-convert', input_path, output_path], check=True)
|
268 |
+
except subprocess.CalledProcessError as e:
|
269 |
+
print(f"An error occurred while converting the eBook: {e}")
|
270 |
+
return False
|
271 |
+
return True
|
272 |
+
|
273 |
+
def save_chapters_as_text(epub_path):
|
274 |
+
directory = os.path.join(".", "Working_files", "temp_ebook")
|
275 |
+
ensure_directory(directory)
|
276 |
+
|
277 |
+
book = epub.read_epub(epub_path)
|
278 |
+
|
279 |
+
previous_chapter_text = ''
|
280 |
+
previous_filename = ''
|
281 |
+
chapter_counter = 0
|
282 |
+
|
283 |
+
for item in book.get_items():
|
284 |
+
if item.get_type() == ebooklib.ITEM_DOCUMENT:
|
285 |
+
soup = BeautifulSoup(item.get_content(), 'html.parser')
|
286 |
+
text = soup.get_text()
|
287 |
+
|
288 |
+
if text.strip():
|
289 |
+
if len(text) < 2300 and previous_filename:
|
290 |
+
with open(previous_filename, 'a', encoding='utf-8') as file:
|
291 |
+
file.write('\n' + text)
|
292 |
+
else:
|
293 |
+
previous_filename = os.path.join(directory, f"chapter_{chapter_counter}.txt")
|
294 |
+
chapter_counter += 1
|
295 |
+
with open(previous_filename, 'w', encoding='utf-8') as file:
|
296 |
+
file.write(text)
|
297 |
+
print(f"Saved chapter: {previous_filename}")
|
298 |
+
|
299 |
+
input_ebook = ebook_file_path
|
300 |
+
output_epub = os.path.join(".", "Working_files", "temp.epub")
|
301 |
+
|
302 |
+
if os.path.exists(output_epub):
|
303 |
+
os.remove(output_epub)
|
304 |
+
print(f"File {output_epub} has been removed.")
|
305 |
+
else:
|
306 |
+
print(f"The file {output_epub} does not exist.")
|
307 |
+
|
308 |
+
if convert_to_epub(input_ebook, output_epub):
|
309 |
+
save_chapters_as_text(output_epub)
|
310 |
+
|
311 |
+
nltk.download('punkt')
|
312 |
+
|
313 |
+
def process_chapter_files(folder_path, output_csv):
|
314 |
+
with open(output_csv, 'w', newline='', encoding='utf-8') as csvfile:
|
315 |
+
writer = csv.writer(csvfile)
|
316 |
+
writer.writerow(['Text', 'Start Location', 'End Location', 'Is Quote', 'Speaker', 'Chapter'])
|
317 |
+
|
318 |
+
chapter_files = sorted(os.listdir(folder_path), key=lambda x: int(x.split('_')[1].split('.')[0]))
|
319 |
+
for filename in chapter_files:
|
320 |
+
if filename.startswith('chapter_') and filename.endswith('.txt'):
|
321 |
+
chapter_number = int(filename.split('_')[1].split('.')[0])
|
322 |
+
file_path = os.path.join(folder_path, filename)
|
323 |
+
|
324 |
+
try:
|
325 |
+
with open(file_path, 'r', encoding='utf-8') as file:
|
326 |
+
text = file.read()
|
327 |
+
if text:
|
328 |
+
text = "NEWCHAPTERABC" + text
|
329 |
+
sentences = nltk.tokenize.sent_tokenize(text)
|
330 |
+
for sentence in sentences:
|
331 |
+
start_location = text.find(sentence)
|
332 |
+
end_location = start_location + len(sentence)
|
333 |
+
writer.writerow([sentence, start_location, end_location, 'True', 'Narrator', chapter_number])
|
334 |
+
except Exception as e:
|
335 |
+
print(f"Error processing file {filename}: {e}")
|
336 |
+
|
337 |
+
folder_path = os.path.join(".", "Working_files", "temp_ebook")
|
338 |
+
output_csv = os.path.join(".", "Working_files", "Book", "Other_book.csv")
|
339 |
+
|
340 |
+
process_chapter_files(folder_path, output_csv)
|
341 |
+
|
342 |
+
def sort_key(filename):
|
343 |
+
match = re.search(r'chapter_(\d+)\.txt', filename)
|
344 |
+
return int(match.group(1)) if match else 0
|
345 |
+
|
346 |
+
def combine_chapters(input_folder, output_file):
|
347 |
+
os.makedirs(os.path.dirname(output_file), exist_ok=True)
|
348 |
+
|
349 |
+
files = [f for f in os.listdir(input_folder) if f.endswith('.txt')]
|
350 |
+
sorted_files = sorted(files, key=sort_key)
|
351 |
+
|
352 |
+
with open(output_file, 'w', encoding='utf-8') as outfile:
|
353 |
+
for i, filename in enumerate(sorted_files):
|
354 |
+
with open(os.path.join(input_folder, filename), 'r', encoding='utf-8') as infile:
|
355 |
+
outfile.write(infile.read())
|
356 |
+
if i < len(sorted_files) - 1:
|
357 |
+
outfile.write("\nNEWCHAPTERABC\n")
|
358 |
+
|
359 |
+
input_folder = os.path.join(".", 'Working_files', 'temp_ebook')
|
360 |
+
output_file = os.path.join(".", 'Working_files', 'Book', 'Chapter_Book.txt')
|
361 |
+
|
362 |
+
combine_chapters(input_folder, output_file)
|
363 |
+
ensure_directory(os.path.join(".", "Working_files", "Book"))
|
364 |
+
|
365 |
+
# Function to combine WAV files
|
366 |
+
def combine_wav_files(input_directory, output_directory, file_name):
|
367 |
+
os.makedirs(output_directory, exist_ok=True)
|
368 |
+
output_file_path = os.path.join(output_directory, file_name)
|
369 |
+
combined_audio = AudioSegment.empty()
|
370 |
+
input_file_paths = sorted(
|
371 |
+
[os.path.join(input_directory, f) for f in os.listdir(input_directory) if f.endswith(".wav")],
|
372 |
+
key=lambda f: int(''.join(filter(str.isdigit, f)))
|
373 |
+
)
|
374 |
+
for input_file_path in input_file_paths:
|
375 |
+
audio_segment = AudioSegment.from_wav(input_file_path)
|
376 |
+
combined_audio += audio_segment
|
377 |
+
combined_audio.export(output_file_path, format='wav')
|
378 |
+
print(f"Combined audio saved to {output_file_path}")
|
379 |
+
|
380 |
+
# Function to split long sentences
|
381 |
+
def split_long_sentence(sentence, max_length=249, max_pauses=10):
|
382 |
+
parts = []
|
383 |
+
while len(sentence) > max_length or sentence.count(',') + sentence.count(';') + sentence.count('.') > max_pauses:
|
384 |
+
possible_splits = [i for i, char in enumerate(sentence) if char in ',;.' and i < max_length]
|
385 |
+
if possible_splits:
|
386 |
+
split_at = possible_splits[-1] + 1
|
387 |
+
else:
|
388 |
+
split_at = max_length
|
389 |
+
parts.append(sentence[:split_at].strip())
|
390 |
+
sentence = sentence[split_at:].strip()
|
391 |
+
parts.append(sentence)
|
392 |
+
return parts
|
393 |
+
|
394 |
+
# Function to convert chapters to audio using custom model
|
395 |
+
def convert_chapters_to_audio_custom_model(chapters_dir, output_audio_dir, target_voice_path=None, language=None, custom_model=None):
|
396 |
+
if target_voice_path is None:
|
397 |
+
target_voice_path = default_target_voice_path
|
398 |
+
if custom_model:
|
399 |
+
print("Loading custom model...")
|
400 |
+
config = XttsConfig()
|
401 |
+
config.load_json(custom_model['config'])
|
402 |
+
model = Xtts.init_from_config(config)
|
403 |
+
model.load_checkpoint(config, checkpoint_path=custom_model['model'], vocab_path=custom_model['vocab'], use_deepspeed=False)
|
404 |
+
model.device
|
405 |
+
print("Computing speaker latents...")
|
406 |
+
gpt_cond_latent, speaker_embedding = model.get_conditioning_latents(audio_path=[target_voice_path])
|
407 |
+
else:
|
408 |
+
selected_tts_model = "tts_models/multilingual/multi-dataset/xtts_v2"
|
409 |
+
tts = TTS(selected_tts_model, progress_bar=False).to(device)
|
410 |
+
|
411 |
+
if not os.path.exists(output_audio_dir):
|
412 |
+
os.makedirs(output_audio_dir)
|
413 |
+
|
414 |
+
for chapter_file in sorted(os.listdir(chapters_dir)):
|
415 |
+
if chapter_file.endswith('.txt'):
|
416 |
+
match = re.search(r"chapter_(\d+).txt", chapter_file)
|
417 |
+
if match:
|
418 |
+
chapter_num = int(match.group(1))
|
419 |
+
else:
|
420 |
+
print(f"Skipping file {chapter_file} as it does not match the expected format.")
|
421 |
+
continue
|
422 |
+
|
423 |
+
chapter_path = os.path.join(chapters_dir, chapter_file)
|
424 |
+
output_file_name = f"audio_chapter_{chapter_num}.wav"
|
425 |
+
output_file_path = os.path.join(output_audio_dir, output_file_name)
|
426 |
+
temp_audio_directory = os.path.join(".", "Working_files", "temp")
|
427 |
+
os.makedirs(temp_audio_directory, exist_ok=True)
|
428 |
+
temp_count = 0
|
429 |
+
|
430 |
+
with open(chapter_path, 'r', encoding='utf-8') as file:
|
431 |
+
chapter_text = file.read()
|
432 |
+
sentences = sent_tokenize(chapter_text, language='italian' if language == 'it' else 'english')
|
433 |
+
for sentence in tqdm(sentences, desc=f"Chapter {chapter_num}"):
|
434 |
+
fragments = split_long_sentence(sentence, max_length=249 if language == "en" else 213, max_pauses=10)
|
435 |
+
for fragment in fragments:
|
436 |
+
if fragment != "":
|
437 |
+
print(f"Generating fragment: {fragment}...")
|
438 |
+
fragment_file_path = os.path.join(temp_audio_directory, f"{temp_count}.wav")
|
439 |
+
if custom_model:
|
440 |
+
out = model.inference(fragment, language, gpt_cond_latent, speaker_embedding, temperature=0.7)
|
441 |
+
torchaudio.save(fragment_file_path, torch.tensor(out["wav"]).unsqueeze(0), 24000)
|
442 |
+
else:
|
443 |
+
speaker_wav_path = target_voice_path if target_voice_path else default_target_voice_path
|
444 |
+
language_code = language if language else default_language_code
|
445 |
+
tts.tts_to_file(text=fragment, file_path=fragment_file_path, speaker_wav=speaker_wav_path, language=language_code)
|
446 |
+
temp_count += 1
|
447 |
+
|
448 |
+
combine_wav_files(temp_audio_directory, output_audio_dir, output_file_name)
|
449 |
+
wipe_folder(temp_audio_directory)
|
450 |
+
print(f"Converted chapter {chapter_num} to audio.")
|
451 |
+
|
452 |
+
# Function to convert chapters to audio using standard model
|
453 |
+
def convert_chapters_to_audio_standard_model(chapters_dir, output_audio_dir, target_voice_path=None, language=None):
|
454 |
+
selected_tts_model = "tts_models/multilingual/multi-dataset/xtts_v2"
|
455 |
+
tts = TTS(selected_tts_model, progress_bar=False).to(device)
|
456 |
+
|
457 |
+
if not os.path.exists(output_audio_dir):
|
458 |
+
os.makedirs(output_audio_dir)
|
459 |
+
|
460 |
+
for chapter_file in sorted(os.listdir(chapters_dir)):
|
461 |
+
if chapter_file.endswith('.txt'):
|
462 |
+
match = re.search(r"chapter_(\d+).txt", chapter_file)
|
463 |
+
if match:
|
464 |
+
chapter_num = int(match.group(1))
|
465 |
+
else:
|
466 |
+
print(f"Skipping file {chapter_file} as it does not match the expected format.")
|
467 |
+
continue
|
468 |
+
|
469 |
+
chapter_path = os.path.join(chapters_dir, chapter_file)
|
470 |
+
output_file_name = f"audio_chapter_{chapter_num}.wav"
|
471 |
+
output_file_path = os.path.join(output_audio_dir, output_file_name)
|
472 |
+
temp_audio_directory = os.path.join(".", "Working_files", "temp")
|
473 |
+
os.makedirs(temp_audio_directory, exist_ok=True)
|
474 |
+
temp_count = 0
|
475 |
+
|
476 |
+
with open(chapter_path, 'r', encoding='utf-8') as file:
|
477 |
+
chapter_text = file.read()
|
478 |
+
sentences = sent_tokenize(chapter_text, language='italian' if language == 'it' else 'english')
|
479 |
+
for sentence in tqdm(sentences, desc=f"Chapter {chapter_num}"):
|
480 |
+
fragments = split_long_sentence(sentence, max_length=249 if language == "en" else 213, max_pauses=10)
|
481 |
+
for fragment in fragments:
|
482 |
+
if fragment != "":
|
483 |
+
print(f"Generating fragment: {fragment}...")
|
484 |
+
fragment_file_path = os.path.join(temp_audio_directory, f"{temp_count}.wav")
|
485 |
+
speaker_wav_path = target_voice_path if target_voice_path else default_target_voice_path
|
486 |
+
language_code = language if language else default_language_code
|
487 |
+
tts.tts_to_file(text=fragment, file_path=fragment_file_path, speaker_wav=speaker_wav_path, language=language_code)
|
488 |
+
temp_count += 1
|
489 |
+
|
490 |
+
combine_wav_files(temp_audio_directory, output_audio_dir, output_file_name)
|
491 |
+
wipe_folder(temp_audio_directory)
|
492 |
+
print(f"Converted chapter {chapter_num} to audio.")
|
493 |
+
|
494 |
+
# Function to handle the processing of an eBook to an audiobook
|
495 |
+
def process_request(ebook_file, target_voice, language, email, use_custom_model, custom_model):
|
496 |
+
working_files = os.path.join(".", "Working_files", "temp_ebook")
|
497 |
+
full_folder_working_files = os.path.join(".", "Working_files")
|
498 |
+
chapters_directory = os.path.join(".", "Working_files", "temp_ebook")
|
499 |
+
output_audio_directory = os.path.join(".", 'Chapter_wav_files')
|
500 |
+
remove_folder_with_contents(full_folder_working_files)
|
501 |
+
remove_folder_with_contents(output_audio_directory)
|
502 |
+
|
503 |
+
create_chapter_labeled_book(ebook_file.name)
|
504 |
+
audiobook_output_path = os.path.join(".", "Audiobooks")
|
505 |
+
|
506 |
+
if use_custom_model:
|
507 |
+
convert_chapters_to_audio_custom_model(chapters_directory, output_audio_directory, target_voice, language, custom_model)
|
508 |
+
else:
|
509 |
+
convert_chapters_to_audio_standard_model(chapters_directory, output_audio_directory, target_voice, language)
|
510 |
+
|
511 |
+
create_m4b_from_chapters(output_audio_directory, ebook_file.name, audiobook_output_path)
|
512 |
+
|
513 |
+
m4b_filepath = os.path.join(audiobook_output_path, os.path.splitext(os.path.basename(ebook_file.name))[0] + '.m4b')
|
514 |
+
|
515 |
+
# Upload the final audiobook to file.io
|
516 |
+
with open(m4b_filepath, 'rb') as f:
|
517 |
+
response = requests.post('https://file.io', files={'file': f})
|
518 |
+
download_link = response.json().get('link', '')
|
519 |
+
|
520 |
+
# Send the download link to the user's email
|
521 |
+
if email and download_link:
|
522 |
+
send_email(email, download_link)
|
523 |
+
|
524 |
+
return download_link
|
525 |
+
|
526 |
+
# Function to manage the queue and process each request sequentially
|
527 |
+
def handle_queue():
|
528 |
+
while True:
|
529 |
+
ebook_file, target_voice, language, email, use_custom_model, custom_model = queue.get()
|
530 |
+
process_request(ebook_file, target_voice, language, email, use_custom_model, custom_model)
|
531 |
+
queue.task_done()
|
532 |
+
|
533 |
+
# Start the queue handler thread
|
534 |
+
thread = Thread(target=handle_queue, daemon=True)
|
535 |
+
thread.start()
|
536 |
+
|
537 |
+
# Gradio function to add a request to the queue
|
538 |
+
def enqueue_request(ebook_file, target_voice_file, language, email, use_custom_model, custom_model_file, custom_config_file, custom_vocab_file, custom_model_url=None):
|
539 |
+
target_voice = target_voice_file.name if target_voice_file else None
|
540 |
+
custom_model = None
|
541 |
+
|
542 |
+
if use_custom_model and custom_model_file and custom_config_file and custom_vocab_file:
|
543 |
+
custom_model = {
|
544 |
+
'model': custom_model_file.name,
|
545 |
+
'config': custom_config_file.name,
|
546 |
+
'vocab': custom_vocab_file.name
|
547 |
+
}
|
548 |
+
if use_custom_model and custom_model_url:
|
549 |
+
download_dir = os.path.join(".", "Working_files", "custom_model")
|
550 |
+
download_and_extract_zip(custom_model_url, download_dir)
|
551 |
+
custom_model = {
|
552 |
+
'model': os.path.join(download_dir, 'model.pth'),
|
553 |
+
'config': os.path.join(download_dir, 'config.json'),
|
554 |
+
'vocab': os.path.join(download_dir, 'vocab.json_')
|
555 |
+
}
|
556 |
+
|
557 |
+
# Add request to the queue
|
558 |
+
queue_lock.acquire()
|
559 |
+
queue.put((ebook_file, target_voice, language, email, use_custom_model, custom_model))
|
560 |
+
position = queue.qsize()
|
561 |
+
queue_lock.release()
|
562 |
+
return f"Your request has been added to the queue. You are number {position} in line."
|
563 |
+
|
564 |
+
# Gradio UI setup
|
565 |
+
language_options = [
|
566 |
+
"en", "es", "fr", "de", "it", "pt", "pl", "tr", "ru", "nl", "cs", "ar", "zh-cn", "ja", "hu", "ko"
|
567 |
+
]
|
568 |
+
|
569 |
+
theme = gr.themes.Soft(
|
570 |
+
primary_hue="blue",
|
571 |
+
secondary_hue="blue",
|
572 |
+
neutral_hue="blue",
|
573 |
+
text_size=gr.themes.sizes.text_md,
|
574 |
+
)
|
575 |
+
|
576 |
+
with gr.Blocks(theme=theme) as demo:
|
577 |
+
gr.Markdown(
|
578 |
+
"""
|
579 |
+
# eBook to Audiobook Converter
|
580 |
+
|
581 |
+
Transform your eBooks into immersive audiobooks with optional custom TTS models.
|
582 |
+
"""
|
583 |
+
)
|
584 |
+
|
585 |
+
with gr.Row():
|
586 |
+
with gr.Column(scale=3):
|
587 |
+
ebook_file = gr.File(label="eBook File")
|
588 |
+
target_voice_file = gr.File(label="Target Voice File (Optional)")
|
589 |
+
language = gr.Dropdown(label="Language", choices=language_options, value="en")
|
590 |
+
email = gr.Textbox(label="Email Address")
|
591 |
+
|
592 |
+
with gr.Column(scale=3):
|
593 |
+
use_custom_model = gr.Checkbox(label="Use Custom Model")
|
594 |
+
custom_model_file = gr.File(label="Custom Model File (Optional)", visible=False)
|
595 |
+
custom_config_file = gr.File(label="Custom Config File (Optional)", visible=False)
|
596 |
+
custom_vocab_file = gr.File(label="Custom Vocab File (Optional)", visible=False)
|
597 |
+
custom_model_url = gr.Textbox(label="Custom Model Zip URL (Optional)", visible=False)
|
598 |
+
|
599 |
+
convert_btn = gr.Button("Convert to Audiobook", variant="primary")
|
600 |
+
queue_status = gr.Textbox(label="Queue Status")
|
601 |
+
|
602 |
+
convert_btn.click(
|
603 |
+
enqueue_request,
|
604 |
+
inputs=[ebook_file, target_voice_file, language, email, use_custom_model, custom_model_file, custom_config_file, custom_vocab_file, custom_model_url],
|
605 |
+
outputs=[queue_status]
|
606 |
+
)
|
607 |
+
|
608 |
+
use_custom_model.change(
|
609 |
+
lambda x: [gr.update(visible=x)] * 4,
|
610 |
+
inputs=[use_custom_model],
|
611 |
+
outputs=[custom_model_file, custom_config_file, custom_vocab_file, custom_model_url]
|
612 |
+
)
|
613 |
+
|
614 |
+
demo.launch(share=True)
|
legacy/v1.0/legacy/install.bat
ADDED
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
@echo off
|
2 |
+
:: Check for administrative privileges
|
3 |
+
net session >nul 2>&1
|
4 |
+
if %errorLevel% neq 0 (
|
5 |
+
echo This script requires administrator privileges.
|
6 |
+
echo Switching to administrator...
|
7 |
+
|
8 |
+
powershell -Command "Start-Process cmd -ArgumentList '/c', '%~dpnx0' -Verb runAs"
|
9 |
+
exit /b
|
10 |
+
)
|
11 |
+
|
12 |
+
:: If already elevated, continue the script
|
13 |
+
echo Running with administrator privileges...
|
14 |
+
|
15 |
+
:: Run the PowerShell script in the same directory as this batch file
|
16 |
+
powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0install.ps1"
|
17 |
+
|
18 |
+
pause
|
legacy/v1.0/legacy/install.ps1
ADDED
@@ -0,0 +1,255 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Function to check if the script is running as Administrator
|
2 |
+
function Test-IsAdmin {
|
3 |
+
$currentUser = New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())
|
4 |
+
return $currentUser.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
|
5 |
+
}
|
6 |
+
|
7 |
+
# If the script is not running as Administrator, restart it with elevated privileges
|
8 |
+
if (-not (Test-IsAdmin)) {
|
9 |
+
Write-Host "This script requires administrative privileges. Restarting as Administrator..." -ForegroundColor Yellow
|
10 |
+
Start-Process powershell.exe -ArgumentList "-NoProfile", "-ExecutionPolicy RemoteSigned", "-File", "`"$PSCommandPath`" $Params" -Verb RunAs
|
11 |
+
exit
|
12 |
+
}
|
13 |
+
|
14 |
+
################# Main script starts here with admin privileges #################
|
15 |
+
|
16 |
+
# Function to check if Conda is installed
|
17 |
+
function Check-CondaInstalled {
|
18 |
+
Write-Host "Checking if Conda is installed..."
|
19 |
+
$condaPath = (Get-Command conda -ErrorAction SilentlyContinue).Source
|
20 |
+
if ($condaPath) {
|
21 |
+
Write-Host "Conda is already installed at: $condaPath"
|
22 |
+
return $true
|
23 |
+
} else {
|
24 |
+
Write-Host "Conda is not installed."
|
25 |
+
return $false
|
26 |
+
}
|
27 |
+
}
|
28 |
+
|
29 |
+
function Check-ProgramsInstalled {
|
30 |
+
param (
|
31 |
+
[string[]]$Programs
|
32 |
+
)
|
33 |
+
|
34 |
+
$programsMissing = @()
|
35 |
+
|
36 |
+
if (-not (Get-Command choco -ErrorAction SilentlyContinue)) {
|
37 |
+
Write-Host "Chocolatey is not installed. Installing Chocolatey..."
|
38 |
+
Set-ExecutionPolicy Bypass -Scope Process -Force
|
39 |
+
[System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072
|
40 |
+
iex ((New-Object System.Net.WebClient).DownloadString('https://community.chocolatey.org/install.ps1'))
|
41 |
+
|
42 |
+
if (-not (Get-Command choco -ErrorAction SilentlyContinue)) {
|
43 |
+
return $true
|
44 |
+
} else {
|
45 |
+
Write-Host "Chocolatey installed successfully."
|
46 |
+
}
|
47 |
+
}
|
48 |
+
|
49 |
+
foreach ($program in $Programs) {
|
50 |
+
if (Get-Command $program -ErrorAction SilentlyContinue) {
|
51 |
+
Write-Host "$program is installed."
|
52 |
+
} else {
|
53 |
+
$programsMissing += $program
|
54 |
+
}
|
55 |
+
}
|
56 |
+
|
57 |
+
$missingCount = $programsMissing.Count
|
58 |
+
|
59 |
+
if ($missingCount -eq 0) {
|
60 |
+
return $true
|
61 |
+
} else {
|
62 |
+
$installedCount = 0
|
63 |
+
foreach ($program in $programsMissing) {
|
64 |
+
if ($program -eq "ffmpeg") {
|
65 |
+
Write-Host "Installing ffmpeg..."
|
66 |
+
choco install ffmpeg -y
|
67 |
+
|
68 |
+
if (Get-Command ffmpeg -ErrorAction SilentlyContinue) {
|
69 |
+
Write-Host "ffmpeg installed successfully!"
|
70 |
+
$installedCount += 1
|
71 |
+
}
|
72 |
+
} elseif ($program -eq "calibre") {
|
73 |
+
# Avoid conflict with calibre built-in lxml
|
74 |
+
pip uninstall lxml -y
|
75 |
+
|
76 |
+
# Install Calibre using Chocolatey
|
77 |
+
Write-Host "Installing Calibre..."
|
78 |
+
choco install calibre -y
|
79 |
+
|
80 |
+
# Verify Calibre installation
|
81 |
+
if (Get-Command calibre -ErrorAction SilentlyContinue) {
|
82 |
+
Write-Host "Calibre installed successfully!"
|
83 |
+
$installedCount += 1
|
84 |
+
}
|
85 |
+
}
|
86 |
+
}
|
87 |
+
}
|
88 |
+
if ($installedCount -eq $countMissing) {
|
89 |
+
return $false
|
90 |
+
}
|
91 |
+
return $true
|
92 |
+
}
|
93 |
+
|
94 |
+
# Function to check if Docker is installed and running
|
95 |
+
function Check-Docker {
|
96 |
+
Write-Host "Checking if Docker is installed..."
|
97 |
+
$dockerPath = (Get-Command docker -ErrorAction SilentlyContinue).Source
|
98 |
+
if ($dockerPath) {
|
99 |
+
Write-Host "Docker is installed at: $dockerPath"
|
100 |
+
# Check if Docker service is running
|
101 |
+
$dockerStatus = (Get-Service -Name com.docker.service -ErrorAction SilentlyContinue).Status
|
102 |
+
if ($dockerStatus -eq 'Running') {
|
103 |
+
Write-Host "Docker service is running."
|
104 |
+
return $true
|
105 |
+
} else {
|
106 |
+
Write-Host "Docker service is installed but not running. Attempting to start Docker service..."
|
107 |
+
Start-Service -Name "com.docker.service" -ErrorAction SilentlyContinue
|
108 |
+
|
109 |
+
# Wait for Docker service to start
|
110 |
+
while ((Get-Service -Name "com.docker.service").Status -ne 'Running') {
|
111 |
+
Write-Host "Waiting for Docker service to start..."
|
112 |
+
Start-Sleep -Seconds 5
|
113 |
+
}
|
114 |
+
Write-Host "Docker service is now running."
|
115 |
+
return $true
|
116 |
+
}
|
117 |
+
} else {
|
118 |
+
Write-Host "Docker is not installed."
|
119 |
+
return $false
|
120 |
+
}
|
121 |
+
}
|
122 |
+
|
123 |
+
######### Miniconda installation
|
124 |
+
|
125 |
+
$minicondaUrl = "https://repo.anaconda.com/miniconda/Miniconda3-latest-Windows-x86_64.exe"
|
126 |
+
$installerPath = "$env:TEMP\Miniconda3-latest-Windows-x86_64.exe"
|
127 |
+
|
128 |
+
if (-not (Check-CondaInstalled)) {
|
129 |
+
# Check if the Miniconda installer already exists
|
130 |
+
if (-not (Test-Path $installerPath)) {
|
131 |
+
Write-Host "Downloading Miniconda installer..."
|
132 |
+
Invoke-WebRequest -Uri $minicondaUrl -OutFile $installerPath
|
133 |
+
} else {
|
134 |
+
Write-Host "Miniconda installer already exists at $installerPath. Skipping download."
|
135 |
+
}
|
136 |
+
|
137 |
+
# Set the installation path for Miniconda
|
138 |
+
$installPath = "C:\Miniconda3"
|
139 |
+
|
140 |
+
Write-Host "Installing Miniconda..."
|
141 |
+
Start-Process -FilePath $installerPath -ArgumentList "/InstallationType=JustMe", "/RegisterPython=0", "/AddToPath=1", "/S", "/D=$installPath" -NoNewWindow -Wait
|
142 |
+
|
143 |
+
Write-Host "Verifying Miniconda installation..."
|
144 |
+
& "$installPath\Scripts\conda.exe" --version
|
145 |
+
Write-Host "Miniconda installation complete."
|
146 |
+
} else {
|
147 |
+
Write-Host "Skipping Miniconda installation."
|
148 |
+
}
|
149 |
+
|
150 |
+
######### Docker installation
|
151 |
+
|
152 |
+
$dockerMsiUrl = "https://desktop.docker.com/win/main/amd64/Docker%20Desktop%20Installer.exe"
|
153 |
+
$dockerInstallerPath = "$env:TEMP\DockerInstaller.exe"
|
154 |
+
|
155 |
+
$dockerUtilsNeeded = Check-ProgramsInstalled -Programs @("ffmpeg", "calibre")
|
156 |
+
|
157 |
+
if ($dockerUtilsNeeded) {
|
158 |
+
if (-not (Check-Docker)) {
|
159 |
+
# Verify the installer file or re-download if corrupted or missing
|
160 |
+
if (-not (Test-Path $dockerInstallerPath)) {
|
161 |
+
Write-Host "Downloading Docker installer for Windows..."
|
162 |
+
Invoke-WebRequest -Uri $dockerMsiUrl -OutFile $dockerInstallerPath
|
163 |
+
}
|
164 |
+
|
165 |
+
# Launch the Docker installer
|
166 |
+
Write-Host "Launching Docker installer..."
|
167 |
+
Start-Process -FilePath $dockerInstallerPath
|
168 |
+
Write-Host "Please complete the Docker installation manually."
|
169 |
+
pause
|
170 |
+
|
171 |
+
# Ensure Docker service is running after installation
|
172 |
+
Write-Host "Ensuring Docker service is running..."
|
173 |
+
Start-Service -Name "com.docker.service" -ErrorAction SilentlyContinue
|
174 |
+
|
175 |
+
# Wait for Docker service to start
|
176 |
+
while ((Get-Service -Name "com.docker.service").Status -ne 'Running') {
|
177 |
+
Write-Host "Waiting for Docker service to start..."
|
178 |
+
Start-Sleep -Seconds 5
|
179 |
+
}
|
180 |
+
|
181 |
+
Write-Host "Docker service is now running."
|
182 |
+
}
|
183 |
+
}
|
184 |
+
|
185 |
+
######### Install ebook2audiobook
|
186 |
+
|
187 |
+
if (Check-CondaInstalled) {
|
188 |
+
|
189 |
+
Write-Host "Installing ebook2audiobook..." -ForegroundColor Yellow
|
190 |
+
|
191 |
+
# Set the working directory to the script's directory
|
192 |
+
$scriptDir = $PSScriptRoot
|
193 |
+
Set-Location -Path $scriptDir
|
194 |
+
|
195 |
+
# Create new Conda environment with Python 3.11 in the script directory, showing progress
|
196 |
+
Write-Host "Creating Conda environment with Python 3.11 in $scriptDir..."
|
197 |
+
& conda create --prefix "$scriptDir\python_env" python=3.11 -y -v
|
198 |
+
|
199 |
+
# Ensure the correct Python environment is active
|
200 |
+
Write-Host "Checking Python version in Conda environment..."
|
201 |
+
|
202 |
+
# Get python.exe version from python_env
|
203 |
+
$pythonEnvVersion = & "$scriptDir\python_env\python.exe" --version
|
204 |
+
|
205 |
+
# Get the Conda-managed Python version using conda run
|
206 |
+
$pythonVersion = & conda run --prefix "$scriptDir\python_env" python --version
|
207 |
+
|
208 |
+
if ($pythonVersion.Trim() -eq $pythonEnvVersion.Trim()) {
|
209 |
+
Write-Host "Python versions match, proceeding with installation..."
|
210 |
+
|
211 |
+
if ($dockerUtilsNeeded) {
|
212 |
+
# Build Docker image for utils
|
213 |
+
Write-Host "Building Docker image for utils..."
|
214 |
+
& conda run --prefix "$scriptDir\python_env" docker build -f DockerfileUtils -t utils .
|
215 |
+
}
|
216 |
+
|
217 |
+
# Install required Python packages with pip, showing progress
|
218 |
+
Write-Host "Installing required Python packages..."
|
219 |
+
& conda run --prefix "$scriptDir\python_env" python.exe -m pip install --upgrade pip --progress-bar on -v
|
220 |
+
& conda run --prefix "$scriptDir\python_env" pip install pydub nltk beautifulsoup4 ebooklib translate coqui-tts tqdm mecab mecab-python3 unidic gradio>=4.44.0 docker --progress-bar on -v
|
221 |
+
|
222 |
+
# Download unidic language model for MeCab with progress
|
223 |
+
Write-Host "Downloading unidic language model for MeCab..."
|
224 |
+
& conda run --prefix "$scriptDir\python_env" python.exe -m unidic download
|
225 |
+
|
226 |
+
# Download spacy NLP model with progress
|
227 |
+
Write-Host "Downloading spaCy language model..."
|
228 |
+
& conda run --prefix "$scriptDir\python_env" python.exe -m spacy download en_core_web_sm
|
229 |
+
|
230 |
+
# Install ebook2audiobook
|
231 |
+
Write-Host "Installing ebook2audiobook..."
|
232 |
+
& conda run --prefix "$scriptDir\python_env" pip install -e .
|
233 |
+
|
234 |
+
# Delete Docker and Miniconda installers if both are installed and running
|
235 |
+
if ((Check-CondaInstalled) -and (Check-Docker)) {
|
236 |
+
Write-Host "Both Conda and Docker are installed and running. Deleting installer files..."
|
237 |
+
Remove-Item -Path $installerPath -Force -ErrorAction SilentlyContinue
|
238 |
+
Remove-Item -Path $dockerInstallerPath -Force -ErrorAction SilentlyContinue
|
239 |
+
Write-Host "Installer files deleted."
|
240 |
+
}
|
241 |
+
|
242 |
+
Write-Host "******************* ebook2audiobook installation successful! *******************" -ForegroundColor Green
|
243 |
+
Write-Host "To launch ebook2audiobook:" -ForegroundColor Yellow
|
244 |
+
Write-Host "- in command line mode: ./ebook2audiobook.cmd --headless [other options]"
|
245 |
+
Write-Host "- in graphic web mode: ./ebook2audiobook.cmd [--share]"
|
246 |
+
} else {
|
247 |
+
Write-Host "The python terminal is still using the OS python version $pythonVersion, but it should be $pythonEnvVersion from the python_env virtual environment"
|
248 |
+
}
|
249 |
+
|
250 |
+
# Deactivate Conda environment
|
251 |
+
Write-Host "Deactivating Conda environment..."
|
252 |
+
& conda deactivate
|
253 |
+
} else {
|
254 |
+
Write-Host "Installation cannot proceed. Either Conda is not installed or Docker is not running." -ForegroundColor Red
|
255 |
+
}
|
legacy/v1.0/legacy/install.sh
ADDED
@@ -0,0 +1,171 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/usr/bin/env bash
|
2 |
+
|
3 |
+
WGET=$(which wget 2>/dev/null)
|
4 |
+
CONDA_VERSION=$(conda --version 2>/dev/null)
|
5 |
+
DOCKER_UTILS=$(which docker 2>/dev/null)
|
6 |
+
DOCKER_UTILS_NEEDED=false
|
7 |
+
PACK_MGR=""
|
8 |
+
PACK_MGR_OPTIONS=""
|
9 |
+
|
10 |
+
if [[ "$OSTYPE" == "darwin"* ]]; then
|
11 |
+
PACK_MGR="brew install"
|
12 |
+
elif command -v emerge &> /dev/null; then
|
13 |
+
PACK_MGR="sudo emerge"
|
14 |
+
elif command -v dnf &> /dev/null; then
|
15 |
+
PACK_MGR="sudo dnf install"
|
16 |
+
PACK_MGR_OPTIONS="-y"
|
17 |
+
elif command -v yum &> /dev/null; then
|
18 |
+
PACK_MGR="sudo yum install"
|
19 |
+
PACK_MGR_OPTIONS="-y"
|
20 |
+
elif command -v zypper &> /dev/null; then
|
21 |
+
PACK_MGR="sudo zypper install"
|
22 |
+
PACK_MGR_OPTIONS="-y"
|
23 |
+
elif command -v pacman &> /dev/null; then
|
24 |
+
PACK_MGR="sudo pacman -Sy"
|
25 |
+
elif command -v apt-get &> /dev/null; then
|
26 |
+
sudo apt-get update
|
27 |
+
PACK_MGR="sudo apt-get install"
|
28 |
+
PACK_MGR_OPTIONS="-y"
|
29 |
+
elif command -v apk &> /dev/null; then
|
30 |
+
PACK_MGR="sudo apk add"
|
31 |
+
fi
|
32 |
+
|
33 |
+
check_programs_installed() {
|
34 |
+
local programs=("$@")
|
35 |
+
declare -a programs_missing
|
36 |
+
|
37 |
+
for program in "${programs[@]}"; do
|
38 |
+
if command -v "$program" >/dev/null 2>&1; then
|
39 |
+
echo "$program is installed."
|
40 |
+
else
|
41 |
+
echo "$program is not installed."
|
42 |
+
programs_missing+=($program)
|
43 |
+
fi
|
44 |
+
done
|
45 |
+
|
46 |
+
local count=${#programs_missing[@]}
|
47 |
+
|
48 |
+
if [[ $count -eq 0 || "$PKG_MGR" = "" ]]; then
|
49 |
+
DOCKER_UTILS_NEEDED=true
|
50 |
+
else
|
51 |
+
for program in "${programs_missing[@]}"; do
|
52 |
+
if [ "$program" = "ffmpeg" ];then
|
53 |
+
eval "$PKG_MGR ffmpeg $PKG_MGR_OPTIONS"
|
54 |
+
if command -v ffmpeg >/dev/null 2>&1; then
|
55 |
+
echo "FFmpeg installed successfully!"
|
56 |
+
else
|
57 |
+
echo "FFmpeg installation failed."
|
58 |
+
DOCKER_UTILS_NEEDED=true
|
59 |
+
break
|
60 |
+
fi
|
61 |
+
elif [ "$program" = "calibre" ];then
|
62 |
+
# avoid conflict with calibre builtin lxml
|
63 |
+
pip uninstall lxml -y 2>/dev/null
|
64 |
+
|
65 |
+
if [[ "$OSTYPE" == "Linux" ]]; then
|
66 |
+
echo "Installing Calibre for Linux..."
|
67 |
+
$WGET -nv -O- https://download.calibre-ebook.com/linux-installer.sh | sh /dev/stdin
|
68 |
+
elif [[ "$OSTYPE" == "Darwin"* ]]; then
|
69 |
+
echo "Installing Calibre for macOS using Homebrew..."
|
70 |
+
eval "$PACK_MGR --cask calibre"
|
71 |
+
fi
|
72 |
+
|
73 |
+
if command -v calibre >/dev/null 2>&1; then
|
74 |
+
echo "Calibre installed successfully!"
|
75 |
+
else
|
76 |
+
echo "Calibre installation failed."
|
77 |
+
fi
|
78 |
+
fi
|
79 |
+
done
|
80 |
+
fi
|
81 |
+
}
|
82 |
+
|
83 |
+
# Check for Homebrew on macOS
|
84 |
+
if [[ "$OSTYPE" == "darwin"* ]]; then
|
85 |
+
echo "Detected macOS."
|
86 |
+
if ! command -v brew &> /dev/null; then
|
87 |
+
echo "Homebrew is not installed. Installing Homebrew..."
|
88 |
+
/usr/bin/env bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
|
89 |
+
echo 'eval "$(/opt/homebrew/bin/brew shellenv)"' >> ~/.zprofile
|
90 |
+
eval "$(/opt/homebrew/bin/brew shellenv)"
|
91 |
+
fi
|
92 |
+
fi
|
93 |
+
|
94 |
+
if [ -z "$WGET" ]; then
|
95 |
+
echo -e "\e[33m wget is missing! trying to install it... \e[0m"
|
96 |
+
if [ "$PACK_MGR" != "" ]; then
|
97 |
+
eval "$PACK_MGR wget $PACK_MGR_OPTIONS"
|
98 |
+
else
|
99 |
+
echo "Cannot recognize your package manager. Please install wget manually."
|
100 |
+
fi
|
101 |
+
WGET=$(which wget 2>/dev/null)
|
102 |
+
fi
|
103 |
+
|
104 |
+
if [[ -n "$WGET" && -z "$CONDA_VERSION" ]]; then
|
105 |
+
echo -e "\e[33m conda is missing! trying to install it... \e[0m"
|
106 |
+
|
107 |
+
if [[ "$OSTYPE" == "darwin"* ]]; then
|
108 |
+
$WGET https://repo.anaconda.com/miniconda/Miniconda3-latest-MacOSX-x86_64.sh -O Miniconda3-latest.sh
|
109 |
+
else
|
110 |
+
$WGET https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O Miniconda3-latest.sh
|
111 |
+
fi
|
112 |
+
|
113 |
+
chmod +x Miniconda3-latest.sh
|
114 |
+
./Miniconda3-latest.sh -b -u && \
|
115 |
+
~/miniconda3/bin/conda init && \
|
116 |
+
rm -f Miniconda3-latest.sh
|
117 |
+
|
118 |
+
# Source the appropriate shell configuration file
|
119 |
+
SHELL_RC=~/miniconda3/etc/profile.d/conda.sh
|
120 |
+
source $SHELL_RC
|
121 |
+
|
122 |
+
CONDA_VERSION=$(conda --version 2>/dev/null)
|
123 |
+
echo -e "\e[32m===============>>> conda is installed! <<===============\e[0m"
|
124 |
+
fi
|
125 |
+
|
126 |
+
check_programs_installed()
|
127 |
+
|
128 |
+
if [ $DOCKER_UTILS_NEEDED = true ]; then
|
129 |
+
if [[ -n "$WGET" && -z "$DOCKER_UTILS" ]]; then
|
130 |
+
echo -e "\e[33m docker is missing! trying to install it... \e[0m"
|
131 |
+
if [[ "$OSTYPE" == "darwin"* ]]; then
|
132 |
+
echo "Installing Docker using Homebrew..."
|
133 |
+
brew install --cask docker
|
134 |
+
else
|
135 |
+
$WGET -qO get-docker.sh https://get.docker.com && \
|
136 |
+
sudo sh get-docker.sh && \
|
137 |
+
sudo systemctl start docker && \
|
138 |
+
sudo systemctl enable docker && \
|
139 |
+
docker run hello-world && \
|
140 |
+
DOCKER_UTILS=$(which docker 2>/dev/null)
|
141 |
+
rm -f get-docker.sh
|
142 |
+
fi
|
143 |
+
echo -e "\e[32m===============>>> docker is installed! <<===============\e[0m"
|
144 |
+
fi
|
145 |
+
fi
|
146 |
+
|
147 |
+
if [[ -n "$WGET" && -n "$CONDA_VERSION" ]]; then
|
148 |
+
SHELL_RC=~/miniconda3/etc/profile.d/conda.sh
|
149 |
+
echo -e "\e[33m Installing ebook2audiobook... \e[0m"
|
150 |
+
if [ $DOCKER_UTILS_NEEDED = true ]; then
|
151 |
+
conda create --prefix $(pwd)/python_env python=3.11 -y
|
152 |
+
source $SHELL_RC
|
153 |
+
conda activate $(pwd)/python_env
|
154 |
+
$DOCKER_UTILS build -f DockerfileUtils -t utils .
|
155 |
+
fi
|
156 |
+
pip install --upgrade pip && \
|
157 |
+
pip install pydub nltk beautifulsoup4 ebooklib translate coqui-tts tqdm mecab mecab-python3 unidic gradio>=4.44.0 docker && \
|
158 |
+
python -m unidic download && \
|
159 |
+
python -m spacy download en_core_web_sm && \
|
160 |
+
pip install -e .
|
161 |
+
if [ $DOCKER_UTILS_NEEDED = true ]; then
|
162 |
+
conda deactivate
|
163 |
+
conda deactivate
|
164 |
+
fi
|
165 |
+
echo -e "\e[32m******************* ebook2audiobook installation successful! *******************\e[0m"
|
166 |
+
echo -e "\e[33mTo launch ebook2audiobook:\e[0m"
|
167 |
+
echo -e "- in command line mode: ./ebook2audiobook.sh --headless [other options]"
|
168 |
+
echo -e "- in graphic web mode: ./ebook2audiobook.sh [--share]"
|
169 |
+
fi
|
170 |
+
|
171 |
+
exit 0
|
legacy/v1.0/readme/README_CN.md
ADDED
@@ -0,0 +1,428 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# 📚 ebook2audiobook
|
2 |
+
|
3 |
+
使用Calibre和Coqui XTTS将电子书转换为包含章节和元数据的有声读物。支持可选的语音克隆和多种语言!
|
4 |
+
|
5 |
+
#### 🖥️ Web GUI界面
|
6 |
+
![demo_web_gui](https://github.com/user-attachments/assets/85af88a7-05dd-4a29-91de-76a14cf5ef06)
|
7 |
+
|
8 |
+
<details>
|
9 |
+
<summary>点击查看Web GUI的图片</summary>
|
10 |
+
<img width="1728" alt="image" src="https://github.com/user-attachments/assets/b36c71cf-8e06-484c-a252-934e6b1d0c2f">
|
11 |
+
<img width="1728" alt="image" src="https://github.com/user-attachments/assets/c0dab57a-d2d4-4658-bff9-3842ec90cb40">
|
12 |
+
<img width="1728" alt="image" src="https://github.com/user-attachments/assets/0a99eeac-c521-4b21-8656-e064c1adc528">
|
13 |
+
</details>
|
14 |
+
|
15 |
+
## 🌟 特征
|
16 |
+
|
17 |
+
- 📖 使用Calibre将电子书转换为文本格式。
|
18 |
+
- 📚 将电子书拆分为章节,以获得有组织的音频。
|
19 |
+
- 🎙️ 使用Coqui XTTS实现高质量的文本到语音转换。
|
20 |
+
- 🗣️ 可选择使用您自己的语音文件进行语音克隆。
|
21 |
+
- 🌍 支持多种语言(默认为英语)。
|
22 |
+
- 🖥️ 基于4GB RAM运行。
|
23 |
+
|
24 |
+
## 🛠️ 环境要求
|
25 |
+
|
26 |
+
- Python 3.10
|
27 |
+
- `coqui-tts` Python package
|
28 |
+
- Calibre (用于电子书转换)
|
29 |
+
- FFmpeg (用于有声读物创作)
|
30 |
+
- Optional: 用于语音克隆的自定义语音文件
|
31 |
+
|
32 |
+
### 🔧 安装说明
|
33 |
+
|
34 |
+
1. **安装 Python 3.x** from [Python.org](https://www.python.org/downloads/).
|
35 |
+
|
36 |
+
2. **安装 Calibre**:
|
37 |
+
- **Ubuntu**: `sudo apt-get install -y calibre`
|
38 |
+
- **macOS**: `brew install calibre`
|
39 |
+
- **Windows** (Admin Powershell): `choco install calibre`
|
40 |
+
|
41 |
+
3. **安装 FFmpeg**:
|
42 |
+
- **Ubuntu**: `sudo apt-get install -y ffmpeg`
|
43 |
+
- **macOS**: `brew install ffmpeg`
|
44 |
+
- **Windows** (Admin Powershell): `choco install ffmpeg`
|
45 |
+
|
46 |
+
4. **可选: Install Mecab** (非拉丁语言):
|
47 |
+
- **Ubuntu**: `sudo apt-get install -y mecab libmecab-dev mecab-ipadic-utf8`
|
48 |
+
- **macOS**: `brew install mecab`, `brew install mecab-ipadic`
|
49 |
+
- **Windows**: [mecab-website-to-install-manually](https://taku910.github.io/mecab/#download) (注:日语支持有限)
|
50 |
+
|
51 |
+
5. **安装 Python packages**:
|
52 |
+
```bash
|
53 |
+
pip install coqui-tts==0.24.2 pydub nltk beautifulsoup4 ebooklib tqdm gradio==4.44.0
|
54 |
+
|
55 |
+
python -m nltk.downloader punkt
|
56 |
+
python -m nltk.downloader punkt_tab
|
57 |
+
```
|
58 |
+
|
59 |
+
**For non-Latin languages**:
|
60 |
+
```bash
|
61 |
+
pip install mecab mecab-python3 unidic
|
62 |
+
|
63 |
+
python -m unidic download
|
64 |
+
```
|
65 |
+
|
66 |
+
## 🌐 支持的语言
|
67 |
+
|
68 |
+
- **English (en)**
|
69 |
+
- **Spanish (es)**
|
70 |
+
- **French (fr)**
|
71 |
+
- **German (de)**
|
72 |
+
- **Italian (it)**
|
73 |
+
- **Portuguese (pt)**
|
74 |
+
- **Polish (pl)**
|
75 |
+
- **Turkish (tr)**
|
76 |
+
- **Russian (ru)**
|
77 |
+
- **Dutch (nl)**
|
78 |
+
- **Czech (cs)**
|
79 |
+
- **Arabic (ar)**
|
80 |
+
- **Chinese (zh-cn)**
|
81 |
+
- **Japanese (ja)**
|
82 |
+
- **Hungarian (hu)**
|
83 |
+
- **Korean (ko)**
|
84 |
+
|
85 |
+
在无头模式下运行脚本时指定语言代码。
|
86 |
+
## 🚀 使用
|
87 |
+
|
88 |
+
### 🖥️ 启动Gradio Web界面
|
89 |
+
|
90 |
+
1. **运行脚本**:
|
91 |
+
```bash
|
92 |
+
python app.py
|
93 |
+
```
|
94 |
+
|
95 |
+
2. **打开web应用程序**: 点击终端中提供的URL访问web应用程序并转换电子书.
|
96 |
+
3. **公共链接**: 在末尾添加“--share True”,如下所示:`python app.py--share True`
|
97 |
+
- **[更多参数]**: 使用`-h`参数,如`python app.py-h`
|
98 |
+
|
99 |
+
### 📝 基本的无头用法
|
100 |
+
|
101 |
+
```bash
|
102 |
+
python app.py --headless True --ebook <path_to_ebook_file> --voice [path_to_voice_file] --language [language_code]
|
103 |
+
```
|
104 |
+
|
105 |
+
- **<path_to_ebook_file>**: 电子书文件的路径。
|
106 |
+
- **[path_to_voice_file]**: 指定转换的语音文件,可选。
|
107 |
+
- **[language_code]**: 指定转换的语言,可选。
|
108 |
+
- **[更多参数]**: 使用 `-h` 参数,如 `python app.py -h`
|
109 |
+
|
110 |
+
### 🧩 自定义XTTS模型的无头用法
|
111 |
+
|
112 |
+
```bash
|
113 |
+
python app.py --headless True --use_custom_model True --ebook <ebook_file_path> --voice <target_voice_file_path> --language <language> --custom_model <custom_model_path> --custom_config <custom_config_path> --custom_vocab <custom_vocab_path>
|
114 |
+
```
|
115 |
+
|
116 |
+
- **<ebook_file_path>**: 电子书文件的路径。
|
117 |
+
- **<target_voice_file_path>**: 指定转换的语音文件,可选。
|
118 |
+
- **<language>**: 指定转换的语言,可选。
|
119 |
+
- **<custom_model_path>**: `model.pth`的路径。
|
120 |
+
- **<custom_config_path>**: `config.json`的路径。
|
121 |
+
- **<custom_vocab_path>**: `vocab.json`的路径。
|
122 |
+
- **[更多参数]**: 使用 `-h` 参数,如 `python app.py -h`
|
123 |
+
|
124 |
+
### 🧩 自定义XTTS Fine-Tune 模型的无头用法 🌐
|
125 |
+
|
126 |
+
```bash
|
127 |
+
python app.py --headless True --use_custom_model True --ebook <ebook_file_path> --voice <target_voice_file_path> --language <language> --custom_model_url <custom_model_URL_ZIP_path>
|
128 |
+
```
|
129 |
+
|
130 |
+
- **<ebook_file_path>**: 电子书文件的路径。
|
131 |
+
- **<target_voice_file_path>**: 指定转换的语音文件,可选。
|
132 |
+
- **<language>**: 指定转换的语言,可选。
|
133 |
+
- **<custom_model_URL_ZIP_path>**: 模型文件夹压缩包的URL路径。例如
|
134 |
+
[xtts_David_Attenborough_fine_tune](https://huggingface.co/drewThomasson/xtts_David_Attenborough_fine_tune/tree/main) `https://huggingface.co/drewThomasson/xtts_David_Attenborough_fine_tune/resolve/main/Finished_model_files.zip?download=true`
|
135 |
+
- **[更多参数]**: 使用 `-h` 参数,如 `python app.py -h`
|
136 |
+
|
137 |
+
### 🔍 详细指南,包括所有要使用的参数列表
|
138 |
+
```bash
|
139 |
+
python app.py -h
|
140 |
+
```
|
141 |
+
- 这将输出以下内容:
|
142 |
+
```bash
|
143 |
+
usage: app.py [-h] [--share SHARE] [--headless HEADLESS] [--ebook EBOOK] [--voice VOICE]
|
144 |
+
[--language LANGUAGE] [--use_custom_model USE_CUSTOM_MODEL]
|
145 |
+
[--custom_model CUSTOM_MODEL] [--custom_config CUSTOM_CONFIG]
|
146 |
+
[--custom_vocab CUSTOM_VOCAB] [--custom_model_url CUSTOM_MODEL_URL]
|
147 |
+
[--temperature TEMPERATURE] [--length_penalty LENGTH_PENALTY]
|
148 |
+
[--repetition_penalty REPETITION_PENALTY] [--top_k TOP_K] [--top_p TOP_P]
|
149 |
+
[--speed SPEED] [--enable_text_splitting ENABLE_TEXT_SPLITTING]
|
150 |
+
|
151 |
+
Convert eBooks to Audiobooks using a Text-to-Speech model. You can either launch the
|
152 |
+
Gradio interface or run the script in headless mode for direct conversion.
|
153 |
+
|
154 |
+
options:
|
155 |
+
-h, --help show this help message and exit
|
156 |
+
--share SHARE Set to True to enable a public shareable Gradio link. Defaults
|
157 |
+
to False.
|
158 |
+
--headless HEADLESS Set to True to run in headless mode without the Gradio
|
159 |
+
interface. Defaults to False.
|
160 |
+
--ebook EBOOK Path to the ebook file for conversion. Required in headless
|
161 |
+
mode.
|
162 |
+
--voice VOICE Path to the target voice file for TTS. Optional, uses a default
|
163 |
+
voice if not provided.
|
164 |
+
--language LANGUAGE Language for the audiobook conversion. Options: en, es, fr, de,
|
165 |
+
it, pt, pl, tr, ru, nl, cs, ar, zh-cn, ja, hu, ko. Defaults to
|
166 |
+
English (en).
|
167 |
+
--use_custom_model USE_CUSTOM_MODEL
|
168 |
+
Set to True to use a custom TTS model. Defaults to False. Must
|
169 |
+
be True to use custom models, otherwise you'll get an error.
|
170 |
+
--custom_model CUSTOM_MODEL
|
171 |
+
Path to the custom model file (.pth). Required if using a custom
|
172 |
+
model.
|
173 |
+
--custom_config CUSTOM_CONFIG
|
174 |
+
Path to the custom config file (config.json). Required if using
|
175 |
+
a custom model.
|
176 |
+
--custom_vocab CUSTOM_VOCAB
|
177 |
+
Path to the custom vocab file (vocab.json). Required if using a
|
178 |
+
custom model.
|
179 |
+
--custom_model_url CUSTOM_MODEL_URL
|
180 |
+
URL to download the custom model as a zip file. Optional, but
|
181 |
+
will be used if provided. Examples include David Attenborough's
|
182 |
+
model: 'https://huggingface.co/drewThomasson/xtts_David_Attenbor
|
183 |
+
ough_fine_tune/resolve/main/Finished_model_files.zip?download=tr
|
184 |
+
ue'. More XTTS fine-tunes can be found on my Hugging Face at
|
185 |
+
'https://huggingface.co/drewThomasson'.
|
186 |
+
--temperature TEMPERATURE
|
187 |
+
Temperature for the model. Defaults to 0.65. Higher Tempatures
|
188 |
+
will lead to more creative outputs IE: more Hallucinations.
|
189 |
+
Lower Tempatures will be more monotone outputs IE: less
|
190 |
+
Hallucinations.
|
191 |
+
--length_penalty LENGTH_PENALTY
|
192 |
+
A length penalty applied to the autoregressive decoder. Defaults
|
193 |
+
to 1.0. Not applied to custom models.
|
194 |
+
--repetition_penalty REPETITION_PENALTY
|
195 |
+
A penalty that prevents the autoregressive decoder from
|
196 |
+
repeating itself. Defaults to 2.0.
|
197 |
+
--top_k TOP_K Top-k sampling. Lower values mean more likely outputs and
|
198 |
+
increased audio generation speed. Defaults to 50.
|
199 |
+
--top_p TOP_P Top-p sampling. Lower values mean more likely outputs and
|
200 |
+
increased audio generation speed. Defaults to 0.8.
|
201 |
+
--speed SPEED Speed factor for the speech generation. IE: How fast the
|
202 |
+
Narrerator will speak. Defaults to 1.0.
|
203 |
+
--enable_text_splitting ENABLE_TEXT_SPLITTING
|
204 |
+
Enable splitting text into sentences. Defaults to True.
|
205 |
+
|
206 |
+
Example: python script.py --headless --ebook path_to_ebook --voice path_to_voice
|
207 |
+
--language en --use_custom_model True --custom_model model.pth --custom_config
|
208 |
+
config.json --custom_vocab vocab.json
|
209 |
+
```
|
210 |
+
|
211 |
+
<details>
|
212 |
+
<summary>⚠️ 遗留的旧版使用说明</summary>
|
213 |
+
|
214 |
+
## 🚀 使用
|
215 |
+
|
216 |
+
----> `ebook2audiobookXTTS/legacy/`
|
217 |
+
|
218 |
+
### 🖥️ Web界面
|
219 |
+
|
220 |
+
1. **运行脚本**:
|
221 |
+
```bash
|
222 |
+
python custom_model_ebook2audiobookXTTS_gradio.py
|
223 |
+
```
|
224 |
+
|
225 |
+
2. **打开web应用程序**: 单击终端中提供的URL以访问web应用程序并转换电子书。
|
226 |
+
|
227 |
+
### 📝 基础用法
|
228 |
+
|
229 |
+
```bash
|
230 |
+
python ebook2audiobook.py <path_to_ebook_file> [path_to_voice_file] [language_code]
|
231 |
+
```
|
232 |
+
|
233 |
+
- **<path_to_ebook_file>**: 电子书文件的路径。
|
234 |
+
- **[path_to_voice_file]**: 指定转换的语音文件,可选。
|
235 |
+
- **[language_code]**: 指定转换的语言,可选。
|
236 |
+
|
237 |
+
### 🧩 自定义XTTS模型
|
238 |
+
|
239 |
+
```bash
|
240 |
+
python custom_model_ebook2audiobookXTTS.py <ebook_file_path> <target_voice_file_path> <language> <custom_model_path> <custom_config_path> <custom_vocab_path>
|
241 |
+
```
|
242 |
+
|
243 |
+
- **<ebook_file_path>**: 电子书文件的路径。
|
244 |
+
- **<target_voice_file_path>**: 指定转换的语音文件,可选。
|
245 |
+
- **<language>**: 指定转换的语言,可选。
|
246 |
+
- **<custom_model_path>**: `model.pth`的路径。
|
247 |
+
- **<custom_config_path>**: `config.json`的路径。
|
248 |
+
- **<custom_vocab_path>**: `vocab.json`的路径。
|
249 |
+
</details>
|
250 |
+
|
251 |
+
### 🐳 使用Docker
|
252 |
+
|
253 |
+
您还可以使用Docker运行电子书到有声读物的转换器。这种方法确保了不同环境之间的一致性,并简化了设置。
|
254 |
+
|
255 |
+
#### 🚀 运行Docker容器
|
256 |
+
|
257 |
+
要运行Docker容器并启动Gradio接口,请使用以下命令:
|
258 |
+
|
259 |
+
-仅使用CPU运行
|
260 |
+
```powershell
|
261 |
+
docker run -it --rm -p 7860:7860 --platform=linux/amd64 athomasson2/ebook2audiobookxtts:huggingface python app.py
|
262 |
+
```
|
263 |
+
-使用GPU加速运行(仅限Nvida显卡)
|
264 |
+
```powershell
|
265 |
+
docker run -it --rm --gpus all -p 7860:7860 --platform=linux/amd64 athomasson2/ebook2audiobookxtts:huggingface python app.py
|
266 |
+
```
|
267 |
+
|
268 |
+
此命令将启动7860端口上的Gradio接口(localhost:7860)
|
269 |
+
- 对于更多选项,如以无头模式运行docker或公开gradio链接,请在docker启动命令中的`app.py`后添加`-h`参数
|
270 |
+
<details>
|
271 |
+
<summary><strong>在无头模式下使用docker或使用额外参数修改任何内容的示例+完整指南</strong></summary>
|
272 |
+
|
273 |
+
## 在无头模式下使用docker的示例
|
274 |
+
|
275 |
+
首先是docker pull的最新版本
|
276 |
+
```bash
|
277 |
+
docker pull athomasson2/ebook2audiobookxtts:huggingface
|
278 |
+
```
|
279 |
+
|
280 |
+
- 在运行此命令之前,您需要在当前目录中创建一个名为“input folder”的目录,该目录将被链接,您可以在此处放置docker镜像的输入文件
|
281 |
+
```bash
|
282 |
+
mkdir input-folder && mkdir Audiobooks
|
283 |
+
```
|
284 |
+
|
285 |
+
- 运行下面命令需要将 **YOUR_INPUT_FILE.TXT** 替换为您创建的输入文件的名称
|
286 |
+
|
287 |
+
```bash
|
288 |
+
docker run -it --rm \
|
289 |
+
-v $(pwd)/input-folder:/home/user/app/input_folder \
|
290 |
+
-v $(pwd)/Audiobooks:/home/user/app/Audiobooks \
|
291 |
+
--platform linux/amd64 \
|
292 |
+
athomasson2/ebook2audiobookxtts:huggingface \
|
293 |
+
python app.py --headless True --ebook /home/user/app/input_folder/YOUR_INPUT_FILE.TXT
|
294 |
+
```
|
295 |
+
|
296 |
+
- 应该就是这样了!
|
297 |
+
|
298 |
+
- 输出Audiobooks将在Audiobook文件夹中找到,该文件夹也位于您运行此docker命令的本地目录中
|
299 |
+
|
300 |
+
|
301 |
+
## 要获取此程序中其他参数的帮助命令,可以运行以下命令
|
302 |
+
|
303 |
+
```bash
|
304 |
+
docker run -it --rm \
|
305 |
+
--platform linux/amd64 \
|
306 |
+
athomasson2/ebook2audiobookxtts:huggingface \
|
307 |
+
python app.py -h
|
308 |
+
|
309 |
+
```
|
310 |
+
|
311 |
+
|
312 |
+
这将输出以下内容
|
313 |
+
|
314 |
+
```bash
|
315 |
+
user/app/ebook2audiobookXTTS/input-folder -v $(pwd)/Audiobooks:/home/user/app/ebook2audiobookXTTS/Audiobooks --memory="4g" --network none --platform linux/amd64 athomasson2/ebook2audiobookxtts:huggingface python app.py -h
|
316 |
+
starting...
|
317 |
+
usage: app.py [-h] [--share SHARE] [--headless HEADLESS] [--ebook EBOOK] [--voice VOICE]
|
318 |
+
[--language LANGUAGE] [--use_custom_model USE_CUSTOM_MODEL]
|
319 |
+
[--custom_model CUSTOM_MODEL] [--custom_config CUSTOM_CONFIG]
|
320 |
+
[--custom_vocab CUSTOM_VOCAB] [--custom_model_url CUSTOM_MODEL_URL]
|
321 |
+
[--temperature TEMPERATURE] [--length_penalty LENGTH_PENALTY]
|
322 |
+
[--repetition_penalty REPETITION_PENALTY] [--top_k TOP_K] [--top_p TOP_P]
|
323 |
+
[--speed SPEED] [--enable_text_splitting ENABLE_TEXT_SPLITTING]
|
324 |
+
|
325 |
+
Convert eBooks to Audiobooks using a Text-to-Speech model. You can either launch the
|
326 |
+
Gradio interface or run the script in headless mode for direct conversion.
|
327 |
+
|
328 |
+
options:
|
329 |
+
-h, --help show this help message and exit
|
330 |
+
--share SHARE Set to True to enable a public shareable Gradio link. Defaults
|
331 |
+
to False.
|
332 |
+
--headless HEADLESS Set to True to run in headless mode without the Gradio
|
333 |
+
interface. Defaults to False.
|
334 |
+
--ebook EBOOK Path to the ebook file for conversion. Required in headless
|
335 |
+
mode.
|
336 |
+
--voice VOICE Path to the target voice file for TTS. Optional, uses a default
|
337 |
+
voice if not provided.
|
338 |
+
--language LANGUAGE Language for the audiobook conversion. Options: en, es, fr, de,
|
339 |
+
it, pt, pl, tr, ru, nl, cs, ar, zh-cn, ja, hu, ko. Defaults to
|
340 |
+
English (en).
|
341 |
+
--use_custom_model USE_CUSTOM_MODEL
|
342 |
+
Set to True to use a custom TTS model. Defaults to False. Must
|
343 |
+
be True to use custom models, otherwise you'll get an error.
|
344 |
+
--custom_model CUSTOM_MODEL
|
345 |
+
Path to the custom model file (.pth). Required if using a custom
|
346 |
+
model.
|
347 |
+
--custom_config CUSTOM_CONFIG
|
348 |
+
Path to the custom config file (config.json). Required if using
|
349 |
+
a custom model.
|
350 |
+
--custom_vocab CUSTOM_VOCAB
|
351 |
+
Path to the custom vocab file (vocab.json). Required if using a
|
352 |
+
custom model.
|
353 |
+
--custom_model_url CUSTOM_MODEL_URL
|
354 |
+
URL to download the custom model as a zip file. Optional, but
|
355 |
+
will be used if provided. Examples include David Attenborough's
|
356 |
+
model: 'https://huggingface.co/drewThomasson/xtts_David_Attenbor
|
357 |
+
ough_fine_tune/resolve/main/Finished_model_files.zip?download=tr
|
358 |
+
ue'. More XTTS fine-tunes can be found on my Hugging Face at
|
359 |
+
'https://huggingface.co/drewThomasson'.
|
360 |
+
--temperature TEMPERATURE
|
361 |
+
Temperature for the model. Defaults to 0.65. Higher Tempatures
|
362 |
+
will lead to more creative outputs IE: more Hallucinations.
|
363 |
+
Lower Tempatures will be more monotone outputs IE: less
|
364 |
+
Hallucinations.
|
365 |
+
--length_penalty LENGTH_PENALTY
|
366 |
+
A length penalty applied to the autoregressive decoder. Defaults
|
367 |
+
to 1.0. Not applied to custom models.
|
368 |
+
--repetition_penalty REPETITION_PENALTY
|
369 |
+
A penalty that prevents the autoregressive decoder from
|
370 |
+
repeating itself. Defaults to 2.0.
|
371 |
+
--top_k TOP_K Top-k sampling. Lower values mean more likely outputs and
|
372 |
+
increased audio generation speed. Defaults to 50.
|
373 |
+
--top_p TOP_P Top-p sampling. Lower values mean more likely outputs and
|
374 |
+
increased audio generation speed. Defaults to 0.8.
|
375 |
+
--speed SPEED Speed factor for the speech generation. IE: How fast the
|
376 |
+
Narrerator will speak. Defaults to 1.0.
|
377 |
+
--enable_text_splitting ENABLE_TEXT_SPLITTING
|
378 |
+
Enable splitting text into sentences. Defaults to True.
|
379 |
+
|
380 |
+
Example: python script.py --headless --ebook path_to_ebook --voice path_to_voice
|
381 |
+
--language en --use_custom_model True --custom_model model.pth --custom_config
|
382 |
+
config.json --custom_vocab vocab.json
|
383 |
+
```
|
384 |
+
</details>
|
385 |
+
|
386 |
+
#### 🖥️ Docker图形用户界面
|
387 |
+
![demo_web_gui](https://github.com/user-attachments/assets/85af88a7-05dd-4a29-91de-76a14cf5ef06)
|
388 |
+
|
389 |
+
<details>
|
390 |
+
<summary>点击查看Web界面的图片</summary>
|
391 |
+
<img width="1728" alt="image" src="https://github.com/user-attachments/assets/b36c71cf-8e06-484c-a252-934e6b1d0c2f">
|
392 |
+
<img width="1728" alt="image" src="https://github.com/user-attachments/assets/c0dab57a-d2d4-4658-bff9-3842ec90cb40">
|
393 |
+
<img width="1728" alt="image" src="https://github.com/user-attachments/assets/0a99eeac-c521-4b21-8656-e064c1adc528">
|
394 |
+
</details>
|
395 |
+
|
396 |
+
### 🛠️ 关于自定义XTTS模型
|
397 |
+
|
398 |
+
为更好地处理特定声音而构建的模型。查看我的Hugging Face页面 [here](https://huggingface.co/drewThomasson).
|
399 |
+
|
400 |
+
要使用自定义模型,请粘贴“Finished_model_files.zip”文件的链接,如下所示:
|
401 |
+
|
402 |
+
[David Attenborough fine tuned Finished_model_files.zip](https://huggingface.co/drewThomasson/xtts_David_Attenborough_fine_tune/resolve/main/Finished_model_files.zip?download=true)
|
403 |
+
|
404 |
+
|
405 |
+
|
406 |
+
|
407 |
+
更多详细信息请访问 [Dockerfile Hub Page]([https://github.com/DrewThomasson/ebook2audiobookXTTS](https://hub.docker.com/repository/docker/athomasson2/ebook2audiobookxtts/general)).
|
408 |
+
|
409 |
+
## 🌐 微调XTTS模型
|
410 |
+
|
411 |
+
要查找已经过微调的XTTS型号,请访问[Hugging Face](https://huggingface.co/drewThomasson) 🌐. 模型搜索需要包含“xtts fine tune”的关键字。
|
412 |
+
|
413 |
+
## 🎥 Demos
|
414 |
+
|
415 |
+
https://github.com/user-attachments/assets/8486603c-38b1-43ce-9639-73757dfb1031
|
416 |
+
|
417 |
+
## 🤗 [Huggingface space demo](https://huggingface.co/spaces/drewThomasson/ebook2audiobookXTTS)
|
418 |
+
- Huggingface空间正在空闲cpu层上运行,所以预计会非常慢或超时,哈哈,只是不要给它大文件
|
419 |
+
- 最好复制空间或在本地运行。
|
420 |
+
## 📚 支持的电子书格式
|
421 |
+
|
422 |
+
- `.epub`, `.pdf`, `.mobi`, `.txt`, `.html`, `.rtf`, `.chm`, `.lit`, `.pdb`, `.fb2`, `.odt`, `.cbr`, `.cbz`, `.prc`, `.lrf`, `.pml`, `.snb`, `.cbc`, `.rb`, `.tcr`
|
423 |
+
- **最佳结果**: `.epub` 或者 `.mobi`格式可以进行自动章节检测。
|
424 |
+
|
425 |
+
## 📂 输出
|
426 |
+
|
427 |
+
- 创建一个包含元数据和章节的“.m4b”文件。
|
428 |
+
- **例子**: ![Example](https://github.com/DrewThomasson/VoxNovel/blob/dc5197dff97252fa44c391dc0596902d71278a88/readme_files/example_in_app.jpeg)
|
legacy/v1.0/readme/README_RU.md
ADDED
@@ -0,0 +1,387 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# 📚 ebook2audiobook
|
2 |
+
|
3 |
+
Конвертация электронных книг в аудиокниги с сохранением глав и метаданных, используются механизмы Calibre и XTTS. Поддерживаются опциональное клонирование голоса и множественные языки!
|
4 |
+
|
5 |
+
|
6 |
+
#### 🖥️ Web-интерфейс
|
7 |
+
![demo_web_gui](https://github.com/user-attachments/assets/85af88a7-05dd-4a29-91de-76a14cf5ef06)
|
8 |
+
|
9 |
+
<details>
|
10 |
+
<summary>Больше картинок Web-интерфейса</summary>
|
11 |
+
<img width="1728" alt="image" src="https://github.com/user-attachments/assets/b36c71cf-8e06-484c-a252-934e6b1d0c2f">
|
12 |
+
<img width="1728" alt="image" src="https://github.com/user-attachments/assets/c0dab57a-d2d4-4658-bff9-3842ec90cb40">
|
13 |
+
<img width="1728" alt="image" src="https://github.com/user-attachments/assets/0a99eeac-c521-4b21-8656-e064c1adc528">
|
14 |
+
</details>
|
15 |
+
|
16 |
+
## README.md
|
17 |
+
- en [English](README.md)
|
18 |
+
- zh_CN [简体中文](readme/README_CN.md)
|
19 |
+
- ru [Русский](readme/README_RU.md)
|
20 |
+
|
21 |
+
|
22 |
+
## 🌟 Возможности
|
23 |
+
|
24 |
+
- 📖 Преобразование электронных книг в текстовый формат при помощи Calibre.
|
25 |
+
- 📚 Разбитие электронных книг по главам для аудиоформата.
|
26 |
+
- 🎙️ Высококачественное преобразование текста в голос при помощи Coqui XTTS.
|
27 |
+
- 🗣️ Опциональное клонирование голоса на основе вашего голосового файла.
|
28 |
+
- 🌍 Многоязыковая поддержка (английский по умолчанию).
|
29 |
+
- 🖥️ Для работы достаточно всего 4 Гб ОЗУ.
|
30 |
+
|
31 |
+
## 🤗 [Демонстрация на HuggingFace](https://huggingface.co/spaces/drewThomasson/ebook2audiobookXTTS)
|
32 |
+
- Пространство на HuggingFace работает на бесплатном процессорном уровне, посему не стоит ожидать от него высокой скорости обработки или отсутствия сообщений о таймаутах. Даже и не пытайтесь обработать большие файлы.
|
33 |
+
- Лучше всего скопировать пространство или запустить приложение локально.
|
34 |
+
|
35 |
+
## Бесплатный Google Colab [![Бесплатный Google Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/DrewThomasson/ebook2audiobookXTTS/blob/main/Notebooks/colab_ebook2audiobookxtts.ipynb)
|
36 |
+
|
37 |
+
|
38 |
+
## 🛠️ Требования
|
39 |
+
|
40 |
+
- Python 3.10
|
41 |
+
- `coqui-tts` Python package
|
42 |
+
- Calibre (для конвертации электронных книг)
|
43 |
+
- FFmpeg (для создания аудиокниг)
|
44 |
+
- Опционально: собственный файл с голосом для начитки
|
45 |
+
|
46 |
+
|
47 |
+
### 🔧 Установка
|
48 |
+
|
49 |
+
1. **Установить Python 3.x** из [Python.org](https://www.python.org/downloads/).
|
50 |
+
|
51 |
+
2. **Установить Calibre**:
|
52 |
+
- **Ubuntu**: `sudo apt-get install -y calibre`
|
53 |
+
- **macOS**: `brew install calibre`
|
54 |
+
- **Windows** (Admin Powershell): `choco install calibre`
|
55 |
+
|
56 |
+
3. **Установить FFmpeg**:
|
57 |
+
- **Ubuntu**: `sudo apt-get install -y ffmpeg`
|
58 |
+
- **macOS**: `brew install ffmpeg`
|
59 |
+
- **Windows** (Admin Powershell): `choco install ffmpeg`
|
60 |
+
|
61 |
+
4. **Опционально: установить Mecab** (для нелатинских языков):
|
62 |
+
- **Ubuntu**: `sudo apt-get install -y mecab libmecab-dev mecab-ipadic-utf8`
|
63 |
+
- **macOS**: `brew install mecab`, `brew install mecab-ipadic`
|
64 |
+
- **Windows**: [mecab-website-to-install-manually](https://taku910.github.io/mecab/#download) (Замечание: японский язык поддерживается ограниченно)
|
65 |
+
|
66 |
+
5. **Установить пакеты Python**:
|
67 |
+
```bash
|
68 |
+
pip install coqui-tts==0.24.2 pydub nltk beautifulsoup4 ebooklib tqdm gradio==4.44.0
|
69 |
+
|
70 |
+
python -m nltk.downloader punkt
|
71 |
+
python -m nltk.downloader punkt_tab
|
72 |
+
```
|
73 |
+
|
74 |
+
**Для нелатинских языков**:
|
75 |
+
```bash
|
76 |
+
pip install mecab mecab-python3 unidic
|
77 |
+
|
78 |
+
python -m unidic download
|
79 |
+
```
|
80 |
+
|
81 |
+
## 🌐 Поддерживаемые языки
|
82 |
+
|
83 |
+
- **English (en)**
|
84 |
+
- **Spanish (es)**
|
85 |
+
- **French (fr)**
|
86 |
+
- **German (de)**
|
87 |
+
- **Italian (it)**
|
88 |
+
- **Portuguese (pt)**
|
89 |
+
- **Polish (pl)**
|
90 |
+
- **Turkish (tr)**
|
91 |
+
- **Russian (ru)**
|
92 |
+
- **Dutch (nl)**
|
93 |
+
- **Czech (cs)**
|
94 |
+
- **Arabic (ar)**
|
95 |
+
- **Chinese (zh-cn)**
|
96 |
+
- **Japanese (ja)**
|
97 |
+
- **Hungarian (hu)**
|
98 |
+
- **Korean (ko)**
|
99 |
+
|
100 |
+
Указывайте код нужного языка при запуске в безинтерфейсном режиме (в командной строке).
|
101 |
+
## 🚀 Использование
|
102 |
+
|
103 |
+
### 🖥️ За��уск Gradio Web-интерфейса
|
104 |
+
|
105 |
+
1. **Запустите скрипт**:
|
106 |
+
```bash
|
107 |
+
python app.py
|
108 |
+
```
|
109 |
+
|
110 |
+
2. **Откройте Web-приложение**: нажмите на ссылку появившуюся в окне терминала для доступа к Web-приложению и конвертированию электронных книг.
|
111 |
+
3. **Для доступа из сети**: добавьте `--share True` в конец команды, наподобие: `python app.py --share True`
|
112 |
+
- **[Для большего количества параметров]**: используйте `-h` ключ, наподобие: `python app.py -h`
|
113 |
+
|
114 |
+
### 📝 Типовое использование в безинтерфейсном режиме
|
115 |
+
|
116 |
+
```bash
|
117 |
+
python app.py --headless True --ebook <path_to_ebook_file> --voice [path_to_voice_file] --language [language_code]
|
118 |
+
```
|
119 |
+
|
120 |
+
- **<path_to_ebook_file>**: путь к файлу электронной книги.
|
121 |
+
- **[path_to_voice_file]**: путь к примеру голоса, для опционального клонирования голоса для начитки.
|
122 |
+
- **[language_code]**: по желанию, выбрать язык.
|
123 |
+
- **[Для большего количества параметров]**: используйте `-h` ключ, наподобие `python app.py -h`
|
124 |
+
|
125 |
+
### 🧩 Безинтерфейсное использование с индивиуальной моделью XTTS
|
126 |
+
|
127 |
+
```bash
|
128 |
+
python app.py --headless True --use_custom_model True --ebook <ebook_file_path> --voice <target_voice_file_path> --language <language> --custom_model <custom_model_path> --custom_config <custom_config_path> --custom_vocab <custom_vocab_path>
|
129 |
+
```
|
130 |
+
|
131 |
+
- **<ebook_file_path>**: путь к файлу электронной книги.
|
132 |
+
- **<target_voice_file_path>**: путь к примеру голоса, для опционального клонирования.
|
133 |
+
- **\<language>**: по желанию, выбрать язык.
|
134 |
+
- **<custom_model_path>**: путь к `model.pth`.
|
135 |
+
- **<custom_config_path>**: путь к `config.json`.
|
136 |
+
- **<custom_vocab_path>**: путь к `vocab.json`.
|
137 |
+
- **[Для большего количества параметров]**: используйте `-h` ключ, наподобие `python app.py -h`
|
138 |
+
|
139 |
+
|
140 |
+
### 🧩 Безинтерфейсное использование с индивидуальной моделью XTTS со ссылкой на Zip-архив, содержащий модель тонкой настройки XTTS 🌐
|
141 |
+
|
142 |
+
```bash
|
143 |
+
python app.py --headless True --use_custom_model True --ebook <ebook_file_path> --voice <target_voice_file_path> --language <language> --custom_model_url <custom_model_URL_ZIP_path>
|
144 |
+
```
|
145 |
+
|
146 |
+
- **<ebook_file_path>**: путь к файлу eBook.
|
147 |
+
- **<target_voice_file_path>**: путь к примеру голоса, для опционального клонирования.
|
148 |
+
- **\<language>**: по желанию, выбрать язык.
|
149 |
+
- **<custom_model_URL_ZIP_path>**: путь в виде URL к архиву формата zip с папкой модели. Например, [xtts_David_Attenborough_fine_tune](https://huggingface.co/drewThomasson/xtts_David_Attenborough_fine_tune/tree/main) `https://huggingface.co/drewThomasson/xtts_David_Attenborough_fine_tune/resolve/main/Finished_model_files.zip?download=true`
|
150 |
+
- Для индивидуальной модели все равно потребуется референсный аудиофайл с голосом:
|
151 |
+
[референсный аудиофайл с голосом David Attenborough](https://huggingface.co/drewThomasson/xtts_David_Attenborough_fine_tune/blob/main/ref.wav)
|
152 |
+
- **[Для большего количества параметров]**: используйте `-h` ключ, наподобие `python app.py -h`
|
153 |
+
|
154 |
+
### 🔍 Для подробного списка всех параметров используйте
|
155 |
+
```bash
|
156 |
+
python app.py -h
|
157 |
+
```
|
158 |
+
- Будет выведен примерно следующий список ключей:
|
159 |
+
```bash
|
160 |
+
использование: app.py [-h] [--share SHARE] [--headless HEADLESS] [--ebook EBOOK] [--voice VOICE]
|
161 |
+
[--language LANGUAGE] [--use_custom_model USE_CUSTOM_MODEL]
|
162 |
+
[--custom_model CUSTOM_MODEL] [--custom_config CUSTOM_CONFIG]
|
163 |
+
[--custom_vocab CUSTOM_VOCAB] [--custom_model_url CUSTOM_MODEL_URL]
|
164 |
+
[--temperature TEMPERATURE] [--length_penalty LENGTH_PENALTY]
|
165 |
+
[--repetition_penalty REPETITION_PENALTY] [--top_k TOP_K] [--top_p TOP_P]
|
166 |
+
[--speed SPEED] [--enable_text_splitting ENABLE_TEXT_SPLITTING]
|
167 |
+
|
168 |
+
Преобразование электронных книг в аудиокниги с использованием модели Text-to-Speech (TTS). Вы можете либо использовать
|
169 |
+
интерфейс Gradio, либо запустить скрипт в безинтерфейсном режиме (командная строка) для прямого конвертирования.
|
170 |
+
|
171 |
+
опции:
|
172 |
+
-h, --help Отобразить этот список и выйти
|
173 |
+
--share SHARE Установить в True для включения публичного доступа к Web-интерфейсу Gradio. По умолчанию False.
|
174 |
+
--headless HEADLESS Установить в True для использования безинтерфейсного режима. По умолчанию False.
|
175 |
+
--ebook EBOOK Путь к электронной книге для конвертации. Необходимо для безинтерфейсного режима.
|
176 |
+
--voice VOICE Путь к целевому голосовому файлу для TTS (текст-в-голос). Опционально, используется голос по умолчанию, если путь не указан.
|
177 |
+
--language LANGUAGE Язык для конвертации в аудиокнигу. Варианты: en, es, fr, de,
|
178 |
+
it, pt, pl, tr, ru, nl, cs, ar, zh-cn, ja, hu, ko. По умолчанию English (en).
|
179 |
+
--use_custom_model USE_CUSTOM_MODEL
|
180 |
+
Установить в True для использования индивидуальной модели TTS. По умолчанию False. Необходимо переключить в
|
181 |
+
True для использования индивидуальной модели, в противном случае возникнет ошибка.
|
182 |
+
--custom_model CUSTOM_MODEL
|
183 |
+
Путь к файлу индивидуальной модели (.pth). Требуется, если используется индивидуальная модель.
|
184 |
+
--custom_config CUSTOM_CONFIG
|
185 |
+
Путь к конфигурационному файлу индивидуальной модели (config.json). Требуется, если используется индивидуальная модель.
|
186 |
+
--custom_vocab CUSTOM_VOCAB
|
187 |
+
Путь к словарю индивидуальной модели (vocab.json). Требуется, если используется индивидуальная модель.
|
188 |
+
--custom_model_url CUSTOM_MODEL_URL
|
189 |
+
URL для скачивания индивидуальной модели в виде zip-архива. Опционально, но если указано, то будет использовано.
|
190 |
+
Примеры включающие модель David Attenborough: 'https://huggingface.co/drewThomasson/xtts_David_Attenborough_fine_tune/resolve/main/Finished_model_files.zip?download=true'. Больше точно-настроенных моделей XTTS можно найти на Hugging Face 'https://huggingface.co/drewThomasson'.
|
191 |
+
--temperature TEMPERATURE
|
192 |
+
Температура для модели. По умолчанию 0.65. Чем выше температура, тем более креативным будет синтез голоса, с большим наваждением. Чем меньше, тем более монотонным и спокойным.
|
193 |
+
--length_penalty LENGTH_PENALTY
|
194 |
+
Ограничение длины авторегрессионного декодера. По умолчанию 1.0. Не применяется к индивидуальным моделям.
|
195 |
+
--repetition_penalty REPETITION_PENALTY
|
196 |
+
Ограничение, предотвращающее повторение авторегрессивным декодером за собой. По умолчанию 2.0
|
197 |
+
--top_k TOP_K Сэмплирование Top-k. Меньшее значение приводит к более вероятностному выводу и ускоряют генерацию аудио. По умолчанию 50.
|
198 |
+
--top_p TOP_P Сэмплирование Top-p. Меньшее значение приводит к более вероятностному выводу и ускоряют генерацию аудио. По умолчанию 0.8.
|
199 |
+
--speed SPEED Фактор скорости начитки. Чем больше значение, тем быстрее диктор будет читать текст. По умолчанию 1.0.
|
200 |
+
--enable_text_splitting ENABLE_TEXT_SPLITTING
|
201 |
+
Включает разбиение текста на предложения. По умолчанию True.
|
202 |
+
|
203 |
+
Пример: python script.py --headless --ebook path_to_ebook --voice path_to_voice --language en --use_custom_model True --custom_model model.pth --custom_config config.json --custom_vocab vocab.json
|
204 |
+
```
|
205 |
+
|
206 |
+
|
207 |
+
|
208 |
+
### 🐳 Использование Docker
|
209 |
+
|
210 |
+
Помимо всего прочего, можн�� использовать Docker для использования конвертера электронных книг в аудиокниги. Этот метод обеспечивает согласованность в различных средах и упрощает настройку.
|
211 |
+
|
212 |
+
#### 🚀 Запуск контейнера Docker
|
213 |
+
|
214 |
+
Для запуска контейнера Docker и интерфейса Gradio используйте следующую команду:
|
215 |
+
|
216 |
+
-Запуск с использованием только CPU (процессора)
|
217 |
+
```powershell
|
218 |
+
docker run -it --rm -p 7860:7860 --platform=linux/amd64 athomasson2/ebook2audiobookxtts:huggingface python app.py
|
219 |
+
```
|
220 |
+
-Запуск с использованием ускорения на GPU (графической карты), поддерживаются только видеокарты NVIDIA
|
221 |
+
```powershell
|
222 |
+
docker run -it --rm --gpus all -p 7860:7860 --platform=linux/amd64 athomasson2/ebook2audiobookxtts:huggingface python app.py
|
223 |
+
```
|
224 |
+
|
225 |
+
Эта команда запускает интерфейс Gradio на порту 7860. (localhost:7860)
|
226 |
+
- Для получения большей информации о доступных командах в безинтерфейсном режиме или предоставление доступа к Gradio в сети, используйте ключ `-h` после имени команды `app.py` в терминале Docker
|
227 |
+
<details>
|
228 |
+
<summary><strong>Пример использования Docker в безинтерфейсном режиме или модификаций параметров + полный гид</strong></summary>
|
229 |
+
|
230 |
+
## Пример использования Docker в безинтерфейсном режиме
|
231 |
+
|
232 |
+
- Сперва необходимо получить свежий контейнер с приложением
|
233 |
+
```bash
|
234 |
+
docker pull athomasson2/ebook2audiobookxtts:huggingface
|
235 |
+
```
|
236 |
+
|
237 |
+
- Прежде чем запустить команду на исполнение, необходимо создать директорию с именем "input-folder" в текущей папке, которая будет подтянута к использованию. В эту папку необходимо помещать файлы, которые будут видны образу Docker
|
238 |
+
```bash
|
239 |
+
mkdir input-folder && mkdir Audiobooks
|
240 |
+
```
|
241 |
+
|
242 |
+
- В команде ниже замените **YOUR_INPUT_FILE.TXT** именем файла, который необходимо начитать
|
243 |
+
|
244 |
+
```bash
|
245 |
+
docker run -it --rm \
|
246 |
+
-v $(pwd)/input-folder:/home/user/app/input_folder \
|
247 |
+
-v $(pwd)/Audiobooks:/home/user/app/Audiobooks \
|
248 |
+
--platform linux/amd64 \
|
249 |
+
athomasson2/ebook2audiobookxtts:huggingface \
|
250 |
+
python app.py --headless True --ebook /home/user/app/input_folder/YOUR_INPUT_FILE.TXT
|
251 |
+
```
|
252 |
+
|
253 |
+
- И на этом это всё!
|
254 |
+
|
255 |
+
- Начитанная аудиокнига будет сформирована в папке Audiobooks, которая будет создана в вашей локальной директории, в которой был осуществлен запуск Docker
|
256 |
+
|
257 |
+
|
258 |
+
## Для получения помощи по параметрам, необходимо запустить следующую команду
|
259 |
+
|
260 |
+
```bash
|
261 |
+
docker run -it --rm \
|
262 |
+
--platform linux/amd64 \
|
263 |
+
athomasson2/ebook2audiobookxtts:huggingface \
|
264 |
+
python app.py -h
|
265 |
+
|
266 |
+
```
|
267 |
+
|
268 |
+
|
269 |
+
и вывод будет следующим
|
270 |
+
|
271 |
+
```bash
|
272 |
+
user/app/ebook2audiobookXTTS/input-folder -v $(pwd)/Audiobooks:/home/user/app/ebook2audiobookXTTS/Audiobooks --memory="4g" --network none --platform linux/amd64 athomasson2/ebook2audiobookxtts:huggingface python app.py -h
|
273 |
+
starting...
|
274 |
+
Преобразование электронных книг в аудиокниги с использованием модели Text-to-Speech (TTS). Вы можете либо использовать
|
275 |
+
интерфейс Gradio, либо запустить скрипт в безинтерфейсном режиме (командная строка) для прямого конвертирования.
|
276 |
+
|
277 |
+
Опции:
|
278 |
+
-h, --help Отобразить этот список и выйти
|
279 |
+
--share SHARE Установить в True для включения публичного доступа к Web-интерфейсу Gradio. По умолчанию False.
|
280 |
+
--headless HEADLESS Установить в True для использования безинтерфейсного режима. По умолчанию False.
|
281 |
+
--ebook EBOOK Путь к электронной книге для конвертации. Необходимо для безинтерфейсного режима.
|
282 |
+
--voice VOICE Путь к целевому голосовому файлу для TTS (текст-в-голос). Опционально, используется голос по умолчанию, если путь не указан.
|
283 |
+
--language LANGUAGE Язык для конвертации в аудиокнигу. Варианты: en, es, fr, de,
|
284 |
+
it, pt, pl, tr, ru, nl, cs, ar, zh-cn, ja, hu, ko. По умолчанию English (en).
|
285 |
+
--use_custom_model USE_CUSTOM_MODEL
|
286 |
+
Установить в True для использования индивидуальной модели TTS. По умолчанию False. Необходимо переключить в
|
287 |
+
True для использования индивидуальной модели, в противном случае возникнет ошибка.
|
288 |
+
--custom_model CUSTOM_MODEL
|
289 |
+
Путь к файлу индивидуальной модели (.pth). Требуется, если используется индивидуальная модель.
|
290 |
+
--custom_config CUSTOM_CONFIG
|
291 |
+
Путь к конфигурационному файлу индивидуальной модели (config.json). Требуется, если используется индивидуальная модель.
|
292 |
+
--custom_vocab CUSTOM_VOCAB
|
293 |
+
Путь к словарю индивидуальной модели (vocab.json). Требуется, если используется индивидуальная модель.
|
294 |
+
--custom_model_url CUSTOM_MODEL_URL
|
295 |
+
URL для скачивания индивидуальной модели в виде zip-архива. Опционально, но если указано, то будет использовано.
|
296 |
+
Примеры включающие модель David Attenborough: 'https://huggingface.co/drewThomasson/xtts_David_Attenborough_fine_tune/resolve/main/Finished_model_files.zip?download=true'. Больше точно-настроенных моделей XTTS можно найти на Hugging Face 'https://huggingface.co/drewThomasson'.
|
297 |
+
--temperature TEMPERATURE
|
298 |
+
Температура для модели. По умолчанию 0.65. Чем выше температура, тем более креативным будет синтез голоса, с большим наваждением. Чем меньше, тем более монотонным и спокойным.
|
299 |
+
--length_penalty LENGTH_PENALTY
|
300 |
+
Ограничение длинны авторегрессионного декодера. По умолчанию 1.0. Не применяется к индивидуальным моделям.
|
301 |
+
--repetition_penalty REPETITION_PENALTY
|
302 |
+
Ограниечение предотвращающее повторение авторегрессивным декодером за собой. По умолчанию 2.0
|
303 |
+
--top_k TOP_K Сэмплирование Top-k. Меньшее значение приводит к более вероятностному выводу и ускоряют генерацию аудио. По умолчанию 50.
|
304 |
+
--top_p TOP_P Сэмплирование Top-p. Меньшее значение приводит к более вероятностному выводу и ускоряют генерацию аудио. По умолчанию 0.8.
|
305 |
+
--speed SPEED Фактор скорости начитки. Чем больше значение, тем быстрее диктор будет читать текст. По умолчанию 1.0.
|
306 |
+
--enable_text_splitting ENABLE_TEXT_SPLITTING
|
307 |
+
Включает разбиение текста на предложения. По умолчанию True.
|
308 |
+
|
309 |
+
Пример: python script.py --headless --ebook path_to_ebook --voice path_to_voice --language en --use_custom_model True --custom_model model.pth --custom_config config.json --custom_vocab vocab.json
|
310 |
+
```
|
311 |
+
</details>
|
312 |
+
|
313 |
+
#### 🖥️ Docker Web-интерфейс
|
314 |
+
![demo_web_gui](https://github.com/user-attachments/assets/85af88a7-05dd-4a29-91de-76a14cf5ef06)
|
315 |
+
|
316 |
+
<details>
|
317 |
+
<summary>Нажмите для просмотра изображений Web-интерфейса</summary>
|
318 |
+
<img width="1728" alt="image" src="https://github.com/user-attachments/assets/b36c71cf-8e06-484c-a252-934e6b1d0c2f">
|
319 |
+
<img width="1728" alt="image" src="https://github.com/user-attachments/assets/c0dab57a-d2d4-4658-bff9-3842ec90cb40">
|
320 |
+
<img width="1728" alt="image" src="https://github.com/user-attachments/assets/0a99eeac-c521-4b21-8656-e064c1adc528">
|
321 |
+
</details>
|
322 |
+
|
323 |
+
### 🛠️ Для индивидуальных Xtts моделей
|
324 |
+
|
325 |
+
Модели создаются для лучшего использования с конкретным голосом. Проверьте различные модели на страничке Hugging Face [тут](https://huggingface.co/drewThomasson).
|
326 |
+
|
327 |
+
Для использования инди��идуальных моделей, используйте ссылку на архив с моделью `Finished_model_files.zip`, например:
|
328 |
+
[David Attenborough точно настроенный голос Finished_model_files.zip](https://huggingface.co/drewThomasson/xtts_David_Attenborough_fine_tune/resolve/main/Finished_model_files.zip?download=true)
|
329 |
+
|
330 |
+
Для индивидуальной модели также необходим файл с голосом:
|
331 |
+
[файл с голосом David Attenborough](https://huggingface.co/drewThomasson/xtts_David_Attenborough_fine_tune/blob/main/ref.wav)
|
332 |
+
|
333 |
+
|
334 |
+
|
335 |
+
Больше информации можно найти на [странице Dockerfile Hub]([https://github.com/DrewThomasson/ebook2audiobookXTTS](https://hub.docker.com/repository/docker/athomasson2/ebook2audiobookxtts/general)).
|
336 |
+
|
337 |
+
## 🌐 Точно отстроенные модели Xtts models
|
338 |
+
|
339 |
+
Для поиска уже подготовленных точно настроенных моделей XTTS обратитесь к [этой страничке на Hugging Face](https://huggingface.co/drewThomasson) 🌐. Ищите модели которые имеют в наименовании "xtts fine tune".
|
340 |
+
|
341 |
+
## 🎥 Демонстрация
|
342 |
+
|
343 |
+
Голос ненастного дня
|
344 |
+
|
345 |
+
https://github.com/user-attachments/assets/8486603c-38b1-43ce-9639-73757dfb1031
|
346 |
+
|
347 |
+
Голос David Attenborough
|
348 |
+
|
349 |
+
https://github.com/user-attachments/assets/47c846a7-9e51-4eb9-844a-7460402a20a8
|
350 |
+
|
351 |
+
|
352 |
+
## 🤗 [Демонстрация в пространстве Huggingface](https://huggingface.co/spaces/drewThomasson/ebook2audiobookXTTS)
|
353 |
+
- Пространства на Huggingface работают на бесплатном уровне процессоров, поэтому выполнение очень медленное и часто возникают ошибки связанные с истечением времени. Не пытайтесь преобразовывать большие файлы.
|
354 |
+
- Лучше всего клонировать пространство или запускать его локально.
|
355 |
+
|
356 |
+
## Бесплатный Google Colab [![Бесплатный Google Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/DrewThomasson/ebook2audiobookXTTS/blob/main/Notebooks/colab_ebook2audiobookxtts.ipynb)
|
357 |
+
|
358 |
+
|
359 |
+
|
360 |
+
## 📚 Поддерживаемые форматы электронных книг
|
361 |
+
|
362 |
+
- **Можно**: `.epub`, `.pdf`, `.mobi`, `.txt`, `.html`, `.rtf`, `.chm`, `.lit`, `.pdb`, `.fb2`, `.odt`, `.cbr`, `.cbz`, `.prc`, `.lrf`, `.pml`, `.snb`, `.cbc`, `.rb`, `.tcr`
|
363 |
+
- **Лучше**: `.epub` или `.mobi` для автоматического определения глав.
|
364 |
+
|
365 |
+
## 📂 Вывод
|
366 |
+
|
367 |
+
- Создается файл с расширением `.m4b`, содержащий метаданные и главы.
|
368 |
+
- **Пример вывода**: ![Пример](https://github.com/DrewThomasson/VoxNovel/blob/dc5197dff97252fa44c391dc0596902d71278a88/readme_files/example_in_app.jpeg)
|
369 |
+
|
370 |
+
## 🛠️ Частые проблемы:
|
371 |
+
- "Очень медленно!" - При конвертации только на CPU она происходит медленно, единственный способ ускорения - использовать GPU от NVIDIA: [Обсуждение](https://github.com/DrewThomasson/ebook2audiobookXTTS/discussions/19#discussioncomment-10879846). Для быстрой многоязыковой генерации аудио, рекомендуется использовать другой проект, [использующий piper-tts](https://github.com/DrewThomasson/ebook2audiobookpiper-tts). (Тем не менее, в нем нет функции клонирования голоса без лишней суеты, и он воспроизводит голоса в качестве Siri, но он намного быстрее работает на CPU.)
|
372 |
+
- "У меня проблема с зависимостями" - Просто используйте Docker. Образы в Docker самодостаточны, имеют, в том числе, режим работы с командной строкой, ключ для вывода помощи.
|
373 |
+
- "У меня проблема с обрезаным аудио!" - создайте запись о проблеме, автор не говорит на каждом из поддерживаемых языков, и ему требуется помощь по автоматическому разбиению текста на предложения в поддерживаемых языках.😊
|
374 |
+
- "Процесс застопорился на 30% в Web-интерфейсе!" - Отображение прогресса в Web-интерфейсе выполнено на базовом уровне и содержит всего 3 шага, для контроллирования процесса посматривайте в терминальный вывод, где и отображается обработка текущего предложения.
|
375 |
+
|
376 |
+
## С чем требуется помощь! 🙌
|
377 |
+
## [Полный список тут](https://github.com/DrewThomasson/ebook2audiobookXTTS/issues/32)
|
378 |
+
- Любая помощь от людей, говорящих на поддерживаемых языках для более корректного разбиения текста на предложения.
|
379 |
+
- Потенциальная помощь в создании инструкций для разных языков (автор знает только английский 😔).
|
380 |
+
|
381 |
+
## 🙏 Отдельные спасибо
|
382 |
+
|
383 |
+
- **Coqui TTS**: [Coqui TTS GitHub](https://github.com/coqui-ai/TTS)
|
384 |
+
- **Calibre**: [Calibre Website](https://calibre-ebook.com)
|
385 |
+
|
386 |
+
- [@shakenbake15 за лучший способ сохранения глав](https://github.com/DrewThomasson/ebook2audiobookXTTS/issues/8)
|
387 |
+
|
legacy/v1.0/samples/Supported_language_sample__generated_outputs/ar.m4b
ADDED
Binary file (456 kB). View file
|
|
legacy/v1.0/samples/Supported_language_sample__generated_outputs/cs.m4b
ADDED
Binary file (400 kB). View file
|
|
legacy/v1.0/samples/Supported_language_sample__generated_outputs/de.m4b
ADDED
Binary file (420 kB). View file
|
|
legacy/v1.0/samples/Supported_language_sample__generated_outputs/en.m4b
ADDED
Binary file (432 kB). View file
|
|
legacy/v1.0/samples/Supported_language_sample__generated_outputs/es.m4b
ADDED
Binary file (499 kB). View file
|
|
legacy/v1.0/samples/Supported_language_sample__generated_outputs/fr.m4b
ADDED
Binary file (412 kB). View file
|
|
legacy/v1.0/samples/Supported_language_sample__generated_outputs/hu.m4b
ADDED
Binary file (365 kB). View file
|
|
legacy/v1.0/samples/Supported_language_sample__generated_outputs/it.m4b
ADDED
Binary file (503 kB). View file
|
|
legacy/v1.0/samples/Supported_language_sample__generated_outputs/ko.m4b
ADDED
Binary file (440 kB). View file
|
|
legacy/v1.0/samples/Supported_language_sample__generated_outputs/nl.m4b
ADDED
Binary file (411 kB). View file
|
|
legacy/v1.0/samples/Supported_language_sample__generated_outputs/pl.m4b
ADDED
Binary file (413 kB). View file
|
|
legacy/v1.0/samples/Supported_language_sample__generated_outputs/pt.m4b
ADDED
Binary file (477 kB). View file
|
|
legacy/v1.0/samples/Supported_language_sample__generated_outputs/ru.m4b
ADDED
Binary file (412 kB). View file
|
|
legacy/v1.0/samples/Supported_language_sample__generated_outputs/tr.m4b
ADDED
Binary file (356 kB). View file
|
|
legacy/v1.0/samples/Supported_language_sample__generated_outputs/zh-cn.m4b
ADDED
Binary file (400 kB). View file
|
|
legacy/v1.0/samples/Supported_language_sample_texts/ar.txt
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
في البداية كان هناك نور، وظهر العالم إلى الوجود. ارتفعت الجبال، جرت الأنهار، وازدهرت الغابات بالحياة. ومع شروق الشمس كل يوم، اكتشف الناس عجائب الأرض. بنوا المنازل، شكلوا المجتمعات، وبدأوا في تأسيس الحضارات. مع مرور الوقت، انتقلت المعرفة من جيل إلى جيل، حاملةً معها القدرة على تشكيل المستقبل. ومن خلال الانتصارات والتحديات، واصلت البشرية النمو، واستكشفت أسرار الكون الواسعة.
|
legacy/v1.0/samples/Supported_language_sample_texts/cs.txt
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
Na počátku bylo světlo, a svět vznikl. Hory se zvedly, řeky tekly a lesy se rozkvétaly životem. Každý den s východem slunce lidé objevovali zázraky Země. Stavěli domy, tvořili komunity a zakládali civilizace. Časem se znalosti předávaly dál a přinášely s sebou moc formovat budoucnost. Prostřednictvím triumfů a výzev lidstvo stále rostlo a zkoumalo nekonečná tajemství vesmíru.
|
legacy/v1.0/samples/Supported_language_sample_texts/de.txt
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
Am Anfang war Licht, und die Welt entstand. Berge erhoben sich, Flüsse flossen, und Wälder erblühten mit Leben. Als die Sonne jeden Tag aufging, entdeckten die Menschen die Wunder der Erde. Sie bauten Häuser, gründeten Gemeinschaften und begannen Zivilisationen. Mit der Zeit wurde Wissen weitergegeben, und mit ihm die Fähigkeit, die Zukunft zu gestalten. Durch Erfolge und Herausforderungen wuchs die Menschheit weiter und erforschte die weiten Geheimnisse des Universums.
|