opentune 0.2.1__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.
opentune/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """OpenTune terminal music player."""
2
+
3
+ __version__ = "0.2.1"
opentune/__main__.py ADDED
@@ -0,0 +1,497 @@
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import curses
5
+ import json
6
+ import os
7
+ import shutil
8
+ import socket
9
+ import subprocess
10
+ import sys
11
+ import tempfile
12
+ import threading
13
+ import time
14
+ import re
15
+ from dataclasses import dataclass
16
+ from pathlib import Path
17
+ from typing import Any
18
+ from urllib.parse import parse_qs, urlparse
19
+
20
+ from . import __version__
21
+
22
+
23
+ SEARCH_LIMIT = 12
24
+ MIX_LIMIT = 10
25
+
26
+ HELP_TEXT = """\
27
+ OpenTune — stream YouTube music from your terminal
28
+
29
+ Usage:
30
+ opentune [MUSIC ...]
31
+
32
+ Examples:
33
+ opentune Daft Punk Get Lucky
34
+ opentune
35
+
36
+ Options:
37
+ -h, --help Show this help and exit.
38
+
39
+ Player keys:
40
+ j / Down Select next result or queue track
41
+ k / Up Select previous result or queue track
42
+ Enter Play the selected track
43
+ Space Pause or resume
44
+ h / l Previous / next track
45
+ H / L Rewind / forward 10 seconds
46
+ Ctrl-l Toggle looping for the current track
47
+ Tab Switch between Results and Queue
48
+ / Search YouTube from inside OpenTune
49
+ ? Toggle this key reference in the TUI
50
+ q / Esc Quit OpenTune
51
+
52
+ OpenTune requires mpv and yt-dlp. It streams audio only and does not
53
+ download tracks. Selecting a result creates a short related mix, shown
54
+ in the Queue tab."""
55
+
56
+
57
+ @dataclass(frozen=True)
58
+ class Track:
59
+ title: str
60
+ url: str
61
+ duration: int = 0
62
+ uploader: str = ""
63
+
64
+ @property
65
+ def label(self) -> str:
66
+ return f"{self.title} — {self.uploader}" if self.uploader else self.title
67
+
68
+
69
+ def format_time(seconds: float | int | None) -> str:
70
+ total = max(0, int(seconds or 0))
71
+ minutes, seconds = divmod(total, 60)
72
+ hours, minutes = divmod(minutes, 60)
73
+ return f"{hours}:{minutes:02d}:{seconds:02d}" if hours else f"{minutes}:{seconds:02d}"
74
+
75
+
76
+ def require_tools() -> str | None:
77
+ absent = [name for name in ("mpv", "yt-dlp") if not shutil.which(name)]
78
+ return f"Missing required command(s): {', '.join(absent)}" if absent else None
79
+
80
+
81
+ class YouTube:
82
+ """Small, deliberately dependency-free yt-dlp adapter."""
83
+
84
+ @staticmethod
85
+ def _fetch(target: str, label: str) -> list[Track]:
86
+ command = ["yt-dlp", "--flat-playlist", "--dump-single-json", target]
87
+ try:
88
+ completed = subprocess.run(command, capture_output=True, text=True, timeout=25, check=True)
89
+ payload = json.loads(completed.stdout)
90
+ except (subprocess.SubprocessError, json.JSONDecodeError) as error:
91
+ raise RuntimeError(f"{label} failed: {error}") from error
92
+ tracks: list[Track] = []
93
+ for entry in payload.get("entries") or []:
94
+ video_id = entry.get("id")
95
+ if not video_id:
96
+ continue
97
+ tracks.append(Track(
98
+ title=entry.get("title") or "Untitled",
99
+ url=entry.get("webpage_url") or f"https://www.youtube.com/watch?v={video_id}",
100
+ duration=int(entry.get("duration") or 0),
101
+ uploader=entry.get("uploader") or entry.get("channel") or "",
102
+ ))
103
+ return tracks
104
+
105
+ @classmethod
106
+ def search(cls, query: str, limit: int = SEARCH_LIMIT) -> list[Track]:
107
+ if not query.strip():
108
+ return []
109
+ return cls._fetch(f"ytsearch{limit}:{query}", "Search")
110
+
111
+ @staticmethod
112
+ def _video_id(url: str) -> str | None:
113
+ parsed = urlparse(url)
114
+ if parsed.netloc in {"youtu.be", "www.youtu.be"}:
115
+ return parsed.path.strip("/") or None
116
+ video_id = parse_qs(parsed.query).get("v", [None])[0]
117
+ return video_id
118
+
119
+ @staticmethod
120
+ def _track_key(track: Track) -> str:
121
+ """Create a loose song identity to exclude alternate uploads of a seed."""
122
+ title = track.title.lower()
123
+ if track.uploader:
124
+ title = title.replace(track.uploader.lower(), " ")
125
+ title = re.sub(r"\[[^]]*\]|\([^)]*\)", " ", title)
126
+ title = re.sub(
127
+ r"\b(official|audio|video|lyrics?|visuali[sz]er|music|hd|4k|remaster(?:ed)?)\b",
128
+ " ",
129
+ title,
130
+ )
131
+ return re.sub(r"\s+", " ", re.sub(r"[^a-z0-9]+", " ", title)).strip()
132
+
133
+ @classmethod
134
+ def _unique_mix(cls, seed: Track, candidates: list[Track]) -> list[Track]:
135
+ seed_key = cls._track_key(seed)
136
+ seen: set[str] = set()
137
+ mix: list[Track] = []
138
+ for candidate in candidates:
139
+ key = cls._track_key(candidate)
140
+ same_song = bool(seed_key and (key == seed_key or key.startswith(seed_key + " ") or seed_key.startswith(key + " ")))
141
+ if not key or candidate.url == seed.url or same_song or key in seen:
142
+ continue
143
+ seen.add(key)
144
+ mix.append(candidate)
145
+ if len(mix) == MIX_LIMIT:
146
+ break
147
+ return mix
148
+
149
+ @classmethod
150
+ def mix_for(cls, track: Track) -> list[Track]:
151
+ # YouTube's RD playlist is the same radio/mix mechanism exposed by its UI.
152
+ # It produces a varied sequence rather than search matches of the same video.
153
+ video_id = cls._video_id(track.url)
154
+ if video_id:
155
+ try:
156
+ radio = cls._fetch(
157
+ f"https://www.youtube.com/watch?v={video_id}&list=RD{video_id}",
158
+ "YouTube mix",
159
+ )
160
+ mix = cls._unique_mix(track, radio)
161
+ if mix:
162
+ return mix
163
+ except RuntimeError:
164
+ pass
165
+
166
+ # Fallback when YouTube does not expose a radio playlist for a video.
167
+ artist = track.uploader or track.title
168
+ candidates = cls.search(f"{artist} songs", MIX_LIMIT * 3)
169
+ return cls._unique_mix(track, candidates)
170
+
171
+
172
+ class MPV:
173
+ """Controls one headless mpv instance over its JSON IPC socket."""
174
+
175
+ def __init__(self, on_finished: callable) -> None:
176
+ self._on_finished = on_finished
177
+ self._directory = tempfile.TemporaryDirectory(prefix="opentune-")
178
+ self.socket_path = str(Path(self._directory.name) / "mpv.sock")
179
+ self.process: subprocess.Popen[str] | None = None
180
+ self._intentional_stop = False
181
+ self._lock = threading.Lock()
182
+
183
+ def play(self, track: Track, loop: bool = False) -> None:
184
+ self.stop()
185
+ self._intentional_stop = False
186
+ command = [
187
+ "mpv", "--no-video", "--force-window=no", "--really-quiet",
188
+ f"--input-ipc-server={self.socket_path}", "--ytdl-format=bestaudio/best", track.url,
189
+ ]
190
+ if loop:
191
+ command.insert(-1, "--loop-file=inf")
192
+ self.process = subprocess.Popen(command, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, text=True)
193
+ threading.Thread(target=self._watch, args=(self.process,), daemon=True).start()
194
+
195
+ def _watch(self, process: subprocess.Popen[str]) -> None:
196
+ process.wait()
197
+ if not self._intentional_stop and process is self.process:
198
+ self._on_finished()
199
+
200
+ def command(self, command: list[Any]) -> Any | None:
201
+ if not self.process or self.process.poll() is not None:
202
+ return None
203
+ message = json.dumps({"command": command}) + "\n"
204
+ with self._lock:
205
+ try:
206
+ client = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
207
+ client.settimeout(0.25)
208
+ client.connect(self.socket_path)
209
+ client.sendall(message.encode())
210
+ response = client.recv(4096)
211
+ client.close()
212
+ return json.loads(response.decode().splitlines()[0]).get("data")
213
+ except (OSError, json.JSONDecodeError, IndexError):
214
+ return None
215
+
216
+ def toggle_pause(self) -> None:
217
+ self.command(["cycle", "pause"])
218
+
219
+ def seek(self, seconds: int) -> None:
220
+ self.command(["seek", seconds, "relative+exact"])
221
+
222
+ def set_loop(self, enabled: bool) -> None:
223
+ self.command(["set_property", "loop-file", "inf" if enabled else "no"])
224
+
225
+ def state(self) -> tuple[float, bool]:
226
+ position = self.command(["get_property", "playback-time"])
227
+ paused = self.command(["get_property", "pause"])
228
+ return float(position or 0), bool(paused)
229
+
230
+ def stop(self) -> None:
231
+ if self.process and self.process.poll() is None:
232
+ self._intentional_stop = True
233
+ self.command(["quit"])
234
+ try:
235
+ self.process.wait(timeout=1)
236
+ except subprocess.TimeoutExpired:
237
+ self.process.kill()
238
+ self.process = None
239
+
240
+ def close(self) -> None:
241
+ self.stop()
242
+ self._directory.cleanup()
243
+
244
+
245
+ class Player:
246
+ def __init__(self) -> None:
247
+ self.current: Track | None = None
248
+ self.queue: list[Track] = []
249
+ self.history: list[Track] = []
250
+ self.loop = False
251
+ self.message = "Ready. Press / to search."
252
+ self._lock = threading.Lock()
253
+ self.mpv = MPV(self._finished)
254
+
255
+ def start(self, track: Track, *, build_mix: bool = True, remember_current: bool = True) -> None:
256
+ with self._lock:
257
+ if remember_current and self.current and self.current.url != track.url:
258
+ self.history.append(self.current)
259
+ self.current = track
260
+ self.mpv.play(track, self.loop)
261
+ self.message = f"Playing: {track.title}"
262
+ if build_mix:
263
+ threading.Thread(target=self._build_mix, args=(track,), daemon=True).start()
264
+
265
+ def _build_mix(self, track: Track) -> None:
266
+ try:
267
+ mix = YouTube.mix_for(track)
268
+ with self._lock:
269
+ if self.current == track:
270
+ existing = {item.url for item in self.queue}
271
+ self.queue.extend(item for item in mix if item.url not in existing)
272
+ self.message = f"Mix ready: {len(self.queue)} tracks queued"
273
+ except RuntimeError:
274
+ pass
275
+
276
+ def next(self) -> None:
277
+ with self._lock:
278
+ if not self.queue:
279
+ self.message = "Queue is empty"
280
+ return
281
+ next_track = self.queue.pop(0)
282
+ self.start(next_track, build_mix=False)
283
+
284
+ def previous(self) -> None:
285
+ with self._lock:
286
+ if not self.history:
287
+ self.message = "No previous track"
288
+ return
289
+ previous_track = self.history.pop()
290
+ if self.current:
291
+ self.queue.insert(0, self.current)
292
+ self.start(previous_track, build_mix=False, remember_current=False)
293
+
294
+ def _finished(self) -> None:
295
+ if not self.loop:
296
+ self.next()
297
+
298
+ def toggle_loop(self) -> None:
299
+ self.loop = not self.loop
300
+ self.mpv.set_loop(self.loop)
301
+ self.message = f"Loop {'on' if self.loop else 'off'}"
302
+
303
+ def close(self) -> None:
304
+ self.mpv.close()
305
+
306
+
307
+ class TUI:
308
+ def __init__(self, screen: curses.window, player: Player, initial_query: str = "") -> None:
309
+ self.screen, self.player = screen, player
310
+ self.results: list[Track] = []
311
+ self.result_index = 0
312
+ self.queue_index = 0
313
+ self.tab = 0 # 0 results, 1 queue
314
+ self.running = True
315
+ self.showing_help = False
316
+ curses.curs_set(0)
317
+ screen.nodelay(True)
318
+ screen.keypad(True)
319
+ if initial_query:
320
+ self.search(initial_query)
321
+
322
+ def search(self, query: str) -> None:
323
+ self.player.message = f"Searching YouTube for: {query}"
324
+ self.draw()
325
+ try:
326
+ self.results = YouTube.search(query)
327
+ self.result_index = 0
328
+ self.tab = 0
329
+ self.player.message = f"{len(self.results)} results for “{query}”"
330
+ except RuntimeError as error:
331
+ self.player.message = str(error)
332
+
333
+ def prompt_search(self) -> None:
334
+ height, _ = self.screen.getmaxyx()
335
+ self.screen.nodelay(False)
336
+ curses.curs_set(1)
337
+ # curses.wrapper() enables noecho for the TUI. Turn echo on only for this
338
+ # text field so a query is visible as the user types it.
339
+ curses.echo()
340
+ self.screen.move(height - 1, 0)
341
+ self.screen.clrtoeol()
342
+ self.screen.addstr(height - 1, 0, "Search: ")
343
+ try:
344
+ query = self.screen.getstr(height - 1, 8).decode().strip()
345
+ except KeyboardInterrupt:
346
+ query = ""
347
+ finally:
348
+ curses.noecho()
349
+ curses.curs_set(0)
350
+ self.screen.nodelay(True)
351
+ if query:
352
+ self.search(query)
353
+
354
+ @staticmethod
355
+ def clipped(value: str, width: int) -> str:
356
+ return value if len(value) <= width else value[: max(0, width - 1)] + "…"
357
+
358
+ def draw_track_list(self, items: list[Track], selected: int, top: int, height: int, width: int) -> None:
359
+ if not items:
360
+ self.screen.addstr(top, 2, "Nothing here yet.", curses.A_DIM)
361
+ return
362
+ start = max(0, min(selected - height + 1, len(items) - height))
363
+ for line, index in enumerate(range(start, min(len(items), start + height))):
364
+ item = items[index]
365
+ marker = "›" if index == selected else " "
366
+ duration = format_time(item.duration)
367
+ text = f"{marker} {index + 1:2}. {item.label} [{duration}]"
368
+ attr = curses.A_REVERSE if index == selected else curses.A_NORMAL
369
+ self.screen.addnstr(top + line, 1, self.clipped(text, width - 2), width - 2, attr)
370
+
371
+ def draw(self) -> None:
372
+ self.screen.erase()
373
+ height, width = self.screen.getmaxyx()
374
+ current = self.player.current
375
+ position, paused = self.player.mpv.state() if current else (0, False)
376
+ title = current.title if current else "Nothing playing"
377
+ duration = current.duration if current else 0
378
+ mode = "PAUSED" if paused else "PLAYING" if current else "IDLE"
379
+ loop = " LOOP" if self.player.loop else ""
380
+ self.screen.addnstr(0, 1, f" OPENTUNE · {mode}{loop}", width - 2, curses.A_BOLD)
381
+ self.screen.hline(1, 0, curses.ACS_HLINE, width)
382
+ self.screen.addnstr(2, 2, self.clipped(title, width - 4), width - 4, curses.A_BOLD)
383
+ self.screen.addnstr(3, 2, f"{format_time(position)} / {format_time(duration)}", width - 4, curses.A_DIM)
384
+ self.screen.hline(5, 0, curses.ACS_HLINE, width)
385
+ tabs = "[ Results ]" if self.tab == 0 else " Results "
386
+ tabs += " " + ("[ Queue ]" if self.tab == 1 else " Queue ")
387
+ self.screen.addnstr(6, 2, tabs, width - 4, curses.A_BOLD)
388
+ list_height = max(1, height - 10)
389
+ if self.showing_help:
390
+ self.draw_help(8, width, list_height)
391
+ elif self.tab == 0:
392
+ self.draw_track_list(self.results, self.result_index, 8, list_height, width)
393
+ else:
394
+ self.draw_track_list(self.player.queue, self.queue_index, 8, list_height, width)
395
+ self.screen.hline(height - 2, 0, curses.ACS_HLINE, width)
396
+ status = self.clipped(self.player.message, width - 4)
397
+ self.screen.addnstr(height - 1, 2, status, width - 4, curses.A_DIM)
398
+ self.screen.refresh()
399
+
400
+ def draw_help(self, top: int, width: int, height: int) -> None:
401
+ lines = [
402
+ "KEY REFERENCE (press ? or Esc to return)",
403
+ "",
404
+ "j / ↓ down k / ↑ up Enter play selection",
405
+ "Space pause/play h previous l next",
406
+ "H rewind 10s L forward 10s Ctrl-l toggle loop",
407
+ "Tab Results/Queue / search q quit",
408
+ "",
409
+ "Selecting a result starts playback and prepares a related mix in Queue.",
410
+ ]
411
+ for index, line in enumerate(lines[:height]):
412
+ attr = curses.A_BOLD if index == 0 else curses.A_NORMAL
413
+ self.screen.addnstr(top + index, 2, self.clipped(line, width - 4), width - 4, attr)
414
+
415
+ def move(self, delta: int) -> None:
416
+ if self.tab == 0:
417
+ self.result_index = max(0, min(len(self.results) - 1, self.result_index + delta))
418
+ else:
419
+ self.queue_index = max(0, min(len(self.player.queue) - 1, self.queue_index + delta))
420
+
421
+ def select(self) -> None:
422
+ if self.tab == 0 and self.results:
423
+ self.player.start(self.results[self.result_index])
424
+ elif self.tab == 1 and self.player.queue:
425
+ with self.player._lock:
426
+ track = self.player.queue.pop(self.queue_index)
427
+ self.queue_index = max(0, min(self.queue_index, len(self.player.queue) - 1))
428
+ self.player.start(track, build_mix=False)
429
+
430
+ def handle(self, key: int) -> None:
431
+ if self.showing_help:
432
+ if key in (ord("?"), 27, ord("q")):
433
+ self.showing_help = False
434
+ return
435
+ if key in (ord("q"), 27):
436
+ self.running = False
437
+ elif key in (ord("j"), curses.KEY_DOWN):
438
+ self.move(1)
439
+ elif key in (ord("k"), curses.KEY_UP):
440
+ self.move(-1)
441
+ elif key in (9,):
442
+ self.tab = 1 - self.tab
443
+ elif key in (10, 13, curses.KEY_ENTER):
444
+ self.select()
445
+ elif key == ord(" "):
446
+ self.player.mpv.toggle_pause()
447
+ elif key == ord("h"):
448
+ self.player.previous()
449
+ elif key == ord("l"):
450
+ self.player.next()
451
+ elif key == ord("H"):
452
+ self.player.mpv.seek(-10)
453
+ elif key == ord("L"):
454
+ self.player.mpv.seek(10)
455
+ elif key == 12: # Ctrl-l
456
+ self.player.toggle_loop()
457
+ elif key == ord("/"):
458
+ self.prompt_search()
459
+ elif key == ord("?"):
460
+ self.showing_help = True
461
+
462
+ def run(self) -> None:
463
+ while self.running:
464
+ self.draw()
465
+ key = self.screen.getch()
466
+ if key != -1:
467
+ self.handle(key)
468
+ time.sleep(0.08)
469
+
470
+
471
+ def main() -> int:
472
+ parser = argparse.ArgumentParser(
473
+ prog="opentune",
474
+ description="A Vim-keyed terminal music player for YouTube audio streams.",
475
+ epilog=HELP_TEXT,
476
+ formatter_class=argparse.RawDescriptionHelpFormatter,
477
+ )
478
+ parser.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
479
+ parser.add_argument("query", nargs="*", help="Search query to open on launch")
480
+ args = parser.parse_args()
481
+ missing = require_tools()
482
+ if missing:
483
+ print(f"opentune: {missing}", file=sys.stderr)
484
+ return 1
485
+ player = Player()
486
+ try:
487
+ curses.wrapper(lambda screen: TUI(screen, player, " ".join(args.query)).run())
488
+ except curses.error as error:
489
+ print(f"opentune: terminal UI error: {error}", file=sys.stderr)
490
+ return 1
491
+ finally:
492
+ player.close()
493
+ return 0
494
+
495
+
496
+ if __name__ == "__main__":
497
+ raise SystemExit(main())
@@ -0,0 +1,288 @@
1
+ Metadata-Version: 2.4
2
+ Name: opentune
3
+ Version: 0.2.1
4
+ Summary: A Vim-keyed terminal music player for YouTube audio streams
5
+ License-Expression: Apache-2.0
6
+ Keywords: music,youtube,terminal,tui,mpv,yt-dlp
7
+ Classifier: Development Status :: 3 - Alpha
8
+ Classifier: Environment :: Console
9
+ Classifier: Intended Audience :: End Users/Desktop
10
+ Classifier: Operating System :: POSIX :: Linux
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3 :: Only
13
+ Classifier: Programming Language :: Python :: 3.10
14
+ Classifier: Programming Language :: Python :: 3.11
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Programming Language :: Python :: 3.13
17
+ Classifier: Topic :: Multimedia :: Sound/Audio :: Players
18
+ Classifier: Topic :: Terminals
19
+ Requires-Python: >=3.10
20
+ Description-Content-Type: text/markdown
21
+ License-File: LICENSE
22
+ Dynamic: license-file
23
+
24
+ # OpenTune
25
+
26
+ OpenTune is a terminal music player for Linux/Unix systems. Search YouTube for a song, choose a result using Vim-style keys, and listen without leaving the terminal.
27
+
28
+ It is deliberately small: OpenTune streams audio; it does not download songs, require a browser, require a YouTube account, or maintain a media library. Playback happens in a full-screen terminal UI (TUI).
29
+
30
+ ## What it can do
31
+
32
+ - Search YouTube from the command line: `opentune <music name>`
33
+ - Show several matching tracks with artist/channel and duration
34
+ - Play, pause, go to the next/previous track, seek, and loop a track
35
+ - Use Vim-like navigation (`h`, `j`, `k`, `l`) as well as arrow keys
36
+ - Create a short related mix after you choose a song
37
+ - Show the upcoming mix in a Queue tab
38
+ - Display the playing title, elapsed time, total duration, and playback state
39
+
40
+ ## How it works
41
+
42
+ OpenTune coordinates two established command-line programs:
43
+
44
+ 1. `yt-dlp` searches YouTube and returns video title, channel, duration, and URL.
45
+ 2. OpenTune shows those results in its terminal UI.
46
+ 3. When a track is selected, `mpv` opens the YouTube URL and streams the best available audio format.
47
+ 4. OpenTune controls `mpv` through a private local socket, so pause, seek, loop, and progress updates work while the TUI remains open.
48
+ 5. In the background, OpenTune asks YouTube for its radio/mix playlist seeded by the selected video, then filters alternate uploads of the same song before filling the queue. If YouTube does not expose a radio playlist, OpenTune falls back to other songs from the selected artist.
49
+
50
+ Nothing is downloaded or uploaded by OpenTune. Search, stream playback, and mix generation need an active internet connection.
51
+
52
+ ## Requirements
53
+
54
+ Install these before installing OpenTune:
55
+
56
+ - Python 3.10 or newer
57
+ - [`mpv`](https://mpv.io/) — audio playback and YouTube streaming
58
+ - [`yt-dlp`](https://github.com/yt-dlp/yt-dlp) — YouTube search metadata
59
+
60
+ Examples for common Linux distributions:
61
+
62
+ ```sh
63
+ # Arch Linux
64
+ sudo pacman -S python mpv yt-dlp
65
+
66
+ # Debian / Ubuntu
67
+ sudo apt install python3 python3-pip mpv yt-dlp
68
+
69
+ # Fedora
70
+ sudo dnf install python3 python3-pip mpv yt-dlp
71
+ ```
72
+
73
+ If YouTube changes its site, updating `yt-dlp` is usually the first thing to try when search or playback stops working.
74
+
75
+ ## Installation
76
+
77
+ On current Arch Linux, do **not** use `pip install --user` for this project. Arch marks its system Python as externally managed (PEP 668), so `pip` correctly refuses to modify it. Choose one of the following isolated installation methods.
78
+
79
+ ### Recommended: install the CLI with pipx
80
+
81
+ `pipx` installs Python applications into their own virtual environments while exposing their commands on your `PATH`. This is the best option when you want to run `opentune` from any directory.
82
+
83
+ ```sh
84
+ # Install pipx once on Arch Linux
85
+ sudo pacman -S python-pipx
86
+ pipx ensurepath
87
+
88
+ # Open a new terminal, then install this checkout
89
+ cd /path/to/opentune
90
+ pipx install .
91
+ ```
92
+
93
+ Afterward, use it like any other command:
94
+
95
+ ```sh
96
+ opentune "Daft Punk Get Lucky"
97
+ opentune --help
98
+ ```
99
+
100
+ If `opentune` is not found immediately after `pipx ensurepath`, restart the shell. `pipx` normally adds `~/.local/bin` to your `PATH`.
101
+
102
+ ### Updating an installation from this checkout
103
+
104
+ `pipx upgrade opentune` checks the package's published source (usually PyPI). It cannot detect edits made only in this local Git checkout, even if the local version number changes. To install the current checkout after pulling or editing code, run this from the project directory:
105
+
106
+ ```sh
107
+ pipx install --force .
108
+ ```
109
+
110
+ Or use the included shortcut:
111
+
112
+ ```sh
113
+ make upgrade
114
+ ```
115
+
116
+ Confirm the installed release with:
117
+
118
+ ```sh
119
+ opentune --version
120
+ ```
121
+
122
+ OpenTune follows semantic versioning: patch releases (for example `0.2.0` → `0.2.1`) contain fixes, while minor releases add backwards-compatible features.
123
+
124
+ ### Alternative: project virtual environment
125
+
126
+ Use this when developing OpenTune or when you only need the command from this checkout:
127
+
128
+ ```sh
129
+ cd /path/to/opentune
130
+ python3 -m venv .venv
131
+ source .venv/bin/activate
132
+ python -m pip install .
133
+ opentune "Daft Punk Get Lucky"
134
+ ```
135
+
136
+ Important: omit `--user` inside a virtual environment. The virtual environment already isolates the installation, and Python intentionally hides user site-packages from it.
137
+
138
+ While the environment is active, `opentune` works normally. After `deactivate`, either activate it again or run the executable explicitly:
139
+
140
+ ```sh
141
+ .venv/bin/opentune "Daft Punk Get Lucky"
142
+ ```
143
+
144
+ Do not use `--break-system-packages`; it bypasses Arch's protection for the system Python and is unnecessary for OpenTune.
145
+
146
+ ### Install from PyPI
147
+
148
+ After OpenTune's first PyPI release, installation and future upgrades will work from any directory:
149
+
150
+ ```sh
151
+ pipx install opentune
152
+ pipx upgrade opentune
153
+ ```
154
+
155
+ Maintainers can follow [the PyPI release guide](docs/PYPI_RELEASE.md) to configure Trusted Publishing and publish releases.
156
+
157
+ ### Run without installing
158
+
159
+ For development or a one-off run from this checkout:
160
+
161
+ ```sh
162
+ ./bin/opentune "Daft Punk Get Lucky"
163
+ ```
164
+
165
+ ## Usage
166
+
167
+ Start OpenTune and search immediately:
168
+
169
+ ```sh
170
+ opentune "Daft Punk Get Lucky"
171
+ ```
172
+
173
+ Words after `opentune` form the search query, so quotes are optional unless your shell needs them:
174
+
175
+ ```sh
176
+ opentune Kendrick Lamar
177
+ ```
178
+
179
+ Start with an empty player and search from inside the TUI instead:
180
+
181
+ ```sh
182
+ opentune
183
+ ```
184
+
185
+ Use the standard command help at any time:
186
+
187
+ ```sh
188
+ opentune --help
189
+ ```
190
+
191
+ ## First run
192
+
193
+ 1. Run `opentune <song or artist>`.
194
+ 2. A list of YouTube matches appears in the **Results** tab.
195
+ 3. Move with `j`/`k` or `↓`/`↑`.
196
+ 4. Press `Enter` to start the highlighted result.
197
+ 5. The title and time appear at the top of the screen.
198
+ 6. OpenTune prepares related tracks in the background. Press `Tab` to view them in the **Queue** tab.
199
+ 7. Press `q` or `Esc` to quit.
200
+
201
+ ## Keybinds
202
+
203
+ | Key | Action |
204
+ | --- | --- |
205
+ | `j` or `↓` | Move selection down in Results or Queue |
206
+ | `k` or `↑` | Move selection up in Results or Queue |
207
+ | `Enter` | Play the selected result or queue item |
208
+ | `Space` | Pause or resume playback |
209
+ | `h` | Play the previous track, if there is one |
210
+ | `l` | Play the next queued track |
211
+ | `H` (`Shift+h`) | Rewind 10 seconds |
212
+ | `L` (`Shift+l`) | Forward 10 seconds |
213
+ | `Ctrl+l` | Toggle looping of the current track |
214
+ | `Tab` | Switch between **Results** and **Queue** |
215
+ | `/` | Open a search prompt |
216
+ | `?` | Open/close the in-player key reference |
217
+ | `q` or `Esc` | Quit OpenTune (or close the `?` help overlay) |
218
+
219
+ ## Results, playback, and the queue
220
+
221
+ ### Results tab
222
+
223
+ The Results tab contains the latest YouTube search. Each row shows its title, channel/uploader when available, and duration. Press `Enter` to play a result. Choosing a new search result replaces the current track and adds the former track to playback history, allowing `h` to go back.
224
+
225
+ ### Queue tab
226
+
227
+ Selecting a search result starts a short YouTube radio-style mix. OpenTune filters duplicate uploads and alternate versions of the selected song, so the queue should contain different songs rather than the same title from several channels. The Queue tab shows the tracks waiting to play. You can:
228
+
229
+ - Press `l` to start the next queued track.
230
+ - Highlight a queued track and press `Enter` to jump directly to it.
231
+ - Use `Tab` to return to Results.
232
+
233
+ The queue is kept in memory for the current session only. It is cleared when OpenTune exits.
234
+
235
+ ### Looping
236
+
237
+ `Ctrl+l` loops the currently playing track. The screen header displays `LOOP` while it is enabled. Turn it off with `Ctrl+l` again; then, when a track ends, OpenTune advances to the next item in the queue.
238
+
239
+ ## Troubleshooting
240
+
241
+ ### `opentune: command not found`
242
+
243
+ The user-level bin directory is likely not on `PATH`. Run:
244
+
245
+ ```sh
246
+ export PATH="$HOME/.local/bin:$PATH"
247
+ ```
248
+
249
+ Then add it to `~/.zshrc` or your shell's startup file as described above.
250
+
251
+ ### Missing `mpv` or `yt-dlp`
252
+
253
+ OpenTune checks for both commands at startup. Install the missing package with your distribution's package manager, then run OpenTune again.
254
+
255
+ ### Search or playback fails
256
+
257
+ - Confirm that the internet connection and YouTube are reachable.
258
+ - Update `yt-dlp`; YouTube changes can require a newer version.
259
+ - Try the URL in `mpv` directly to distinguish an OpenTune issue from a `mpv`/`yt-dlp` issue:
260
+
261
+ ```sh
262
+ mpv --no-video "https://www.youtube.com/watch?v=VIDEO_ID"
263
+ ```
264
+
265
+ ### The terminal UI looks broken
266
+
267
+ OpenTune needs an interactive terminal with enough space for the player. Enlarge the terminal window and avoid running it through a non-interactive shell or redirected output.
268
+
269
+ ## Project layout
270
+
271
+ ```text
272
+ opentune/
273
+ ├── bin/opentune # launcher for running from this checkout
274
+ ├── opentune/__main__.py # CLI, terminal UI, search, queue, and mpv control
275
+ ├── tests/ # small automated checks
276
+ ├── Makefile # install, local pipx upgrade, and test shortcuts
277
+ └── pyproject.toml # package metadata and installed `opentune` command
278
+ ```
279
+
280
+ ## Current scope and limitations
281
+
282
+ OpenTune v1 is a streaming player. It does not yet provide persistent playlists, saved favorites, downloads, lyrics, volume controls, or system media-key integration. These are good candidates for later releases, but the current goal is fast terminal search and playback with a lightweight mix queue.
283
+
284
+ ## License
285
+
286
+ Copyright 2026 Rudraksh.
287
+
288
+ OpenTune is licensed under the [Apache License 2.0](LICENSE). It includes an explicit patent grant; see [NOTICE](NOTICE) for the project attribution notice.
@@ -0,0 +1,8 @@
1
+ opentune/__init__.py,sha256=I2yhmHsPpw_O5xGvZQgnwU8rWYEhjh1xCdA-HYhNN-I,61
2
+ opentune/__main__.py,sha256=kGa0M9RN-H3-rKogG0EZQVBw0Qe7CzraiXxniRbQgiI,18696
3
+ opentune-0.2.1.dist-info/licenses/LICENSE,sha256=UpiDt2c2SRYNOl_hfkRYfSScU9wrJ5-Zu-yq4tuxFM4,11338
4
+ opentune-0.2.1.dist-info/METADATA,sha256=dA0P7CMNHQ0WTaGXZPobcYbNvM06Bb10Fmy_2FSTY2s,10370
5
+ opentune-0.2.1.dist-info/WHEEL,sha256=K260EYznzXsJYBQGqmI8VTxEdiZYNvDZwW9cBh9-_MA,91
6
+ opentune-0.2.1.dist-info/entry_points.txt,sha256=78e_ShJiGx-LXv5cWDGPV5mRiK0gPiu8vW8vkYfv_T0,52
7
+ opentune-0.2.1.dist-info/top_level.txt,sha256=fO5xHwCf9HjxPAHLoufKolZR5q0VerD8KIfJ2-09jsE,9
8
+ opentune-0.2.1.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (83.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ opentune = opentune.__main__:main
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Rudraksh
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1 @@
1
+ opentune