Files
KeySelector/README.md
T

207 lines
12 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<p align="center">
<img src="public/favicon.png" alt="KeySelector Logo" width="128" />
</p>
<h1 align="center">KeySelector</h1>
<p align="center"><strong>A browser-based harmonic DJ assistant with live audio recognition, interactive Camelot Wheel, and PostgreSQL track catalog.</strong></p>
<p align="center">
<a href="README.md">🇬🇧 English</a> · <a href="LIESMICH.md">🇩🇪 Deutsch</a>
</p>
---
## Overview
**KeySelector** is a lightweight, local-first web application designed for DJs to identify currently playing tracks, inspect their musical key (in **Camelot** and standard musical notation) and **BPM**, and immediately discover harmonically and rhythmically compatible follow-up tracks.
```text
┌───────────────────────────┐ HTTP / REST ┌──────────────────────────────┐
│ Browser (Vanilla JS SPA) │ ◄───────────────────► │ Node.js / Express (:3000) │
│ • System / Mic Capture │ │ • /api/recognize (ACR/AudD) │
│ • Interactive SVG Wheel │ │ • /api/metadata (ffmpeg) │
│ • Live Search & Filters │ │ • /api/suggestions │
└───────────────────────────┘ │ • /api/search, /cover │
└──────────────┬───────────────┘
│ pg Pool
┌──────────────▼───────────────┐
│ PostgreSQL (26,000+ tracks) │
│ + In-Memory Fallback │
└──────────────────────────────┘
```
---
## Features
- **Live Audio Recognition (`POST /api/recognize`):** Captures **PC / System Audio** (via `getDisplayMedia` for VLC, DJ software, browser tabs, YouTube), **Room Microphone**, or a **specific audio input device**, includes a live input level meter, and identifies songs via **ACRCloud** or **AudD**.
- **Multi-Source Metadata & Audio Analysis (`GET /api/metadata`):** Resolves key, BPM, genre tags, duration, cover art, and 30-second audio previews using PostgreSQL lookup (exact + fuzzy matching), **Deezer API**, **SongBPM**, **GetSongBPM**, **Last.fm**, and built-in **FFmpeg** preview audio analysis (BPM onset autocorrelation + Goertzel chroma key detection).
- **Harmonic Mixing Suggestions (`GET /api/suggestions`):** Applies Mixed In Key / Camelot compatibility rules (`Perfect`, `Quinte -1`, `Quinte +1`, `Energy`, `Scale`, `Diagonal`, `Jaw's`, `Mood`) with progressive BPM tolerance widening (`±6%`, `±12%`, `±20%`, up to `50–220 BPM`) and UI filters for Mix Type and Pitch Tolerance (`±4% (DJ)`, `±8%`, `All BPM`).
- **Interactive Camelot Wheel (`public/wheel.js`):** Renders a 24-segment SVG Camelot Wheel (outer `B` Major ring, inner `A` Minor ring) that highlights compatible keys and expands inline on click.
- **Live Hybrid Search (`GET /api/search`):** Searches local PostgreSQL tracks first and merges live results from the **Deezer Search API** with 30-second audio previews and quick links to Spotify, Deezer, and YouTube.
- **Persistent Key & BPM Corrections (`POST /api/tracks/correct`):** Click on the Key or BPM stat card to correct values in a modal; corrections are saved with `is_corrected = TRUE` in PostgreSQL and take precedence in future lookups.
- **Audio Attributes & Cover Zoom:** Displays Tunebat-style attributes (Duration, Energy, Danceability, Mood) and supports inline cover expansion and 30-second preview playback.
- **Dark / Light Theme:** Instant theme switching via CSS custom properties.
- **26,000+ Track Catalog Seed:** Automatically seeds curated Camelot reference tracks (`db/schema.sql`) and imports `db/spotify_songs.csv` (`server/importer.js`) on startup when the database has fewer than 5,000 tracks.
---
## How It Works & Tech Stack
The frontend (`public/`) requires **no build step** and is served statically alongside `/shared` modules by Express (`server/index.js`). Shared JavaScript files in `shared/` work identically in both Node.js (`require`) and the browser (`window.*`) to guarantee consistent Camelot geometry, colors, and mixing rules. If PostgreSQL is unavailable at startup, `server/db.js` automatically falls back to an in-memory `Map`.
| Component | Technology / Details |
|---|---|
| Frontend | Vanilla HTML5, CSS3 (Custom Properties), JavaScript (`public/`) |
| Backend | Node.js 22 (`node:22-alpine` in Docker), Express `^4.18.2`, Multer `^2.2.0`, Axios `^1.19.0` |
| Audio Processing | `ffmpeg` & `chromaprint` (installed in Docker image), custom PCM BPM & key analyzer |
| Database | PostgreSQL (`postgres:15-alpine`, `pg` `^8.23.0`) with in-memory fallback |
| External APIs | ACRCloud, AudD, Deezer, SongBPM, GetSongBPM, Last.fm, iTunes Search API |
| Ports | Backend listens on `3000` (mapped to `3030:3000` in `docker-compose.yml`); PostgreSQL on `5432` |
---
## Prerequisites & Installation
### Prerequisites
- **Docker & Docker Compose** (recommended, includes PostgreSQL, `ffmpeg`, and `chromaprint`), **or**
- **Node.js** (18/22+), **PostgreSQL**, and **`ffmpeg`** in `PATH` for local execution
### Local Installation
1. Clone the repository:
```bash
git clone https://git.orfel.de/Jannik/KeySelector.git
cd KeySelector
```
2. Copy `.env.example` to `.env` (or `server/.env`) and configure your database and API keys:
```bash
cp .env.example server/.env
```
3. Install backend dependencies and start the server:
```bash
cd server
npm install
npm start
```
4. Open `http://localhost:3000` in your browser.
### Docker & Production Setup
Start both the KeySelector app and PostgreSQL database via Docker Compose:
```bash
docker compose up -d --build
```
The web UI will be available at `http://localhost:3030` (container port `3000`).
In **Jannik-Cloud**, KeySelector runs as an integrated service under `keyselector.orfel.de` (configured in the central infrastructure repo under `services/keyselector`).
---
## Configuration
Environment variables defined in `.env.example`, `docker-compose.yml`, and `server/`:
| Variable | Default | Description |
|---|---|---|
| `PORT` | `3000` | Port Express listens on inside the container / locally |
| `DATABASE_URL` | — | Optional full PostgreSQL connection string (overrides `DB_*` vars) |
| `DB_HOST` | `localhost` (`postgres` in Compose) | PostgreSQL host |
| `DB_PORT` | `5432` | PostgreSQL port |
| `DB_USER` | `postgres` | PostgreSQL user |
| `DB_PASSWORD` | `postgres` | PostgreSQL password |
| `DB_NAME` | `keyselector` | PostgreSQL database name |
| `ACRCLOUD_HOST` | `identify-eu-west-1.acrcloud.com` | ACRCloud identification host |
| `ACRCLOUD_ACCESS_KEY` | — | ACRCloud project access key |
| `ACRCLOUD_ACCESS_SECRET` | — | ACRCloud project access secret |
| `ACRCLOUD_CONSOLE_TOKEN` | — | Optional ACRCloud console token in `.env.example` |
| `AUDD_API_TOKEN` | — | AudD API token (`AUDD_API_KEY` also accepted as fallback) |
| `GETSONGBPM_API_KEY` | — | Optional GetSongBPM API key for key/BPM lookups |
| `LASTFM_API_KEY` | — | Optional Last.fm API key for genre tag enrichment |
| `MINIMAX_API_KEY` | — | Optional MiniMax key listed in `.env.example` / `docker-compose.yml` |
| `NTFY_URL` | — | Optional ntfy endpoint used by `server/workers/poll-quota.js` |
### Volumes
- `pgdata:/var/lib/postgresql/data` (in `docker-compose.yml`) persists the PostgreSQL track catalog and user corrections.
---
## Usage
### Web UI Workflow
1. **Audio Recognition:** Select an audio source in the top bar (**System Audio**, **Microphone**, or **Specific Device**) and click the microphone status badge (`Bereit`) to start or pause listening. Note: For System Audio, check **"Share audio"** in the browser's screen/tab picker.
2. **Manual Search:** Type an artist or track title in the search bar to query the local catalog and Deezer simultaneously.
3. **Inspect & Play:** Click the album cover to zoom in, click the play icon on the cover for a 30-second audio preview, or click the Camelot Wheel in the bottom-right of the hero card to expand it full-size.
4. **Correct Key / BPM:** Click the **Key** or **BPM** stat box to open the correction modal and save verified values to PostgreSQL.
5. **Filter Follow-Up Tracks:** Use the **Mix** pills (`Alle`, `Exakt`, `Quinte (±1)`, `Relativ (A↔B)`, `Energy (+2)`) and **Pitch** pills (`±4% (DJ)`, `±8%`, `Alle BPM`) above the suggestions grid.
### API Endpoints
| Method & Path | Description |
|---|---|
| `POST /api/recognize` | Accepts `multipart/form-data` (`audio` file), identifies via ACRCloud/AudD, enriches from DB |
| `GET /api/metadata?track=...&artist=...` | Resolves Camelot key, BPM, cover, preview URL, tags & audio features |
| `GET /api/suggestions?key=4B&bpm=120&artist=...&title=...` | Returns harmonically compatible tracks sorted by compatibility level |
| `GET /api/search?q=...` | Searches local PostgreSQL + Deezer API |
| `POST /api/tracks/correct` | Saves manual `artist`, `title`, `camelotKey`, `bpm` corrections (`is_corrected = TRUE`) |
| `GET /api/cover?q=...` | Proxies iTunes Search API for `300x300` album artwork |
---
## Project Structure
```text
KeySelector/
├── db/
│ ├── schema.sql # PostgreSQL schema + 24-key curated seed tracks
│ ├── seed-acousticbrainz.sh # Placeholder/mock AcousticBrainz seed script
│ └── spotify_songs.csv # 26,000+ track catalog auto-imported on init
├── docs/
│ ├── Camelot-Wheel-Chart.png
│ ├── Camelot-Wheel-Mixed-In-Key-Harmonic-Mixing.png
│ └── KeySelector_SPEC.md # Original design specification
├── public/
│ ├── app.js # Audio capture, UI state & API orchestration
│ ├── cover.js # Album cover loading & zoom toggle
│ ├── favicon.png
│ ├── index.html # Single-page frontend
│ ├── search.js # Live search dropdown & Deezer integration
│ ├── styles.css # Dark/Light theme styling
│ └── wheel.js # Interactive 24-segment SVG Camelot Wheel
├── server/
│ ├── routes/
│ │ ├── cover.js # iTunes cover proxy
│ │ ├── metadata.js # Multi-source metadata + ffmpeg audio analyzer
│ │ ├── recognize.js # ACRCloud & AudD audio recognition
│ │ ├── search.js # Local DB + Deezer hybrid search
│ │ ├── suggestions.js # Camelot harmonic matching engine
│ │ └── tracks.js # User key/BPM correction endpoint
│ ├── workers/
│ │ └── poll-quota.js # Daily quota check stub (ntfy)
│ ├── db.js # PostgreSQL pool, schema init & in-memory fallback
│ ├── importer.js # Bulk CSV catalog importer
│ ├── index.js # Express app entrypoint
│ └── package.json
├── shared/
│ ├── camelot-angle.js # Camelot code to SVG angle mapping
│ ├── camelot-to-musickey.js # Camelot to standard musical key mapping
│ ├── color-matrix.js # Camelot color palette
│ └── mixing-rules.js # Mixed In Key compatibility rules & labels
├── .env.example
├── docker-compose.yml
├── Dockerfile
├── LIESMICH.md
└── README.md
```
---
## License
Private / Internal Project.