dzen.nstarikov.ru/dzen-assistant/app/chapters.py
2026-08-08 14:02:14 +03:00

102 lines
3.2 KiB
Python

from __future__ import annotations
import re
from dataclasses import dataclass
from typing import Any
@dataclass(frozen=True)
class VideoChapter:
id: str
title: str
start_seconds: int
end_seconds: int | None
@property
def duration_seconds(self) -> int | None:
if self.end_seconds is None:
return None
return max(0, self.end_seconds - self.start_seconds)
TIMECODE_RE = re.compile(
r"(?:^|\n)\s*(?:[-*]\s*)?(?:\[(?P<link_time>\d{1,2}:\d{2}(?::\d{2})?)\]\([^)]+\)|(?P<plain_time>\d{1,2}:\d{2}(?::\d{2})?))\s*(?P<title>[^\n]+)",
flags=re.I,
)
def timecode_to_seconds(value: str) -> int:
parts = [int(part) for part in value.split(":")]
if len(parts) == 2:
minutes, seconds = parts
return minutes * 60 + seconds
hours, minutes, seconds = parts
return hours * 3600 + minutes * 60 + seconds
def seconds_to_timecode(seconds: int | None) -> str:
if seconds is None:
return ""
seconds = max(0, seconds)
hours = seconds // 3600
minutes = (seconds % 3600) // 60
rest = seconds % 60
if hours:
return f"{hours:02d}:{minutes:02d}:{rest:02d}"
return f"{minutes:02d}:{rest:02d}"
def clean_chapter_title(title: str) -> str:
title = re.sub(r"\]\([^)]+\)", "", title)
title = re.sub(r"\s+", " ", title).strip(" -—–\t")
return title[:180].strip() or "Эпизод"
def parse_video_chapters(description: str | None, duration_seconds: int | None = None) -> list[VideoChapter]:
raw: list[tuple[int, str]] = []
for match in TIMECODE_RE.finditer(description or ""):
time_value = match.group("link_time") or match.group("plain_time")
if not time_value:
continue
start = timecode_to_seconds(time_value)
title = clean_chapter_title(match.group("title") or "")
raw.append((start, title))
deduped: list[tuple[int, str]] = []
seen: set[int] = set()
for start, title in sorted(raw, key=lambda item: item[0]):
if start in seen:
continue
if duration_seconds and start >= duration_seconds:
continue
seen.add(start)
deduped.append((start, title))
chapters: list[VideoChapter] = []
for index, (start, title) in enumerate(deduped):
next_start = deduped[index + 1][0] if index + 1 < len(deduped) else duration_seconds
if next_start is not None and next_start <= start:
continue
chapters.append(
VideoChapter(
id=f"{index + 1}-{start}",
title=title,
start_seconds=start,
end_seconds=next_start,
)
)
return chapters
def chapter_to_payload(chapter: VideoChapter, default_selected_min_seconds: int = 180) -> dict[str, Any]:
duration = chapter.duration_seconds
return {
"id": chapter.id,
"title": chapter.title,
"startSeconds": chapter.start_seconds,
"endSeconds": chapter.end_seconds,
"durationSeconds": duration,
"startTimecode": seconds_to_timecode(chapter.start_seconds),
"endTimecode": seconds_to_timecode(chapter.end_seconds),
"selected": bool(duration is not None and duration >= default_selected_min_seconds),
}