First checkin of the sources

This commit is contained in:
2026-09-19 14:18:15 +02:00
parent 56ea3736d7
commit 701ff3a6d3
17 changed files with 1196 additions and 0 deletions
View File
+32
View File
@@ -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}.")
+94
View File
@@ -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,
)
+4
View File
@@ -0,0 +1,4 @@
from .error_screen import ErrorScreen
from .format_select_screen import FormatSelectScreen
__all__ = ["ErrorScreen", "FormatSelectScreen"]
+61
View File
@@ -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)
+123
View File
@@ -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)
+356
View File
@@ -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()
+119
View File
@@ -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 <url>`` and parses the
resulting JSON document.
* :func:`download` runs ``yt-dlp -i <url> -o <filename> -f <format_id>`` 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 <url>`` 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}.")