4 Commits
6 changed files with 180 additions and 47 deletions
+5 -3
View File
@@ -1,3 +1,5 @@
- Added new output format: `m4b`, enabling chapter metadata in audiobooks. Special thanks to @jborza for implementing this feature in PR #10. - Added `Insert chapter marker` button in text editor to insert chapter markers at the current cursor position.
- Better approach for determining the correct configuration folder for Linux and MacOS, using platformdirs. (Fixes Docker issue #12) - Added `Preview` button in voice mixer to preview the voice mix with the selected settings.
- Improvements in documentation and code. - 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.
+1 -1
View File
@@ -1 +1 @@
1.0.5 1.0.6
+67 -16
View File
@@ -13,6 +13,10 @@ from constants import PROGRAM_NAME, LANGUAGE_DESCRIPTIONS, SAMPLE_VOICE_TEXTS
from voice_formulas import get_new_voice from voice_formulas import get_new_voice
import static_ffmpeg import static_ffmpeg
import threading # for efficient waiting import threading # for efficient waiting
import subprocess
import sys
import platform
def get_sample_voice_text(lang_code): def get_sample_voice_text(lang_code):
return SAMPLE_VOICE_TEXTS.get(lang_code, SAMPLE_VOICE_TEXTS["a"]) return SAMPLE_VOICE_TEXTS.get(lang_code, SAMPLE_VOICE_TEXTS["a"])
@@ -224,6 +228,12 @@ class ConversionThread(QThread):
chapter_splits = list(re.finditer(chapter_pattern, text)) chapter_splits = list(re.finditer(chapter_pattern, text))
chapters = [] chapters = []
if chapter_splits: 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): for idx, match in enumerate(chapter_splits):
start = match.end() start = match.end()
end = ( end = (
@@ -610,45 +620,86 @@ class ConversionThread(QThread):
# If there is only one chapter, skip adding chapters and just return the wav file path # 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: if not chapters_time or len(chapters_time) <= 1:
self.log_updated.emit( 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") (
"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 return out_path
# generate chapters.txt in the same folder as the output file # generate chapters.txt in the same folder as the output file
chapters_info_path = os.path.splitext(out_path)[0] + "_chapters.txt" chapters_info_path = os.path.splitext(out_path)[0] + "_chapters.txt"
with open(chapters_info_path, "w", encoding="utf-8") as f: with open(chapters_info_path, "w", encoding="utf-8") as f:
f.write(';FFMETADATA1\n') # required header for ffmpeg f.write(";FFMETADATA1\n") # required header for ffmpeg
for chapter in chapters_time: for chapter in chapters_time:
f.write(f"[CHAPTER]\n") f.write(f"[CHAPTER]\n")
f.write(f"TIMEBASE=1/10\n") f.write(f"TIMEBASE=1/10\n")
# use 10th of second for start/end time # use 10th of second for start/end time
f.write(f"START={int(chapter["start"]*10)}\n") f.write(f"START={int(chapter['start']*10)}\n")
f.write(f"END={int(chapter["end"]*10)}\n") f.write(f"END={int(chapter['end']*10)}\n")
f.write(f"title={chapter["chapter"]}\n\n") f.write(f"title={chapter['chapter']}\n\n")
# call ffmpeg to merge the chapters into the output file # call ffmpeg to merge the chapters into the output file
# ffmpeg installed on first call to add_paths() # ffmpeg installed on first call to add_paths()
static_ffmpeg.add_paths() static_ffmpeg.add_paths()
import subprocess
out_path_m4b = os.path.splitext(out_path)[0] + ".m4b" 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 -i input.m4b -i ch.txt -map 0:a -map_chapters 1 output.m4b
ffmpeg_cmd = [ ffmpeg_cmd = [
"ffmpeg", "ffmpeg",
"-i", out_path, "-i",
"-i", chapters_info_path, out_path,
"-map", "0:a", "-i",
"-map_chapters", "1", chapters_info_path,
out_path_m4b "-map",
"0:a",
"-map_chapters",
"1",
out_path_m4b,
] ]
self.log_updated.emit("Adding chapters to the audio file...\n") self.log_updated.emit("Adding chapters to the audio file...\n")
result = subprocess.run(ffmpeg_cmd, capture_output=True, text=True)
# 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 # Check for errors in the ffmpeg command
if result.returncode != 0: if process.returncode != 0:
self.log_updated.emit((f"FFmpeg error: {result.stderr}", "red")) 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 # Log error but continue with original file
self.log_updated.emit(("Falling back to the original audio file without chapters\n", "orange")) 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 return out_path
else: else:
self.log_updated.emit(("Successfully added chapters to the audio file.\n", "green")) self.log_updated.emit(
("Successfully added chapters to the audio file.\n", "green")
)
# delete the chapters path and original (wav) file # delete the chapters path and original (wav) file
os.remove(chapters_info_path) os.remove(chapters_info_path)
+32 -9
View File
@@ -290,8 +290,8 @@ class InputBox(QLabel):
) )
win.selected_book_path = file_path win.selected_book_path = file_path
win.open_book_file( win.open_book_file(
file_path file_path # This will handle the dialog and setting file info
) # This will handle the dialog and setting file info )
event.acceptProposedAction() event.acceptProposedAction()
else: else:
self.set_error("Please drop a .txt, .epub, or .pdf file.") self.set_error("Please drop a .txt, .epub, or .pdf file.")
@@ -328,7 +328,7 @@ class TextboxDialog(QDialog):
self.setWindowFlags( self.setWindowFlags(
Qt.Window | Qt.WindowCloseButtonHint | Qt.WindowMaximizeButtonHint Qt.Window | Qt.WindowCloseButtonHint | Qt.WindowMaximizeButtonHint
) )
self.resize(600, 400) self.resize(700, 500)
layout = QVBoxLayout(self) layout = QVBoxLayout(self)
@@ -358,6 +358,11 @@ class TextboxDialog(QDialog):
self.save_as_button.clicked.connect(self.save_as_text) self.save_as_button.clicked.connect(self.save_as_text)
self.save_as_button.setToolTip("Save the current text to a file") 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 = QPushButton("Cancel", self)
self.cancel_button.clicked.connect(self.reject) self.cancel_button.clicked.connect(self.reject)
@@ -444,6 +449,13 @@ class TextboxDialog(QDialog):
except Exception as e: except Exception as e:
QMessageBox.critical(self, "Save Error", f"Could not save file:\n{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): class abogen(QWidget):
def __init__(self): def __init__(self):
@@ -670,9 +682,16 @@ class abogen(QWidget):
format_layout = QVBoxLayout() format_layout = QVBoxLayout()
format_layout.addWidget(QLabel("Output Format:", self)) format_layout.addWidget(QLabel("Output Format:", self))
self.format_combo = QComboBox(self) self.format_combo = QComboBox(self)
self.format_combo.setStyleSheet("QComboBox { min-height: 20px; padding: 6px 12px; }") self.format_combo.setStyleSheet(
"QComboBox { min-height: 20px; padding: 6px 12px; }"
)
# Add items with display labels and underlying keys # Add items with display labels and underlying keys
for key, label in [("wav","wav"),("flac","flac"),("mp3","mp3"),("m4b","m4b (with chapters)")]: for key, label in [
("wav", "wav"),
("flac", "flac"),
("mp3", "mp3"),
("m4b", "m4b (with chapters)"),
]:
self.format_combo.addItem(label, key) self.format_combo.addItem(label, key)
# Initialize selection by matching saved key # Initialize selection by matching saved key
idx = self.format_combo.findData(self.selected_format) idx = self.format_combo.findData(self.selected_format)
@@ -1422,6 +1441,7 @@ class abogen(QWidget):
if self.preview_playing: if self.preview_playing:
try: try:
import pygame import pygame
pygame.mixer.music.stop() pygame.mixer.music.stop()
except Exception: except Exception:
pass pass
@@ -1438,7 +1458,7 @@ class abogen(QWidget):
self.btn_start.setEnabled(False) # Disable start button during preview self.btn_start.setEnabled(False) # Disable start button during preview
# Start loading animation - ensure signal connection is always active # Start loading animation - ensure signal connection is always active
if hasattr(self, 'loading_movie'): if hasattr(self, "loading_movie"):
# Disconnect previous connections to avoid multiple connections # Disconnect previous connections to avoid multiple connections
try: try:
self.loading_movie.frameChanged.disconnect() self.loading_movie.frameChanged.disconnect()
@@ -1447,7 +1467,9 @@ class abogen(QWidget):
# Reconnect the signal # Reconnect the signal
self.loading_movie.frameChanged.connect( self.loading_movie.frameChanged.connect(
lambda: self.btn_preview.setIcon(QIcon(self.loading_movie.currentPixmap())) lambda: self.btn_preview.setIcon(
QIcon(self.loading_movie.currentPixmap())
)
) )
self.loading_movie.start() self.loading_movie.start()
@@ -1478,14 +1500,14 @@ class abogen(QWidget):
# Build voice formula string # Build voice formula string
components = [f"{name}*{weight}" for name, weight in self.mixed_voice_state] components = [f"{name}*{weight}" for name, weight in self.mixed_voice_state]
voice = " + ".join(filter(None, components)) 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: if self.selected_profile_name:
from voice_profiles import load_profiles from voice_profiles import load_profiles
entry = load_profiles().get(self.selected_profile_name, {}) entry = load_profiles().get(self.selected_profile_name, {})
lang = entry.get("language") lang = entry.get("language")
else: else:
lang = None lang = self.selected_lang
if not lang and self.mixed_voice_state: if not lang and self.mixed_voice_state:
lang = ( lang = (
self.mixed_voice_state[0][0][0] self.mixed_voice_state[0][0][0]
@@ -1845,6 +1867,7 @@ class abogen(QWidget):
def show_voice_formula_dialog(self): def show_voice_formula_dialog(self):
from voice_profiles import load_profiles from voice_profiles import load_profiles
profiles = load_profiles() profiles = load_profiles()
initial_state = None initial_state = None
selected_profile = self.selected_profile_name selected_profile = self.selected_profile_name
+1
View File
@@ -67,6 +67,7 @@ def get_version():
# Define config path # Define config path
def get_user_config_path(): def get_user_config_path():
from platformdirs import user_config_dir from platformdirs import user_config_dir
# TODO Config directory is changed for Linux and MacOS. But if old config exists, it will be used. # TODO Config directory is changed for Linux and MacOS. But if old config exists, it will be used.
# On nonWindows, prefer ~/.config/abogen if it already exists # On nonWindows, prefer ~/.config/abogen if it already exists
if platform.system() != "Windows": if platform.system() != "Windows":
+62 -6
View File
@@ -47,7 +47,7 @@ VOICE_MIXER_WIDTH = 100
SLIDER_WIDTH = 32 SLIDER_WIDTH = 32
MIN_WINDOW_WIDTH = 600 MIN_WINDOW_WIDTH = 600
MIN_WINDOW_HEIGHT = 400 MIN_WINDOW_HEIGHT = 400
INITIAL_WINDOW_WIDTH = 1000 INITIAL_WINDOW_WIDTH = 1200
INITIAL_WINDOW_HEIGHT = 500 INITIAL_WINDOW_HEIGHT = 500
# Language options for the language selector loaded from constants # Language options for the language selector loaded from constants
@@ -413,6 +413,11 @@ class VoiceFormulaDialog(QDialog):
self.language_combo.setCurrentIndex(idx) self.language_combo.setCurrentIndex(idx)
self.language_combo.currentIndexChanged.connect(self.mark_profile_modified) self.language_combo.currentIndexChanged.connect(self.mark_profile_modified)
header_row.addWidget(self.language_combo) 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) mixer_layout.addLayout(header_row)
# Error message # Error message
@@ -708,6 +713,9 @@ class VoiceFormulaDialog(QDialog):
] ]
total = sum(w for _, w in selected) 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: if total > 0:
self.error_label.hide() self.error_label.hide()
@@ -943,6 +951,7 @@ class VoiceFormulaDialog(QDialog):
def new_profile(self): def new_profile(self):
import re import re
while True: while True:
name, ok = QInputDialog.getText(self, "New Profile", "Enter profile name:") name, ok = QInputDialog.getText(self, "New Profile", "Enter profile name:")
if not ok or not name: if not ok or not name:
@@ -950,8 +959,12 @@ class VoiceFormulaDialog(QDialog):
name = name.strip() # Remove leading/trailing spaces name = name.strip() # Remove leading/trailing spaces
if not name: if not name:
continue continue
if not re.match(r'^[\w\- ]+$', name): if not re.match(r"^[\w\- ]+$", name):
QMessageBox.warning(self, "Invalid Name", "Profile name can only contain letters, numbers, spaces, underscores, and hyphens.") QMessageBox.warning(
self,
"Invalid Name",
"Profile name can only contain letters, numbers, spaces, underscores, and hyphens.",
)
continue continue
profiles = load_profiles() profiles = load_profiles()
# Remove 'New profile' placeholder if not persisted in JSON # Remove 'New profile' placeholder if not persisted in JSON
@@ -1173,13 +1186,16 @@ class VoiceFormulaDialog(QDialog):
def rename_profile(self, item): def rename_profile(self, item):
name = item.text().lstrip("*") name = item.text().lstrip("*")
# block if profile has unsaved changes and it's not a virtual New profile # 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( QMessageBox.warning(
self, "Unsaved Changes", "Please save the profile before renaming." self, "Unsaved Changes", "Please save the profile before renaming."
) )
return return
old = item.text().lstrip("*") old = item.text().lstrip("*")
import re import re
while True: while True:
new, ok = QInputDialog.getText( new, ok = QInputDialog.getText(
self, "Rename Profile", f"Profile name:", text=old self, "Rename Profile", f"Profile name:", text=old
@@ -1189,8 +1205,12 @@ class VoiceFormulaDialog(QDialog):
new = new.strip() # Remove leading/trailing spaces new = new.strip() # Remove leading/trailing spaces
if not new: if not new:
continue continue
if not re.match(r'^[\w\- ]+$', new): if not re.match(r"^[\w\- ]+$", new):
QMessageBox.warning(self, "Invalid Name", "Profile name can only contain letters, numbers, spaces, underscores, and hyphens.") QMessageBox.warning(
self,
"Invalid Name",
"Profile name can only contain letters, numbers, spaces, underscores, and hyphens.",
)
continue continue
profiles = load_profiles() profiles = load_profiles()
@@ -1326,3 +1346,39 @@ class VoiceFormulaDialog(QDialog):
else: else:
item.setBackground(QColor("white")) item.setBackground(QColor("white"))
self.update_profile_save_buttons() 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()