Commit c676e123 authored by Aryan Noshirvani's avatar Aryan Noshirvani

Initial commit: Stax Backend API

parents
Pipeline #959 canceled with stages
TELEGRAM_BOT_TOKEN=8604213025:AAFjp9xHC7FxYPwOCuIjt4KfJxWbpUfZyCY
ACOUSTID_API_KEY=8UmfE5vPes
GEMINI_API_KEY=AQ.Ab8RN6KYy9dbD5eT17JdnU7BHrdrMViDPH5lvGqplBZNhZSjnw
TELEGRAM_BOT_TOKEN=your_telegram_bot_token_here
# Stax Audio Beta API
Welcome to the backend repository for the Stax Audio Beta application. This API provides the core infrastructure for an advanced music streaming, discovery, and AI-remixing service integrated with Telegram.
## Overview
Stax Audio offers users a rich music experience by leveraging their existing Telegram chats. Key features include:
- **Music Recognition:** Identify songs using Shazam/AcoustID and fallback to Gemini.
- **Telegram Integration:** Authenticate via Telegram and sync music natively shared in individual chats or groups.
- **Library & Playlists:** Add discovered and synced songs to a global library and organize them into custom playlists.
- **Background Discovery:** Continuously log ambient music (kept for 24 hours) allowing users to swipe through tracks they want to keep.
- **AI Batch Remixing:** Select multiple tracks from your chats/library and automatically apply AI-driven audio styles (e.g., slowed, reverb, trap).
## Architecture
The backend consists of two primary services running side-by-side:
1. **FastAPI Web Service (`api.py`)**
- Serves the frontend (mobile/web apps).
- Handles RESTful routing, authentication (`Pyrogram` based), database models (`SQLAlchemy`), and background task delegation.
- Runs via `uvicorn` on port 8000.
2. **Telegram Userbot / Downloader (`bot.py` / `audio_processing.py`)**
- Interacts heavily with the Telegram API to intercept audio messages and download raw files.
- Handles AI-powered audio manipulation (`pydub`) and generates remixes.
## Setup & Configuration
### Prerequisites
- Python 3.10+
- FFmpeg (required for `pydub` and audio conversion)
### Installation
1. Clone the repository and navigate into it.
2. Create and activate a virtual environment:
```bash
python3 -m venv venv
source venv/bin/activate
```
3. Install the dependencies:
```bash
pip install -r requirements.txt
```
### Environment Variables (`.env`)
Create a `.env` file in the root directory. You will need:
- `TELEGRAM_API_ID`: Your Telegram API ID.
- `TELEGRAM_API_HASH`: Your Telegram API Hash.
- `GEMINI_API_KEY`: API key for Gemini fallback operations.
- `DATABASE_URL`: Defaults to `sqlite:///./music.db`.
### Database
The API uses SQLite by default. When the application starts, `SQLAlchemy` will automatically generate the required tables (`LibrarySong`, `Playlist`, `PlaylistTrack`, etc.).
## Running the Application
### Locally (Development)
```bash
uvicorn api:app --host 0.0.0.0 --port 8000 --reload
```
### Production (systemd)
On the production VPS, the services are managed via `systemd`:
```bash
sudo systemctl restart stax_api
sudo systemctl restart stax_bot
```
To view logs:
```bash
sudo journalctl -u stax_api -f
```
## Testing
We use `pytest` alongside `httpx` to validate our endpoints:
```bash
pytest test_api.py
```
This ensures the primary CRUD logic and AI batch queuing remain stable.
## Contributing
We develop on the `dev` branch. Features are merged into `main` once they pass automated testing and manual review.
import asyncio
import json
import os
import shutil
import subprocess
import google.generativeai as genai
from pedalboard import Pedalboard, Reverb, PitchShift, Compressor
from pedalboard.io import AudioFile
from src.core.config import GEMINI_API_KEY, logger
if GEMINI_API_KEY:
genai.configure(api_key=GEMINI_API_KEY)
async def get_remix_recipe(user_prompt: str, original_title: str) -> dict:
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"})
prompt = f"""
Analyze this user request for an audio remix: "{user_prompt}"
The original song title is "{original_title}".
We are using a professional AI Demucs engine. The AI will isolate the vocals from the original song and layer a massive new drum loop over it.
Choose a beat style that best fits the request: "House" (120 BPM, EDM), "Trap" (140 BPM, Hip-Hop), or "LoFi" (85 BPM, chill).
Create a short 1-3 word creative name for this remix (e.g., "Dreamy Trap").
Return a JSON object strictly following this schema:
{{
"remix_name": str (The 1-3 word creative descriptor, do NOT include the word 'remix'),
"beat_style": str (Must be exactly "House", "Trap", or "LoFi"),
"pitch_shift_semitones": int (e.g., -2 for deeper, 2 for higher. Range -12 to 12),
"reverb_room_size": float (e.g., 0.8 for massive hall, 0.0 for none. Range 0.0 to 1.0)
}}
"""
response = await asyncio.to_thread(model.generate_content, prompt)
return json.loads(response.text)
async def detect_bpm(file_path: str) -> float:
try:
cmd = f"sox '{file_path}' -t raw -r 44100 -e float -c 1 - | bpm"
process = await asyncio.create_subprocess_shell(cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
stdout, stderr = await process.communicate()
bpm_str = stdout.decode().strip()
return float(bpm_str) if bpm_str else 120.0
except Exception as e:
logger.error(f"BPM detection failed: {e}")
return 120.0
async def apply_remix(raw_file_path: str, recipe: dict) -> str:
out_path = f"{raw_file_path}_remixed.mp3"
temp_wav_path = f"{raw_file_path}_temp.wav"
beat_path = f"{raw_file_path}_beat.wav"
mixed_path = f"{raw_file_path}_mixed.wav"
beat_style = recipe.get("beat_style", "House").lower()
loop_file = f"assets/loops/{beat_style}.mp3"
if not os.path.exists(loop_file):
loop_file = "assets/loops/house.mp3"
try:
# Convert raw file to WAV using pedalboard because sox fails if there is no file extension
def convert_to_wav():
with AudioFile(raw_file_path) as f:
audio = f.read(f.frames)
samplerate = f.samplerate
with AudioFile(temp_wav_path, 'w', samplerate, audio.shape[0]) as f:
f.write(audio)
await asyncio.to_thread(convert_to_wav)
song_bpm = await detect_bpm(temp_wav_path)
logger.info(f"Detected original BPM: {song_bpm}")
loop_bpm = {"house": 120.0, "trap": 140.0, "lofi": 85.0}.get(beat_style, 120.0)
tempo_ratio = song_bpm / loop_bpm
cmd_len = f"soxi -D '{temp_wav_path}'"
proc = await asyncio.create_subprocess_shell(cmd_len, stdout=asyncio.subprocess.PIPE)
stdout, _ = await proc.communicate()
song_length = float(stdout.decode().strip())
# Tempo stretch loop
cmd_beat = f"sox '{loop_file}' '{beat_path}' repeat 100 tempo -q {tempo_ratio} trim 0 {song_length}"
await asyncio.create_subprocess_shell(cmd_beat)
await asyncio.sleep(2)
# High-pass filter to fake "vocals" and mix with beat
cmd_mix = f"sox -m -v 1.2 '|sox {temp_wav_path} -p highpass 300' -v 1.0 '{beat_path}' '{mixed_path}'"
await asyncio.create_subprocess_shell(cmd_mix)
await asyncio.sleep(2)
def process_final():
with AudioFile(mixed_path) as f:
audio = f.read(f.frames)
samplerate = f.samplerate
board = Pedalboard([
Compressor(threshold_db=-15, ratio=4),
PitchShift(semitones=recipe.get("pitch_shift_semitones", 0)),
Reverb(room_size=recipe.get("reverb_room_size", 0.0))
])
effected = board(audio, samplerate)
with AudioFile(out_path, 'w', samplerate, effected.shape[0]) as f:
f.write(effected)
await asyncio.to_thread(process_final)
except Exception as e:
logger.error(f"Sox AI Remix failed: {e}")
raise e
finally:
for p in [temp_wav_path, beat_path, mixed_path]:
if os.path.exists(p): os.remove(p)
return out_path
import secrets
from fastapi import FastAPI, Depends, HTTPException, status, Request, Form, Response, UploadFile, File
from fastapi.responses import HTMLResponse, RedirectResponse
from fastapi.openapi.docs import get_swagger_ui_html
from fastapi.openapi.utils import get_openapi
from fastapi.security import APIKeyCookie
from pydantic import BaseModel
from typing import List, Optional
cookie_sec = APIKeyCookie(name="session_token", auto_error=False)
def verify_cookie(session_token: str = Depends(cookie_sec)):
if not session_token or session_token != "valid_token_xyz":
raise HTTPException(status_code=401, detail="Not authenticated")
return True
app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None)
@app.get("/", response_class=HTMLResponse, include_in_schema=False)
async def login_get(request: Request):
token = request.cookies.get("session_token")
if token == "valid_token_xyz":
return RedirectResponse(url="/docs", status_code=302)
html_content = """
<!DOCTYPE html>
<html>
<head>
<title>Stax API Login</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; display: flex; justify-content: center; align-items: center; height: 100vh; background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%); margin: 0; }
.login-box { background: white; padding: 40px; border-radius: 12px; box-shadow: 0 8px 24px rgba(0,0,0,0.1); width: 100%; max-width: 320px; text-align: center; }
h2 { margin-top: 0; color: #333; margin-bottom: 24px; font-weight: 600; }
input { width: 100%; padding: 12px; margin: 8px 0 16px 0; border: 1px solid #ddd; border-radius: 6px; box-sizing: border-box; font-size: 15px; transition: border-color 0.3s; }
input:focus { border-color: #007bff; outline: none; }
button { width: 100%; padding: 12px; background: #007bff; color: white; border: none; border-radius: 6px; cursor: pointer; font-size: 16px; font-weight: 600; transition: background 0.3s; }
button:hover { background: #0056b3; }
.error { color: #dc3545; font-size: 14px; margin-bottom: 10px; }
</style>
</head>
<body>
<div class="login-box">
<h2>Stax API Docs</h2>
<form method="post" action="/login">
<input type="text" name="username" placeholder="Username" required autocomplete="username">
<input type="password" name="password" placeholder="Password" required autocomplete="current-password">
<button type="submit">Login to Docs</button>
</form>
</div>
</body>
</html>
"""
return HTMLResponse(content=html_content)
@app.post("/login", include_in_schema=False)
async def login_post(response: Response, username: str = Form(...), password: str = Form(...)):
correct_username = secrets.compare_digest(username, "admin")
correct_password = secrets.compare_digest(password, "stax123")
if correct_username and correct_password:
res = RedirectResponse(url="/docs", status_code=302)
res.set_cookie(key="session_token", value="valid_token_xyz", httponly=True, max_age=86400)
return res
else:
return HTMLResponse("""
<div style="font-family: sans-serif; text-align: center; padding: 50px;">
<h2 style="color: red;">Invalid Credentials</h2>
<a href="/">Try Again</a>
</div>
""", status_code=401)
@app.get("/docs", include_in_schema=False)
async def get_documentation(is_valid: bool = Depends(verify_cookie)):
return get_swagger_ui_html(openapi_url="/openapi.json", title="Stax API Docs")
@app.get("/openapi.json", include_in_schema=False)
async def openapi(is_valid: bool = Depends(verify_cookie)):
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.",
routes=app.routes,
)
openapi_schema["components"]["securitySchemes"] = {
"BearerAuth": {
"type": "http",
"scheme": "bearer",
"bearerFormat": "JWT"
}
}
app.openapi_schema = openapi_schema
return app.openapi_schema
# --- Pydantic Models ---
class TagRequest(BaseModel):
chat_id: int
message_id: int
language_preference: str = "native"
class TagResponse(BaseModel):
status: str
download_url: str
metadata: dict
class FileToRemix(BaseModel):
chat_id: int
message_id: int
class RemixBatchRequest(BaseModel):
files: List[FileToRemix]
prompt: str
# --- Core API Endpoints ---
@app.post("/music/tag", response_model=TagResponse, tags=["Music Processing"])
async def tag_music(req: TagRequest):
return {
"status": "success",
"download_url": "https://api.staxmusic.com/downloads/tagged_track.mp3",
"metadata": {
"title": "Mock Title",
"artist": "Mock Artist",
"album": "Mock Album",
"genre": "Pop"
}
}
@app.post("/music/remix/batch", tags=["Music Processing"])
async def batch_remix(req: RemixBatchRequest):
return {"status": "accepted", "message": "Batch remix job accepted and processing in background."}
@app.post("/music/upload", response_model=TagResponse, tags=["Music Processing"])
async def upload_direct(file: UploadFile = File(...)):
# Note: NGINX has been updated to accept up to 30MB uploads
return {
"status": "success",
"download_url": "https://api.staxmusic.com/downloads/uploaded_tagged.mp3",
"metadata": {
"title": file.filename,
"artist": "Unknown Artist",
"album": "",
"genre": ""
}
}
import secrets
from database import LibrarySong, Playlist, PlaylistTrack
import telegram_auth
class RequestCodeReq(BaseModel):
phone_number: str
class LoginReq(BaseModel):
phone_number: str
phone_code_hash: str
code: str
from fastapi.responses import FileResponse
from pydantic import BaseModel
from typing import List
from database import SessionLocal, DiscoveredSong, get_db
from sqlalchemy.orm import Session
from datetime import datetime, timedelta, timezone
import os
import shutil
import uuid
from fastapi import FastAPI, Depends, HTTPException, status, Request, Form, Response, UploadFile, File
from fastapi.responses import HTMLResponse, RedirectResponse
from fastapi.openapi.docs import get_swagger_ui_html
from fastapi.openapi.utils import get_openapi
from fastapi.security import APIKeyCookie
from fastapi.staticfiles import StaticFiles
from pydantic import BaseModel
from typing import List, Optional
import urllib.parse
from music_identification import identify_with_gemini, identify_audio, fetch_lyrics
from audio_processing import tag_and_convert_audio
import google.generativeai as genai
import asyncio
os.makedirs("/root/antigrav-stax-audio/downloads", exist_ok=True)
os.makedirs("/root/antigrav-stax-audio/temp", exist_ok=True)
cookie_sec = APIKeyCookie(name="session_token", auto_error=False)
def verify_cookie(session_token: str = Depends(cookie_sec)):
if not session_token or session_token != "valid_token_xyz":
raise HTTPException(status_code=401, detail="Not authenticated")
return True
app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None)
app.mount("/downloads", StaticFiles(directory="/root/antigrav-stax-audio/downloads"), name="downloads")
@app.get("/", response_class=HTMLResponse, include_in_schema=False)
async def login_get(request: Request):
token = request.cookies.get("session_token")
if token == "valid_token_xyz":
return RedirectResponse(url="/docs", status_code=302)
html_content = """
<!DOCTYPE html>
<html>
<head>
<title>Stax API Login</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; display: flex; justify-content: center; align-items: center; height: 100vh; background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%); margin: 0; }
.login-box { background: white; padding: 40px; border-radius: 12px; box-shadow: 0 8px 24px rgba(0,0,0,0.1); width: 100%; max-width: 320px; text-align: center; }
h2 { margin-top: 0; color: #333; margin-bottom: 24px; font-weight: 600; }
input { width: 100%; padding: 12px; margin: 8px 0 16px 0; border: 1px solid #ddd; border-radius: 6px; box-sizing: border-box; font-size: 15px; transition: border-color 0.3s; }
input:focus { border-color: #007bff; outline: none; }
button { width: 100%; padding: 12px; background: #007bff; color: white; border: none; border-radius: 6px; cursor: pointer; font-size: 16px; font-weight: 600; transition: background 0.3s; }
button:hover { background: #0056b3; }
.error { color: #dc3545; font-size: 14px; margin-bottom: 10px; }
</style>
</head>
<body>
<div class="login-box">
<h2>Stax API Docs</h2>
<form method="post" action="/login">
<input type="text" name="username" placeholder="Username" required autocomplete="username">
<input type="password" name="password" placeholder="Password" required autocomplete="current-password">
<button type="submit">Login to Docs</button>
</form>
</div>
</body>
</html>
"""
return HTMLResponse(content=html_content)
@app.post("/login", include_in_schema=False)
async def login_post(response: Response, username: str = Form(...), password: str = Form(...)):
correct_username = secrets.compare_digest(username, "admin")
correct_password = secrets.compare_digest(password, "stax123")
if correct_username and correct_password:
res = RedirectResponse(url="/docs", status_code=302)
res.set_cookie(key="session_token", value="valid_token_xyz", httponly=True, max_age=86400)
return res
else:
return HTMLResponse("""
<div style="font-family: sans-serif; text-align: center; padding: 50px;">
<h2 style="color: red;">Invalid Credentials</h2>
<a href="/">Try Again</a>
</div>
""", status_code=401)
@app.get("/docs", include_in_schema=False)
async def get_documentation(is_valid: bool = Depends(verify_cookie)):
return get_swagger_ui_html(openapi_url="/openapi.json", title="Stax API Docs")
@app.get("/openapi.json", include_in_schema=False)
async def openapi(is_valid: bool = Depends(verify_cookie)):
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.",
routes=app.routes,
)
openapi_schema["components"]["securitySchemes"] = {
"BearerAuth": {
"type": "http",
"scheme": "bearer",
"bearerFormat": "JWT"
}
}
app.openapi_schema = openapi_schema
return app.openapi_schema
# --- Pydantic Models ---
class TagRequest(BaseModel):
chat_id: int
message_id: int
language_preference: str = "native"
class TagResponse(BaseModel):
status: str
download_url: str
metadata: dict
class FileToRemix(BaseModel):
chat_id: int
message_id: int
class RemixBatchRequest(BaseModel):
files: List[FileToRemix]
prompt: str
# --- Core API Endpoints ---
@app.post("/music/tag", response_model=TagResponse, tags=["Music Processing"])
async def tag_music(req: TagRequest):
return {
"status": "success",
"download_url": "https://api.staxmusic.com/downloads/tagged_track.mp3",
"metadata": {
"title": "Mock Title",
"artist": "Mock Artist",
"album": "Mock Album",
"genre": "Pop"
}
}
@app.post("/music/remix/batch", tags=["Music Processing"])
async def batch_remix(req: RemixBatchRequest):
return {"status": "accepted", "message": "Batch remix job accepted and processing in background."}
@app.post("/music/upload", response_model=TagResponse, tags=["Music Processing"])
async def upload_direct(file: UploadFile = File(...)):
temp_filename = f"/root/antigrav-stax-audio/temp/{uuid.uuid4()}_{file.filename}"
with open(temp_filename, "wb") as buffer:
shutil.copyfileobj(file.file, buffer)
try:
from pydub import AudioSegment
mp3_filename = f"{temp_filename}.mp3"
audio = AudioSegment.from_file(temp_filename)
audio.export(mp3_filename, format="mp3", bitrate="192k")
if os.path.exists(temp_filename):
os.remove(temp_filename)
candidates = await identify_audio(mp3_filename)
candidate = candidates[0] if candidates else None
if not candidate:
gemini_result = await identify_with_gemini(mp3_filename, "native")
candidate = gemini_result if gemini_result else {}
if not candidate.get("lyrics"):
lyrics = await fetch_lyrics(candidate.get("title", ""), candidate.get("artist", ""))
candidate["lyrics"] = lyrics
if not candidate.get("genre") or candidate.get("genre") == "Unknown Genre":
title = candidate.get("title", "")
artist = candidate.get("artist", "")
if title and artist and title != "Unknown" and artist != "Unknown":
try:
model = genai.GenerativeModel('gemini-2.5-flash')
prompt = f"What is the genre of the song '{title}' by '{artist}'? Reply with ONLY a single genre name (e.g. Pop, Synth-pop, Classical). Do not include any other text."
response = await asyncio.to_thread(model.generate_content, prompt)
raw_text = response.text.strip()
if "\n" in raw_text:
candidate["genre"] = [line.strip() for line in raw_text.split("\n") if line.strip()][-1]
else:
candidate["genre"] = raw_text
except:
candidate["genre"] = "Unknown Genre"
final_filename = await tag_and_convert_audio(temp_filename, candidate)
# move to downloads directory
download_path = f"/root/antigrav-stax-audio/downloads/{final_filename}"
shutil.move(final_filename, download_path)
if os.path.exists(temp_filename):
os.remove(temp_filename)
quoted_filename = urllib.parse.quote(final_filename)
return {
"status": "success",
"download_url": f"http://216.126.237.62/downloads/{quoted_filename}",
"metadata": {
"title": candidate.get('title', 'Unknown'),
"artist": candidate.get('artist', 'Unknown'),
"album": candidate.get('album', ''),
"genre": candidate.get('genre', ''),
"year": candidate.get('year', ''),
"has_lyrics": bool(candidate.get('lyrics'))
}
}
except Exception as e:
if os.path.exists(temp_filename):
os.remove(temp_filename)
if 'mp3_filename' in locals() and os.path.exists(mp3_filename):
os.remove(mp3_filename)
raise HTTPException(status_code=500, detail=str(e))
@app.post("/discovery/listen")
async def discovery_listen(file: UploadFile = File(...), db: Session = Depends(get_db)):
"""Accepts a short audio snippet from the microphone to identify what's playing."""
temp_filename = f"/root/antigrav-stax-audio/temp/{file.filename}"
with open(temp_filename, "wb") as buffer:
shutil.copyfileobj(file.file, buffer)
candidates = await identify_audio(temp_filename)
if not candidates:
os.remove(temp_filename)
return {"status": "error", "message": "No music detected"}
candidate = candidates[0]
new_song = DiscoveredSong(
title=candidate.get("title"),
artist=candidate.get("artist"),
genre=candidate.get("genre"),
coverart=candidate.get("coverart")
)
db.add(new_song)
db.commit()
db.refresh(new_song)
os.remove(temp_filename)
return {"status": "success", "detected": candidate, "discovery_id": new_song.id}
@app.get("/discovery/history")
async def discovery_history(db: Session = Depends(get_db)):
"""Returns the background listening history for the past 24 hours."""
time_24h_ago = datetime.now(timezone.utc) - timedelta(hours=24)
songs = db.query(DiscoveredSong).filter(DiscoveredSong.detected_at >= time_24h_ago).order_by(DiscoveredSong.detected_at.desc()).all()
return {"status": "success", "history": songs}
@app.post("/discovery/{song_id}/swipe")
async def discovery_swipe(song_id: int, liked: bool = Form(...), db: Session = Depends(get_db)):
"""Swipe right (liked=true) or left (liked=false) on a discovered song."""
song = db.query(DiscoveredSong).filter(DiscoveredSong.id == song_id).first()
if not song:
raise HTTPException(status_code=404, detail="Song not found")
song.liked = liked
db.commit()
return {"status": "success", "message": "Preference saved"}
class PlaylistCreate(BaseModel):
name: str
@app.get("/library")
async def get_library(db: Session = Depends(get_db)):
songs = db.query(LibrarySong).order_by(LibrarySong.added_at.desc()).all()
return {"status": "success", "library": songs}
@app.get("/library/stream/{file_id}")
async def stream_audio(file_id: int, db: Session = Depends(get_db)):
song = db.query(LibrarySong).filter(LibrarySong.id == file_id).first()
if not song or not song.file_path or not os.path.exists(song.file_path):
raise HTTPException(status_code=404, detail="Audio file not found")
return FileResponse(song.file_path, media_type="audio/mpeg")
@app.get("/library/lyrics/{file_id}")
async def get_lyrics(file_id: int, db: Session = Depends(get_db)):
song = db.query(LibrarySong).filter(LibrarySong.id == file_id).first()
if not song:
raise HTTPException(status_code=404, detail="Song not found")
return {"status": "success", "lyrics": song.lyrics}
@app.post("/library/search")
async def search_library(query: str = Form(...), db: Session = Depends(get_db)):
q = f"%{query}%"
songs = db.query(LibrarySong).filter(
(LibrarySong.title.ilike(q)) |
(LibrarySong.artist.ilike(q)) |
(LibrarySong.genre.ilike(q))
).all()
return {"status": "success", "results": songs}
@app.get("/playlists")
async def get_playlists(db: Session = Depends(get_db)):
playlists = db.query(Playlist).order_by(Playlist.created_at.desc()).all()
return {"status": "success", "playlists": playlists}
@app.post("/playlists")
async def create_playlist(data: PlaylistCreate, db: Session = Depends(get_db)):
new_pl = Playlist(name=data.name)
db.add(new_pl)
db.commit()
db.refresh(new_pl)
return {"status": "success", "playlist": new_pl}
@app.post("/playlists/{playlist_id}/add")
async def add_to_playlist(playlist_id: int, song_id: int = Form(...), db: Session = Depends(get_db)):
pl = db.query(Playlist).filter(Playlist.id == playlist_id).first()
if not pl:
raise HTTPException(status_code=404, detail="Playlist not found")
song = db.query(LibrarySong).filter(LibrarySong.id == song_id).first()
if not song:
raise HTTPException(status_code=404, detail="Song not found")
# Get max order
max_order = db.query(PlaylistTrack).filter(PlaylistTrack.playlist_id == playlist_id).count()
pt = PlaylistTrack(playlist_id=playlist_id, song_id=song_id, order=max_order)
db.add(pt)
db.commit()
return {"status": "success", "message": "Added to playlist"}
@app.post("/auth/request_code")
async def auth_request_code(req: RequestCodeReq):
try:
res = await telegram_auth.request_code(req.phone_number)
return {"status": "success", "data": res}
except Exception as e:
raise HTTPException(status_code=400, detail=str(e))
@app.post("/auth/login")
async def auth_login(req: LoginReq, db: Session = Depends(get_db)):
try:
res = await telegram_auth.login(req.phone_number, req.phone_code_hash, req.code)
# Save or update user in our DB
user = db.query(User).filter(User.id == res["user_id"]).first()
if not user:
user = User(id=res["user_id"], username=req.phone_number)
db.add(user)
db.commit()
return {"status": "success", "access_token": res["session_string"], "user_id": res["user_id"]}
except Exception as e:
raise HTTPException(status_code=400, detail=str(e))
import secrets
from database import LibrarySong, Playlist, PlaylistTrack
import telegram_auth
import telegram_sync
class RequestCodeReq(BaseModel):
phone_number: str
class LoginReq(BaseModel):
phone_number: str
phone_code_hash: str
code: str
from fastapi.responses import FileResponse
from pydantic import BaseModel
from typing import List
from database import SessionLocal, DiscoveredSong, get_db
from sqlalchemy.orm import Session
from datetime import datetime, timedelta, timezone
import os
import shutil
import uuid
from fastapi import FastAPI, Depends, HTTPException, status, Request, Form, Response, UploadFile, File
from fastapi.responses import HTMLResponse, RedirectResponse
from fastapi.openapi.docs import get_swagger_ui_html
from fastapi.openapi.utils import get_openapi
from fastapi.security import APIKeyCookie
from fastapi.staticfiles import StaticFiles
from pydantic import BaseModel
from typing import List, Optional
import urllib.parse
from music_identification import identify_with_gemini, identify_audio, fetch_lyrics
from audio_processing import tag_and_convert_audio
import google.generativeai as genai
import asyncio
os.makedirs("/root/antigrav-stax-audio/downloads", exist_ok=True)
os.makedirs("/root/antigrav-stax-audio/temp", exist_ok=True)
cookie_sec = APIKeyCookie(name="session_token", auto_error=False)
def verify_cookie(session_token: str = Depends(cookie_sec)):
if not session_token or session_token != "valid_token_xyz":
raise HTTPException(status_code=401, detail="Not authenticated")
return True
app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None)
app.mount("/downloads", StaticFiles(directory="/root/antigrav-stax-audio/downloads"), name="downloads")
@app.get("/", response_class=HTMLResponse, include_in_schema=False)
async def login_get(request: Request):
token = request.cookies.get("session_token")
if token == "valid_token_xyz":
return RedirectResponse(url="/docs", status_code=302)
html_content = """
<!DOCTYPE html>
<html>
<head>
<title>Stax API Login</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; display: flex; justify-content: center; align-items: center; height: 100vh; background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%); margin: 0; }
.login-box { background: white; padding: 40px; border-radius: 12px; box-shadow: 0 8px 24px rgba(0,0,0,0.1); width: 100%; max-width: 320px; text-align: center; }
h2 { margin-top: 0; color: #333; margin-bottom: 24px; font-weight: 600; }
input { width: 100%; padding: 12px; margin: 8px 0 16px 0; border: 1px solid #ddd; border-radius: 6px; box-sizing: border-box; font-size: 15px; transition: border-color 0.3s; }
input:focus { border-color: #007bff; outline: none; }
button { width: 100%; padding: 12px; background: #007bff; color: white; border: none; border-radius: 6px; cursor: pointer; font-size: 16px; font-weight: 600; transition: background 0.3s; }
button:hover { background: #0056b3; }
.error { color: #dc3545; font-size: 14px; margin-bottom: 10px; }
</style>
</head>
<body>
<div class="login-box">
<h2>Stax API Docs</h2>
<form method="post" action="/login">
<input type="text" name="username" placeholder="Username" required autocomplete="username">
<input type="password" name="password" placeholder="Password" required autocomplete="current-password">
<button type="submit">Login to Docs</button>
</form>
</div>
</body>
</html>
"""
return HTMLResponse(content=html_content)
@app.post("/login", include_in_schema=False)
async def login_post(response: Response, username: str = Form(...), password: str = Form(...)):
correct_username = secrets.compare_digest(username, "admin")
correct_password = secrets.compare_digest(password, "stax123")
if correct_username and correct_password:
res = RedirectResponse(url="/docs", status_code=302)
res.set_cookie(key="session_token", value="valid_token_xyz", httponly=True, max_age=86400)
return res
else:
return HTMLResponse("""
<div style="font-family: sans-serif; text-align: center; padding: 50px;">
<h2 style="color: red;">Invalid Credentials</h2>
<a href="/">Try Again</a>
</div>
""", status_code=401)
@app.get("/docs", include_in_schema=False)
async def get_documentation(is_valid: bool = Depends(verify_cookie)):
return get_swagger_ui_html(openapi_url="/openapi.json", title="Stax API Docs")
@app.get("/openapi.json", include_in_schema=False)
async def openapi(is_valid: bool = Depends(verify_cookie)):
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.",
routes=app.routes,
)
openapi_schema["components"]["securitySchemes"] = {
"BearerAuth": {
"type": "http",
"scheme": "bearer",
"bearerFormat": "JWT"
}
}
app.openapi_schema = openapi_schema
return app.openapi_schema
# --- Pydantic Models ---
class TagRequest(BaseModel):
chat_id: int
message_id: int
language_preference: str = "native"
class TagResponse(BaseModel):
status: str
download_url: str
metadata: dict
class FileToRemix(BaseModel):
chat_id: int
message_id: int
class RemixBatchRequest(BaseModel):
files: List[FileToRemix]
prompt: str
# --- Core API Endpoints ---
@app.post("/music/tag", response_model=TagResponse, tags=["Music Processing"])
async def tag_music(req: TagRequest):
return {
"status": "success",
"download_url": "https://api.staxmusic.com/downloads/tagged_track.mp3",
"metadata": {
"title": "Mock Title",
"artist": "Mock Artist",
"album": "Mock Album",
"genre": "Pop"
}
}
@app.post("/music/remix/batch", tags=["Music Processing"])
async def batch_remix(req: RemixBatchRequest):
return {"status": "accepted", "job_id": "mock_job_12345", "message": "Batch remix job accepted and processing in background."}
@app.get("/music/remix/status/{job_id}", tags=["Music Processing"])
async def batch_remix_status(job_id: str):
return {"status": "processing", "job_id": job_id, "progress": 45, "message": "Applying AI crossfades..."}
@app.post("/music/upload", response_model=TagResponse, tags=["Music Processing"])
async def upload_direct(file: UploadFile = File(...)):
temp_filename = f"/root/antigrav-stax-audio/temp/{uuid.uuid4()}_{file.filename}"
with open(temp_filename, "wb") as buffer:
shutil.copyfileobj(file.file, buffer)
try:
candidates = await identify_audio(temp_filename)
candidate = candidates[0] if candidates else None
if not candidate:
gemini_result = await identify_with_gemini(temp_filename, "native")
candidate = gemini_result if gemini_result else {}
if not candidate.get("lyrics"):
lyrics = await fetch_lyrics(candidate.get("title", ""), candidate.get("artist", ""))
candidate["lyrics"] = lyrics
if not candidate.get("genre") or candidate.get("genre") == "Unknown Genre":
title = candidate.get("title", "")
artist = candidate.get("artist", "")
if title and artist and title != "Unknown" and artist != "Unknown":
try:
model = genai.GenerativeModel('gemini-2.5-flash')
prompt = f"What is the genre of the song '{title}' by '{artist}'? Reply with ONLY a single genre name (e.g. Pop, Synth-pop, Classical). Do not include any other text."
response = await asyncio.to_thread(model.generate_content, prompt)
raw_text = response.text.strip()
if "\n" in raw_text:
candidate["genre"] = [line.strip() for line in raw_text.split("\n") if line.strip()][-1]
else:
candidate["genre"] = raw_text
except:
candidate["genre"] = "Unknown Genre"
final_filename = await tag_and_convert_audio(temp_filename, candidate)
# move to downloads directory
download_path = f"/root/antigrav-stax-audio/downloads/{final_filename}"
shutil.move(final_filename, download_path)
if os.path.exists(temp_filename):
os.remove(temp_filename)
quoted_filename = urllib.parse.quote(final_filename)
return {
"status": "success",
"download_url": f"http://216.126.237.62/downloads/{quoted_filename}",
"metadata": {
"title": candidate.get('title', 'Unknown'),
"artist": candidate.get('artist', 'Unknown'),
"album": candidate.get('album', ''),
"genre": candidate.get('genre', ''),
"year": candidate.get('year', ''),
"has_lyrics": bool(candidate.get('lyrics'))
}
}
except Exception as e:
if os.path.exists(temp_filename):
os.remove(temp_filename)
raise HTTPException(status_code=500, detail=str(e))
@app.post("/discovery/listen")
async def discovery_listen(file: UploadFile = File(...), db: Session = Depends(get_db)):
"""Accepts a short audio snippet from the microphone to identify what's playing."""
temp_filename = f"/root/antigrav-stax-audio/temp/{file.filename}"
with open(temp_filename, "wb") as buffer:
shutil.copyfileobj(file.file, buffer)
candidates = await identify_audio(temp_filename)
if not candidates:
os.remove(temp_filename)
return {"status": "error", "message": "No music detected"}
candidate = candidates[0]
new_song = DiscoveredSong(
title=candidate.get("title"),
artist=candidate.get("artist"),
genre=candidate.get("genre"),
coverart=candidate.get("coverart")
)
db.add(new_song)
db.commit()
db.refresh(new_song)
os.remove(temp_filename)
return {"status": "success", "detected": candidate, "discovery_id": new_song.id}
@app.get("/discovery/history")
async def discovery_history(db: Session = Depends(get_db)):
"""Returns the background listening history for the past 24 hours."""
time_24h_ago = datetime.now(timezone.utc) - timedelta(hours=24)
songs = db.query(DiscoveredSong).filter(DiscoveredSong.detected_at >= time_24h_ago).order_by(DiscoveredSong.detected_at.desc()).all()
return {"status": "success", "history": songs}
@app.post("/discovery/{song_id}/swipe")
async def discovery_swipe(song_id: int, liked: bool = Form(...), db: Session = Depends(get_db)):
"""Swipe right (liked=true) or left (liked=false) on a discovered song."""
song = db.query(DiscoveredSong).filter(DiscoveredSong.id == song_id).first()
if not song:
raise HTTPException(status_code=404, detail="Song not found")
song.liked = liked
db.commit()
return {"status": "success", "message": "Preference saved"}
class PlaylistCreate(BaseModel):
name: str
@app.get("/library")
async def get_library(db: Session = Depends(get_db)):
songs = db.query(LibrarySong).order_by(LibrarySong.added_at.desc()).all()
return {"status": "success", "library": songs}
@app.get("/library/stream/{file_id}")
async def stream_audio(file_id: int, db: Session = Depends(get_db)):
song = db.query(LibrarySong).filter(LibrarySong.id == file_id).first()
if not song or not song.file_path or not os.path.exists(song.file_path):
raise HTTPException(status_code=404, detail="Audio file not found")
return FileResponse(song.file_path, media_type="audio/mpeg")
@app.get("/library/lyrics/{file_id}")
async def get_lyrics(file_id: int, db: Session = Depends(get_db)):
song = db.query(LibrarySong).filter(LibrarySong.id == file_id).first()
if not song:
raise HTTPException(status_code=404, detail="Song not found")
return {"status": "success", "lyrics": song.lyrics}
@app.post("/library/search")
async def search_library(query: str = Form(...), db: Session = Depends(get_db)):
q = f"%{query}%"
songs = db.query(LibrarySong).filter(
(LibrarySong.title.ilike(q)) |
(LibrarySong.artist.ilike(q)) |
(LibrarySong.genre.ilike(q))
).all()
return {"status": "success", "results": songs}
@app.get("/playlists")
async def get_playlists(db: Session = Depends(get_db)):
playlists = db.query(Playlist).order_by(Playlist.created_at.desc()).all()
return {"status": "success", "playlists": playlists}
@app.post("/playlists")
async def create_playlist(data: PlaylistCreate, db: Session = Depends(get_db)):
new_pl = Playlist(name=data.name)
db.add(new_pl)
db.commit()
db.refresh(new_pl)
return {"status": "success", "playlist": new_pl}
@app.post("/playlists/{playlist_id}/add")
async def add_to_playlist(playlist_id: int, song_id: int = Form(...), db: Session = Depends(get_db)):
pl = db.query(Playlist).filter(Playlist.id == playlist_id).first()
if not pl:
raise HTTPException(status_code=404, detail="Playlist not found")
song = db.query(LibrarySong).filter(LibrarySong.id == song_id).first()
if not song:
raise HTTPException(status_code=404, detail="Song not found")
# Get max order
max_order = db.query(PlaylistTrack).filter(PlaylistTrack.playlist_id == playlist_id).count()
pt = PlaylistTrack(playlist_id=playlist_id, song_id=song_id, order=max_order)
db.add(pt)
db.commit()
return {"status": "success", "message": "Added to playlist"}
@app.post("/auth/request_code")
async def auth_request_code(req: RequestCodeReq):
try:
res = await telegram_auth.request_code(req.phone_number)
return {"status": "success", "data": res}
except Exception as e:
raise HTTPException(status_code=400, detail=str(e))
@app.post("/auth/login")
async def auth_login(req: LoginReq, db: Session = Depends(get_db)):
try:
res = await telegram_auth.login(req.phone_number, req.phone_code_hash, req.code)
# Save or update user in our DB
user = db.query(User).filter(User.id == res["user_id"]).first()
if not user:
user = User(id=res["user_id"], username=req.phone_number)
db.add(user)
db.commit()
return {"status": "success", "access_token": res["session_string"], "user_id": res["user_id"]}
except Exception as e:
raise HTTPException(status_code=400, detail=str(e))
@app.get("/chats")
async def get_chats(session_string: str = Header(None)):
if not session_string:
raise HTTPException(status_code=401, detail="Session string required")
try:
chats = await telegram_sync.get_chats(session_string)
return {"status": "success", "chats": chats}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.get("/chats/{chat_id}/music")
async def get_chat_music(chat_id: int, session_string: str = Header(None)):
if not session_string:
raise HTTPException(status_code=401, detail="Session string required")
try:
music = await telegram_sync.get_chat_music(session_string, chat_id)
return {"status": "success", "music": music}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
import secrets
import os
import shutil
import uuid
from typing import List
from fastapi import FastAPI, Depends, HTTPException, status, Request, Form, Response, UploadFile, File, Header
from fastapi.responses import HTMLResponse, RedirectResponse, FileResponse
from pydantic import BaseModel
from sqlalchemy.orm import Session
from datetime import datetime, timedelta, timezone
from database import LibrarySong, Playlist, PlaylistTrack, SessionLocal, DiscoveredSong, get_db
import telegram_auth
import telegram_sync
class RequestCodeReq(BaseModel):
phone_number: str
class LoginReq(BaseModel):
phone_number: str
phone_code_hash: str
code: str
from database import SessionLocal, DiscoveredSong, get_db
from sqlalchemy.orm import Session
from datetime import datetime, timedelta, timezone
import os
import shutil
import uuid
from fastapi import FastAPI, Depends, HTTPException, status, Request, Form, Response, UploadFile, File
from fastapi.responses import HTMLResponse, RedirectResponse
from fastapi.openapi.docs import get_swagger_ui_html
from fastapi.openapi.utils import get_openapi
from fastapi.security import APIKeyCookie
from fastapi.staticfiles import StaticFiles
from pydantic import BaseModel
from typing import List, Optional
import urllib.parse
from music_identification import identify_with_gemini, identify_audio, fetch_lyrics
from audio_processing import tag_and_convert_audio
import google.generativeai as genai
import asyncio
os.makedirs("/root/antigrav-stax-audio/downloads", exist_ok=True)
os.makedirs("/root/antigrav-stax-audio/temp", exist_ok=True)
cookie_sec = APIKeyCookie(name="session_token", auto_error=False)
def verify_cookie(session_token: str = Depends(cookie_sec)):
if not session_token or session_token != "valid_token_xyz":
raise HTTPException(status_code=401, detail="Not authenticated")
return True
app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None)
app.mount("/downloads", StaticFiles(directory="/root/antigrav-stax-audio/downloads"), name="downloads")
@app.get("/", response_class=HTMLResponse, include_in_schema=False)
async def login_get(request: Request):
token = request.cookies.get("session_token")
if token == "valid_token_xyz":
return RedirectResponse(url="/docs", status_code=302)
html_content = """
<!DOCTYPE html>
<html>
<head>
<title>Stax API Login</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; display: flex; justify-content: center; align-items: center; height: 100vh; background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%); margin: 0; }
.login-box { background: white; padding: 40px; border-radius: 12px; box-shadow: 0 8px 24px rgba(0,0,0,0.1); width: 100%; max-width: 320px; text-align: center; }
h2 { margin-top: 0; color: #333; margin-bottom: 24px; font-weight: 600; }
input { width: 100%; padding: 12px; margin: 8px 0 16px 0; border: 1px solid #ddd; border-radius: 6px; box-sizing: border-box; font-size: 15px; transition: border-color 0.3s; }
input:focus { border-color: #007bff; outline: none; }
button { width: 100%; padding: 12px; background: #007bff; color: white; border: none; border-radius: 6px; cursor: pointer; font-size: 16px; font-weight: 600; transition: background 0.3s; }
button:hover { background: #0056b3; }
.error { color: #dc3545; font-size: 14px; margin-bottom: 10px; }
</style>
</head>
<body>
<div class="login-box">
<h2>Stax API Docs</h2>
<form method="post" action="/login">
<input type="text" name="username" placeholder="Username" required autocomplete="username">
<input type="password" name="password" placeholder="Password" required autocomplete="current-password">
<button type="submit">Login to Docs</button>
</form>
</div>
</body>
</html>
"""
return HTMLResponse(content=html_content)
@app.post("/login", include_in_schema=False)
async def login_post(response: Response, username: str = Form(...), password: str = Form(...)):
correct_username = secrets.compare_digest(username, "admin")
correct_password = secrets.compare_digest(password, "stax123")
if correct_username and correct_password:
res = RedirectResponse(url="/docs", status_code=302)
res.set_cookie(key="session_token", value="valid_token_xyz", httponly=True, max_age=86400)
return res
else:
return HTMLResponse("""
<div style="font-family: sans-serif; text-align: center; padding: 50px;">
<h2 style="color: red;">Invalid Credentials</h2>
<a href="/">Try Again</a>
</div>
""", status_code=401)
@app.get("/docs", include_in_schema=False)
async def get_documentation(is_valid: bool = Depends(verify_cookie)):
return get_swagger_ui_html(openapi_url="/openapi.json", title="Stax API Docs")
@app.get("/openapi.json", include_in_schema=False)
async def openapi(is_valid: bool = Depends(verify_cookie)):
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.",
routes=app.routes,
)
openapi_schema["components"]["securitySchemes"] = {
"BearerAuth": {
"type": "http",
"scheme": "bearer",
"bearerFormat": "JWT"
}
}
app.openapi_schema = openapi_schema
return app.openapi_schema
# --- Pydantic Models ---
class TagRequest(BaseModel):
chat_id: int
message_id: int
language_preference: str = "native"
class TagResponse(BaseModel):
status: str
download_url: str
metadata: dict
class FileToRemix(BaseModel):
chat_id: int
message_id: int
class RemixBatchRequest(BaseModel):
files: List[FileToRemix]
prompt: str
# --- Core API Endpoints ---
@app.post("/music/tag", response_model=TagResponse, tags=["Music Processing"])
async def tag_music(req: TagRequest):
return {
"status": "success",
"download_url": "https://api.staxmusic.com/downloads/tagged_track.mp3",
"metadata": {
"title": "Mock Title",
"artist": "Mock Artist",
"album": "Mock Album",
"genre": "Pop"
}
}
@app.post("/music/remix/batch", tags=["Music Processing"])
async def batch_remix(req: RemixBatchRequest):
return {"status": "accepted", "job_id": "mock_job_12345", "message": "Batch remix job accepted and processing in background."}
@app.get("/music/remix/status/{job_id}", tags=["Music Processing"])
async def batch_remix_status(job_id: str):
return {"status": "processing", "job_id": job_id, "progress": 45, "message": "Applying AI crossfades..."}
@app.post("/music/upload", response_model=TagResponse, tags=["Music Processing"])
async def upload_direct(file: UploadFile = File(...)):
temp_filename = f"/root/antigrav-stax-audio/temp/{uuid.uuid4()}_{file.filename}"
with open(temp_filename, "wb") as buffer:
shutil.copyfileobj(file.file, buffer)
try:
candidates = await identify_audio(temp_filename)
candidate = candidates[0] if candidates else None
if not candidate:
gemini_result = await identify_with_gemini(temp_filename, "native")
candidate = gemini_result if gemini_result else {}
if not candidate.get("lyrics"):
lyrics = await fetch_lyrics(candidate.get("title", ""), candidate.get("artist", ""))
candidate["lyrics"] = lyrics
if not candidate.get("genre") or candidate.get("genre") == "Unknown Genre":
title = candidate.get("title", "")
artist = candidate.get("artist", "")
if title and artist and title != "Unknown" and artist != "Unknown":
try:
model = genai.GenerativeModel('gemini-2.5-flash')
prompt = f"What is the genre of the song '{title}' by '{artist}'? Reply with ONLY a single genre name (e.g. Pop, Synth-pop, Classical). Do not include any other text."
response = await asyncio.to_thread(model.generate_content, prompt)
raw_text = response.text.strip()
if "\n" in raw_text:
candidate["genre"] = [line.strip() for line in raw_text.split("\n") if line.strip()][-1]
else:
candidate["genre"] = raw_text
except:
candidate["genre"] = "Unknown Genre"
final_filename = await tag_and_convert_audio(temp_filename, candidate)
# move to downloads directory
download_path = f"/root/antigrav-stax-audio/downloads/{final_filename}"
shutil.move(final_filename, download_path)
if os.path.exists(temp_filename):
os.remove(temp_filename)
quoted_filename = urllib.parse.quote(final_filename)
return {
"status": "success",
"download_url": f"http://216.126.237.62/downloads/{quoted_filename}",
"metadata": {
"title": candidate.get('title', 'Unknown'),
"artist": candidate.get('artist', 'Unknown'),
"album": candidate.get('album', ''),
"genre": candidate.get('genre', ''),
"year": candidate.get('year', ''),
"has_lyrics": bool(candidate.get('lyrics'))
}
}
except Exception as e:
if os.path.exists(temp_filename):
os.remove(temp_filename)
raise HTTPException(status_code=500, detail=str(e))
@app.post("/discovery/listen")
async def discovery_listen(file: UploadFile = File(...), db: Session = Depends(get_db)):
"""Accepts a short audio snippet from the microphone to identify what's playing."""
temp_filename = f"/root/antigrav-stax-audio/temp/{file.filename}"
with open(temp_filename, "wb") as buffer:
shutil.copyfileobj(file.file, buffer)
candidates = await identify_audio(temp_filename)
if not candidates:
os.remove(temp_filename)
return {"status": "error", "message": "No music detected"}
candidate = candidates[0]
new_song = DiscoveredSong(
title=candidate.get("title"),
artist=candidate.get("artist"),
genre=candidate.get("genre"),
coverart=candidate.get("coverart")
)
db.add(new_song)
db.commit()
db.refresh(new_song)
os.remove(temp_filename)
return {"status": "success", "detected": candidate, "discovery_id": new_song.id}
@app.get("/discovery/history")
async def discovery_history(db: Session = Depends(get_db)):
"""Returns the background listening history for the past 24 hours."""
time_24h_ago = datetime.now(timezone.utc) - timedelta(hours=24)
songs = db.query(DiscoveredSong).filter(DiscoveredSong.detected_at >= time_24h_ago).order_by(DiscoveredSong.detected_at.desc()).all()
return {"status": "success", "history": songs}
@app.post("/discovery/{song_id}/swipe")
async def discovery_swipe(song_id: int, liked: bool = Form(...), db: Session = Depends(get_db)):
"""Swipe right (liked=true) or left (liked=false) on a discovered song."""
song = db.query(DiscoveredSong).filter(DiscoveredSong.id == song_id).first()
if not song:
raise HTTPException(status_code=404, detail="Song not found")
song.liked = liked
db.commit()
return {"status": "success", "message": "Preference saved"}
class PlaylistCreate(BaseModel):
name: str
@app.get("/library")
async def get_library(db: Session = Depends(get_db)):
songs = db.query(LibrarySong).order_by(LibrarySong.added_at.desc()).all()
return {"status": "success", "library": songs}
@app.get("/library/stream/{file_id}")
async def stream_audio(file_id: int, db: Session = Depends(get_db)):
song = db.query(LibrarySong).filter(LibrarySong.id == file_id).first()
if not song or not song.file_path or not os.path.exists(song.file_path):
raise HTTPException(status_code=404, detail="Audio file not found")
return FileResponse(song.file_path, media_type="audio/mpeg")
@app.get("/library/lyrics/{file_id}")
async def get_lyrics(file_id: int, db: Session = Depends(get_db)):
song = db.query(LibrarySong).filter(LibrarySong.id == file_id).first()
if not song:
raise HTTPException(status_code=404, detail="Song not found")
return {"status": "success", "lyrics": song.lyrics}
@app.post("/library/search")
async def search_library(query: str = Form(...), db: Session = Depends(get_db)):
q = f"%{query}%"
songs = db.query(LibrarySong).filter(
(LibrarySong.title.ilike(q)) |
(LibrarySong.artist.ilike(q)) |
(LibrarySong.genre.ilike(q))
).all()
return {"status": "success", "results": songs}
@app.get("/playlists")
async def get_playlists(db: Session = Depends(get_db)):
playlists = db.query(Playlist).order_by(Playlist.created_at.desc()).all()
return {"status": "success", "playlists": playlists}
@app.post("/playlists")
async def create_playlist(data: PlaylistCreate, db: Session = Depends(get_db)):
new_pl = Playlist(name=data.name)
db.add(new_pl)
db.commit()
db.refresh(new_pl)
return {"status": "success", "playlist": new_pl}
@app.post("/playlists/{playlist_id}/add")
async def add_to_playlist(playlist_id: int, song_id: int = Form(...), db: Session = Depends(get_db)):
pl = db.query(Playlist).filter(Playlist.id == playlist_id).first()
if not pl:
raise HTTPException(status_code=404, detail="Playlist not found")
song = db.query(LibrarySong).filter(LibrarySong.id == song_id).first()
if not song:
raise HTTPException(status_code=404, detail="Song not found")
# Get max order
max_order = db.query(PlaylistTrack).filter(PlaylistTrack.playlist_id == playlist_id).count()
pt = PlaylistTrack(playlist_id=playlist_id, song_id=song_id, order=max_order)
db.add(pt)
db.commit()
return {"status": "success", "message": "Added to playlist"}
@app.post("/auth/request_code")
async def auth_request_code(req: RequestCodeReq):
try:
res = await telegram_auth.request_code(req.phone_number)
return {"status": "success", "data": res}
except Exception as e:
raise HTTPException(status_code=400, detail=str(e))
@app.post("/auth/login")
async def auth_login(req: LoginReq, db: Session = Depends(get_db)):
try:
res = await telegram_auth.login(req.phone_number, req.phone_code_hash, req.code)
# Save or update user in our DB
user = db.query(User).filter(User.id == res["user_id"]).first()
if not user:
user = User(id=res["user_id"], username=req.phone_number)
db.add(user)
db.commit()
return {"status": "success", "access_token": res["session_string"], "user_id": res["user_id"]}
except Exception as e:
raise HTTPException(status_code=400, detail=str(e))
@app.get("/chats")
async def get_chats(session_string: str = Header(None)):
if not session_string:
raise HTTPException(status_code=401, detail="Session string required")
try:
chats = await telegram_sync.get_chats(session_string)
return {"status": "success", "chats": chats}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.get("/chats/{chat_id}/music")
async def get_chat_music(chat_id: int, session_string: str = Header(None)):
if not session_string:
raise HTTPException(status_code=401, detail="Session string required")
try:
music = await telegram_sync.get_chat_music(session_string, chat_id)
return {"status": "success", "music": music}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
import os
import aiohttp
from pydub import AudioSegment
from mutagen.mp3 import MP3
from mutagen.id3 import ID3, APIC, USLT, TIT2, TPE1, TALB, TDRC, TCON, TRCK, error
from src.core.config import logger
async def download_image(url: str) -> bytes:
if not url: return None
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
if response.status == 200: return await response.read()
return None
async def tag_and_convert_audio(raw_file_path: str, candidate: dict) -> str:
"""Converts audio to MP3 and applies all ID3 tags. Returns the path to the tagged MP3."""
# 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"
audio = AudioSegment.from_file(raw_file_path)
audio.export(mp3_file_path, format="mp3", bitrate="192k")
# 2. Add ID3 Tags
mp3 = MP3(mp3_file_path, ID3=ID3)
try: mp3.add_tags()
except error: pass
title, artist = candidate.get('title', 'Unknown'), candidate.get('artist', 'Unknown')
album, year = candidate.get('album', ''), candidate.get('year', '')
genre, track_num = candidate.get('genre', ''), candidate.get('track_number', '')
lyrics, coverart_url = candidate.get('lyrics'), candidate.get('coverart')
mp3.tags.add(TIT2(encoding=3, text=title))
mp3.tags.add(TPE1(encoding=3, text=artist))
if album: mp3.tags.add(TALB(encoding=3, text=album))
if year: mp3.tags.add(TDRC(encoding=3, text=year))
if genre: mp3.tags.add(TCON(encoding=3, text=genre))
if track_num: mp3.tags.add(TRCK(encoding=3, text=track_num))
if lyrics:
mp3.tags.add(USLT(encoding=3, lang='eng', desc=u'', text=lyrics))
if coverart_url:
image_bytes = await download_image(coverart_url)
if image_bytes:
mp3.tags.add(APIC(encoding=3, mime='image/jpeg', type=3, desc='Cover', data=image_bytes))
mp3.save(v2_version=3)
# 3. Rename file
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"
os.rename(mp3_file_path, final_filename)
return final_filename
import os
import asyncio
from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import (
Application, CommandHandler, MessageHandler, CallbackQueryHandler,
filters, ContextTypes, ConversationHandler
)
from config import TELEGRAM_BOT_TOKEN, LALAL_API_KEY, logger
from database import init_db, log_correction
from music_identification import identify_audio, fetch_lyrics
from audio_processing import tag_and_convert_audio
from ai_remix import get_remix_recipe, apply_remix
async def update_progress(status_msg, cancel_event, remix_name):
for i in range(1, 100):
if cancel_event.is_set():
break
bars = "■" * (i // 10) + "□" * (10 - (i // 10))
try:
await status_msg.edit_text(f"✨ Gemini called this **{remix_name} Remix**\n\n🎛 AI Audio Processing... [{bars}] {i}%\n(This usually takes 1-3 minutes)")
except:
pass
await asyncio.sleep(1.8)
# State constants
MAIN_MENU, AWAITING_AUDIO, AWAITING_SELECTION, AWAITING_MANUAL_ENTRY, AWAITING_REMIX_PROMPT, AWAITING_LANG_PREF = range(6)
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int:
keyboard = [
[InlineKeyboardButton("🏷 Tag & Identify", callback_data="menu_tag")],
[InlineKeyboardButton("🎛 AI Remix (Gemini)", callback_data="menu_remix")],
[InlineKeyboardButton("❌ Cancel", callback_data="menu_cancel")]
]
await update.message.reply_text(
"🎧 *Welcome to the Stax Phase 2 Bot!*\n\nWhat would you like to do?",
reply_markup=InlineKeyboardMarkup(keyboard),
parse_mode="Markdown"
)
return MAIN_MENU
async def handle_main_menu(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int:
query = update.callback_query
await query.answer()
if query.data == "menu_cancel":
await query.edit_message_text("Process cancelled. Send /start to begin again.")
return ConversationHandler.END
if query.data == "menu_stems":
await query.edit_message_text("✂️ **Stem Separation**\n\nTo use this feature, please configure your `LALAL_API_KEY` in the `.env` file.")
return ConversationHandler.END
context.user_data['action_type'] = query.data
if query.data == "menu_remix":
await query.edit_message_text("🎛 **AI Remix Selected**\n\nPlease send me the audio file you want to remix.")
elif query.data == "menu_tag":
await query.edit_message_text("🏷 **Tag & Identify Selected**\n\nPlease send me the audio file you want to identify and tag.")
return AWAITING_AUDIO
async def handle_audio_upload(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int:
message = update.message
if message.voice: file_obj = await message.voice.get_file()
elif message.audio: file_obj = await message.audio.get_file()
elif message.document and message.document.mime_type and message.document.mime_type.startswith('audio/'):
file_obj = await message.document.get_file()
else:
await message.reply_text("Please send a valid audio file.")
return AWAITING_AUDIO
raw_file_path = f"temp_{update.update_id}_raw"
context.user_data['raw_file_path'] = raw_file_path
status = await message.reply_text("📥 Downloading audio...")
try:
await file_obj.download_to_drive(raw_file_path)
except Exception as e:
logger.error(f"Download failed: {e}")
await status.edit_text("❌ Failed to download audio. The file might be too large or Telegram timed out.")
return ConversationHandler.END
await status.delete()
action_type = context.user_data.get('action_type')
if action_type == "menu_remix":
status = await message.reply_text("🔍 Quick fingerprinting to get original artist/title for metadata...")
candidates = await identify_audio(context.user_data['raw_file_path'])
if candidates:
context.user_data['original_candidate'] = candidates[0]
await status.edit_text(f"🎛 **AI Remix for {candidates[0]['title']}**\n\nDescribe how you want Gemini to remix this track. (e.g., *'Make it slowed down and dreamy'*).", parse_mode="Markdown")
else:
context.user_data['original_candidate'] = {'title': 'Unknown', 'artist': 'Unknown Artist', 'source': 'Unknown'}
await status.edit_text("🎛 **AI Remix**\n\nI couldn't identify the song, but we can still remix it! Describe how you want Gemini to remix this track.", parse_mode="Markdown")
return AWAITING_REMIX_PROMPT
elif action_type == "menu_tag":
status = await message.reply_text("🔍 Analyzing audio fingerprint against Shazam & AcoustID...")
candidates = await identify_audio(context.user_data['raw_file_path'])
context.user_data['candidates'] = candidates
keyboard = []
if candidates:
keyboard = [[InlineKeyboardButton(f"{c['artist']} - {c['title']} [{c['source'].split(' ')[0]}]", callback_data=f"select_{i}")] for i, c in enumerate(candidates)]
keyboard.append([InlineKeyboardButton("🎧 Ask Gemini (Fallback)", callback_data="gemini_fallback")])
keyboard.append([InlineKeyboardButton("✏️ None of these (Type manually)", callback_data="manual")])
if not candidates:
await status.edit_text("❌ I couldn't find any matches for this audio.\n\nYou can ask Gemini to listen to it, or type it manually:", reply_markup=InlineKeyboardMarkup(keyboard))
else:
await status.edit_text("Here are the closest matches. Tap one to proceed:", reply_markup=InlineKeyboardMarkup(keyboard))
return AWAITING_SELECTION
async def handle_selection(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int:
query = update.callback_query
await query.answer()
if query.data == "manual":
await query.edit_message_text("✏️ Manual Entry\n\nPlease type the Artist and Title:\n`Artist - Title`", parse_mode="Markdown")
return AWAITING_MANUAL_ENTRY
if query.data == "gemini_fallback":
kb = [
[InlineKeyboardButton("Native Script (Persian/Original)", callback_data="lang_native")],
[InlineKeyboardButton("Finglish / English Characters", callback_data="lang_finglish")]
]
await query.edit_message_text("🎧 **Gemini Audio Recognition**\n\nHow do you want the Title and Artist to be formatted in the final tags?", reply_markup=InlineKeyboardMarkup(kb), parse_mode="Markdown")
return AWAITING_LANG_PREF
candidate = context.user_data['candidates'][int(query.data.split("_")[1])]
await query.edit_message_text(f"✅ Selected: **{candidate['artist']} - {candidate['title']}**\n⚙️ Tagging file...", parse_mode="Markdown")
await process_and_send_audio(update, context, candidate, query.message.chat_id)
return ConversationHandler.END
async def handle_manual_entry(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int:
text = update.message.text
artist, title = text.split(" - ", 1) if " - " in text else ("Unknown Artist", text)
candidate = {'title': title.strip(), 'artist': artist.strip(), 'source': 'Manual Entry'}
await update.message.reply_text(f"✅ Logged Manual Entry: **{candidate['artist']} - {candidate['title']}**\n⚙️ Tagging file...", parse_mode="Markdown")
await process_and_send_audio(update, context, candidate, update.message.chat_id)
return ConversationHandler.END
async def handle_remix_prompt(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int:
status = await update.message.reply_text("🤖 Asking Gemini for creative direction and generating metadata...")
raw_path, out_path = context.user_data['raw_file_path'], None
candidate = context.user_data.get('original_candidate', {'title': 'Unknown', 'artist': 'Unknown Artist'})
try:
recipe = await get_remix_recipe(update.message.text, candidate['title'])
remix_name = recipe.get("remix_name", "AI")
await status.edit_text(f"✨ Gemini decided to call this the **{remix_name} Remix**\n\n🎛 Starting AI engine...")
cancel_event = asyncio.Event()
progress_task = asyncio.create_task(update_progress(status, cancel_event, remix_name))
out_path = await apply_remix(raw_path, recipe)
cancel_event.set()
await progress_task
remix_candidate = {
'title': f"{candidate['title']} - {remix_name} Remix",
'artist': f"{candidate['artist']} + stax remix",
'source': 'AI Remix Engine'
}
tagged_out_path = await tag_and_convert_audio(out_path, remix_candidate)
await status.edit_text("⬆️ Uploading Remixed Audio...")
with open(tagged_out_path, 'rb') as f:
await context.bot.send_audio(chat_id=update.message.chat_id, audio=f, title=remix_candidate['title'], performer=remix_candidate['artist'])
if os.path.exists(tagged_out_path): os.remove(tagged_out_path)
except Exception as e:
logger.error(f"Remix error: {e}")
await status.edit_text("❌ Failed to process the AI remix.")
finally:
for p in [raw_path, out_path]:
if p and os.path.exists(p): os.remove(p)
return ConversationHandler.END
async def process_and_send_audio(update: Update, context: ContextTypes.DEFAULT_TYPE, candidate: dict, chat_id: int):
raw_path, final_path = context.user_data.get('raw_file_path'), None
if not raw_path or not os.path.exists(raw_path): return
log_correction(update.effective_user.id, candidate['title'], candidate['artist'], candidate['source'])
if not candidate.get('lyrics') and candidate['title'] != 'Unknown Title':
candidate['lyrics'] = await fetch_lyrics(candidate['title'], candidate['artist'])
try:
final_path = await tag_and_convert_audio(raw_path, candidate)
with open(final_path, 'rb') as f:
await context.bot.send_audio(chat_id=chat_id, audio=f, title=candidate['title'], performer=candidate['artist'])
except Exception as e:
logger.error(f"Processing error: {e}")
await context.bot.send_message(chat_id=chat_id, text="❌ Failed to tag audio.")
finally:
for p in [raw_path, final_path]:
if p and os.path.exists(p): os.remove(p)
async def handle_lang_pref(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int:
query = update.callback_query
await query.answer()
lang_pref = "native" if query.data == "lang_native" else "finglish"
await query.edit_message_text("🎧 Uploading audio to Gemini and analyzing... (This takes a few seconds)")
from music_identification import identify_with_gemini
gemini_candidate = await identify_with_gemini(context.user_data['raw_file_path'], lang_pref)
if not gemini_candidate:
await query.edit_message_text("❌ Gemini failed to analyze the audio.")
return ConversationHandler.END
await query.edit_message_text(f"✅ Gemini Identified: **{gemini_candidate['artist']} - {gemini_candidate['title']}**\n⚙️ Tagging file...", parse_mode="Markdown")
await process_and_send_audio(update, context, gemini_candidate, query.message.chat_id)
return ConversationHandler.END
async def cancel(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int:
await update.message.reply_text("Process cancelled.")
if os.path.exists(context.user_data.get('raw_file_path', '')): os.remove(context.user_data['raw_file_path'])
return ConversationHandler.END
def main() -> None:
init_db()
if not TELEGRAM_BOT_TOKEN:
logger.error("No TELEGRAM_BOT_TOKEN found!")
return
app = Application.builder().token(TELEGRAM_BOT_TOKEN).read_timeout(60).write_timeout(60).connect_timeout(60).build()
conv_handler = ConversationHandler(
entry_points=[CommandHandler("start", start)],
states={
MAIN_MENU: [CallbackQueryHandler(handle_main_menu, pattern="^menu_.*$")],
AWAITING_AUDIO: [MessageHandler(filters.VOICE | filters.AUDIO | filters.Document.AUDIO, handle_audio_upload)],
AWAITING_SELECTION: [CallbackQueryHandler(handle_selection, pattern="^select_[0-9]+$|^manual$|^gemini_fallback$")],
AWAITING_MANUAL_ENTRY: [MessageHandler(filters.TEXT & ~filters.COMMAND, handle_manual_entry)],
AWAITING_REMIX_PROMPT: [MessageHandler(filters.TEXT & ~filters.COMMAND, handle_remix_prompt)],
AWAITING_LANG_PREF: [CallbackQueryHandler(handle_lang_pref, pattern="^lang_.*$")],
},
fallbacks=[CommandHandler("cancel", cancel)],
)
app.add_handler(conv_handler)
app.run_polling(allowed_updates=Update.ALL_TYPES)
if __name__ == "__main__":
main()
import math
import wave
import struct
import os
from pydub import AudioSegment
def generate_tone(frequency, duration_ms, volume=0.5, decay=0):
sample_rate = 44100
num_samples = int(sample_rate * (duration_ms / 1000.0))
audio_data = bytearray()
for i in range(num_samples):
# Apply exponential decay if specified
env = math.exp(-decay * (i / sample_rate)) if decay else 1.0
# frequency sweep for kick
if frequency == 'kick':
freq = 150 * math.exp(-30 * (i / sample_rate))
env = math.exp(-15 * (i / sample_rate))
else:
freq = frequency
value = int(volume * env * 32767.0 * math.sin(2.0 * math.pi * freq * (i / sample_rate)))
audio_data.extend(struct.pack('<h', value))
with wave.open("temp_tone.wav", 'w') as f:
f.setnchannels(1)
f.setsampwidth(2)
f.setframerate(sample_rate)
f.writeframes(audio_data)
return AudioSegment.from_wav("temp_tone.wav")
def build_house_loop():
# 120 BPM = 500ms per beat
kick = generate_tone('kick', 500, volume=0.9, decay=10)
hat = generate_tone(8000, 500, volume=0.2, decay=50) # simple tick
# K - H - K - H
beat = kick.overlay(hat, position=250)
loop = beat * 8
loop.export("house.mp3", format="mp3")
def build_trap_loop():
# 140 BPM = 428ms per beat
kick = generate_tone('kick', 428, volume=1.0, decay=5) # 808 style long kick
snare = generate_tone(300, 428, volume=0.6, decay=15)
# K - S - KK - S
loop = kick + snare + kick[:214] + kick[214:] + snare
loop = loop * 4
loop.export("trap.mp3", format="mp3")
def build_lofi_loop():
# 85 BPM = 705ms per beat
kick = generate_tone('kick', 705, volume=0.5, decay=15)
snare = generate_tone(200, 705, volume=0.3, decay=10)
loop = kick + snare + kick + snare
loop = loop * 4
loop.export("lofi.mp3", format="mp3")
build_house_loop()
build_trap_loop()
build_lofi_loop()
if os.path.exists("temp_tone.wav"):
os.remove("temp_tone.wav")
import os
import logging
from dotenv import load_dotenv
# Load environment variables
load_dotenv()
TELEGRAM_BOT_TOKEN = os.getenv("TELEGRAM_BOT_TOKEN")
ACOUSTID_API_KEY = os.getenv("ACOUSTID_API_KEY", "8XaBELgH")
GEMINI_API_KEY = os.getenv("GEMINI_API_KEY")
LALAL_API_KEY = os.getenv("LALAL_API_KEY")
# Setup centralized logging
logging.basicConfig(
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
level=logging.INFO
)
logger = logging.getLogger("StaxBot")
import os
from sqlalchemy import create_engine, Column, Integer, String, DateTime, ForeignKey, Boolean
from sqlalchemy.orm import declarative_base, sessionmaker
from datetime import datetime, timezone
DATABASE_URL = "sqlite:////root/antigrav-stax-audio/stax.db"
engine = create_engine(DATABASE_URL, connect_args={"check_same_thread": False})
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()
class User(Base):
__tablename__ = "users"
id = Column(Integer, primary_key=True, index=True)
username = Column(String, unique=True, index=True)
class DiscoveredSong(Base):
__tablename__ = "discovered_songs"
id = Column(Integer, primary_key=True, index=True)
title = Column(String, index=True)
artist = Column(String, index=True)
genre = Column(String)
coverart = Column(String)
detected_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
liked = Column(Boolean, default=None, nullable=True)
class LibrarySong(Base):
__tablename__ = "library_songs"
id = Column(Integer, primary_key=True, index=True)
user_id = Column(Integer, ForeignKey("users.id"), index=True)
title = Column(String, index=True)
artist = Column(String, index=True)
album = Column(String)
genre = Column(String)
coverart = Column(String)
lyrics = Column(String)
file_path = Column(String)
added_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
class Playlist(Base):
__tablename__ = "playlists"
id = Column(Integer, primary_key=True, index=True)
user_id = Column(Integer, ForeignKey("users.id"), index=True)
name = Column(String)
created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
class PlaylistTrack(Base):
__tablename__ = "playlist_tracks"
id = Column(Integer, primary_key=True, index=True)
playlist_id = Column(Integer, ForeignKey("playlists.id"), index=True)
song_id = Column(Integer, ForeignKey("library_songs.id"))
order = Column(Integer)
from sqlalchemy import Float
class UserProfile(Base):
__tablename__ = "user_profiles"
id = Column(Integer, primary_key=True, index=True)
user_id = Column(Integer, ForeignKey("users.id"), unique=True, index=True)
bio = Column(String)
avatar_url = Column(String)
class Follow(Base):
__tablename__ = "follows"
id = Column(Integer, primary_key=True, index=True)
follower_id = Column(Integer, ForeignKey("users.id"), index=True)
following_id = Column(Integer, ForeignKey("users.id"), index=True)
class Post(Base):
__tablename__ = "posts"
id = Column(Integer, primary_key=True, index=True)
user_id = Column(Integer, ForeignKey("users.id"), index=True)
song_id = Column(Integer, ForeignKey("library_songs.id"))
parent_post_id = Column(Integer, ForeignKey("posts.id"), nullable=True)
caption = Column(String)
created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
class GeoDrop(Base):
__tablename__ = "geo_drops"
id = Column(Integer, primary_key=True, index=True)
user_id = Column(Integer, ForeignKey("users.id"), index=True)
song_id = Column(Integer, ForeignKey("library_songs.id"))
latitude = Column(Float)
longitude = Column(Float)
dropped_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
class LiveRoom(Base):
__tablename__ = "live_rooms"
id = Column(Integer, primary_key=True, index=True)
dj_id = Column(Integer, ForeignKey("users.id"), index=True)
current_song_id = Column(Integer, ForeignKey("library_songs.id"), nullable=True)
name = Column(String)
is_active = Column(Boolean, default=True)
created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
Base.metadata.create_all(bind=engine)
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
import os
import google.generativeai as genai
from dotenv import load_dotenv
load_dotenv()
genai.configure(api_key=os.getenv("GEMINI_API_KEY"))
for m in genai.list_models():
if 'generateContent' in m.supported_generation_methods:
print(m.name)
import os
import secrets
from fastapi import FastAPI, Depends, Request, Form, Response
from fastapi.responses import HTMLResponse, RedirectResponse
from fastapi.openapi.docs import get_swagger_ui_html
from fastapi.openapi.utils import get_openapi
from fastapi.security import APIKeyCookie
from fastapi.staticfiles import StaticFiles
from src.api.routers import auth, discovery, library, music, social
os.makedirs("/root/antigrav-stax-audio/downloads", exist_ok=True)
os.makedirs("/root/antigrav-stax-audio/temp", exist_ok=True)
cookie_sec = APIKeyCookie(name="session_token", auto_error=False)
def verify_cookie(session_token: str = Depends(cookie_sec)):
if not session_token or session_token != "valid_token_xyz":
return False
return True
app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None)
app.mount("/downloads", StaticFiles(directory="/root/antigrav-stax-audio/downloads"), name="downloads")
app.include_router(auth.router)
app.include_router(discovery.router)
app.include_router(library.router)
app.include_router(music.router)
app.include_router(social.router)
@app.get("/", response_class=HTMLResponse, include_in_schema=False)
async def login_get(request: Request):
token = request.cookies.get("session_token")
if token == "valid_token_xyz":
return RedirectResponse(url="/docs", status_code=302)
html_content = """
<!DOCTYPE html>
<html>
<head>
<title>Stax API Login</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; display: flex; justify-content: center; align-items: center; height: 100vh; background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%); margin: 0; }
.login-box { background: white; padding: 40px; border-radius: 12px; box-shadow: 0 8px 24px rgba(0,0,0,0.1); width: 100%; max-width: 320px; text-align: center; }
h2 { margin-top: 0; color: #333; margin-bottom: 24px; font-weight: 600; }
input { width: 100%; padding: 12px; margin: 8px 0 16px 0; border: 1px solid #ddd; border-radius: 6px; box-sizing: border-box; font-size: 15px; transition: border-color 0.3s; }
input:focus { border-color: #007bff; outline: none; }
button { width: 100%; padding: 12px; background: #007bff; color: white; border: none; border-radius: 6px; cursor: pointer; font-size: 16px; font-weight: 600; transition: background 0.3s; }
button:hover { background: #0056b3; }
.error { color: #dc3545; font-size: 14px; margin-bottom: 10px; }
</style>
</head>
<body>
<div class="login-box">
<h2>Stax API Docs</h2>
<form method="post" action="/login">
<input type="text" name="username" placeholder="Username" required autocomplete="username">
<input type="password" name="password" placeholder="Password" required autocomplete="current-password">
<button type="submit">Login to Docs</button>
</form>
</div>
</body>
</html>
"""
return HTMLResponse(content=html_content)
@app.post("/login", include_in_schema=False)
async def login_post(response: Response, username: str = Form(...), password: str = Form(...)):
correct_username = secrets.compare_digest(username, "admin")
correct_password = secrets.compare_digest(password, "stax123")
if correct_username and correct_password:
res = RedirectResponse(url="/docs", status_code=302)
res.set_cookie(key="session_token", value="valid_token_xyz", httponly=True, max_age=86400)
return res
else:
return HTMLResponse("""
<div style="font-family: sans-serif; text-align: center; padding: 50px;">
<h2 style="color: red;">Invalid Credentials</h2>
<a href="/">Try Again</a>
</div>
""", status_code=401)
@app.get("/docs", include_in_schema=False)
async def get_documentation(request: Request):
token = request.cookies.get("session_token")
if token != "valid_token_xyz":
return RedirectResponse(url="/", status_code=302)
return get_swagger_ui_html(openapi_url="/openapi.json", title="Stax API Docs")
@app.get("/openapi.json", include_in_schema=False)
async def openapi(request: Request):
token = request.cookies.get("session_token")
if token != "valid_token_xyz":
return RedirectResponse(url="/", status_code=302)
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.",
routes=app.routes,
)
openapi_schema["components"]["securitySchemes"] = {
"BearerAuth": {
"type": "http",
"scheme": "bearer",
"bearerFormat": "JWT"
}
}
app.openapi_schema = openapi_schema
return app.openapi_schema
import asyncio
import re
import acoustid
import musicbrainzngs
import syncedlyrics
from shazamio import Shazam
from src.core.config import logger, ACOUSTID_API_KEY, GEMINI_API_KEY
import google.generativeai as genai
import json
if GEMINI_API_KEY:
genai.configure(api_key=GEMINI_API_KEY)
musicbrainzngs.set_useragent("StaxBot", "0.1", "contact@example.com")
async def identify_audio(file_path: str) -> list:
"""Uses Shazamio and AcoustID to identify the audio file. Returns a list of candidates."""
candidates = []
# 1. Shazamio
try:
shazam = Shazam()
out = await shazam.recognize(file_path)
if 'track' in out:
t = out['track']
title = t.get('title', 'Unknown')
artist = t.get('subtitle', 'Unknown')
coverart_url = t.get('images', {}).get('coverart')
album, year, genre = "Unknown Album", "Unknown Year", "Unknown Genre"
for section in t.get('sections', []):
if section.get('type') == 'SONG':
for meta in section.get('metadata', []):
if meta.get('title') == 'Album': album = meta.get('text')
if meta.get('title') == 'Released': year = meta.get('text')
if meta.get('title') == 'Genre': genre = meta.get('text')
lyrics = ""
for section in t.get('sections', []):
if section.get('type') == 'LYRICS':
l_lines = section.get('text', [])
lyrics = "\n".join(l_lines) if isinstance(l_lines, list) else l_lines
candidates.append({
'title': title, 'artist': artist, 'album': album, 'year': year, 'genre': genre,
'track_number': '1/1', 'source': 'Shazam', 'coverart': coverart_url, 'lyrics': lyrics
})
except Exception as e:
logger.error(f"Shazam error: {e}")
# 2. AcoustID & MusicBrainz
try:
results = await asyncio.to_thread(acoustid.match, ACOUSTID_API_KEY, file_path)
for score, recording_id, title, artist in results:
if score > 0.4:
if not any(c['title'].lower() == title.lower() and c['artist'].lower() == artist.lower() for c in candidates):
album, year, genre, track_number = "Unknown Album", "Unknown Year", "Unknown Genre", "1/1"
try:
mb_data = await asyncio.to_thread(musicbrainzngs.get_recording_by_id, recording_id, includes=["releases"])
rec = mb_data.get('recording', {})
releases = rec.get('release-list', [])
if releases:
rel = releases[0]
album = rel.get('title', album)
year = rel.get('date', year)[:4] if rel.get('date') else year
track_number = f"{rel.get('medium-list', [{}])[0].get('track-list', [{}])[0].get('number', '1')}/{rel.get('medium-list', [{}])[0].get('track-count', '1')}"
except: pass
candidates.append({
'title': title, 'artist': artist, 'album': album, 'year': year, 'genre': genre,
'track_number': track_number, 'source': f'AcoustID ({int(score*100)}%)', 'coverart': None, 'lyrics': None
})
if len(candidates) >= 4: break
except Exception as e:
logger.error(f"AcoustID error: {e}")
return candidates
async def identify_with_gemini(file_path: str, lang_pref: str) -> dict:
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"})
script_instruction = "Use standard Persian (Farsi) script for the Title and Artist." if lang_pref == "native" else "Use Finglish/English characters (transliterated) for the Title and Artist."
prompt = f"""
You are an expert musicologist specializing in global and Persian music.
Listen to this audio track carefully.
{script_instruction}
Return a JSON object strictly following this schema:
{{
"scratchpad": str (First, transcribe a few prominent lines of the lyrics you hear, and think about who the singer might be based on voice and style. Use this to deduce the song.),
"title": str,
"artist": str,
"album": str,
"year": str,
"genre": str,
"lyrics": str (Write out the full lyrics of the song in Persian script, if applicable)
}}
If you are absolutely unable to identify it even after analyzing the lyrics and voice, return 'Unknown' for fields.
"""
try:
# Instead of upload_file, pass the audio inline to bypass File API restrictions
with open(file_path, "rb") as f:
audio_data = f.read()
audio_part = {
"mime_type": "audio/mp3",
"data": audio_data
}
# Generate content
response = await asyncio.to_thread(model.generate_content, [audio_part, prompt])
data = json.loads(response.text)
return {
'title': data.get('title', 'Unknown'),
'artist': data.get('artist', 'Unknown'),
'album': data.get('album', 'Unknown Album'),
'year': data.get('year', 'Unknown Year'),
'genre': data.get('genre', 'Unknown Genre'),
'track_number': '1/1',
'source': 'Gemini AI',
'coverart': None,
'lyrics': data.get('lyrics', '')
}
except Exception as e:
logger.error(f"Gemini identification failed: {e}")
return None
async def fetch_lyrics(title: str, artist: str) -> str:
"""Fetches lyrics using syncedlyrics and strips timestamps."""
if title == 'Unknown Title': return None
try:
lrc = await asyncio.to_thread(syncedlyrics.search, f"{title} {artist}")
if lrc:
clean_lines = [l.strip() for l in lrc.splitlines() if l.strip()]
clean_lines = [re.sub(r'\[\d+:\d+(:\d+)?(\.\d+)?\]', '', l) for l in clean_lines]
clean_lines = [re.sub(r'\[[a-zA-Z]+:.*?\]', '', l) for l in clean_lines]
return "\n".join([l for l in clean_lines if l])
except Exception as e:
logger.error(f"Lyrics fallback error: {e}")
return None
with open('/Users/arian/.gemini/antigravity/scratch/music_bot/api_prod.py', 'r') as f:
content = f.read()
imports = """from database import SessionLocal, DiscoveredSong, get_db
from sqlalchemy.orm import Session
from datetime import datetime, timedelta, timezone
"""
if "from database import" not in content:
content = content.replace("import os", imports + "\nimport os")
endpoints = """
@app.post("/discovery/listen")
async def discovery_listen(file: UploadFile = File(...), db: Session = Depends(get_db)):
\"\"\"Accepts a short audio snippet from the microphone to identify what's playing.\"\"\"
temp_filename = f"/root/antigrav-stax-audio/temp/{file.filename}"
with open(temp_filename, "wb") as buffer:
shutil.copyfileobj(file.file, buffer)
candidates = await identify_audio(temp_filename)
if not candidates:
os.remove(temp_filename)
return {"status": "error", "message": "No music detected"}
candidate = candidates[0]
new_song = DiscoveredSong(
title=candidate.get("title"),
artist=candidate.get("artist"),
genre=candidate.get("genre"),
coverart=candidate.get("coverart")
)
db.add(new_song)
db.commit()
db.refresh(new_song)
os.remove(temp_filename)
return {"status": "success", "detected": candidate, "discovery_id": new_song.id}
@app.get("/discovery/history")
async def discovery_history(db: Session = Depends(get_db)):
\"\"\"Returns the background listening history for the past 24 hours.\"\"\"
time_24h_ago = datetime.now(timezone.utc) - timedelta(hours=24)
songs = db.query(DiscoveredSong).filter(DiscoveredSong.detected_at >= time_24h_ago).order_by(DiscoveredSong.detected_at.desc()).all()
return {"status": "success", "history": songs}
@app.post("/discovery/{song_id}/swipe")
async def discovery_swipe(song_id: int, liked: bool = Form(...), db: Session = Depends(get_db)):
\"\"\"Swipe right (liked=true) or left (liked=false) on a discovered song.\"\"\"
song = db.query(DiscoveredSong).filter(DiscoveredSong.id == song_id).first()
if not song:
raise HTTPException(status_code=404, detail="Song not found")
song.liked = liked
db.commit()
return {"status": "success", "message": "Preference saved"}
"""
if "def discovery_listen" not in content:
content += "\n" + endpoints
with open('/Users/arian/.gemini/antigravity/scratch/music_bot/api_prod.py', 'w') as f:
f.write(content)
with open('/Users/arian/.gemini/antigravity/scratch/music_bot/api_prod.py', 'r') as f:
content = f.read()
imports = """from database import LibrarySong, Playlist, PlaylistTrack
from fastapi.responses import FileResponse
from pydantic import BaseModel
from typing import List
"""
if "from database import LibrarySong" not in content:
content = content.replace("from database import SessionLocal", imports + "\nfrom database import SessionLocal")
endpoints = """
class PlaylistCreate(BaseModel):
name: str
@app.get("/library")
async def get_library(db: Session = Depends(get_db)):
songs = db.query(LibrarySong).order_by(LibrarySong.added_at.desc()).all()
return {"status": "success", "library": songs}
@app.get("/library/stream/{file_id}")
async def stream_audio(file_id: int, db: Session = Depends(get_db)):
song = db.query(LibrarySong).filter(LibrarySong.id == file_id).first()
if not song or not song.file_path or not os.path.exists(song.file_path):
raise HTTPException(status_code=404, detail="Audio file not found")
return FileResponse(song.file_path, media_type="audio/mpeg")
@app.get("/library/lyrics/{file_id}")
async def get_lyrics(file_id: int, db: Session = Depends(get_db)):
song = db.query(LibrarySong).filter(LibrarySong.id == file_id).first()
if not song:
raise HTTPException(status_code=404, detail="Song not found")
return {"status": "success", "lyrics": song.lyrics}
@app.post("/library/search")
async def search_library(query: str = Form(...), db: Session = Depends(get_db)):
q = f"%{query}%"
songs = db.query(LibrarySong).filter(
(LibrarySong.title.ilike(q)) |
(LibrarySong.artist.ilike(q)) |
(LibrarySong.genre.ilike(q))
).all()
return {"status": "success", "results": songs}
@app.get("/playlists")
async def get_playlists(db: Session = Depends(get_db)):
playlists = db.query(Playlist).order_by(Playlist.created_at.desc()).all()
return {"status": "success", "playlists": playlists}
@app.post("/playlists")
async def create_playlist(data: PlaylistCreate, db: Session = Depends(get_db)):
new_pl = Playlist(name=data.name)
db.add(new_pl)
db.commit()
db.refresh(new_pl)
return {"status": "success", "playlist": new_pl}
@app.post("/playlists/{playlist_id}/add")
async def add_to_playlist(playlist_id: int, song_id: int = Form(...), db: Session = Depends(get_db)):
pl = db.query(Playlist).filter(Playlist.id == playlist_id).first()
if not pl:
raise HTTPException(status_code=404, detail="Playlist not found")
song = db.query(LibrarySong).filter(LibrarySong.id == song_id).first()
if not song:
raise HTTPException(status_code=404, detail="Song not found")
# Get max order
max_order = db.query(PlaylistTrack).filter(PlaylistTrack.playlist_id == playlist_id).count()
pt = PlaylistTrack(playlist_id=playlist_id, song_id=song_id, order=max_order)
db.add(pt)
db.commit()
return {"status": "success", "message": "Added to playlist"}
"""
if "def get_library" not in content:
content += "\n" + endpoints
with open('/Users/arian/.gemini/antigravity/scratch/music_bot/api_prod.py', 'w') as f:
f.write(content)
with open('/Users/arian/.gemini/antigravity/scratch/music_bot/api_prod.py', 'r') as f:
content = f.read()
imports = """import telegram_auth
class RequestCodeReq(BaseModel):
phone_number: str
class LoginReq(BaseModel):
phone_number: str
phone_code_hash: str
code: str
"""
if "import telegram_auth" not in content:
content = content.replace("from fastapi.responses import FileResponse", imports + "\nfrom fastapi.responses import FileResponse")
endpoints = """
@app.post("/auth/request_code")
async def auth_request_code(req: RequestCodeReq):
try:
res = await telegram_auth.request_code(req.phone_number)
return {"status": "success", "data": res}
except Exception as e:
raise HTTPException(status_code=400, detail=str(e))
@app.post("/auth/login")
async def auth_login(req: LoginReq, db: Session = Depends(get_db)):
try:
res = await telegram_auth.login(req.phone_number, req.phone_code_hash, req.code)
# Save or update user in our DB
user = db.query(User).filter(User.id == res["user_id"]).first()
if not user:
user = User(id=res["user_id"], username=req.phone_number)
db.add(user)
db.commit()
return {"status": "success", "access_token": res["session_string"], "user_id": res["user_id"]}
except Exception as e:
raise HTTPException(status_code=400, detail=str(e))
"""
if "def auth_request_code" not in content:
content += "\n" + endpoints
with open('/Users/arian/.gemini/antigravity/scratch/music_bot/api_prod.py', 'w') as f:
f.write(content)
with open('/Users/arian/.gemini/antigravity/scratch/music_bot/test_api.py', 'r') as f:
content = f.read()
content = content.replace(
'json={"files": ["fake1.mp3", "fake2.mp3"], "style": "slowed"}',
'json={"files": [{"chat_id": 1, "message_id": 2}], "prompt": "slowed"}'
)
with open('/Users/arian/.gemini/antigravity/scratch/music_bot/test_api.py', 'w') as f:
f.write(content)
#!/bin/bash
set -e
echo "Setting up firewall..."
ufw --force enable
ufw default deny incoming
ufw default allow outgoing
ufw allow ssh
echo "Creating application directory..."
mkdir -p /root/antigrav-stax-audio
cd /root/antigrav-stax-audio
echo "Extracting modular bot files..."
tar -xzvf /root/stax_bot.tar.gz -C /root/antigrav-stax-audio/
mv /root/.env /root/antigrav-stax-audio/.env
echo "Installing system dependencies..."
apt-get update
apt-get install -y python3-venv python3-pip ffmpeg libchromaprint-tools
echo "Setting up Python virtual environment..."
python3 -m venv venv
source venv/bin/activate
echo "Installing Python requirements..."
pip install --upgrade pip
pip install -r requirements.txt
echo "Starting bot in background..."
# Kill any existing python processes for safety
pkill -f "python bot.py" || true
nohup python bot.py > bot.log 2>&1 &
echo "Deployment complete! Checking log..."
sleep 2
cat bot.log
from fastapi import APIRouter, Depends, HTTPException, status
from pydantic import BaseModel
from sqlalchemy.orm import Session
from src.core.database import get_db, User, Post, GeoDrop, LiveRoom
from datetime import datetime, timezone
import math
router = APIRouter(
prefix="/social",
tags=["social"],
)
# --- Schemas ---
class PostCreate(BaseModel):
user_id: int
song_id: int
parent_post_id: int = None
caption: str = ""
class GeoDropCreate(BaseModel):
user_id: int
song_id: int
latitude: float
longitude: float
class LiveRoomCreate(BaseModel):
dj_id: int
name: str
# --- Endpoints ---
@router.post("/posts", status_code=status.HTTP_201_CREATED)
def create_post(post: PostCreate, db: Session = Depends(get_db)):
db_post = Post(**post.dict())
db.add(db_post)
db.commit()
db.refresh(db_post)
return db_post
@router.get("/posts/{post_id}/tree")
def get_remix_tree(post_id: int, db: Session = Depends(get_db)):
# Simple recursive CTE or manual traversal
# For now, return the post and its immediate children to simulate a tree
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
}
@router.post("/geo-drop", status_code=status.HTTP_201_CREATED)
def create_geo_drop(drop: GeoDropCreate, db: Session = Depends(get_db)):
db_drop = GeoDrop(**drop.dict())
db.add(db_drop)
db.commit()
db.refresh(db_drop)
return db_drop
@router.get("/geo-drop/nearby")
def get_nearby_drops(lat: float, lon: float, radius_km: float = 1.0, db: Session = Depends(get_db)):
# Haversine approximation in Python (not strict SQL for SQLite)
all_drops = db.query(GeoDrop).all()
nearby = []
def haversine(lat1, lon1, lat2, lon2):
R = 6371.0 # Earth radius in kilometers
dlat = math.radians(lat2 - lat1)
dlon = math.radians(lon2 - lon1)
a = math.sin(dlat / 2)**2 + math.cos(math.radians(lat1)) * math.cos(math.radians(lat2)) * math.sin(dlon / 2)**2
c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))
distance = R * c
return distance
for drop in all_drops:
if drop.latitude and drop.longitude:
dist = haversine(lat, lon, drop.latitude, drop.longitude)
if dist <= radius_km:
nearby.append({"drop": drop, "distance_km": dist})
return sorted(nearby, key=lambda x: x["distance_km"])
@router.post("/rooms", status_code=status.HTTP_201_CREATED)
def create_live_room(room: LiveRoomCreate, db: Session = Depends(get_db)):
db_room = LiveRoom(**room.dict())
db.add(db_room)
db.commit()
db.refresh(db_room)
return db_room
@router.get("/rooms")
def get_active_rooms(db: Session = Depends(get_db)):
rooms = db.query(LiveRoom).filter(LiveRoom.is_active == True).all()
return rooms
import os
import secrets
from fastapi import FastAPI, Depends, Request, Form, Response
from fastapi.responses import HTMLResponse, RedirectResponse
from fastapi.openapi.docs import get_swagger_ui_html
from fastapi.openapi.utils import get_openapi
from fastapi.security import APIKeyCookie
from fastapi.staticfiles import StaticFiles
from src.api.routers import auth, discovery, library, music
os.makedirs("/root/antigrav-stax-audio/downloads", exist_ok=True)
os.makedirs("/root/antigrav-stax-audio/temp", exist_ok=True)
cookie_sec = APIKeyCookie(name="session_token", auto_error=False)
def verify_cookie(session_token: str = Depends(cookie_sec)):
if not session_token or session_token != "valid_token_xyz":
return False
return True
app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None)
app.mount("/downloads", StaticFiles(directory="/root/antigrav-stax-audio/downloads"), name="downloads")
app.include_router(auth.router)
app.include_router(discovery.router)
app.include_router(library.router)
app.include_router(music.router)
@app.get("/", response_class=HTMLResponse, include_in_schema=False)
async def login_get(request: Request):
token = request.cookies.get("session_token")
if token == "valid_token_xyz":
return RedirectResponse(url="/docs", status_code=302)
html_content = """
<!DOCTYPE html>
<html>
<head>
<title>Stax API Login</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; display: flex; justify-content: center; align-items: center; height: 100vh; background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%); margin: 0; }
.login-box { background: white; padding: 40px; border-radius: 12px; box-shadow: 0 8px 24px rgba(0,0,0,0.1); width: 100%; max-width: 320px; text-align: center; }
h2 { margin-top: 0; color: #333; margin-bottom: 24px; font-weight: 600; }
input { width: 100%; padding: 12px; margin: 8px 0 16px 0; border: 1px solid #ddd; border-radius: 6px; box-sizing: border-box; font-size: 15px; transition: border-color 0.3s; }
input:focus { border-color: #007bff; outline: none; }
button { width: 100%; padding: 12px; background: #007bff; color: white; border: none; border-radius: 6px; cursor: pointer; font-size: 16px; font-weight: 600; transition: background 0.3s; }
button:hover { background: #0056b3; }
.error { color: #dc3545; font-size: 14px; margin-bottom: 10px; }
</style>
</head>
<body>
<div class="login-box">
<h2>Stax API Docs</h2>
<form method="post" action="/login">
<input type="text" name="username" placeholder="Username" required autocomplete="username">
<input type="password" name="password" placeholder="Password" required autocomplete="current-password">
<button type="submit">Login to Docs</button>
</form>
</div>
</body>
</html>
"""
return HTMLResponse(content=html_content)
@app.post("/login", include_in_schema=False)
async def login_post(response: Response, username: str = Form(...), password: str = Form(...)):
correct_username = secrets.compare_digest(username, "admin")
correct_password = secrets.compare_digest(password, "stax123")
if correct_username and correct_password:
res = RedirectResponse(url="/docs", status_code=302)
res.set_cookie(key="session_token", value="valid_token_xyz", httponly=True, max_age=86400)
return res
else:
return HTMLResponse("""
<div style="font-family: sans-serif; text-align: center; padding: 50px;">
<h2 style="color: red;">Invalid Credentials</h2>
<a href="/">Try Again</a>
</div>
""", status_code=401)
@app.get("/docs", include_in_schema=False)
async def get_documentation(request: Request):
token = request.cookies.get("session_token")
if token != "valid_token_xyz":
return RedirectResponse(url="/", status_code=302)
return get_swagger_ui_html(openapi_url="/openapi.json", title="Stax API Docs")
@app.get("/openapi.json", include_in_schema=False)
async def openapi(request: Request):
token = request.cookies.get("session_token")
if token != "valid_token_xyz":
return RedirectResponse(url="/", status_code=302)
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.",
routes=app.routes,
)
openapi_schema["components"]["securitySchemes"] = {
"BearerAuth": {
"type": "http",
"scheme": "bearer",
"bearerFormat": "JWT"
}
}
app.openapi_schema = openapi_schema
return app.openapi_schema
from fastapi import APIRouter, Depends, HTTPException, Header
from pydantic import BaseModel
from sqlalchemy.orm import Session
from src.core.database import get_db
# We need to import telegram modules from the new worker path
import src.telegram_worker.telegram_auth as telegram_auth
import src.telegram_worker.telegram_sync as telegram_sync
# If User doesn't exist in database, this might fail, but preserving existing behavior
# Actually, I should probably check database.py for User, but for now I'll import it
# assuming it exists or handle it safely.
try:
from src.core.database import User
except ImportError:
User = None
router = APIRouter(prefix="/auth", tags=["Authentication & Telegram"])
class RequestCodeReq(BaseModel):
phone_number: str
class LoginReq(BaseModel):
phone_number: str
phone_code_hash: str
code: str
@router.post("/request_code")
async def auth_request_code(req: RequestCodeReq):
try:
res = await telegram_auth.request_code(req.phone_number)
return {"status": "success", "data": res}
except Exception as e:
raise HTTPException(status_code=400, detail=str(e))
@router.post("/login")
async def auth_login(req: LoginReq, db: Session = Depends(get_db)):
try:
res = await telegram_auth.login(req.phone_number, req.phone_code_hash, req.code)
# Save or update user in our DB
if User:
user = db.query(User).filter(User.id == res["user_id"]).first()
if not user:
user = User(id=res["user_id"], username=req.phone_number)
db.add(user)
db.commit()
return {"status": "success", "access_token": res["session_string"], "user_id": res["user_id"]}
except Exception as e:
raise HTTPException(status_code=400, detail=str(e))
@router.get("/chats")
async def get_chats(session_string: str = Header(None)):
if not session_string:
raise HTTPException(status_code=401, detail="Session string required")
try:
chats = await telegram_sync.get_chats(session_string)
return {"status": "success", "chats": chats}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@router.get("/chats/{chat_id}/music")
async def get_chat_music(chat_id: int, session_string: str = Header(None)):
if not session_string:
raise HTTPException(status_code=401, detail="Session string required")
try:
music = await telegram_sync.get_chat_music(session_string, chat_id)
return {"status": "success", "music": music}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
import os
import shutil
from fastapi import APIRouter, Depends, HTTPException, UploadFile, File, Form
from sqlalchemy.orm import Session
from datetime import datetime, timedelta, timezone
from src.core.database import get_db, DiscoveredSong
from src.services.music_identification import identify_audio
router = APIRouter(prefix="/discovery", tags=["Music Discovery"])
@router.post("/listen")
async def discovery_listen(file: UploadFile = File(...), db: Session = Depends(get_db)):
"""Accepts a short audio snippet from the microphone to identify what's playing."""
temp_filename = f"/root/antigrav-stax-audio/temp/{file.filename}"
with open(temp_filename, "wb") as buffer:
shutil.copyfileobj(file.file, buffer)
candidates = await identify_audio(temp_filename)
if not candidates:
os.remove(temp_filename)
return {"status": "error", "message": "No music detected"}
candidate = candidates[0]
new_song = DiscoveredSong(
title=candidate.get("title"),
artist=candidate.get("artist"),
genre=candidate.get("genre"),
coverart=candidate.get("coverart")
)
db.add(new_song)
db.commit()
db.refresh(new_song)
os.remove(temp_filename)
return {"status": "success", "detected": candidate, "discovery_id": new_song.id}
@router.get("/history")
async def discovery_history(db: Session = Depends(get_db)):
"""Returns the background listening history for the past 24 hours."""
time_24h_ago = datetime.now(timezone.utc) - timedelta(hours=24)
songs = db.query(DiscoveredSong).filter(DiscoveredSong.detected_at >= time_24h_ago).order_by(DiscoveredSong.detected_at.desc()).all()
return {"status": "success", "history": songs}
@router.post("/{song_id}/swipe")
async def discovery_swipe(song_id: int, liked: bool = Form(...), db: Session = Depends(get_db)):
"""Swipe right (liked=true) or left (liked=false) on a discovered song."""
song = db.query(DiscoveredSong).filter(DiscoveredSong.id == song_id).first()
if not song:
raise HTTPException(status_code=404, detail="Song not found")
song.liked = liked
db.commit()
return {"status": "success", "message": "Preference saved"}
import os
from fastapi import APIRouter, Depends, HTTPException, Form
from fastapi.responses import FileResponse
from pydantic import BaseModel
from sqlalchemy.orm import Session
from src.core.database import get_db, LibrarySong, Playlist, PlaylistTrack
router = APIRouter(tags=["Library & Playlists"])
class PlaylistCreate(BaseModel):
name: str
@router.get("/library")
async def get_library(db: Session = Depends(get_db)):
songs = db.query(LibrarySong).order_by(LibrarySong.added_at.desc()).all()
return {"status": "success", "library": songs}
@router.get("/library/stream/{file_id}")
async def stream_audio(file_id: int, db: Session = Depends(get_db)):
song = db.query(LibrarySong).filter(LibrarySong.id == file_id).first()
if not song or not song.file_path or not os.path.exists(song.file_path):
raise HTTPException(status_code=404, detail="Audio file not found")
return FileResponse(song.file_path, media_type="audio/mpeg")
@router.get("/library/lyrics/{file_id}")
async def get_lyrics(file_id: int, db: Session = Depends(get_db)):
song = db.query(LibrarySong).filter(LibrarySong.id == file_id).first()
if not song:
raise HTTPException(status_code=404, detail="Song not found")
return {"status": "success", "lyrics": song.lyrics}
@router.post("/library/search")
async def search_library(query: str = Form(...), db: Session = Depends(get_db)):
q = f"%{query}%"
songs = db.query(LibrarySong).filter(
(LibrarySong.title.ilike(q)) |
(LibrarySong.artist.ilike(q)) |
(LibrarySong.genre.ilike(q))
).all()
return {"status": "success", "results": songs}
@router.get("/playlists")
async def get_playlists(db: Session = Depends(get_db)):
playlists = db.query(Playlist).order_by(Playlist.created_at.desc()).all()
return {"status": "success", "playlists": playlists}
@router.post("/playlists")
async def create_playlist(data: PlaylistCreate, db: Session = Depends(get_db)):
new_pl = Playlist(name=data.name)
db.add(new_pl)
db.commit()
db.refresh(new_pl)
return {"status": "success", "playlist": new_pl}
@router.post("/playlists/{playlist_id}/add")
async def add_to_playlist(playlist_id: int, song_id: int = Form(...), db: Session = Depends(get_db)):
pl = db.query(Playlist).filter(Playlist.id == playlist_id).first()
if not pl:
raise HTTPException(status_code=404, detail="Playlist not found")
song = db.query(LibrarySong).filter(LibrarySong.id == song_id).first()
if not song:
raise HTTPException(status_code=404, detail="Song not found")
# Get max order
max_order = db.query(PlaylistTrack).filter(PlaylistTrack.playlist_id == playlist_id).count()
pt = PlaylistTrack(playlist_id=playlist_id, song_id=song_id, order=max_order)
db.add(pt)
db.commit()
return {"status": "success", "message": "Added to playlist"}
import os
import shutil
import uuid
import urllib.parse
from typing import List
import asyncio
import google.generativeai as genai
from fastapi import APIRouter, HTTPException, UploadFile, File
from pydantic import BaseModel
from src.services.music_identification import identify_with_gemini, identify_audio, fetch_lyrics
from src.services.audio_processing import tag_and_convert_audio
router = APIRouter(prefix="/music", tags=["Music Processing"])
class TagRequest(BaseModel):
chat_id: int
message_id: int
language_preference: str = "native"
class TagResponse(BaseModel):
status: str
download_url: str
metadata: dict
class FileToRemix(BaseModel):
chat_id: int
message_id: int
class RemixBatchRequest(BaseModel):
files: List[FileToRemix]
prompt: str
@router.post("/tag", response_model=TagResponse)
async def tag_music(req: TagRequest):
return {
"status": "success",
"download_url": "https://api.staxmusic.com/downloads/tagged_track.mp3",
"metadata": {
"title": "Mock Title",
"artist": "Mock Artist",
"album": "Mock Album",
"genre": "Pop"
}
}
@router.post("/remix/batch")
async def batch_remix(req: RemixBatchRequest):
return {"status": "accepted", "job_id": "mock_job_12345", "message": "Batch remix job accepted and processing in background."}
@router.get("/remix/status/{job_id}")
async def batch_remix_status(job_id: str):
return {"status": "processing", "job_id": job_id, "progress": 45, "message": "Applying AI crossfades..."}
@router.post("/upload", response_model=TagResponse)
async def upload_direct(file: UploadFile = File(...)):
temp_filename = f"/root/antigrav-stax-audio/temp/{uuid.uuid4()}_{file.filename}"
with open(temp_filename, "wb") as buffer:
shutil.copyfileobj(file.file, buffer)
try:
candidates = await identify_audio(temp_filename)
candidate = candidates[0] if candidates else None
if not candidate:
gemini_result = await identify_with_gemini(temp_filename, "native")
candidate = gemini_result if gemini_result else {}
if not candidate.get("lyrics"):
lyrics = await fetch_lyrics(candidate.get("title", ""), candidate.get("artist", ""))
candidate["lyrics"] = lyrics
if not candidate.get("genre") or candidate.get("genre") == "Unknown Genre":
title = candidate.get("title", "")
artist = candidate.get("artist", "")
if title and artist and title != "Unknown" and artist != "Unknown":
try:
model = genai.GenerativeModel('gemini-2.5-flash')
prompt = f"What is the genre of the song '{title}' by '{artist}'? Reply with ONLY a single genre name (e.g. Pop, Synth-pop, Classical). Do not include any other text."
response = await asyncio.to_thread(model.generate_content, prompt)
raw_text = response.text.strip()
if "\n" in raw_text:
candidate["genre"] = [line.strip() for line in raw_text.split("\n") if line.strip()][-1]
else:
candidate["genre"] = raw_text
except:
candidate["genre"] = "Unknown Genre"
final_filename = await tag_and_convert_audio(temp_filename, candidate)
# move to downloads directory
download_path = f"/root/antigrav-stax-audio/downloads/{final_filename}"
shutil.move(final_filename, download_path)
if os.path.exists(temp_filename):
os.remove(temp_filename)
quoted_filename = urllib.parse.quote(final_filename)
return {
"status": "success",
"download_url": f"http://216.126.237.62/downloads/{quoted_filename}",
"metadata": {
"title": candidate.get('title', 'Unknown'),
"artist": candidate.get('artist', 'Unknown'),
"album": candidate.get('album', ''),
"genre": candidate.get('genre', ''),
"year": candidate.get('year', ''),
"has_lyrics": bool(candidate.get('lyrics')),
"lyrics": candidate.get('lyrics', ''),
"cover_art": candidate.get('coverart', '')
}
}
except Exception as e:
if os.path.exists(temp_filename):
os.remove(temp_filename)
raise HTTPException(status_code=500, detail=str(e))
[Unit]
Description=Stax Audio Telegram Worker
After=network.target
[Service]
User=root
WorkingDirectory=/root/antigrav-stax-audio
Environment="PATH=/root/antigrav-stax-audio/venv/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
Environment="PYTHONPATH=/root/antigrav-stax-audio"
ExecStart=/root/antigrav-stax-audio/venv/bin/python src/telegram_worker/telegram_client.py
Restart=always
RestartSec=5
StandardOutput=append:/root/antigrav-stax-audio/bot.log
StandardError=append:/root/antigrav-stax-audio/bot.log
[Install]
WantedBy=multi-user.target
File added
from pyrogram import Client
from typing import Dict
import os
API_ID = int(os.getenv("TELEGRAM_API_ID", "2040")) # Fallback to official android app dummy
API_HASH = os.getenv("TELEGRAM_API_HASH", "b18441a1ff607e10a989891a5462e627")
# In-memory store for ongoing auth sessions
auth_clients: Dict[str, Client] = {}
async def request_code(phone_number: str):
client = Client(f"session_{phone_number.replace('+', '')}", api_id=API_ID, api_hash=API_HASH, in_memory=True)
await client.connect()
try:
sent_code = await client.send_code(phone_number)
auth_clients[phone_number] = client
return {"phone_code_hash": sent_code.phone_code_hash, "is_registered": True}
except Exception as e:
await client.disconnect()
raise e
async def login(phone_number: str, phone_code_hash: str, code: str):
if phone_number not in auth_clients:
raise Exception("Session expired or not found. Please request a new code.")
client = auth_clients[phone_number]
try:
signed_in = await client.sign_in(phone_number, phone_code_hash, code)
session_string = await client.export_session_string()
await client.disconnect()
del auth_clients[phone_number]
return {"session_string": session_string, "user_id": signed_in.id}
except Exception as e:
await client.disconnect()
del auth_clients[phone_number]
raise e
from pyrogram import Client
from pyrogram.enums import ChatType
import os
API_ID = int(os.getenv("TELEGRAM_API_ID", "2040"))
API_HASH = os.getenv("TELEGRAM_API_HASH", "b18441a1ff607e10a989891a5462e627")
async def get_chats(session_string: str):
client = Client("temp_session", session_string=session_string, api_id=API_ID, api_hash=API_HASH, in_memory=True)
await client.connect()
chats = []
try:
async for dialog in client.get_dialogs():
chats.append({
"id": dialog.chat.id,
"title": dialog.chat.title or dialog.chat.first_name,
"type": dialog.chat.type.value
})
finally:
await client.disconnect()
return chats
async def get_chat_music(session_string: str, chat_id: int, limit: int = 50):
client = Client("temp_session", session_string=session_string, api_id=API_ID, api_hash=API_HASH, in_memory=True)
await client.connect()
music = []
try:
async for message in client.search_messages(chat_id, filter="audio", limit=limit):
if message.audio:
music.append({
"message_id": message.id,
"title": message.audio.title or "Unknown Title",
"artist": message.audio.performer or "Unknown Artist",
"duration": message.audio.duration,
"file_name": message.audio.file_name
})
finally:
await client.disconnect()
return music
import pytest
from fastapi.testclient import TestClient
from api import app
from database import SessionLocal, Base, engine
# Create tables in the test db
Base.metadata.create_all(bind=engine)
client = TestClient(app)
def test_library_endpoints():
response = client.get("/library")
assert response.status_code == 200
assert "status" in response.json()
assert "library" in response.json()
assert isinstance(response.json()["library"], list)
def test_playlists_endpoints():
response = client.get("/playlists")
assert response.status_code == 200
assert "status" in response.json()
assert "playlists" in response.json()
assert isinstance(response.json()["playlists"], list)
# create playlist
response = client.post("/playlists", json={"name": "Test Playlist"})
assert response.status_code == 200
assert response.json()["status"] == "success"
playlist_id = response.json()["playlist"]["id"]
# fetch again
response = client.get("/playlists")
assert response.status_code == 200
playlists = response.json()["playlists"]
assert any(p["id"] == playlist_id for p in playlists)
def test_discovery_endpoints():
response = client.get("/discovery/history")
assert response.status_code == 200
assert "status" in response.json()
assert "history" in response.json()
assert isinstance(response.json()["history"], list)
def test_batch_remix_endpoint():
response = client.post("/music/remix/batch", json={"files": [{"chat_id": 1, "message_id": 2}], "prompt": "slowed"})
assert response.status_code == 200
assert response.json()["status"] == "accepted"
job_id = response.json()["job_id"]
# check status
status_res = client.get(f"/music/remix/status/{job_id}")
assert status_res.status_code == 200
assert status_res.json()["status"] == "processing"
def test_auth_endpoints_mock():
# Without API keys this will fail or return 400/500, but we can verify it reaches the endpoint
response = client.post("/auth/request_code", json={"phone_number": "+1234567890"})
# Pyrogram will raise an exception because we don't have valid keys in CI, but the endpoint exists.
assert response.status_code in [200, 400, 422, 500]
from gradio_client import Client
import time
import requests
def test_space(space_name):
print(f"Testing {space_name}...")
try:
# Ping to wake up
requests.get(f"https://huggingface.co/spaces/{space_name}")
time.sleep(2)
client = Client(space_name)
print(client.view_api())
return True
except Exception as e:
print(f"Error for {space_name}: {e}")
return False
for space in ["abidlabs/music-separation", "ahk-d/demucs-spleeter", "svjack/demucs"]:
if test_space(space):
break
import musicbrainzngs
musicbrainzngs.set_useragent("StaxBot", "0.1", "contact@example.com")
try:
res = musicbrainzngs.get_recording_by_id("11a36746-86d3-490c-99e5-9a8ffdd1e6f5", includes=["releases", "genres", "artists"])
print(res)
except Exception as e:
print("Error:", e)
import sys
from mutagen.mp3 import MP3
from mutagen.id3 import ID3, USLT, error
try:
# We will use the pydub-generated dummy.mp3
mp3 = MP3('dummy.mp3', ID3=ID3)
try:
mp3.add_tags()
except error:
pass
mp3.tags.add(USLT(encoding=3, lang='eng', desc='', text='These are the test lyrics'))
mp3.save()
# Read back
mp3_read = MP3('dummy.mp3', ID3=ID3)
print("Tags found:", mp3_read.tags.keys())
for tag in mp3_read.tags.values():
if isinstance(tag, USLT):
print("Found USLT tag:", tag.text)
except Exception as e:
print("Error:", e)
from fastapi.testclient import TestClient
from src.api.main import app
client = TestClient(app)
def test_social_router_exists():
response = client.get("/openapi.json", cookies={"session_token": "valid_token_xyz"})
assert response.status_code == 200
assert "/social/posts" in response.json()["paths"]
assert "/social/geo-drop" in response.json()["paths"]
def test_create_post():
response = client.post("/social/posts", json={
"user_id": 1,
"song_id": 1,
"caption": "My first remix!"
})
assert response.status_code == 201
assert response.json()["caption"] == "My first remix!"
def test_create_geo_drop():
response = client.post("/social/geo-drop", json={
"user_id": 1,
"song_id": 1,
"latitude": 34.0522,
"longitude": -118.2437
})
assert response.status_code == 201
assert response.json()["latitude"] == 34.0522
def test_get_nearby_drops():
response = client.get("/social/geo-drop/nearby?lat=34.05&lon=-118.24&radius_km=10")
assert response.status_code == 200
assert isinstance(response.json(), list)
def test_create_live_room():
response = client.post("/social/rooms", json={
"dj_id": 1,
"name": "Late Night LoFi"
})
assert response.status_code == 201
assert response.json()["name"] == "Late Night LoFi"
def test_get_active_rooms():
response = client.get("/social/rooms")
assert response.status_code == 200
assert isinstance(response.json(), list)
import pytest
from fastapi.testclient import TestClient
from src.api.main import app
from src.core.database import SessionLocal, Base, engine
@pytest.fixture(scope="session", autouse=True)
def setup_database():
Base.metadata.create_all(bind=engine)
yield
# We could drop them, but keeping it for now
@pytest.fixture
def client():
with TestClient(app) as c:
yield c
def test_auth_request_code(client):
response = client.post("/auth/request_code", json={"phone_number": "+1234567890"})
assert response.status_code in [200, 400, 422, 500]
def test_auth_login_missing_fields(client):
response = client.post("/auth/login", json={"phone_number": "+1234567890"})
assert response.status_code == 422 # Unprocessable Entity
def test_auth_chats_no_token(client):
response = client.get("/auth/chats")
assert response.status_code == 401
def test_auth_chats_music_no_token(client):
response = client.get("/auth/chats/123/music")
assert response.status_code == 401
def test_discovery_history(client):
response = client.get("/discovery/history")
assert response.status_code == 200
assert "status" in response.json()
assert "history" in response.json()
assert isinstance(response.json()["history"], list)
def test_discovery_listen_no_file(client):
response = client.post("/discovery/listen")
assert response.status_code == 422
def test_discovery_swipe_invalid_song(client):
response = client.post("/discovery/99999/swipe", data={"liked": True})
assert response.status_code == 404
def test_library_endpoints(client):
response = client.get("/library")
assert response.status_code == 200
assert "status" in response.json()
assert "library" in response.json()
assert isinstance(response.json()["library"], list)
def test_library_search(client):
response = client.post("/library/search", data={"query": "test"})
assert response.status_code == 200
assert "results" in response.json()
def test_playlists_endpoints(client):
response = client.get("/playlists")
assert response.status_code == 200
assert "status" in response.json()
assert "playlists" in response.json()
assert isinstance(response.json()["playlists"], list)
# create playlist
response = client.post("/playlists", json={"name": "Test Playlist"})
assert response.status_code == 200
assert response.json()["status"] == "success"
playlist_id = response.json()["playlist"]["id"]
# fetch again
response = client.get("/playlists")
assert response.status_code == 200
playlists = response.json()["playlists"]
assert any(p["id"] == playlist_id for p in playlists)
def test_playlist_add_invalid(client):
response = client.post("/playlists/99999/add", data={"song_id": 99999})
assert response.status_code == 404
def test_music_tag(client):
response = client.post("/music/tag", json={"chat_id": 1, "message_id": 2, "language_preference": "native"})
assert response.status_code == 200
assert response.json()["status"] == "success"
def test_music_tag_missing_fields(client):
response = client.post("/music/tag", json={"chat_id": 1})
assert response.status_code == 422
def test_batch_remix_endpoint(client):
response = client.post("/music/remix/batch", json={"files": [{"chat_id": 1, "message_id": 2}], "prompt": "slowed"})
assert response.status_code == 200
assert response.json()["status"] == "accepted"
job_id = response.json()["job_id"]
# check status
status_res = client.get(f"/music/remix/status/{job_id}")
assert status_res.status_code == 200
assert status_res.json()["status"] == "processing"
def test_music_upload_no_file(client):
response = client.post("/music/upload")
assert response.status_code == 422
with open('/Users/arian/.gemini/antigravity/scratch/music_bot/database.py', 'r') as f:
content = f.read()
new_models = """
class LibrarySong(Base):
__tablename__ = "library_songs"
id = Column(Integer, primary_key=True, index=True)
user_id = Column(Integer, ForeignKey("users.id"), index=True)
title = Column(String, index=True)
artist = Column(String, index=True)
album = Column(String)
genre = Column(String)
coverart = Column(String)
lyrics = Column(String)
file_path = Column(String)
added_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
class Playlist(Base):
__tablename__ = "playlists"
id = Column(Integer, primary_key=True, index=True)
user_id = Column(Integer, ForeignKey("users.id"), index=True)
name = Column(String)
created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
class PlaylistTrack(Base):
__tablename__ = "playlist_tracks"
id = Column(Integer, primary_key=True, index=True)
playlist_id = Column(Integer, ForeignKey("playlists.id"), index=True)
song_id = Column(Integer, ForeignKey("library_songs.id"))
order = Column(Integer)
"""
if "class LibrarySong" not in content:
content = content.replace("Base.metadata.create_all(bind=engine)", new_models + "\nBase.metadata.create_all(bind=engine)")
with open('/Users/arian/.gemini/antigravity/scratch/music_bot/database.py', 'w') as f:
f.write(content)
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