shalinx 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,11 @@
1
+ .venv/
2
+ __pycache__/
3
+ *.py[cod]
4
+ .pytest_cache/
5
+ .coverage
6
+ .env
7
+ *.db
8
+ *.sqlite*
9
+ build/
10
+ dist/
11
+ *.egg-info/
shalinx-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,59 @@
1
+ Metadata-Version: 2.5
2
+ Name: shalinx
3
+ Version: 0.1.0
4
+ Summary: Recognize music playing on a Linux desktop
5
+ Project-URL: Source, https://github.com/ljbuturovic/Shalinx
6
+ Classifier: Environment :: X11 Applications :: Qt
7
+ Classifier: Intended Audience :: End Users/Desktop
8
+ Classifier: Operating System :: POSIX :: Linux
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: Topic :: Multimedia :: Sound/Audio
11
+ Requires-Python: >=3.10
12
+ Requires-Dist: pyside6<7,>=6.6
13
+ Description-Content-Type: text/markdown
14
+
15
+ # Shalinx
16
+
17
+ Shalinx identifies music playing through your Linux desktop output. It records ten seconds from the default output monitor, asks AudD to identify the song, and saves successful matches locally.
18
+
19
+ ## Requirements
20
+
21
+ - Linux with PipeWire's PulseAudio compatibility or PulseAudio
22
+ - `ffmpeg` and `pactl` available on `PATH`
23
+ - Python 3.11 or newer and `pipx`
24
+ - An AudD API token
25
+
26
+ ## Install and launch
27
+
28
+ Install from PyPI after a release is published:
29
+
30
+ ```bash
31
+ pipx install shalinx
32
+ export AUDD_API_TOKEN='your-token-here'
33
+ shalinx
34
+ ```
35
+
36
+ To install directly from a local checkout instead:
37
+
38
+ ```bash
39
+ cd ~/github/Shalinx
40
+ pipx install .
41
+ ```
42
+
43
+ If `shalinx` is not found after installation, run `pipx ensurepath` and start a new shell. The `AUDD_API_TOKEN` environment variable must be available when you launch the app.
44
+
45
+ Play a song through the computer's default audio output, then click **Identify song**. The app records the output monitor, not the microphone. It opens song links with your default browser. Click the trash icon beside a history entry to remove it after confirmation.
46
+
47
+ History rows show cover thumbnails from AudD's song links when available, including for previously saved matches. Artwork loads in the background and is cached under `${XDG_CACHE_HOME:-~/.cache}/shalinx/artwork`.
48
+
49
+ History is stored in `${XDG_DATA_HOME:-~/.local/share}/shalinx/history.sqlite3`. The AudD token is read from the environment and is never stored in the database. The database does store AudD's full response metadata for successful matches.
50
+
51
+ ## Development and offline tests
52
+
53
+ ```bash
54
+ uv venv .venv --python 3.12 --prompt shalinx
55
+ uv pip install --python .venv/bin/python -e .
56
+ .venv/bin/python -m unittest discover -s tests -v
57
+ ```
58
+
59
+ These tests do not call AudD or use an API token.
@@ -0,0 +1,45 @@
1
+ # Shalinx
2
+
3
+ Shalinx identifies music playing through your Linux desktop output. It records ten seconds from the default output monitor, asks AudD to identify the song, and saves successful matches locally.
4
+
5
+ ## Requirements
6
+
7
+ - Linux with PipeWire's PulseAudio compatibility or PulseAudio
8
+ - `ffmpeg` and `pactl` available on `PATH`
9
+ - Python 3.11 or newer and `pipx`
10
+ - An AudD API token
11
+
12
+ ## Install and launch
13
+
14
+ Install from PyPI after a release is published:
15
+
16
+ ```bash
17
+ pipx install shalinx
18
+ export AUDD_API_TOKEN='your-token-here'
19
+ shalinx
20
+ ```
21
+
22
+ To install directly from a local checkout instead:
23
+
24
+ ```bash
25
+ cd ~/github/Shalinx
26
+ pipx install .
27
+ ```
28
+
29
+ If `shalinx` is not found after installation, run `pipx ensurepath` and start a new shell. The `AUDD_API_TOKEN` environment variable must be available when you launch the app.
30
+
31
+ Play a song through the computer's default audio output, then click **Identify song**. The app records the output monitor, not the microphone. It opens song links with your default browser. Click the trash icon beside a history entry to remove it after confirmation.
32
+
33
+ History rows show cover thumbnails from AudD's song links when available, including for previously saved matches. Artwork loads in the background and is cached under `${XDG_CACHE_HOME:-~/.cache}/shalinx/artwork`.
34
+
35
+ History is stored in `${XDG_DATA_HOME:-~/.local/share}/shalinx/history.sqlite3`. The AudD token is read from the environment and is never stored in the database. The database does store AudD's full response metadata for successful matches.
36
+
37
+ ## Development and offline tests
38
+
39
+ ```bash
40
+ uv venv .venv --python 3.12 --prompt shalinx
41
+ uv pip install --python .venv/bin/python -e .
42
+ .venv/bin/python -m unittest discover -s tests -v
43
+ ```
44
+
45
+ These tests do not call AudD or use an API token.
@@ -0,0 +1,65 @@
1
+ We are building a new application called Shalinx, a cross-platform music recognition application. The eventual goal is to support Linux, iOS and potentially other platforms, with synchronized music recognition history.
2
+
3
+ For now, implement a standalone Linux desktop application.
4
+
5
+ ## Technology stack
6
+
7
+ - Python 3
8
+ - PySide6 for the GUI
9
+ - FFmpeg for audio capture
10
+ - AudD REST API for music recognition
11
+ - SQLite for persistent local recognition history
12
+
13
+ ## Verified environment
14
+
15
+ The development machine is called ljubljana. It runs Linux with PipeWire 1.0.5 and PulseAudio compatibility. FFmpeg is already installed.
16
+
17
+ The following audio capture command has been successfully tested:
18
+
19
+ ```bash
20
+ ffmpeg -f pulse \
21
+ -i "$(pactl get-default-sink).monitor" \
22
+ -t 10 -ac 1 -ar 44100 -y /tmp/shalinx-test.wav
23
+ ```
24
+
25
+ The following AudD API call has also been successfully tested:
26
+
27
+ ```bash
28
+ curl -s https://api.audd.io/ \
29
+ -F "api_token=$AUDD_API_TOKEN" \
30
+ -F "file=@/tmp/shalinx-test.wav"
31
+ ```
32
+
33
+ ## Functional requirements
34
+
35
+ 1. Display a clean, minimalist desktop GUI titled Shalinx.
36
+ 2. Provide a large, prominent "Identify song" button.
37
+ 3. Capture 10 seconds of digital audio from the default desktop audio output, without using the microphone.
38
+ 4. Submit the captured audio to AudD.
39
+ 5. Display progress during recording and recognition.
40
+ 6. Display the recognized song's title, artist, album and release date.
41
+ 7. Save successful recognitions in a persistent SQLite database, including the recognition timestamp and all returned metadata.
42
+ 8. Display recognition history in reverse chronological order within the main window.
43
+ 9. Allow the user to open the returned song_link in their default browser.
44
+ 10. Handle missing audio, unrecognized songs, network failures and API errors gracefully.
45
+
46
+ ## Implementation requirements
47
+
48
+ - Keep the GUI responsive during recording and API calls.
49
+ - Prevent concurrent recognition requests.
50
+ - Separate audio capture, music recognition, database and GUI into distinct modules.
51
+ - Make the recognition provider interchangeable, as we may support other providers later.
52
+ - Read the AudD API token from the AUDD_API_TOKEN environment variable. Never hardcode it or commit it to Git.
53
+ - Use unique temporary audio files and delete them after processing.
54
+ - Store persistent application data in the appropriate XDG user data directory, not the source repository.
55
+ - Support Unicode metadata, including non-Latin scripts.
56
+ - Create a Python virtual environment, requirements.txt, .gitignore and README.md.
57
+ - Include basic automated tests that do not consume paid API requests.
58
+
59
+ ## Out of scope
60
+
61
+ Do not implement cloud synchronization, user accounts, music purchases, subscriptions, iOS support or elaborate graphics yet.
62
+
63
+ Prioritize simplicity, reliability and maintainability. Avoid overengineering.
64
+
65
+ Implement the application, run the automated tests, and provide instructions for launching it locally.
@@ -0,0 +1,27 @@
1
+ [build-system]
2
+ requires = ["hatchling>=1.26"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "shalinx"
7
+ version = "0.1.0"
8
+ description = "Recognize music playing on a Linux desktop"
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ dependencies = ["PySide6>=6.6,<7"]
12
+ classifiers = [
13
+ "Environment :: X11 Applications :: Qt",
14
+ "Intended Audience :: End Users/Desktop",
15
+ "Operating System :: POSIX :: Linux",
16
+ "Programming Language :: Python :: 3",
17
+ "Topic :: Multimedia :: Sound/Audio",
18
+ ]
19
+
20
+ [project.urls]
21
+ Source = "https://github.com/ljbuturovic/Shalinx"
22
+
23
+ [project.scripts]
24
+ shalinx = "shalinx.gui:run"
25
+
26
+ [tool.hatch.build.targets.wheel]
27
+ packages = ["shalinx"]
@@ -0,0 +1 @@
1
+ PySide6>=6.6,<7
@@ -0,0 +1 @@
1
+ """Shalinx desktop music recognition."""
@@ -0,0 +1,64 @@
1
+ """Fetch and cache AudD song thumbnails without blocking the GUI."""
2
+
3
+ import os
4
+ from pathlib import Path
5
+ from urllib.parse import urlsplit, urlunsplit
6
+
7
+ from PySide6.QtCore import QObject, QUrl, Signal
8
+ from PySide6.QtGui import QPixmap
9
+ from PySide6.QtNetwork import (
10
+ QNetworkAccessManager, QNetworkDiskCache, QNetworkReply, QNetworkRequest,
11
+ )
12
+
13
+
14
+ def thumbnail_url(song_link: str | None) -> str | None:
15
+ """AudD exposes cover art for lis.tn song links via the thumb query."""
16
+ if not song_link:
17
+ return None
18
+ parts = urlsplit(song_link)
19
+ if parts.scheme != "https" or parts.hostname != "lis.tn" or not parts.path.strip("/"):
20
+ return None
21
+ query = f"{parts.query}&thumb" if parts.query else "thumb"
22
+ return urlunsplit((parts.scheme, parts.netloc, parts.path, query, ""))
23
+
24
+
25
+ class ArtworkLoader(QObject):
26
+ loaded = Signal(str, QPixmap)
27
+
28
+ def __init__(self, parent: QObject | None = None):
29
+ super().__init__(parent)
30
+ self.manager = QNetworkAccessManager(self)
31
+ self.manager.finished.connect(self._on_finished)
32
+ self.pending: set[str] = set()
33
+ self.memory_cache: dict[str, QPixmap] = {}
34
+ cache_dir = Path(os.environ.get("XDG_CACHE_HOME") or Path.home() / ".cache") / "shalinx" / "artwork"
35
+ try:
36
+ cache_dir.mkdir(parents=True, exist_ok=True)
37
+ cache = QNetworkDiskCache(self.manager)
38
+ cache.setCacheDirectory(str(cache_dir))
39
+ cache.setMaximumCacheSize(50 * 1024 * 1024)
40
+ self.manager.setCache(cache)
41
+ except OSError:
42
+ pass # Artwork still loads when the cache directory is unavailable.
43
+
44
+ def fetch(self, url: str) -> None:
45
+ if url in self.memory_cache:
46
+ self.loaded.emit(url, self.memory_cache[url])
47
+ return
48
+ if url in self.pending:
49
+ return
50
+ self.pending.add(url)
51
+ request = QNetworkRequest(QUrl(url))
52
+ request.setAttribute(QNetworkRequest.Attribute.CacheLoadControlAttribute,
53
+ QNetworkRequest.CacheLoadControl.PreferCache)
54
+ self.manager.get(request)
55
+
56
+ def _on_finished(self, reply: QNetworkReply) -> None:
57
+ url = reply.request().url().toString()
58
+ self.pending.discard(url)
59
+ if reply.error() == QNetworkReply.NetworkError.NoError:
60
+ pixmap = QPixmap()
61
+ if pixmap.loadFromData(reply.readAll()):
62
+ self.memory_cache[url] = pixmap
63
+ self.loaded.emit(url, pixmap)
64
+ reply.deleteLater()
@@ -0,0 +1,88 @@
1
+ """Capture the default desktop output through PulseAudio's monitor source."""
2
+
3
+ from array import array
4
+ import subprocess
5
+ import sys
6
+ import time
7
+ import wave
8
+ from pathlib import Path
9
+ from typing import Callable
10
+
11
+
12
+ class AudioCaptureError(Exception):
13
+ pass
14
+
15
+
16
+ def default_monitor() -> str:
17
+ try:
18
+ result = subprocess.run(
19
+ ["pactl", "get-default-sink"], capture_output=True, text=True,
20
+ check=True, timeout=5,
21
+ )
22
+ except (OSError, subprocess.SubprocessError) as exc:
23
+ raise AudioCaptureError("Could not find the default desktop audio output (pactl).") from exc
24
+ sink = result.stdout.strip()
25
+ if not sink:
26
+ raise AudioCaptureError("No default desktop audio output is available.")
27
+ return f"{sink}.monitor"
28
+
29
+
30
+ def has_audible_audio(path: Path) -> bool:
31
+ """Reject empty and effectively silent 16-bit mono recordings."""
32
+ try:
33
+ with wave.open(str(path), "rb") as recording:
34
+ if recording.getnchannels() != 1 or recording.getsampwidth() != 2:
35
+ raise AudioCaptureError("The audio recording has an unexpected format.")
36
+ if recording.getnframes() == 0:
37
+ return False
38
+ while chunk := recording.readframes(44100):
39
+ samples = array("h")
40
+ samples.frombytes(chunk)
41
+ if sys.byteorder != "little":
42
+ samples.byteswap()
43
+ if any(abs(sample) > 200 for sample in samples):
44
+ return True
45
+ except (OSError, EOFError, wave.Error) as exc:
46
+ raise AudioCaptureError("The desktop audio recording could not be read.") from exc
47
+ return False
48
+
49
+
50
+ def capture_desktop_audio(path: Path, progress: Callable[[int], None] | None = None,
51
+ duration: int = 10) -> None:
52
+ monitor = default_monitor()
53
+ command = [
54
+ "ffmpeg", "-nostdin", "-hide_banner", "-loglevel", "error", "-f", "pulse",
55
+ "-i", monitor, "-t", str(duration), "-ac", "1", "-ar", "44100",
56
+ "-c:a", "pcm_s16le", "-y", str(path),
57
+ ]
58
+ try:
59
+ process = subprocess.Popen(command, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE)
60
+ except OSError as exc:
61
+ raise AudioCaptureError("FFmpeg could not be started.") from exc
62
+ started = time.monotonic()
63
+ last_second = -1
64
+ try:
65
+ while process.poll() is None:
66
+ elapsed = time.monotonic() - started
67
+ second = min(int(elapsed), duration)
68
+ if progress and second != last_second:
69
+ progress(second)
70
+ last_second = second
71
+ if elapsed > duration + 12:
72
+ process.kill()
73
+ process.communicate()
74
+ raise AudioCaptureError("Audio capture timed out. Check the desktop audio output.")
75
+ time.sleep(0.1)
76
+ _, error = process.communicate()
77
+ except BaseException:
78
+ if process.poll() is None:
79
+ process.kill()
80
+ process.communicate()
81
+ raise
82
+ if process.returncode != 0:
83
+ detail = error.decode("utf-8", errors="replace").strip()
84
+ raise AudioCaptureError(f"Desktop audio capture failed: {detail or 'unknown FFmpeg error'}")
85
+ if progress:
86
+ progress(duration)
87
+ if not has_audible_audio(path):
88
+ raise AudioCaptureError("No desktop audio was heard. Play a song and try again.")
@@ -0,0 +1,60 @@
1
+ """Local recognition history in the user's XDG data directory."""
2
+
3
+ from datetime import datetime, timezone
4
+ import json
5
+ import os
6
+ from pathlib import Path
7
+ import sqlite3
8
+
9
+ from .provider import Song
10
+
11
+
12
+ def database_path() -> Path:
13
+ base = Path(os.environ.get("XDG_DATA_HOME") or Path.home() / ".local" / "share")
14
+ return base / "shalinx" / "history.sqlite3"
15
+
16
+
17
+ class HistoryStore:
18
+ def __init__(self, path: Path | None = None):
19
+ self.path = path or database_path()
20
+ self.path.parent.mkdir(parents=True, exist_ok=True)
21
+ with self._connect() as connection:
22
+ connection.execute("""
23
+ CREATE TABLE IF NOT EXISTS recognitions (
24
+ id INTEGER PRIMARY KEY,
25
+ recognized_at TEXT NOT NULL,
26
+ title TEXT NOT NULL,
27
+ artist TEXT NOT NULL,
28
+ album TEXT,
29
+ release_date TEXT,
30
+ song_link TEXT,
31
+ metadata_json TEXT NOT NULL
32
+ )
33
+ """)
34
+
35
+ def _connect(self) -> sqlite3.Connection:
36
+ connection = sqlite3.connect(self.path)
37
+ connection.row_factory = sqlite3.Row
38
+ return connection
39
+
40
+ def add(self, song: Song) -> None:
41
+ with self._connect() as connection:
42
+ connection.execute("""
43
+ INSERT INTO recognitions
44
+ (recognized_at, title, artist, album, release_date, song_link, metadata_json)
45
+ VALUES (?, ?, ?, ?, ?, ?, ?)
46
+ """, (
47
+ datetime.now(timezone.utc).isoformat(timespec="seconds"), song.title,
48
+ song.artist, song.album, song.release_date, song.song_link,
49
+ json.dumps(song.metadata, ensure_ascii=False),
50
+ ))
51
+
52
+ def recent(self) -> list[sqlite3.Row]:
53
+ with self._connect() as connection:
54
+ return connection.execute(
55
+ "SELECT * FROM recognitions ORDER BY recognized_at DESC, id DESC"
56
+ ).fetchall()
57
+
58
+ def delete(self, recognition_id: int) -> None:
59
+ with self._connect() as connection:
60
+ connection.execute("DELETE FROM recognitions WHERE id = ?", (recognition_id,))
@@ -0,0 +1,299 @@
1
+ """PySide6 main window and background recognition worker."""
2
+
3
+ from datetime import datetime
4
+ import os
5
+ from pathlib import Path
6
+ import tempfile
7
+ from urllib.parse import urlparse
8
+
9
+ from PySide6.QtCore import QObject, QSize, Qt, QThread, QUrl, Signal, Slot
10
+ from PySide6.QtGui import QCloseEvent, QColor, QDesktopServices, QIcon, QPainter, QPixmap
11
+ from PySide6.QtWidgets import (
12
+ QAbstractItemView, QApplication, QHeaderView, QLabel, QMainWindow,
13
+ QMessageBox, QProgressBar, QPushButton, QStyle, QTableWidget,
14
+ QTableWidgetItem, QToolButton, QVBoxLayout, QWidget,
15
+ )
16
+
17
+ from .audio import AudioCaptureError, capture_desktop_audio
18
+ from .artwork import ArtworkLoader, thumbnail_url
19
+ from .database import HistoryStore
20
+ from .provider import AudDProvider, RecognitionError, RecognitionProvider, Song
21
+
22
+
23
+ class RecognitionWorker(QObject):
24
+ progress = Signal(int)
25
+ stage = Signal(str)
26
+ completed = Signal(object, str)
27
+
28
+ def __init__(self, provider: RecognitionProvider):
29
+ super().__init__()
30
+ self.provider = provider
31
+
32
+ @Slot()
33
+ def run(self) -> None:
34
+ path: Path | None = None
35
+ try:
36
+ with tempfile.NamedTemporaryFile(prefix="shalinx-", suffix=".wav", delete=False) as file:
37
+ path = Path(file.name)
38
+ self.stage.emit("Recording desktop audio…")
39
+ capture_desktop_audio(path, self.progress.emit)
40
+ self.stage.emit("Identifying song…")
41
+ song = self.provider.recognize(path)
42
+ self.completed.emit(song, "")
43
+ except (AudioCaptureError, RecognitionError) as exc:
44
+ self.completed.emit(None, str(exc))
45
+ except Exception as exc:
46
+ self.completed.emit(None, f"Recognition failed: {exc}")
47
+ finally:
48
+ if path is not None:
49
+ path.unlink(missing_ok=True)
50
+
51
+
52
+ class MainWindow(QMainWindow):
53
+ def __init__(self, store: HistoryStore | None = None,
54
+ provider: RecognitionProvider | None = None):
55
+ super().__init__()
56
+ self.store = store or HistoryStore()
57
+ self.provider = provider or AudDProvider(os.environ.get("AUDD_API_TOKEN", ""))
58
+ self.thread: QThread | None = None
59
+ self.worker: RecognitionWorker | None = None
60
+ self.close_when_finished = False
61
+ self.current_link: str | None = None
62
+ self.setWindowTitle("Shalinx")
63
+ self.resize(820, 620)
64
+
65
+ central = QWidget()
66
+ layout = QVBoxLayout(central)
67
+ layout.setSpacing(14)
68
+ layout.setContentsMargins(24, 24, 24, 24)
69
+ self.setCentralWidget(central)
70
+
71
+ heading = QLabel("Shalinx")
72
+ heading.setObjectName("heading")
73
+ layout.addWidget(heading)
74
+
75
+ self.identify_button = QPushButton("Identify song")
76
+ self.identify_button.setObjectName("identifyButton")
77
+ self.identify_button.setMinimumHeight(64)
78
+ self.identify_button.clicked.connect(self.identify)
79
+ layout.addWidget(self.identify_button)
80
+
81
+ self.status_label = QLabel("Play music on this computer, then identify it.")
82
+ self.status_label.setWordWrap(True)
83
+ layout.addWidget(self.status_label)
84
+ self.progress_bar = QProgressBar()
85
+ self.progress_bar.setRange(0, 10)
86
+ self.progress_bar.setValue(0)
87
+ self.progress_bar.hide()
88
+ layout.addWidget(self.progress_bar)
89
+
90
+ self.result_label = QLabel("No song identified yet")
91
+ self.result_label.setObjectName("result")
92
+ self.result_label.setWordWrap(True)
93
+ self.result_label.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse)
94
+ layout.addWidget(self.result_label)
95
+ self.open_button = QPushButton("Open song link")
96
+ self.open_button.setEnabled(False)
97
+ self.open_button.clicked.connect(self.open_link)
98
+ layout.addWidget(self.open_button, alignment=Qt.AlignmentFlag.AlignLeft)
99
+
100
+ history_heading = QLabel("History")
101
+ history_heading.setObjectName("historyHeading")
102
+ layout.addWidget(history_heading)
103
+ self.history = QTableWidget(0, 6)
104
+ self.history.setHorizontalHeaderLabels(
105
+ ["Recognized", "Title", "Artist", "Album", "Release date", ""]
106
+ )
107
+ self.history.setSelectionBehavior(QAbstractItemView.SelectionBehavior.SelectRows)
108
+ self.history.setSelectionMode(QAbstractItemView.SelectionMode.SingleSelection)
109
+ self.history.setEditTriggers(QAbstractItemView.EditTrigger.NoEditTriggers)
110
+ self.history.verticalHeader().hide()
111
+ self.history.verticalHeader().setDefaultSectionSize(42)
112
+ self.history.setIconSize(QSize(32, 32))
113
+ self.history.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeMode.Stretch)
114
+ self.history.horizontalHeader().setSectionResizeMode(5, QHeaderView.ResizeMode.Fixed)
115
+ self.history.setColumnWidth(5, 44)
116
+ self.history.itemSelectionChanged.connect(self.select_history_song)
117
+ self.history.cellDoubleClicked.connect(lambda *_: self.open_link())
118
+ layout.addWidget(self.history, 1)
119
+
120
+ self.placeholder_icon = self._make_placeholder_icon()
121
+ self.artwork = ArtworkLoader(self)
122
+ self.artwork.loaded.connect(self.on_artwork_loaded)
123
+
124
+ self.setStyleSheet("""
125
+ QMainWindow { background: #f7f8fa; }
126
+ QLabel#heading { font-size: 30px; font-weight: 700; color: #202b3a; }
127
+ QLabel#historyHeading { font-size: 18px; font-weight: 600; }
128
+ QLabel#result { font-size: 17px; padding: 14px; background: white;
129
+ border: 1px solid #e3e7ed; border-radius: 8px; }
130
+ QPushButton#identifyButton { font-size: 20px; font-weight: 600;
131
+ color: white; background: #315fc4; border: 0; border-radius: 10px; }
132
+ QPushButton#identifyButton:hover { background: #264fa9; }
133
+ QPushButton#identifyButton:disabled { background: #9ba9ca; }
134
+ """)
135
+ self.load_history()
136
+
137
+ def load_history(self) -> None:
138
+ records = self.store.recent()
139
+ self.history.setRowCount(len(records))
140
+ for row_index, record in enumerate(records):
141
+ try:
142
+ date = datetime.fromisoformat(record["recognized_at"]).astimezone().strftime("%Y-%m-%d %H:%M")
143
+ except ValueError:
144
+ date = record["recognized_at"]
145
+ cover_url = thumbnail_url(record["song_link"])
146
+ values = [date, record["title"], record["artist"],
147
+ record["album"] or "", record["release_date"] or ""]
148
+ for column, value in enumerate(values):
149
+ item = QTableWidgetItem(value)
150
+ if column == 0:
151
+ item.setData(Qt.ItemDataRole.UserRole, record["song_link"])
152
+ elif column == 1:
153
+ item.setIcon(self.placeholder_icon)
154
+ item.setData(Qt.ItemDataRole.UserRole, cover_url)
155
+ self.history.setItem(row_index, column, item)
156
+ if cover_url:
157
+ self.artwork.fetch(cover_url)
158
+ delete_button = QToolButton(self.history)
159
+ delete_button.setIcon(self.style().standardIcon(QStyle.StandardPixmap.SP_TrashIcon))
160
+ delete_button.setAutoRaise(True)
161
+ delete_button.setToolTip(f"Delete {record['title']} from history")
162
+ delete_button.setAccessibleName(f"Delete {record['title']} from history")
163
+ delete_button.clicked.connect(
164
+ lambda _checked=False, record_id=record["id"], title=record["title"],
165
+ artist=record["artist"]: self.delete_history_entry(record_id, title, artist)
166
+ )
167
+ self.history.setCellWidget(row_index, 5, delete_button)
168
+
169
+ @staticmethod
170
+ def _make_placeholder_icon() -> QIcon:
171
+ pixmap = QPixmap(32, 32)
172
+ pixmap.fill(QColor("#e5eaf2"))
173
+ painter = QPainter(pixmap)
174
+ painter.setPen(QColor("#64748b"))
175
+ font = painter.font()
176
+ font.setPointSize(18)
177
+ painter.setFont(font)
178
+ painter.drawText(pixmap.rect(), Qt.AlignmentFlag.AlignCenter, "♫")
179
+ painter.end()
180
+ return QIcon(pixmap)
181
+
182
+ @Slot(str, QPixmap)
183
+ def on_artwork_loaded(self, url: str, pixmap: QPixmap) -> None:
184
+ icon = QIcon(pixmap.scaled(
185
+ QSize(32, 32), Qt.AspectRatioMode.KeepAspectRatio,
186
+ Qt.TransformationMode.SmoothTransformation,
187
+ ))
188
+ for row in range(self.history.rowCount()):
189
+ item = self.history.item(row, 1)
190
+ if item and item.data(Qt.ItemDataRole.UserRole) == url:
191
+ item.setIcon(icon)
192
+
193
+ def delete_history_entry(self, record_id: int, title: str, artist: str) -> None:
194
+ answer = QMessageBox.question(
195
+ self, "Delete recognition",
196
+ f"Delete “{title}” by {artist} from history?",
197
+ QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.Cancel,
198
+ QMessageBox.StandardButton.Cancel,
199
+ )
200
+ if answer != QMessageBox.StandardButton.Yes:
201
+ return
202
+ try:
203
+ self.store.delete(record_id)
204
+ self.load_history()
205
+ except Exception as exc:
206
+ QMessageBox.warning(self, "Shalinx", f"Could not delete the history entry: {exc}")
207
+ return
208
+ self.status_label.setText(f"Removed “{title}” from history.")
209
+
210
+ @Slot()
211
+ def identify(self) -> None:
212
+ if self.thread is not None:
213
+ return
214
+ if isinstance(self.provider, AudDProvider) and not self.provider.token:
215
+ self.status_label.setText("Set AUDD_API_TOKEN before identifying a song.")
216
+ return
217
+ self.identify_button.setEnabled(False)
218
+ self.progress_bar.setValue(0)
219
+ self.progress_bar.show()
220
+ self.thread = QThread(self)
221
+ self.worker = RecognitionWorker(self.provider)
222
+ self.worker.moveToThread(self.thread)
223
+ self.thread.started.connect(self.worker.run)
224
+ self.worker.progress.connect(self.progress_bar.setValue)
225
+ self.worker.stage.connect(self.status_label.setText)
226
+ self.worker.completed.connect(self.on_completed)
227
+ self.worker.completed.connect(self.thread.quit)
228
+ self.worker.completed.connect(self.worker.deleteLater)
229
+ self.thread.finished.connect(self.on_thread_finished)
230
+ self.thread.finished.connect(self.thread.deleteLater)
231
+ self.thread.start()
232
+
233
+ @Slot(object, str)
234
+ def on_completed(self, song: Song | None, error: str) -> None:
235
+ if error:
236
+ self.status_label.setText(error)
237
+ elif song is None:
238
+ self.status_label.setText("No song recognized. Try a clearer 10-second segment.")
239
+ else:
240
+ try:
241
+ self.store.add(song)
242
+ self.load_history()
243
+ except Exception as exc:
244
+ self.status_label.setText(f"Song identified, but history could not be saved: {exc}")
245
+ else:
246
+ self.status_label.setText("Song identified and saved to history.")
247
+ self.show_song(song)
248
+ self.progress_bar.hide()
249
+
250
+ @Slot()
251
+ def on_thread_finished(self) -> None:
252
+ self.worker = None
253
+ self.thread = None
254
+ self.identify_button.setEnabled(True)
255
+ if self.close_when_finished:
256
+ self.close()
257
+
258
+ def closeEvent(self, event: QCloseEvent) -> None:
259
+ if self.thread is not None:
260
+ self.close_when_finished = True
261
+ self.status_label.setText("Finishing recognition before closing…")
262
+ event.ignore()
263
+ else:
264
+ event.accept()
265
+
266
+ def show_song(self, song: Song) -> None:
267
+ self.result_label.setText(
268
+ f"{song.title} — {song.artist}\n"
269
+ f"Album: {song.album or 'Unknown'}\n"
270
+ f"Release date: {song.release_date or 'Unknown'}"
271
+ )
272
+ self.current_link = song.song_link
273
+ self.open_button.setEnabled(self._valid_link(self.current_link))
274
+
275
+ @Slot()
276
+ def select_history_song(self) -> None:
277
+ row = self.history.currentRow()
278
+ if row < 0:
279
+ return
280
+ item = self.history.item(row, 0)
281
+ self.current_link = item.data(Qt.ItemDataRole.UserRole) if item else None
282
+ self.open_button.setEnabled(self._valid_link(self.current_link))
283
+
284
+ @staticmethod
285
+ def _valid_link(link: str | None) -> bool:
286
+ return bool(link and urlparse(link).scheme in ("http", "https") and urlparse(link).netloc)
287
+
288
+ @Slot()
289
+ def open_link(self) -> None:
290
+ if self._valid_link(self.current_link):
291
+ if not QDesktopServices.openUrl(QUrl(self.current_link)):
292
+ QMessageBox.warning(self, "Shalinx", "Could not open the song link.")
293
+
294
+
295
+ def run() -> int:
296
+ app = QApplication.instance() or QApplication([])
297
+ window = MainWindow()
298
+ window.show()
299
+ return app.exec()
@@ -0,0 +1,83 @@
1
+ """Interchangeable music recognition provider interface and AudD implementation."""
2
+
3
+ from dataclasses import dataclass
4
+ import json
5
+ import mimetypes
6
+ from pathlib import Path
7
+ from typing import Any, Protocol
8
+ from urllib.error import HTTPError, URLError
9
+ from urllib.request import Request, urlopen
10
+ from uuid import uuid4
11
+
12
+
13
+ class RecognitionError(Exception):
14
+ pass
15
+
16
+
17
+ @dataclass(frozen=True)
18
+ class Song:
19
+ title: str
20
+ artist: str
21
+ album: str | None
22
+ release_date: str | None
23
+ song_link: str | None
24
+ metadata: dict[str, Any]
25
+
26
+
27
+ class RecognitionProvider(Protocol):
28
+ def recognize(self, audio_path: Path) -> Song | None: ...
29
+
30
+
31
+ class AudDProvider:
32
+ endpoint = "https://api.audd.io/"
33
+
34
+ def __init__(self, token: str):
35
+ self.token = token
36
+
37
+ def recognize(self, audio_path: Path) -> Song | None:
38
+ if not self.token:
39
+ raise RecognitionError("Set AUDD_API_TOKEN before identifying a song.")
40
+ boundary = f"shalinx-{uuid4().hex}"
41
+ parts = [
42
+ f"--{boundary}\r\nContent-Disposition: form-data; name=\"api_token\"\r\n\r\n{self.token}\r\n".encode(),
43
+ (f"--{boundary}\r\nContent-Disposition: form-data; name=\"file\"; "
44
+ f"filename=\"{audio_path.name}\"\r\nContent-Type: "
45
+ f"{mimetypes.guess_type(audio_path.name)[0] or 'audio/wav'}\r\n\r\n").encode(),
46
+ audio_path.read_bytes(),
47
+ f"\r\n--{boundary}--\r\n".encode(),
48
+ ]
49
+ request = Request(
50
+ self.endpoint, data=b"".join(parts), method="POST",
51
+ headers={"Content-Type": f"multipart/form-data; boundary={boundary}"},
52
+ )
53
+ try:
54
+ with urlopen(request, timeout=30) as response:
55
+ payload = json.load(response)
56
+ except HTTPError as exc:
57
+ raise RecognitionError(f"AudD returned HTTP {exc.code}.") from exc
58
+ except (URLError, TimeoutError, OSError) as exc:
59
+ raise RecognitionError("Could not reach AudD. Check your network connection.") from exc
60
+ except (ValueError, UnicodeError) as exc:
61
+ raise RecognitionError("AudD returned an unreadable response.") from exc
62
+ return parse_audd_response(payload)
63
+
64
+
65
+ def parse_audd_response(payload: Any) -> Song | None:
66
+ if not isinstance(payload, dict):
67
+ raise RecognitionError("AudD returned an unexpected response.")
68
+ if payload.get("status") != "success":
69
+ error = payload.get("error")
70
+ message = error.get("error_message") if isinstance(error, dict) else None
71
+ raise RecognitionError(f"AudD error: {message or 'request failed'}")
72
+ result = payload.get("result")
73
+ if result is None:
74
+ return None
75
+ if not isinstance(result, dict) or not result.get("title") or not result.get("artist"):
76
+ raise RecognitionError("AudD returned incomplete song information.")
77
+ return Song(
78
+ title=str(result["title"]), artist=str(result["artist"]),
79
+ album=str(result["album"]) if result.get("album") else None,
80
+ release_date=str(result["release_date"]) if result.get("release_date") else None,
81
+ song_link=str(result["song_link"]) if result.get("song_link") else None,
82
+ metadata=payload,
83
+ )
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env python3
2
+ """Launch the Shalinx desktop application."""
3
+
4
+ from shalinx.gui import run
5
+
6
+
7
+ if __name__ == "__main__":
8
+ raise SystemExit(run())
@@ -0,0 +1,81 @@
1
+ import json
2
+ from pathlib import Path
3
+ import tempfile
4
+ import unittest
5
+ import wave
6
+
7
+ from shalinx.audio import has_audible_audio
8
+ from shalinx.artwork import thumbnail_url
9
+ from shalinx.database import HistoryStore, database_path
10
+ from shalinx.provider import RecognitionError, parse_audd_response
11
+
12
+
13
+ class ProviderTests(unittest.TestCase):
14
+ def test_unicode_result_and_complete_metadata(self):
15
+ payload = {"status": "success", "result": {
16
+ "title": "夜に駆ける", "artist": "YOASOBI", "album": "THE BOOK",
17
+ "release_date": "2020-01-01", "song_link": "https://example.com/song",
18
+ "extra": {"script": "日本語"},
19
+ }}
20
+ song = parse_audd_response(payload)
21
+ self.assertEqual(song.title, "夜に駆ける")
22
+ self.assertEqual(song.metadata, payload)
23
+
24
+ def test_no_match_and_api_error(self):
25
+ self.assertIsNone(parse_audd_response({"status": "success", "result": None}))
26
+ with self.assertRaisesRegex(RecognitionError, "invalid token"):
27
+ parse_audd_response({"status": "error", "error": {"error_message": "invalid token"}})
28
+
29
+
30
+ class HistoryTests(unittest.TestCase):
31
+ def test_persistence_order_and_unicode(self):
32
+ with tempfile.TemporaryDirectory() as folder:
33
+ path = Path(folder) / "history.sqlite3"
34
+ store = HistoryStore(path)
35
+ first = parse_audd_response({"status": "success", "result": {
36
+ "title": "First", "artist": "Artist", "extra": "α"}})
37
+ second = parse_audd_response({"status": "success", "result": {
38
+ "title": "夜に駆ける", "artist": "YOASOBI"}})
39
+ store.add(first)
40
+ store.add(second)
41
+ rows = HistoryStore(path).recent()
42
+ self.assertEqual([row["title"] for row in rows], ["夜に駆ける", "First"])
43
+ self.assertEqual(json.loads(rows[1]["metadata_json"])["result"]["extra"], "α")
44
+ self.assertTrue(rows[0]["recognized_at"])
45
+
46
+ def test_xdg_location(self):
47
+ from unittest.mock import patch
48
+ with patch.dict("os.environ", {"XDG_DATA_HOME": "/tmp/shalinx-test-data"}):
49
+ self.assertEqual(database_path(), Path("/tmp/shalinx-test-data/shalinx/history.sqlite3"))
50
+
51
+
52
+ class AudioTests(unittest.TestCase):
53
+ def test_silence_and_signal(self):
54
+ with tempfile.TemporaryDirectory() as folder:
55
+ path = Path(folder) / "audio.wav"
56
+ with wave.open(str(path), "wb") as output:
57
+ output.setnchannels(1)
58
+ output.setsampwidth(2)
59
+ output.setframerate(44100)
60
+ output.writeframes(b"\x00\x00" * 1000)
61
+ self.assertFalse(has_audible_audio(path))
62
+ with wave.open(str(path), "wb") as output:
63
+ output.setnchannels(1)
64
+ output.setsampwidth(2)
65
+ output.setframerate(44100)
66
+ output.writeframes(b"\xe8\x03" * 1000)
67
+ self.assertTrue(has_audible_audio(path))
68
+
69
+
70
+ class ArtworkTests(unittest.TestCase):
71
+ def test_audd_thumbnail_url(self):
72
+ self.assertEqual(thumbnail_url("https://lis.tn/KAOIJUČER"),
73
+ "https://lis.tn/KAOIJUČER?thumb")
74
+ self.assertEqual(thumbnail_url("https://lis.tn/Song?t=15"),
75
+ "https://lis.tn/Song?t=15&thumb")
76
+ self.assertIsNone(thumbnail_url("https://example.com/Song"))
77
+ self.assertIsNone(thumbnail_url(None))
78
+
79
+
80
+ if __name__ == "__main__":
81
+ unittest.main()
@@ -0,0 +1,96 @@
1
+ import os
2
+ os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
3
+
4
+ from pathlib import Path
5
+ import tempfile
6
+ import unittest
7
+ from unittest.mock import patch
8
+
9
+ from PySide6.QtCore import QEventLoop, QTimer
10
+ from PySide6.QtGui import QColor, QPixmap
11
+ from PySide6.QtWidgets import QApplication, QMessageBox
12
+
13
+ from shalinx.database import HistoryStore
14
+ from shalinx.gui import MainWindow
15
+ from shalinx.provider import Song
16
+
17
+
18
+ class FakeProvider:
19
+ def recognize(self, audio_path: Path) -> Song:
20
+ assert audio_path.exists()
21
+ return Song("夜に駆ける", "YOASOBI", "THE BOOK", "2020-01-01",
22
+ "https://example.com/song", {"result": {"title": "夜に駆ける"}})
23
+
24
+
25
+ class GuiTests(unittest.TestCase):
26
+ @classmethod
27
+ def setUpClass(cls):
28
+ cls.app = QApplication.instance() or QApplication([])
29
+
30
+ def test_background_recognition_saves_history_and_removes_temp_file(self):
31
+ captured = []
32
+
33
+ def fake_capture(path, progress):
34
+ captured.append(path)
35
+ path.write_bytes(b"audio")
36
+ progress(10)
37
+
38
+ with tempfile.TemporaryDirectory() as folder:
39
+ window = MainWindow(HistoryStore(Path(folder) / "history.sqlite3"), FakeProvider())
40
+ loop = QEventLoop()
41
+ timer = QTimer()
42
+ timer.setSingleShot(True)
43
+ timer.timeout.connect(loop.quit)
44
+ with patch("shalinx.gui.capture_desktop_audio", fake_capture):
45
+ window.identify()
46
+ self.assertFalse(window.identify_button.isEnabled())
47
+ window.thread.finished.connect(loop.quit)
48
+ timer.start(3000)
49
+ loop.exec()
50
+ timer.stop()
51
+ self.assertIsNone(window.thread)
52
+ self.assertEqual(window.history.rowCount(), 1)
53
+ self.assertIn("夜に駆ける", window.result_label.text())
54
+ self.assertTrue(window.open_button.isEnabled())
55
+ self.assertEqual(len(captured), 1)
56
+ self.assertFalse(captured[0].exists())
57
+ window.close()
58
+
59
+ def test_trash_button_deletes_only_its_row_after_confirmation(self):
60
+ with tempfile.TemporaryDirectory() as folder:
61
+ store = HistoryStore(Path(folder) / "history.sqlite3")
62
+ store.add(Song("First", "Artist A", None, None, None, {}))
63
+ store.add(Song("Second", "Artist B", None, None, None, {}))
64
+ window = MainWindow(store, FakeProvider())
65
+ self.assertEqual(window.history.rowCount(), 2)
66
+ button = window.history.cellWidget(0, 5)
67
+ self.assertFalse(button.icon().isNull())
68
+
69
+ with patch("shalinx.gui.QMessageBox.question", return_value=QMessageBox.StandardButton.Cancel):
70
+ button.click()
71
+ self.assertEqual([row["title"] for row in store.recent()], ["Second", "First"])
72
+
73
+ with patch("shalinx.gui.QMessageBox.question", return_value=QMessageBox.StandardButton.Yes):
74
+ button.click()
75
+ self.assertEqual([row["title"] for row in store.recent()], ["First"])
76
+ self.assertEqual(window.history.rowCount(), 1)
77
+ window.close()
78
+
79
+ def test_history_requests_and_displays_audd_cover(self):
80
+ with tempfile.TemporaryDirectory() as folder:
81
+ store = HistoryStore(Path(folder) / "history.sqlite3")
82
+ store.add(Song("Track", "Artist", None, None, "https://lis.tn/Track", {}))
83
+ with patch("shalinx.gui.ArtworkLoader.fetch", autospec=True) as fetch:
84
+ window = MainWindow(store, FakeProvider())
85
+ fetch.assert_called_once_with(window.artwork, "https://lis.tn/Track?thumb")
86
+ item = window.history.item(0, 1)
87
+ placeholder_key = item.icon().cacheKey()
88
+ cover = QPixmap(32, 32)
89
+ cover.fill(QColor("red"))
90
+ window.on_artwork_loaded("https://lis.tn/Track?thumb", cover)
91
+ self.assertNotEqual(item.icon().cacheKey(), placeholder_key)
92
+ window.close()
93
+
94
+
95
+ if __name__ == "__main__":
96
+ unittest.main()