mirror of
https://github.com/denizsafak/abogen.git
synced 2026-07-18 13:40:27 +02:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8f8ad3ec26 | ||
|
|
67b35d1dfb | ||
|
|
15f1eb7f1e | ||
|
|
146fcb3c1f | ||
|
|
412fb3bc7e | ||
|
|
d9b6081a06 | ||
|
|
674fc14813 | ||
|
|
fa144561fb | ||
|
|
1d27f6fd2e | ||
|
|
a03120d66f | ||
|
|
68b44a3516 | ||
|
|
3bbb88d446 | ||
|
|
a1ccd51ea0 | ||
|
|
13cf6f20a4 | ||
|
|
4311ed51d4 | ||
|
|
9170d9ae3e | ||
|
|
593d21675e | ||
|
|
9aebdecc60 | ||
|
|
290d246e80 | ||
|
|
5ac6e3bb2a | ||
|
|
6bf189312a | ||
|
|
22fdccd78d | ||
|
|
62aeaecf89 | ||
|
|
a7a41fa4f6 | ||
|
|
1ca4d0d5f9 | ||
|
|
e09535fa83 | ||
|
|
0863b25d82 | ||
|
|
b02416e068 | ||
|
|
8daa3cb3b5 |
+5
-6
@@ -1,6 +1,5 @@
|
||||
- Merge pull request [#7](https://github.com/denizsafak/abogen/pull/7) by [@jborza](https://github.com/jborza) that improves voice preview and documentation.
|
||||
- Fixed the issue when a voice is selected, the voice mixer tries to pre-select that voice and ignores existing profiles.
|
||||
- Fixed the error while renaming the default "New profile" in the voice mixer.
|
||||
- Fixed subtitle_combo enabling/disabling when a voice in the voice mixer is selected.
|
||||
- Prevented using special characters in the profile name to avoid conflicts.
|
||||
- Improved invalid profile handling in the voice mixer.
|
||||
- Added `Insert chapter marker` button in text editor to insert chapter markers at the current cursor position.
|
||||
- Added `Preview` button in voice mixer to preview the voice mix with the selected settings.
|
||||
- Fixed `f-string: unmatched '['` error in Voice preview, mentioned in #14
|
||||
- Fixed the issue with the content before first chapter not being included in the output.
|
||||
- Fixed m4b chapter generation opens CMD window in Windows.
|
||||
@@ -85,12 +85,12 @@ Here’s Abogen in action: in this demo, it processes ∼3,000 characters of tex
|
||||
- **Voices**: First letter of the language code (e.g., `a` for American English, `b` for British English, etc.), second letter is for `m` for male and `f` for female.
|
||||
- **Voice mixer**: Create custom voices by mixing different voice models with a profile system.
|
||||
- **Generate subtitles**: `Disabled`, `Sentence`, `Sentence + Comma`, `1 word`, `2 words`, `3 words`, etc. (Represents the number of words in each subtitle entry)
|
||||
- **Output formats**: `.WAV`, `.FLAC`, or `.MP3`
|
||||
- **Output formats**: `.WAV`, `.FLAC`, `.MP3`, and `M4B (with chapters)` (Special thanks to [@jborza](https://github.com/jborza) for chapter support in PR [#10](https://github.com/denizsafak/abogen/pull/10))
|
||||
- **Save location**: `Save next to input file`, `Save to desktop`, or `Choose output folder`
|
||||
- **Chapter Control**: Select specific `chapters` from ePUBs or `chapters + pages` from PDFs.
|
||||
- **Options**:
|
||||
- **Replace single newlines with spaces**: Replaces single newlines with spaces in the text. This is useful for texts that have imaginary line breaks.
|
||||
- **Configure max words per subtitle**: Automatically configures the maximum number of words per subtitle entry.
|
||||
- **Configure max words per subtitle**: Configures the maximum number of words per subtitle entry.
|
||||
- **Create desktop shortcut**: Creates a shortcut on your desktop for easy access.
|
||||
- **Open config.json directory**: Opens the directory where the configuration file is stored.
|
||||
- **Open temp directory**: Opens the temporary directory where converted text files are stored.
|
||||
@@ -103,6 +103,30 @@ Here’s Abogen in action: in this demo, it processes ∼3,000 characters of tex
|
||||
|
||||
With voice mixer, you can create custom voices by mixing different voice models. You can adjust the weight of each voice and save your custom voice as a profile for future use. The voice mixer allows you to create unique and personalized voices. (Huge thanks to [@jborza](https://github.com/jborza) for making this possible through his contributions in [#5](https://github.com/denizsafak/abogen/pull/5))
|
||||
|
||||
## `About Chapter Markers`
|
||||
When you process ePUB or PDF files, abogen converts them into text files stored in your temporary directory. When you click "Edit," you're actually modifying these converted text files. In these text files, you'll notice tags that look like this:
|
||||
|
||||
```
|
||||
<<CHAPTER_MARKER:Chapter Title>>
|
||||
```
|
||||
These are chapter markers. They are automatically added when you process ePUB or PDF files, based on the chapters you select. They serve an important purpose:
|
||||
- Allow you to split the text into separate audio files for each chapter
|
||||
- Save time by letting you reprocess only specific chapters if errors occur, rather than the entire file
|
||||
|
||||
You can manually add these markers to plain text files for the same benefits. Simply include them in your text like this:
|
||||
|
||||
```
|
||||
<<CHAPTER_MARKER:Introduction>>
|
||||
This is the beginning of my text...
|
||||
|
||||
<<CHAPTER_MARKER:Main Content>>
|
||||
Here's another part...
|
||||
```
|
||||
When you process the text file, abogen will detect these markers automatically and ask if you want to save each chapter separately and create a merged version.
|
||||
|
||||

|
||||
|
||||
|
||||
## `Supported Languages`
|
||||
```
|
||||
# 🇺🇸 'a' => American English, 🇬🇧 'b' => British English
|
||||
@@ -131,6 +155,42 @@ audio-samplerate=48000
|
||||
volume-max=200
|
||||
```
|
||||
|
||||
## `Docker Guide`
|
||||
If you want to run Abogen in a Docker container:
|
||||
1) [Download the repository](https://github.com/denizsafak/abogen/archive/refs/heads/main.zip) and extract, or clone it using git.
|
||||
2) Go to `abogen` folder. You should see `Dockerfile` there.
|
||||
3) Open your termminal in that directory and run the following commands:
|
||||
|
||||
```bash
|
||||
# Build the Docker image:
|
||||
docker build --progress plain -t abogen .
|
||||
|
||||
# Note that building the image may take a while.
|
||||
# After building is complete, run the Docker container:
|
||||
|
||||
# Windows
|
||||
docker run --name abogen -v %cd%:/shared -p 5800:5800 -p 5900:5900 --gpus all abogen
|
||||
|
||||
# Linux
|
||||
docker run --name abogen -v $(pwd):/shared -p 5800:5800 -p 5900:5900 --gpus all abogen
|
||||
|
||||
# MacOS
|
||||
docker run --name abogen -v $(pwd):/shared -p 5800:5800 -p 5900:5900 abogen
|
||||
|
||||
# We expose port 5800 for use by a web browser, 5900 if you want to connect with a VNC client.
|
||||
```
|
||||
|
||||
Abogen launches automatically inside the container.
|
||||
- You can access it via a web browser at [http://localhost:5800](http://localhost:5800) or connect to it using a VNC client at `localhost:5900`.
|
||||
- You can use `/shared` directory to share files between your host and the container.
|
||||
- For later use, start it with `docker start abogen` and stop it with `docker stop abogen`.
|
||||
|
||||
Known issues:
|
||||
- Audio preview is not working inside container (ALSA error).
|
||||
- `Open temp directory` and `Open configuration directory` options in settings not working. (Tried pcmanfm, did not work with abogen).
|
||||
|
||||
(Special thanks to [@geo38](https://www.reddit.com/user/geo38/) from Reddit, who provided the Dockerfile and instructions in [this comment](https://www.reddit.com/r/selfhosted/comments/1k8x1yo/comment/mpe0bz8/).)
|
||||
|
||||
## `Similar Projects`
|
||||
Abogen is a standalone project, but it is inspired by and shares some similarities with other projects. Here are a few:
|
||||
- [audiblez](https://github.com/santinic/audiblez): Generate audiobooks from e-books. **(Has CLI and GUI support)**
|
||||
@@ -140,9 +200,9 @@ Abogen is a standalone project, but it is inspired by and shares some similariti
|
||||
|
||||
## `Roadmap`
|
||||
- [ ] Improve PDF support for better text extraction.
|
||||
- [ ] Add chapter metadata for .m4a files using ffmpeg-bin.
|
||||
- [x] Add chapter metadata for .m4a files. (Issue [#9](https://github.com/denizsafak/abogen/issues/9), PR [#10](https://github.com/denizsafak/abogen/pull/10))
|
||||
- [ ] Add support for different languages in GUI.
|
||||
- [x] Add voice formula feature that enables mixing different voice models. #1
|
||||
- [x] Add voice formula feature that enables mixing different voice models. (Issue [#1](https://github.com/denizsafak/abogen/issues/1), PR [#5](https://github.com/denizsafak/abogen/pull/5))
|
||||
- [ ] Add support for kokoro-onnx.
|
||||
- [ ] Add dark mode.
|
||||
|
||||
|
||||
+1
-1
@@ -221,7 +221,7 @@ if errorlevel 1 (
|
||||
|
||||
:: Install setup requirements
|
||||
echo Installing setup requirements...
|
||||
%PYTHON_CONSOLE_PATH% -m pip install --upgrade setuptools wheel sphinx hatchling --no-warn-script-location
|
||||
%PYTHON_CONSOLE_PATH% -m pip install --upgrade setuptools wheel sphinx hatchling progress --no-warn-script-location
|
||||
if errorlevel 1 (
|
||||
echo Failed to install setup requirements.
|
||||
pause
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
# Special thanks to @geo38 from Reddit, who provided this Dockerfile:
|
||||
# https://www.reddit.com/r/selfhosted/comments/1k8x1yo/comment/mpe0bz8/
|
||||
|
||||
# Use a docker base image that runs a window manager that can be viewed
|
||||
# outside the image with a web browser or VNC client.
|
||||
# https://github.com/jlesage/docker-baseimage-gui
|
||||
FROM jlesage/baseimage-gui:debian-12-v4
|
||||
|
||||
# Load stuff needed by abogen
|
||||
RUN apt-get update \
|
||||
&& apt-get install -y \
|
||||
python3 \
|
||||
python3-venv \
|
||||
python3-pip \
|
||||
python3-pyqt5 \
|
||||
espeak-ng \
|
||||
&& apt-get clean \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
# The base image will run /startapp.sh on launch.
|
||||
#
|
||||
# The base image runs that script as user 'app' uid=1000. That user
|
||||
# does not exist in the base image but is created at run time.
|
||||
#
|
||||
# We need to install abogen in python venv (requirement of newer python3).
|
||||
#
|
||||
# The python venv has to be writable by the 'app' user as abogen dynamically
|
||||
# installs python packages, so create the venv as that user
|
||||
#
|
||||
# We intend to share the /shared directory with the host using a bind volume
|
||||
# in order to access any source files and the created files.
|
||||
|
||||
RUN echo '#!/bin/bash\nsource /app/venv/bin/activate\nexec abogen' > /startapp.sh \
|
||||
&& chmod 555 /startapp.sh \
|
||||
&& mkdir /app /shared \
|
||||
&& chown 1000:1000 /app /shared \
|
||||
&& chmod 755 /app /shared
|
||||
USER 1000:1000
|
||||
RUN python3 -m venv /app/venv
|
||||
RUN /bin/bash -c "source /app/venv/bin/activate && pip install abogen"
|
||||
# Change back to user ROOT as the startup scripts inside base image needs it
|
||||
USER root
|
||||
+1
-1
@@ -1 +1 @@
|
||||
1.0.4
|
||||
1.0.6
|
||||
+137
-10
@@ -11,6 +11,11 @@ import soundfile as sf
|
||||
from utils import clean_text
|
||||
from constants import PROGRAM_NAME, LANGUAGE_DESCRIPTIONS, SAMPLE_VOICE_TEXTS
|
||||
from voice_formulas import get_new_voice
|
||||
import static_ffmpeg
|
||||
import threading # for efficient waiting
|
||||
import subprocess
|
||||
import sys
|
||||
import platform
|
||||
|
||||
|
||||
def get_sample_voice_text(lang_code):
|
||||
@@ -128,6 +133,7 @@ class ConversionThread(QThread):
|
||||
use_gpu=True,
|
||||
): # Add use_gpu parameter
|
||||
super().__init__()
|
||||
self._chapter_options_event = threading.Event()
|
||||
self.np = np_module
|
||||
self.KPipeline = kpipeline_class
|
||||
self.file_name = file_name
|
||||
@@ -222,6 +228,12 @@ class ConversionThread(QThread):
|
||||
chapter_splits = list(re.finditer(chapter_pattern, text))
|
||||
chapters = []
|
||||
if chapter_splits:
|
||||
# prepend Introduction for content before first marker
|
||||
first_start = chapter_splits[0].start()
|
||||
if first_start > 0:
|
||||
intro_text = text[:first_start].strip()
|
||||
if intro_text:
|
||||
chapters.append(("Introduction", intro_text))
|
||||
for idx, match in enumerate(chapter_splits):
|
||||
start = match.end()
|
||||
end = (
|
||||
@@ -252,18 +264,12 @@ class ConversionThread(QThread):
|
||||
and not self.chapter_options_set
|
||||
):
|
||||
|
||||
self.waiting_for_user_input = True
|
||||
# Emit signal to main thread to show dialog
|
||||
# Emit signal to main thread and wait
|
||||
self.chapters_detected.emit(total_chapters)
|
||||
|
||||
# Wait for chapter options to be set
|
||||
while self.waiting_for_user_input and not self.cancel_requested:
|
||||
time.sleep(0.1)
|
||||
|
||||
self._chapter_options_event.wait()
|
||||
if self.cancel_requested:
|
||||
self.conversion_finished.emit("Cancelled", None)
|
||||
return
|
||||
|
||||
self.chapter_options_set = True
|
||||
|
||||
# Log all detected chapters at the beginning
|
||||
@@ -339,6 +345,12 @@ class ConversionThread(QThread):
|
||||
# Initialize current segment counter
|
||||
current_segment = 0
|
||||
|
||||
# Initialize chapter times
|
||||
chapters_time = [
|
||||
{"chapter": chapter[0], "start": 0.0, "end": 0.0}
|
||||
for chapter in chapters
|
||||
]
|
||||
|
||||
# Instead of processing the whole text, process by chapter
|
||||
for chapter_idx, (chapter_name, chapter_text) in enumerate(chapters, 1):
|
||||
if total_chapters > 1:
|
||||
@@ -354,6 +366,10 @@ class ConversionThread(QThread):
|
||||
chapter_subtitle_entries = []
|
||||
chapter_current_time = 0.0
|
||||
|
||||
# chapter start time
|
||||
chapter_time = chapters_time[chapter_idx - 1]
|
||||
chapter_time["start"] = current_time
|
||||
|
||||
# Set split_pattern to \n+ which will split on one or more newlines
|
||||
split_pattern = r"\n+"
|
||||
|
||||
@@ -467,6 +483,9 @@ class ConversionThread(QThread):
|
||||
# Update progress more frequently (after each result)
|
||||
self.progress_updated.emit(percent, etr_str)
|
||||
|
||||
# Update chapter end time
|
||||
chapter_time["end"] = current_time
|
||||
|
||||
# Save the individual chapter output if save_chapters_separately is enabled
|
||||
if (
|
||||
save_chapters_separately
|
||||
@@ -483,14 +502,20 @@ class ConversionThread(QThread):
|
||||
|
||||
# Concatenate chapter audio and save
|
||||
chapter_audio = self.np.concatenate(chapter_audio_segments)
|
||||
# If output format is m4b, save chapter as wav
|
||||
chapter_ext = self.output_format
|
||||
chapter_format = self.output_format
|
||||
if self.output_format == "m4b":
|
||||
chapter_ext = "wav"
|
||||
chapter_format = "wav"
|
||||
chapter_out_path = os.path.join(
|
||||
chapters_out_dir, f"{chapter_filename}.{self.output_format}"
|
||||
chapters_out_dir, f"{chapter_filename}.{chapter_ext}"
|
||||
)
|
||||
sf.write(
|
||||
chapter_out_path,
|
||||
chapter_audio,
|
||||
24000,
|
||||
format=self.output_format,
|
||||
format=chapter_format,
|
||||
)
|
||||
|
||||
# Generate .srt subtitle file for chapter if not Disabled
|
||||
@@ -531,6 +556,7 @@ class ConversionThread(QThread):
|
||||
or not self.save_chapters_separately
|
||||
or getattr(self, "merge_chapters_at_end", True)
|
||||
)
|
||||
m4b_picked = False # Ensure m4b_picked is always defined
|
||||
if audio_segments and merge_chapters:
|
||||
self.log_updated.emit("\nFinalizing audio file...\n")
|
||||
audio = self.np.concatenate(audio_segments)
|
||||
@@ -539,7 +565,16 @@ class ConversionThread(QThread):
|
||||
out_filename = f"{base_name}{suffix}.{self.output_format}"
|
||||
out_path = os.path.join(out_dir, out_filename)
|
||||
srt_path = os.path.splitext(out_path)[0] + ".srt"
|
||||
|
||||
# in case the user picked m4b format, we need to change the output format to wav
|
||||
if self.output_format == "m4b":
|
||||
out_path = os.path.splitext(out_path)[0] + ".wav"
|
||||
self.output_format = "wav"
|
||||
m4b_picked = True
|
||||
sf.write(out_path, audio, 24000, format=self.output_format)
|
||||
if m4b_picked:
|
||||
out_path = self._generate_m4b_with_chapters(out_path, chapters_time)
|
||||
|
||||
if self.subtitle_mode != "Disabled":
|
||||
with open(
|
||||
srt_path, "w", encoding="utf-8", errors="replace"
|
||||
@@ -579,6 +614,98 @@ class ConversionThread(QThread):
|
||||
self.save_chapters_separately = options["save_chapters_separately"]
|
||||
self.merge_chapters_at_end = options["merge_chapters_at_end"]
|
||||
self.waiting_for_user_input = False
|
||||
self._chapter_options_event.set()
|
||||
|
||||
def _generate_m4b_with_chapters(self, out_path, chapters_time):
|
||||
# If there is only one chapter, skip adding chapters and just return the wav file path
|
||||
if not chapters_time or len(chapters_time) <= 1:
|
||||
self.log_updated.emit(
|
||||
(
|
||||
"File contains only one chapter or no chapters were detected. The audio will be saved as a standard .wav file instead.\n",
|
||||
"red",
|
||||
)
|
||||
)
|
||||
return out_path
|
||||
# generate chapters.txt in the same folder as the output file
|
||||
chapters_info_path = os.path.splitext(out_path)[0] + "_chapters.txt"
|
||||
with open(chapters_info_path, "w", encoding="utf-8") as f:
|
||||
f.write(";FFMETADATA1\n") # required header for ffmpeg
|
||||
for chapter in chapters_time:
|
||||
f.write(f"[CHAPTER]\n")
|
||||
f.write(f"TIMEBASE=1/10\n")
|
||||
# use 10th of second for start/end time
|
||||
f.write(f"START={int(chapter['start']*10)}\n")
|
||||
f.write(f"END={int(chapter['end']*10)}\n")
|
||||
f.write(f"title={chapter['chapter']}\n\n")
|
||||
# call ffmpeg to merge the chapters into the output file
|
||||
# ffmpeg installed on first call to add_paths()
|
||||
static_ffmpeg.add_paths()
|
||||
out_path_m4b = os.path.splitext(out_path)[0] + ".m4b"
|
||||
# ffmpeg -i input.m4b -i ch.txt -map 0:a -map_chapters 1 output.m4b
|
||||
ffmpeg_cmd = [
|
||||
"ffmpeg",
|
||||
"-i",
|
||||
out_path,
|
||||
"-i",
|
||||
chapters_info_path,
|
||||
"-map",
|
||||
"0:a",
|
||||
"-map_chapters",
|
||||
"1",
|
||||
out_path_m4b,
|
||||
]
|
||||
|
||||
self.log_updated.emit("Adding chapters to the audio file...\n")
|
||||
|
||||
# Define kwargs for Popen
|
||||
default_encoding = sys.getdefaultencoding() # Get default encoding
|
||||
kwargs = {
|
||||
"stdout": subprocess.PIPE,
|
||||
"stderr": subprocess.PIPE, # Capture stderr separately
|
||||
"universal_newlines": True,
|
||||
"encoding": default_encoding,
|
||||
"errors": "replace",
|
||||
}
|
||||
|
||||
# Add Windows-specific settings
|
||||
if platform.system() == "Windows":
|
||||
startupinfo = subprocess.STARTUPINFO()
|
||||
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
|
||||
startupinfo.wShowWindow = subprocess.SW_HIDE
|
||||
kwargs.update(
|
||||
{
|
||||
"startupinfo": startupinfo,
|
||||
"creationflags": subprocess.CREATE_NO_WINDOW,
|
||||
}
|
||||
)
|
||||
|
||||
# Use Popen instead of run
|
||||
process = subprocess.Popen(ffmpeg_cmd, **kwargs)
|
||||
stdout, stderr = process.communicate() # Get stdout and stderr
|
||||
|
||||
# Check for errors in the ffmpeg command
|
||||
if process.returncode != 0:
|
||||
self.log_updated.emit((f"FFmpeg error (stderr):\n{stderr}", "red"))
|
||||
if stdout: # Log stdout as well if it exists
|
||||
self.log_updated.emit((f"FFmpeg output (stdout):\n{stdout}", "orange"))
|
||||
# Log error but continue with original file
|
||||
self.log_updated.emit(
|
||||
("Falling back to the original audio file without chapters\n", "orange")
|
||||
)
|
||||
# Clean up chapters file even on error
|
||||
if os.path.exists(chapters_info_path):
|
||||
os.remove(chapters_info_path)
|
||||
return out_path
|
||||
else:
|
||||
self.log_updated.emit(
|
||||
("Successfully added chapters to the audio file.\n", "green")
|
||||
)
|
||||
|
||||
# delete the chapters path and original (wav) file
|
||||
os.remove(chapters_info_path)
|
||||
os.remove(out_path)
|
||||
# the new file is in m4b format - use that for messages
|
||||
return out_path_m4b
|
||||
|
||||
def _srt_time(self, t):
|
||||
"""Helper function to format time for SRT files"""
|
||||
|
||||
+49
-10
@@ -290,8 +290,8 @@ class InputBox(QLabel):
|
||||
)
|
||||
win.selected_book_path = file_path
|
||||
win.open_book_file(
|
||||
file_path
|
||||
) # This will handle the dialog and setting file info
|
||||
file_path # This will handle the dialog and setting file info
|
||||
)
|
||||
event.acceptProposedAction()
|
||||
else:
|
||||
self.set_error("Please drop a .txt, .epub, or .pdf file.")
|
||||
@@ -328,7 +328,7 @@ class TextboxDialog(QDialog):
|
||||
self.setWindowFlags(
|
||||
Qt.Window | Qt.WindowCloseButtonHint | Qt.WindowMaximizeButtonHint
|
||||
)
|
||||
self.resize(600, 400)
|
||||
self.resize(700, 500)
|
||||
|
||||
layout = QVBoxLayout(self)
|
||||
|
||||
@@ -358,6 +358,11 @@ class TextboxDialog(QDialog):
|
||||
self.save_as_button.clicked.connect(self.save_as_text)
|
||||
self.save_as_button.setToolTip("Save the current text to a file")
|
||||
|
||||
self.insert_chapter_btn = QPushButton("Insert Chapter Marker", self)
|
||||
self.insert_chapter_btn.setToolTip("Insert a chapter marker at the cursor")
|
||||
self.insert_chapter_btn.clicked.connect(self.insert_chapter_marker)
|
||||
button_layout.addWidget(self.insert_chapter_btn)
|
||||
|
||||
self.cancel_button = QPushButton("Cancel", self)
|
||||
self.cancel_button.clicked.connect(self.reject)
|
||||
|
||||
@@ -444,6 +449,13 @@ class TextboxDialog(QDialog):
|
||||
except Exception as e:
|
||||
QMessageBox.critical(self, "Save Error", f"Could not save file:\n{e}")
|
||||
|
||||
def insert_chapter_marker(self):
|
||||
# Insert a fixed chapter marker without prompting
|
||||
cursor = self.text_edit.textCursor()
|
||||
cursor.insertText("<<CHAPTER_MARKER:Title>>")
|
||||
self.text_edit.setTextCursor(cursor)
|
||||
self.update_char_count()
|
||||
|
||||
|
||||
class abogen(QWidget):
|
||||
def __init__(self):
|
||||
@@ -673,10 +685,22 @@ class abogen(QWidget):
|
||||
self.format_combo.setStyleSheet(
|
||||
"QComboBox { min-height: 20px; padding: 6px 12px; }"
|
||||
)
|
||||
format_options = ["wav", "flac", "mp3"]
|
||||
self.format_combo.addItems(format_options)
|
||||
self.format_combo.setCurrentText(self.selected_format)
|
||||
self.format_combo.currentTextChanged.connect(self.on_format_changed)
|
||||
# Add items with display labels and underlying keys
|
||||
for key, label in [
|
||||
("wav", "wav"),
|
||||
("flac", "flac"),
|
||||
("mp3", "mp3"),
|
||||
("m4b", "m4b (with chapters)"),
|
||||
]:
|
||||
self.format_combo.addItem(label, key)
|
||||
# Initialize selection by matching saved key
|
||||
idx = self.format_combo.findData(self.selected_format)
|
||||
if idx >= 0:
|
||||
self.format_combo.setCurrentIndex(idx)
|
||||
# Map selection back to key on change
|
||||
self.format_combo.currentIndexChanged.connect(
|
||||
lambda i: self.on_format_changed(self.format_combo.itemData(i))
|
||||
)
|
||||
format_layout.addWidget(self.format_combo)
|
||||
controls_layout.addLayout(format_layout)
|
||||
# Save location
|
||||
@@ -1432,7 +1456,21 @@ class abogen(QWidget):
|
||||
self.voice_combo.setEnabled(False)
|
||||
self.btn_voice_formula_mixer.setEnabled(False) # Disable mixer button
|
||||
self.btn_start.setEnabled(False) # Disable start button during preview
|
||||
# start loading animation
|
||||
|
||||
# Start loading animation - ensure signal connection is always active
|
||||
if hasattr(self, "loading_movie"):
|
||||
# Disconnect previous connections to avoid multiple connections
|
||||
try:
|
||||
self.loading_movie.frameChanged.disconnect()
|
||||
except TypeError:
|
||||
pass # Ignore error if not connected
|
||||
|
||||
# Reconnect the signal
|
||||
self.loading_movie.frameChanged.connect(
|
||||
lambda: self.btn_preview.setIcon(
|
||||
QIcon(self.loading_movie.currentPixmap())
|
||||
)
|
||||
)
|
||||
self.loading_movie.start()
|
||||
|
||||
def pipeline_loaded_callback(np_module, kpipeline_class, error):
|
||||
@@ -1462,14 +1500,14 @@ class abogen(QWidget):
|
||||
# Build voice formula string
|
||||
components = [f"{name}*{weight}" for name, weight in self.mixed_voice_state]
|
||||
voice = " + ".join(filter(None, components))
|
||||
# determine language: use profile setting if available, else first voice code
|
||||
# determine language: use profile setting, else explicit mixer selection, else fallback to first voice code
|
||||
if self.selected_profile_name:
|
||||
from voice_profiles import load_profiles
|
||||
|
||||
entry = load_profiles().get(self.selected_profile_name, {})
|
||||
lang = entry.get("language")
|
||||
else:
|
||||
lang = None
|
||||
lang = self.selected_lang
|
||||
if not lang and self.mixed_voice_state:
|
||||
lang = (
|
||||
self.mixed_voice_state[0][0][0]
|
||||
@@ -1829,6 +1867,7 @@ class abogen(QWidget):
|
||||
|
||||
def show_voice_formula_dialog(self):
|
||||
from voice_profiles import load_profiles
|
||||
|
||||
profiles = load_profiles()
|
||||
initial_state = None
|
||||
selected_profile = self.selected_profile_name
|
||||
|
||||
+13
-3
@@ -66,10 +66,20 @@ def get_version():
|
||||
|
||||
# Define config path
|
||||
def get_user_config_path():
|
||||
if os.name == "nt":
|
||||
config_dir = os.path.join(os.environ["APPDATA"], "abogen")
|
||||
from platformdirs import user_config_dir
|
||||
|
||||
# TODO Config directory is changed for Linux and MacOS. But if old config exists, it will be used.
|
||||
# On non‑Windows, prefer ~/.config/abogen if it already exists
|
||||
if platform.system() != "Windows":
|
||||
custom_dir = os.path.join(os.path.expanduser("~"), ".config", "abogen")
|
||||
if os.path.exists(custom_dir):
|
||||
config_dir = custom_dir
|
||||
else:
|
||||
config_dir = os.path.join(os.path.expanduser("~"), ".config", "abogen")
|
||||
config_dir = user_config_dir("abogen", appauthor=False, roaming=True)
|
||||
else:
|
||||
# Windows and fallback case
|
||||
config_dir = user_config_dir("abogen", appauthor=False, roaming=True)
|
||||
|
||||
os.makedirs(config_dir, exist_ok=True)
|
||||
return os.path.join(config_dir, "config.json")
|
||||
|
||||
|
||||
@@ -47,7 +47,7 @@ VOICE_MIXER_WIDTH = 100
|
||||
SLIDER_WIDTH = 32
|
||||
MIN_WINDOW_WIDTH = 600
|
||||
MIN_WINDOW_HEIGHT = 400
|
||||
INITIAL_WINDOW_WIDTH = 1000
|
||||
INITIAL_WINDOW_WIDTH = 1200
|
||||
INITIAL_WINDOW_HEIGHT = 500
|
||||
|
||||
# Language options for the language selector loaded from constants
|
||||
@@ -413,6 +413,11 @@ class VoiceFormulaDialog(QDialog):
|
||||
self.language_combo.setCurrentIndex(idx)
|
||||
self.language_combo.currentIndexChanged.connect(self.mark_profile_modified)
|
||||
header_row.addWidget(self.language_combo)
|
||||
# Preview current voice mix using main window's preview
|
||||
self.btn_preview_mix = QPushButton("Preview", self)
|
||||
self.btn_preview_mix.setToolTip("Preview current voice mix")
|
||||
self.btn_preview_mix.clicked.connect(self.preview_current_mix)
|
||||
header_row.addWidget(self.btn_preview_mix)
|
||||
mixer_layout.addLayout(header_row)
|
||||
|
||||
# Error message
|
||||
@@ -708,6 +713,9 @@ class VoiceFormulaDialog(QDialog):
|
||||
]
|
||||
|
||||
total = sum(w for _, w in selected)
|
||||
# disable Preview if no voices selected, but don't enable while loading
|
||||
if not getattr(self, "_loading", False):
|
||||
self.btn_preview_mix.setEnabled(total > 0)
|
||||
|
||||
if total > 0:
|
||||
self.error_label.hide()
|
||||
@@ -943,6 +951,7 @@ class VoiceFormulaDialog(QDialog):
|
||||
|
||||
def new_profile(self):
|
||||
import re
|
||||
|
||||
while True:
|
||||
name, ok = QInputDialog.getText(self, "New Profile", "Enter profile name:")
|
||||
if not ok or not name:
|
||||
@@ -950,8 +959,12 @@ class VoiceFormulaDialog(QDialog):
|
||||
name = name.strip() # Remove leading/trailing spaces
|
||||
if not name:
|
||||
continue
|
||||
if not re.match(r'^[\w\- ]+$', name):
|
||||
QMessageBox.warning(self, "Invalid Name", "Profile name can only contain letters, numbers, spaces, underscores, and hyphens.")
|
||||
if not re.match(r"^[\w\- ]+$", name):
|
||||
QMessageBox.warning(
|
||||
self,
|
||||
"Invalid Name",
|
||||
"Profile name can only contain letters, numbers, spaces, underscores, and hyphens.",
|
||||
)
|
||||
continue
|
||||
profiles = load_profiles()
|
||||
# Remove 'New profile' placeholder if not persisted in JSON
|
||||
@@ -1173,13 +1186,16 @@ class VoiceFormulaDialog(QDialog):
|
||||
def rename_profile(self, item):
|
||||
name = item.text().lstrip("*")
|
||||
# block if profile has unsaved changes and it's not a virtual New profile
|
||||
if self._profile_dirty.get(name, False) and not (self._virtual_new_profile and name == "New profile"):
|
||||
if self._profile_dirty.get(name, False) and not (
|
||||
self._virtual_new_profile and name == "New profile"
|
||||
):
|
||||
QMessageBox.warning(
|
||||
self, "Unsaved Changes", "Please save the profile before renaming."
|
||||
)
|
||||
return
|
||||
old = item.text().lstrip("*")
|
||||
import re
|
||||
|
||||
while True:
|
||||
new, ok = QInputDialog.getText(
|
||||
self, "Rename Profile", f"Profile name:", text=old
|
||||
@@ -1189,8 +1205,12 @@ class VoiceFormulaDialog(QDialog):
|
||||
new = new.strip() # Remove leading/trailing spaces
|
||||
if not new:
|
||||
continue
|
||||
if not re.match(r'^[\w\- ]+$', new):
|
||||
QMessageBox.warning(self, "Invalid Name", "Profile name can only contain letters, numbers, spaces, underscores, and hyphens.")
|
||||
if not re.match(r"^[\w\- ]+$", new):
|
||||
QMessageBox.warning(
|
||||
self,
|
||||
"Invalid Name",
|
||||
"Profile name can only contain letters, numbers, spaces, underscores, and hyphens.",
|
||||
)
|
||||
continue
|
||||
|
||||
profiles = load_profiles()
|
||||
@@ -1326,3 +1346,39 @@ class VoiceFormulaDialog(QDialog):
|
||||
else:
|
||||
item.setBackground(QColor("white"))
|
||||
self.update_profile_save_buttons()
|
||||
|
||||
def preview_current_mix(self):
|
||||
# Disable preview until playback completes
|
||||
self.btn_preview_mix.setEnabled(False)
|
||||
self.btn_preview_mix.setText("Loading...")
|
||||
self._loading = True
|
||||
parent = self.parent()
|
||||
if parent and hasattr(parent, "preview_voice"):
|
||||
# Apply mixed voices and selected language
|
||||
parent.mixed_voice_state = self.get_selected_voices()
|
||||
parent.selected_profile_name = None
|
||||
lang = self.language_combo.currentData()
|
||||
parent.selected_lang = lang
|
||||
parent.subtitle_combo.setEnabled(
|
||||
lang in SUPPORTED_LANGUAGES_FOR_SUBTITLE_GENERATION
|
||||
)
|
||||
# Reset start flag and trigger preview
|
||||
self._started = False
|
||||
parent.preview_voice()
|
||||
# Poll preview_playing: wait for start then end
|
||||
self._preview_poll_timer = QTimer(self)
|
||||
self._preview_poll_timer.timeout.connect(self._check_preview_done)
|
||||
self._preview_poll_timer.start(200)
|
||||
|
||||
def _check_preview_done(self):
|
||||
parent = self.parent()
|
||||
if parent and hasattr(parent, "preview_playing"):
|
||||
# Mark when playback starts
|
||||
if parent.preview_playing:
|
||||
self._started = True
|
||||
# Once started and then stopped, re-enable
|
||||
elif getattr(self, "_started", False):
|
||||
self.btn_preview_mix.setEnabled(True)
|
||||
self.btn_preview_mix.setText("Preview")
|
||||
self._loading = False
|
||||
self._preview_poll_timer.stop()
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import os
|
||||
import json
|
||||
from utils import get_user_config_path, get_resource_path
|
||||
from utils import get_user_config_path
|
||||
|
||||
|
||||
def _get_profiles_path():
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 11 KiB |
+2
-1
@@ -22,7 +22,8 @@ dependencies = [
|
||||
"soundfile>=0.13.1",
|
||||
"pygame>=2.6.1",
|
||||
"charset_normalizer>=3.4.1",
|
||||
"chardet>=5.2.0"
|
||||
"chardet>=5.2.0",
|
||||
"static_ffmpeg>=2.13"
|
||||
]
|
||||
|
||||
classifiers = [
|
||||
|
||||
Reference in New Issue
Block a user