talk-notes 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- talk_notes/__init__.py +0 -0
- talk_notes/__main__.py +3 -0
- talk_notes/cli.py +144 -0
- talk_notes/crop.py +187 -0
- talk_notes/llm/__init__.py +44 -0
- talk_notes/llm/base.py +20 -0
- talk_notes/llm/claude_code.py +41 -0
- talk_notes/llm/fake.py +26 -0
- talk_notes/llm/ollama.py +122 -0
- talk_notes/prompts/report.md +81 -0
- talk_notes/render.py +48 -0
- talk_notes/report.py +40 -0
- talk_notes/slides.py +124 -0
- talk_notes/source.py +168 -0
- talk_notes/talk_folder.py +148 -0
- talk_notes/transcribe.py +67 -0
- talk_notes/transcript.py +32 -0
- talk_notes/util.py +39 -0
- talk_notes-0.1.0.dist-info/METADATA +117 -0
- talk_notes-0.1.0.dist-info/RECORD +23 -0
- talk_notes-0.1.0.dist-info/WHEEL +4 -0
- talk_notes-0.1.0.dist-info/entry_points.txt +2 -0
- talk_notes-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
You are turning a recorded tech talk into a written report. People read it instead of watching
|
|
2
|
+
the talk, and coding agents use it as a reference. The reader has not seen the talk, so they
|
|
3
|
+
must always be able to tell what went wrong from what fixes it, and what the speaker said from
|
|
4
|
+
what you added.
|
|
5
|
+
|
|
6
|
+
The input is the talk's transcript grouped by slide, with each slide's image or a description
|
|
7
|
+
of it. The transcript comes from speech recognition: fix misheard technical terms using the
|
|
8
|
+
slides as ground truth, without comment.
|
|
9
|
+
|
|
10
|
+
## 1. Classify the talk
|
|
11
|
+
|
|
12
|
+
Pick the type whose outline covers most of the talk. Prefer a single type: a problem-solving
|
|
13
|
+
story that ends in a demo of the solution is still a problem-solving story. Use Mixed only when no
|
|
14
|
+
single outline covers most of the talk.
|
|
15
|
+
|
|
16
|
+
| Type | Outline for section 2 |
|
|
17
|
+
|---|---|
|
|
18
|
+
| Problem-solving story | Problem → Why it happens → How the speaker investigated → Solution → Results |
|
|
19
|
+
| Argument or opinion | Thesis → Evidence → Objections and limits → What the speaker recommends |
|
|
20
|
+
| Tutorial or best practices | A list of problem → fix pairs |
|
|
21
|
+
| Catalogue or survey | Items grouped by theme, each with why it matters |
|
|
22
|
+
| Product or tool demo | What it solves → How it works → What was shown → Limits |
|
|
23
|
+
| Mixed | The outline of the main type, plus extra subsections for the other parts |
|
|
24
|
+
|
|
25
|
+
Start the report with the talk's title as a `#` heading, then one line:
|
|
26
|
+
`**Talk type:** <type> (<fits well | fits partly: one-clause reason>)`
|
|
27
|
+
|
|
28
|
+
If the talk fits none of these types, write instead:
|
|
29
|
+
`**Talk type:** none of the supported types (<one-clause description of what it is>). Please report this at {{ISSUES_URL}} so the report format can be improved.`
|
|
30
|
+
and use this outline for section 2: Summary → Key points.
|
|
31
|
+
|
|
32
|
+
## 2. Write the report
|
|
33
|
+
|
|
34
|
+
Use these sections as `##` headings, in this order; subsections inside them are `###`.
|
|
35
|
+
|
|
36
|
+
**Summary.** One short paragraph: what the talk is about and its main conclusion.
|
|
37
|
+
|
|
38
|
+
**The outline from step 1.** One or more `##` sections named after the talk's subject, not after
|
|
39
|
+
the outline (for example "How the self-improvement loop works"). Use the outline's steps as `###`
|
|
40
|
+
subsections, or for pair and item lists one bold lead-in per pair or item. Rules for every point:
|
|
41
|
+
|
|
42
|
+
- Write each point as its own list item starting with exactly one bold label and a colon, for
|
|
43
|
+
example `- **Problem:** Agents work around failing tool calls.` Indent a point under another
|
|
44
|
+
when it only supports that one. The labels are:
|
|
45
|
+
**Problem** (something that goes wrong or hurts), **Cause** (why it happens), **Evidence**
|
|
46
|
+
(data, demo or anecdote backing a claim), **Solution** (something the speaker did or built),
|
|
47
|
+
**Recommendation** (advice to the audience), **Opinion** (the speaker's view, without
|
|
48
|
+
evidence), **Caveat** (limits, trade-offs, when advice does not apply).
|
|
49
|
+
Do not invent other labels: background goes under the label of the point it supports. Bold
|
|
50
|
+
lead-ins naming a pair or item (as in a problem → fix list) are fine.
|
|
51
|
+
- Put each Problem directly next to its Cause and its Solution or Recommendation. If the speaker
|
|
52
|
+
offers no fix, add `- **Solution:** none offered.`
|
|
53
|
+
- Put each Caveat next to the point it qualifies, not in a separate section.
|
|
54
|
+
- Anything not stated in the talk or on the slides (context, clarifications, conclusions you
|
|
55
|
+
draw) ends with *(inferred)*. Never present an inference as the speaker's claim.
|
|
56
|
+
- Define a term only where the talk itself defines it.
|
|
57
|
+
|
|
58
|
+
Keep these sections readable in about five minutes: roughly one page per 20 minutes of talk.
|
|
59
|
+
Prefer specifics (numbers, names, concrete examples) over general statements.
|
|
60
|
+
|
|
61
|
+
**Examples.** Code, configuration, commands, prompts and data shown on the slides, reproduced
|
|
62
|
+
verbatim in fenced code blocks, each with a one-line caption saying what it shows. Omit the
|
|
63
|
+
section if there are none.
|
|
64
|
+
|
|
65
|
+
**For coding agents.** Rules a coding agent could follow, derived from the talk's Solutions and
|
|
66
|
+
Recommendations. Only include rules the talk supports; mark rules that go beyond the speaker's
|
|
67
|
+
words *(inferred)*. Format each rule as:
|
|
68
|
+
|
|
69
|
+
- **When** <situation> **do** <action>. **Why:** <reason from the talk>. (<timestamp link>)
|
|
70
|
+
|
|
71
|
+
Repeat relevant code or config from Examples under the rule it supports. If the talk gives
|
|
72
|
+
nothing actionable, keep the heading and say so in one line.
|
|
73
|
+
|
|
74
|
+
**References.** Links, papers, books, tools, projects and people mentioned, one line each.
|
|
75
|
+
|
|
76
|
+
## Style
|
|
77
|
+
|
|
78
|
+
- Write in English. Keep exact quotes and slide text in their original language.
|
|
79
|
+
- Cite claims with the timestamp links from the input, copied exactly (`[HH:MM:SS](url)`). Do not
|
|
80
|
+
write timestamps yourself and do not cite every sentence; cite claims a reader may want to check.
|
|
81
|
+
- Plain, direct sentences. No filler, no praise of the talk, no closing summary.
|
talk_notes/render.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
from collections.abc import Callable
|
|
2
|
+
|
|
3
|
+
from talk_notes.source import Meta
|
|
4
|
+
from talk_notes.util import hms
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def assign_segments(slides: list[dict], segments: list[dict]) -> list[list[dict]]:
|
|
8
|
+
"""Group transcript segments under the slide on screen at each segment's midpoint."""
|
|
9
|
+
groups: list[list[dict]] = [[] for _ in slides]
|
|
10
|
+
i = 0
|
|
11
|
+
for seg in segments:
|
|
12
|
+
mid = (seg["start"] + seg["end"]) / 2
|
|
13
|
+
while i + 1 < len(slides) and mid >= slides[i + 1]["start"]:
|
|
14
|
+
i += 1
|
|
15
|
+
groups[i].append(seg)
|
|
16
|
+
return groups
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def render_markdown(meta: Meta, slides: list[dict], segments: list[dict],
|
|
20
|
+
link: Callable[[float], str | None] = lambda t: None) -> str:
|
|
21
|
+
"""talk.md: metadata, then each slide image with the speech while it was on screen.
|
|
22
|
+
|
|
23
|
+
`link(seconds)` gives the URL that opens the talk at that time, or None for a plain timestamp.
|
|
24
|
+
"""
|
|
25
|
+
def stamp(t: float) -> str:
|
|
26
|
+
url = link(t)
|
|
27
|
+
return f"[{hms(t)}]({url})" if url else hms(t)
|
|
28
|
+
|
|
29
|
+
lines = [f"# {meta.title}", ""]
|
|
30
|
+
for value, label in ((meta.channel, "Channel"), (meta.upload_date, "Uploaded"), (meta.url, "Source")):
|
|
31
|
+
if value:
|
|
32
|
+
lines.append(f"- {label}: {value}")
|
|
33
|
+
if meta.duration:
|
|
34
|
+
lines.append(f"- Duration: {hms(meta.duration)}")
|
|
35
|
+
lines.append("")
|
|
36
|
+
if meta.description:
|
|
37
|
+
lines += ["## Video description", "", meta.description.strip(), ""]
|
|
38
|
+
|
|
39
|
+
if not slides:
|
|
40
|
+
slides = [{"index": 0, "start": 0.0, "end": float("inf"), "image": None}]
|
|
41
|
+
for slide, segs in zip(slides, assign_segments(slides, segments)):
|
|
42
|
+
lines.append(f"## Slide {slide['index']} ({stamp(slide['start'])})")
|
|
43
|
+
lines.append("")
|
|
44
|
+
if slide.get("image"):
|
|
45
|
+
lines += [f"![Slide {slide['index']}]({slide['image']})", ""]
|
|
46
|
+
text = " ".join(s["text"] for s in segs).strip()
|
|
47
|
+
lines += [text or "_(no speech)_", ""]
|
|
48
|
+
return "\n".join(lines)
|
talk_notes/report.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
from importlib.metadata import PackageNotFoundError, metadata
|
|
2
|
+
from importlib.resources import files
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
|
|
5
|
+
from talk_notes.llm import LLM
|
|
6
|
+
from talk_notes.util import log
|
|
7
|
+
|
|
8
|
+
DEFAULT_ISSUES_URL = "https://github.com/ManuelCarullo/talk-notes/issues"
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def _issues_url() -> str:
|
|
12
|
+
"""The Issues link from the installed package metadata, so forks change it in pyproject.toml."""
|
|
13
|
+
try:
|
|
14
|
+
for entry in metadata("talk-notes").get_all("Project-URL") or []:
|
|
15
|
+
label, _, url = entry.partition(",")
|
|
16
|
+
if label.strip().lower() == "issues":
|
|
17
|
+
return url.strip()
|
|
18
|
+
except PackageNotFoundError:
|
|
19
|
+
pass
|
|
20
|
+
return DEFAULT_ISSUES_URL
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def load_prompt(path: Path | None) -> str:
|
|
24
|
+
"""The writing instructions: a user file from --prompt, or the bundled default."""
|
|
25
|
+
text = path.read_text() if path else files("talk_notes").joinpath("prompts/report.md").read_text()
|
|
26
|
+
return text.replace("{{ISSUES_URL}}", _issues_url())
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
INPUT_NOTE = """
|
|
30
|
+
|
|
31
|
+
---
|
|
32
|
+
|
|
33
|
+
Input: talk.md is the talk's transcript grouped by slide; the slide images it references are also
|
|
34
|
+
provided. Output only the report Markdown, with no preamble or closing remarks."""
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def generate_report(talk_md: Path, images: list[Path], llm: LLM, prompt: str) -> str:
|
|
38
|
+
"""The report's Markdown, from talk.md and the slide images, following `prompt`. Raises LLMError."""
|
|
39
|
+
log(f"Writing report.md with {llm.name}")
|
|
40
|
+
return llm.ask(prompt + INPUT_NOTE, [talk_md, *images]) + "\n"
|
talk_notes/slides.py
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
import subprocess
|
|
2
|
+
import tempfile
|
|
3
|
+
from collections.abc import Callable
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
|
|
6
|
+
import imagehash
|
|
7
|
+
import numpy as np
|
|
8
|
+
from PIL import Image, ImageDraw
|
|
9
|
+
|
|
10
|
+
from talk_notes.util import ffmpeg_exe, hms, log
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def _sample_frames(video: Path, tmp: Path, interval: float, crop: str | None) -> list[Path]:
|
|
14
|
+
filters = [f"fps=1/{interval}"]
|
|
15
|
+
if crop:
|
|
16
|
+
filters.append(f"crop={crop}")
|
|
17
|
+
filters.append("scale=320:-2")
|
|
18
|
+
cmd = [ffmpeg_exe(), "-v", "error", "-i", str(video), "-vf", ",".join(filters), str(tmp / "%06d.png")]
|
|
19
|
+
subprocess.run(cmd, check=True)
|
|
20
|
+
return sorted(tmp.glob("*.png"))
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _extract_frame(video: Path, t: float, dest: Path, crop: str | None) -> None:
|
|
24
|
+
cmd = [ffmpeg_exe(), "-v", "error", "-y", "-ss", f"{t:.2f}", "-i", str(video), "-frames:v", "1", "-q:v", "2"]
|
|
25
|
+
if crop:
|
|
26
|
+
cmd += ["-vf", f"crop={crop}"]
|
|
27
|
+
cmd.append(str(dest))
|
|
28
|
+
subprocess.run(cmd, check=True)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _masked(img: Image.Image, mask: list[float] | None) -> Image.Image:
|
|
32
|
+
if not mask:
|
|
33
|
+
return img
|
|
34
|
+
img = img.convert("RGB")
|
|
35
|
+
w, h = img.size
|
|
36
|
+
ImageDraw.Draw(img).rectangle([mask[0] * w, mask[1] * h, mask[2] * w, mask[3] * h], fill=(0, 0, 0))
|
|
37
|
+
return img
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
# Stretches of continuous change (live coding, scrolling, video) get a slide at least this often.
|
|
41
|
+
MAX_GAP_SECONDS = 20.0
|
|
42
|
+
|
|
43
|
+
Frame = np.ndarray # perceptual hash bits
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _dist(a: Frame, b: Frame) -> int:
|
|
47
|
+
return int(np.count_nonzero(a != b))
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _window_dist(hashes: list[Frame], before: int, after: int, m: int) -> int:
|
|
51
|
+
"""Smallest distance between the m frames ending before `before` and the m frames starting at `after`.
|
|
52
|
+
|
|
53
|
+
Using the smallest of all pairs makes a single odd frame (a flash, a camera cut) not count.
|
|
54
|
+
"""
|
|
55
|
+
if before <= 0 or after >= len(hashes):
|
|
56
|
+
return 0
|
|
57
|
+
return min(_dist(a, b) for a in hashes[max(0, before - m):before] for b in hashes[after:after + m])
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _boundaries(hashes: list[Frame], threshold: int, m: int, max_gap: int) -> list[int]:
|
|
61
|
+
"""Indices of the frames where a new slide starts.
|
|
62
|
+
|
|
63
|
+
A frame starts a slide when the frames after it differ from the frames before it (its change
|
|
64
|
+
score) by more than `threshold`, and the score is the highest within `m` frames, so slides
|
|
65
|
+
last at least `m` frames. Gradual change gets a boundary on a fixed grid every `max_gap`
|
|
66
|
+
frames, when the drift over that span exceeds its largest single jump by more than
|
|
67
|
+
`threshold`. Scores, peaks and the grid don't depend on `threshold`, so a higher threshold can
|
|
68
|
+
only remove boundaries: it never gives more slides.
|
|
69
|
+
"""
|
|
70
|
+
n = len(hashes)
|
|
71
|
+
score = [0] + [_window_dist(hashes, i, i, m) for i in range(1, n)]
|
|
72
|
+
found = {0}
|
|
73
|
+
for i in range(1, n):
|
|
74
|
+
if score[i] > threshold \
|
|
75
|
+
and all(score[i] > score[j] for j in range(max(1, i - m), i)) \
|
|
76
|
+
and all(score[i] >= score[j] for j in range(i + 1, min(n, i + m + 1))):
|
|
77
|
+
found.add(i)
|
|
78
|
+
for i in range(max_gap, n, max_gap):
|
|
79
|
+
drift = _window_dist(hashes, i - max_gap + 1, i - m + 1, m)
|
|
80
|
+
if drift - max(score[i - max_gap + 1:i + 1]) > threshold:
|
|
81
|
+
found.add(i)
|
|
82
|
+
return sorted(found)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def detect_slides(
|
|
86
|
+
video: Path,
|
|
87
|
+
slides_dir: Path,
|
|
88
|
+
interval: float = 2.0,
|
|
89
|
+
threshold: int = 12,
|
|
90
|
+
min_duration: float = 4.0,
|
|
91
|
+
crop: str | None = None,
|
|
92
|
+
mask: list[float] | None = None,
|
|
93
|
+
*,
|
|
94
|
+
sample_frames: Callable[[Path, Path, float, str | None], list[Path]] = _sample_frames,
|
|
95
|
+
extract_frame: Callable[[Path, float, Path, str | None], None] = _extract_frame,
|
|
96
|
+
) -> list[dict]:
|
|
97
|
+
"""Split the video into stretches showing the same picture and save one image per stretch.
|
|
98
|
+
|
|
99
|
+
A frame every `interval` seconds is hashed; see `_boundaries` for where slides start. `mask`
|
|
100
|
+
([left, top, right, bottom] fractions of the cropped frame, e.g. a speaker camera overlay) is
|
|
101
|
+
blacked out before hashing, so changes inside it don't start slides; saved images keep it. Each
|
|
102
|
+
slide's image is its last frame, so slides with incremental builds are captured fully built.
|
|
103
|
+
`sample_frames` and `extract_frame` are the ffmpeg calls; tests replace them.
|
|
104
|
+
"""
|
|
105
|
+
log(f"Detecting slides (every {interval}s, threshold {threshold})")
|
|
106
|
+
with tempfile.TemporaryDirectory() as tmpdir:
|
|
107
|
+
frames = sample_frames(video, Path(tmpdir), interval, crop)
|
|
108
|
+
hashes = [imagehash.phash(_masked(Image.open(f), mask), hash_size=16).hash.flatten() for f in frames]
|
|
109
|
+
|
|
110
|
+
m = max(1, round(min_duration / interval))
|
|
111
|
+
max_gap = max(m + 1, round(MAX_GAP_SECONDS / interval))
|
|
112
|
+
starts = _boundaries(hashes, threshold, m, max_gap) if hashes else []
|
|
113
|
+
|
|
114
|
+
slides_dir.mkdir(parents=True, exist_ok=True)
|
|
115
|
+
for old in slides_dir.glob("slide_*.jpg"):
|
|
116
|
+
old.unlink()
|
|
117
|
+
slides = []
|
|
118
|
+
for n, (first, nxt) in enumerate(zip(starts, [*starts[1:], len(hashes)]), 1):
|
|
119
|
+
last = nxt - 1
|
|
120
|
+
name = f"slide_{n:03d}.jpg"
|
|
121
|
+
extract_frame(video, last * interval, slides_dir / name, crop)
|
|
122
|
+
slides.append({"index": n, "start": first * interval, "end": nxt * interval, "image": str(slides_dir / name)})
|
|
123
|
+
log(f" {len(slides)} slides from {len(frames)} sampled frames ({hms(len(frames) * interval)})")
|
|
124
|
+
return slides
|
talk_notes/source.py
ADDED
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
"""Where a talk comes from: a URL that yt-dlp can download, or a local video file.
|
|
2
|
+
|
|
3
|
+
`open_source(arg)` picks the adapter. Every source provides metadata, audio and video files
|
|
4
|
+
(downloaded on first use), captions, and timestamp links. Every failure surfaces as `SourceError`.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import json
|
|
8
|
+
import tempfile
|
|
9
|
+
from collections.abc import Callable
|
|
10
|
+
from dataclasses import dataclass
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
from typing import Protocol
|
|
13
|
+
|
|
14
|
+
import yt_dlp
|
|
15
|
+
|
|
16
|
+
from talk_notes.util import ffmpeg_exe, log, media_duration
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class SourceError(Exception):
|
|
20
|
+
"""The talk cannot be read: not a file or URL, download failed, or no captions."""
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@dataclass
|
|
24
|
+
class Meta:
|
|
25
|
+
title: str
|
|
26
|
+
id: str | None = None
|
|
27
|
+
url: str | None = None
|
|
28
|
+
channel: str | None = None
|
|
29
|
+
upload_date: str | None = None
|
|
30
|
+
duration: float | None = None
|
|
31
|
+
description: str | None = None
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
Segment = dict # {"start": float, "end": float, "text": str}
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class Source(Protocol):
|
|
38
|
+
meta: Meta
|
|
39
|
+
|
|
40
|
+
def audio(self, media_dir: Path) -> Path:
|
|
41
|
+
"""A file with the talk's audio, downloaded into `media_dir` if needed."""
|
|
42
|
+
...
|
|
43
|
+
|
|
44
|
+
def video(self, media_dir: Path, max_height: int) -> Path:
|
|
45
|
+
"""A file with the talk's video, downloaded into `media_dir` if needed."""
|
|
46
|
+
...
|
|
47
|
+
|
|
48
|
+
def captions(self, language: str | None) -> list[Segment]:
|
|
49
|
+
"""The source's own captions as transcript segments. Raises SourceError if there are none."""
|
|
50
|
+
...
|
|
51
|
+
|
|
52
|
+
def link(self, seconds: float) -> str | None:
|
|
53
|
+
"""A URL that opens the talk at `seconds`, or None if the source has none."""
|
|
54
|
+
...
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def open_source(arg: str) -> Source:
|
|
58
|
+
path = Path(arg).expanduser()
|
|
59
|
+
if path.is_file():
|
|
60
|
+
return LocalFileSource(path.resolve())
|
|
61
|
+
if "://" in arg:
|
|
62
|
+
return UrlSource(arg)
|
|
63
|
+
raise SourceError(f"not a file or URL: {arg}")
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
class LocalFileSource:
|
|
67
|
+
def __init__(self, path: Path):
|
|
68
|
+
self.path = path
|
|
69
|
+
try:
|
|
70
|
+
duration = media_duration(path)
|
|
71
|
+
except ValueError as e:
|
|
72
|
+
raise SourceError(str(e)) from None
|
|
73
|
+
self.meta = Meta(title=path.stem, duration=duration)
|
|
74
|
+
|
|
75
|
+
def audio(self, media_dir: Path) -> Path:
|
|
76
|
+
return self.path
|
|
77
|
+
|
|
78
|
+
def video(self, media_dir: Path, max_height: int) -> Path:
|
|
79
|
+
return self.path
|
|
80
|
+
|
|
81
|
+
def captions(self, language: str | None) -> list[Segment]:
|
|
82
|
+
raise SourceError("local files have no captions; use --transcript whisper")
|
|
83
|
+
|
|
84
|
+
def link(self, seconds: float) -> str | None:
|
|
85
|
+
return None
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
class UrlSource:
|
|
89
|
+
"""Anything yt-dlp supports. `ydl_factory` is the seam tests use to replace yt-dlp."""
|
|
90
|
+
|
|
91
|
+
def __init__(self, url: str, ydl_factory: Callable[[dict], object] | None = None):
|
|
92
|
+
self._ydl_factory = ydl_factory or (lambda opts: yt_dlp.YoutubeDL(opts))
|
|
93
|
+
info = self._run(url, lambda ydl: ydl.extract_info(url, download=False))
|
|
94
|
+
self.url = info.get("webpage_url") or url
|
|
95
|
+
self._extractor = (info.get("extractor_key") or "").lower()
|
|
96
|
+
self.meta = Meta(
|
|
97
|
+
title=info.get("title") or "talk",
|
|
98
|
+
id=info.get("id"),
|
|
99
|
+
url=self.url,
|
|
100
|
+
channel=info.get("channel") or info.get("uploader"),
|
|
101
|
+
upload_date=info.get("upload_date"),
|
|
102
|
+
duration=info.get("duration"),
|
|
103
|
+
description=info.get("description"),
|
|
104
|
+
)
|
|
105
|
+
|
|
106
|
+
def _run(self, what: str, action: Callable, **opts):
|
|
107
|
+
# yt-dlp needs a JS runtime for YouTube; it only enables deno by default.
|
|
108
|
+
options = {"js_runtimes": {"deno": {}, "node": {}}, "quiet": True, "no_warnings": True,
|
|
109
|
+
"noprogress": True, "ffmpeg_location": ffmpeg_exe(), **opts}
|
|
110
|
+
try:
|
|
111
|
+
with self._ydl_factory(options) as ydl:
|
|
112
|
+
return action(ydl)
|
|
113
|
+
except yt_dlp.utils.DownloadError as e:
|
|
114
|
+
raise SourceError(f"yt-dlp failed for {what}: {e}") from None
|
|
115
|
+
|
|
116
|
+
def _download(self, fmt: str, stem: Path) -> Path:
|
|
117
|
+
info = self._run(self.url, lambda ydl: ydl.extract_info(self.url, download=True),
|
|
118
|
+
format=fmt, outtmpl=f"{stem}.%(ext)s")
|
|
119
|
+
return Path(info["requested_downloads"][0]["filepath"])
|
|
120
|
+
|
|
121
|
+
def audio(self, media_dir: Path) -> Path:
|
|
122
|
+
existing = sorted(media_dir.glob("audio.*"))
|
|
123
|
+
if existing:
|
|
124
|
+
return existing[0]
|
|
125
|
+
log("Downloading audio")
|
|
126
|
+
media_dir.mkdir(parents=True, exist_ok=True)
|
|
127
|
+
return self._download("ba[ext=m4a]/ba/b", media_dir / "audio")
|
|
128
|
+
|
|
129
|
+
def video(self, media_dir: Path, max_height: int) -> Path:
|
|
130
|
+
existing = sorted(media_dir.glob("video.*"))
|
|
131
|
+
if existing:
|
|
132
|
+
return existing[0]
|
|
133
|
+
log(f"Downloading video (<= {max_height}p, no audio)")
|
|
134
|
+
media_dir.mkdir(parents=True, exist_ok=True)
|
|
135
|
+
# Video-only stream: slides are all we need from it, so no merge step is required.
|
|
136
|
+
return self._download(f"bv*[height<={max_height}][vcodec^=avc1]/bv*[height<={max_height}]/b",
|
|
137
|
+
media_dir / "video")
|
|
138
|
+
|
|
139
|
+
def captions(self, language: str | None) -> list[Segment]:
|
|
140
|
+
"""Uploaded captions if present, otherwise auto-generated ones."""
|
|
141
|
+
lang = language or "en"
|
|
142
|
+
log(f"Fetching captions ({lang})")
|
|
143
|
+
with tempfile.TemporaryDirectory() as tmp:
|
|
144
|
+
self._run(self.url, lambda ydl: ydl.download([self.url]),
|
|
145
|
+
skip_download=True, writesubtitles=True, writeautomaticsub=True,
|
|
146
|
+
subtitleslangs=[lang, f"{lang}-orig", f"{lang}.*"], subtitlesformat="json3",
|
|
147
|
+
outtmpl=str(Path(tmp) / "subs"))
|
|
148
|
+
files = sorted(Path(tmp).glob("subs.*.json3"))
|
|
149
|
+
if not files:
|
|
150
|
+
raise SourceError(f"no captions found for language '{lang}'; use --transcript whisper")
|
|
151
|
+
return parse_json3(files[0].read_text())
|
|
152
|
+
|
|
153
|
+
def link(self, seconds: float) -> str | None:
|
|
154
|
+
if self._extractor == "youtube" and "watch?v=" in self.url:
|
|
155
|
+
return f"{self.url}&t={int(seconds)}s"
|
|
156
|
+
return None
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def parse_json3(text: str) -> list[Segment]:
|
|
160
|
+
"""Transcript segments from yt-dlp's json3 caption format."""
|
|
161
|
+
segments = []
|
|
162
|
+
for ev in json.loads(text).get("events", []):
|
|
163
|
+
content = "".join(s.get("utf8", "") for s in ev.get("segs", [])).replace("\n", " ").strip()
|
|
164
|
+
if not content:
|
|
165
|
+
continue
|
|
166
|
+
start = ev["tStartMs"] / 1000
|
|
167
|
+
segments.append({"start": start, "end": start + ev.get("dDurationMs", 0) / 1000, "text": content})
|
|
168
|
+
return segments
|
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
"""The output folder of one talk: its layout, and which steps can be reused.
|
|
2
|
+
|
|
3
|
+
Each step (transcript, crop, slides, report) runs through `cached(step, params, compute)`. The
|
|
4
|
+
manifest `talk-notes.json` records the parameters each step ran with; a step runs again when it
|
|
5
|
+
has no result, its parameters changed, or it is named in `--redo`. Steps include the results of
|
|
6
|
+
the steps they depend on in their parameters (slides include the crop, the report hashes
|
|
7
|
+
talk.md and the slide images), so a redone step that changes its result also redoes the steps
|
|
8
|
+
after it.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
import json
|
|
12
|
+
import shutil
|
|
13
|
+
from collections.abc import Callable
|
|
14
|
+
from dataclasses import asdict
|
|
15
|
+
from datetime import UTC, datetime
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
from typing import Any
|
|
18
|
+
|
|
19
|
+
from talk_notes.source import Meta
|
|
20
|
+
from talk_notes.util import log, slugify
|
|
21
|
+
|
|
22
|
+
MANIFEST = "talk-notes.json"
|
|
23
|
+
VERSION = 1
|
|
24
|
+
STEPS = ("transcript", "crop", "slides", "report")
|
|
25
|
+
# Where each step's result is stored; None means inside the manifest.
|
|
26
|
+
FILES = {"transcript": "transcript.json", "crop": None, "slides": "slides.json", "report": "report.md"}
|
|
27
|
+
LEGACY_CROP = Path("crop") / "crop.json"
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class TalkFolder:
|
|
31
|
+
def __init__(self, root: Path, redo: set[str] = frozenset()):
|
|
32
|
+
unknown = set(redo) - set(STEPS)
|
|
33
|
+
if unknown:
|
|
34
|
+
raise ValueError(f"unknown step(s) for --redo: {', '.join(sorted(unknown))}")
|
|
35
|
+
self.root = root
|
|
36
|
+
self.redo = set(redo)
|
|
37
|
+
root.mkdir(parents=True, exist_ok=True)
|
|
38
|
+
path = root / MANIFEST
|
|
39
|
+
# A folder written before the manifest existed: take over its results instead of redoing them.
|
|
40
|
+
self._adopting = not path.exists()
|
|
41
|
+
self._manifest = json.loads(path.read_text()) if path.exists() else {"version": VERSION, "steps": {}}
|
|
42
|
+
self._adopted: set[str] = set()
|
|
43
|
+
|
|
44
|
+
@classmethod
|
|
45
|
+
def for_talk(cls, out: Path, meta: Meta, name: str | None = None, redo: set[str] = frozenset()) -> "TalkFolder":
|
|
46
|
+
name = name or slugify(meta.title) + (f"-{meta.id}" if meta.id else "")
|
|
47
|
+
folder = cls((out / name).resolve(), redo)
|
|
48
|
+
(folder.root / "meta.json").write_text(json.dumps(asdict(meta), indent=2))
|
|
49
|
+
return folder
|
|
50
|
+
|
|
51
|
+
# --- layout -----------------------------------------------------------------------------
|
|
52
|
+
|
|
53
|
+
@property
|
|
54
|
+
def media_dir(self) -> Path:
|
|
55
|
+
"""Downloaded audio and video; deleted by `finish` unless kept."""
|
|
56
|
+
return self.root / "media"
|
|
57
|
+
|
|
58
|
+
@property
|
|
59
|
+
def slides_dir(self) -> Path:
|
|
60
|
+
return self.root / "slides"
|
|
61
|
+
|
|
62
|
+
@property
|
|
63
|
+
def crop_dir(self) -> Path:
|
|
64
|
+
return self.root / "crop"
|
|
65
|
+
|
|
66
|
+
@property
|
|
67
|
+
def talk_md(self) -> Path:
|
|
68
|
+
return self.root / "talk.md"
|
|
69
|
+
|
|
70
|
+
@property
|
|
71
|
+
def report_md(self) -> Path:
|
|
72
|
+
return self.root / FILES["report"]
|
|
73
|
+
|
|
74
|
+
def relative(self, path: Path) -> str:
|
|
75
|
+
return Path(path).resolve().relative_to(self.root).as_posix()
|
|
76
|
+
|
|
77
|
+
# --- caching ----------------------------------------------------------------------------
|
|
78
|
+
|
|
79
|
+
def was_adopted(self, step: str) -> bool:
|
|
80
|
+
"""Whether this run took the step's result over from a folder without a manifest."""
|
|
81
|
+
return step in self._adopted
|
|
82
|
+
|
|
83
|
+
def cached(self, step: str, params: dict, compute: Callable[[], Any], legacy_params: dict | None = None) -> Any:
|
|
84
|
+
"""The step's stored result if still valid, else `compute()`'s result, stored.
|
|
85
|
+
|
|
86
|
+
If `compute` returns None, the step failed: nothing is stored, so the next run retries.
|
|
87
|
+
`legacy_params` are what a result found in a folder without a manifest was made with, when
|
|
88
|
+
that differs from `params`; the result is then recorded with them and redone.
|
|
89
|
+
"""
|
|
90
|
+
params = json.loads(json.dumps(params)) # normalise (tuples, paths) to what the manifest holds
|
|
91
|
+
entry = self._manifest["steps"].get(step)
|
|
92
|
+
if step not in self.redo:
|
|
93
|
+
if entry is None and self._adopting and self._has_legacy_result(step):
|
|
94
|
+
old = json.loads(json.dumps(legacy_params)) if legacy_params is not None else params
|
|
95
|
+
value = self._load_legacy(step)
|
|
96
|
+
self._record(step, old, value)
|
|
97
|
+
self._adopted.add(step)
|
|
98
|
+
if old == params:
|
|
99
|
+
log(f" Reusing the existing {step} from before talk-notes.json")
|
|
100
|
+
return value
|
|
101
|
+
log(f" Redoing the existing {step}: it was made with different options")
|
|
102
|
+
elif entry is not None and entry["params"] == params and self._has_result(step):
|
|
103
|
+
return self._load(step, entry)
|
|
104
|
+
value = compute()
|
|
105
|
+
if value is None:
|
|
106
|
+
return None
|
|
107
|
+
self._record(step, params, value)
|
|
108
|
+
return value
|
|
109
|
+
|
|
110
|
+
def _has_result(self, step: str) -> bool:
|
|
111
|
+
file = FILES[step]
|
|
112
|
+
return file is None or (self.root / file).exists()
|
|
113
|
+
|
|
114
|
+
def _has_legacy_result(self, step: str) -> bool:
|
|
115
|
+
if step == "crop":
|
|
116
|
+
return (self.root / LEGACY_CROP).exists()
|
|
117
|
+
return (self.root / FILES[step]).exists()
|
|
118
|
+
|
|
119
|
+
def _load(self, step: str, entry: dict) -> Any:
|
|
120
|
+
file = FILES[step]
|
|
121
|
+
if file is None:
|
|
122
|
+
return entry["value"]
|
|
123
|
+
text = (self.root / file).read_text()
|
|
124
|
+
return json.loads(text) if file.endswith(".json") else text
|
|
125
|
+
|
|
126
|
+
def _load_legacy(self, step: str) -> Any:
|
|
127
|
+
if step == "crop":
|
|
128
|
+
legacy = self.root / LEGACY_CROP
|
|
129
|
+
value = json.loads(legacy.read_text())
|
|
130
|
+
legacy.unlink()
|
|
131
|
+
return value
|
|
132
|
+
return self._load(step, {})
|
|
133
|
+
|
|
134
|
+
def _record(self, step: str, params: dict, value: Any) -> None:
|
|
135
|
+
file = FILES[step]
|
|
136
|
+
entry = {"params": params, "finished": datetime.now(UTC).isoformat(timespec="seconds")}
|
|
137
|
+
if file is None:
|
|
138
|
+
entry["value"] = value
|
|
139
|
+
else:
|
|
140
|
+
path = self.root / file
|
|
141
|
+
path.write_text(json.dumps(value, indent=2) if file.endswith(".json") else value)
|
|
142
|
+
self._manifest["steps"][step] = entry
|
|
143
|
+
self._manifest["version"] = VERSION
|
|
144
|
+
(self.root / MANIFEST).write_text(json.dumps(self._manifest, indent=2) + "\n")
|
|
145
|
+
|
|
146
|
+
def finish(self, keep_media: bool) -> None:
|
|
147
|
+
if not keep_media:
|
|
148
|
+
shutil.rmtree(self.media_dir, ignore_errors=True)
|
talk_notes/transcribe.py
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import ctypes
|
|
2
|
+
import sys
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
|
|
5
|
+
from talk_notes.util import hms, log
|
|
6
|
+
|
|
7
|
+
DEFAULTS = {
|
|
8
|
+
# device: (model, compute_type)
|
|
9
|
+
"cuda": ("large-v3-turbo", "float16"),
|
|
10
|
+
"cpu": ("small", "int8"),
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _preload_cuda_libs() -> None:
|
|
15
|
+
"""Load cuBLAS/cuDNN from the `gpu` extra's pip wheels so LD_LIBRARY_PATH needs no setup."""
|
|
16
|
+
try:
|
|
17
|
+
import nvidia
|
|
18
|
+
except ImportError:
|
|
19
|
+
return
|
|
20
|
+
libs = [p for base in nvidia.__path__ for p in Path(base).glob("*/lib/lib*.so*") if "cublas" in p.name or "cudnn" in p.name]
|
|
21
|
+
# Libraries depend on each other; retry until no more can be loaded.
|
|
22
|
+
pending = sorted(libs)
|
|
23
|
+
while pending:
|
|
24
|
+
failed = []
|
|
25
|
+
for lib in pending:
|
|
26
|
+
try:
|
|
27
|
+
ctypes.CDLL(str(lib), mode=ctypes.RTLD_GLOBAL)
|
|
28
|
+
except OSError:
|
|
29
|
+
failed.append(lib)
|
|
30
|
+
if len(failed) == len(pending):
|
|
31
|
+
break
|
|
32
|
+
pending = failed
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def resolve_device(device: str) -> str:
|
|
36
|
+
if device != "auto":
|
|
37
|
+
if device == "cuda":
|
|
38
|
+
_preload_cuda_libs()
|
|
39
|
+
return device
|
|
40
|
+
_preload_cuda_libs()
|
|
41
|
+
import ctranslate2
|
|
42
|
+
|
|
43
|
+
return "cuda" if ctranslate2.get_cuda_device_count() > 0 else "cpu"
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def whisper_settings(device: str, model: str | None, compute_type: str | None) -> tuple[str, str, str]:
|
|
47
|
+
"""(device, model, compute_type) with "auto" and missing values resolved to the defaults."""
|
|
48
|
+
device = resolve_device(device)
|
|
49
|
+
default_model, default_ct = DEFAULTS[device]
|
|
50
|
+
return device, model or default_model, compute_type or default_ct
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def whisper_transcript(audio: Path, device: str, model: str | None, compute_type: str | None, language: str | None) -> list[dict]:
|
|
54
|
+
from faster_whisper import WhisperModel
|
|
55
|
+
|
|
56
|
+
default_model, default_ct = DEFAULTS[device]
|
|
57
|
+
model = model or default_model
|
|
58
|
+
compute_type = compute_type or default_ct
|
|
59
|
+
log(f"Transcribing with faster-whisper {model} on {device} ({compute_type})")
|
|
60
|
+
whisper = WhisperModel(model, device=device, compute_type=compute_type)
|
|
61
|
+
segments, info = whisper.transcribe(str(audio), language=language, vad_filter=True, beam_size=5)
|
|
62
|
+
out = []
|
|
63
|
+
for seg in segments:
|
|
64
|
+
out.append({"start": seg.start, "end": seg.end, "text": seg.text.strip()})
|
|
65
|
+
print(f"\r {hms(seg.end)} / {hms(info.duration)}", end="", flush=True, file=sys.stderr)
|
|
66
|
+
log("")
|
|
67
|
+
return out
|