Restyle using black, improve m4b process handling

This commit is contained in:
Deniz Şafak
2025-05-04 11:39:54 +03:00
parent 412fb3bc7e
commit 146fcb3c1f
5 changed files with 104 additions and 37 deletions
+1 -3
View File
@@ -1,3 +1 @@
- Added new output format: `m4b`, enabling chapter metadata in audiobooks. Special thanks to @jborza for implementing this feature in PR #10. - Fixed m4b chapter generation opens CMD window in Windows.
- Better approach for determining the correct configuration folder for Linux and MacOS, using platformdirs. (Fixes Docker issue #12)
- Improvements in documentation and code.
+58 -13
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"])
@@ -610,13 +614,16 @@ 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")
@@ -627,28 +634,66 @@ class ConversionThread(QThread):
# 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)
+15 -4
View File
@@ -670,9 +670,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 +1429,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 +1446,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 +1455,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()
@@ -1845,6 +1855,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":
+17 -5
View File
@@ -943,6 +943,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 +951,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 +1178,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 +1197,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()