Metadata-Version: 2.4
Name: apexmusic
Version: 1.0.1
Summary: A dark music brand
Author-email: Jorge Albuquerque <sonoriabr@gmail.com>
License: MIT License
        
        Copyright (c) 2026 Jorge Albuquerque
        
        Permission is hereby granted, free of charge, to any person obtaining a copy
        of this software and associated documentation files (the "Software"), to deal
        in the Software without restriction, including without limitation the rights
        to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        copies of the Software, and to permit persons to whom the Software is
        furnished to do so, subject to the following conditions:
        
        The above copyright notice and this permission notice shall be included in all
        copies or substantial portions of the Software.
        
        THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        SOFTWARE.
        
Keywords: music,machine,audio,ai,lyrics
Classifier: Development Status :: 3 - Alpha
Classifier: Environment :: Console
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: typer>=0.12.0
Requires-Dist: pyllmrouter[all]>=0.4.2
Requires-Dist: diffusers>=0.36.0
Requires-Dist: transformers>=5.2.0
Requires-Dist: accelerate>=1.12.0
Requires-Dist: torch>=2.10.0
Requires-Dist: chromadb>=0.5.0
Requires-Dist: requests>=2.32.0
Requires-Dist: beautifulsoup4>=4.12.0
Requires-Dist: google-api-python-client>=2.140.0
Requires-Dist: google-auth-httplib2>=0.2.0
Requires-Dist: google-auth-oauthlib>=1.2.0
Provides-Extra: dev
Requires-Dist: pytest>=8.0; extra == "dev"
Requires-Dist: pytest-cov>=5.0; extra == "dev"
Requires-Dist: ruff>=0.5.0; extra == "dev"
Requires-Dist: pyrefly>=0.1.0; extra == "dev"
Dynamic: license-file

# Apex Music Machine

**An AI music studio in a command line:** study a band's lyrics, write new songs in that style, turn them into music,
plan and render a music video, and publish it – with *any* LLM you happen to have (Claude, Gemini, Codex, Ollama,
llama.cpp…) through [**pyllmrouter**](https://github.com/fortalbrz/pyllmrouter) (no paid API key required, just regular OAUTH sign-in).


![apex music machone](docs/img/logo.jpg)

## Overview

Apex Music Machine is a Python package and CLI (`apexmusic`) that automates the creative chain of an independent music
brand. Every step is a stand-alone command, and one command (`pipeline`) runs them all:

```text
 Genius / AZLyrics ─► download-lyrics ─► lyrics/*.md ─► ChromaDB  (embeddings via pyllmrouter: gemini | ollama | llamacpp)
                                                           │
   topic ─► infer-lyrics / lyrics ◄── retrieves similar passages, writes NEW lyrics with any LLM provider (pyllmrouter)
                 │                    (+ title, critic analysis, social post, translations)
                 ▼
   generate-music  (Suno gateway in Docker) ─► MP3
                 ▼
   video           (LLM "director": concept, scenes, image prompts) ─► video plan  ─► image / video generation
                 ▼
   cartoon         (AnimeGAN on the GPU, optional optical-flow stabilisation) ─► stylised video
                 ▼
   upload-youtube  (YouTube Data API, OAuth, resumable upload) ─► published video
```

| Capability | Command | What it does | Needs |
|---|---|---|---|
| LLM access | `providers`, `chat`, `test` | 8 interchangeable LLM backends, auto-detected; interactive chat | at least one provider |
| Lyrics library | `download-lyrics` | Saves a band's complete lyrics as markdown | `GENIUS_API_KEY` (or AZLyrics fallback) |
| Lyric writing (RAG) | `infer-lyrics`, `lyrics` | New lyrics in the band's style; `lyrics` also returns title, analysis, social post and translations as JSON | an embedding provider (Gemini, Ollama or llama.cpp) + any LLM provider |
| Music | `suno-gateway`, `generate-music` | Generates a track from style + lyrics through a Suno gateway | Docker, `SUNO_COOKIE` |
| Video plan | `video` | An LLM "director" turns song + lyrics into concepts, scenes and image prompts | any LLM provider |
| Video stylisation | `cartoon` | Converts a video to a cartoon on the GPU (AnimeGAN, optional temporal stabilisation) | NVIDIA GPU, FFmpeg with NVENC |
| Publishing | `upload-youtube` | Resumable YouTube upload with cached OAuth | Google OAuth client secret |
| Automation | `bots` | Opens many browser instances on a URL list | Selenium (optional) |
| End to end | `pipeline` | lyrics → music → video plan → YouTube in one go | all of the above you do not skip |

## Installation

### Prerequisites
- **Python 3.10+** and [`uv`](https://docs.astral.sh/uv/) (recommended) or `pip`
- **At least one LLM provider** (see [LLM providers](#llm-providers-pyllmrouter)): a Claude login/token/API key, a Gemini key,
  an Antigravity (`agy`) or ChatGPT/Codex sign-in, a local Ollama, or a llama.cpp server
- **An embedding provider** if you use the lyric RAG commands: **Gemini** (`GEMINI_API_KEY`), **Ollama** (with an
  embedding model, e.g. `ollama pull qwen3-embedding:4b`) or a **llama.cpp** server started with `--embeddings`. Embeddings go through
  pyllmrouter just like chat, so they are auto-detected too (Claude, Codex and Antigravity have no embeddings API)
- An **NVIDIA GPU + CUDA** for image generation and the `cartoon` command; **FFmpeg/FFprobe** (with NVENC for `cartoon`)
- Optional: **Docker** (Suno gateway), a **Genius API key**, a Google **OAuth client secret** (YouTube)

### Setup


```bash
pip install apexmusic
```

1. Install the package (this also installs [`pyllmrouter`](https://github.com/fortalbrz/pyllmrouter) with all of its provider SDKs):
```bash
uv sync                      # or: pip install -e .
uv sync --extra dev          # development tools: pytest, ruff, pyrefly
```

2. Set up at least one LLM provider – check what is usable with `apexmusic providers`. Examples:
```bash
# local: Ollama (chat model + embedding model for the lyric RAG)
ollama pull qwen3:8b && ollama pull qwen3-embedding:4b && ollama serve
# cloud: Claude API key / Gemini API key / Claude subscription token (claude setup-token) ...
export ANTHROPIC_API_KEY=sk-ant-...      # or GEMINI_API_KEY, CLAUDE_CODE_OAUTH_TOKEN
```
   Full guide: [LLM providers](#llm-providers-pyllmrouter).

3. Optional services, only for the steps you use:
```bash
export GENIUS_API_KEY=...                # download-lyrics (otherwise AZLyrics scraping)
export SUNO_COOKIE=...                   # generate-music (Suno gateway)
export YOUTUBE_CLIENT_SECRET=client_secret.json   # upload-youtube
```

## Quick Start

```bash
apexmusic providers                                   # which LLM providers work right now
apexmusic chat                                        # talk to the auto-detected provider
apexmusic download-lyrics "Some Band" -o lyrics       # 1. build the lyric library
apexmusic lyrics "midnight rain" -d lyrics            # 2. write new lyrics (+ analysis, translations) as JSON
apexmusic suno-gateway start                          # 3. start the Suno gateway ...
apexmusic generate-music "dark metal, atmospheric" -l lyrics.txt   #    ... and make the song
apexmusic video --info song.json                      # 4. plan the music video
apexmusic cartoon -i clip.mp4 -o clip_cartoon.mp4     # 5. stylise a video
apexmusic upload-youtube clip_cartoon.mp4 --privacy unlisted       # 6. publish
apexmusic pipeline "Some Band" --topic "midnight rain" --skip-upload   # ... or all of it at once
```

### Command Options

```bash
apexmusic [OPTIONS] COMMAND

Options:
  --version              Show program version and exit
  -v, --verbose          Enable verbose output
  --provider NAME        LLM provider: claude-agent-token | claude-agent-login | claude |
                         gemini | antigravity | codex | ollama | llamacpp
                         (default: not set = auto-detect the first available, in that order)
  --model MODEL          Model for the selected provider (default: the provider's default)
  --embedding-provider NAME   Embeddings (lyric RAG): gemini | ollama | llamacpp
                         (default: not set = auto-detect the first available, in that order)
  --embedding-model MODEL     Embedding model (default: the provider's default; Ollama: qwen3-embedding:4b)

Commands:
  providers              Show which LLM and embedding providers are available (--embeddings, --json)
  chat                   Interactive chat with the AI assistant
  test                   System health checks (GPU, LLM providers)
  download-lyrics        Download all lyrics of a band as markdown files
  lyrics                 Write new lyrics with RAG + title, analysis, social post and translations (JSON)
  suno-gateway           start | stop | status the Suno Docker gateway
  generate-music         Generate a music track through the gateway
  video                  Create a music video plan from a song-info JSON file
  cartoon                Convert a video to a cartoon (avoid video restrictions)
  upload-youtube         Upload a video to YouTube
  bots                   Browser automation over a URL list (check and testing)
  pipeline               Run lyrics -> music -> video -> YouTube end to end
```

## Features in detail

### LLM layer – any provider, auto-detected
Every LLM-backed command (`chat`, `video`, `infer-lyrics`, `lyrics`, `pipeline`) goes through
[`pyllmrouter`](https://github.com/fortalbrz/pyllmrouter): eight interchangeable backends, a priority-ordered **auto-detection**
that only runs when you did not pick a provider, per-provider model defaults, thread-safe and async chats, and retries for
transient failures. See [LLM providers](#llm-providers-pyllmrouter).

### Lyrics library – `download-lyrics`
```bash
apexmusic download-lyrics "Band Name" [-o DIR] [--delay 1.5]
```
Saves every song of a band as a markdown file. It uses the **Genius API** when `GENIUS_API_KEY` is set and otherwise
scrapes **AZLyrics**, with polite delays (`--delay`) and up to five retries with exponential back-off (3, 6, 12, 24, 48 s).

### Lyric writing with retrieval – `infer-lyrics` and `lyrics`
```bash
apexmusic infer-lyrics "a lighthouse keeper's last night" -d lyrics -o new.txt [--backend claude] [--model ...] [--reindex]
apexmusic lyrics       "a lighthouse keeper's last night" -d lyrics -o out/    [--backend gemini]
```
The lyric files are split into overlapping chunks (about 800 characters, 3 lines of overlap) and indexed once in a
persistent **ChromaDB** collection (`--db-path`, `--reindex` rebuilds it). The vectors are computed through
**pyllmrouter** by the embedding provider you choose (`--embedding-provider gemini|ollama|llamacpp`, or auto-detected; default
Ollama model `qwen3-embedding:4b`, override with `--embedding-model` or `OLLAMA_EMBED_MODEL` / `GEMINI_EMBED_MODEL`). Every
embedding space (provider + model) gets **its own collection**, so changing the embedder never mixes incompatible vectors – the
new space is simply indexed on first use, and an index built before with Ollama `qwen3-embedding:4b` is reused as is. For a
topic, the most relevant passages are retrieved and the chosen LLM writes **new, original lyrics in the same style** (section tags such as `[Verse]`, `[Chorus]`).

* `infer-lyrics` returns the lyrics as text.
* `lyrics` additionally produces, each in its **own isolated chat session** (a failure in one field never loses the rest),
  a **title** (five words or fewer), a two-paragraph **critic analysis**, a **social-media post**, and **translations**
  (Spanish, Brazilian Portuguese and German by default), saved as `<title>.json`.
* The LLM is whatever `--backend` / `--provider` / `LLM_BACKEND` selects, or the first available provider.

### Music generation – `suno-gateway` and `generate-music`
```bash
apexmusic suno-gateway start|stop|status [--port 3000]
apexmusic generate-music "dark metal, aggressive" -l lyrics.txt -t "Song Title" -s "dark metal, atmospheric" -o output/music
```
Runs the community Suno API gateway (`gcui/suno-api`) in Docker and calls it over REST, polling until the track is ready
and downloading the MP3. Requires Docker and `SUNO_COOKIE` from an authenticated Suno session; `SUNO_API_URL` (or `--api-url`)
points at another gateway.

### Music video planning – `video`
```bash
apexmusic video --info song.json [--lyrics lyrics.txt]      # or: apexmusic video -f song.mp3
```
An LLM **"director"** (`MusicVideoDirector`) analyses the song and its lyrics, then proposes visual themes, aesthetics, a
storyline and a scene-by-scene plan with generation prompts. `ImageGenerator` / `VideoGenerator` (Hugging Face
`diffusers`, Stable Diffusion) can then render the frames, with optional reference-image guidance.
The song-info JSON carries `song_title`, `lyrics`, `clip_description`, `duration`, `prompt`, `language` and `audio_file`
(see `docs/sample_song_info.json`).

### Video stylisation – `cartoon`
```bash
apexmusic cartoon -i input.mp4 -o output_cartoon.mp4 [--optical_flow]
```
A GPU pipeline: **NVDEC** hardware decoding → **AnimeGAN** (`face_paint_512_v2` by default; `celeba_distill`,
`face_paint_512_v1` and `paprika` are available) in FP16 batches → **NVENC** hardware encoding (`h264_nvenc`, or
`hevc_nvenc`) through FFmpeg, keeping the audio. `--optical_flow` turns on **temporal stabilisation**
(`TemporalStabilizedAnimeGAN`, RAFT optical-flow warping of the previous stylised frame) to remove flicker between frames.
Requires an NVIDIA GPU with CUDA and FFmpeg/FFprobe with NVENC support; the CLI validates this before starting.
Library users configure everything through `PipelineConfig` (batch size, `cq`, NVENC preset, …).

### Publishing – `upload-youtube`
```bash
apexmusic upload-youtube video.mp4 -t "Title" -d "Description" --tags "ai music,metal" --privacy unlisted
```
YouTube Data API v3 with the OAuth 2.0 installed-app flow (browser consent on first use, token cached in
`.youtube_token.json`) and **resumable** 256 KB-chunk uploads. Privacy: `public`, `unlisted` or `private`.

### Browser automation – `bots`
Opens a list of URLs in many browser instances (Selenium with automatic fallback to the system browser), with parallelism
limits, a watchdog timer, process monitoring and automatic closure. See [apexmusic.processing.bots](#apexmusicprocessingbots).

### End to end – `pipeline`
```bash
apexmusic pipeline "Band Name" --topic "dark metal journey" --style "dark metal, aggressive, atmospheric" \
    --privacy unlisted [--skip-download] [--skip-upload]
```
Runs: **download lyrics → write new lyrics → generate music → plan the video → upload to YouTube**, stopping with a clear
error at the first failing step. Skip flags let you reuse an existing lyric library or keep the result local.

### Diagnostics – `providers` and `test`
`apexmusic providers` prints every LLM provider with the reason it is or is not usable (`--json` for scripts), and
`apexmusic test` checks the GPU and the providers.

> **Paths.** Default folders in [`constants.py`](src/apexmusic/constants.py) (lyrics, ChromaDB, output) point at
> `d:\dev\bots\apex\…`; every command has an option (`-d`, `--db-path`, `-o`) to use your own.

## Module Documentation

### apexmusic Package

Main package initialization and metadata.

**File**: `src/apexmusic/__init__.py`

Version: see `apexmusic --version` (read from the installed package metadata)  
Author: Jorge Albuquerque  
Email: sonoriabr@gmail.com

### apexmusic.__main__

Command-line interface (built with [Typer](https://typer.tiangolo.com/)); registered as the `apexmusic` console script.

**File**: `src/apexmusic/__main__.py`

- A global callback resolves `--verbose`, `--provider` and `--model` into a small state object that every command reads.
- Each command is a thin Typer function delegating to a `_handle_*` function that holds the logic and returns an exit code
  (handlers are plain functions, easy to unit-test).
- LLM objects are created only through `apexmusic.llm.chat.create_llm` (see below); nothing branches on provider names.
- The `pipeline` command chains the handlers and stops with a clear message at the first failing step.

```bash
apexmusic --verbose chat
apexmusic --provider ollama --model qwen3:8b video -f song.mp3
apexmusic providers            # which LLM providers are usable right now
```

### apexmusic.constants

Configuration constants and defaults.

**File**: `src/apexmusic/constants.py`

**Constants**:
- `DEFAULT_OLLAMA_MODEL = 'qwen3.5:9b-q4_K_M'`: Default Ollama model name (application default; env `OLLAMA_MODEL` and `--model` override it)
- `DEFAULT_OLLAMA_EMBEDDING = 'qwen3-embedding:4b'`: Application default of the `ollama` embedding provider
- `DEFAULT_CLAUDE_MODEL = 'claude-sonnet-4-6'`: Default model of the `claude` (Anthropic API) provider

---

## LLM Package (apexmusic.llm)

Handles interaction with language models and document processing.

### apexmusic.llm.chat

Thin integration layer over [`pyllmrouter`](https://github.com/fortalbrz/pyllmrouter), the reusable package that
holds every LLM provider implementation.

**File**: `src/apexmusic/llm/chat.py`

| Symbol | Description |
|---|---|
| `create_llm(provider=None, model=None, **kwargs)` | Create the chat backend. **Use this instead of instantiating provider classes.** |
| `AbstractChat` | Alias of `pyllmrouter.BaseChat`: `chat()`, `chat_stream()`, `achat()`, `set_system_message()`, `get_history()`, `reset_conversation()`, `verify_connection()` |
| `LLMError` | Raised for every LLM failure (alias of `pyllmrouter.LLMError`) |
| `APEX_DEFAULT_MODELS` | Application model defaults per provider (`claude` → `DEFAULT_CLAUDE_MODEL`, `ollama` → `DEFAULT_OLLAMA_MODEL`) |

```python
from apexmusic.llm.chat import create_llm

chat = create_llm()                      # nothing set -> auto-detect the first available provider
chat = create_llm("ollama")              # explicit provider, application default model
chat = create_llm("claude", "claude-sonnet-4-6")
chat.set_system_message("You are a music theory expert. Be concise.")
print(chat.chat("Write a song chorus about midnight"))
for token in chat.chat_stream("And a bridge?"):
    print(token, end="")
```

All history, streaming and error semantics are those of `pyllmrouter.BaseChat` (a failed or aborted turn is rolled
back; every failure is an `LLMError`). See the [pyllmrouter README](https://github.com/fortalbrz/pyllmrouter#readme)
for the complete API.

### apexmusic.llm.embeddings

The same thin layer for **text embeddings** (lyric RAG); see [Embeddings](#embeddings-through-pyllmrouter-too).

**File**: `src/apexmusic/llm/embeddings.py`

| Symbol | Description |
|---|---|
| `create_app_embedder(provider=None, model=None, **kwargs)` | Create the embedder (any `pyllmrouter` embedding provider). **The only way embeddings are created.** |
| `APEX_DEFAULT_EMBEDDING_MODELS` | Application embedding defaults per provider (`ollama` → `DEFAULT_OLLAMA_EMBEDDING`) |
| `collection_name(signature)` | ChromaDB collection of one embedding space (`lyrics` for the legacy Ollama space) |

## LLM providers (pyllmrouter)

All provider logic lives in a separate, reusable project: **[pyllmrouter](https://github.com/fortalbrz/pyllmrouter)** – "one chat
interface, eight LLM backends, automatic provider detection – thread-safe and async". Apex depends on it from
PyPI (`pyllmrouter[all]>=0.4.2`, pinned by `uv.lock`) and only adds
application defaults on top. The pyllmrouter README has the full guides (install and sign-in steps with screenshots for
Claude, Antigravity and Codex), the Python API, the concurrency/async contract and troubleshooting.

What this gives Apex: a Claude subscription, an API key, a Google AI plan, a ChatGPT plan or a local model all work with the
same commands; batch jobs can share a chat across threads or use one per worker; async code never blocks its event loop;
and transient failures (connection refused, HTTP 429/5xx) are retried before any output is produced.

### Embeddings through pyllmrouter too

**Every model call in Apex goes through pyllmrouter – text generation *and* embeddings** (a test fails if any module imports
an LLM SDK such as `ollama`, `anthropic` or `google.genai`, or hard-codes a model endpoint). Embeddings follow the same rules as
chat, restricted to the providers that have an embeddings API:

| Provider | Embeddings | Default embedding model |
|---|---|---|
| `gemini` | yes | `gemini-embedding-001` (`GEMINI_EMBED_MODEL`) |
| `ollama` | yes | `qwen3-embedding:4b` (application default; `OLLAMA_EMBED_MODEL` / `--embedding-model`) |
| `llamacpp` | yes (server started with `--embeddings`; `LLAMACPP_EMBED_SERVER`) | the loaded model |
| `claude-agent-*`, `claude`, `antigravity`, `codex` | **no** – asking for them is a clear error | – |

1. Set explicitly – `--embedding-provider NAME`, else `EMBEDDING_BACKEND`, else `LLMROUTER_EMBEDDING_PROVIDER` → used, not probed.
2. **Nothing set** → auto-detection over `gemini` → `ollama` → `llamacpp`; the probe checks that the **model exists** (for Ollama:
   `ollama pull qwen3-embedding:4b`). `apexmusic providers --embeddings` shows the result.

```bash
apexmusic --embedding-provider ollama lyrics "midnight rain"
apexmusic --embedding-provider gemini --embedding-model gemini-embedding-001 infer-lyrics "midnight rain" --reindex
apexmusic providers --embeddings
```

> **Cloud embeddings send your lyric text to that provider.** Auto-detection is consistent with chat (first available), so a
> machine with `GEMINI_API_KEY` set and no `--embedding-provider` will embed through Gemini. Pin `--embedding-provider ollama`
> (or `EMBEDDING_BACKEND=ollama`) to keep lyrics local. Vectors of different providers/models are never mixed: each embedding
> space has its own ChromaDB collection (a new one is indexed on first use; `--reindex` rebuilds the current one).

**Which provider?** Local providers (`ollama`, `llamacpp`) are free, private and offline; cloud providers are stronger
at long-form creative writing. Subscription-backed ones (`claude-agent-*`, `antigravity`, `codex`) need no API billing but
are meant for your own local automation. `apexmusic providers` shows what is usable on *this* machine:

```text
$ apexmusic providers
LLM providers (auto-detection picks the first available, top to bottom):
  1. [-- ] claude-agent-token   CLAUDE_CODE_OAUTH_TOKEN is not set
  2. [-- ] claude-agent-login   claude CLI is not logged in (run: claude auth login)
  3. [OK ] anthropic            ANTHROPIC_API_KEY is set
  4. [OK ] gemini               GEMINI_API_KEY is set
  5. [-- ] antigravity          agy found (...) but not signed in: run `agy` and finish the browser sign-in
  6. [OK ] codex                signed in (API key) [SDK]
  7. [OK ] ollama               server http://localhost:11434 reachable, 7 model(s) pulled
  8. [-- ] llamacpp             server http://localhost:8080 not reachable (ConnectTimeout)
```

Every LLM-backed command (`chat`, `video`, `infer`, `lyrics`, ...) resolves its provider the same way.

**Provider selection**

1. A provider is set - `--backend NAME` (`infer` / `lyrics` only) or the global `--provider NAME`, else the
   `LLM_BACKEND` environment variable, else `LLMROUTER_PROVIDER` (first one wins) -> that provider is used and
   nothing is probed. `--model` works the same way (`--model` on the command, else the global `--model`).
2. **Nothing is set** -> auto-detection: all providers are checked in the priority order below and the first
   available one is used. If none works, the error lists the reason for each.

| # | `--provider` | Backend | Credential / requirement |
|---|---|---|---|
| 1 | `claude-agent-token` | Claude Agent SDK | `CLAUDE_CODE_OAUTH_TOKEN` (create with `claude setup-token`) |
| 2 | `claude-agent-login` | Claude Agent SDK | interactive login: `claude auth login` |
| 3 | `claude` (= `anthropic`) | Claude API | `ANTHROPIC_API_KEY` |
| 4 | `gemini` | Gemini API (`google-genai`) | `GEMINI_API_KEY` |
| 5 | `antigravity` (alias `agy`) | Antigravity CLI via `subprocess` | install `agy` (Windows PowerShell `irm https://antigravity.google/cli/install.ps1 \| iex`; Linux/macOS/WSL `curl -fsSL https://antigravity.google/cli/install.sh \| bash`), then run `agy` once to sign in with Google |
| 6 | `codex` | OpenAI Codex (official Python SDK `openai_codex` or CLI) | `npm install -g @openai/codex`, run `codex` and choose **Sign in with ChatGPT** (Plus / Pro / Business plans) |
| 7 | `ollama` | Ollama server | `ollama serve` (`OLLAMA_SERVER`, default `http://localhost:11434`) |
| 8 | `llamacpp` | llama.cpp `llama-server` | `llama-server -m model.gguf --jinja` (`LLAMACPP_SERVER`, default `http://localhost:8080`) |

```bash
apexmusic providers                       # table: which providers are usable and why not
apexmusic providers --json                # machine-readable
apexmusic chat                            # auto-detected provider
apexmusic --provider gemini chat          # explicit provider
apexmusic --provider ollama --model qwen3:8b lyrics "midnight rain"
apexmusic lyrics "midnight rain" --backend claude
LLM_BACKEND=ollama apexmusic infer "midnight rain"
```

**Models** - precedence, highest first: `--model` -> the provider's environment variable (`CLAUDE_MODEL`,
`OLLAMA_MODEL`, `GEMINI_MODEL`, `LLAMACPP_MODEL`) -> the application default (`DEFAULT_CLAUDE_MODEL` for
`claude`, `DEFAULT_OLLAMA_MODEL` for `ollama`) -> the provider's own default. Providers 1, 2, 4, 5 and 7 use
their own default unless you pass a model.

> **Behaviour change.** `--provider` used to default to `ollama` and `lyrics --backend` to `claude`. Both are now
> *unset*, so the first available provider is auto-detected. To pin the old behaviour, pass
> `--provider ollama` / `--backend claude` or set `LLM_BACKEND`.

Notes: Google ended "Sign in with Google" in the legacy Gemini CLI for individual accounts on 2026-06-18, so `gemini-cli`
was replaced by `antigravity` (`agy`; the old name still works as a deprecated alias). The Agent SDK tiers, `antigravity` and `codex` do not support `temperature` / `max_tokens` (ignored); the Claude API
tier never sends `temperature` (current Claude models reject it). See the
[pyllmrouter provider guides](https://github.com/fortalbrz/pyllmrouter#provider-guides) for details.

### apexmusic.llm.image

Image generation using Hugging Face diffusers models (Stable Diffusion).

**File**: `src/apexmusic/llm/image.py`

#### ImageGenerator

Generate images from text prompts with optional reference image guidance.

**Features**:
- Text-to-image generation using Stable Diffusion
- Reference image guidance for conditional generation
- Custom model selection and parameters
- GPU/CPU device support with automatic selection

**Attributes**:
- `model_id` (str): Hugging Face model ID for Stable Diffusion
- `device` (str): Device for inference ("cuda" or "cpu")
- `dtype` (torch.dtype): Data type for inference (float32 or float16)

**Constructor**:
```python
def __init__(
    self,
    model_id: str = "runwayml/stable-diffusion-v1-5",
    device: str = "cuda" if torch.cuda.is_available() else "cpu",
    dtype: torch.dtype = torch.float16 if torch.cuda.is_available() else torch.float32,
    enable_attention_slicing: bool = True,
)
```

**Parameters**:
- `model_id` (str): Hugging Face model identifier. Default: "runwayml/stable-diffusion-v1-5"
- `device` (str): Compute device ("cuda" for GPU or "cpu"). Automatically selects CUDA if available
- `dtype` (torch.dtype): Data type for inference
  - `torch.float16`: Faster, uses less memory (for CUDA)
  - `torch.float32`: Higher precision, slower (recommended for CPU)
- `enable_attention_slicing` (bool): Enable for memory-efficient inference. Default: True

##### `generate_from_prompt(prompt, negative_prompt=None, height=512, width=512, ...) -> List[Image.Image]`

Generate images from a text prompt.

**Parameters**:
- `prompt` (str): Text description of the image to generate
- `negative_prompt` (str, optional): Description of what NOT to include in the image
- `height` (int): Height of generated image in pixels. Default: 512
- `width` (int): Width of generated image in pixels. Default: 512
- `num_inference_steps` (int): Number of denoising steps. Higher = better quality but slower. Default: 50
- `guidance_scale` (float): Strength of prompt guidance (0.0 to 20.0). Higher = follow prompt more closely. Default: 7.5
- `num_images_per_prompt` (int): Number of images per prompt. Default: 1
- `seed` (int, optional): Random seed for reproducibility

**Returns**: List of PIL Image objects

**Example**:
```python
from apexmusic.llm.image import ImageGenerator

generator = ImageGenerator()

# Generate a single image
images = generator.generate_from_prompt(
    prompt="A dark cyberpunk cityscape at night with neon lights",
    negative_prompt="blurry, low quality, grainy",
    num_inference_steps=50,
    guidance_scale=7.5,
    seed=42
)

# Save the image
images[0].save("output.png")

# Generate multiple variations
images = generator.generate_from_prompt(
    prompt="Abstract music visualizer",
    num_images_per_prompt=4
)
```

##### `generate_from_reference(prompt, reference_image, negative_prompt=None, strength=0.75, ...) -> List[Image.Image]`

Generate images using a reference image and text prompt.

**Parameters**:
- `prompt` (str): Text description of the image to generate
- `reference_image` (str/Path/Image.Image): Path or PIL Image object for guidance
- `negative_prompt` (str, optional): Description of what NOT to include
- `strength` (float): How much the output resembles the reference (0.0 to 1.0). Default: 0.75
  - Lower values: Preserve more of reference image structure
  - Higher values: More creative deviation from reference
- `num_inference_steps` (int): Number of denoising steps. Default: 50
- `guidance_scale` (float): Strength of prompt guidance. Default: 7.5
- `num_images_per_prompt` (int): Number of images to generate. Default: 1
- `seed` (int, optional): Random seed for reproducibility

**Returns**: List of PIL Image objects

**Example**:
```python
# Use reference image to guide generation
images = generator.generate_from_reference(
    prompt="Transform to dark cyberpunk style",
    reference_image="original_photo.jpg",
    strength=0.75,
    guidance_scale=7.5
)
```

---

### apexmusic.llm.musicvideo

Music video director service for orchestrating video concept creation.

**File**: `src/apexmusic/llm/musicvideo.py`

#### Enums

##### `MusicSection`
Enumeration of music sections found in song lyrics.

**Values**:
- `INTRO`: Introductory section
- `VERSE`: Verse section
- `PRE_CHORUS`: Section before chorus
- `CHORUS`: Chorus/refrain section
- `BREAK`: Musical break or bridge
- `OUTRO`: Concluding section

#### Data Classes

##### `Scene`
Represents a single scene in the music video sequence.

**Attributes**:
- `sequence_number` (int): Position in sequence
- `start_time` (float): Scene start time in seconds
- `end_time` (float): Scene end time in seconds
- `duration` (timedelta): Scene duration
- `section_type` (str): Type of music section (from MusicSection)
- `description` (str): Detailed scene description
- `visual_elements` (List[str]): Visual components in the scene
- `mood` (str): Emotional mood of the scene
- `camera_movement` (str): Camera movement description
- `kling_prompt` (str, optional): Prompt for Kling video generation

##### `MusicAnalysis`
Results of music sentiment and structural analysis.

**Attributes**:
- `overall_sentiment` (str): Overall emotional tone
- `emotional_arc` (str): How emotions progress through the song
- `dominant_feelings` (List[str]): Primary emotions present
- `key_themes` (List[str]): Main themes or topics
- `suggested_aesthetics` (List[str]): Visual style suggestions
- `color_palette` (List[str]): Recommended colors
- `video_title` (str): Generated video title
- `video_description` (str): Generated video description

##### `VideoConceptPlan`
Complete music video concept plan.

**Attributes**:
- `concept_title` (str): Title of the video concept
- `concept_description` (str): Detailed concept description
- `visual_style` (str): Overall visual aesthetic
- `narrative_arc` (str): Story structure and progression
- `key_visual_metaphors` (List[str]): Visual symbolism used
- `color_scheme` (Dict[str, str]): Color palette with meanings
- `camera_style` (str): Camera work and framing style
- `overall_mood` (str): Emotional tone throughout

#### MusicVideoDirector

Service class for orchestrating music video creation using LLM capabilities.

**Attributes**:
- `lyrics` (str): Song lyrics with section annotations
- `duration` (float): Total song duration in seconds
- `clip_description` (str): General description or creative direction
- `chat_service` (AbstractChat): LLM service instance for analysis
- `artist_name` (str): Artist name for context (default: "Apex Music Machine")

**Constructor**:
```python
def __init__(self, llm_service: AbstractChat, artist_name: str = "Apex Music Machine") -> None
```

**Parameters**:
- `llm_service` (AbstractChat): Initialized chat service (any pyllmrouter provider, see `create_llm`)
- `artist_name` (str): Artist name for video context

**Example**:
```python
from apexmusic.llm.chat import create_llm
from apexmusic.llm.musicvideo import MusicVideoDirector

llm = create_llm()   # auto-detected provider
director = MusicVideoDirector(llm, artist_name="Your Band Name")

# Analyze song and create concepts
director.run(
    clip_description="A dark, atmospheric journey through midnight",
    song_title="Midnight Dreams",
    lyrics="Your song lyrics here...",
    duration=timedelta(minutes=4),
    language="english"
)

# Get results
plan = director.get_full_plan()
print(plan)

# Save for later use
director.save("video_plan.json")
```

---

## Processing Package (apexmusic.processing)

Handles video and browser automation operations.

### apexmusic.processing.bots

Browser automation module for opening and managing multiple browser instances.

**File**: `src/apexmusic/processing/bots.py`

#### BrowserBot

Manages multiple browser instances for parallel operations.

**Features**:
- Opens multiple browser windows to specified URLs
- Supports Selenium (recommended) with fallback to webbrowser module
- Automatic or manual closing of instances
- Thread-safe parallel browser management
- Automatic device driver detection

**Attributes**:
- `use_selenium` (bool): Whether to use Selenium for browser automation
- `browser_instances` (List): List of active browser instances
- `processes` (List[subprocess.Popen]): Subprocess handles
- `threads` (List[threading.Thread]): Managed threads
- `selenium_available` (bool): Flag indicating Selenium availability

**Constructor**:
```python
def __init__(self, use_selenium: bool = True):
```

**Parameters**:
- `use_selenium` (bool): Prefer Selenium. Falls back to webbrowser if unavailable. Default: True

##### `open_browsers(urls, num_instances=1, duration_seconds=60, auto_close=True) -> None`

Open multiple browser instances with specified URLs.

**Parameters**:
- `urls` (str or List[str]): Single URL or list of URLs
  - Example: `'https://www.youtube.com/watch?v=...'`
  - Or: `['https://url1.com', 'https://url2.com']`
- `num_instances` (int): Number of browser windows per URL. Default: 1
  - Total opened = len(urls) × num_instances
- `duration_seconds` (int): Time in seconds before auto-closing. Default: 60
- `auto_close` (bool): Automatically close after duration. Default: True

**Example**:
```python
from apexmusic.processing.bots import BrowserBot

bot = BrowserBot(use_selenium=True)

# Open single URL in 5 browsers for 30 seconds
bot.open_browsers(
    urls="https://www.youtube.com/watch?v=dQw4w9WgXcQ",
    num_instances=5,
    duration_seconds=30,
    auto_close=True
)

# Open multiple URLs, 3 instances each, manual close
bot.open_browsers(
    urls=["https://youtube.com/watch?v=...", "https://youtube.com/watch?v=..."],
    num_instances=3,
    auto_close=False
)

# Later close manually
bot.close_all()
```

##### `close_all() -> None`

Close all open browser instances (both Selenium and webbrowser).

**Example**:
```python
bot.close_all()  # Closes all instances
```

**Error Handling**:
- Gracefully falls back from Selenium to webbrowser if Selenium not installed
- Handles individual browser crashes without affecting others
- Thread-safe closing of all instances

---

### apexmusic.processing.video

Music video generator service orchestrating the complete creation workflow.

**File**: `src/apexmusic/processing/video.py`

#### MusicVideoGenerator

Responsible for creating music videos based on music files and optional lyrics.

**Features**:
- Analyzes music using LLM services
- Generates creative video concepts
- Creates visual theme, aesthetic, and storyline
- Produces scene sequences with prompts for video generation
- Supports multiple languages
- Outputs detailed film/video planning documents

**Attributes**:
- `artist_name` (str): Name of the artist
- `llm_service` (AbstractChat): Language model service instance
- `director` (MusicVideoDirector): Director service for orchestration

**Constructor**:
```python
def __init__(self, llm_service: AbstractChat, **kwargs) -> None
```

**Parameters**:
- `llm_service` (AbstractChat, optional): Initialized chat service. Created with `create_llm` if None
- **Keyword Arguments**:
  - `provider` (str): pyllmrouter provider when creating the service (blank = auto-detect)
  - `model` (str): Model name when creating the service
  - `base_url` (str): Ollama server URL (selects the `ollama` provider)
  - `artist_name` (str): Artist name for context (default: "Apex Music Machine")

##### `run(clip_description: str, **kwargs) -> None`

Run the music video generation process.

**Parameters**:
- `clip_description` (str): General description or creative direction for the video

**Keyword Arguments**:
- `song_title` (str): Title of the song (default: "unknown")
- `lyrics` (str): Full lyrics of the song (default: "")
- `duration` (timedelta): Total song duration (default: 4 minutes)
- `prompt` (str): Additional creative prompt (default: "")
- `language` (str): Language for analysis (default: "portuguese")

**Example**:
```python
from apexmusic.processing.video import MusicVideoGenerator
from apexmusic.llm.chat import create_llm
from datetime import timedelta

# With existing LLM service
llm = create_llm("ollama")
generator = MusicVideoGenerator(llm, artist_name="Apex Band")

# Run video generation
generator.run(
    clip_description="Dark atmospheric visuals with neon accents",
    song_title="Midnight Echo",
    lyrics="Your full song lyrics...",
    duration=timedelta(minutes=3, seconds=45),
    language="english"
)

# Or with auto-creation of LLM service
generator = MusicVideoGenerator(
    llm_service=None,
    model="qwen3:8b",
    artist_name="Your Band"
)

generator.run(
    clip_description="Abstract cyberpunk narrative",
    song_title="Digital Dreams",
    lyrics="...",
    duration=timedelta(minutes=4)
)
```

**Output**:
- Generates comprehensive music video plan
- Saves plan to `c:\temp\{song_title}_music_video_plan.json`
- Prints full plan with scenes, concepts, and generation prompts

---

## Project Structure

```
apexmusicmachine/
├── src/apexmusic/
│   ├── __init__.py                 # Package metadata
│   ├── __main__.py                 # Typer CLI (all commands)
│   ├── constants.py                # Defaults (models, servers, folders)
│   ├── llm/
│   │   ├── chat.py                 # create_llm(): thin layer over pyllmrouter + application model defaults
│   │   ├── embeddings.py           # create_app_embedder(): embeddings over pyllmrouter + collection naming
│   │   ├── image.py                # ImageGenerator / VideoGenerator (diffusers)
│   │   └── musicvideo.py           # MusicVideoDirector (LLM-planned scenes and prompts)
│   └── processing/
│       ├── lyrics.py               # Genius / AZLyrics downloader
│       ├── inference.py            # LyricInferenceEngine (ChromaDB RAG + LLM)
│       ├── translation.py          # LyricsTranslationService (title, analysis, post, translations)
│       ├── suno.py                 # SunoGateway (Docker) + SunoClient (REST)
│       ├── video.py                # MusicVideoGenerator
│       ├── cartoonizer.py          # AnimeGAN + optional optical-flow stabilisation (NVDEC/NVENC)
│       ├── youtube.py              # YouTubeUploader (OAuth, resumable upload)
│       └── bots.py                 # BrowserBot
├── tests/                          # pytest suite (LLM layer, translation, music video, image, cartoonizer, lyrics CLI)
├── docs/                           # index.html (generated from this README), agent guides, samples
├── batches/                        # Windows helper scripts (build, test, lyrics, bots)
├── pyproject.toml / uv.lock        # dependencies (pyllmrouter is pinned in the lock)
├── ruff.toml                       # lint + format rules
├── AGENTS.md / CLAUDE.md           # contributor guidelines
└── README.md                       # this file
```

## Dependencies

### Core Dependencies
- **typer**: the command-line interface
- **pyllmrouter[all]** (from PyPI): provider-agnostic LLM chat – Claude Agent SDK / API, Gemini API, Antigravity CLI, OpenAI Codex, Ollama, llama.cpp ([repo](https://github.com/fortalbrz/pyllmrouter))
- **chromadb**: vector store for the lyric RAG
- **diffusers**, **transformers**, **accelerate**, **torch**: image / video generation and the AnimeGAN cartoonizer
- **requests**, **beautifulsoup4**: lyric download (Genius API, AZLyrics scraping) and the Suno gateway client
- **google-api-python-client**, **google-auth-httplib2**, **google-auth-oauthlib**: YouTube upload

### Development Dependencies (`--extra dev`)
- **pytest**, **pytest-cov**: tests and coverage
- **ruff**: lint and format · **pyrefly**: type checking

### External tools
- **FFmpeg / FFprobe** (NVENC for `cartoon`), **Docker** (Suno gateway), an LLM/embedding backend of your choice (e.g. **Ollama**), **Selenium** (optional, `bots`)

## Configuration

### Environment Variables

```bash
# Provider selection (all optional; unset = auto-detect, see "LLM providers")
export LLM_BACKEND="ollama"            # same names as --provider; or LLMROUTER_PROVIDER

# Credentials / servers, one block per provider you use
export CLAUDE_CODE_OAUTH_TOKEN="..."   # claude-agent-token   (claude setup-token)
export ANTHROPIC_API_KEY="sk-ant-..."  # claude (API)
export GEMINI_API_KEY="..."            # gemini
export OLLAMA_SERVER="http://localhost:11434"
export LLAMACPP_SERVER="http://localhost:8080"

# Model overrides (rank below --model, above the application defaults)
export CLAUDE_MODEL="claude-sonnet-4-6"
export OLLAMA_MODEL="qwen3:8b"
export GEMINI_MODEL="gemini-3.5-flash"

# Other pipeline steps
export EMBEDDING_BACKEND="ollama"                # embedding provider (gemini | ollama | llamacpp); unset = auto-detect
export OLLAMA_EMBED_MODEL="qwen3-embedding:4b"   # embedding model per provider
export GEMINI_EMBED_MODEL="gemini-embedding-001"
export GENIUS_API_KEY="..."                      # download-lyrics (otherwise AZLyrics scraping)
export SUNO_COOKIE="..."                         # generate-music / suno-gateway
export SUNO_API_URL="http://localhost:3000"      # Suno gateway URL
export YOUTUBE_CLIENT_SECRET="client_secret.json"   # upload-youtube (OAuth client secret)
```

The complete LLM variable list (`AGY_CLI_*`, `CODEX_*`, llama.cpp key, ...) is in the
[pyllmrouter README](https://github.com/fortalbrz/pyllmrouter#environment-variables).

### Default Settings

See [apexmusic.constants](src/apexmusic/constants.py) for default configuration values.

## Testing

```bash
uv run pytest                          # all tests (coverage gate: 90 % on src/apexmusic/llm)
uv run pytest tests/test_llm.py -v     # one file
uv run pytest -x                       # stop at the first failure
```

The LLM tests use fakes and never touch the network or your credentials; the provider backends themselves are tested in the
[pyllmrouter](https://github.com/fortalbrz/pyllmrouter) project.

## Usage Examples

### Generate Music Video Concept

```python
from apexmusic.processing.video import MusicVideoGenerator
from datetime import timedelta

generator = MusicVideoGenerator(llm_service=None)
generator.run(
    clip_description="Dark synthwave journey through abandoned city",
    song_title="Neon Nights",
    lyrics="Your song lyrics...",
    duration=timedelta(minutes=3, seconds=30),
    language="english"
)
```

### Chat with any LLM provider

```python
from apexmusic.llm.chat import create_llm

chat = create_llm()                  # nothing set -> the first available provider (see `apexmusic providers`)
# chat = create_llm("gemini")        # or choose one; create_llm("ollama", "qwen3:8b") also picks the model
chat.set_system_message("You are a music production expert")

while (user_input := input("You: ")).lower() != "exit":
    print(f"Assistant: {chat.chat(user_input)}\n")

# streaming and async are built in:
#   for token in chat.chat_stream("..."): ...        reply = await chat.achat("...")
```

### Generate Images from Text

```python
from apexmusic.llm.image import ImageGenerator

generator = ImageGenerator()

images = generator.generate_from_prompt(
    prompt="Dark cyberpunk music venue with holographic stage",
    negative_prompt="bright, colorful, daytime",
    num_inference_steps=50,
    guidance_scale=7.5
)

images[0].save("music_venue.png")
```

### Browser Automation for YouTube

```python
from apexmusic.processing.bots import BrowserBot

bot = BrowserBot(use_selenium=True)

# Open 10 instances of a YouTube video for 2 minutes
bot.open_browsers(
    urls="https://www.youtube.com/watch?v=YOUR_VIDEO_ID",
    num_instances=10,
    duration_seconds=120
)
```

## Development

Quality tooling is configured in [`ruff.toml`](ruff.toml) and [`pyproject.toml`](pyproject.toml); the contributor rules are
in [AGENTS.md](AGENTS.md). When CI fails, fix in this order:

```bash
uv run ruff format .
uv run ruff check . --fix
uv run pyrefly check
uv run pytest -x
```

### Building

```bash
uv build                        # sdist + wheel in dist/
batches\build.bat               # Windows: builds, reinstalls and regenerates docs/index.html with Pandoc
```

`docs/index.html` is generated from this README by `batches\build.bat` (`pandoc README.md … -o docs/index.html`).

## Author

- **[Jorge Albuquerque](mailto:quantamentalguy@gmail.com)**, Ph.D. [[LinkedIn](https://www.linkedin.com/in/jorgealbuquerque)] [[X](https://x.com/quantamentalguy)]
- GitHub: [fortalbrz/apexmusicmachine](https://github.com/fortalbrz/apexmusicmachine)
- Companion project: [fortalbrz/pyllmrouter](https://github.com/fortalbrz/pyllmrouter) (the LLM layer, reusable in other projects)
- Also, check out the [ollama2cpp](https://github.com/fortalbrz/ollama2cpp) project for a simple and optimized migration from the local LLM server [ollama](https://ollama.com/) to [llama-cpp](https://llama-cpp.com/) (increase your local token generation rate by tunning algorithm).

## License

 [`MIT`](LICENSE) 
 
 The companion project [pyllmrouter](https://github.com/fortalbrz/pyllmrouter) is MIT-licensed too.

## Support

For issues, questions, or feature requests:
1. Check existing [issues](https://github.com/fortalbrz/apexmusicmachine/issues) 
2. Create a new issue with detailed information
3. Include error messages, Python version, and OS information (and the output of `apexmusic providers` for LLM problems)

## Changelog

### Unreleased
- All LLM access now goes through [pyllmrouter](https://github.com/fortalbrz/pyllmrouter): 8 providers (Claude Agent SDK token/login,
  Claude API, Gemini API, Antigravity CLI, OpenAI Codex, Ollama, llama.cpp) with auto-detection when no provider is set
- `--provider` and `lyrics --backend` no longer default to `ollama` / `claude`; global `--provider` / `--model` also apply to
  `lyrics` and `infer-lyrics`
- Lyric embeddings now go through pyllmrouter as well (`gemini`, `ollama` or `llamacpp`, auto-detected when not set): new
  `--embedding-provider` / `--embedding-model` options, one ChromaDB collection per embedding space (an existing Ollama
  `qwen3-embedding:4b` index is reused), and a test that forbids direct model-SDK imports anywhere in `src/`
- The `pipeline` lyric step now honours the global `--provider` / `--model`
- New `apexmusic providers` command (`--embeddings` for the embedding providers); `apexmusic test` reports provider availability
- Removed the direct `ollama` dependency (it is only used through pyllmrouter)
- Fixed a stray space in the default Ollama model name

### Version 0.1.0 (Alpha)
- Initial release
- Chat interface with Ollama support
- Image generation with Stable Diffusion
- Music video concept and scene generation
- Browser automation utilities
- Command-line interface
