Commit b1bd442b authored by Aryan Noshirvani's avatar Aryan Noshirvani

Replace stock Swagger UI with a custom API console

The generic Swagger UI has no concept of "upload audio, get audio back" -
every response was just a raw JSON blob with a download_url string you'd
have to copy elsewhere to actually listen to. Built a small self-contained
console (single HTML file, dark/neon theme matching the Flutter app's
AppTheme) instead:

- AI Remix panel: drag-and-drop up to 5 files, a prompt box, a live
  per-stage progress bar (queued -> planning -> separating -> mixing ->
  mastering -> tagging -> done) that polls GET /remix/{job_id}, and an
  inline <audio> player for the result plus the AI's actual plan
  (target BPM, which stems came from which song).
- Tag & Identify panel: same idea for the single-file /music/upload flow.
- A generic endpoint explorer below both, built dynamically from the
  live /openapi.json (grouped by router tag, expandable "try it" forms
  for path/query params and JSON bodies) so every other route - auth,
  discovery, library, social - is still reachable without hand-writing
  bespoke UI for each.

Same HTTP Basic auth gate as before (verify_docs_auth on the /docs
route); the console's own fetch() calls ride on the browser's cached
Basic Auth for the origin, no extra plumbing needed.
Co-Authored-By: 's avatarClaude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BCxXmJVvDFJVHTUi4QgNzi
parent 841bed29
import os
import secrets
from fastapi import Depends, FastAPI, HTTPException, status
from fastapi.responses import RedirectResponse
from fastapi.openapi.docs import get_swagger_ui_html
from fastapi.responses import HTMLResponse, RedirectResponse
from fastapi.openapi.utils import get_openapi
from fastapi.security import HTTPBasic, HTTPBasicCredentials
from fastapi.staticfiles import StaticFiles
......@@ -13,6 +12,8 @@ from src.core.config import DOCS_PASSWORD, DOCS_USERNAME
os.makedirs("/root/antigrav-stax-audio/downloads", exist_ok=True)
os.makedirs("/root/antigrav-stax-audio/temp", exist_ok=True)
CONSOLE_HTML_PATH = os.path.join(os.path.dirname(__file__), "static", "console.html")
docs_security = HTTPBasic()
......@@ -47,9 +48,10 @@ async def root():
return RedirectResponse(url="/docs")
@app.get("/docs", include_in_schema=False)
@app.get("/docs", include_in_schema=False, response_class=HTMLResponse)
async def get_documentation(username: str = Depends(verify_docs_auth)):
return get_swagger_ui_html(openapi_url="/openapi.json", title="Stax API Docs")
with open(CONSOLE_HTML_PATH, "r") as f:
return f.read()
@app.get("/openapi.json", include_in_schema=False)
......
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Stax API Console</title>
<style>
:root {
--bg: #0D0F12;
--panel: #14171C;
--panel-2: #1B1F26;
--border: #262B33;
--text: #E7ECF2;
--text-dim: #8A93A3;
--accent: #00E5FF;
--accent-dim: #00B8CC;
--good: #37E29A;
--bad: #FF5C7A;
--warn: #FFC857;
}
* { box-sizing: border-box; }
body {
margin: 0;
background: var(--bg);
color: var(--text);
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
}
header {
padding: 22px 32px;
border-bottom: 1px solid var(--border);
display: flex;
align-items: baseline;
gap: 14px;
}
header h1 {
font-size: 20px;
margin: 0;
letter-spacing: 0.02em;
}
header h1 span { color: var(--accent); }
.badge {
font-size: 11px;
text-transform: uppercase;
letter-spacing: 0.08em;
color: var(--bg);
background: var(--accent);
padding: 3px 8px;
border-radius: 4px;
font-weight: 700;
}
main {
max-width: 980px;
margin: 0 auto;
padding: 32px;
}
section {
background: var(--panel);
border: 1px solid var(--border);
border-radius: 14px;
padding: 24px;
margin-bottom: 24px;
}
section h2 {
margin: 0 0 4px 0;
font-size: 17px;
}
section p.desc {
margin: 0 0 18px 0;
color: var(--text-dim);
font-size: 13.5px;
line-height: 1.5;
}
.dropzone {
border: 1.5px dashed var(--border);
border-radius: 10px;
padding: 22px;
text-align: center;
color: var(--text-dim);
cursor: pointer;
transition: border-color .15s, background .15s;
font-size: 13.5px;
}
.dropzone.drag { border-color: var(--accent); background: rgba(0,229,255,0.05); }
.dropzone input { display: none; }
.filelist {
display: flex;
flex-wrap: wrap;
gap: 8px;
margin-top: 10px;
}
.filechip {
background: var(--panel-2);
border: 1px solid var(--border);
border-radius: 20px;
padding: 5px 12px;
font-size: 12.5px;
display: flex;
align-items: center;
gap: 8px;
}
.filechip button {
background: none;
border: none;
color: var(--text-dim);
cursor: pointer;
font-size: 14px;
line-height: 1;
padding: 0;
}
textarea, input[type=text], input[type=number] {
width: 100%;
background: var(--panel-2);
border: 1px solid var(--border);
border-radius: 8px;
color: var(--text);
padding: 10px 12px;
font-size: 13.5px;
font-family: inherit;
margin-top: 12px;
resize: vertical;
}
textarea:focus, input:focus { outline: none; border-color: var(--accent); }
button.primary {
margin-top: 14px;
background: var(--accent);
color: #06141A;
border: none;
border-radius: 8px;
padding: 10px 20px;
font-weight: 700;
font-size: 13.5px;
cursor: pointer;
}
button.primary:hover { background: var(--accent-dim); }
button.primary:disabled { opacity: 0.5; cursor: default; }
.progress-track {
display: flex;
gap: 4px;
margin-top: 16px;
}
.progress-step {
flex: 1;
text-align: center;
font-size: 10.5px;
color: var(--text-dim);
padding-top: 8px;
border-top: 3px solid var(--border);
text-transform: uppercase;
letter-spacing: 0.04em;
}
.progress-step.active { border-top-color: var(--accent); color: var(--accent); }
.progress-step.done { border-top-color: var(--good); color: var(--good); }
.progress-step.error { border-top-color: var(--bad); color: var(--bad); }
.result-card {
margin-top: 18px;
background: var(--panel-2);
border: 1px solid var(--border);
border-radius: 10px;
padding: 16px;
display: none;
}
.result-card.show { display: block; }
.result-card h3 { margin: 0 0 10px 0; font-size: 15px; color: var(--accent); }
.result-card .row { display: flex; justify-content: space-between; font-size: 12.5px; padding: 3px 0; color: var(--text-dim); }
.result-card .row b { color: var(--text); font-weight: 500; }
audio { width: 100%; margin-top: 12px; }
.status-line { margin-top: 10px; font-size: 12.5px; color: var(--text-dim); min-height: 16px; }
.status-line.error { color: var(--bad); }
details.endpoint {
border: 1px solid var(--border);
border-radius: 8px;
margin-bottom: 8px;
overflow: hidden;
}
details.endpoint summary {
padding: 10px 14px;
cursor: pointer;
display: flex;
gap: 10px;
align-items: center;
font-size: 13px;
list-style: none;
}
details.endpoint summary::-webkit-details-marker { display: none; }
.method {
font-size: 10.5px;
font-weight: 800;
padding: 2px 7px;
border-radius: 4px;
letter-spacing: 0.03em;
}
.method.get { background: #17324a; color: #6bc8ff; }
.method.post { background: #1e3a2a; color: var(--good); }
.method.put, .method.patch { background: #3a3220; color: var(--warn); }
.method.delete { background: #3a1f26; color: var(--bad); }
.path { color: var(--text); font-family: ui-monospace, Menlo, monospace; }
.endpoint-body { padding: 14px; border-top: 1px solid var(--border); background: var(--panel); }
.endpoint-body label { display: block; font-size: 11.5px; color: var(--text-dim); margin-top: 10px; text-transform: uppercase; letter-spacing: 0.04em; }
.endpoint-body label:first-child { margin-top: 0; }
pre.response {
background: #0A0C0F;
border: 1px solid var(--border);
border-radius: 8px;
padding: 12px;
font-size: 12px;
overflow-x: auto;
margin-top: 12px;
max-height: 320px;
}
.tag-group h2 { margin-bottom: 14px; }
.small-btn {
background: var(--panel-2);
color: var(--text);
border: 1px solid var(--border);
border-radius: 6px;
padding: 7px 14px;
font-size: 12.5px;
cursor: pointer;
margin-top: 12px;
}
.small-btn:hover { border-color: var(--accent); }
.loading-spin {
display: inline-block;
width: 11px; height: 11px;
border: 2px solid var(--border);
border-top-color: var(--accent);
border-radius: 50%;
animation: spin 0.7s linear infinite;
margin-right: 6px;
vertical-align: -1px;
}
@keyframes spin { to { transform: rotate(360deg); } }
</style>
</head>
<body>
<header>
<h1>🎧 Stax<span> API</span> Console</h1>
<span class="badge" id="instance-badge">…</span>
</header>
<main>
<section id="remix-section">
<h2>🎛 AI Remix</h2>
<p class="desc">Upload 1&ndash;5 songs and describe the remix in plain language. Gemini listens to each track, plans which stems to pull from which song, and Demucs does the actual separation before mixing/mastering.</p>
<div class="dropzone" id="remix-drop">
Drop up to 5 audio files here, or click to choose
<input type="file" id="remix-file-input" multiple accept="audio/*">
</div>
<div class="filelist" id="remix-filelist"></div>
<textarea id="remix-prompt" rows="2" placeholder="e.g. Blend the vocals of the first song over the drums of the second, slowed down with heavy reverb"></textarea>
<button class="primary" id="remix-submit">Create Remix</button>
<div class="progress-track" id="remix-progress" style="display:none;">
<div class="progress-step" data-stage="queued">Queued</div>
<div class="progress-step" data-stage="planning">Planning</div>
<div class="progress-step" data-stage="separating">Separating</div>
<div class="progress-step" data-stage="mixing">Mixing</div>
<div class="progress-step" data-stage="mastering">Mastering</div>
<div class="progress-step" data-stage="tagging">Tagging</div>
<div class="progress-step" data-stage="done">Done</div>
</div>
<div class="status-line" id="remix-status"></div>
<div class="result-card" id="remix-result">
<h3 id="remix-result-name"></h3>
<div class="row"><span>Target BPM</span><b id="remix-result-bpm"></b></div>
<div class="row"><span>Song roles</span><b id="remix-result-roles"></b></div>
<audio controls id="remix-result-audio"></audio>
</div>
</section>
<section id="tag-section">
<h2>🏷 Tag &amp; Identify</h2>
<p class="desc">Upload a single untagged track. It's fingerprinted (Shazam/AcoustID, Gemini fallback), tagged with title/artist/album/art/lyrics, and returned as a finished MP3.</p>
<div class="dropzone" id="tag-drop">
Drop one audio file here, or click to choose
<input type="file" id="tag-file-input" accept="audio/*">
</div>
<div class="filelist" id="tag-filelist"></div>
<button class="primary" id="tag-submit">Tag Track</button>
<div class="status-line" id="tag-status"></div>
<div class="result-card" id="tag-result">
<h3 id="tag-result-title"></h3>
<div class="row"><span>Artist</span><b id="tag-result-artist"></b></div>
<div class="row"><span>Album</span><b id="tag-result-album"></b></div>
<div class="row"><span>Genre</span><b id="tag-result-genre"></b></div>
<audio controls id="tag-result-audio"></audio>
</div>
</section>
<section id="explorer-section">
<h2>📚 All Endpoints</h2>
<p class="desc">Auto-generated from this instance's live OpenAPI schema. Expand any endpoint to fill in parameters and send a real request.</p>
<div id="explorer-groups">Loading schema…</div>
</section>
</main>
<script>
const $ = (sel, root=document) => root.querySelector(sel);
const $$ = (sel, root=document) => Array.from(root.querySelectorAll(sel));
// ---------- shared helpers ----------
function setupDropzone(dropEl, inputEl, listEl, multiple) {
let files = [];
const render = () => {
listEl.innerHTML = '';
files.forEach((f, i) => {
const chip = document.createElement('div');
chip.className = 'filechip';
chip.innerHTML = `<span>${f.name}</span>`;
const btn = document.createElement('button');
btn.textContent = '✕';
btn.onclick = () => { files.splice(i, 1); render(); };
chip.appendChild(btn);
listEl.appendChild(chip);
});
};
const addFiles = (fileList) => {
for (const f of fileList) {
if (!multiple) { files = [f]; break; }
if (files.length < 5) files.push(f);
}
render();
};
dropEl.addEventListener('click', () => inputEl.click());
inputEl.addEventListener('change', (e) => addFiles(e.target.files));
dropEl.addEventListener('dragover', (e) => { e.preventDefault(); dropEl.classList.add('drag'); });
dropEl.addEventListener('dragleave', () => dropEl.classList.remove('drag'));
dropEl.addEventListener('drop', (e) => {
e.preventDefault();
dropEl.classList.remove('drag');
addFiles(e.dataTransfer.files);
});
return { getFiles: () => files };
}
// ---------- Remix flow ----------
const remixDz = setupDropzone($('#remix-drop'), $('#remix-file-input'), $('#remix-filelist'), true);
function setRemixStage(stage, isError) {
$$('#remix-progress .progress-step').forEach(el => {
el.classList.remove('active', 'done', 'error');
const order = ['queued','planning','separating','mixing','mastering','tagging','done'];
const cur = order.indexOf(stage);
const idx = order.indexOf(el.dataset.stage);
if (isError && idx === cur) el.classList.add('error');
else if (idx < cur || (idx === cur && stage === 'done')) el.classList.add('done');
else if (idx === cur) el.classList.add('active');
});
}
$('#remix-submit').addEventListener('click', async () => {
const files = remixDz.getFiles();
const prompt = $('#remix-prompt').value.trim();
const statusEl = $('#remix-status');
const resultEl = $('#remix-result');
resultEl.classList.remove('show');
if (!files.length) { statusEl.textContent = 'Add at least one audio file first.'; statusEl.className = 'status-line error'; return; }
if (!prompt) { statusEl.textContent = 'Describe the remix you want first.'; statusEl.className = 'status-line error'; return; }
$('#remix-submit').disabled = true;
$('#remix-progress').style.display = 'flex';
setRemixStage('queued', false);
statusEl.className = 'status-line';
statusEl.innerHTML = '<span class="loading-spin"></span>Submitting…';
const form = new FormData();
form.append('prompt', prompt);
files.forEach(f => form.append('files', f));
try {
const res = await fetch('/remix', { method: 'POST', body: form, credentials: 'same-origin' });
if (!res.ok) throw new Error((await res.json()).detail || res.statusText);
const job = await res.json();
statusEl.innerHTML = `<span class="loading-spin"></span>Job #${job.job_id} queued…`;
poll(job.job_id);
} catch (e) {
statusEl.textContent = 'Failed to submit: ' + e.message;
statusEl.className = 'status-line error';
$('#remix-submit').disabled = false;
}
async function poll(jobId) {
try {
const res = await fetch(`/remix/${jobId}`, { credentials: 'same-origin' });
const data = await res.json();
setRemixStage(data.status, data.status === 'error');
if (data.status === 'error') {
statusEl.textContent = 'Remix failed: ' + (data.error || 'unknown error');
statusEl.className = 'status-line error';
$('#remix-submit').disabled = false;
return;
}
statusEl.innerHTML = `<span class="loading-spin"></span>${data.stage_detail || data.status}`;
if (data.status === 'done') {
statusEl.textContent = 'Done.';
$('#remix-submit').disabled = false;
$('#remix-result-name').textContent = data.remix_name || 'Remix';
if (data.plan) {
$('#remix-result-bpm').textContent = data.plan.target_bpm ?? '—';
const roles = (data.plan.song_roles || []).map(r => `#${r.index}: ${(r.stems||[]).join('+') || 'none'}`).join(' · ');
$('#remix-result-roles').textContent = roles || '—';
}
$('#remix-result-audio').src = data.download_url;
resultEl.classList.add('show');
return;
}
setTimeout(() => poll(jobId), 2500);
} catch (e) {
statusEl.textContent = 'Lost connection while polling: ' + e.message;
statusEl.className = 'status-line error';
$('#remix-submit').disabled = false;
}
}
});
// ---------- Tag flow ----------
const tagDz = setupDropzone($('#tag-drop'), $('#tag-file-input'), $('#tag-filelist'), false);
$('#tag-submit').addEventListener('click', async () => {
const files = tagDz.getFiles();
const statusEl = $('#tag-status');
const resultEl = $('#tag-result');
resultEl.classList.remove('show');
if (!files.length) { statusEl.textContent = 'Add an audio file first.'; statusEl.className = 'status-line error'; return; }
$('#tag-submit').disabled = true;
statusEl.className = 'status-line';
statusEl.innerHTML = '<span class="loading-spin"></span>Identifying and tagging… this can take a bit.';
const form = new FormData();
form.append('file', files[0]);
try {
const res = await fetch('/music/upload', { method: 'POST', body: form, credentials: 'same-origin' });
if (!res.ok) throw new Error((await res.json()).detail || res.statusText);
const data = await res.json();
statusEl.textContent = 'Done.';
const meta = data.metadata || {};
$('#tag-result-title').textContent = meta.title || 'Unknown';
$('#tag-result-artist').textContent = meta.artist || '—';
$('#tag-result-album').textContent = meta.album || '—';
$('#tag-result-genre').textContent = meta.genre || '—';
$('#tag-result-audio').src = data.download_url;
resultEl.classList.add('show');
} catch (e) {
statusEl.textContent = 'Failed: ' + e.message;
statusEl.className = 'status-line error';
} finally {
$('#tag-submit').disabled = false;
}
});
// ---------- Generic endpoint explorer, built from /openapi.json ----------
function methodClass(m) { return 'method ' + m.toLowerCase(); }
function buildEndpointBody(path, method, op) {
const wrap = document.createElement('div');
wrap.className = 'endpoint-body';
if (op.description) {
const p = document.createElement('p');
p.className = 'desc';
p.style.margin = '0 0 8px 0';
p.textContent = op.description;
wrap.appendChild(p);
}
const pathParamInputs = {};
(op.parameters || []).forEach(param => {
const label = document.createElement('label');
label.textContent = `${param.name}${param.in === 'path' ? ' (path)' : ' (query)'}${param.required ? ' *' : ''}`;
const input = document.createElement('input');
input.type = 'text';
input.placeholder = param.schema && param.schema.type || '';
wrap.appendChild(label);
wrap.appendChild(input);
pathParamInputs[param.name] = { input, in: param.in };
});
let bodyTextarea = null;
const hasJsonBody = op.requestBody && op.requestBody.content && op.requestBody.content['application/json'];
if (hasJsonBody) {
const label = document.createElement('label');
label.textContent = 'Request body (JSON)';
bodyTextarea = document.createElement('textarea');
bodyTextarea.rows = 5;
bodyTextarea.placeholder = '{\n \n}';
wrap.appendChild(label);
wrap.appendChild(bodyTextarea);
}
const sendBtn = document.createElement('button');
sendBtn.className = 'small-btn';
sendBtn.textContent = 'Send';
wrap.appendChild(sendBtn);
const pre = document.createElement('pre');
pre.className = 'response';
pre.style.display = 'none';
wrap.appendChild(pre);
sendBtn.addEventListener('click', async () => {
let url = path;
const query = [];
for (const [name, meta] of Object.entries(pathParamInputs)) {
const val = meta.input.value;
if (meta.in === 'path') url = url.replace(`{${name}}`, encodeURIComponent(val));
else if (val) query.push(`${encodeURIComponent(name)}=${encodeURIComponent(val)}`);
}
if (query.length) url += '?' + query.join('&');
const opts = { method: method.toUpperCase(), credentials: 'same-origin' };
if (bodyTextarea && bodyTextarea.value.trim()) {
opts.headers = { 'Content-Type': 'application/json' };
opts.body = bodyTextarea.value;
}
pre.style.display = 'block';
pre.textContent = 'Sending…';
try {
const res = await fetch(url, opts);
const text = await res.text();
let display = text;
try { display = JSON.stringify(JSON.parse(text), null, 2); } catch (_) {}
pre.textContent = `${res.status} ${res.statusText}\n\n${display}`;
} catch (e) {
pre.textContent = 'Request failed: ' + e.message;
}
});
return wrap;
}
async function loadExplorer() {
const container = $('#explorer-groups');
try {
const res = await fetch('/openapi.json', { credentials: 'same-origin' });
const schema = await res.json();
const groups = {};
for (const [path, methods] of Object.entries(schema.paths || {})) {
for (const [method, op] of Object.entries(methods)) {
const tag = (op.tags && op.tags[0]) || 'Other';
groups[tag] = groups[tag] || [];
groups[tag].push({ path, method, op });
}
}
container.innerHTML = '';
Object.entries(groups).forEach(([tag, ops]) => {
const groupWrap = document.createElement('div');
groupWrap.className = 'tag-group';
const h = document.createElement('h2');
h.textContent = tag;
h.style.fontSize = '14px';
h.style.color = 'var(--text-dim)';
h.style.textTransform = 'uppercase';
h.style.letterSpacing = '0.05em';
groupWrap.appendChild(h);
ops.forEach(({ path, method, op }) => {
const details = document.createElement('details');
details.className = 'endpoint';
const summary = document.createElement('summary');
summary.innerHTML = `<span class="${methodClass(method)}">${method.toUpperCase()}</span><span class="path">${path}</span><span style="color:var(--text-dim); font-size:12px; margin-left:auto;">${op.summary || ''}</span>`;
details.appendChild(summary);
let built = false;
details.addEventListener('toggle', () => {
if (details.open && !built) {
details.appendChild(buildEndpointBody(path, method, op));
built = true;
}
});
groupWrap.appendChild(details);
});
container.appendChild(groupWrap);
});
$('#instance-badge').textContent = schema.info && schema.info.description && schema.info.description.includes('dev') ? 'dev' : (window.location.port === '8001' ? 'dev' : 'main');
} catch (e) {
container.textContent = 'Failed to load schema: ' + e.message;
}
}
loadExplorer();
</script>
</body>
</html>
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment