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.
- Better approach for determining the correct configuration folder for Linux and MacOS, using platformdirs. (Fixes Docker issue #12)
- Improvements in documentation and code.
- 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.
+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
import static_ffmpeg
import threading # for efficient waiting
import subprocess
import sys
import platform
def get_sample_voice_text(lang_code):
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))
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 = (
@@ -610,45 +620,86 @@ class ConversionThread(QThread):
# 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")
(
"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
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")
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()
import subprocess
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
"-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")
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
if result.returncode != 0:
self.log_updated.emit((f"FFmpeg error: {result.stderr}", "red"))
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"))
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"))
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)
+32 -9
View File
@@ -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):
@@ -670,9 +682,16 @@ class abogen(QWidget):
format_layout = QVBoxLayout()
format_layout.addWidget(QLabel("Output Format:", 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
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)
# Initialize selection by matching saved key
idx = self.format_combo.findData(self.selected_format)
@@ -1422,6 +1441,7 @@ class abogen(QWidget):
if self.preview_playing:
try:
import pygame
pygame.mixer.music.stop()
except Exception:
pass
@@ -1438,7 +1458,7 @@ class abogen(QWidget):
self.btn_start.setEnabled(False) # Disable start button during preview
# 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
try:
self.loading_movie.frameChanged.disconnect()
@@ -1447,7 +1467,9 @@ class abogen(QWidget):
# Reconnect the signal
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()
@@ -1478,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]
@@ -1845,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
+1
View File
@@ -67,6 +67,7 @@ def get_version():
# Define config path
def get_user_config_path():
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 nonWindows, prefer ~/.config/abogen if it already exists
if platform.system() != "Windows":
+62 -6
View File
@@ -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()