Commit eef79169 authored by Aryan Noshirvani's avatar Aryan Noshirvani

Reorganize into a modular src/ layout, remove dead legacy files

- Delete 18 files fully superseded by src/ (api_new/prod/remote*.py,
  root config/database/audio_processing/music_identification/
  telegram_auth/telegram_sync/social.py duplicates, broken patch_*.py
  and update_database.py debug scripts that reference a nonexistent
  Mac path, dead test_api.py/test_gradio.py, and the redundant
  stax_bot.tar.gz backup of the same dead files)
- Relocate bot.py + ai_remix.py into a new src/telegram_bot/ package
  and fix their imports to use src.core/src.services (the Telegram
  bot isn't wired into the live FastAPI app, but it's real unshipped
  functionality, not cruft - kept it, not deleted it)
- Move one-off dev scripts (list_models.py, build_loops.py, and the
  manual smoke scripts test_mb.py/test_mutagen.py) into scripts/,
  renaming the smoke scripts so pytest's default test_*.py discovery
  never sweeps them up outside tests/
- Fold the misplaced-but-real test_social.py into tests/ (6 passing
  tests that weren't part of the actual suite)
- Move stax_bot.service into deploy/systemd/ and fix its ExecStart
  (was pointing at a nonexistent telegram_client.py under a stale
  antigrav-stax-audio path)
- Add .gitignore; untrack .env going forward (secrets remain in prior
  history - flagged separately, not rewritten here)
- Rewrite README.md and setup.sh, which described/depended on the old
  flat api.py/bot.py architecture and the deleted tarball

Full suite: 21/21 passing (up from 15 - gained test_social.py's 6).
Live stax_backend service on this host untouched: same src/api/main.py
entrypoint, same .env/stax.db on disk, still responding through the
reorg.
Co-Authored-By: 's avatarClaude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BCxXmJVvDFJVHTUi4QgNzi
parent 2df04b6a
TELEGRAM_BOT_TOKEN=your_telegram_bot_token_here TELEGRAM_BOT_TOKEN=your_telegram_bot_token_here
ACOUSTID_API_KEY=your_acoustid_api_key_here
GEMINI_API_KEY=your_gemini_api_key_here
# Optional, used by src/telegram_bot (stem separation feature)
LALAL_API_KEY=your_lalal_api_key_here
# Python
__pycache__/
*.pyc
.pytest_cache/
venv/
*.egg-info/
# Secrets
.env
# Runtime data
*.db
*.log
# OS
.DS_Store
# Stax Audio Beta API # Stax Backend 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. Backend for Stax: a music tagging, playback, and social discovery platform. Users upload
unorganized/untagged audio, the API identifies it (Shazam/AcoustID, with a Gemini fallback),
fetches lyrics and album art, and tags the file. Social features (channels, remix trees,
live listening rooms, geo-tagged drops) build on top of that library.
## Overview ## Architecture
Stax Audio offers users a rich music experience by leveraging their existing Telegram chats. Key features include: All application code lives under `src/`, organized by responsibility:
- **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. src/
- **Library & Playlists:** Add discovered and synced songs to a global library and organize them into custom playlists. ├── api/ # FastAPI app
- **Background Discovery:** Continuously log ambient music (kept for 24 hours) allowing users to swipe through tracks they want to keep. │ ├── main.py # App entrypoint (mounted routers, docs auth)
- **AI Batch Remixing:** Select multiple tracks from your chats/library and automatically apply AI-driven audio styles (e.g., slowed, reverb, trap). │ └── routers/ # auth, discovery, library, music, social
├── core/ # config.py (env vars), database.py (SQLAlchemy models)
├── services/ # audio_processing.py, music_identification.py
├── telegram_worker/ # Telegram auth/session helpers used by the API (linking a Telegram account)
└── telegram_bot/ # Standalone Telegram conversational bot + AI remix engine (not wired
# into the FastAPI app; run separately, see Services below)
scripts/ # One-off dev utilities, not part of the app
├── list_gemini_models.py
├── build_loops.py
└── dev_smoke/ # Manual smoke-test scripts (not part of the pytest suite)
tests/ # pytest suite (run via `pytest tests/`)
deploy/systemd/ # systemd unit file references
```
## Architecture ## Services
The backend consists of two primary services running side-by-side: Two independent processes make up the backend:
1. **FastAPI Web Service (`api.py`)** 1. **FastAPI web service** (`src/api/main.py`) — REST API, serves `/downloads`, runs via
- Serves the frontend (mobile/web apps). `uvicorn src.api.main:app` on port 8000. Deployed as the `stax_backend` systemd service.
- Handles RESTful routing, authentication (`Pyrogram` based), database models (`SQLAlchemy`), and background task delegation. 2. **Telegram bot** (`src/telegram_bot/bot.py`) — a conversational Telegram bot for tagging
- Runs via `uvicorn` on port 8000. and AI remixing directly from chat. **Not currently deployed** — see note below.
2. **Telegram Userbot / Downloader (`bot.py` / `audio_processing.py`)** > **Known issue:** `src/telegram_bot/bot.py` calls `init_db` and `log_correction` from
- Interacts heavily with the Telegram API to intercept audio messages and download raw files. > `src.core.database`, but neither function exists there (this predates the folder
- Handles AI-powered audio manipulation (`pydub`) and generates remixes. > reorganization — the functions were never defined even in the original flat-file layout).
> The bot will not start until this is implemented or the calls are removed. Flagging this
> here rather than silently fixing it, since it changes behavior beyond a structural cleanup.
## Setup & Configuration ## Setup & Configuration
...@@ -32,51 +51,44 @@ The backend consists of two primary services running side-by-side: ...@@ -32,51 +51,44 @@ The backend consists of two primary services running side-by-side:
- FFmpeg (required for `pydub` and audio conversion) - FFmpeg (required for `pydub` and audio conversion)
### Installation ### Installation
1. Clone the repository and navigate into it. ```bash
2. Create and activate a virtual environment: python3 -m venv venv
```bash source venv/bin/activate
python3 -m venv venv pip install -r requirements.txt
source venv/bin/activate ```
```
3. Install the dependencies:
```bash
pip install -r requirements.txt
```
### Environment Variables (`.env`) ### Environment Variables (`.env`)
Create a `.env` file in the root directory. You will need: Copy `.env.example` to `.env` and fill in:
- `TELEGRAM_API_ID`: Your Telegram API ID. - `TELEGRAM_BOT_TOKEN` — Telegram bot token (for `src/telegram_bot`)
- `TELEGRAM_API_HASH`: Your Telegram API Hash. - `ACOUSTID_API_KEY` — audio fingerprinting
- `GEMINI_API_KEY`: API key for Gemini fallback operations. - `GEMINI_API_KEY` — Gemini fallback identification/remix recipes
- `DATABASE_URL`: Defaults to `sqlite:///./music.db`. - `LALAL_API_KEY` — optional, stem separation in the Telegram bot
`.env` is gitignored and must never be committed.
### Database ### Database
The API uses SQLite by default. When the application starts, `SQLAlchemy` will automatically generate the required tables (`LibrarySong`, `Playlist`, `PlaylistTrack`, etc.). SQLite by default (`stax.db`, gitignored). SQLAlchemy creates tables automatically on startup
from the models in `src/core/database.py`.
## Running the Application ## Running the Application
### Locally (Development) ### Locally (development)
```bash ```bash
uvicorn api:app --host 0.0.0.0 --port 8000 --reload uvicorn src.api.main:app --host 0.0.0.0 --port 8000 --reload
``` ```
### Production (systemd) ### 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 ```bash
sudo journalctl -u stax_api -f sudo systemctl restart stax_backend
sudo journalctl -u stax_backend -f
``` ```
## Testing ## Testing
We use `pytest` alongside `httpx` to validate our endpoints:
```bash ```bash
pytest test_api.py pytest tests/
``` ```
This ensures the primary CRUD logic and AI batch queuing remain stable. CI (`.gitlab-ci.yml`) runs this on every push to `main` and on merge requests.
## Contributing ## Contributing
We develop on the `dev` branch. Features are merged into `main` once they pass automated testing and manual review. We develop on the `dev` branch. Features are merged into `main` once they pass automated
testing and manual review.
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": ""
}
}
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
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 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 = os.getenv("DATABASE_URL", "sqlite:///./stax.db")
db_dir = os.path.dirname(DATABASE_URL.replace("sqlite:///", ""))
if db_dir and not os.path.exists(db_dir):
os.makedirs(db_dir, exist_ok=True)
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 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 #!/bin/bash
# Fresh-VPS bootstrap for the Stax backend. Not used by CI/CD (see .gitlab-ci.yml's
# deploy_prod job, which does a git pull + pip install + systemctl restart on an
# already-provisioned host) — this is for setting up a brand new server from scratch.
set -e set -e
echo "Setting up firewall..." echo "Setting up firewall..."
...@@ -6,14 +9,7 @@ ufw --force enable ...@@ -6,14 +9,7 @@ ufw --force enable
ufw default deny incoming ufw default deny incoming
ufw default allow outgoing ufw default allow outgoing
ufw allow ssh ufw allow ssh
ufw allow 8000
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..." echo "Installing system dependencies..."
apt-get update apt-get update
...@@ -27,11 +23,15 @@ echo "Installing Python requirements..." ...@@ -27,11 +23,15 @@ echo "Installing Python requirements..."
pip install --upgrade pip pip install --upgrade pip
pip install -r requirements.txt pip install -r requirements.txt
echo "Starting bot in background..." if [ ! -f .env ]; then
# Kill any existing python processes for safety echo "No .env found - copy .env.example to .env and fill in your API keys before starting the app."
pkill -f "python bot.py" || true exit 1
nohup python bot.py > bot.log 2>&1 & fi
echo "Starting FastAPI backend in background..."
pkill -f "uvicorn src.api.main:app" || true
PYTHONPATH=. nohup venv/bin/uvicorn src.api.main:app --host 0.0.0.0 --port 8000 > backend.log 2>&1 &
echo "Deployment complete! Checking log..." echo "Deployment complete! Checking log..."
sleep 2 sleep 2
cat bot.log cat backend.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
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
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