shalinx 0.1.0__py3-none-any.whl
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.
- shalinx/__init__.py +1 -0
- shalinx/artwork.py +64 -0
- shalinx/audio.py +88 -0
- shalinx/database.py +60 -0
- shalinx/gui.py +299 -0
- shalinx/provider.py +83 -0
- shalinx-0.1.0.dist-info/METADATA +59 -0
- shalinx-0.1.0.dist-info/RECORD +10 -0
- shalinx-0.1.0.dist-info/WHEEL +4 -0
- shalinx-0.1.0.dist-info/entry_points.txt +2 -0
shalinx/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Shalinx desktop music recognition."""
|
shalinx/artwork.py
ADDED
|
@@ -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()
|
shalinx/audio.py
ADDED
|
@@ -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.")
|
shalinx/database.py
ADDED
|
@@ -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,))
|
shalinx/gui.py
ADDED
|
@@ -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()
|
shalinx/provider.py
ADDED
|
@@ -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,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,10 @@
|
|
|
1
|
+
shalinx/__init__.py,sha256=6R3J9xFjGtOYB_gPCaLd-21o2vbb98GToY_IcHgisLA,41
|
|
2
|
+
shalinx/artwork.py,sha256=eQu5JD-J2cvwU1W4sbJHfuA4qBd8n_0EPEgGTVi_Lew,2523
|
|
3
|
+
shalinx/audio.py,sha256=-GlsBU_7SVEJblIzYhUTZ79hGTGAK_809e05GE9dBOs,3363
|
|
4
|
+
shalinx/database.py,sha256=5UEuH0Nct0R2S3Q6SaHuBeb97m5p_WyozdsLyxvTJ54,2189
|
|
5
|
+
shalinx/gui.py,sha256=oQl2pjw5QIkkxujeQLC42MxSLBvG9CQf690dnAWyzsw,12811
|
|
6
|
+
shalinx/provider.py,sha256=eJcj9bds0MEjUq4VOj91wFexIctMGUSG6CddSOLVWNQ,3202
|
|
7
|
+
shalinx-0.1.0.dist-info/METADATA,sha256=mNu74JbQ3GXZVH1XPH3dey_EykN8lI2f0TMsMhDjGhI,2278
|
|
8
|
+
shalinx-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
9
|
+
shalinx-0.1.0.dist-info/entry_points.txt,sha256=aD6hjAKx0VeYf2LajgSuUxCjIOc22wYGBuKekoi1fFA,44
|
|
10
|
+
shalinx-0.1.0.dist-info/RECORD,,
|