- Add XTTS v2 configuration to .env.example - Refactor Dockerfile to multi-stage build with CUDA 12.1 support - Update Makefile with Kokoro and XTTS test environment targets - Refactor Piper engine (app/engines/piper.py) to use python module execution - Add comprehensive documentation for Kokoro and XTTS plans - Add helper scripts and patches for build process
13 KiB
Session Resumee - AudioEngineHub Project Refactoring
Date: Donnerstag, 4. Dezember 2025
Objective: Refactor the AudioEngineHub project to follow best practices for containerization, error handling, and project structure, based on a provided guide.md document.
Initial Project State & Overview
The project was a modular FastAPI-based TTS server with a TTSEngineBase interface. Key initial findings:
piperwas functional.stylettsandchatttswere dummy implementations.f5_ttswas implemented but inactive.- Configuration was scattered and hardcoded.
- Error handling was basic.
- Tests (
pytestandunittest) existed but were limited and inconsistent. - No containerization strategy was in place, leading to potential dependency hell.
Refactoring Phase 1: Robustness & Configuration
-
Centralized Configuration:
- Replaced hardcoded values with
pydantic-settingsfor.envfile management. config.pycreated (later moved toapp/config.py).IMAGE_NAMEinMakefilewas also user-configurable.requirements.txtwas updated withpydantic-settings.docker-compose.ymlwas updated to use.env.
- Replaced hardcoded values with
-
Configurable Engines Feature:
- Implemented dynamic
ENGINE_REGISTRYloading based onACTIVE_ENGINESsetting in.env. - Allows easy activation/deactivation of TTS engines.
- Implemented dynamic
-
Robust Error Handling:
- Implemented comprehensive input validation in the
/ttsendpoint (checking engine, model, speaker existence). - Added dependency checks (e.g.,
ffmpeg,piperexecutables) to engines, reportingHTTP 503for unavailable engines. - Secured
tempfile.mktempusage by replacing it withtempfile.NamedTemporaryFile. - Wrapped synthesis logic in
try-exceptblocks to catch and propagate engine-specific errors asHTTP 500.
- Implemented comprehensive input validation in the
-
Asynchronous Operations:
- Changed
TTSEngineBase.synthesizeandselftesttoasync. - Refactored all concrete engine implementations (
piper,f5_tts,styletts,chattts) to useasync defmethods. - Updated
app/main.py's/ttsendpoint to beasyncand useawaitfor engine calls andasyncio.gatherfor concurrent chunk synthesis. - Wrapped blocking I/O (file ops,
ffmpeg) and CPU-bound tasks inasyncio.to_thread. - Updated
tests/test_f5_tts.pyto correctlyawaitasync calls.
- Changed
Refactoring Phase 2: Containerization & Workflow (Based on guide.md)
-
Integrated
Makefile:- Created a
Makefilewith targets forbuild,run,stop,logs,shell,up,down,test,tag,push,clean,help. - Included robust shell functions for port checking (
check_traefik_ports_free,check_app_port_free). - Set
SHELL := /bin/bashinMakefileto ensure correct shell interpretation. - Ensured
PYTHONPATH=$(PWD)is set formake test.
- Created a
-
Adopted Multi-Stage
Dockerfile:- Implemented a multi-stage
Dockerfile(builder/runner stages). builderstage creates a Python virtual environment and installsrequirements.txt(includinggunicorn).runnerstage usespython:3.11-slim, installs runtime system dependencies (ffmpeg), creates an unprivilegedappuser, and sets the productionCMDtogunicornwithuvicornworkers.
- Implemented a multi-stage
-
Refactored Project Structure (
app/package):- Created an
app/directory. - Moved
main.py,config.py,engines/,models/,utils/intoapp/. - Created
app/__init__.py. - Updated all Python import paths (
from app.config import settings,from app.engines.piper import PiperEngine, etc.). - Updated internal references in engine files (e.g.,
model_dir,voices_dir).
- Created an
-
Refined
docker-compose.ymlwith Traefik:- Integrated
traefikservice for dynamic reverse proxying during local development. - Modified
appservice with Traefiklabelsand connected both services to awebnetwork. - Adjusted Docker
volumesmounts to match the newapp/structure (e.g.,./models:/home/appuser/app/models). - Updated
appservicecommandfor Uvicorn hot-reloading in dev.
- Integrated
-
Centralized Testing Workflow:
- Removed
test_run.sh. - Integrated
make testfor runningpytest --cov=. app/ tests/.
- Removed
-
Dedicated Documentation:
- Created
docs/directory. - Moved
guide.mdtodocs/guide.md.
- Created
Verification & Troubleshooting
- Tests: All unit/integration tests (
make test) are passing. - Local Run (Virtual Env): Initial local runs (
python app/main.py) failed due toModuleNotFoundError(fixed bypython -m app.main) andPermissionError(fixed by needing to mock or redirectsettings.AUDIO_CACHE_DIRfor local direct execution, but not strictly needed for successful app execution throughuvicorn). The current approach is to verify in Docker. - Docker Compose:
- Initial
make upfailures were due to an outdateddocker-composeclient (1.29.2) and later,Makefilesyntax issues (fixed by settingSHELL := /bin/bashand fixing macros). docker-composewas eventually updated to thedocker composeCLI plugin (v5.0.0).make upcommand finally succeeded in bringing up containers.- The
curl http://localhost/healthcommand returned404 page not found. This indicates a potential routing issue with Traefik or the application not being responsive on the expected path within the container. (This is the last unresolved issue).
- Initial
Final Debugging & Resolution (Post-Refactoring)
After the major refactoring, the service was unable to start and was returning 404 errors. The final debugging session addressed these issues.
-
FastAPI App Startup Fix:
- Problem: The Uvicorn server was failing with
Attribute "app" not found in module "app.main". - Solution: The
appinstance was only created inside theif __name__ == "__main__"block. Movedapp = create_app()to the module's global scope inapp/main.pyso Uvicorn could find it.
- Problem: The Uvicorn server was failing with
-
Traefik & Docker Compose Issues:
- Problem: The initial
docker-compose.ymlincluded a Traefik service for reverse proxying, which was causing multiple issues (invalid container names due to missing.envvariables, Docker client API version errors). The user also clarified that they use an existing reverse proxy and did not want a new Traefik container deployed. - Solution: Removed the
traefikservice entirely fromdocker-compose.yml. Theappservice's port was exposed directly to the host.
- Problem: The initial
-
Model Loading Failure:
- Problem: The
piperengine was not loading any models, returning an empty list and causing/ttsrequests to fail with a422 Unprocessable Entityerror. - Diagnosis: The root cause was an incorrect volume mount. The
docker-compose.ymlwas attempting to mount a non-existent, empty./modelsdirectory from the host. The actual models were located in./app/models. - Solution:
- Corrected the
docker-compose.ymlvolume mount to point to the correct source directory:- ./app/models:/models. - Updated the
app/engines/piper.pycode to use the absolute path/models/piper/to look for models inside the container, making the configuration more robust and independent of the working directory.
- Corrected the
- Problem: The
-
Developer Experience (DX) Improvements:
- Automatic Port Finding: The
Makefilewas enhanced. Themake upandmake runcommands now automatically find a free port starting from 8000, preventing port conflicts. - Health Check Command: A
make health-checktarget was added. It runs a sanity check against the deployed container's/healthendpoint to verify that the service is up and all engines are reporting an "ok" status. - Documentation:
- The
README.mdwas completely rewritten to provide a clear and up-to-date guide for getting started, usage, and availablemakecommands. - A note was added to
docs/guide.mdto clarify that it describes an older, more advanced setup and to point readers to the newREADME.md.
- The
- Automatic Port Finding: The
Final Status: The service is now fully deployable via make up and passes make health-check. All identified startup issues and bugs have been resolved.
Container Registry Integration
To facilitate pushing and pulling Docker images from a remote registry (e.g., git.wlkns.org), the Makefile and docker-compose.yml were updated:
-
Makefile Configuration:
- Added
REGISTRY := git.wlkns.organdUSERNAME := stephanvariables. - Modified the
tagtarget to tag images in the format$(REGISTRY)/$(USERNAME)/$(IMAGE_NAME):$(TAG). - Modified the
pushtarget to depend onbuildandtag, then push the image to the configured registry.
- Added
-
docker-compose.ymlIntegration:- Changed the
appservice definition to useimage: ${REGISTRY}/${USERNAME}/${IMAGE_NAME}:${TAG}instead ofbuild: ., making it pull from the registry by default.
- Changed the
-
Makefile Workflow Enhancements:
- Added a
pulltarget (make pull) to explicitly download the image from the registry. - The
uptarget (make up) was modified to start the service using the image specified indocker-compose.yml(which now points to the registry). - A new
dev-uptarget (make dev-up) was introduced for local development, which explicitly builds the image from source (docker compose up --build -d) before starting the service. - The
downandhelptargets were updated accordingly.
- Added a
This allows for flexible deployment, supporting both local development with on-demand building and production-like environments pulling from a registry.
Debugging "Always the Same Text" Bug
The user reported that the TTS server was not synthesizing the provided text but was always returning audio for a fixed, incorrect text.
-
Initial Reproduction Attempt (and "422 Unprocessable Entity" error):
- Attempted to reproduce the bug by sending different texts via
scripts/tts_client.py. - Encountered a
422 Unprocessable Entityerror, which led to debugging model loading. - Resolution 1 (Model Loading): Fixed by correcting the volume mount source in
docker-compose.yml(./app/modelsto/models) and updating paths inapp/engines/piper.pyto absolute/models/piper/. - Resolution 2 (Startup Race Condition): Added a startup event handler in
app/main.pyto wait for the models directory to be available, preventing a race condition. - Resolution 3 (Client Connection): Mitigated
ConnectionResetErrorfrom client by addingtime.sleep(1)beforerequests.postcall inscripts/tts_client.py, indicating a subtle client-server connection timing issue.
- Attempted to reproduce the bug by sending different texts via
-
Debugging the "Always the Same Text" Issue:
- Initial Test: Generated audio for "This is a test with the vctk model." and "This is a completely different sentence to verify the bug."
- Result:
cmpshowed the files were different, contradicting the user's report that the text was always the same. - User Clarification: User confirmed that listening to the files revealed the same speech output, indicating a deeper issue beyond simple file difference.
- Investigation of
piper.py:- The original method for passing text to the
piperexecutable viastdin(--stdin) seemed correct. - Manual testing
echo "text" | piper ...inside the container provedpiperexecutable works correctly withstdin. - Hypothesis: The
asyncio.subprocess.communicate(input=...)call was not reliably passing text topiper.
- The original method for passing text to the
- Attempted Fix 1 (Explicit stdin write): Modified
piper.pyto manually write toprocess.stdin,drain, andclose. This led toConnectionResetError(server crash). - Attempted Fix 2 (Revert and
--input-filestrategy): Revertedpiper.pyback toprocess.communicate()(after fixingcmdto use--stdin). Then, changed strategy to use a temporary file for input (--input-file) instead ofstdin. This also led toConnectionResetError. - Persistent Crash: The server consistently crashed after each attempt to synthesize actual audio. Debugging was hampered by
uvicorn's reloader hiding tracebacks, even after disabling it. It became apparent that the crash was very low-level, possibly within thepiperexecutable's interaction with the file system or system resources.
-
Current Status: The server still crashes when the
synthesizemethod is called to generate real audio. The exact cause of this crash is still unknown, as no Python traceback is being produced in the server logs. Further debugging is required to stabilize thepiperengine's subprocess execution.