### Quick Development Setup with Just Source: https://docs.voicebox.sh/developer/setup This snippet demonstrates the recommended quick setup for Voicebox development using the 'just' command-line tool. It clones the repository, installs all dependencies, and starts the development server and desktop application. ```bash git clone https://github.com/jamiepine/voicebox.git cd voicebox # Setup everything (Python venv, JS deps, dev sidecar) just setup # Start development (backend + desktop app) just dev ``` -------------------------------- ### Manual Python Backend Setup Source: https://docs.voicebox.sh/developer/setup These commands outline the manual setup process for the Python backend, including creating and activating a virtual environment, installing core dependencies, and installing MLX and Qwen3-TTS specific dependencies. ```bash cd backend # Create virtual environment python -m venv venv # Activate virtual environment source venv/bin/activate # macOS/Linux # or venv\Scripts\activate # Windows # Install Python dependencies pip install -r requirements.txt # Apple Silicon: install MLX dependencies pip install -r requirements-mlx.txt # Install Qwen3-TTS pip install git+https://github.com/QwenLM/Qwen3-TTS.git ``` -------------------------------- ### Install Just Source: https://docs.voicebox.sh/developer/setup Instructions for installing the 'just' command-line tool, which is used extensively for automating development tasks in the Voicebox project. It provides commands for setup, development, building, and testing. ```bash brew install just # macOS cargo install just # Linux/Windows ``` -------------------------------- ### Manual Desktop App Start Source: https://docs.voicebox.sh/developer/setup This command starts the Tauri desktop application in development mode. It requires the backend server to be running separately. Ensure you are in the 'tauri' directory. ```bash cd tauri bun run tauri dev ``` -------------------------------- ### Install Bun Source: https://docs.voicebox.sh/developer/setup This command installs the Bun JavaScript runtime. Bun is a fast all-in-one JavaScript toolkit, used here for managing frontend dependencies. ```bash curl -fsSL https://bun.sh/install | bash ``` -------------------------------- ### Manual Backend Server Start Source: https://docs.voicebox.sh/developer/setup This command starts the FastAPI backend server for development. It uses 'uvicorn' and reloads automatically on file changes. Ensure the virtual environment is activated before running. ```bash cd backend source venv/bin/activate uvicorn main:app --reload --port 17493 ``` -------------------------------- ### Manual JavaScript Dependency Installation Source: https://docs.voicebox.sh/developer/setup This command installs JavaScript dependencies for the frontend applications (shared React, Tauri desktop wrapper, and web deployment wrapper) using Bun. ```bash bun install ``` -------------------------------- ### Install Backend Dependencies Source: https://docs.voicebox.sh/overview/troubleshooting Installs Python dependencies for the Voicebox backend, including the Qwen3-TTS model from its GitHub repository. This is essential for development. ```shell cd backend pip install -r requirements.txt pip install git+https://github.com/QwenLM/Qwen3-TTS.git ``` -------------------------------- ### Install Voicebox on macOS via Terminal Source: https://docs.voicebox.sh/overview/installation Commands to extract the Voicebox application archive and move it to the Applications directory on macOS. This process applies to both Apple Silicon and Intel-based architectures. ```bash # Extract the archive tar -xzf voicebox_aarch64.app.tar.gz # Move to Applications mv Voicebox.app /Applications/ ``` ```bash # Extract the archive tar -xzf voicebox_x64.app.tar.gz # Move to Applications mv Voicebox.app /Applications/ ``` -------------------------------- ### Get Audio File using Python Source: https://docs.voicebox.sh/api-reference/generation/get_audio_audio__generation_id__get This snippet provides a Python example for fetching a generated audio file. It uses the requests library to send a GET request. The function returns the audio content or an error. ```python # Python example would go here, using the requests library. ``` -------------------------------- ### Verify CUDA Installation Source: https://docs.voicebox.sh/overview/troubleshooting This command checks if the NVIDIA CUDA drivers are installed and recognized by the system. Proper CUDA installation is essential for GPU acceleration during generation. If this command fails or shows no output, CUDA drivers may need to be installed or updated. ```shell nvidia-smi ``` -------------------------------- ### Install Python Packages with pip Source: https://docs.voicebox.sh/developer/tts-engines Installs Python packages using pip. It demonstrates normal installation, installation with specific versions to check for conflicts, and installation without dependencies. ```bash # Install the package (try normally first) pip install model-package # Check if it conflicts with our stack pip install model-package torch==2.10 transformers==4.57.3 numpy>=1.26 # If this fails, you need --no-deps: pip install --no-deps model-package ``` -------------------------------- ### Get Profile Samples - Java Source: https://docs.voicebox.sh/api-reference/profiles/get_profile_samples_profiles__profile_id__samples_get Provides a Java method to retrieve all samples for a voice profile. This example assumes the use of a library like Apache HttpClient or Java 11+ HttpClient. It constructs the URL and handles the HTTP GET request and response parsing. ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.io.IOException; public class VoiceboxClient { public String getProfileSamples(String profileId) throws IOException, InterruptedException { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("http://localhost:8000/profiles/" + profileId + "/samples")) .GET() .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); if (response.statusCode() != 200) { throw new IOException("Unexpected status code: " + response.statusCode()); } return response.body(); } } ``` -------------------------------- ### API Development Example Source: https://docs.voicebox.sh/developer/contributing Example of how to add a new API endpoint in the backend, including request/response models and API documentation generation. ```APIDOC ## POST /api/new-endpoint ### Description Endpoint description. ### Method POST ### Endpoint /api/new-endpoint ### Parameters #### Request Body - **data** (RequestModel) - Required - Request data for the new endpoint. ### Request Example ```json { "field": "example_value" } ``` ### Response #### Success Response (200) - **result** (str) - The result of the endpoint operation. #### Response Example ```json { "result": "success" } ``` ### Models #### RequestModel - **field** (str) - Description of the field. #### ResponseModel - **result** (str) - Description of the result field. ### Notes - Ensure endpoint has proper docstrings and type hints. - Run `bun run generate:api` to update the TypeScript client and regenerate API documentation. ``` -------------------------------- ### GET Root Endpoint (Python) Source: https://docs.voicebox.sh/api-reference/general/root__get Shows a Python example for interacting with the Voicebox API's root endpoint. It utilizes the 'requests' library for making the GET request. ```python import requests response = requests.get('http://localhost:8000') print(response.json()) ``` -------------------------------- ### GET Root Endpoint (C#) Source: https://docs.voicebox.sh/api-reference/general/root__get A C# example for making a GET request to the Voicebox API's root endpoint. It uses `HttpClient` to send the request and receive the response. ```csharp using System; using System.Net.Http; public class VoiceboxClient { public static async Task Main(string[] args) { using (HttpClient client = new HttpClient()) { HttpResponseMessage response = await client.GetAsync("http://localhost:8000"); response.EnsureSuccessStatusCode(); // Throw if HTTP status is not 2xx string responseBody = await response.Content.ReadAsStringAsync(); Console.WriteLine(responseBody); } } } ``` -------------------------------- ### GET Root Endpoint (Java) Source: https://docs.voicebox.sh/api-reference/general/root__get Illustrates how to call the Voicebox API's root endpoint using Java. This example uses the standard `java.net.http` package for HTTP requests. ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class VoiceboxClient { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("http://localhost:8000")) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.body()); } } ``` -------------------------------- ### List History - Go Source: https://docs.voicebox.sh/api-reference/history/list_history_history_get Example of how to list generation history using Go. This code snippet shows how to make an HTTP GET request to the /history endpoint and process the JSON response. ```go package main import ( "fmt" "net/http" "io/ioutil" ) func main() { res, err := http.Get("http://localhost:8000/history") if err != nil { fmt.Printf("Error making request: %s\n", err) return } defer res.Body.Close() body, err := ioutil.ReadAll(res.Body) if err != nil { fmt.Printf("Error reading response body: %s\n", err) return } fmt.Println(string(body)) } ``` -------------------------------- ### Get Audio File using Go Source: https://docs.voicebox.sh/api-reference/generation/get_audio_audio__generation_id__get This snippet illustrates how to get a generated audio file using Go. It involves making an HTTP GET request to the specified endpoint. The function returns the audio data or an error. ```go // Go example would go here, using the net/http package to make the request. ``` -------------------------------- ### Inspect Installed Python Packages Source: https://docs.voicebox.sh/developer/tts-engines Provides commands to inspect installed Python packages, including their dependencies and a list of all installed files. This is useful for understanding package contents and requirements. ```bash # Get the full dependency tree pip show model-package # Check Requires: field pip show -f model-package # List all installed files (look for data files) ``` -------------------------------- ### Get Audio File using Java Source: https://docs.voicebox.sh/api-reference/generation/get_audio_audio__generation_id__get This snippet shows a Java implementation for retrieving a generated audio file. It typically uses libraries like Apache HttpClient or OkHttp to perform the GET request. The result is the audio data or an exception. ```java // Java example would go here, using an HTTP client library. ``` -------------------------------- ### GET /effects/available Source: https://docs.voicebox.sh/developer/effects-pipeline Retrieves a list of all available audio effect types and their configurable parameter definitions. ```APIDOC ## GET /effects/available ### Description Returns a list of all supported DSP effects (e.g., Chorus, Reverb, Compressor) along with their valid parameter ranges and default values. ### Method GET ### Endpoint /effects/available ### Response #### Success Response (200) - **effects** (array) - List of available effect objects with parameter schemas #### Response Example { "effects": [ { "type": "reverb", "parameters": { "room_size": {"min": 0.0, "max": 1.0, "default": 0.5} } } ] } ``` -------------------------------- ### Get Profile Samples - Go Source: https://docs.voicebox.sh/api-reference/profiles/get_profile_samples_profiles__profile_id__samples_get Implements a Go function to retrieve all samples for a voice profile. It constructs the URL with the provided profile ID and makes an HTTP GET request. Error handling is included for network issues and non-OK responses. ```go package main import ( "encoding/json" "fmt" "net/http" ) func getProfileSamples(profileID string) ([]map[string]interface{}, error) { url := fmt.Sprintf("http://localhost:8000/profiles/%s/samples", profileID) resp, err := http.Get(url) if err != nil { return nil, fmt.Errorf("failed to make request: %w", err) } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { return nil, fmt.Errorf("unexpected status code: %d", resp.StatusCode) } var samples []map[string]interface{} if err := json.NewDecoder(resp.Body).Decode(&samples); err != nil { return nil, fmt.Errorf("failed to decode response: %w", err) } return samples, nil } ``` -------------------------------- ### GET /models/progress/{name} Source: https://docs.voicebox.sh/developer/model-management Streams the download progress of a specific model using Server-Sent Events (SSE). ```APIDOC ## GET /models/progress/{name} ### Description Streams the download progress of a specific model using Server-Sent Events (SSE). ### Method GET ### Endpoint /models/progress/{name} ### Parameters #### Path Parameters - **name** (string) - Required - The name of the model for which to stream progress. ### Request Body None ### Response #### Success Response (200) - Server-Sent Events stream containing progress updates. - **data** (object) - JSON object with download progress details. - **current** (integer) - The number of bytes downloaded so far. - **total** (integer) - The total number of bytes to download. - **status** (string) - The current status of the download (e.g., "downloading", "complete"). #### Response Example (SSE data format) ``` data: {"current": 1048576, "total": 5242880, "status": "downloading"} ``` ``` data: {"current": 5242880, "total": 5242880, "status": "complete"} ``` ``` -------------------------------- ### Download Model from Ungated Mirror (Python) Source: https://docs.voicebox.sh/developer/tts-engines This code example shows how to download model components (like tokenizers) from an ungated Hugging Face repository mirror and then patch the model's configuration to use the locally downloaded path. This bypasses issues with gated repositories that require authentication and ensures models can be loaded correctly. ```python # Download tokenizer from ungated mirror UNGATED_TOKENIZER = "unsloth/Llama-3.2-1B" tokenizer_path = snapshot_download(UNGATED_TOKENIZER, token=None) # Patch the model config to use the local path instead of the gated repo config = ModelConfig.from_pretrained(model_path) config.tokenizer_name = tokenizer_path model = ModelClass.from_pretrained(model_path, config=config) ``` -------------------------------- ### Building Tauri Desktop App (Bun) Source: https://docs.voicebox.sh/developer/building Command to build the Tauri desktop application. This command initiates the build process for the frontend (Vite), Rust wrapper, and bundles the server sidecar binary, ultimately creating platform-specific installers. ```bash cd tauri bun run tauri build ``` -------------------------------- ### CUDA Backend Download Progress - SSE Source: https://docs.voicebox.sh/developer/autoupdater This example shows the Server-Sent Events (SSE) format used to report download progress for the CUDA backend. The frontend subscribes to the `/backend/cuda-progress` endpoint to display real-time download status, including current bytes downloaded, total size, filename, and status. ```text GET /backend/cuda-progress event: progress data: {"current": 52428800, "total": 104857600, "filename": "Downloading CUDA backend (2/4)", "status": "downloading"} ``` -------------------------------- ### Voicebox Build Commands Source: https://docs.voicebox.sh/developer/building Provides the primary 'just' commands for building the Voicebox application. These commands allow for building the entire application, or individual components like the server binary or the Tauri desktop app. ```bash just build # Build everything (server + Tauri) just build-server # Build Python server binary only just build-tauri # Build Tauri app only ``` -------------------------------- ### Server Binary Build Script (Bash) Source: https://docs.voicebox.sh/developer/building The `scripts/build-server.sh` script orchestrates the building of the Python server binary. It determines the target platform and uses PyInstaller via `build_binary.py` to create the executable, then copies it to the Tauri binaries directory. ```bash # Determine platform (e.g., x86_64-apple-darwin) PLATFORM=$(rustc --print host-tuple) # Run PyInstaller via build_binary.py cd backend python build_binary.py # Copy to Tauri's binaries directory cp dist/voicebox-server ../tauri/src-tauri/binaries/voicebox-server-${PLATFORM} ``` -------------------------------- ### Building CUDA-Enabled Server Binary (Python) Source: https://docs.voicebox.sh/developer/building Command to build the CUDA-enabled version of the server binary using PyInstaller. This process is separate due to the significantly larger file size of the CUDA-enabled version compared to the CPU-only version. ```bash cd backend python build_binary.py --cuda ``` -------------------------------- ### Check Python Version Source: https://docs.voicebox.sh/overview/troubleshooting Checks the installed Python version on the system. This is a prerequisite for the Voicebox backend development environment. ```shell python --version ``` -------------------------------- ### PyInstaller Configuration for Platform-Specific Logic (Python) Source: https://docs.voicebox.sh/developer/building This Python code snippet demonstrates platform-specific logic within PyInstaller configuration for building the server binary. It includes conditional arguments for Apple Silicon (MLX), CUDA builds, and excluding NVIDIA packages for CPU builds to manage binary size. ```python # Apple Silicon — include MLX backend if is_apple_silicon() and not cuda: args.extend([ "--hidden-import", "mlx", "--collect-all", "mlx", # Bundles .dylib and .metallib files ]) # CUDA builds — include torch.cuda if cuda: args.extend(["--hidden-import", "torch.cuda"]) # CPU builds — exclude NVIDIA packages to save ~3GB else: for pkg in ["nvidia", "nvidia.cublas", "nvidia.cudnn", ...]: args.extend(["--exclude-module", pkg]) ``` -------------------------------- ### Packaging CUDA Binary and Libraries (Python) Source: https://docs.voicebox.sh/developer/building Python script used to package the CUDA-enabled server binary and associated NVIDIA runtime libraries into separate archives for distribution. This allows for on-demand downloading by users who enable CUDA. ```python # Example usage within the build process: # scripts/package_cuda.py # Produces: # voicebox-server-cuda.tar.gz (~945 MB) # cuda-libs-cu128-v1.tar.gz (~1.7 GB) ``` -------------------------------- ### List History - cURL Source: https://docs.voicebox.sh/api-reference/history/list_history_history_get Example of how to list generation history using cURL. This command sends a GET request to the /history endpoint. ```shell curl -X GET "http://localhost:8000/history" ``` -------------------------------- ### Get Voice Profile by ID (Java) Source: https://docs.voicebox.sh/api-reference/profiles/get_profile_profiles__profile_id__get A Java example for retrieving a voice profile by its ID. This typically involves using an HTTP client library like Apache HttpClient or OkHttp to make the GET request and parse the JSON response. Proper exception handling is essential. ```java import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.io.IOException; public class GetProfile { public static void main(String[] args) throws IOException, InterruptedException { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(java.net.URI.create("http://localhost:8000/profiles/string")) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.body()); } } ``` -------------------------------- ### Replace torchaudio.load with soundfile (Python) Source: https://docs.voicebox.sh/developer/tts-engines This snippet demonstrates how to replace the use of `torchaudio.load()` with `soundfile.read()` for audio file I/O. This is necessary for `torchaudio` versions 2.10 and later, which require the `torchcodec` package for audio loading. `soundfile` provides a compatible alternative. ```python # Before (breaks without torchcodec): import torchaudio waveform, sr = torchaudio.load("audio.wav") # After: import soundfile as sf import torch data, sr = sf.read("audio.wav", dtype="float32") waveform = torch.from_numpy(data).unsqueeze(0) ``` -------------------------------- ### Grant Execute Permissions on macOS/Linux Source: https://docs.voicebox.sh/overview/troubleshooting Grants execute permissions to a file on macOS or Linux. This is necessary for server binaries to run correctly, especially after installation or updates. ```shell chmod +x ~/Library/Application\ Support/com.voicebox.app/backend/voicebox-server ``` -------------------------------- ### Check Port Usage on Windows Source: https://docs.voicebox.sh/overview/troubleshooting Checks if a specific port is currently in use on Windows systems using PowerShell. This helps identify if a port conflict is preventing a server from starting. ```powershell Get-NetTCPConnection -LocalPort 17493 -State Listen ``` -------------------------------- ### Cloning and Branching in Git Source: https://docs.voicebox.sh/developer/contributing Demonstrates how to fork and clone the Voicebox repository, and create new branches for feature development, bug fixes, or documentation updates using Git. ```git # Fork the repository on GitHub # Then clone your fork git clone https://github.com/YOUR_USERNAME/voicebox.git cd voicebox # For features git checkout -b feature/voice-effects # For bug fixes git checkout -b fix/audio-playback-issue # For documentation git checkout -b docs/api-examples ``` -------------------------------- ### List History - C# Source: https://docs.voicebox.sh/api-reference/history/list_history_history_get Example of how to list generation history using C#'s HttpClient. This code sends a GET request to the /history endpoint and displays the response content. ```csharp using System; using System.Net.Http; using System.Threading.Tasks; public class HistoryClient { public static async Task Main(string[] args) { using (HttpClient client = new HttpClient()) { try { HttpResponseMessage response = await client.GetAsync("http://localhost:8000/history"); response.EnsureSuccessStatusCode(); // Throw if HTTP status code is not 2xx string responseBody = await response.Content.ReadAsStringAsync(); Console.WriteLine(responseBody); } catch (HttpRequestException e) { Console.WriteLine($"Request error: {e.Message}"); } } } } ``` -------------------------------- ### Initialize Voicebox Backend Server Source: https://docs.voicebox.sh/overview/remote-mode Commands to clone the repository, install Python dependencies, and launch the backend server on a remote machine. Requires Python and pip environment. ```bash git clone https://github.com/jamiepine/voicebox.git cd voicebox/backend pip install -r requirements.txt pip install git+https://github.com/QwenLM/Qwen3-TTS.git uvicorn main:app --host 0.0.0.0 --port 17493 ``` -------------------------------- ### List History - Java Source: https://docs.voicebox.sh/api-reference/history/list_history_history_get Example of how to list generation history using Java's HttpClient. This code demonstrates making a GET request to the /history endpoint and printing the response body. ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.io.IOException; public class HistoryClient { public static void main(String[] args) throws IOException, InterruptedException { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("http://localhost:8000/history")) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.body()); } } ``` -------------------------------- ### Setting Qwen TTS Path Environment Variable (Bash) Source: https://docs.voicebox.sh/developer/building An example of setting the `QWEN_TTS_PATH` environment variable. This is used to specify the local source path for the Qwen3-TTS model, which is necessary for certain build configurations. ```bash export QWEN_TTS_PATH=~/path/to/Qwen3-TTS # Use local Qwen3-TTS source ``` -------------------------------- ### Voice Prompt Patterns in Python Source: https://docs.voicebox.sh/developer/tts-engines Illustrates different patterns for handling voice prompts in TTS backends. These patterns cover pre-computed tensors, deferred file paths, and hybrid approaches, along with caching strategies. ```python # Pattern A: Pre-computed tensors (Qwen, LuxTTS) encoded = model.encode_prompt(audio_path) # return encoded, False # (prompt_dict, was_cached) # Pattern B: Deferred file paths (Chatterbox, MLX) # return {"ref_audio": audio_path, "ref_text": reference_text}, False # Pattern C: Hybrid (possible for new engines) # embedding = model.extract_speaker(audio_path) # return {"embedding": embedding, "ref_audio": audio_path}, False # If caching, prefix your cache keys: # cache_key = "yourengine_" + get_cache_key(audio_path, reference_text) ``` -------------------------------- ### List History - Python Source: https://docs.voicebox.sh/api-reference/history/list_history_history_get Example of how to list generation history using Python's requests library. This code sends a GET request to the /history endpoint and prints the JSON response. ```python import requests response = requests.get('http://localhost:8000/history') print(response.json()) ``` -------------------------------- ### Runtime Frozen-Build Handling in server.py Source: https://docs.voicebox.sh/developer/tts-engines This code snippet shows essential runtime handling for frozen builds, specifically calling `multiprocessing.freeze_support()` in the `backend/server.py` entry point. This must be executed before any multiprocessing operations to prevent crashes in bundled applications. ```python # 1. freeze_support() — MUST be called before any multiprocessing use import multiprocessing multiprocessing.freeze_support() ``` -------------------------------- ### List History - JavaScript Source: https://docs.voicebox.sh/api-reference/history/list_history_history_get Example of how to list generation history using JavaScript's fetch API. This code demonstrates making a GET request to the /history endpoint and handling the JSON response. ```javascript fetch('http://localhost:8000/history') .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error('Error:', error)); ``` -------------------------------- ### Apply Audio Effects Chain (Python) Source: https://docs.voicebox.sh/developer/effects-pipeline Applies a chain of audio effects to a generation version. This involves building a Pedalboard from the effects chain and processing the audio asynchronously. Requires the 'pedalboard' and 'asyncio' libraries. ```python from pedalboard import Pedalboard import asyncio # Assume build_pedalboard and effects_chain are defined elsewhere # board = build_pedalboard(effects_chain) # audio = ... # loaded audio data # sample_rate = ... # audio sample rate # processed = await asyncio.to_thread(lambda: board(audio, sample_rate)) ``` -------------------------------- ### Transcription with Language Hint Example (Python) Source: https://docs.voicebox.sh/developer/transcription Demonstrates how to use the transcribe method with and without a language hint. Providing a language hint can improve accuracy, especially for shorter audio clips. ```python # Without language hint - auto-detect transcription = await whisper.transcribe(audio_path) # With language hint - more accurate for short clips transcription = await whisper.transcribe(audio_path, language="en") ``` -------------------------------- ### Get Voice Profile by ID (Go) Source: https://docs.voicebox.sh/api-reference/profiles/get_profile_profiles__profile_id__get Provides a Go implementation for retrieving a voice profile by its ID. This example shows how to construct the HTTP request and handle the JSON response. It's crucial to manage potential errors during the request and parsing phases. ```go package main import ( "fmt" "net/http" "io/ioutil" ) func main() { resp, err := http.Get("http://localhost:8000/profiles/string") if err != nil { fmt.Println("Error making request:", err) return } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { fmt.Println("Error reading response body:", err) return } fmt.Println(string(body)) } ``` -------------------------------- ### Auto-Update CUDA Binary Check - Python Source: https://docs.voicebox.sh/developer/autoupdater This Python code snippet demonstrates the logic for checking and updating the CUDA binary on server startup. It compares the installed CUDA binary version with the current application version and triggers a background download if they do not match. This ensures the backend always uses the latest compatible CUDA binary. ```python # backend/services/cuda.py cuda_version = get_cuda_binary_version() # runs `voicebox-server-cuda --version` current_version = __version__ if cuda_version != current_version: await download_cuda_binary() # Auto-download in background ``` -------------------------------- ### Running Frontend Tests with Bun Source: https://docs.voicebox.sh/developer/contributing Command to run frontend tests, likely using Jest or a similar framework integrated with Bun. ```bash bun run test ``` -------------------------------- ### Get Audio File using C# Source: https://docs.voicebox.sh/api-reference/generation/get_audio_audio__generation_id__get This snippet demonstrates how to get a generated audio file using C#. It utilizes the HttpClient class to make the GET request. The method returns the audio stream or throws an exception. ```csharp // C# example would go here, using System.Net.Http.HttpClient. ``` -------------------------------- ### Build and Development Commands Source: https://docs.voicebox.sh/developer/architecture Shell commands for managing the development lifecycle and production builds of the Voicebox application, including the frontend, backend server, and Tauri desktop wrapper. ```bash # Frontend (Vite dev server) cd app && bun run dev # Backend (manual start) cd backend && uvicorn main:app --reload # Desktop app (connects to manual backend) bun run dev ``` ```bash # Build everything (server binary + Tauri app) bun run build # Build server binary (PyInstaller) bun run build:server # Build Tauri app cd tauri && bun run tauri build ``` -------------------------------- ### Test Model Loading on CPU with PyTorch Source: https://docs.voicebox.sh/developer/tts-engines Tests loading a model on the CPU using PyTorch to catch potential mapping or data type issues early. It also includes a test with a float32 audio array. ```python import torch import numpy as np # Force CPU to catch map_location bugs early model = ModelClass.from_pretrained("org/model", device="cpu") # Test with a float32 audio array (not float64) audio = np.random.randn(16000).astype(np.float32) output = model.generate("Hello world", audio) print(f"Output shape: {output.shape}, dtype: {output.dtype}, sample rate: {model.sample_rate}") ``` -------------------------------- ### Get Profile Samples - C# Source: https://docs.voicebox.sh/api-reference/profiles/get_profile_samples_profiles__profile_id__samples_get A C# method to get all samples for a voice profile. It utilizes `HttpClient` to send a GET request to the specified endpoint. The method includes basic error handling for the HTTP response. ```csharp using System; using System.Net.Http; using System.Threading.Tasks; public class VoiceboxApiClient { private readonly HttpClient _httpClient; public VoiceboxApiClient() { _httpClient = new HttpClient(); _httpClient.BaseAddress = new Uri("http://localhost:8000/"); } public async Task GetProfileSamplesAsync(string profileId) { HttpResponseMessage response = await _httpClient.GetAsync($"profiles/{profileId}/samples"); response.EnsureSuccessStatusCode(); // Throws an exception if the status code is not success return await response.Content.ReadAsStringAsync(); } } ``` -------------------------------- ### Get Audio File using JavaScript Source: https://docs.voicebox.sh/api-reference/generation/get_audio_audio__generation_id__get This snippet shows how to retrieve a generated audio file using JavaScript. It makes a GET request to the /audio/{generation_id} endpoint. The response will be the audio file or an error. ```javascript // JavaScript example would go here, making a fetch or axios request to the endpoint. ``` -------------------------------- ### Generate OpenAPI Client Source: https://docs.voicebox.sh/developer/setup This command generates the TypeScript API client for the Voicebox backend. It downloads the OpenAPI schema from the running backend and creates the client in the specified directory. ```bash just generate-api ``` -------------------------------- ### Get Voice Profile by ID (C#) Source: https://docs.voicebox.sh/api-reference/profiles/get_profile_profiles__profile_id__get Demonstrates how to get a voice profile by its ID in C#. This involves using `HttpClient` to send a GET request and process the JSON response. Error handling for network issues and API errors should be implemented. ```csharp using System; using System.Net.Http; using System.Threading.Tasks; public class GetProfileClient { static readonly HttpClient client = new HttpClient(); public static async Task GetProfileAsync(string profileId) { try { HttpResponseMessage response = await client.GetAsync($"http://localhost:8000/profiles/{profileId}"); response.EnsureSuccessStatusCode(); // Throw if HTTP status code is not 2xx string responseBody = await response.Content.ReadAsStringAsync(); Console.WriteLine(responseBody); } catch (HttpRequestException e) { Console.WriteLine($"Request error: {e.Message}"); } } public static async Task Main(string[] args) { await GetProfileAsync("string"); } } ``` -------------------------------- ### GET /audio/{generation_id} Source: https://docs.voicebox.sh/api-reference/generation/get_audio_audio__generation_id__get Serve generated audio file using the provided generation ID. ```APIDOC ## GET /audio/{generation_id} ### Description Serve generated audio file using the provided generation ID. ### Method GET ### Endpoint http://localhost:8000/audio/{generation_id} ### Parameters #### Path Parameters - **generation_id** (string) - Required - The ID of the audio generation. ### Response #### Success Response (200) - **null** (null) - Indicates successful retrieval of the audio file. #### Error Response (422) - **detail** (array) - An array of error objects detailing the issue. - **loc** (array) - The location of the error in the request. - **msg** (string) - The error message. - **type** (string) - The type of error. ### Request Example ```curl curl -X GET "http://localhost:8000/audio/string" ``` ### Response Example #### 200 ```json null ``` #### 422 ```json { "detail": [ { "loc": [ "string" ], "msg": "string", "type": "string" } ] } ``` ``` -------------------------------- ### Tauri Sidecar Configuration (JSON) Source: https://docs.voicebox.sh/developer/building Configuration within `tauri.conf.json` that declares the server binary as an external binary. Tauri automatically finds and bundles the `voicebox-server-${PLATFORM}` binary located in the `src-tauri/binaries/` directory. ```json { "tauri": { "bundle": { "externalBin": ["binaries/voicebox-server"] } } } ``` -------------------------------- ### Load Qwen3-TTS Model Source: https://docs.voicebox.sh/developer/tts-generation Handles downloading and loading the Qwen3-TTS model from the HuggingFace Hub. Includes both synchronous and asynchronous loading methods to ensure non-blocking performance. ```python def load_model(self, model_size: Optional[str] = None): hf_model_map = { "1.7B": "Qwen/Qwen3-TTS-12Hz-1.7B-Base", "0.6B": "Qwen/Qwen3-TTS-12Hz-0.6B-Base", } with tracker.patch_download(): self.model = Qwen3TTSModel.from_pretrained( model_path, device_map=self.device, torch_dtype=torch.bfloat16, ) async def load_model_async(self, model_size: Optional[str] = None): if self.model is not None and self._current_model_size == model_size: return await asyncio.to_thread(self.load_model, model_size) ``` -------------------------------- ### Running Backend Tests with Pytest Source: https://docs.voicebox.sh/developer/contributing Command to execute backend unit and integration tests using the Pytest framework. ```bash cd backend pytest ``` -------------------------------- ### GET Root Endpoint (cURL) Source: https://docs.voicebox.sh/api-reference/general/root__get Retrieves information from the root endpoint of the Voicebox API. This is a basic GET request to the root URL. ```cURL curl -X GET "http://localhost:8000" ``` -------------------------------- ### POST /effects/presets Source: https://docs.voicebox.sh/developer/effects-pipeline Creates a new user-defined effect preset for future reuse across different generations. ```APIDOC ## POST /effects/presets ### Description Saves a new effects chain configuration as a user preset in the database. ### Method POST ### Endpoint /effects/presets ### Request Body - **name** (string) - Required - The display name for the preset - **effects_chain** (array) - Required - The sequence of effects to save ### Request Example { "name": "My Custom Radio", "effects_chain": [ {"type": "high_pass", "cutoff_frequency_hz": 300} ] } ### Response #### Success Response (200) - **id** (string) - The unique ID of the created preset ```