Commit 78e816ec authored by Aryan Noshirvnai's avatar Aryan Noshirvnai

Merge origin/dev (remix engine, live rooms, channels, custom console) into dev

Reconciles the hardening/caching/deploy-pipeline work on this branch with the
previously-unmerged remix engine, Pass-the-Aux room websocket infra, Channels
router, and custom API console from origin/dev.

Conflict resolution notes:
- Kept the current JWT/session-based auth (src/core/security.py) over origin/dev's
  older session-string-header auth; adapted its unique test coverage (chats/music
  endpoint, discovery listen/swipe content paths, library search/stream/lyrics/
  playlist content paths, remix-tree tests) to the current auth_as fixture instead
  of dropping that coverage.
- Kept origin/dev's branded login-page + session-cookie docs auth (superset of the
  plain HTTP Basic version), and its recursive _build_remix_tree over a flat one-
  level version.
- Replaced the stopgap _run_lightweight_migrations()/create_all-at-import-time in
  database.py with Alembic, which both sides now share as the single source of
  truth for schema; generated a new migration for the 7 tables origin/dev added
  (Correction, RemixJob, Channel, ChannelFollow, VibeSet, VibeSetTrack, AudioStory,
  ChannelShowcase).
- Fixed a real bug surfaced by the merge: remix_engine.py and remix.py hardcoded
  /root/antigrav-stax-audio/* for stem cache/temp/downloads, a different directory
  than storage.py's LOCAL_STORAGE_ROOT-based paths that main.py's /downloads mount
  actually serves - remix downloads would have 404'd. Both now share storage.py's
  paths.
- deploy.sh and .gitlab-ci.yml now install CPU-only torch and libsndfile1, needed
  by the remix engine's demucs/librosa dependency chain.
- test_channels.py::test_showcase_owner_only still posted to /social/posts without
  auth headers; updated to use the auth_as fixture like the rest of the suite.

104 tests pass (up from 40 pre-merge + origin/dev's own suite, combined and
de-duplicated).
Co-Authored-By: 's avatarClaude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019i3NAUkLkHNbsPg5vKfzF9
parents 92a8a0e4 9c7c9c22
Pipeline #1010 failed
......@@ -9,9 +9,9 @@ LALAL_API_KEY=your_lalal_api_key_here
# No default, no fallback: the app refuses to start without it.
JWT_SECRET=
# Gate for the interactive API docs (/docs, /openapi.json)
DOCS_USERNAME=your_docs_username
DOCS_PASSWORD=your_docs_password
# HTTP Basic Auth credentials gating /docs and /openapi.json
DOCS_USERNAME=choose_a_username
DOCS_PASSWORD=choose_a_strong_password
# Where uploaded/tagged audio lives locally. Defaults to ./var/storage if unset.
LOCAL_STORAGE_ROOT=./var/storage
......
......@@ -16,7 +16,10 @@ test:
stage: test
image: python:3.10-slim
before_script:
- apt-get update -qq && apt-get install -y -qq --no-install-recommends ffmpeg git
- apt-get update -qq && apt-get install -y -qq --no-install-recommends ffmpeg git libsndfile1
# CPU-only torch first - this repo has no GPU anywhere, and the default PyPI
# wheel is a multi-GB CUDA build that would blow out CI time/disk for nothing.
- pip install --index-url https://download.pytorch.org/whl/cpu torch
- pip install --prefer-binary -q -r requirements.txt
script:
- PYTHONPATH=. pytest tests/ -v
......
"""add remix, channels, and correction tables
Revision ID: d7aa8b954a33
Revises: 704f3f6d4916
Create Date: 2026-08-09 09:01:33.744604
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision: str = 'd7aa8b954a33'
down_revision: Union[str, Sequence[str], None] = '704f3f6d4916'
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
"""Upgrade schema."""
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('corrections',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('user_id', sa.Integer(), nullable=True),
sa.Column('title', sa.String(), nullable=True),
sa.Column('artist', sa.String(), nullable=True),
sa.Column('source', sa.String(), nullable=True),
sa.Column('created_at', sa.DateTime(), nullable=True),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_corrections_id'), 'corrections', ['id'], unique=False)
op.create_index(op.f('ix_corrections_user_id'), 'corrections', ['user_id'], unique=False)
op.create_table('channels',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('owner_id', sa.Integer(), nullable=True),
sa.Column('name', sa.String(), nullable=True),
sa.Column('description', sa.String(), nullable=True),
sa.Column('avatar_url', sa.String(), nullable=True),
sa.Column('created_at', sa.DateTime(), nullable=True),
sa.ForeignKeyConstraint(['owner_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_channels_id'), 'channels', ['id'], unique=False)
op.create_index(op.f('ix_channels_name'), 'channels', ['name'], unique=False)
op.create_index(op.f('ix_channels_owner_id'), 'channels', ['owner_id'], unique=False)
op.create_table('audio_stories',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('channel_id', sa.Integer(), nullable=True),
sa.Column('song_id', sa.Integer(), nullable=True),
sa.Column('caption', sa.String(), nullable=True),
sa.Column('created_at', sa.DateTime(), nullable=True),
sa.Column('expires_at', sa.DateTime(), nullable=True),
sa.ForeignKeyConstraint(['channel_id'], ['channels.id'], ),
sa.ForeignKeyConstraint(['song_id'], ['library_songs.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_audio_stories_channel_id'), 'audio_stories', ['channel_id'], unique=False)
op.create_index(op.f('ix_audio_stories_id'), 'audio_stories', ['id'], unique=False)
op.create_table('channel_follows',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('channel_id', sa.Integer(), nullable=True),
sa.Column('user_id', sa.Integer(), nullable=True),
sa.Column('followed_at', sa.DateTime(), nullable=True),
sa.ForeignKeyConstraint(['channel_id'], ['channels.id'], ),
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_channel_follows_channel_id'), 'channel_follows', ['channel_id'], unique=False)
op.create_index(op.f('ix_channel_follows_id'), 'channel_follows', ['id'], unique=False)
op.create_index(op.f('ix_channel_follows_user_id'), 'channel_follows', ['user_id'], unique=False)
op.create_table('vibe_sets',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('channel_id', sa.Integer(), nullable=True),
sa.Column('title', sa.String(), nullable=True),
sa.Column('description', sa.String(), nullable=True),
sa.Column('created_at', sa.DateTime(), nullable=True),
sa.ForeignKeyConstraint(['channel_id'], ['channels.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_vibe_sets_channel_id'), 'vibe_sets', ['channel_id'], unique=False)
op.create_index(op.f('ix_vibe_sets_id'), 'vibe_sets', ['id'], unique=False)
op.create_table('channel_showcases',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('channel_id', sa.Integer(), nullable=True),
sa.Column('post_id', sa.Integer(), nullable=True),
sa.Column('added_at', sa.DateTime(), nullable=True),
sa.ForeignKeyConstraint(['channel_id'], ['channels.id'], ),
sa.ForeignKeyConstraint(['post_id'], ['posts.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_channel_showcases_channel_id'), 'channel_showcases', ['channel_id'], unique=False)
op.create_index(op.f('ix_channel_showcases_id'), 'channel_showcases', ['id'], unique=False)
op.create_index(op.f('ix_channel_showcases_post_id'), 'channel_showcases', ['post_id'], unique=False)
op.create_table('remix_jobs',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('status', sa.String(), nullable=True),
sa.Column('stage_detail', sa.String(), nullable=True),
sa.Column('prompt', sa.String(), nullable=True),
sa.Column('input_paths', sa.String(), nullable=True),
sa.Column('plan_json', sa.String(), nullable=True),
sa.Column('remix_name', sa.String(), nullable=True),
sa.Column('result_filename', sa.String(), nullable=True),
sa.Column('result_song_id', sa.Integer(), nullable=True),
sa.Column('result_post_id', sa.Integer(), nullable=True),
sa.Column('error', sa.String(), nullable=True),
sa.Column('created_at', sa.DateTime(), nullable=True),
sa.Column('updated_at', sa.DateTime(), nullable=True),
sa.ForeignKeyConstraint(['result_post_id'], ['posts.id'], ),
sa.ForeignKeyConstraint(['result_song_id'], ['library_songs.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_remix_jobs_id'), 'remix_jobs', ['id'], unique=False)
op.create_table('vibe_set_tracks',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('vibe_set_id', sa.Integer(), nullable=True),
sa.Column('song_id', sa.Integer(), nullable=True),
sa.Column('order', sa.Integer(), nullable=True),
sa.ForeignKeyConstraint(['song_id'], ['library_songs.id'], ),
sa.ForeignKeyConstraint(['vibe_set_id'], ['vibe_sets.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_vibe_set_tracks_id'), 'vibe_set_tracks', ['id'], unique=False)
op.create_index(op.f('ix_vibe_set_tracks_vibe_set_id'), 'vibe_set_tracks', ['vibe_set_id'], unique=False)
# ### end Alembic commands ###
def downgrade() -> None:
"""Downgrade schema."""
# ### commands auto generated by Alembic - please adjust! ###
op.drop_index(op.f('ix_vibe_set_tracks_vibe_set_id'), table_name='vibe_set_tracks')
op.drop_index(op.f('ix_vibe_set_tracks_id'), table_name='vibe_set_tracks')
op.drop_table('vibe_set_tracks')
op.drop_index(op.f('ix_remix_jobs_id'), table_name='remix_jobs')
op.drop_table('remix_jobs')
op.drop_index(op.f('ix_channel_showcases_post_id'), table_name='channel_showcases')
op.drop_index(op.f('ix_channel_showcases_id'), table_name='channel_showcases')
op.drop_index(op.f('ix_channel_showcases_channel_id'), table_name='channel_showcases')
op.drop_table('channel_showcases')
op.drop_index(op.f('ix_vibe_sets_id'), table_name='vibe_sets')
op.drop_index(op.f('ix_vibe_sets_channel_id'), table_name='vibe_sets')
op.drop_table('vibe_sets')
op.drop_index(op.f('ix_channel_follows_user_id'), table_name='channel_follows')
op.drop_index(op.f('ix_channel_follows_id'), table_name='channel_follows')
op.drop_index(op.f('ix_channel_follows_channel_id'), table_name='channel_follows')
op.drop_table('channel_follows')
op.drop_index(op.f('ix_audio_stories_id'), table_name='audio_stories')
op.drop_index(op.f('ix_audio_stories_channel_id'), table_name='audio_stories')
op.drop_table('audio_stories')
op.drop_index(op.f('ix_channels_owner_id'), table_name='channels')
op.drop_index(op.f('ix_channels_name'), table_name='channels')
op.drop_index(op.f('ix_channels_id'), table_name='channels')
op.drop_table('channels')
op.drop_index(op.f('ix_corrections_user_id'), table_name='corrections')
op.drop_index(op.f('ix_corrections_id'), table_name='corrections')
op.drop_table('corrections')
# ### end Alembic commands ###
......@@ -32,7 +32,7 @@ log "Ensuring system packages are present"
export DEBIAN_FRONTEND=noninteractive
apt-get update -qq
apt-get install -y -qq --no-install-recommends \
python3 python3-venv ffmpeg git curl build-essential
python3 python3-venv ffmpeg git curl build-essential libsndfile1
# --- 2. Repo - clone on a bare box, fetch+reset on an already-deployed one -----------------
if [ ! -d "$DEPLOY_DIR/.git" ]; then
......@@ -63,6 +63,9 @@ fi
log "Installing dependencies into $VENV_DIR"
# shellcheck disable=SC1091
source "$VENV_DIR/bin/activate"
# CPU-only torch first - this VPS has no GPU, and the default PyPI wheel is a multi-GB CUDA
# build. pip skips this entirely on repeat runs once the CPU wheel is already satisfied.
pip install --prefer-binary -q --index-url https://download.pytorch.org/whl/cpu torch
pip install --prefer-binary -q -r requirements.txt
# --- 4. .env - only (re)written when the CI job actually supplied prod secrets, so a manual
......
[Unit]
Description=Stax Backend API Service (dev branch)
After=network.target
[Service]
User=root
WorkingDirectory=/root/stax_backend_api-dev
ExecStart=/root/stax_backend_api-dev/venv/bin/uvicorn src.api.main:app --host 0.0.0.0 --port 8001
Restart=always
RestartSec=3
Environment=PYTHONPATH=/root/stax_backend_api-dev
Environment=HTTP_PROXY=http://127.0.0.1:8118
Environment=HTTPS_PROXY=http://127.0.0.1:8118
Environment=http_proxy=http://127.0.0.1:8118
Environment=https_proxy=http://127.0.0.1:8118
Environment=NO_PROXY=127.0.0.1,localhost
Environment=no_proxy=127.0.0.1,localhost
[Install]
WantedBy=multi-user.target
......@@ -10,6 +10,9 @@ google-generativeai==0.8.3
pedalboard==0.9.8
fastapi>=0.110.0
uvicorn>=0.28.0
websockets>=13.0 # uvicorn's WebSocket protocol implementation - without this, uvicorn
# silently has no WebSocket support at all (no error, connections just
# fail); needed for the Pass-the-Aux room websocket routes
sqlalchemy>=2.0.0
httpx>=0.27.0
python-multipart>=0.0.9
......@@ -19,3 +22,15 @@ pyrogram>=2.0.106
tgcrypto>=1.2.5
pyjwt>=2.8.0
alembic>=1.13.0
# Remix engine. Install torch CPU-only *before* this file, this VPS has no GPU:
# pip install torch --index-url https://download.pytorch.org/whl/cpu
# Otherwise pip pulls the default CUDA wheel (multiple GB, useless here).
# numpy is pinned <2: this VPS's virtualized CPU exposes no SSE3/SSE4/AVX at all,
# and numpy>=2's default wheels require the x86-64-v2 baseline and segfault/RuntimeError
# on import here. 1.26.4 is what the rest of this project already runs on successfully.
numpy==1.26.4
scipy==1.13.1
demucs>=4.0.1
librosa>=0.10.2
soundfile>=0.12.1
import base64
import os
import secrets
from fastapi import Depends, FastAPI, HTTPException, status
from datetime import datetime, timedelta, timezone
from fastapi import Depends, FastAPI, Form, HTTPException, Request, status
from fastapi.responses import HTMLResponse, JSONResponse, RedirectResponse
from fastapi.openapi.utils import get_openapi
from fastapi.security import HTTPBasic, HTTPBasicCredentials
from fastapi.staticfiles import StaticFiles
from sqlalchemy import text
from src.api.routers import auth, discovery, library, music, social
from src.api.routers import auth, channels, discovery, library, music, remix, social
from src.core.config import DOCS_PASSWORD, DOCS_USERNAME
from src.core.database import SessionLocal
from src.services.storage import DOWNLOADS_DIR
CONSOLE_HTML_PATH = os.path.join(os.path.dirname(__file__), "static", "console.html")
LOGIN_HTML_PATH = os.path.join(os.path.dirname(__file__), "static", "login.html")
# --- Docs auth: a real branded login page + session cookie, with HTTP Basic kept as a
# fallback for scripted/curl access (no browser to show a login page to). Sessions are
# in-memory only - lost on restart, which is fine for an admin-facing docs gate. ---
SESSION_COOKIE_NAME = "stax_docs_session"
SESSION_DURATION = timedelta(hours=24)
_active_sessions: dict[str, datetime] = {}
def _create_session() -> str:
token = secrets.token_urlsafe(32)
_active_sessions[token] = datetime.now(timezone.utc) + SESSION_DURATION
return token
def _check_session_cookie(request: Request) -> bool:
token = request.cookies.get(SESSION_COOKIE_NAME)
if not token:
return False
expiry = _active_sessions.get(token)
if not expiry or expiry < datetime.now(timezone.utc):
_active_sessions.pop(token, None)
return False
return True
def _check_basic_auth(request: Request) -> bool:
auth_header = request.headers.get("authorization", "")
if not auth_header.lower().startswith("basic "):
return False
try:
decoded = base64.b64decode(auth_header[6:]).decode()
username, _, password = decoded.partition(":")
except Exception:
return False
if not DOCS_USERNAME or not DOCS_PASSWORD:
return False
return secrets.compare_digest(username, DOCS_USERNAME) and secrets.compare_digest(password, DOCS_PASSWORD)
docs_security = HTTPBasic()
def _is_authenticated(request: Request) -> bool:
return _check_session_cookie(request) or _check_basic_auth(request)
def verify_docs_auth(credentials: HTTPBasicCredentials = Depends(docs_security)):
def require_docs_auth(request: Request):
if not DOCS_USERNAME or not DOCS_PASSWORD:
raise HTTPException(status_code=500, detail="DOCS_USERNAME/DOCS_PASSWORD are not configured on this server.")
valid_username = secrets.compare_digest(credentials.username, DOCS_USERNAME)
valid_password = secrets.compare_digest(credentials.password, DOCS_PASSWORD)
if not (valid_username and valid_password):
if not _is_authenticated(request):
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Incorrect username or password",
detail="Not authenticated",
headers={"WWW-Authenticate": "Basic"},
)
return credentials.username
app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None)
......@@ -40,6 +81,8 @@ app.include_router(discovery.router)
app.include_router(library.router)
app.include_router(music.router)
app.include_router(social.router)
app.include_router(remix.router)
app.include_router(channels.router)
@app.get("/", include_in_schema=False)
......@@ -47,6 +90,12 @@ async def root():
return RedirectResponse(url="/docs")
@app.get("/login", include_in_schema=False, response_class=HTMLResponse)
async def login_page():
with open(LOGIN_HTML_PATH, "r") as f:
return f.read()
@app.get("/healthz", include_in_schema=False)
async def healthz():
"""Unauthenticated liveness/readiness probe for the deploy script - confirms the process
......@@ -62,20 +111,47 @@ async def healthz():
return {"status": "ok"}
@app.post("/login", include_in_schema=False)
async def login_submit(username: str = Form(...), password: str = Form(...)):
if not DOCS_USERNAME or not DOCS_PASSWORD:
raise HTTPException(status_code=500, detail="DOCS_USERNAME/DOCS_PASSWORD are not configured on this server.")
if secrets.compare_digest(username, DOCS_USERNAME) and secrets.compare_digest(password, DOCS_PASSWORD):
token = _create_session()
response = RedirectResponse(url="/docs", status_code=status.HTTP_303_SEE_OTHER)
response.set_cookie(
SESSION_COOKIE_NAME, token, httponly=True, samesite="lax",
max_age=int(SESSION_DURATION.total_seconds()),
)
return response
return RedirectResponse(url="/login?error=1", status_code=status.HTTP_303_SEE_OTHER)
@app.get("/logout", include_in_schema=False)
async def logout(request: Request):
token = request.cookies.get(SESSION_COOKIE_NAME)
if token:
_active_sessions.pop(token, None)
response = RedirectResponse(url="/login")
response.delete_cookie(SESSION_COOKIE_NAME)
return response
@app.get("/docs", include_in_schema=False, response_class=HTMLResponse)
async def get_documentation(username: str = Depends(verify_docs_auth)):
async def get_documentation(request: Request):
if not _is_authenticated(request):
return RedirectResponse(url="/login")
with open(CONSOLE_HTML_PATH, "r") as f:
return f.read()
@app.get("/openapi.json", include_in_schema=False)
async def openapi(username: str = Depends(verify_docs_auth)):
async def openapi(request: Request, _auth=Depends(require_docs_auth)):
if app.openapi_schema:
return app.openapi_schema
openapi_schema = get_openapi(
title="Stax Music API",
version="1.0.0",
description="API backend for the Stax App. Features music tagging and batch remixing.",
description="API backend for the Stax App. Features music tagging, batch remixing, and AI multi-song remixing.",
routes=app.routes,
)
app.openapi_schema = openapi_schema
......
from datetime import datetime, timedelta, timezone
from typing import List, Optional
from fastapi import APIRouter, Depends, HTTPException, status
from pydantic import BaseModel
from sqlalchemy.orm import Session
from src.core.database import (
AudioStory,
Channel,
ChannelFollow,
ChannelShowcase,
LibrarySong,
Post,
VibeSet,
VibeSetTrack,
get_db,
)
router = APIRouter(prefix="/channels", tags=["Channels"])
STORY_LIFETIME = timedelta(hours=24)
class ChannelCreate(BaseModel):
owner_id: int
name: str
description: Optional[str] = None
avatar_url: Optional[str] = None
class FollowRequest(BaseModel):
user_id: int
class VibeSetCreate(BaseModel):
user_id: int # must match the channel's owner_id
title: str
description: Optional[str] = None
song_ids: List[int] = []
class StoryCreate(BaseModel):
user_id: int # must match the channel's owner_id
song_id: int
caption: Optional[str] = None
class ShowcaseCreate(BaseModel):
user_id: int # must match the channel's owner_id
post_id: int
def _get_channel_or_404(channel_id: int, db: Session) -> Channel:
channel = db.query(Channel).filter(Channel.id == channel_id).first()
if not channel:
raise HTTPException(status_code=404, detail="Channel not found")
return channel
def _require_owner(channel: Channel, user_id: int):
if channel.owner_id != user_id:
raise HTTPException(status_code=403, detail="Only the channel owner can do this")
@router.post("", status_code=status.HTTP_201_CREATED)
def create_channel(data: ChannelCreate, db: Session = Depends(get_db)):
channel = Channel(**data.dict())
db.add(channel)
db.commit()
db.refresh(channel)
return channel
@router.get("")
def list_channels(db: Session = Depends(get_db)):
return db.query(Channel).order_by(Channel.created_at.desc()).all()
# NOTE: routes with a fixed first path segment (vibe-sets/{id}) must be registered before
# the generic /{channel_id} catch-all below - FastAPI/Starlette match routes in
# registration order, and without an explicit {channel_id:int} converter a request for
# "/channels/vibe-sets/5" would otherwise match "/{channel_id}" first and 422 trying to
# parse "vibe-sets" as an int, never reaching this route at all.
@router.get("/vibe-sets/{vibe_set_id}")
def get_vibe_set(vibe_set_id: int, db: Session = Depends(get_db)):
vibe_set = db.query(VibeSet).filter(VibeSet.id == vibe_set_id).first()
if not vibe_set:
raise HTTPException(status_code=404, detail="Vibe set not found")
tracks = (
db.query(VibeSetTrack)
.filter(VibeSetTrack.vibe_set_id == vibe_set_id)
.order_by(VibeSetTrack.order)
.all()
)
return {"vibe_set": vibe_set, "tracks": tracks}
@router.get("/{channel_id}")
def get_channel(channel_id: int, db: Session = Depends(get_db)):
channel = _get_channel_or_404(channel_id, db)
follower_count = db.query(ChannelFollow).filter(ChannelFollow.channel_id == channel_id).count()
return {"channel": channel, "follower_count": follower_count}
@router.post("/{channel_id}/follow", status_code=status.HTTP_201_CREATED)
def follow_channel(channel_id: int, data: FollowRequest, db: Session = Depends(get_db)):
_get_channel_or_404(channel_id, db)
existing = db.query(ChannelFollow).filter(
ChannelFollow.channel_id == channel_id, ChannelFollow.user_id == data.user_id
).first()
if existing:
return existing
follow = ChannelFollow(channel_id=channel_id, user_id=data.user_id)
db.add(follow)
db.commit()
db.refresh(follow)
return follow
@router.post("/{channel_id}/unfollow")
def unfollow_channel(channel_id: int, data: FollowRequest, db: Session = Depends(get_db)):
follow = db.query(ChannelFollow).filter(
ChannelFollow.channel_id == channel_id, ChannelFollow.user_id == data.user_id
).first()
if follow:
db.delete(follow)
db.commit()
return {"status": "ok"}
@router.post("/{channel_id}/vibe-sets", status_code=status.HTTP_201_CREATED)
def create_vibe_set(channel_id: int, data: VibeSetCreate, db: Session = Depends(get_db)):
channel = _get_channel_or_404(channel_id, db)
_require_owner(channel, data.user_id)
vibe_set = VibeSet(channel_id=channel_id, title=data.title, description=data.description)
db.add(vibe_set)
db.commit()
db.refresh(vibe_set)
for i, song_id in enumerate(data.song_ids):
song = db.query(LibrarySong).filter(LibrarySong.id == song_id).first()
if not song:
raise HTTPException(status_code=400, detail=f"Library song {song_id} not found")
db.add(VibeSetTrack(vibe_set_id=vibe_set.id, song_id=song_id, order=i))
db.commit()
# SQLAlchemy sessions expire_on_commit by default - the second commit above (for the
# VibeSetTrack rows) re-expires vibe_set's already-loaded attributes even though it
# wasn't touched by that commit, and returning it unrefreshed serializes as {} (no
# error, just silently empty - this is what broke the vibe-set tests). Refresh again
# right before returning.
db.refresh(vibe_set)
return vibe_set
@router.get("/{channel_id}/vibe-sets")
def list_vibe_sets(channel_id: int, db: Session = Depends(get_db)):
_get_channel_or_404(channel_id, db)
return db.query(VibeSet).filter(VibeSet.channel_id == channel_id).order_by(VibeSet.created_at.desc()).all()
@router.post("/{channel_id}/stories", status_code=status.HTTP_201_CREATED)
def create_story(channel_id: int, data: StoryCreate, db: Session = Depends(get_db)):
channel = _get_channel_or_404(channel_id, db)
_require_owner(channel, data.user_id)
song = db.query(LibrarySong).filter(LibrarySong.id == data.song_id).first()
if not song:
raise HTTPException(status_code=400, detail=f"Library song {data.song_id} not found")
story = AudioStory(
channel_id=channel_id,
song_id=data.song_id,
caption=data.caption,
expires_at=datetime.now(timezone.utc) + STORY_LIFETIME,
)
db.add(story)
db.commit()
db.refresh(story)
return story
@router.get("/{channel_id}/stories")
def list_active_stories(channel_id: int, db: Session = Depends(get_db)):
_get_channel_or_404(channel_id, db)
now = datetime.now(timezone.utc)
return (
db.query(AudioStory)
.filter(AudioStory.channel_id == channel_id, AudioStory.expires_at >= now)
.order_by(AudioStory.created_at.desc())
.all()
)
@router.post("/{channel_id}/showcase", status_code=status.HTTP_201_CREATED)
def showcase_post(channel_id: int, data: ShowcaseCreate, db: Session = Depends(get_db)):
channel = _get_channel_or_404(channel_id, db)
_require_owner(channel, data.user_id)
post = db.query(Post).filter(Post.id == data.post_id).first()
if not post:
raise HTTPException(status_code=400, detail=f"Post {data.post_id} not found")
showcase = ChannelShowcase(channel_id=channel_id, post_id=data.post_id)
db.add(showcase)
db.commit()
db.refresh(showcase)
return showcase
@router.get("/{channel_id}/showcase")
def list_showcase(channel_id: int, db: Session = Depends(get_db)):
_get_channel_or_404(channel_id, db)
return (
db.query(ChannelShowcase)
.filter(ChannelShowcase.channel_id == channel_id)
.order_by(ChannelShowcase.added_at.desc())
.all()
)
import json
import os
import shutil
import uuid
from typing import List, Optional
from fastapi import APIRouter, BackgroundTasks, Depends, File, Form, HTTPException, Request, UploadFile
from sqlalchemy.orm import Session
from src.core.database import LibrarySong, RemixJob, get_db
from src.services import storage
from src.services.remix_engine import render_remix_sync
router = APIRouter(prefix="/remix", tags=["AI Remix"])
MAX_SONGS = 5
TEMP_DIR = storage.TEMP_DIR
@router.post("")
async def create_remix(
background_tasks: BackgroundTasks,
prompt: str = Form(..., description="Natural-language description of the remix you want, e.g. 'blend the vocals of the first song over the beat of the second, slowed down and dreamy'"),
files: List[UploadFile] = File(default=[], description="Audio files to remix together"),
library_song_ids: Optional[str] = Form(None, description="Comma-separated LibrarySong IDs to use as sources instead of (or alongside) uploaded files - using library songs is what lets the finished remix link back into the social/remix-tree graph"),
user_id: Optional[int] = Form(None, description="Attributes the resulting library entry and social post to this user"),
db: Session = Depends(get_db),
):
# Deliberately does nothing here except fast local I/O (save uploads, look up library
# rows) - no identify_audio/Shazam/AcoustID calls. Those are real network calls that can
# take ~30s each to time out, and doing them here would block this response for
# potentially minutes with multiple files. All of that happens inside the background
# job instead, where it belongs alongside the rest of the slow pipeline.
parsed_library_ids = [s.strip() for s in (library_song_ids or "").split(",") if s.strip()]
total_requested = len(parsed_library_ids) + len(files)
if total_requested == 0:
raise HTTPException(status_code=400, detail="At least one audio file or library_song_id is required.")
if total_requested > MAX_SONGS:
raise HTTPException(status_code=400, detail=f"At most {MAX_SONGS} songs are supported per remix.")
input_paths = []
filenames = []
source_song_ids = [] # parallel to input_paths: LibrarySong.id if this source came from
# the library (so the finished remix's Post can link back to it),
# None for a fresh upload with no existing library entry.
if library_song_ids:
for raw_id in library_song_ids.split(","):
raw_id = raw_id.strip()
if not raw_id:
continue
try:
song_id = int(raw_id)
except ValueError:
raise HTTPException(status_code=400, detail=f"Invalid library_song_ids value: {raw_id!r}")
song = db.query(LibrarySong).filter(LibrarySong.id == song_id).first()
if not song or not song.file_path or not os.path.exists(song.file_path):
raise HTTPException(status_code=400, detail=f"Library song {song_id} not found or its file is missing.")
input_paths.append(song.file_path)
filenames.append(song.title or os.path.basename(song.file_path))
source_song_ids.append(song.id)
try:
for f in files:
temp_path = os.path.join(TEMP_DIR, f"{uuid.uuid4()}_{f.filename}")
with open(temp_path, "wb") as buffer:
shutil.copyfileobj(f.file, buffer)
input_paths.append(temp_path)
filenames.append(f.filename)
source_song_ids.append(None)
except Exception as e:
for p in input_paths:
if os.path.exists(p) and p.startswith(TEMP_DIR):
os.remove(p)
raise HTTPException(status_code=500, detail=f"Failed to receive uploaded files: {e}")
job = RemixJob(status="queued", prompt=prompt, input_paths=json.dumps(input_paths))
db.add(job)
db.commit()
db.refresh(job)
background_tasks.add_task(render_remix_sync, job.id, input_paths, prompt, filenames, source_song_ids, user_id)
return {"job_id": job.id, "status": job.status, "status_url": f"/remix/{job.id}"}
@router.get("/{job_id}")
async def get_remix_status(job_id: int, request: Request, db: Session = Depends(get_db)):
job = db.query(RemixJob).filter(RemixJob.id == job_id).first()
if not job:
raise HTTPException(status_code=404, detail="Remix job not found.")
response = {
"job_id": job.id,
"status": job.status,
"stage_detail": job.stage_detail,
"remix_name": job.remix_name,
}
if job.plan_json:
response["plan"] = json.loads(job.plan_json)
if job.status == "done" and job.result_filename:
response["download_url"] = f"{str(request.base_url).rstrip('/')}/downloads/{job.result_filename}"
response["library_song_id"] = job.result_song_id
response["post_id"] = job.result_post_id
if job.status == "error":
response["error"] = job.error
return response
from fastapi import APIRouter, Depends, HTTPException, status
import time
from fastapi import APIRouter, Depends, HTTPException, WebSocket, WebSocketDisconnect, status
from pydantic import BaseModel
from sqlalchemy.orm import Session
from src.core.database import get_db, User, Post, GeoDrop, LiveRoom
from src.core.database import get_db, SessionLocal, User, Post, GeoDrop, LiveRoom
from src.core.security import get_current_user
from src.services.room_manager import room_manager
from datetime import datetime, timezone
import math
......@@ -39,18 +42,27 @@ def create_post(post: PostCreate, db: Session = Depends(get_db), current_user: U
db.refresh(db_post)
return db_post
MAX_TREE_DEPTH = 50 # guards against runaway recursion on pathological/corrupted data;
# normal remix trees (remixes of remixes of remixes...) come nowhere
# close to this in practice.
def _build_remix_tree(post_id: int, db: Session, depth: int = 0) -> dict:
post = db.query(Post).filter(Post.id == post_id).first()
children = db.query(Post).filter(Post.parent_post_id == post_id).all() if depth < MAX_TREE_DEPTH else []
return {
"post": post,
"children": [_build_remix_tree(c.id, db, depth + 1) for c in children],
}
@router.get("/posts/{post_id}/tree")
def get_remix_tree(post_id: int, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
post = db.query(Post).filter(Post.id == post_id).first()
if not post:
raise HTTPException(status_code=404, detail="Post not found")
children = db.query(Post).filter(Post.parent_post_id == post_id).all()
return {
"post": post,
"children": children
}
return _build_remix_tree(post_id, db)
@router.post("/geo-drop", status_code=status.HTTP_201_CREATED)
def create_geo_drop(drop: GeoDropCreate, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
......@@ -94,3 +106,126 @@ def create_live_room(room: LiveRoomCreate, db: Session = Depends(get_db), curren
def get_active_rooms(db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
rooms = db.query(LiveRoom).filter(LiveRoom.is_active == True).all()
return rooms
# --- Pass-the-Aux: live room WebSocket ---
# Chat, reactions/fire-meter, presence, and DJ handoff are all in-memory ephemeral state
# (src/services/room_manager.py) - only dj_id and current_song_id persist to the LiveRoom
# row, since those are the only parts that make sense to still be true if someone checks
# the room later via GET /social/rooms rather than being connected live.
def _get_room_or_none(room_id: int):
db = SessionLocal()
try:
return db.query(LiveRoom).filter(LiveRoom.id == room_id).first()
finally:
db.close()
def _set_room_dj(room_id: int, dj_id: int):
db = SessionLocal()
try:
room = db.query(LiveRoom).filter(LiveRoom.id == room_id).first()
if room:
room.dj_id = dj_id
db.commit()
finally:
db.close()
def _set_room_current_song(room_id: int, song_id):
db = SessionLocal()
try:
room = db.query(LiveRoom).filter(LiveRoom.id == room_id).first()
if room:
room.current_song_id = song_id
db.commit()
finally:
db.close()
@router.websocket("/rooms/{room_id}/ws")
async def room_websocket(websocket: WebSocket, room_id: int, user_id: int):
room_row = _get_room_or_none(room_id)
if not room_row:
await websocket.close(code=4404)
return
if not room_row.is_active:
await websocket.close(code=4403)
return
await room_manager.connect(room_id, user_id, websocket)
state = room_manager.get_room(room_id)
await websocket.send_json({
"type": "snapshot",
"dj_id": room_row.dj_id,
"current_song_id": room_row.current_song_id,
"presence": room_manager.presence(room_id),
"chat_history": list(state.chat_history),
"fire_count": state.fire_count(),
"dj_queue": state.dj_queue,
})
await room_manager.broadcast(room_id, {"type": "user_joined", "user_id": user_id}, exclude_user_id=user_id)
try:
while True:
data = await websocket.receive_json()
msg_type = data.get("type")
if msg_type == "chat":
text = str(data.get("text", ""))[:500]
if not text.strip():
continue
chat_msg = {"type": "chat", "user_id": user_id, "text": text}
state.chat_history.append(chat_msg)
await room_manager.broadcast(room_id, chat_msg)
elif msg_type == "reaction":
emoji = str(data.get("emoji", "🔥"))[:8]
if emoji == "🔥":
state.fire_events.append(time.time())
await room_manager.broadcast(room_id, {
"type": "reaction", "user_id": user_id, "emoji": emoji, "fire_count": state.fire_count(),
})
elif msg_type == "request_aux":
if user_id != room_row.dj_id and user_id not in state.dj_queue:
state.dj_queue.append(user_id)
await room_manager.broadcast(room_id, {"type": "queue_updated", "dj_queue": state.dj_queue})
elif msg_type == "pass_aux":
if user_id != room_row.dj_id:
await websocket.send_json({"type": "error", "detail": "Only the current DJ can pass the aux."})
continue
next_dj = None
if state.dj_queue:
next_dj = state.dj_queue.pop(0)
else:
requested = data.get("to_user_id")
if requested in state.connections:
next_dj = requested
if next_dj is not None:
room_row.dj_id = next_dj
_set_room_dj(room_id, next_dj)
await room_manager.broadcast(room_id, {"type": "dj_changed", "dj_id": next_dj, "dj_queue": state.dj_queue})
else:
await websocket.send_json({"type": "error", "detail": "No one is waiting to take the aux."})
elif msg_type == "now_playing":
if user_id != room_row.dj_id:
await websocket.send_json({"type": "error", "detail": "Only the current DJ can change what's playing."})
continue
song_id = data.get("song_id")
room_row.current_song_id = song_id
_set_room_current_song(room_id, song_id)
await room_manager.broadcast(room_id, {"type": "now_playing_changed", "song_id": song_id, "dj_id": user_id})
else:
await websocket.send_json({"type": "error", "detail": f"Unknown message type: {msg_type!r}"})
except WebSocketDisconnect:
pass
finally:
room_manager.disconnect(room_id, user_id)
await room_manager.broadcast(room_id, {"type": "user_left", "user_id": user_id})
......@@ -254,10 +254,47 @@
<header>
<h1>🎧 Stax<span> API</span> Console</h1>
<span class="badge" id="instance-badge">…</span>
<a href="/logout" style="margin-left:auto; color:var(--text-dim); font-size:12.5px; text-decoration:none;">Log out</a>
</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 and directs the arrangement (sections, harmonic key matching, sidechain, style), and Demucs does the actual stem separation before rendering.</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>Target key</span><b id="remix-result-key"></b></div>
<div class="row"><span>Style</span><b id="remix-result-style"></b></div>
<div class="row"><span>Sidechain</span><b id="remix-result-sidechain"></b></div>
<div id="remix-result-sections" style="margin-top:10px;"></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>
......@@ -328,6 +365,104 @@ function setupDropzone(dropEl, inputEl, listEl, multiple) {
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) {
const p = data.plan;
const noteNames = ['C','C#','D','D#','E','F','F#','G','G#','A','A#','B'];
$('#remix-result-bpm').textContent = p.target_bpm ?? '—';
$('#remix-result-key').textContent = (p.target_key_tonic !== undefined) ? noteNames[p.target_key_tonic] : '—';
$('#remix-result-style').textContent = p.style && p.style !== 'none' ? p.style : 'none';
$('#remix-result-sidechain').textContent = (p.sidechain && p.sidechain.enabled)
? `on (song #${p.sidechain.source_index} drums, ${Math.round((p.sidechain.amount||0)*100)}%)`
: 'off';
const sectionsEl = $('#remix-result-sections');
sectionsEl.innerHTML = '';
(p.sections || []).forEach(section => {
const row = document.createElement('div');
row.className = 'section-row';
const roles = (section.song_roles || [])
.map(r => `#${r.index}: ${(r.stems || []).join('+') || 'none'}`)
.join(' · ');
row.innerHTML = `<span class="section-name">${section.name}</span><span class="section-range">${Math.round(section.start_fraction*100)}%&ndash;${Math.round(section.end_fraction*100)}%</span><div class="section-roles">${roles || 'nothing active'}</div>`;
sectionsEl.appendChild(row);
});
}
$('#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);
......
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Stax API Console - Login</title>
<style>
:root {
--bg: #0D0F12;
--panel: #14171C;
--panel-2: #1B1F26;
--border: #262B33;
--text: #E7ECF2;
--text-dim: #8A93A3;
--accent: #00E5FF;
--accent-dim: #00B8CC;
--bad: #FF5C7A;
}
* { box-sizing: border-box; }
html, body {
height: 100%;
margin: 0;
}
body {
background: var(--bg);
color: var(--text);
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
display: flex;
align-items: center;
justify-content: center;
}
.card {
width: 100%;
max-width: 340px;
background: var(--panel);
border: 1px solid var(--border);
border-radius: 14px;
padding: 32px;
margin: 20px;
}
.card h1 {
font-size: 19px;
margin: 0 0 4px 0;
text-align: center;
}
.card h1 span { color: var(--accent); }
.card p.sub {
text-align: center;
color: var(--text-dim);
font-size: 12.5px;
margin: 0 0 24px 0;
}
label {
display: block;
font-size: 11.5px;
color: var(--text-dim);
text-transform: uppercase;
letter-spacing: 0.04em;
margin-bottom: 6px;
}
input {
width: 100%;
background: var(--panel-2);
border: 1px solid var(--border);
border-radius: 8px;
color: var(--text);
padding: 11px 12px;
font-size: 14px;
margin-bottom: 16px;
}
input:focus { outline: none; border-color: var(--accent); }
button {
width: 100%;
background: var(--accent);
color: #06141A;
border: none;
border-radius: 8px;
padding: 12px;
font-weight: 700;
font-size: 14px;
cursor: pointer;
margin-top: 4px;
}
button:hover { background: var(--accent-dim); }
.error {
display: none;
background: rgba(255, 92, 122, 0.1);
border: 1px solid var(--bad);
color: var(--bad);
border-radius: 8px;
padding: 10px 12px;
font-size: 12.5px;
margin-bottom: 16px;
text-align: center;
}
.error.show { display: block; }
</style>
</head>
<body>
<div class="card">
<h1>🎧 Stax<span> API</span></h1>
<p class="sub">Sign in to view the API console</p>
<div class="error" id="error-box">Incorrect username or password.</div>
<form method="post" action="/login">
<label for="username">Username</label>
<input type="text" id="username" name="username" autocomplete="username" required autofocus>
<label for="password">Password</label>
<input type="password" id="password" name="password" autocomplete="current-password" required>
<button type="submit">Sign In</button>
</form>
</div>
<script>
if (new URLSearchParams(location.search).get('error') === '1') {
document.getElementById('error-box').classList.add('show');
}
</script>
</body>
</html>
......@@ -145,9 +145,108 @@ class IdentifiedTrack(Base):
lyrics = Column(String)
identified_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
class Correction(Base):
__tablename__ = "corrections"
id = Column(Integer, primary_key=True, index=True)
user_id = Column(Integer, index=True)
title = Column(String)
artist = Column(String)
source = Column(String)
created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
class RemixJob(Base):
__tablename__ = "remix_jobs"
id = Column(Integer, primary_key=True, index=True)
status = Column(String, default="queued") # queued, planning, separating, mixing, mastering, tagging, done, error
stage_detail = Column(String, nullable=True)
prompt = Column(String)
input_paths = Column(String) # JSON-encoded list of source file paths
plan_json = Column(String, nullable=True) # the AI-generated remix plan, once produced
remix_name = Column(String, nullable=True)
result_filename = Column(String, nullable=True)
result_song_id = Column(Integer, ForeignKey("library_songs.id"), nullable=True) # set once the finished remix is registered in the library
result_post_id = Column(Integer, ForeignKey("posts.id"), nullable=True) # set once the finished remix is posted to the social feed
error = Column(String, nullable=True)
created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
updated_at = Column(DateTime, default=lambda: datetime.now(timezone.utc), onupdate=lambda: datetime.now(timezone.utc))
# --- Channels: the creator hub. Users host a channel and publish Vibe Sets (curated song
# collections), Audio Stories (ephemeral short clips), and showcase specific remixes
# (existing Posts) - the one pillar from the original vision doc with nothing built at all
# before this.
class Channel(Base):
__tablename__ = "channels"
id = Column(Integer, primary_key=True, index=True)
owner_id = Column(Integer, ForeignKey("users.id"), index=True)
name = Column(String, index=True)
description = Column(String, nullable=True)
avatar_url = Column(String, nullable=True)
created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
class ChannelFollow(Base):
__tablename__ = "channel_follows"
id = Column(Integer, primary_key=True, index=True)
channel_id = Column(Integer, ForeignKey("channels.id"), index=True)
user_id = Column(Integer, ForeignKey("users.id"), index=True)
followed_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
class VibeSet(Base):
__tablename__ = "vibe_sets"
id = Column(Integer, primary_key=True, index=True)
channel_id = Column(Integer, ForeignKey("channels.id"), index=True)
title = Column(String)
description = Column(String, nullable=True)
created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
class VibeSetTrack(Base):
__tablename__ = "vibe_set_tracks"
id = Column(Integer, primary_key=True, index=True)
vibe_set_id = Column(Integer, ForeignKey("vibe_sets.id"), index=True)
song_id = Column(Integer, ForeignKey("library_songs.id"))
order = Column(Integer)
class AudioStory(Base):
__tablename__ = "audio_stories"
id = Column(Integer, primary_key=True, index=True)
channel_id = Column(Integer, ForeignKey("channels.id"), index=True)
song_id = Column(Integer, ForeignKey("library_songs.id"))
caption = Column(String, nullable=True)
created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
expires_at = Column(DateTime) # default 24h from creation, set at insert time (matches
# the existing DiscoveredSong 24h-history pattern: rows
# aren't deleted on expiry, just filtered out of "active"
# queries - see get_active_stories in channels.py)
class ChannelShowcase(Base):
__tablename__ = "channel_showcases"
id = Column(Integer, primary_key=True, index=True)
channel_id = Column(Integer, ForeignKey("channels.id"), index=True)
post_id = Column(Integer, ForeignKey("posts.id"), index=True)
added_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
def init_db():
"""Schema is normally created/updated via `alembic upgrade head` (see alembic/). This is
a defensive fallback for src/telegram_bot/bot.py, which calls it before starting in case
the bot runs as a standalone process before migrations have ever been applied - create_all
only fills in missing tables, it won't conflict with Alembic-managed ones."""
Base.metadata.create_all(bind=engine)
def log_correction(user_id: int, title: str, artist: str, source: str):
"""Records a user's manual song-ID correction/confirmation from the Telegram bot flow
(picking from candidates, typing manually, or confirming a Gemini guess) as a simple
audit trail - was called from bot.py but never implemented anywhere."""
db = SessionLocal()
try:
db.add(Correction(user_id=user_id, title=title, artist=artist, source=source))
db.commit()
finally:
db.close()
import os
import shutil
import aiohttp
from pydub import AudioSegment
from mutagen.mp3 import MP3
......@@ -18,7 +19,6 @@ async def tag_and_convert_audio(raw_file_path: str, candidate: dict) -> str:
# 1. Convert to MP3 (or skip if already MP3)
if raw_file_path.lower().endswith('.mp3'):
mp3_file_path = f"{raw_file_path}_tagged.mp3"
import shutil
shutil.copyfile(raw_file_path, mp3_file_path)
else:
mp3_file_path = f"{raw_file_path}.mp3"
......@@ -55,11 +55,14 @@ async def tag_and_convert_audio(raw_file_path: str, candidate: dict) -> str:
# Persian text saved as v2.3+UTF-8 renders as mojibake in many players.
mp3.save(v2_version=4)
# 3. Rename file
# 3. Move into place. shutil.move (not os.rename) - the source lives under a temp dir
# that can be a different filesystem/mount from the destination (e.g. a separate CI
# build volume), and os.rename raises "Invalid cross-device link" (EXDEV) whenever
# source and destination aren't on the same filesystem. shutil.move falls back to a
# copy+delete in that case, so it works regardless of the deployment's mount topology.
safe_title = "".join([c for c in title if c.isalnum() or c==' ']).rstrip()
final_filename = f"{safe_title}.mp3" if safe_title else "Unknown Track.mp3"
import shutil as _shutil
final_path = os.path.join(os.path.dirname(mp3_file_path) or ".", final_filename)
_shutil.move(mp3_file_path, final_path)
shutil.move(mp3_file_path, final_path)
return final_path
import asyncio
import hashlib
import json
import os
import shutil
import threading
import google.generativeai as genai
import librosa
import numpy as np
import soundfile as sf
import torch
from pedalboard import (
Compressor,
Distortion,
HighpassFilter,
LowpassFilter,
LowShelfFilter,
Pedalboard,
PitchShift,
Reverb,
)
from scipy.signal import butter, filtfilt
from src.core.config import GEMINI_API_KEY, logger
from src.core.database import LibrarySong, Post, RemixJob, SessionLocal
from src.services import storage
from src.services.music_identification import identify_audio
# This VPS's virtualized CPU exposes no SSE3/SSE4/AVX at all, which makes PyTorch's
# oneDNN (MKLDNN) backend fail with "could not create a primitive" on demucs's real-sized
# convolutions (a tiny toy conv works fine, which is what makes this easy to miss). Disabling
# MKLDNN falls back to PyTorch's plain conv kernels, which are slower but actually run here.
torch.backends.mkldnn.enabled = False
if GEMINI_API_KEY:
genai.configure(api_key=GEMINI_API_KEY)
# Shares storage.py's LOCAL_STORAGE_ROOT rather than a separate hardcoded tree, so remix
# output lands in the same directory the /downloads StaticFiles mount actually serves.
STEM_CACHE_DIR = os.path.join(storage.LOCAL_STORAGE_ROOT, "stem_cache")
REMIX_TEMP_DIR = storage.TEMP_DIR
DOWNLOADS_DIR = storage.DOWNLOADS_DIR
STEM_NAMES = ["vocals", "drums", "bass", "other"]
TARGET_SR = 44100
os.makedirs(STEM_CACHE_DIR, exist_ok=True)
def _file_hash(file_path: str) -> str:
h = hashlib.sha256()
with open(file_path, "rb") as f:
for chunk in iter(lambda: f.read(1 << 20), b""):
h.update(chunk)
return h.hexdigest()[:24]
# ---------------------------------------------------------------------------
# Stem separation (Demucs)
# ---------------------------------------------------------------------------
_separator = None
_separator_lock = threading.Lock()
def _get_separator():
global _separator
if _separator is None:
from demucs.api import Separator
_separator = Separator(model="htdemucs")
return _separator
def separate_stems(file_path: str) -> dict:
"""Runs Demucs source separation, caching results by file content hash so the
same song is never separated twice.
Guarded by a process-wide lock: concurrent calls into demucs/the HF Hub model cache
hung indefinitely in testing (not documented as thread-safe), and this VPS's weak,
no-AVX CPU would thrash running two Demucs passes concurrently anyway - serializing
fixes both at once."""
key = _file_hash(file_path)
cache_dir = os.path.join(STEM_CACHE_DIR, key)
stem_paths = {name: os.path.join(cache_dir, f"{name}.wav") for name in STEM_NAMES}
if all(os.path.exists(p) for p in stem_paths.values()):
return stem_paths
os.makedirs(cache_dir, exist_ok=True)
with _separator_lock:
separator = _get_separator()
_, separated = separator.separate_audio_file(file_path)
for name, tensor in separated.items():
audio = tensor.numpy().T # (channels, samples) -> (samples, channels)
sf.write(stem_paths[name], audio, separator.samplerate)
return stem_paths
# ---------------------------------------------------------------------------
# Tempo & key detection - real analysis, not AI guesswork
# ---------------------------------------------------------------------------
def detect_bpm(file_path: str) -> float:
y, sr = librosa.load(file_path, sr=None, mono=True, duration=60)
tempo, _ = librosa.beat.beat_track(y=y, sr=sr)
tempo = float(tempo)
return tempo if 40 < tempo < 220 else 120.0
PITCH_CLASSES = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"]
# Krumhansl-Kessler key profiles: relative weight of each scale degree in a listener's
# sense of a major/minor key. Correlating a track's chroma vector against all 24 rotations
# of these is a standard, well-established key-estimation technique.
_MAJOR_PROFILE = np.array([6.35, 2.23, 3.48, 2.33, 4.38, 4.09, 2.52, 5.19, 2.39, 3.66, 2.29, 2.88])
_MINOR_PROFILE = np.array([6.33, 2.68, 3.52, 5.38, 2.60, 3.53, 2.54, 4.75, 3.98, 2.69, 3.34, 3.17])
def detect_key(file_path: str) -> dict:
"""Estimates musical key via chroma features + Krumhansl-Kessler profile correlation.
Returns {"tonic": 0-11 pitch class, "mode": "major"|"minor", "name": "C major"}.
This exists so pitch-shift decisions are computed from real harmonic data instead of
an AI guessing a semitone number with nothing to back it - see _semitone_shift_to_key."""
y, sr = librosa.load(file_path, sr=22050, mono=True, duration=60)
chroma = librosa.feature.chroma_cqt(y=y, sr=sr)
chroma_mean = chroma.mean(axis=1)
total = chroma_mean.sum()
if total > 0:
chroma_mean = chroma_mean / total
best_score, best_tonic, best_mode = -np.inf, 0, "major"
for tonic in range(12):
for mode, profile in (("major", _MAJOR_PROFILE), ("minor", _MINOR_PROFILE)):
rotated = np.roll(profile, tonic)
score = np.corrcoef(chroma_mean, rotated)[0, 1]
if score > best_score:
best_score, best_tonic, best_mode = score, tonic, mode
return {"tonic": best_tonic, "mode": best_mode, "name": f"{PITCH_CLASSES[best_tonic]} {best_mode}"}
def _semitone_shift_to_key(from_tonic: int, to_tonic: int) -> int:
"""Smallest-magnitude semitone shift, in [-6, 6], that moves from_tonic to to_tonic
(mod-12 circular distance) - minimizes audible pitch-shift artifacts while still
landing exactly on the target key."""
diff = (to_tonic - from_tonic) % 12
if diff > 6:
diff -= 12
return int(diff)
# ---------------------------------------------------------------------------
# AI pipeline: a single Gemini call both perceives the audio (real previews of every
# song) and reasons about the request, producing the full structured plan.
# ---------------------------------------------------------------------------
def _make_audio_preview_part(file_path: str, seconds: int = 25) -> dict:
y, sr = librosa.load(file_path, sr=22050, mono=True, duration=seconds)
preview_path = file_path + ".preview.wav"
sf.write(preview_path, y, sr)
with open(preview_path, "rb") as f:
data = f.read()
os.remove(preview_path)
return {"mime_type": "audio/wav", "data": data}
def _coerce_gain_db(value) -> float:
"""The schema asks Gemini for a single float gain_db per song_role, but it has been
observed returning a per-stem breakdown instead (e.g. {"drums": -6.0, "other": 0.0})
when a role has multiple stems - even with response_mime_type=application/json
constraining valid JSON syntax, the *shape* of a field isn't guaranteed. Rather than
tightening the prompt and hoping it never recurs, this coerces whatever comes back into
a single usable float: a dict's values are averaged, anything else falls back to 0."""
if isinstance(value, dict):
numbers = [v for v in value.values() if isinstance(v, (int, float))]
return float(sum(numbers) / len(numbers)) if numbers else 0.0
if isinstance(value, (int, float)):
return float(value)
return 0.0
async def plan_remix(prompt: str, songs_info: list) -> dict:
"""Gemini listens to a real audio preview of every song plus real detected BPM/key data,
and produces the full executable plan in one call: a sectioned arrangement, harmonic
pitch target, sidechain routing, and a style preset - not just "pick some stems and slap
reverb on it".
gemini-2.5-pro would reason about structure better than flash, but this API key's free
tier has a hard zero quota for -pro (confirmed via a live 429: "limit: 0" - not
exhausted, actually zero allocation), so flash is what's actually usable here. The
"refinement" is in the prompt itself: real audio previews of every song, real detected
BPM/key data instead of guesses, and an explicit schema for structure/harmony/sidechain/
style that flash is quite capable of following even if it reasons less deeply than pro
would."""
if not GEMINI_API_KEY:
raise Exception("GEMINI_API_KEY not configured.")
model = genai.GenerativeModel(
"gemini-2.5-flash", generation_config={"response_mime_type": "application/json"}
)
song_lines = []
parts = []
for info in songs_info:
song_lines.append(
f'Song {info["index"]}: "{info["title"]}" by {info["artist"]} - '
f'{info["bpm"]:.0f} BPM, detected key {info["key_name"]}.'
)
parts.append(_make_audio_preview_part(info["path"]))
instructions = f"""You are directing a real stem-based remix engine - every decision you make here gets executed literally by DSP code, not summarized or reinterpreted. Take the request seriously and commit to it structurally, not just with a reverb tail at the end.
You've been given {len(songs_info)} song(s) as real audio previews (in the order listed below, alongside their detected tempo and key), plus a user's natural-language request. Listen to each one before deciding anything - the mood, energy, vocal character, and instrumentation you actually hear should drive your choices, not just the title/artist text.
Each song has already been split into 4 isolated stems: vocals, drums, bass, other (harmony/instrumentation). The engine can:
- Include/exclude any stem from any song, at any gain, in any section.
- Time-stretch everything to one shared target BPM.
- Pitch-shift each song by a whole number of semitones to harmonically match a shared target key (the engine computes the exact semitone value from the real detected keys above - you only choose which detected key to target).
- Apply sidechain ducking: one song's drums stem can rhythmically duck the volume of everything else - the "pump" that makes a mix groove. Use this when it fits the request (e.g. anything upbeat/electronic/danceable), not by default.
- Render distinct SECTIONS across the timeline (e.g. intro / build / drop / breakdown / outro), each with a different combination of active stems - this is what makes the result an actual arrangement instead of every stem playing for the whole duration. Use at least 2 sections for anything but the simplest single-song requests.
- Apply a named style preset that shapes the final tone: "lofi" (filtered, warm, saturated), "trap" (heavy low end, punchy), "house" (clean, driving), or "none".
Songs:
{os.linesep.join(song_lines)}
User's request: "{prompt}"
If they ask for a specific genre/style, pick sections, stems, sidechain, and the style preset that actually reads as that genre - don't just rely on the style preset alone to do all the work. If they ask for a mashup, make sure both songs meaningfully contribute across different sections rather than one being wallpaper under the other's vocal for the whole duration.
Return a JSON object strictly following this schema:
{{
"remix_name": str (2-4 word creative title, do NOT include the word "remix"),
"target_bpm": float,
"target_key_tonic": int (0-11, pitch class: 0=C, 1=C#, 2=D, 3=D#, 4=E, 5=F, 6=F#, 7=G, 8=G#, 9=A, 10=A#, 11=B - pick one of the songs' detected tonics, or a musically related one),
"style": str, one of "none", "lofi", "trap", "house",
"sidechain": {{"enabled": bool, "source_index": int (which song's drums stem drives the pump), "amount": float (0.0-1.0)}},
"sections": [
{{
"name": str (e.g. "intro", "build", "drop", "breakdown", "outro"),
"start_fraction": float (0.0-1.0, position in the overall timeline),
"end_fraction": float (0.0-1.0, greater than start_fraction),
"song_roles": [
{{"index": int, "stems": [str, subset of "vocals"/"drums"/"bass"/"other"], "gain_db": float (a single overall number for this role, e.g. -3.0 - NOT a per-stem breakdown/object, even if multiple stems are listed)}}
]
}}
],
"master_effects": {{
"reverb_room_size": float (0.0-1.0),
"compressor_threshold_db": float (-20 to -6),
"compressor_ratio": float (1.5 to 6)
}}
}}
sections must be contiguous and cover start_fraction 0.0 through end_fraction 1.0 with no gaps or overlaps, at least 1 section and no more than 6."""
parts.append(instructions)
# Gemini occasionally returns syntactically invalid JSON despite
# response_mime_type=application/json constraining the output format (seen live: a
# missing comma partway through a large structured response) - a plain retry is the
# standard, effective mitigation for this class of transient generation flakiness.
last_error = None
for attempt in range(3):
response = await asyncio.to_thread(model.generate_content, parts)
try:
plan = json.loads(response.text)
break
except json.JSONDecodeError as e:
last_error = e
logger.warning(f"plan_remix: invalid JSON on attempt {attempt + 1}/3: {e}. Raw response: {response.text[:500]}")
else:
raise Exception(f"Gemini returned invalid JSON for the remix plan after 3 attempts: {last_error}")
valid_indices = {info["index"] for info in songs_info}
for section in plan.get("sections", []):
for role in section.get("song_roles", []):
role["stems"] = [s for s in role.get("stems", []) if s in STEM_NAMES]
role["gain_db"] = _coerce_gain_db(role.get("gain_db", 0.0))
section["song_roles"] = [r for r in section.get("song_roles", []) if r.get("index") in valid_indices]
if not plan.get("sections"):
plan["sections"] = [{
"name": "full",
"start_fraction": 0.0,
"end_fraction": 1.0,
"song_roles": [{"index": i, "stems": STEM_NAMES, "gain_db": 0.0} for i in valid_indices],
}]
return plan
# ---------------------------------------------------------------------------
# Audio helpers: stretching, tiling, sidechain, style presets
# ---------------------------------------------------------------------------
def _time_stretch_to_bpm(audio: np.ndarray, current_bpm: float, target_bpm: float) -> np.ndarray:
if current_bpm <= 0 or abs(current_bpm - target_bpm) < 0.5:
return audio
rate = target_bpm / current_bpm
return librosa.effects.time_stretch(np.ascontiguousarray(audio), rate=rate)
def _pitch_shift(audio: np.ndarray, sr: int, semitones: int) -> np.ndarray:
if not semitones:
return audio
board = Pedalboard([PitchShift(semitones=semitones)])
out = board(audio.astype(np.float32), sr)
return out[0] if out.ndim > 1 else out
def _pad_add(a: np.ndarray, b: np.ndarray) -> np.ndarray:
if len(a) < len(b):
a = np.pad(a, (0, len(b) - len(a)))
elif len(b) < len(a):
b = np.pad(b, (0, len(a) - len(b)))
return a + b
def _tile_to_length(audio: np.ndarray, target_len: int) -> np.ndarray:
if len(audio) == 0:
return np.zeros(target_len, dtype=np.float32)
if len(audio) >= target_len:
return audio[:target_len]
reps = int(np.ceil(target_len / len(audio)))
return np.tile(audio, reps)[:target_len]
def _sidechain_gain_envelope(source_audio: np.ndarray, sr: int, amount: float) -> np.ndarray:
"""Derives a gain-reduction curve from a source signal's energy (typically a drum/kick
stem) that, multiplied onto other stems, produces the classic sidechain 'pump'. A
vectorized lowpass-filtered envelope follower rather than a per-sample Python loop -
this needs to run on a CPU with no SIMD acceleration, so a compiled scipy filter instead
of a manual attack/release loop is the difference between milliseconds and minutes."""
rectified = np.abs(source_audio)
peak = np.max(rectified)
if peak > 0:
rectified = rectified / peak
b, a = butter(2, 8.0 / (sr / 2), btype="low")
envelope = filtfilt(b, a, rectified)
envelope = np.clip(envelope, 0.0, 1.0)
gain = 1.0 - amount * envelope
return np.clip(gain, 1.0 - amount, 1.0).astype(np.float32)
def _apply_style_preset(audio: np.ndarray, sr: int, style: str) -> np.ndarray:
stages = []
if style == "lofi":
stages = [LowpassFilter(cutoff_frequency_hz=4500), Distortion(drive_db=8)]
elif style == "trap":
stages = [LowShelfFilter(cutoff_frequency_hz=100, gain_db=6), Compressor(threshold_db=-18, ratio=4)]
elif style == "house":
stages = [HighpassFilter(cutoff_frequency_hz=30), Compressor(threshold_db=-16, ratio=3)]
if not stages:
return audio
board = Pedalboard(stages)
return board(audio.astype(np.float32), sr)
# ---------------------------------------------------------------------------
# Main pipeline
# ---------------------------------------------------------------------------
def render_remix_sync(job_id: int, input_paths: list, prompt: str, filenames: list, source_song_ids: list = None, user_id: int = None):
"""The full remix pipeline: identify -> detect BPM/key -> plan (Gemini, listens to real
audio previews and directs the whole arrangement) -> separate (Demucs) -> stretch/
pitch-match each stem once -> render each section of the arrangement -> sidechain ->
style preset -> master -> tag -> register in the library and post to the social feed.
Runs in a worker thread via FastAPI's BackgroundTasks; updates the RemixJob row in the
DB as it progresses so clients can poll status. identify_audio and the AI calls run here
(not in the API handler) because they're slow, unpredictable-latency network calls that
would otherwise block the initial HTTP response for a long time.
source_song_ids is parallel to input_paths: a LibrarySong.id for any source that came
from the library (skips the redundant identify_audio call and lets the finished remix's
Post link back to that song's existing Post, if any - this is what makes a "remix tree"
reflect an actual remix instead of only manual /social/posts calls), or None for a
source with no existing library entry (a fresh upload)."""
db = SessionLocal()
source_song_ids = source_song_ids or [None] * len(input_paths)
def set_status(status: str, detail: str = None):
job = db.query(RemixJob).filter(RemixJob.id == job_id).first()
job.status = status
if detail is not None:
job.stage_detail = detail
db.commit()
try:
set_status("planning", "Identifying songs, detecting tempo and key")
songs_info = []
for i, path in enumerate(input_paths):
bpm = detect_bpm(path)
key = detect_key(path)
fallback_title = os.path.splitext(filenames[i])[0] if i < len(filenames) else f"Track {i + 1}"
title, artist = fallback_title, "Unknown Artist"
existing_song_id = source_song_ids[i] if i < len(source_song_ids) else None
if existing_song_id is not None:
existing = db.query(LibrarySong).filter(LibrarySong.id == existing_song_id).first()
if existing:
title = existing.title or title
artist = existing.artist or artist
else:
try:
candidates = asyncio.run(identify_audio(path))
if candidates:
title = candidates[0].get("title", title)
artist = candidates[0].get("artist", artist)
except Exception as e:
logger.warning(f"identify_audio failed for song {i}, using filename as title: {e}")
songs_info.append({
"index": i, "path": path, "bpm": bpm,
"key_tonic": key["tonic"], "key_name": key["name"],
"title": title, "artist": artist,
})
set_status("planning", "Listening to each song and directing the arrangement (Gemini)")
plan = asyncio.run(plan_remix(prompt, songs_info))
job = db.query(RemixJob).filter(RemixJob.id == job_id).first()
job.plan_json = json.dumps(plan)
job.remix_name = plan.get("remix_name", "Untitled")
db.commit()
target_bpm = float(plan.get("target_bpm") or songs_info[0]["bpm"])
target_key_tonic = int(plan.get("target_key_tonic", songs_info[0]["key_tonic"]))
set_status("separating", "Running stem separation (this is the slow part)")
# Every stem of every song used anywhere in the plan gets stretched/pitch-matched
# ONCE and cached in memory; sections then just slice/sum from this shared pool
# instead of reprocessing per section.
used_song_indices = {
role["index"]
for section in plan["sections"]
for role in section["song_roles"]
}
prepared_stems = {} # song_index -> stem_name -> np.ndarray
for idx in used_song_indices:
info = songs_info[idx]
stem_paths = separate_stems(info["path"])
semitone_shift = _semitone_shift_to_key(info["key_tonic"], target_key_tonic)
prepared_stems[idx] = {}
for stem_name, stem_path in stem_paths.items():
y, _ = librosa.load(stem_path, sr=TARGET_SR, mono=True)
y = _time_stretch_to_bpm(y, info["bpm"], target_bpm)
y = _pitch_shift(y, TARGET_SR, semitone_shift)
prepared_stems[idx][stem_name] = y.astype(np.float32)
set_status("mixing", "Rendering the arrangement section by section")
total_len = max(len(y) for stems in prepared_stems.values() for y in stems.values())
rest_buffer = np.zeros(total_len, dtype=np.float32)
source_drums_buffer = np.zeros(total_len, dtype=np.float32)
sidechain = plan.get("sidechain") or {}
sidechain_source_idx = sidechain.get("source_index") if sidechain.get("enabled") else None
crossfade_len = min(int(TARGET_SR * 0.3), total_len // 20 if total_len else 0)
for section in plan["sections"]:
start = int(section["start_fraction"] * total_len)
end = int(section["end_fraction"] * total_len)
end = max(end, start + 1)
section_len = end - start
fade = np.ones(section_len, dtype=np.float32)
if crossfade_len > 0:
ramp = np.linspace(0.0, 1.0, crossfade_len, dtype=np.float32)
if start > 0:
fade[:crossfade_len] = ramp
if end < total_len:
fade[-crossfade_len:] = np.minimum(fade[-crossfade_len:], ramp[::-1])
for role in section["song_roles"]:
idx = role["index"]
stems_wanted = role.get("stems", [])
if not stems_wanted or idx not in prepared_stems:
continue
gain = 10 ** (_coerce_gain_db(role.get("gain_db", 0)) / 20)
for stem_name in stems_wanted:
full = prepared_stems[idx].get(stem_name)
if full is None:
continue
segment = _tile_to_length(full[start:end] if start < len(full) else np.zeros(section_len, dtype=np.float32), section_len)
segment = segment * gain * fade
is_source_drums = (idx == sidechain_source_idx and stem_name == "drums")
target_buffer = source_drums_buffer if is_source_drums else rest_buffer
target_buffer[start:end] = _pad_add(target_buffer[start:end], segment)
if sidechain_source_idx is not None:
set_status("mixing", "Applying sidechain")
envelope = _sidechain_gain_envelope(source_drums_buffer, TARGET_SR, float(sidechain.get("amount", 0.6)))
mix = source_drums_buffer + rest_buffer * envelope
else:
mix = source_drums_buffer + rest_buffer
peak = np.max(np.abs(mix)) or 1.0
if peak > 0.98:
mix = mix / peak * 0.98
style = plan.get("style", "none")
if style and style != "none":
set_status("mastering", f"Applying '{style}' style preset")
mix = _apply_style_preset(mix, TARGET_SR, style)
set_status("mastering", "Applying master effects chain")
effects = plan.get("master_effects", {})
board = Pedalboard([
Compressor(
threshold_db=effects.get("compressor_threshold_db", -14),
ratio=effects.get("compressor_ratio", 3),
),
Reverb(room_size=effects.get("reverb_room_size", 0.15)),
])
mastered = board(mix, TARGET_SR)
peak = np.max(np.abs(mastered)) or 1.0
if peak > 0.98:
mastered = mastered / peak * 0.98
set_status("tagging", "Writing final MP3 and tags")
wav_path = os.path.join(REMIX_TEMP_DIR, f"remix_{job_id}.wav")
sf.write(wav_path, mastered, TARGET_SR)
title_bits = " x ".join(s["title"] for s in songs_info)
candidate = {
"title": f"{plan.get('remix_name', 'Untitled')} ({title_bits})",
"artist": " + ".join(sorted({s['artist'] for s in songs_info})) + " (Stax AI Remix)",
}
from src.services.audio_processing import tag_and_convert_audio
final_local_name = asyncio.run(tag_and_convert_audio(wav_path, candidate))
final_filename = os.path.basename(final_local_name)
download_path = os.path.join(DOWNLOADS_DIR, final_filename)
shutil.move(final_local_name, download_path)
if os.path.exists(wav_path):
os.remove(wav_path)
set_status("tagging", "Registering in library and social feed")
library_song = LibrarySong(
user_id=user_id,
title=candidate["title"],
artist=candidate["artist"],
genre=plan.get("style") if plan.get("style") and plan.get("style") != "none" else None,
file_path=download_path,
)
db.add(library_song)
db.commit()
db.refresh(library_song)
# The schema only supports one parent per post (a tree, not a DAG) - with multiple
# library-sourced inputs, only the first one's most recent post is linked. Sources
# with no existing library entry (fresh uploads) have nothing to link to.
parent_post_id = None
for sid in source_song_ids:
if sid is None:
continue
parent_post = db.query(Post).filter(Post.song_id == sid).order_by(Post.created_at.desc()).first()
if parent_post:
parent_post_id = parent_post.id
break
post = Post(
user_id=user_id,
song_id=library_song.id,
parent_post_id=parent_post_id,
caption=f"{plan.get('remix_name', 'Untitled')} - {prompt}",
)
db.add(post)
db.commit()
db.refresh(post)
job = db.query(RemixJob).filter(RemixJob.id == job_id).first()
job.status = "done"
job.stage_detail = "Complete"
job.result_filename = final_filename
job.result_song_id = library_song.id
job.result_post_id = post.id
db.commit()
except Exception as e:
logger.error(f"Remix job {job_id} failed: {e}")
job = db.query(RemixJob).filter(RemixJob.id == job_id).first()
if job:
job.status = "error"
job.error = str(e)
db.commit()
finally:
db.close()
import time
from collections import deque
from fastapi import WebSocket
MAX_CHAT_HISTORY = 50
FIRE_DECAY_SECONDS = 30 # a "fire meter" reading is how many 🔥 reactions landed in the
# last N seconds, not a lifetime total - it should visibly cool
# off when the room isn't currently popping.
class RoomState:
"""All in-memory, per-room, ephemeral live-session state. None of this is meant to
survive a process restart - it's the equivalent of "who's in the room right now,"
not a historical record. LiveRoom.dj_id/current_song_id in the DB are the durable
parts, updated alongside this."""
def __init__(self):
self.connections: dict[int, WebSocket] = {} # user_id -> websocket
self.chat_history: deque = deque(maxlen=MAX_CHAT_HISTORY)
self.dj_queue: list = [] # user_ids waiting to be handed the aux
self.fire_events: deque = deque() # timestamps of recent fire reactions
def fire_count(self) -> int:
cutoff = time.time() - FIRE_DECAY_SECONDS
while self.fire_events and self.fire_events[0] < cutoff:
self.fire_events.popleft()
return len(self.fire_events)
class RoomConnectionManager:
def __init__(self):
self.rooms: dict[int, RoomState] = {}
def get_room(self, room_id: int) -> RoomState:
if room_id not in self.rooms:
self.rooms[room_id] = RoomState()
return self.rooms[room_id]
async def connect(self, room_id: int, user_id: int, websocket: WebSocket):
await websocket.accept()
self.get_room(room_id).connections[user_id] = websocket
def disconnect(self, room_id: int, user_id: int):
room = self.rooms.get(room_id)
if not room:
return
room.connections.pop(user_id, None)
if user_id in room.dj_queue:
room.dj_queue.remove(user_id)
# An empty room's ephemeral state (chat history, fire meter, queue) is discarded -
# the next person to join starts a fresh session, matching how a live room should
# behave once everyone's left.
if not room.connections:
self.rooms.pop(room_id, None)
async def broadcast(self, room_id: int, message: dict, exclude_user_id: int = None):
room = self.rooms.get(room_id)
if not room:
return
dead = []
for uid, ws in list(room.connections.items()):
if uid == exclude_user_id:
continue
try:
await ws.send_json(message)
except Exception:
dead.append(uid)
for uid in dead:
room.connections.pop(uid, None)
def presence(self, room_id: int) -> list:
room = self.rooms.get(room_id)
return list(room.connections.keys()) if room else []
room_manager = RoomConnectionManager()
......@@ -22,6 +22,11 @@ def test_auth_request_code_upstream_failure_returns_400(client, mocker):
assert response.status_code == 400
def test_auth_request_code_missing_field(client):
response = client.post("/auth/request_code", json={})
assert response.status_code == 422
def test_auth_request_code_rate_limited_per_phone(client, mocker):
mocker.patch(
"src.telegram_worker.telegram_auth.request_code",
......@@ -41,6 +46,7 @@ def test_auth_login_missing_fields(client):
assert response.status_code == 422
def test_auth_login_issues_jwt_and_never_exposes_session_string(client, db_session, mocker):
mocker.patch(
"src.telegram_worker.telegram_auth.login",
......@@ -105,3 +111,17 @@ def test_auth_chats_with_token(client, auth_as, mocker):
response = client.get("/auth/chats", headers=headers)
assert response.status_code == 200
assert response.json()["chats"][0]["title"] == "Test Chat"
def test_auth_chats_music_with_token(client, auth_as, mocker):
headers, _ = auth_as()
mocker.patch(
"src.telegram_worker.telegram_sync.get_chat_music",
return_value=[{"message_id": 1, "title": "Song", "artist": "Someone", "duration": 180, "file_name": "song.mp3"}],
)
response = client.get("/auth/chats/123/music", headers=headers)
assert response.status_code == 200
body = response.json()
assert body["status"] == "success"
assert len(body["music"]) == 1
assert body["music"][0]["title"] == "Song"
import os
import tempfile
from datetime import datetime, timedelta, timezone
from src.core.database import AudioStory, Channel, LibrarySong, Post, SessionLocal
def _make_library_song(**overrides):
fd, path = tempfile.mkstemp(suffix=".mp3", dir="/tmp")
with os.fdopen(fd, "wb") as f:
f.write(b"fake mp3 bytes")
defaults = dict(title="Song", artist="Artist", file_path=path)
defaults.update(overrides)
db = SessionLocal()
try:
song = LibrarySong(**defaults)
db.add(song)
db.commit()
db.refresh(song)
return song.id
finally:
db.close()
def _make_channel(client, owner_id=1, name="Test Channel"):
response = client.post("/channels", json={"owner_id": owner_id, "name": name})
assert response.status_code == 201
return response.json()["id"]
def test_create_and_list_channels(client):
channel_id = _make_channel(client, owner_id=1, name="DJ Test's Channel")
response = client.get("/channels")
assert response.status_code == 200
assert any(c["id"] == channel_id for c in response.json())
def test_get_channel_detail_with_follower_count(client):
channel_id = _make_channel(client)
response = client.get(f"/channels/{channel_id}")
assert response.status_code == 200
body = response.json()
assert body["channel"]["id"] == channel_id
assert body["follower_count"] == 0
client.post(f"/channels/{channel_id}/follow", json={"user_id": 2})
response = client.get(f"/channels/{channel_id}")
assert response.json()["follower_count"] == 1
def test_get_unknown_channel_404s(client):
response = client.get("/channels/999999")
assert response.status_code == 404
def test_follow_is_idempotent(client):
channel_id = _make_channel(client)
r1 = client.post(f"/channels/{channel_id}/follow", json={"user_id": 2})
r2 = client.post(f"/channels/{channel_id}/follow", json={"user_id": 2})
assert r1.status_code == 201
assert r2.status_code == 201
assert r1.json()["id"] == r2.json()["id"]
assert client.get(f"/channels/{channel_id}").json()["follower_count"] == 1
def test_unfollow(client):
channel_id = _make_channel(client)
client.post(f"/channels/{channel_id}/follow", json={"user_id": 2})
assert client.get(f"/channels/{channel_id}").json()["follower_count"] == 1
response = client.post(f"/channels/{channel_id}/unfollow", json={"user_id": 2})
assert response.status_code == 200
assert client.get(f"/channels/{channel_id}").json()["follower_count"] == 0
def test_create_vibe_set_with_tracks_owner_only(client):
channel_id = _make_channel(client, owner_id=1)
song_id = _make_library_song(title="Vibe Track")
forbidden = client.post(
f"/channels/{channel_id}/vibe-sets",
json={"user_id": 999, "title": "Not mine", "song_ids": [song_id]},
)
assert forbidden.status_code == 403
response = client.post(
f"/channels/{channel_id}/vibe-sets",
json={"user_id": 1, "title": "Sunday Chill", "song_ids": [song_id]},
)
assert response.status_code == 201
vibe_set_id = response.json()["id"]
detail = client.get(f"/channels/vibe-sets/{vibe_set_id}")
assert detail.status_code == 200
body = detail.json()
assert body["vibe_set"]["title"] == "Sunday Chill"
assert len(body["tracks"]) == 1
assert body["tracks"][0]["song_id"] == song_id
listing = client.get(f"/channels/{channel_id}/vibe-sets")
assert listing.status_code == 200
assert any(v["id"] == vibe_set_id for v in listing.json())
def test_vibe_set_route_ordering_not_swallowed_by_channel_id(client):
# /channels/vibe-sets/{id} must not be intercepted by the /{channel_id} catch-all
channel_id = _make_channel(client)
response = client.post(
f"/channels/{channel_id}/vibe-sets", json={"user_id": 1, "title": "x", "song_ids": []}
)
vibe_set_id = response.json()["id"]
detail = client.get(f"/channels/vibe-sets/{vibe_set_id}")
assert detail.status_code == 200
assert detail.json()["vibe_set"]["id"] == vibe_set_id
def test_unknown_vibe_set_404s(client):
response = client.get("/channels/vibe-sets/999999")
assert response.status_code == 404
def test_create_story_owner_only_and_expiry(client):
channel_id = _make_channel(client, owner_id=1)
song_id = _make_library_song(title="Story Clip")
forbidden = client.post(f"/channels/{channel_id}/stories", json={"user_id": 999, "song_id": song_id})
assert forbidden.status_code == 403
response = client.post(f"/channels/{channel_id}/stories", json={"user_id": 1, "song_id": song_id, "caption": "vibes"})
assert response.status_code == 201
story_id = response.json()["id"]
active = client.get(f"/channels/{channel_id}/stories")
assert active.status_code == 200
assert any(s["id"] == story_id for s in active.json())
def test_expired_stories_are_filtered_from_active_listing(client):
channel_id = _make_channel(client, owner_id=1)
song_id = _make_library_song(title="Old Clip")
db = SessionLocal()
try:
expired = AudioStory(
channel_id=channel_id, song_id=song_id, caption="old",
expires_at=datetime.now(timezone.utc) - timedelta(hours=1),
)
db.add(expired)
db.commit()
expired_id = expired.id
finally:
db.close()
active = client.get(f"/channels/{channel_id}/stories")
assert active.status_code == 200
assert not any(s["id"] == expired_id for s in active.json())
def test_showcase_owner_only(client, auth_as):
headers, user = auth_as()
channel_id = _make_channel(client, owner_id=user.id)
song_id = _make_library_song(title="Showcased")
post_response = client.post("/social/posts", json={"song_id": song_id, "caption": "check it"}, headers=headers)
post_id = post_response.json()["id"]
forbidden = client.post(f"/channels/{channel_id}/showcase", json={"user_id": 999, "post_id": post_id})
assert forbidden.status_code == 403
response = client.post(f"/channels/{channel_id}/showcase", json={"user_id": user.id, "post_id": post_id})
assert response.status_code == 201
listing = client.get(f"/channels/{channel_id}/showcase")
assert listing.status_code == 200
assert any(s["post_id"] == post_id for s in listing.json())
from src.core.database import Correction, SessionLocal, init_db, log_correction
def test_init_db_is_idempotent():
# Should not raise even when tables already exist (called at import time too)
init_db()
init_db()
def test_log_correction_persists_a_row():
log_correction(user_id=42, title="Test Song", artist="Test Artist", source="Manual Entry")
db = SessionLocal()
try:
row = (
db.query(Correction)
.filter(Correction.user_id == 42, Correction.title == "Test Song")
.order_by(Correction.id.desc())
.first()
)
assert row is not None
assert row.artist == "Test Artist"
assert row.source == "Manual Entry"
finally:
db.close()
import io
from src.api.routers import discovery as discovery_router
from src.core.database import DiscoveredSong
......@@ -41,3 +44,56 @@ def test_discovery_swipe_other_users_song_not_found(client, db_session, auth_as)
response = client.post(f"/discovery/{song.id}/swipe", data={"liked": True}, headers=headers_b)
assert response.status_code == 404
def _dummy_audio_file():
return ("clip.mp3", io.BytesIO(b"not-real-audio-bytes-but-thats-fine-for-this-mock"), "audio/mpeg")
def test_discovery_listen_success_creates_row(client, db_session, auth_as, monkeypatch):
headers, user = auth_as()
async def _fake_identify_hit(path):
return [{"title": "Dummy Song", "artist": "Dummy Artist", "genre": "Pop", "coverart": "http://example.com/art.jpg"}]
monkeypatch.setattr(discovery_router, "identify_audio", _fake_identify_hit)
response = client.post("/discovery/listen", headers=headers, files={"file": _dummy_audio_file()})
assert response.status_code == 200
body = response.json()
assert body["status"] == "success"
assert body["detected"]["title"] == "Dummy Song"
row = db_session.query(DiscoveredSong).filter(DiscoveredSong.id == body["discovery_id"]).first()
assert row is not None
assert row.user_id == user.id
assert row.title == "Dummy Song"
assert row.artist == "Dummy Artist"
def test_discovery_listen_no_match(client, auth_as, monkeypatch):
headers, _ = auth_as()
async def _fake_identify_miss(path):
return []
monkeypatch.setattr(discovery_router, "identify_audio", _fake_identify_miss)
response = client.post("/discovery/listen", headers=headers, files={"file": _dummy_audio_file()})
assert response.status_code == 200
body = response.json()
assert body["status"] == "error"
assert "message" in body
def test_discovery_swipe_success_updates_liked(client, db_session, auth_as):
headers, user = auth_as()
song = DiscoveredSong(user_id=user.id, title="Swipe Me", artist="Someone", genre="Rock")
db_session.add(song)
db_session.commit()
db_session.refresh(song)
response = client.post(f"/discovery/{song.id}/swipe", data={"liked": True}, headers=headers)
assert response.status_code == 200
assert response.json()["status"] == "success"
db_session.refresh(song)
assert song.liked is True
from src.core.config import DOCS_PASSWORD, DOCS_USERNAME
def test_docs_redirects_to_login_when_unauthenticated(client):
response = client.get("/docs", follow_redirects=False)
assert response.status_code in (302, 307)
assert response.headers["location"] == "/login"
def test_login_page_renders(client):
response = client.get("/login")
assert response.status_code == 200
assert "Sign in to view the API console" in response.text
def test_login_wrong_credentials_redirects_with_error(client):
response = client.post(
"/login", data={"username": "wrong", "password": "wrong"}, follow_redirects=False
)
assert response.status_code == 303
assert response.headers["location"] == "/login?error=1"
assert "stax_docs_session" not in response.cookies
def test_login_correct_credentials_sets_session_and_unlocks_docs(client):
response = client.post(
"/login",
data={"username": DOCS_USERNAME, "password": DOCS_PASSWORD},
follow_redirects=False,
)
assert response.status_code == 303
assert response.headers["location"] == "/docs"
assert "stax_docs_session" in response.cookies
docs_response = client.get("/docs")
assert docs_response.status_code == 200
assert "Stax API Console" in docs_response.text
openapi_response = client.get("/openapi.json")
assert openapi_response.status_code == 200
def test_basic_auth_fallback_still_works(client):
response = client.get("/openapi.json", auth=(DOCS_USERNAME, DOCS_PASSWORD))
assert response.status_code == 200
def test_logout_clears_session(client):
login_response = client.post(
"/login",
data={"username": DOCS_USERNAME, "password": DOCS_PASSWORD},
follow_redirects=False,
)
assert "stax_docs_session" in login_response.cookies
logout_response = client.get("/logout", follow_redirects=False)
assert logout_response.status_code in (302, 307)
docs_response = client.get("/docs", follow_redirects=False)
assert docs_response.status_code in (302, 307)
assert docs_response.headers["location"] == "/login"
from src.core.database import LibrarySong
import os
import tempfile
from src.core.database import LibrarySong, PlaylistTrack
def _add_song(db_session, user_id, title="Test Song", artist="Test Artist"):
......@@ -9,6 +12,21 @@ def _add_song(db_session, user_id, title="Test Song", artist="Test Artist"):
return song
def _make_library_song(db_session, user_id, **overrides):
fd, path = tempfile.mkstemp(suffix=".mp3", dir="/tmp")
with os.fdopen(fd, "wb") as f:
f.write(b"fake mp3 bytes for stream test")
defaults = dict(user_id=user_id, title="Test Song", artist="Test Artist", album="Test Album", genre="Pop", lyrics="la la la", file_path=path)
defaults.update(overrides)
song = LibrarySong(**defaults)
db_session.add(song)
db_session.commit()
db_session.refresh(song)
return song, path
def test_library_requires_auth(client):
response = client.get("/library")
assert response.status_code == 401
......@@ -41,6 +59,30 @@ def test_library_search_scoped(client, db_session, auth_as):
assert len(response.json()["results"]) == 1
def test_library_search_finds_match(client, db_session, auth_as):
headers, user = auth_as()
song, path = _make_library_song(db_session, user.id, title="Unique Searchable Title Xyzzy")
try:
response = client.post("/library/search", data={"query": "Xyzzy"}, headers=headers)
assert response.status_code == 200
results = response.json()["results"]
assert any(r["id"] == song.id for r in results)
finally:
os.remove(path)
def test_library_stream_success(client, db_session, auth_as):
headers, user = auth_as()
song, path = _make_library_song(db_session, user.id)
try:
response = client.get(f"/library/stream/{song.id}", headers=headers)
assert response.status_code == 200
assert response.content == b"fake mp3 bytes for stream test"
assert response.headers["content-type"] == "audio/mpeg"
finally:
os.remove(path)
def test_library_stream_not_found_for_other_users_song(client, db_session, auth_as):
headers_a, user_a = auth_as()
headers_b, user_b = auth_as()
......@@ -50,6 +92,40 @@ def test_library_stream_not_found_for_other_users_song(client, db_session, auth_
assert response.status_code == 404
def test_library_stream_unknown_id(client, auth_as):
headers, _ = auth_as()
response = client.get("/library/stream/99999", headers=headers)
assert response.status_code == 404
def test_library_stream_missing_file_on_disk(client, db_session, auth_as):
headers, user = auth_as()
song = LibrarySong(user_id=user.id, title="Ghost Song", artist="Nobody", file_path="/tmp/does_not_exist_xyz.mp3")
db_session.add(song)
db_session.commit()
db_session.refresh(song)
response = client.get(f"/library/stream/{song.id}", headers=headers)
assert response.status_code == 404
def test_library_lyrics_success(client, db_session, auth_as):
headers, user = auth_as()
song, path = _make_library_song(db_session, user.id, lyrics="these are the test lyrics")
try:
response = client.get(f"/library/lyrics/{song.id}", headers=headers)
assert response.status_code == 200
assert response.json()["lyrics"] == "these are the test lyrics"
finally:
os.remove(path)
def test_library_lyrics_unknown_id(client, auth_as):
headers, _ = auth_as()
response = client.get("/library/lyrics/99999", headers=headers)
assert response.status_code == 404
def test_playlists_endpoints(client, auth_as):
headers, _ = auth_as()
response = client.get("/playlists", headers=headers)
......@@ -61,6 +137,7 @@ def test_playlists_endpoints(client, auth_as):
playlist_id = response.json()["playlist"]["id"]
response = client.get("/playlists", headers=headers)
assert response.status_code == 200
playlists = response.json()["playlists"]
assert any(p["id"] == playlist_id for p in playlists)
......@@ -78,3 +155,31 @@ def test_playlist_add_invalid(client, auth_as):
headers, _ = auth_as()
response = client.post("/playlists/99999/add", data={"song_id": 99999}, headers=headers)
assert response.status_code == 404
def test_playlist_add_success(client, db_session, auth_as):
headers, user = auth_as()
song, path = _make_library_song(db_session, user.id)
try:
pl_response = client.post("/playlists", json={"name": "Add Test Playlist"}, headers=headers)
playlist_id = pl_response.json()["playlist"]["id"]
response = client.post(f"/playlists/{playlist_id}/add", data={"song_id": song.id}, headers=headers)
assert response.status_code == 200
assert response.json()["status"] == "success"
track = db_session.query(PlaylistTrack).filter(
PlaylistTrack.playlist_id == playlist_id, PlaylistTrack.song_id == song.id
).first()
assert track is not None
finally:
os.remove(path)
def test_playlist_add_song_not_found(client, auth_as):
headers, _ = auth_as()
pl_response = client.post("/playlists", json={"name": "Another Playlist"}, headers=headers)
playlist_id = pl_response.json()["playlist"]["id"]
response = client.post(f"/playlists/{playlist_id}/add", data={"song_id": 99999}, headers=headers)
assert response.status_code == 404
import io
import os
import tempfile
from src.api.routers import remix as remix_router
from src.core.database import LibrarySong, SessionLocal
def _wav_bytes():
# A tiny valid WAV file is enough - the engine itself is mocked out below,
# these tests only exercise the API contract (validation, job bookkeeping).
import struct
sample_rate = 8000
samples = b"\x00\x00" * sample_rate # 1 second of silence, 16-bit mono
data_size = len(samples)
header = struct.pack(
"<4sI4s4sIHHIIHH4sI",
b"RIFF", 36 + data_size, b"WAVE", b"fmt ", 16, 1, 1,
sample_rate, sample_rate * 2, 2, 16, b"data", data_size,
)
return header + samples
def _make_library_song(**overrides):
fd, path = tempfile.mkstemp(suffix=".wav", dir="/tmp")
with os.fdopen(fd, "wb") as f:
f.write(_wav_bytes())
defaults = dict(title="Library Song", artist="Library Artist", file_path=path)
defaults.update(overrides)
db = SessionLocal()
try:
song = LibrarySong(**defaults)
db.add(song)
db.commit()
db.refresh(song)
return song.id, path
finally:
db.close()
def test_remix_requires_at_least_one_file(client):
response = client.post("/remix", data={"prompt": "make it slower"}, files=[])
assert response.status_code == 400
def test_remix_rejects_more_than_five_songs(client, monkeypatch):
monkeypatch.setattr(remix_router, "render_remix_sync", lambda *a, **kw: None)
files = [("files", (f"song{i}.wav", io.BytesIO(_wav_bytes()), "audio/wav")) for i in range(6)]
response = client.post("/remix", data={"prompt": "mashup"}, files=files)
assert response.status_code == 400
def test_remix_does_not_call_identify_audio_before_responding(client, monkeypatch):
# The whole point of the earlier fix: identify_audio (real Shazam/AcoustID network
# calls, ~30s each on a miss) must never run inside the request/response cycle - only
# inside the background job. If someone re-adds it to the endpoint, this call would
# hang/raise instead of the fast, synchronous response below.
captured = {}
def fake_render(job_id, input_paths, prompt, filenames, source_song_ids=None, user_id=None):
captured["job_id"] = job_id
captured["input_paths"] = input_paths
captured["prompt"] = prompt
captured["filenames"] = filenames
captured["source_song_ids"] = source_song_ids
captured["user_id"] = user_id
monkeypatch.setattr(remix_router, "render_remix_sync", fake_render)
assert not hasattr(remix_router, "identify_audio"), (
"identify_audio got imported back into the router - it belongs in the "
"background job (remix_engine.render_remix_sync), not the request handler."
)
files = [
("files", ("song_a.wav", io.BytesIO(_wav_bytes()), "audio/wav")),
("files", ("song_b.wav", io.BytesIO(_wav_bytes()), "audio/wav")),
]
response = client.post("/remix", data={"prompt": "blend the vocals of the first over the beat of the second"}, files=files)
assert response.status_code == 200
body = response.json()
assert body["status"] == "queued"
job_id = body["job_id"]
status_response = client.get(f"/remix/{job_id}")
assert status_response.status_code == 200
assert status_response.json()["job_id"] == job_id
assert captured["job_id"] == job_id
assert len(captured["input_paths"]) == 2
assert captured["filenames"] == ["song_a.wav", "song_b.wav"]
assert captured["source_song_ids"] == [None, None]
assert captured["user_id"] is None
def test_remix_accepts_library_song_ids(client, monkeypatch):
song_id, path = _make_library_song()
try:
captured = {}
def fake_render(job_id, input_paths, prompt, filenames, source_song_ids=None, user_id=None):
captured["input_paths"] = input_paths
captured["filenames"] = filenames
captured["source_song_ids"] = source_song_ids
captured["user_id"] = user_id
monkeypatch.setattr(remix_router, "render_remix_sync", fake_render)
response = client.post(
"/remix",
data={"prompt": "remix this", "library_song_ids": str(song_id), "user_id": "7"},
)
assert response.status_code == 200
assert captured["input_paths"] == [path]
assert captured["filenames"] == ["Library Song"]
assert captured["source_song_ids"] == [song_id]
assert captured["user_id"] == 7
finally:
os.remove(path)
def test_remix_rejects_unknown_library_song_id(client, monkeypatch):
monkeypatch.setattr(remix_router, "render_remix_sync", lambda *a, **kw: None)
response = client.post("/remix", data={"prompt": "remix this", "library_song_ids": "999999"})
assert response.status_code == 400
def test_remix_mixes_library_songs_and_uploads(client, monkeypatch):
song_id, path = _make_library_song(title="From Library")
try:
captured = {}
def fake_render(job_id, input_paths, prompt, filenames, source_song_ids=None, user_id=None):
captured["source_song_ids"] = source_song_ids
captured["filenames"] = filenames
monkeypatch.setattr(remix_router, "render_remix_sync", fake_render)
files = [("files", ("uploaded.wav", io.BytesIO(_wav_bytes()), "audio/wav"))]
response = client.post(
"/remix",
data={"prompt": "mashup", "library_song_ids": str(song_id)},
files=files,
)
assert response.status_code == 200
assert captured["source_song_ids"] == [song_id, None]
assert captured["filenames"] == ["From Library", "uploaded.wav"]
finally:
os.remove(path)
def test_remix_status_surfaces_library_and_post_ids_when_done(client, monkeypatch):
from src.core.database import RemixJob, SessionLocal as SL
def fake_render(job_id, input_paths, prompt, filenames, source_song_ids=None, user_id=None):
db = SL()
try:
job = db.query(RemixJob).filter(RemixJob.id == job_id).first()
job.status = "done"
job.result_filename = "fake.mp3"
job.result_song_id = 123
job.result_post_id = 456
db.commit()
finally:
db.close()
monkeypatch.setattr(remix_router, "render_remix_sync", fake_render)
files = [("files", ("song.wav", io.BytesIO(_wav_bytes()), "audio/wav"))]
response = client.post("/remix", data={"prompt": "test"}, files=files)
job_id = response.json()["job_id"]
status_response = client.get(f"/remix/{job_id}")
body = status_response.json()
assert body["status"] == "done"
assert body["library_song_id"] == 123
assert body["post_id"] == 456
def test_remix_status_404_for_unknown_job(client):
response = client.get("/remix/999999")
assert response.status_code == 404
import os
import numpy as np
from src.services.remix_engine import (
_coerce_gain_db,
_pad_add,
_semitone_shift_to_key,
_sidechain_gain_envelope,
_tile_to_length,
detect_key,
)
def test_coerce_gain_db_passes_through_numbers():
assert _coerce_gain_db(-3.0) == -3.0
assert _coerce_gain_db(0) == 0.0
def test_coerce_gain_db_averages_per_stem_dict():
# Observed live from Gemini: a per-stem breakdown instead of the single float the
# schema asks for, when a song_role lists multiple stems.
assert _coerce_gain_db({"drums": -6.0, "other": 0.0}) == -3.0
def test_coerce_gain_db_falls_back_to_zero_for_junk():
assert _coerce_gain_db(None) == 0.0
assert _coerce_gain_db("loud") == 0.0
assert _coerce_gain_db({}) == 0.0
def test_semitone_shift_same_key_is_zero():
assert _semitone_shift_to_key(3, 3) == 0
def test_semitone_shift_picks_smallest_magnitude_direction():
# C (0) -> F# (6): exactly 6 either way, must be within [-6, 6]
shift = _semitone_shift_to_key(0, 6)
assert shift in (-6, 6)
# C (0) -> C# (1): +1 is closer than -11
assert _semitone_shift_to_key(0, 1) == 1
# C (0) -> B (11): -1 is closer than +11
assert _semitone_shift_to_key(0, 11) == -1
def test_semitone_shift_always_in_range():
for a in range(12):
for b in range(12):
shift = _semitone_shift_to_key(a, b)
assert -6 <= shift <= 6
assert (a + shift) % 12 == b
FIXTURES_DIR = os.path.join(os.path.dirname(__file__), "fixtures")
def test_detect_key_returns_valid_structure():
key = detect_key(os.path.join(FIXTURES_DIR, "tone.wav"))
assert 0 <= key["tonic"] <= 11
assert key["mode"] in ("major", "minor")
assert key["name"] == f"{['C','C#','D','D#','E','F','F#','G','G#','A','A#','B'][key['tonic']]} {key['mode']}"
def test_sidechain_envelope_ducks_loud_regions_more():
sr = 8000
silence = np.zeros(sr, dtype=np.float32)
loud = np.ones(sr, dtype=np.float32)
source = np.concatenate([silence, loud])
envelope = _sidechain_gain_envelope(source, sr, amount=0.8)
assert envelope.shape == source.shape
assert envelope.min() >= 0.2 - 1e-6 # amount=0.8 -> floor of 1-0.8=0.2
assert envelope.max() <= 1.0
# the loud region should be ducked more (lower gain) than the silent region
assert envelope[:sr].mean() > envelope[sr:].mean()
def test_pad_add_matches_longer_length():
a = np.array([1.0, 2.0, 3.0], dtype=np.float32)
b = np.array([10.0, 20.0], dtype=np.float32)
result = _pad_add(a, b)
assert len(result) == 3
assert np.allclose(result, [11.0, 22.0, 3.0])
def test_tile_to_length_extends_short_audio():
audio = np.array([1.0, 2.0], dtype=np.float32)
result = _tile_to_length(audio, 5)
assert len(result) == 5
assert np.allclose(result, [1.0, 2.0, 1.0, 2.0, 1.0])
def test_tile_to_length_truncates_long_audio():
audio = np.array([1.0, 2.0, 3.0, 4.0], dtype=np.float32)
result = _tile_to_length(audio, 2)
assert np.allclose(result, [1.0, 2.0])
def test_tile_to_length_handles_empty_audio():
result = _tile_to_length(np.array([], dtype=np.float32), 4)
assert len(result) == 4
assert np.allclose(result, 0)
from src.core.database import LiveRoom, SessionLocal
def _make_room(dj_id=1, name="Test Room"):
db = SessionLocal()
try:
room = LiveRoom(dj_id=dj_id, name=name, is_active=True)
db.add(room)
db.commit()
db.refresh(room)
return room.id
finally:
db.close()
def test_websocket_closes_for_unknown_room(client):
from starlette.websockets import WebSocketDisconnect
import pytest
with pytest.raises(WebSocketDisconnect):
with client.websocket_connect("/social/rooms/999999/ws?user_id=1"):
pass
def test_websocket_snapshot_on_connect(client):
room_id = _make_room(dj_id=1)
with client.websocket_connect(f"/social/rooms/{room_id}/ws?user_id=1") as ws:
snapshot = ws.receive_json()
assert snapshot["type"] == "snapshot"
assert snapshot["dj_id"] == 1
assert snapshot["presence"] == [1]
assert snapshot["chat_history"] == []
assert snapshot["fire_count"] == 0
assert snapshot["dj_queue"] == []
def test_websocket_broadcasts_chat_between_clients(client):
room_id = _make_room(dj_id=1)
with client.websocket_connect(f"/social/rooms/{room_id}/ws?user_id=1") as ws1:
ws1.receive_json() # snapshot
with client.websocket_connect(f"/social/rooms/{room_id}/ws?user_id=2") as ws2:
ws2.receive_json() # snapshot
joined = ws1.receive_json()
assert joined == {"type": "user_joined", "user_id": 2}
ws2.send_json({"type": "chat", "text": "hey everyone"})
chat_on_ws1 = ws1.receive_json()
assert chat_on_ws1 == {"type": "chat", "user_id": 2, "text": "hey everyone"}
# Broadcasts (chat/reactions) intentionally include the sender too - simpler,
# more predictable than an asymmetric "everyone except me" rule, and clients
# can always ignore/dedupe their own user_id if they update optimistically.
# This bit a manual live-server test script during development (it assumed
# sender exclusion and read messages out of order) - locking it in explicitly.
chat_echoed_to_sender = ws2.receive_json()
assert chat_echoed_to_sender == {"type": "chat", "user_id": 2, "text": "hey everyone"}
def test_websocket_reaction_increments_fire_count(client):
room_id = _make_room(dj_id=1)
with client.websocket_connect(f"/social/rooms/{room_id}/ws?user_id=1") as ws:
ws.receive_json() # snapshot
ws.send_json({"type": "reaction", "emoji": "🔥"})
reaction = ws.receive_json()
assert reaction["type"] == "reaction"
assert reaction["emoji"] == "🔥"
assert reaction["fire_count"] == 1
def test_websocket_dj_handoff_flow(client):
room_id = _make_room(dj_id=1)
with client.websocket_connect(f"/social/rooms/{room_id}/ws?user_id=1") as dj_ws:
dj_ws.receive_json() # snapshot
with client.websocket_connect(f"/social/rooms/{room_id}/ws?user_id=2") as listener_ws:
listener_ws.receive_json() # snapshot
dj_ws.receive_json() # user_joined for user 2
listener_ws.send_json({"type": "request_aux"})
queue_update_on_listener = listener_ws.receive_json()
queue_update_on_dj = dj_ws.receive_json()
assert queue_update_on_listener == {"type": "queue_updated", "dj_queue": [2]}
assert queue_update_on_dj == {"type": "queue_updated", "dj_queue": [2]}
dj_ws.send_json({"type": "pass_aux"})
dj_changed_on_dj = dj_ws.receive_json()
dj_changed_on_listener = listener_ws.receive_json()
assert dj_changed_on_dj == {"type": "dj_changed", "dj_id": 2, "dj_queue": []}
assert dj_changed_on_listener == {"type": "dj_changed", "dj_id": 2, "dj_queue": []}
db = SessionLocal()
try:
room = db.query(LiveRoom).filter(LiveRoom.id == room_id).first()
assert room.dj_id == 2
finally:
db.close()
def test_websocket_only_dj_can_pass_aux(client):
room_id = _make_room(dj_id=1)
with client.websocket_connect(f"/social/rooms/{room_id}/ws?user_id=2") as ws:
ws.receive_json() # snapshot
ws.send_json({"type": "pass_aux"})
error = ws.receive_json()
assert error == {"type": "error", "detail": "Only the current DJ can pass the aux."}
def test_websocket_only_dj_can_set_now_playing(client):
room_id = _make_room(dj_id=1)
with client.websocket_connect(f"/social/rooms/{room_id}/ws?user_id=1") as dj_ws:
dj_ws.receive_json() # snapshot
dj_ws.send_json({"type": "now_playing", "song_id": 42})
update = dj_ws.receive_json()
assert update == {"type": "now_playing_changed", "song_id": 42, "dj_id": 1}
db = SessionLocal()
try:
room = db.query(LiveRoom).filter(LiveRoom.id == room_id).first()
assert room.current_song_id == 42
finally:
db.close()
def test_websocket_user_left_broadcast_on_disconnect(client):
room_id = _make_room(dj_id=1)
with client.websocket_connect(f"/social/rooms/{room_id}/ws?user_id=1") as ws1:
ws1.receive_json() # snapshot
with client.websocket_connect(f"/social/rooms/{room_id}/ws?user_id=2") as ws2:
ws2.receive_json() # snapshot
ws1.receive_json() # user_joined
left = ws1.receive_json()
assert left == {"type": "user_left", "user_id": 2}
......@@ -68,3 +68,58 @@ def test_get_active_rooms(client, auth_as):
response = client.get("/social/rooms", headers=headers)
assert response.status_code == 200
assert isinstance(response.json(), list)
def test_remix_tree_not_found(client, auth_as):
headers, _ = auth_as()
response = client.get("/social/posts/999999/tree", headers=headers)
assert response.status_code == 404
def test_remix_tree_with_children(client, auth_as):
headers, _ = auth_as()
root_res = client.post("/social/posts", json={"song_id": 1, "caption": "root post"}, headers=headers)
root_id = root_res.json()["id"]
child_res = client.post("/social/posts", json={
"song_id": 1, "parent_post_id": root_id, "caption": "a remix of the root"
}, headers=headers)
assert child_res.status_code == 201
response = client.get(f"/social/posts/{root_id}/tree", headers=headers)
assert response.status_code == 200
body = response.json()
assert body["post"]["id"] == root_id
assert len(body["children"]) == 1
assert body["children"][0]["post"]["id"] == child_res.json()["id"]
def test_remix_tree_is_recursive_across_multiple_generations(client, auth_as):
headers, _ = auth_as()
root_id = client.post("/social/posts", json={"song_id": 1, "caption": "gen 0"}, headers=headers).json()["id"]
child_id = client.post("/social/posts", json={
"song_id": 1, "parent_post_id": root_id, "caption": "gen 1",
}, headers=headers).json()["id"]
grandchild_id = client.post("/social/posts", json={
"song_id": 1, "parent_post_id": child_id, "caption": "gen 2",
}, headers=headers).json()["id"]
response = client.get(f"/social/posts/{root_id}/tree", headers=headers)
assert response.status_code == 200
body = response.json()
assert body["post"]["id"] == root_id
assert len(body["children"]) == 1
child_node = body["children"][0]
assert child_node["post"]["id"] == child_id
assert len(child_node["children"]) == 1
grandchild_node = child_node["children"][0]
assert grandchild_node["post"]["id"] == grandchild_id
assert grandchild_node["children"] == []
def test_remix_tree_leaf_node_has_no_children(client, auth_as):
headers, _ = auth_as()
leaf_id = client.post("/social/posts", json={"song_id": 1, "caption": "no remixes yet"}, headers=headers).json()["id"]
response = client.get(f"/social/posts/{leaf_id}/tree", headers=headers)
assert response.json()["children"] == []
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