From 701ff3a6d34aa667715205d81c410f49b84ac310 Mon Sep 17 00:00:00 2001 From: ingo Date: Sat, 19 Sep 2026 14:18:15 +0200 Subject: [PATCH] First checkin of the sources --- README.claude.md | 99 ++++++++ app/__init__.py | 0 app/ffmpeg_client.py | 32 +++ app/models.py | 94 ++++++++ app/screens/__init__.py | 4 + app/screens/error_screen.py | 61 +++++ app/screens/format_select_screen.py | 123 ++++++++++ app/tui_app.py | 356 ++++++++++++++++++++++++++++ app/ytdlp_client.py | 119 ++++++++++ i18n/de/help.md | 17 ++ i18n/de/strings.json | 45 ++++ i18n/en/help.md | 15 ++ i18n/en/strings.json | 45 ++++ main.py | 45 ++++ pyproject.toml | 8 + requirements.txt | 2 + uv.lock | 131 ++++++++++ 17 files changed, 1196 insertions(+) create mode 100644 README.claude.md create mode 100644 app/__init__.py create mode 100644 app/ffmpeg_client.py create mode 100644 app/models.py create mode 100644 app/screens/__init__.py create mode 100644 app/screens/error_screen.py create mode 100644 app/screens/format_select_screen.py create mode 100644 app/tui_app.py create mode 100644 app/ytdlp_client.py create mode 100644 i18n/de/help.md create mode 100644 i18n/de/strings.json create mode 100644 i18n/en/help.md create mode 100644 i18n/en/strings.json create mode 100644 main.py create mode 100644 pyproject.toml create mode 100644 requirements.txt create mode 100644 uv.lock diff --git a/README.claude.md b/README.claude.md new file mode 100644 index 0000000..5468e6d --- /dev/null +++ b/README.claude.md @@ -0,0 +1,99 @@ +# yt-dlp Download Manager (Textual TUI) + +A small [Textual](https://textual.textualize.io/) user interface around a +specific [yt-dlp](https://github.com/yt-dlp/yt-dlp) workflow: enter a film +URL, inspect the `m3u8_native` formats yt-dlp reports for it, pick the +part(s) to download, and download (merging audio/video with `ffmpeg` when +they come as separate streams). + +## Requirements + +* Python 3.10+ +* [`yt-dlp`](https://pypi.org/project/yt-dlp/) and `ffmpeg` available on + your `PATH` (`ffmpeg` is a system package, not a Python one — install it + with your OS package manager, e.g. `apt install ffmpeg` / + `brew install ffmpeg`). +* Python packages from `requirements.txt`: + + ```bash + pip install -r requirements.txt + ``` + +## Running + +```bash +python main.py +``` + +## Project layout + +``` +main.py Entry point; wires up i18n, then starts the app +app/ + tui_app.py The Textual App: layout + all screen wiring + models.py FormatEntry / VideoInfo + the filtering logic + that decides split vs. combined audio/video + ytdlp_client.py async wrappers for `yt-dlp --dump-json` and + `yt-dlp -f -o ` (with progress) + ffmpeg_client.py async wrapper for the `ffmpeg -c copy` merge + screens/ + format_select_screen.py Modal format-selection table (audio & video) + error_screen.py Modal error dialog +lib/i18n/ The provided i18n library (unmodified aside from + a small `__init__.py` re-export so that + `from i18n import I18n` works as documented) +i18n/en/, i18n/de/ This application's own translation data + (strings.json + help.md), as expected by the + library at /i18n// +``` + +The i18n *library* is kept in `lib/i18n` (added to `sys.path` by +`main.py`), separate from the i18n *data* directory `i18n/` at the project +root, since the library expects its translation data at +`/i18n//strings.json` — the same name as the library's +own package directory would use if it were placed at the project root. + +## How the app maps to the requirements + +* **Info gathering** — `yt-dlp -i --dump-json ` is run in + `ytdlp_client.fetch_info`. Only formats with `protocol == "m3u8_native"` + are kept (`models.VideoInfo.from_json`); anything else (including + `https`) is discarded. +* **Split vs. combined** — if any surviving format has + `resolution == "audio only"`, the film is treated as split and two + selection dialogs are shown (audio, then video). Otherwise a single + dialog is shown. +* **Selection dialogs** — `screens/format_select_screen.py` renders a + table with `format_id`, `resolution`, `acodec`, `vcodec`, `format`. + Cancelling, pressing Escape, or an empty table all resolve to "no valid + entry", which the main screen turns into an error dialog and a disabled + **Start download** button. +* **Main screen** — shows `Audio: ...` / `Video: ...` lines (underscores + in the format text replaced with spaces), a progress line + bar, and the + three buttons from the layout sketch. +* **Downloading** — `yt-dlp -i url -o filename -f stream_id`, run with + `--newline` so `ytdlp_client.download` can parse `[download] NN.N%` + lines and call back into the UI at most once per whole percentage point. + The progress text is ` - Audio|Video|Audio + Video - NN%`. +* **Merging** — for split downloads, both parts land in temporary files + next to the destination; once both finish, `ffmpeg -i video -i audio + -c copy ` merges them, after which the temp files are + deleted (in a `finally` block, so this also happens if something fails + partway through). +* **Async** — all subprocess-driving and status-bar-updating code + (`select_parts`, `start_download`, the `ytdlp_client`/`ffmpeg_client` + functions, and the progress callbacks) is `async` and is launched from + button presses via Textual workers so the UI stays responsive. + +## Notes / assumptions + +* The two example JSON documents from the requirements are used as the + basis for the filtering logic and are exercised by an ad-hoc test during + development; there is no bundled test suite since none was requested. +* Temporary files for split downloads are named + `.video.tmp.mp4` / `.audio.tmp.mp4` + next to the destination file. +* If "Select parts" is used again after a successful selection, the + previous selection is only replaced once a new one completes + successfully; cancelling out of the new attempt clears the selection and + disables **Start download**, matching "no default selection". diff --git a/app/__init__.py b/app/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/app/ffmpeg_client.py b/app/ffmpeg_client.py new file mode 100644 index 0000000..d2d9c40 --- /dev/null +++ b/app/ffmpeg_client.py @@ -0,0 +1,32 @@ +"""Async wrapper around ``ffmpeg`` used to merge separate audio/video files.""" + +from __future__ import annotations + +import asyncio + + +class FfmpegError(RuntimeError): + """Raised when ffmpeg fails to merge the audio and video streams.""" + + +async def merge(video_path: str, audio_path: str, destination: str) -> None: + """Run ``ffmpeg -i video_path -i audio_path -c copy destination``.""" + process = await asyncio.create_subprocess_exec( + "ffmpeg", + "-y", + "-i", + video_path, + "-i", + audio_path, + "-c", + "copy", + destination, + stdout=asyncio.subprocess.PIPE, + stderr=asyncio.subprocess.STDOUT, + ) + stdout, _ = await process.communicate() + return_code = await process.wait() + if return_code != 0: + message = stdout.decode("utf-8", errors="replace").strip() + tail = "\n".join(message.splitlines()[-10:]) + raise FfmpegError(tail or f"ffmpeg exited with status {return_code}.") diff --git a/app/models.py b/app/models.py new file mode 100644 index 0000000..91fd61d --- /dev/null +++ b/app/models.py @@ -0,0 +1,94 @@ +"""Data models and pure logic for interpreting yt-dlp ``--dump-json`` output. + +None of this module touches the UI or external processes; it only knows how +to turn a parsed JSON document into the pieces of information the rest of +the application needs. +""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import Any + +#: The only protocol value considered downloadable by this application. +VALID_PROTOCOL = "m3u8_native" + +#: The resolution value yt-dlp uses to mark an audio-only format. +AUDIO_ONLY_RESOLUTION = "audio only" + + +@dataclass(frozen=True) +class FormatEntry: + """One selectable entry from yt-dlp's ``formats`` list. + + Attributes correspond 1:1 to the yt-dlp JSON attributes named in the + requirements: ``format_id``, ``resolution``, ``acodec``, ``vcodec`` and + ``format``. ``protocol`` is kept too since it drives filtering. + """ + + format_id: str + resolution: str + acodec: str + vcodec: str + format: str + protocol: str + + @property + def is_audio_only(self) -> bool: + return self.resolution == AUDIO_ONLY_RESOLUTION + + @property + def display_text(self) -> str: + """The ``format`` attribute with underscores replaced by blanks.""" + return self.format.replace("_", " ") + + @classmethod + def from_json(cls, raw: dict[str, Any]) -> "FormatEntry": + def _clean(value: Any) -> str: + if value is None or value == "none": + return "none" + return str(value) + + return cls( + format_id=str(raw.get("format_id", "")), + resolution=str(raw.get("resolution", "")), + acodec=_clean(raw.get("acodec")), + vcodec=_clean(raw.get("vcodec")), + format=str(raw.get("format", "")), + protocol=str(raw.get("protocol", "")), + ) + + +@dataclass +class VideoInfo: + """Everything extracted from one yt-dlp ``--dump-json`` document.""" + + fulltitle: str + audio_formats: list[FormatEntry] + video_formats: list[FormatEntry] + + @property + def is_split(self) -> bool: + """True when audio and video are offered as separate formats.""" + return len(self.audio_formats) > 0 + + @classmethod + def from_json(cls, raw: dict[str, Any]) -> "VideoInfo": + formats_raw = raw.get("formats") or [] + + # Only m3u8_native survives; anything using https (or any other + # protocol) is skipped, per the requirements. + filtered = [ + FormatEntry.from_json(f) + for f in formats_raw + if f.get("protocol") == VALID_PROTOCOL + ] + + audio_formats = [f for f in filtered if f.is_audio_only] + video_formats = [f for f in filtered if not f.is_audio_only] + + return cls( + fulltitle=str(raw.get("fulltitle", "")), + audio_formats=audio_formats, + video_formats=video_formats, + ) diff --git a/app/screens/__init__.py b/app/screens/__init__.py new file mode 100644 index 0000000..406170e --- /dev/null +++ b/app/screens/__init__.py @@ -0,0 +1,4 @@ +from .error_screen import ErrorScreen +from .format_select_screen import FormatSelectScreen + +__all__ = ["ErrorScreen", "FormatSelectScreen"] diff --git a/app/screens/error_screen.py b/app/screens/error_screen.py new file mode 100644 index 0000000..509a44c --- /dev/null +++ b/app/screens/error_screen.py @@ -0,0 +1,61 @@ +"""A simple modal dialog for reporting error messages to the user.""" + +from __future__ import annotations + +from textual.app import ComposeResult +from textual.containers import Container, Horizontal +from textual.screen import ModalScreen +from textual.widgets import Button, Label, Static + +from i18n import I18n + + +class ErrorScreen(ModalScreen[None]): + """Modal dialog showing a title and a message, dismissed via OK.""" + + DEFAULT_CSS = """ + ErrorScreen { + align: center middle; + } + + ErrorScreen > Container { + width: 60%; + max-width: 70; + height: auto; + border: thick $error 80%; + background: $surface; + padding: 1 2; + } + + ErrorScreen #error-title { + text-style: bold; + color: $error; + margin-bottom: 1; + } + + ErrorScreen #error-message { + margin-bottom: 1; + } + + ErrorScreen Horizontal { + align-horizontal: center; + height: auto; + } + """ + + def __init__(self, message: str, *, title: str | None = None) -> None: + super().__init__() + self._message = message + self._title = title + + def compose(self) -> ComposeResult: + i18n = I18n() + title = self._title or i18n.t("dialog.error_title", default="Error") + with Container(): + yield Label(title, id="error-title") + yield Static(self._message, id="error-message") + with Horizontal(): + yield Button(i18n.t("button.ok", default="OK"), id="ok", variant="error") + + def on_button_pressed(self, event: Button.Pressed) -> None: + self.dismiss(None) diff --git a/app/screens/format_select_screen.py b/app/screens/format_select_screen.py new file mode 100644 index 0000000..6886ce2 --- /dev/null +++ b/app/screens/format_select_screen.py @@ -0,0 +1,123 @@ +"""Modal dialog that lets the user pick one format from a table. + +Used both for the audio-only selection and the video (or combined +audio+video) selection, since the table layout is identical: format_id, +resolution, acodec, vcodec, format. +""" + +from __future__ import annotations + +from textual.app import ComposeResult +from textual.containers import Container, Horizontal +from textual.screen import ModalScreen +from textual.widgets import Button, DataTable, Label + +from i18n import I18n + +from ..models import FormatEntry + + +class FormatSelectScreen(ModalScreen[FormatEntry | None]): + """Shows ``entries`` in a table and returns the row the user picked. + + Returns ``None`` (via Cancel, Escape, or an empty table) so the caller + can treat that as "no valid entry selected". + """ + + DEFAULT_CSS = """ + FormatSelectScreen { + align: center middle; + } + + FormatSelectScreen > Container { + width: 90%; + max-width: 120; + height: auto; + max-height: 80%; + border: thick $primary 80%; + background: $surface; + padding: 1 2; + } + + FormatSelectScreen #dialog-title { + text-style: bold; + margin-bottom: 1; + } + + FormatSelectScreen DataTable { + height: auto; + max-height: 20; + margin-bottom: 1; + } + + FormatSelectScreen Horizontal { + align-horizontal: center; + height: auto; + } + """ + + BINDINGS = [("escape", "cancel", "Cancel")] + + def __init__(self, title: str, entries: list[FormatEntry]) -> None: + super().__init__() + self._title = title + self._entries = entries + + def compose(self) -> ComposeResult: + i18n = I18n() + with Container(): + yield Label(self._title, id="dialog-title") + table: DataTable[str] = DataTable(id="format-table", cursor_type="row") + table.add_columns( + i18n.t("table.format_id", default="Format ID"), + i18n.t("table.resolution", default="Resolution"), + i18n.t("table.acodec", default="Audio codec"), + i18n.t("table.vcodec", default="Video codec"), + i18n.t("table.format", default="Format"), + ) + for entry in self._entries: + table.add_row( + entry.format_id, + entry.resolution, + entry.acodec, + entry.vcodec, + entry.format, + key=entry.format_id, + ) + yield table + with Horizontal(): + yield Button( + i18n.t("button.ok", default="OK"), + id="select-ok", + variant="primary", + disabled=not self._entries, + ) + yield Button(i18n.t("button.cancel", default="Cancel"), id="select-cancel") + + def on_mount(self) -> None: + if self._entries: + self.query_one(DataTable).focus() + + def on_data_table_row_selected(self, event: DataTable.RowSelected) -> None: + self._confirm(event.row_key.value) + + def on_button_pressed(self, event: Button.Pressed) -> None: + if event.button.id == "select-ok": + table = self.query_one(DataTable) + if table.row_count == 0 or table.cursor_row is None: + self.dismiss(None) + return + row_key, _ = table.coordinate_to_cell_key(table.cursor_coordinate) + self._confirm(row_key.value) + else: + self.dismiss(None) + + def action_cancel(self) -> None: + self.dismiss(None) + + def _confirm(self, format_id: str | None) -> None: + for entry in self._entries: + if entry.format_id == format_id: + self.dismiss(entry) + return + self.dismiss(None) diff --git a/app/tui_app.py b/app/tui_app.py new file mode 100644 index 0000000..f9d8a18 --- /dev/null +++ b/app/tui_app.py @@ -0,0 +1,356 @@ +"""The Textual application: a small front end for a specific yt-dlp workflow.""" + +from __future__ import annotations + +from pathlib import Path + +from textual.app import App, ComposeResult +from textual.containers import Horizontal, Vertical +from textual.widgets import Button, Footer, Header, Input, Label, ProgressBar, Static +from textual.worker import Worker, WorkerState + +from i18n import I18n + +from . import ffmpeg_client, ytdlp_client +from .models import FormatEntry, VideoInfo +from .screens import ErrorScreen, FormatSelectScreen + + +class DownloadManagerApp(App[None]): + """A textual UI for downloading a single film via yt-dlp.""" + + CSS = """ + #form Input { + margin-bottom: 1; + } + + .field-row { + height: auto; + margin-bottom: 1; + } + + .field-row Label { + width: 10; + padding-top: 1; + } + + .field-row Input { + width: 1fr; + } + + #selection-area { + height: auto; + margin-bottom: 1; + } + + #progress-text { + margin-top: 1; + } + + #progress-bar { + width: 100%; + margin-bottom: 1; + } + + #button-row { + height: auto; + align-horizontal: left; + } + + #button-row Button { + margin-right: 1; + } + """ + + def __init__(self) -> None: + super().__init__() + self.i18n = I18n() + self.video_info: VideoInfo | None = None + self.selected_audio: FormatEntry | None = None + self.selected_video: FormatEntry | None = None + # Temp files created for a split audio/video download, cleaned up + # after merging (or after a failed attempt). + self._temp_files: list[Path] = [] + + # -- layout --------------------------------------------------------- + + def compose(self) -> ComposeResult: + t = self.i18n.t + self.title = t("app.title", default="yt-dlp Download Manager") + yield Header() + with Vertical(id="form"): + with Horizontal(classes="field-row"): + yield Label(t("label.url", default="Url")) + yield Input(id="url-input", placeholder=t("placeholder.url", default="https://...")) + with Horizontal(classes="field-row"): + yield Label(t("label.name", default="Name")) + yield Input( + id="name-input", + placeholder=t("placeholder.name", default="destination filename"), + ) + with Vertical(id="selection-area"): + yield Static(self._format_selection_line("audio", None), id="audio-label") + yield Static(self._format_selection_line("video", None), id="video-label") + yield Static(t("status.idle", default="Idle"), id="progress-text") + yield ProgressBar(id="progress-bar", total=100, show_eta=False) + with Horizontal(id="button-row"): + yield Button( + t("button.select_parts", default="Select parts"), + id="select-parts-btn", + ) + yield Button( + t("button.start_download", default="Start download"), + id="start-download-btn", + disabled=True, + ) + yield Button(t("button.exit", default="Exit"), id="exit-btn") + yield Footer() + + # -- helpers ---------------------------------------------------------- + + def _format_selection_line(self, kind: str, entry: FormatEntry | None) -> str: + t = self.i18n.t + prefix = t(f"label.{kind}", default=kind.capitalize()) + if entry is None: + value = t("label.none", default="-") + else: + value = entry.display_text + return f"{prefix}: {value}" + + def _set_progress_text(self, text: str) -> None: + self.query_one("#progress-text", Static).update(text) + + def _set_progress(self, percent: float) -> None: + self.query_one("#progress-bar", ProgressBar).update(progress=percent) + + def _set_busy(self, busy: bool) -> None: + self.query_one("#select-parts-btn", Button).disabled = busy + # The download button additionally requires a valid selection, so + # only re-enable it when not busy AND a selection exists. + download_btn = self.query_one("#start-download-btn", Button) + if busy: + download_btn.disabled = True + else: + download_btn.disabled = self.selected_video is None + + async def _show_error(self, message: str) -> None: + await self.push_screen_wait(ErrorScreen(message)) + + # -- button wiring ------------------------------------------------------ + + def on_button_pressed(self, event: Button.Pressed) -> None: + if event.button.id == "select-parts-btn": + self.run_worker(self.select_parts(), exclusive=True, group="select") + elif event.button.id == "start-download-btn": + self.run_worker(self.start_download(), exclusive=True, group="download") + elif event.button.id == "exit-btn": + self.exit() + + # -- "Select parts" workflow -------------------------------------------- + + async def select_parts(self) -> None: + t = self.i18n.t + url = self.query_one("#url-input", Input).value.strip() + if not url: + await self._show_error(t("error.empty_url", default="Please enter a URL.")) + return + + self._set_busy(True) + self._set_progress_text(t("status.fetching", default="Fetching information...")) + try: + raw = await ytdlp_client.fetch_info(url) + except ytdlp_client.YtDlpError as exc: + await self._show_error( + t("error.fetch_failed", default="Could not read film information:\n{error}", error=str(exc)) + ) + self._set_progress_text(t("status.idle", default="Idle")) + self._set_busy(False) + return + + info = VideoInfo.from_json(raw) + if not info.audio_formats and not info.video_formats: + await self._show_error( + t("error.no_formats", default="No downloadable formats were found for this URL.") + ) + self._reset_selection() + self._set_progress_text(t("status.idle", default="Idle")) + self._set_busy(False) + return + + self.video_info = info + + audio_entry: FormatEntry | None = None + if info.is_split: + audio_entry = await self.push_screen_wait( + FormatSelectScreen(t("dialog.select_audio", default="Select audio part"), info.audio_formats) + ) + if audio_entry is None: + await self._show_error( + t("error.no_audio_selected", default="No valid audio part was selected.") + ) + self._reset_selection() + self._set_progress_text(t("status.idle", default="Idle")) + self._set_busy(False) + return + + video_entry = await self.push_screen_wait( + FormatSelectScreen(t("dialog.select_video", default="Select video part"), info.video_formats) + ) + if video_entry is None: + await self._show_error( + t("error.no_video_selected", default="No valid video part was selected.") + ) + self._reset_selection() + self._set_progress_text(t("status.idle", default="Idle")) + self._set_busy(False) + return + + self.selected_audio = audio_entry + self.selected_video = video_entry + self.query_one("#audio-label", Static).update(self._format_selection_line("audio", audio_entry)) + self.query_one("#video-label", Static).update(self._format_selection_line("video", video_entry)) + self._set_progress_text(t("status.idle", default="Idle")) + self._set_busy(False) + + def _reset_selection(self) -> None: + self.selected_audio = None + self.selected_video = None + self.query_one("#audio-label", Static).update(self._format_selection_line("audio", None)) + self.query_one("#video-label", Static).update(self._format_selection_line("video", None)) + + # -- "Start download" workflow ------------------------------------------ + + async def start_download(self) -> None: + t = self.i18n.t + url = self.query_one("#url-input", Input).value.strip() + name = self.query_one("#name-input", Input).value.strip() + + if not url: + await self._show_error(t("error.empty_url", default="Please enter a URL.")) + return + if not name: + await self._show_error( + t("error.empty_destination", default="Please enter a destination name.") + ) + return + if self.selected_video is None or self.video_info is None: + await self._show_error( + t("error.nothing_selected", default="Please select parts before downloading.") + ) + return + if self.video_info.is_split and self.selected_audio is None: + await self._show_error( + t("error.nothing_selected", default="Please select parts before downloading.") + ) + return + + destination = Path(name) + fulltitle = self.video_info.fulltitle or destination.stem + + self._set_busy(True) + try: + if self.selected_audio is not None: + await self._download_split(url, destination, fulltitle) + else: + await self._download_combined(url, destination, fulltitle) + finally: + self._cleanup_temp_files() + self._set_progress(0) + self._set_busy(False) + + async def _download_combined(self, url: str, destination: Path, fulltitle: str) -> None: + t = self.i18n.t + kind = t("label.audio_video", default="Audio + Video") + assert self.selected_video is not None + + async def on_progress(percent: float) -> None: + self._set_progress(percent) + self._set_progress_text( + t("status.progress", default="{title} - {kind} - {percent:.0f}%", title=fulltitle, kind=kind, percent=percent) + ) + + try: + await ytdlp_client.download( + url, str(destination), self.selected_video.format_id, on_progress + ) + except ytdlp_client.YtDlpError as exc: + await self._show_error( + t("error.download_failed", default="Download failed:\n{error}", error=str(exc)) + ) + self._set_progress(0) + self._set_progress_text(t("status.idle", default="Idle")) + return + + self._set_progress(0) + self._set_progress_text(t("status.done", default="Done")) + + async def _download_split(self, url: str, destination: Path, fulltitle: str) -> None: + t = self.i18n.t + assert self.selected_audio is not None + assert self.selected_video is not None + + parent = destination.parent + stem = destination.stem or "download" + video_temp = parent / f"{stem}.video.tmp.mp4" + audio_temp = parent / f"{stem}.audio.tmp.mp4" + self._temp_files = [video_temp, audio_temp] + + video_kind = t("label.video", default="Video") + audio_kind = t("label.audio", default="Audio") + + def make_progress_cb(kind: str): + async def on_progress(percent: float) -> None: + self._set_progress(percent) + self._set_progress_text( + t( + "status.progress", + default="{title} - {kind} - {percent:.0f}%", + title=fulltitle, + kind=kind, + percent=percent, + ) + ) + + return on_progress + + try: + await ytdlp_client.download( + url, str(video_temp), self.selected_video.format_id, make_progress_cb(video_kind) + ) + self._set_progress(0) + await ytdlp_client.download( + url, str(audio_temp), self.selected_audio.format_id, make_progress_cb(audio_kind) + ) + self._set_progress(0) + except ytdlp_client.YtDlpError as exc: + await self._show_error( + t("error.download_failed", default="Download failed:\n{error}", error=str(exc)) + ) + self._set_progress(0) + self._set_progress_text(t("status.idle", default="Idle")) + return + + self._set_progress_text(t("status.merging", default="Merging audio and video...")) + try: + await ffmpeg_client.merge(str(video_temp), str(audio_temp), str(destination)) + except ffmpeg_client.FfmpegError as exc: + await self._show_error( + t("error.merge_failed", default="Merging audio and video failed:\n{error}", error=str(exc)) + ) + self._set_progress_text(t("status.idle", default="Idle")) + return + + self._set_progress_text(t("status.done", default="Done")) + + def _cleanup_temp_files(self) -> None: + for temp_file in self._temp_files: + try: + if temp_file.exists(): + temp_file.unlink() + except OSError: + pass + self._temp_files = [] + + +def run() -> None: + DownloadManagerApp().run() diff --git a/app/ytdlp_client.py b/app/ytdlp_client.py new file mode 100644 index 0000000..a661bee --- /dev/null +++ b/app/ytdlp_client.py @@ -0,0 +1,119 @@ +"""Async wrappers around the ``yt-dlp`` command line tool. + +Two operations are needed by the application: + +* :func:`fetch_info` runs ``yt-dlp -i --dump-json `` and parses the + resulting JSON document. +* :func:`download` runs ``yt-dlp -i -o -f `` and + reports download progress back to the caller. + +Both are ``async`` because they drive an external process and must not +block the Textual event loop. +""" + +from __future__ import annotations + +import asyncio +import json +import re +from collections.abc import Awaitable, Callable +from typing import Any + +#: Matches yt-dlp's ``--newline`` progress output, e.g. +#: "[download] 12.3% of 50.00MiB at 1.20MiB/s ETA 00:30" +_PROGRESS_RE = re.compile(r"\[download\]\s+(\d{1,3}(?:\.\d+)?)%") + +ProgressCallback = Callable[[float], Awaitable[None]] + + +class YtDlpError(RuntimeError): + """Raised when yt-dlp fails or returns unusable output.""" + + +async def fetch_info(url: str) -> dict[str, Any]: + """Run ``yt-dlp -i --dump-json `` and return the parsed JSON. + + Raises :class:`YtDlpError` if the process fails or produces no usable + JSON document. + """ + process = await asyncio.create_subprocess_exec( + "yt-dlp", + "-i", + "--dump-json", + url, + stdout=asyncio.subprocess.PIPE, + stderr=asyncio.subprocess.PIPE, + ) + stdout, stderr = await process.communicate() + + document = _first_json_object(stdout.decode("utf-8", errors="replace")) + if document is not None: + return document + + message = stderr.decode("utf-8", errors="replace").strip() + raise YtDlpError(message or "yt-dlp produced no information for this URL.") + + +def _first_json_object(text: str) -> dict[str, Any] | None: + """Return the first line of ``text`` that parses as a JSON object.""" + for line in text.splitlines(): + line = line.strip() + if not line.startswith("{"): + continue + try: + data = json.loads(line) + except json.JSONDecodeError: + continue + if isinstance(data, dict): + return data + return None + + +async def download( + url: str, + destination: str, + format_id: str, + on_progress: ProgressCallback | None = None, +) -> None: + """Run ``yt-dlp -i url -o destination -f format_id``. + + ``on_progress`` is awaited with the current percentage (0-100) whenever + the reported progress changes by at least one percentage point. + + Raises :class:`YtDlpError` if the process exits with a non-zero status. + """ + process = await asyncio.create_subprocess_exec( + "yt-dlp", + "--newline", + "-i", + url, + "-o", + destination, + "-f", + format_id, + stdout=asyncio.subprocess.PIPE, + stderr=asyncio.subprocess.STDOUT, + ) + + last_reported = -1 + assert process.stdout is not None + stderr_lines: list[str] = [] + + while True: + raw_line = await process.stdout.readline() + if not raw_line: + break + line = raw_line.decode("utf-8", errors="replace").rstrip() + stderr_lines.append(line) + + match = _PROGRESS_RE.search(line) + if match and on_progress is not None: + percent = float(match.group(1)) + if int(percent) != last_reported: + last_reported = int(percent) + await on_progress(percent) + + return_code = await process.wait() + if return_code != 0: + tail = "\n".join(stderr_lines[-10:]) + raise YtDlpError(tail or f"yt-dlp exited with status {return_code}.") diff --git a/i18n/de/help.md b/i18n/de/help.md new file mode 100644 index 0000000..4f8d2e7 --- /dev/null +++ b/i18n/de/help.md @@ -0,0 +1,17 @@ +# yt-dlp Download-Manager - Hilfe + +1. Geben Sie die URL des Films in das Feld **Url** ein. +2. Geben Sie den Zieldateinamen in das Feld **Name** ein. Sie können einen + Pfad angeben; ohne Pfad wird die Datei im aktuellen Verzeichnis + gespeichert. +3. Klicken Sie auf **Teile auswählen**, um die verfügbaren Formate für die + URL abzurufen. Falls der Film getrennte Audio- und Video-Streams + anbietet, werden Sie zunächst nach einem Audio-Teil und danach nach + einem Video-Teil gefragt. Andernfalls wählen Sie nur einen + kombinierten Teil aus. +4. Nach der Auswahl zeigen die Zeilen **Audio** und/oder **Video** auf dem + Hauptbildschirm die getroffene Auswahl. Klicken Sie auf + **Download starten**, um die ausgewählten Teile herunterzuladen. +5. Wurden Audio und Video getrennt heruntergeladen, werden sie nach + Abschluss beider Downloads automatisch zur Zieldatei zusammengeführt. +6. Klicken Sie auf **Beenden**, um die Anwendung zu schließen. diff --git a/i18n/de/strings.json b/i18n/de/strings.json new file mode 100644 index 0000000..c4e1925 --- /dev/null +++ b/i18n/de/strings.json @@ -0,0 +1,45 @@ +{ + "app.title": "yt-dlp Download-Manager", + + "label.url": "Url", + "label.name": "Name", + "label.audio": "Audio", + "label.video": "Video", + "label.audio_video": "Audio + Video", + "label.none": "-", + + "placeholder.url": "https://...", + "placeholder.name": "Zieldateiname", + + "status.idle": "Bereit", + "status.fetching": "Informationen werden abgerufen...", + "status.merging": "Audio und Video werden zusammengefügt...", + "status.done": "Fertig", + "status.progress": "{title} - {kind} - {percent:.0f}%", + + "button.select_parts": "Teile auswählen", + "button.start_download": "Download starten", + "button.exit": "Beenden", + "button.ok": "OK", + "button.cancel": "Abbrechen", + + "dialog.error_title": "Fehler", + "dialog.select_audio": "Audio-Teil auswählen", + "dialog.select_video": "Video-Teil auswählen", + + "table.format_id": "Format-ID", + "table.resolution": "Auflösung", + "table.acodec": "Audio-Codec", + "table.vcodec": "Video-Codec", + "table.format": "Format", + + "error.empty_url": "Bitte eine Url eingeben.", + "error.empty_destination": "Bitte einen Zieldateinamen eingeben.", + "error.nothing_selected": "Bitte vor dem Download Teile auswählen.", + "error.no_formats": "Für diese Url wurden keine herunterladbaren Formate gefunden.", + "error.no_audio_selected": "Es wurde kein gültiger Audio-Teil ausgewählt.", + "error.no_video_selected": "Es wurde kein gültiger Video-Teil ausgewählt.", + "error.fetch_failed": "Die Filminformationen konnten nicht gelesen werden:\n{error}", + "error.download_failed": "Der Download ist fehlgeschlagen:\n{error}", + "error.merge_failed": "Das Zusammenführen von Audio und Video ist fehlgeschlagen:\n{error}" +} diff --git a/i18n/en/help.md b/i18n/en/help.md new file mode 100644 index 0000000..e2da1af --- /dev/null +++ b/i18n/en/help.md @@ -0,0 +1,15 @@ +# yt-dlp Download Manager - Help + +1. Enter the URL of the film in the **Url** field. +2. Enter the destination file name in the **Name** field. You may include a + path; if you don't, the file is saved in the current directory. +3. Click **Select parts** to fetch the available formats for the URL. If the + film offers separate audio and video streams, you will be asked to pick + an audio part and then a video part. Otherwise you only pick one + combined part. +4. Once a selection has been made, the **Audio** and/or **Video** lines on + the main screen show what was picked. Click **Start download** to + download the selected part(s). +5. If audio and video were downloaded separately, they are merged into the + destination file automatically once both downloads finish. +6. Click **Exit** to close the application. diff --git a/i18n/en/strings.json b/i18n/en/strings.json new file mode 100644 index 0000000..d6e12a9 --- /dev/null +++ b/i18n/en/strings.json @@ -0,0 +1,45 @@ +{ + "app.title": "yt-dlp Download Manager", + + "label.url": "Url", + "label.name": "Name", + "label.audio": "Audio", + "label.video": "Video", + "label.audio_video": "Audio + Video", + "label.none": "-", + + "placeholder.url": "https://...", + "placeholder.name": "destination filename", + + "status.idle": "Idle", + "status.fetching": "Fetching information...", + "status.merging": "Merging audio and video...", + "status.done": "Done", + "status.progress": "{title} - {kind} - {percent:.0f}%", + + "button.select_parts": "Select parts", + "button.start_download": "Start download", + "button.exit": "Exit", + "button.ok": "OK", + "button.cancel": "Cancel", + + "dialog.error_title": "Error", + "dialog.select_audio": "Select audio part", + "dialog.select_video": "Select video part", + + "table.format_id": "Format ID", + "table.resolution": "Resolution", + "table.acodec": "Audio codec", + "table.vcodec": "Video codec", + "table.format": "Format", + + "error.empty_url": "Please enter a URL.", + "error.empty_destination": "Please enter a destination name.", + "error.nothing_selected": "Please select parts before downloading.", + "error.no_formats": "No downloadable formats were found for this URL.", + "error.no_audio_selected": "No valid audio part was selected.", + "error.no_video_selected": "No valid video part was selected.", + "error.fetch_failed": "Could not read film information:\n{error}", + "error.download_failed": "Download failed:\n{error}", + "error.merge_failed": "Merging audio and video failed:\n{error}" +} diff --git a/main.py b/main.py new file mode 100644 index 0000000..187e612 --- /dev/null +++ b/main.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +"""Entry point for the yt-dlp download manager TUI. + +Sets up the bundled i18n library (see ``lib/i18n``) with the application's +own translation data (in ``i18n//strings.json``) before starting the +Textual application. +""" + +from __future__ import annotations + +import sys +from pathlib import Path + +PROJECT_ROOT = Path(__file__).resolve().parent + +# The i18n library package lives in lib/, kept separate from the i18n/ +# *data* directory (project_root/i18n//strings.json) that the library +# itself expects to find at the project root. +sys.path.insert(0, str(PROJECT_ROOT / "lib")) + +from i18n import I18n # noqa: E402 (import must follow sys.path setup) + +DEFAULT_LANGUAGE = "en" +AVAILABLE_LANGUAGES = { + "en": "English", + "de": "Deutsch", +} + + +def main() -> None: + # First construction configures the process-wide singleton; every other + # `I18n()` call elsewhere in the app returns this same instance. + I18n( + default_language=DEFAULT_LANGUAGE, + available_languages=AVAILABLE_LANGUAGES, + project_root=PROJECT_ROOT, + ) + + from app.tui_app import DownloadManagerApp + + DownloadManagerApp().run() + + +if __name__ == "__main__": + main() diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..bc3fdb2 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,8 @@ +[project] +name = "ytdlp-tui" +version = "0.1.0" +requires-python = ">=3.12" +dependencies = [ + "textual>=0.60", + "yt-dlp>=2024.1.1", +] diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..40003a1 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,2 @@ +textual>=0.60 +yt-dlp>=2024.1.1 diff --git a/uv.lock b/uv.lock new file mode 100644 index 0000000..e94929e --- /dev/null +++ b/uv.lock @@ -0,0 +1,131 @@ +version = 1 +revision = 3 +requires-python = ">=3.12" + +[[package]] +name = "linkify-it-py" +version = "2.2.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/45/98/7a1a5f31fd5c7ba93e963b168e244b8e3dd705b3d2a718e3c3307583bf57/linkify_it_py-2.2.0.tar.gz", hash = "sha256:907acd2d17ac1fbb9ddb62c8957ccbd6158cac602231a15c3b0cd1e215f03cee", size = 32939, upload-time = "2026-08-29T07:07:08.305Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/13/d4/1152d1c7ab42d8b908be64fd200ddc870dc9d4925e951198702084aa1a7d/linkify_it_py-2.2.0-py3-none-any.whl", hash = "sha256:3adc40eb5af300b2605fcfdb968c24e1d780a90f1f2221af7c15e5111e94d443", size = 21971, upload-time = "2026-08-29T07:07:07.164Z" }, +] + +[[package]] +name = "markdown-it-py" +version = "4.2.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "mdurl" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/06/ff/7841249c247aa650a76b9ee4bbaeae59370dc8bfd2f6c01f3630c35eb134/markdown_it_py-4.2.0.tar.gz", hash = "sha256:04a21681d6fbb623de53f6f364d352309d4094dd4194040a10fd51833e418d49", size = 82454, upload-time = "2026-05-07T12:08:28.36Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/b3/81/4da04ced5a082363ecfa159c010d200ecbd959ae410c10c0264a38cac0f5/markdown_it_py-4.2.0-py3-none-any.whl", hash = "sha256:9f7ebbcd14fe59494226453aed97c1070d83f8d24b6fc3a3bcf9a38092641c4a", size = 91687, upload-time = "2026-05-07T12:08:27.182Z" }, +] + +[package.optional-dependencies] +linkify = [ + { name = "linkify-it-py" }, +] + +[[package]] +name = "mdit-py-plugins" +version = "0.6.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "markdown-it-py" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/59/fc/f8d0863f8862f25602c0404d75568e89fb6b4109804645e5cdfb1be5cf56/mdit_py_plugins-0.6.1.tar.gz", hash = "sha256:a2bca0f039f39dbd35fb74ae1b5f998608c437463371f0ff7f49a19a17a114d0", size = 56114, upload-time = "2026-05-13T09:03:38.91Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/a5/69/6da5581c6a7fede7dc261bf4e67d6adca4196f176b43288b55b3db395b6e/mdit_py_plugins-0.6.1-py3-none-any.whl", hash = "sha256:214c82fb2ac524472ab6a5bcab1de80f73b50443e187f401bfd77efbc7c6481d", size = 66663, upload-time = "2026-05-13T09:03:37.76Z" }, +] + +[[package]] +name = "mdurl" +version = "0.1.2" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/d6/54/cfe61301667036ec958cb99bd3efefba235e65cdeb9c84d24a8293ba1d90/mdurl-0.1.2.tar.gz", hash = "sha256:bb413d29f5eea38f31dd4754dd7377d4465116fb207585f97bf925588687c1ba", size = 8729, upload-time = "2022-08-14T12:40:10.846Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/b3/38/89ba8ad64ae25be8de66a6d463314cf1eb366222074cfda9ee839c56a4b4/mdurl-0.1.2-py3-none-any.whl", hash = "sha256:84008a41e51615a49fc9966191ff91509e3c40b939176e643fd50a5c2196b8f8", size = 9979, upload-time = "2022-08-14T12:40:09.779Z" }, +] + +[[package]] +name = "platformdirs" +version = "4.11.11" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/f8/13/f870dd0b42690138e4e37a76b5138e5690ed4365a77071bb092d59037da0/platformdirs-4.11.11.tar.gz", hash = "sha256:b0befe8a90759e4a9a8b9820d434ae226a6549063210b596da0038a7a05aede4", size = 39949, upload-time = "2026-09-19T01:18:47.259Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/39/be/3ae887e84c38c4dd1c549cd5825adc93f48069a94fe1cb8ac52a9da16f15/platformdirs-4.11.11-py3-none-any.whl", hash = "sha256:972ea6b2b387155a536226a0750e46923d731d459a387c4a255c583ed2f64547", size = 24992, upload-time = "2026-09-19T01:18:45.825Z" }, +] + +[[package]] +name = "pygments" +version = "2.21.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/49/2e/ced460408999b33da6b31b0021b0f37d329e202d4169aeb164493778f25b/pygments-2.21.0.tar.gz", hash = "sha256:610ca751c9bc2492b38eb9a38a7fbc93edbbb2d7182edaf34e66ae493dee5c8c", size = 5005329, upload-time = "2026-08-17T08:02:48.824Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/71/46/17f022dd3e953bf20a04a028a21ec746d942f8d2af30fa0f124fa0e6a684/pygments-2.21.0-py3-none-any.whl", hash = "sha256:2363c69b61c4a97c838da3b130dcd6468f4848992b21a82f2a63ec34377137d9", size = 1250147, upload-time = "2026-08-17T08:02:44.912Z" }, +] + +[[package]] +name = "rich" +version = "15.0.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "markdown-it-py" }, + { name = "pygments" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/c0/8f/0722ca900cc807c13a6a0c696dacf35430f72e0ec571c4275d2371fca3e9/rich-15.0.0.tar.gz", hash = "sha256:edd07a4824c6b40189fb7ac9bc4c52536e9780fbbfbddf6f1e2502c31b068c36", size = 230680, upload-time = "2026-04-12T08:24:00.75Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/82/3b/64d4899d73f91ba49a8c18a8ff3f0ea8f1c1d75481760df8c68ef5235bf5/rich-15.0.0-py3-none-any.whl", hash = "sha256:33bd4ef74232fb73fe9279a257718407f169c09b78a87ad3d296f548e27de0bb", size = 310654, upload-time = "2026-04-12T08:24:02.83Z" }, +] + +[[package]] +name = "textual" +version = "8.2.8" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "markdown-it-py", extra = ["linkify"] }, + { name = "mdit-py-plugins" }, + { name = "platformdirs" }, + { name = "pygments" }, + { name = "rich" }, + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/00/21/39a76b01bd5eea82a04baaca7580e105d8c59450df03998345bb2cfb307b/textual-8.2.8.tar.gz", hash = "sha256:3f106a9fbc73e39dd266c9712432087de78a6d644084c7c241d6a25c3169115b", size = 1860502, upload-time = "2026-06-30T06:51:24.495Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/fb/be/35261223d9416a0751cdff1c7b4a6f881387218a12d439fe22fefebc8c04/textual-8.2.8-py3-none-any.whl", hash = "sha256:267375fd402dc8d981457212efa71f0e3365fd17bba144ba9bb3ed7563cb374a", size = 731418, upload-time = "2026-06-30T06:51:26.364Z" }, +] + +[[package]] +name = "typing-extensions" +version = "4.16.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/f6/cc/6253133b5bb138fc3306cebfbda2c520f545d36b5be2c7255cc528bb45d6/typing_extensions-4.16.0.tar.gz", hash = "sha256:dc983d19a509c94dba722ee6abd33940f7c05a89e243c47e907eb4db6f1a43e5", size = 113555, upload-time = "2026-07-02T08:40:05.92Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/49/d3/b8441a820a491ddfc024b0b0cf0393375b75ea13866d9c66727e54c2fc80/typing_extensions-4.16.0-py3-none-any.whl", hash = "sha256:481caa481374e813c1b176ada14e97f1f67a4539ce9cfeb3f350d78d6370c2e8", size = 45571, upload-time = "2026-07-02T08:40:04.659Z" }, +] + +[[package]] +name = "yt-dlp" +version = "2026.8.19" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/1e/e0/832fa4ca334b766a06933a196066edc3dba37cdb6f14cd98d59bcc69a4b4/yt_dlp-2026.8.19.tar.gz", hash = "sha256:9e213e48cea35c66b378e4447903f118f6392a5fa380a2b6d7070ec86f4e0af1", size = 3052025, upload-time = "2026-08-19T23:48:59.291Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/69/b2/8cd1613f56eed7ceb64fbd4df3f1c01246bfb098e6f398228bafda22b80b/yt_dlp-2026.8.19-py3-none-any.whl", hash = "sha256:1d57897e94c6665a0a6f9bc54b34e584284e32c034ffab3a7df25d8f7b24eedf", size = 3185533, upload-time = "2026-08-19T23:48:56.925Z" }, +] + +[[package]] +name = "ytdlp-tui" +version = "0.1.0" +source = { virtual = "." } +dependencies = [ + { name = "textual" }, + { name = "yt-dlp" }, +] + +[package.metadata] +requires-dist = [ + { name = "textual", specifier = ">=0.60" }, + { name = "yt-dlp", specifier = ">=2024.1.1" }, +]