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 (no paid API key required, just regular OAUTH sign-in).
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:
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(recommended) orpip - At least one LLM provider (see LLM providers): 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
cartooncommand; FFmpeg/FFprobe (with NVENC forcartoon) - Optional: Docker (Suno gateway), a Genius API key, a Google OAuth client secret (YouTube)
Setup
pip install apexmusic
- Install the package (this also installs
pyllmrouterwith all of its provider SDKs):
uv sync # or: pip install -e .
uv sync --extra dev # development tools: pytest, ruff, pyrefly
- Set up at least one LLM provider – check what is usable with
apexmusic providers. Examples:
# 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.
- Optional services, only for the steps you use:
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
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
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: 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.
Lyrics library – download-lyrics
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
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-lyricsreturns the lyrics as text.lyricsadditionally 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_BACKENDselects, or the first available provider.
Music generation – suno-gateway and generate-music
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
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
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
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.
End to end – pipeline
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(lyrics, ChromaDB, output) point atd:\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); registered as the apexmusic console script.
File: src/apexmusic/__main__.py
- A global callback resolves
--verbose,--providerand--modelinto 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
pipelinecommand chains the handlers and stops with a clear message at the first failing step.
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; envOLLAMA_MODELand--modeloverride it)DEFAULT_OLLAMA_EMBEDDING = 'qwen3-embedding:4b': Application default of theollamaembedding providerDEFAULT_CLAUDE_MODEL = 'claude-sonnet-4-6': Default model of theclaude(Anthropic API) provider
LLM Package (apexmusic.llm)
Handles interaction with language models and document processing.
apexmusic.llm.chat
Thin integration layer over 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) |
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
for the complete API.
apexmusic.llm.embeddings
The same thin layer for text embeddings (lyric RAG); see Embeddings.
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 – "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 | – |
- Set explicitly –
--embedding-provider NAME, elseEMBEDDING_BACKEND, elseLLMROUTER_EMBEDDING_PROVIDER→ used, not probed. - Nothing set → auto-detection over
gemini→ollama→llamacpp; the probe checks that the model exists (for Ollama:ollama pull qwen3-embedding:4b).apexmusic providers --embeddingsshows the result.
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_KEYset and no--embedding-providerwill embed through Gemini. Pin--embedding-provider ollama(orEMBEDDING_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;--reindexrebuilds 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:
$ 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
- A provider is set -
--backend NAME(infer/lyricsonly) or the global--provider NAME, else theLLM_BACKENDenvironment variable, elseLLMROUTER_PROVIDER(first one wins) -> that provider is used and nothing is probed.--modelworks the same way (--modelon the command, else the global--model). - 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) |
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.
--providerused to default toollamaandlyrics --backendtoclaude. Both are now unset, so the first available provider is auto-detected. To pin the old behaviour, pass--provider ollama/--backend claudeor setLLM_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 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 Diffusiondevice(str): Device for inference ("cuda" or "cpu")dtype(torch.dtype): Data type for inference (float32 or float16)
Constructor:
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 availabledtype(torch.dtype): Data type for inferencetorch.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 generatenegative_prompt(str, optional): Description of what NOT to include in the imageheight(int): Height of generated image in pixels. Default: 512width(int): Width of generated image in pixels. Default: 512num_inference_steps(int): Number of denoising steps. Higher = better quality but slower. Default: 50guidance_scale(float): Strength of prompt guidance (0.0 to 20.0). Higher = follow prompt more closely. Default: 7.5num_images_per_prompt(int): Number of images per prompt. Default: 1seed(int, optional): Random seed for reproducibility
Returns: List of PIL Image objects
Example:
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 generatereference_image(str/Path/Image.Image): Path or PIL Image object for guidancenegative_prompt(str, optional): Description of what NOT to includestrength(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: 50guidance_scale(float): Strength of prompt guidance. Default: 7.5num_images_per_prompt(int): Number of images to generate. Default: 1seed(int, optional): Random seed for reproducibility
Returns: List of PIL Image objects
Example:
# 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 sectionVERSE: Verse sectionPRE_CHORUS: Section before chorusCHORUS: Chorus/refrain sectionBREAK: Musical break or bridgeOUTRO: Concluding section
Data Classes
Scene
Represents a single scene in the music video sequence.
Attributes:
sequence_number(int): Position in sequencestart_time(float): Scene start time in secondsend_time(float): Scene end time in secondsduration(timedelta): Scene durationsection_type(str): Type of music section (from MusicSection)description(str): Detailed scene descriptionvisual_elements(List[str]): Visual components in the scenemood(str): Emotional mood of the scenecamera_movement(str): Camera movement descriptionkling_prompt(str, optional): Prompt for Kling video generation
MusicAnalysis
Results of music sentiment and structural analysis.
Attributes:
overall_sentiment(str): Overall emotional toneemotional_arc(str): How emotions progress through the songdominant_feelings(List[str]): Primary emotions presentkey_themes(List[str]): Main themes or topicssuggested_aesthetics(List[str]): Visual style suggestionscolor_palette(List[str]): Recommended colorsvideo_title(str): Generated video titlevideo_description(str): Generated video description
VideoConceptPlan
Complete music video concept plan.
Attributes:
concept_title(str): Title of the video conceptconcept_description(str): Detailed concept descriptionvisual_style(str): Overall visual aestheticnarrative_arc(str): Story structure and progressionkey_visual_metaphors(List[str]): Visual symbolism usedcolor_scheme(Dict[str, str]): Color palette with meaningscamera_style(str): Camera work and framing styleoverall_mood(str): Emotional tone throughout
MusicVideoDirector
Service class for orchestrating music video creation using LLM capabilities.
Attributes:
lyrics(str): Song lyrics with section annotationsduration(float): Total song duration in secondsclip_description(str): General description or creative directionchat_service(AbstractChat): LLM service instance for analysisartist_name(str): Artist name for context (default: "Apex Music Machine")
Constructor:
def __init__(self, llm_service: AbstractChat, artist_name: str = "Apex Music Machine") -> None
Parameters:
llm_service(AbstractChat): Initialized chat service (any pyllmrouter provider, seecreate_llm)artist_name(str): Artist name for video context
Example:
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 automationbrowser_instances(List): List of active browser instancesprocesses(List[subprocess.Popen]): Subprocess handlesthreads(List[threading.Thread]): Managed threadsselenium_available(bool): Flag indicating Selenium availability
Constructor:
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']
- Example:
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: 60auto_close(bool): Automatically close after duration. Default: True
Example:
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:
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 artistllm_service(AbstractChat): Language model service instancedirector(MusicVideoDirector): Director service for orchestration
Constructor:
def __init__(self, llm_service: AbstractChat, **kwargs) -> None
Parameters:
llm_service(AbstractChat, optional): Initialized chat service. Created withcreate_llmif None- Keyword Arguments:
provider(str): pyllmrouter provider when creating the service (blank = auto-detect)model(str): Model name when creating the servicebase_url(str): Ollama server URL (selects theollamaprovider)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:
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)
- 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
# 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.
Default Settings
See apexmusic.constants for default configuration values.
Testing
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 project.
Usage Examples
Generate Music Video Concept
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
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
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
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 and pyproject.toml; the contributor rules are
in AGENTS.md. When CI fails, fix in this order:
uv run ruff format .
uv run ruff check . --fix
uv run pyrefly check
uv run pytest -x
Building
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, Ph.D. [LinkedIn] [X]
- GitHub: fortalbrz/apexmusicmachine
- Companion project: fortalbrz/pyllmrouter (the LLM layer, reusable in other projects)
- Also, check out the ollama2cpp project for a simple and optimized migration from the local LLM server ollama to llama-cpp (increase your local token generation rate by tunning algorithm).
License
The companion project pyllmrouter is MIT-licensed too.
Support
For issues, questions, or feature requests:
- Check existing issues
- Create a new issue with detailed information
- Include error messages, Python version, and OS information (and the output of
apexmusic providersfor LLM problems)
Changelog
Unreleased
- All LLM access now goes through 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
--providerandlyrics --backendno longer default toollama/claude; global--provider/--modelalso apply tolyricsandinfer-lyrics- Lyric embeddings now go through pyllmrouter as well (
gemini,ollamaorllamacpp, auto-detected when not set): new--embedding-provider/--embedding-modeloptions, one ChromaDB collection per embedding space (an existing Ollamaqwen3-embedding:4bindex is reused), and a test that forbids direct model-SDK imports anywhere insrc/ - The
pipelinelyric step now honours the global--provider/--model - New
apexmusic providerscommand (--embeddingsfor the embedding providers);apexmusic testreports provider availability - Removed the direct
ollamadependency (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
Metadata
Release files for apexmusic 1.0.1
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| apexmusic-1.0.1.tar.gz | 114.0 kB | Without provenance | Details for apexmusic-1.0.1.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| apexmusic-1.0.1-py3-none-any.whl | Python 3 | none | any | Details for apexmusic-1.0.1-py3-none-any.whl |
Total release size: 188.4 kB
Release files / apexmusic-1.0.1.tar.gz
| Download URL | apexmusic-1.0.1.tar.gz |
|---|---|
| Size | 114.0 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
8e325dd9bc649f23fbc2f7d980dcee2b775cf53444f2d4b4e80dc80b3571fc43
|
|
BLAKE2b-256 checksum How to use checksums |
59c86ea13ea5d58b9fd70ecd6c280d278738a7f8e18b764c2e826ea974448426
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
uv/0.11.21 {"installer":{"name":"uv","version":"0.11.21","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":null,"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}
|
Release files / apexmusic-1.0.1-py3-none-any.whl
| Download URL | apexmusic-1.0.1-py3-none-any.whl |
|---|---|
| Size | 74.3 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
b536b353c965a36d218b2a252f15ec1696c72b1607df1d44ddbdcb2c1ed38753
|
|
BLAKE2b-256 checksum How to use checksums |
ed39080b4989d805acb0f0829b7c550d2b2e0faf0054857349468f806c96012e
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
uv/0.11.21 {"installer":{"name":"uv","version":"0.11.21","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":null,"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}
|
Security for apexmusic 1.0.1
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.