What happens when you give the Zen of Python a melody? This small Django app turns a paragraph into song lyrics, lets you choose a musical style and mood, and generates an MP3 with ElevenLabs.
Explore the project on GitHub.
Press play to hear the example:
The lyrics come from Tim Peters’ The Zen of Python:
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
The app is intentionally simple: a form, a Django view, one server-side API request, and a short-lived cache entry for the generated audio. Here’s how those pieces fit together.
The architecture: keep the API key on the server#
The browser submits the paragraph, genre, and mood to Django. Django builds a composition plan and sends it to ElevenLabs’ POST /v1/music/stream endpoint. After generation, the app keeps the MP3 in local memory and returns a page with an audio player and a download link.
Browser ── form POST ──> Django ── POST /v1/music/stream ──> ElevenLabs
^ │ │
└── player / download ────┴──── cached MP3 bytes <───────────┘
The ELEVENLABS_API_KEY belongs in the Django process’s environment, not in JavaScript or an HTML page. The server adds it to the upstream request’s xi-api-key header, so visitors can use the app without ever receiving the secret. Keeping the call on the backend also gives the application one place to validate input, handle provider errors, and control access to an API account that may use credits.
The app requests MP3 output (mp3_44100_128) from the streaming endpoint. One detail matters when describing the user experience: although the provider endpoint is a streaming endpoint, this implementation reads the complete response into memory before serving it to the browser. The browser then plays the finished audio from the app’s audio URL. It does not currently relay audio chunks to the player as they arrive.
1. Start the Django app#
The project uses Django and uv. Its package metadata requires Python 3.15 or newer. From the project directory, set an API key with music-generation access and start the app:
uv sync
export ELEVENLABS_API_KEY="your-api-key"
uv run eleven
Open http://127.0.0.1:8000. The app accepts an optional PORT environment variable if you need a different local port. The sample MP3 above is already checked into examples/, so it can be played without making an API request.
2. Turn the form choices into a composition plan#
The form asks for up to 2,000 characters, plus one of the available music styles and moods. build_composition_plan trims and validates the paragraph and choices before constructing a single verse. The user’s text becomes the verse lyrics; the selected style and mood become descriptive style prompts.
For example, “indie” maps to “warm indie folk,” and “chill” maps to “relaxed and mellow.” A matching plan looks like this:
{
"model_id": "music_v2_5",
"composition_plan": {
"chunks": [
{
"text": "[Verse 1]\nRain on the window.\nThe cat conducts the night.",
"duration_ms": 15000,
"positive_styles": [
"warm indie folk",
"relaxed and mellow",
"clear lead vocals",
],
}
]
},
}
The chunk duration is estimated from the word count, then kept between 15 and 120 seconds. Adding the [Verse 1] label gives the model a simple composition structure, while the positive_styles array keeps the selected sound, mood, and vocal preference together. The project also rejects empty text, text over the character limit, and unknown genre or mood values before making the API call.
A note on prompt injection#
The paragraph is user-controlled text, and the app inserts it directly into the composition plan sent to the music model. Instruction-like text could therefore steer the generated song away from the selected lyrics, style, or mood, or produce unexpected content. In that limited sense, the input can act like a prompt injection against the model’s generation task.
This is not an agent-style injection with access to application tools or private data: the app does not give the model tools to execute, and the ElevenLabs API key is sent separately in an HTTP header rather than in the composition plan. The app validates the paragraph’s type and length, but does not detect instructions or check the generated audio’s content. Treat submitted text as untrusted creative input, and use appropriate content/output checks and provider controls where available; prompt wording alone cannot reliably prevent steering. Rate limits or authentication can help protect API usage, but address a separate risk.
3. Make the server-side music request#
generate_song serializes the plan as JSON and sends it to ElevenLabs with the API key in the request header. The key can be passed explicitly by internal callers, but the normal app flow reads it from ELEVENLABS_API_KEY. If it is missing, the app returns a configuration error without attempting a network request.
The request asks for audio and waits up to five minutes for the provider response. The app checks that the response contains audio and reports provider or connection failures as user-facing errors. This keeps provider-specific request handling out of the browser and gives the Django view a simple result: audio bytes and a content type.
Here is the core request, simplified from generate_song:
API_URL = "https://api.elevenlabs.io/v1/music/stream?output_format=mp3_44100_128"
request = Request(
API_URL,
data=json.dumps(payload).encode("utf-8"),
headers={
"xi-api-key": api_key,
"Content-Type": "application/json",
"Accept": "audio/mpeg",
},
method="POST",
)
with urlopen(request, timeout=300) as response:
audio = response.read()
payload is the composition plan from the previous section. The URL targets ElevenLabs’ /v1/music/stream endpoint and requests MP3 output; the JSON body carries the plan, while xi-api-key authenticates the server-side call. Although the endpoint is named stream, this code reads the full response into audio before the app serves it to the browser.
In brief, POST /v1/music/stream generates a song from either a text prompt or a structured composition plan and returns the audio data in the response. This project sends a music_v2_5 composition plan and asks for mp3_44100_128 output. See ElevenLabs’ official Stream music API reference for the full request options and response details.
4. Cache the finished audio temporarily#
Once generation succeeds, the Django view creates a UUID and stores the audio bytes, content type, and lyrics in Django’s LocMemCache for one hour. It redirects to /songs/<uuid>/, where the result page displays an HTML audio player. The player loads /songs/<uuid>/audio/; adding ?download=1 makes that route return the MP3 as a download instead of inline playback.
This temporary in-memory approach avoids writing generated audio files to disk and makes the result easy to play or download. It is also deliberately lightweight, with trade-offs: entries disappear after an hour, a process restart loses them, and Django’s local-memory cache is not shared across separate worker processes. For a multi-worker or production deployment, use shared storage or a cache such as Redis, set explicit size and retention limits, and consider how audio access should be authorized.
What to build next#
- Relay audio as it arrives. The current app buffers the complete MP3 before it can play. A true streaming response to the browser could reduce perceived wait time, but would need a different response and storage flow.
- Add spoken introductions. Generate a voiceover with ElevenLabs text-to-speech, then combine or sequence it with the song for a narrated version of the paragraph.
- Deploy with Docker. Package the supported Python runtime and app dependencies, inject
ELEVENLABS_API_KEYthrough the deployment’s secret mechanism, and configure production Django settings rather than exposing development defaults. - Expand the composition. Add a chorus or multiple sections, give readers more style controls, or let them preview and revise the lyrics before generating audio.
The project’s core idea is small but useful: keep credentials and provider calls on the backend, turn clear user choices into a structured composition plan, and give the browser a simple audio URL to play. From there, it’s easy to experiment with richer song structures and more responsive playback.