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
talk_notes/__init__.py
ADDED
|
File without changes
|
talk_notes/__main__.py
ADDED
talk_notes/cli.py
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
import argparse
|
|
2
|
+
import hashlib
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
|
|
5
|
+
from talk_notes import report
|
|
6
|
+
from talk_notes.crop import auto_crop
|
|
7
|
+
from talk_notes.llm import ADAPTERS, DEFAULT_OLLAMA_URL, LLMError, make_llm
|
|
8
|
+
from talk_notes.render import render_markdown
|
|
9
|
+
from talk_notes.slides import detect_slides
|
|
10
|
+
from talk_notes.source import SourceError, open_source
|
|
11
|
+
from talk_notes.talk_folder import STEPS, TalkFolder
|
|
12
|
+
from talk_notes.transcript import METHODS, get_transcript, transcript_params
|
|
13
|
+
from talk_notes.util import log
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class _HelpFormatter(argparse.ArgumentDefaultsHelpFormatter):
|
|
17
|
+
"""Show defaults only where there is one worth showing."""
|
|
18
|
+
|
|
19
|
+
def _get_help_string(self, action: argparse.Action) -> str:
|
|
20
|
+
if action.default in (None, False, set()) or action.default is argparse.SUPPRESS:
|
|
21
|
+
return action.help or ""
|
|
22
|
+
return super()._get_help_string(action)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _steps(value: str) -> set[str]:
|
|
26
|
+
steps = {s.strip() for s in value.split(",") if s.strip()}
|
|
27
|
+
if steps == {"all"}:
|
|
28
|
+
return set(STEPS)
|
|
29
|
+
unknown = steps - set(STEPS)
|
|
30
|
+
if unknown:
|
|
31
|
+
raise argparse.ArgumentTypeError(f"unknown step(s): {', '.join(sorted(unknown))}")
|
|
32
|
+
return steps
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
|
|
36
|
+
p = argparse.ArgumentParser(
|
|
37
|
+
prog="talk-notes",
|
|
38
|
+
description="Turn a talk (YouTube/yt-dlp URL or local video) into slides + aligned transcript + report.",
|
|
39
|
+
formatter_class=_HelpFormatter,
|
|
40
|
+
)
|
|
41
|
+
p.add_argument("source", help="video URL (anything yt-dlp supports) or local video file")
|
|
42
|
+
p.add_argument("-o", "--out", type=Path, default=Path("out"), help="parent output directory")
|
|
43
|
+
p.add_argument("--name", help="output folder name (default: from the title)")
|
|
44
|
+
p.add_argument("--redo", type=_steps, default=set(), metavar="STEPS",
|
|
45
|
+
help="redo these steps even if their results are still valid: comma-separated from "
|
|
46
|
+
f"{', '.join(STEPS)}, or 'all'. Steps whose options changed are redone automatically")
|
|
47
|
+
p.add_argument("--keep-media", action="store_true", help="keep downloaded video/audio after processing")
|
|
48
|
+
|
|
49
|
+
t = p.add_argument_group("transcript")
|
|
50
|
+
t.add_argument("--transcript", choices=METHODS, default="whisper",
|
|
51
|
+
help="local speech recognition, or the captions the video site already has (fast, lower "
|
|
52
|
+
"quality; URLs only)")
|
|
53
|
+
t.add_argument("--device", choices=["auto", "cpu", "cuda"], default="auto")
|
|
54
|
+
t.add_argument("--whisper-model", help="faster-whisper model (default: large-v3-turbo on cuda, small on cpu)")
|
|
55
|
+
t.add_argument("--compute-type", help="CTranslate2 compute type (default: float16 on cuda, int8 on cpu)")
|
|
56
|
+
t.add_argument("--language", help="spoken language code, e.g. en (default: auto-detect)")
|
|
57
|
+
|
|
58
|
+
s = p.add_argument_group("slides")
|
|
59
|
+
s.add_argument("--no-slides", action="store_true", help="skip slide extraction")
|
|
60
|
+
s.add_argument("--max-height", type=int, default=1080, help="max video resolution to download")
|
|
61
|
+
s.add_argument("--slide-interval", type=float, default=2.0, help="seconds between sampled frames")
|
|
62
|
+
s.add_argument("--slide-threshold", type=int, default=12,
|
|
63
|
+
help="perceptual-hash bit difference that counts as a new slide (lower = more slides)")
|
|
64
|
+
s.add_argument("--min-slide-duration", type=float, default=4.0,
|
|
65
|
+
help="shortest slide in seconds; raise it for live coding to get fewer, fuller slides")
|
|
66
|
+
s.add_argument("--crop", default="auto",
|
|
67
|
+
help="slide area as ffmpeg crop w:h:x:y, 'auto' to have a vision model find it, or 'none' "
|
|
68
|
+
"for the full frame; used for change detection and the saved images, to cut away a "
|
|
69
|
+
"speaker camera or conference banner")
|
|
70
|
+
|
|
71
|
+
m = p.add_argument_group("LLM (used by --crop auto and the report)")
|
|
72
|
+
m.add_argument("--llm", choices=sorted(ADAPTERS), default="claude",
|
|
73
|
+
help="claude runs the Claude Code CLI; ollama is fully local")
|
|
74
|
+
m.add_argument("--llm-model", help="model name for the LLM backend (default: the backend's own default)")
|
|
75
|
+
m.add_argument("--ollama-url", default=DEFAULT_OLLAMA_URL, help="Ollama server used by --llm ollama")
|
|
76
|
+
|
|
77
|
+
r = p.add_argument_group("report")
|
|
78
|
+
r.add_argument("--report", action=argparse.BooleanOptionalAction, default=True,
|
|
79
|
+
help="write report.md with the LLM")
|
|
80
|
+
r.add_argument("--prompt", type=Path, help="Markdown file replacing the report-writing instructions "
|
|
81
|
+
"(default: the bundled prompts/report.md)")
|
|
82
|
+
return p.parse_args(argv)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def main(argv: list[str] | None = None) -> None:
|
|
86
|
+
args = parse_args(argv)
|
|
87
|
+
try:
|
|
88
|
+
run(args)
|
|
89
|
+
except SourceError as e:
|
|
90
|
+
raise SystemExit(f"Error: {e}") from None
|
|
91
|
+
except LLMError as e:
|
|
92
|
+
raise SystemExit(f"Report failed: {e}") from None
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def _sha256(data: bytes) -> str:
|
|
96
|
+
return hashlib.sha256(data).hexdigest()
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def run(args: argparse.Namespace) -> None:
|
|
100
|
+
llm = make_llm(args.llm, args.llm_model, args.ollama_url)
|
|
101
|
+
source = open_source(args.source)
|
|
102
|
+
folder = TalkFolder.for_talk(args.out, source.meta, args.name, args.redo)
|
|
103
|
+
log(f"Output: {folder.root}")
|
|
104
|
+
|
|
105
|
+
params = transcript_params(args.transcript, args.language, args.device, args.whisper_model, args.compute_type)
|
|
106
|
+
segments = folder.cached("transcript", params,
|
|
107
|
+
lambda: get_transcript(source, params, folder.media_dir, args.device))
|
|
108
|
+
|
|
109
|
+
slides = []
|
|
110
|
+
if not args.no_slides:
|
|
111
|
+
if args.crop == "auto":
|
|
112
|
+
result = folder.cached("crop", {"crop": "auto", "llm": llm.name},
|
|
113
|
+
lambda: auto_crop(source.video(folder.media_dir, args.max_height),
|
|
114
|
+
folder.crop_dir, llm))
|
|
115
|
+
crop = result["crop"] if result else None
|
|
116
|
+
mask = result.get("mask") if result else None
|
|
117
|
+
else:
|
|
118
|
+
crop, mask = (None if args.crop == "none" else args.crop), None
|
|
119
|
+
folder.cached("crop", {"crop": args.crop}, lambda: {"crop": crop})
|
|
120
|
+
|
|
121
|
+
def find_slides() -> list[dict]:
|
|
122
|
+
found = detect_slides(source.video(folder.media_dir, args.max_height), folder.slides_dir,
|
|
123
|
+
args.slide_interval, args.slide_threshold, args.min_slide_duration, crop, mask)
|
|
124
|
+
return [{**s, "image": folder.relative(s["image"])} for s in found]
|
|
125
|
+
|
|
126
|
+
params = {"interval": args.slide_interval, "threshold": args.slide_threshold,
|
|
127
|
+
"min_duration": args.min_slide_duration, "max_height": args.max_height, "crop": crop,
|
|
128
|
+
"mask": mask}
|
|
129
|
+
# Slides from before talk-notes.json without a recorded crop were made from the full frame.
|
|
130
|
+
legacy = {**params, "mask": None} if folder.was_adopted("crop") else {**params, "crop": None, "mask": None}
|
|
131
|
+
slides = folder.cached("slides", params, find_slides, legacy_params=legacy)
|
|
132
|
+
|
|
133
|
+
folder.talk_md.write_text(render_markdown(source.meta, slides, segments, source.link))
|
|
134
|
+
folder.finish(args.keep_media)
|
|
135
|
+
|
|
136
|
+
if args.report:
|
|
137
|
+
prompt = report.load_prompt(args.prompt)
|
|
138
|
+
images = [folder.root / s["image"] for s in slides]
|
|
139
|
+
params = {"talk_md": _sha256(folder.talk_md.read_bytes()),
|
|
140
|
+
"slides": _sha256(b"".join(i.read_bytes() for i in images)),
|
|
141
|
+
"prompt": _sha256(prompt.encode()), "llm": llm.name}
|
|
142
|
+
folder.cached("report", params, lambda: report.generate_report(folder.talk_md, images, llm, prompt))
|
|
143
|
+
|
|
144
|
+
log(f"Done: {folder.talk_md}" + (f", {folder.report_md}" if args.report else ""))
|
talk_notes/crop.py
ADDED
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
"""Find the part of the video frame that shows the presentation.
|
|
2
|
+
|
|
3
|
+
A vision model looks at a few frames spread over the talk and returns a rough box as fractions
|
|
4
|
+
of the frame. Models are imprecise with coordinates, so each side is then snapped to the
|
|
5
|
+
strongest straight edge nearby, measured across all sampled frames.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import json
|
|
9
|
+
import subprocess
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
|
|
12
|
+
import numpy as np
|
|
13
|
+
from PIL import Image, ImageDraw
|
|
14
|
+
|
|
15
|
+
from talk_notes.llm import LLM, LLMError
|
|
16
|
+
from talk_notes.util import ffmpeg_exe, log, media_duration
|
|
17
|
+
|
|
18
|
+
N_FRAMES = 8
|
|
19
|
+
SNAP_WINDOW = 0.04 # search this fraction of the frame size on each side of the model's line
|
|
20
|
+
SNAP_BOX_FRACTION = 0.15 # ... but at most this fraction of the box's own size
|
|
21
|
+
INSET = 2 # pixels trimmed inside the snapped edge, to drop the border line itself
|
|
22
|
+
|
|
23
|
+
PROMPT = """\
|
|
24
|
+
These are {n} frames sampled across a recorded tech talk: {files}.
|
|
25
|
+
I want to crop the video to the region that shows the presentation (slides, screen share or
|
|
26
|
+
live demo) and cut away everything else: conference branding, banners and lower thirds,
|
|
27
|
+
sponsor logos, sidebars, and a speaker camera placed next to the slides.
|
|
28
|
+
|
|
29
|
+
Rules:
|
|
30
|
+
- The layout is fixed, so give one region that fits all frames where the presentation is visible.
|
|
31
|
+
- Frames showing only the speaker or the audience are camera cuts; ignore them.
|
|
32
|
+
- If the presentation already fills the whole frame, or the video alternates between full-frame
|
|
33
|
+
camera shots and full-frame slides, there is nothing to crop: answer null.
|
|
34
|
+
- A small speaker camera overlaid on top of the slide area is part of the region; do not cut
|
|
35
|
+
slide content to avoid it. Report it separately as "camera" instead, so it can be ignored when
|
|
36
|
+
detecting slide changes. Use null if there is no such overlay.
|
|
37
|
+
|
|
38
|
+
Answer with only this JSON, no other text:
|
|
39
|
+
{{"box": [left, top, right, bottom] or null, "camera": [left, top, right, bottom] or null,
|
|
40
|
+
"layout": "<one sentence describing the layout>"}}
|
|
41
|
+
where left/right are fractions of the frame width and top/bottom fractions of the frame height,
|
|
42
|
+
each between 0 and 1. Both boxes are in the coordinates of the whole frame.
|
|
43
|
+
"""
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _sample(video: Path, dest: Path) -> list[Path]:
|
|
47
|
+
dest.mkdir(parents=True, exist_ok=True)
|
|
48
|
+
duration = media_duration(video)
|
|
49
|
+
frames = []
|
|
50
|
+
for i in range(N_FRAMES):
|
|
51
|
+
t = duration * (i + 1) / (N_FRAMES + 1)
|
|
52
|
+
f = dest / f"frame_{i + 1}.jpg"
|
|
53
|
+
subprocess.run([ffmpeg_exe(), "-v", "error", "-y", "-ss", f"{t:.2f}", "-i", str(video),
|
|
54
|
+
"-frames:v", "1", "-q:v", "2", str(f)], check=True)
|
|
55
|
+
frames.append(f)
|
|
56
|
+
return frames
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _box(value, min_size: float) -> list[float] | None:
|
|
60
|
+
if value is None:
|
|
61
|
+
return None
|
|
62
|
+
box = [min(1.0, max(0.0, float(v))) for v in value]
|
|
63
|
+
if len(box) != 4 or box[2] - box[0] < min_size or box[3] - box[1] < min_size:
|
|
64
|
+
raise ValueError(f"implausible box {box}")
|
|
65
|
+
return box
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _parse(answer: str) -> tuple[list[float] | None, list[float] | None, str]:
|
|
69
|
+
start = answer.find("{")
|
|
70
|
+
if start < 0:
|
|
71
|
+
raise ValueError(f"no JSON in model answer: {answer[:200]!r}")
|
|
72
|
+
data, _ = json.JSONDecoder().raw_decode(answer, start) # ignores any text after the object
|
|
73
|
+
box = _box(data.get("box"), 0.2)
|
|
74
|
+
try:
|
|
75
|
+
camera = _box(data.get("camera"), 0.02)
|
|
76
|
+
except ValueError:
|
|
77
|
+
camera = None # a bad camera box only costs the mask, not the crop
|
|
78
|
+
return box, camera, data.get("layout", "")
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _ask_model(frames: list[Path], llm: LLM) -> tuple[list[float] | None, list[float] | None, str]:
|
|
82
|
+
prompt = PROMPT.format(n=len(frames), files=", ".join(f.name for f in frames))
|
|
83
|
+
return _parse(llm.ask(prompt, frames))
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _snap(profile: np.ndarray, guess: int, window: int, nearest: bool = False) -> int:
|
|
87
|
+
"""An edge in profile[guess-window : guess+window], or guess if none stands out.
|
|
88
|
+
|
|
89
|
+
By default the strongest edge; with `nearest`, the clear edge closest to the guess, so a small
|
|
90
|
+
box (a camera overlay) doesn't jump onto a stronger neighbouring edge such as the slide border.
|
|
91
|
+
"""
|
|
92
|
+
lo, hi = max(1, guess - window), min(len(profile) - 1, guess + window)
|
|
93
|
+
if hi <= lo:
|
|
94
|
+
return guess
|
|
95
|
+
segment = profile[lo:hi]
|
|
96
|
+
floor = max(8.0, 4 * float(np.median(segment)))
|
|
97
|
+
if nearest:
|
|
98
|
+
clear = [lo + k for k in range(len(segment)) if segment[k] >= floor]
|
|
99
|
+
return min(clear, key=lambda i: abs(i - guess)) if clear else guess
|
|
100
|
+
best = int(np.argmax(segment))
|
|
101
|
+
return lo + best if segment[best] >= floor else guess
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def _refine(frames: list[Path], box: list[float], nearest: bool = False) -> tuple[int, int, int, int]:
|
|
105
|
+
gray = np.stack([np.asarray(Image.open(f).convert("L"), dtype=np.float32) for f in frames])
|
|
106
|
+
_, h, w = gray.shape
|
|
107
|
+
left, top, right, bottom = (round(box[0] * w), round(box[1] * h), round(box[2] * w), round(box[3] * h))
|
|
108
|
+
# Edge strength between neighbouring rows/columns, averaged over the frames and along the
|
|
109
|
+
# box's span, so a full-length border beats text or UI lines inside the slide.
|
|
110
|
+
rows = np.abs(np.diff(gray[:, :, left:right], axis=1)).mean(axis=(0, 2))
|
|
111
|
+
cols = np.abs(np.diff(gray[:, top:bottom, :], axis=2)).mean(axis=(0, 1))
|
|
112
|
+
# diff index i is the boundary between pixel i and i+1, i.e. content starting at i+1.
|
|
113
|
+
rows = np.concatenate([[0], rows])
|
|
114
|
+
cols = np.concatenate([[0], cols])
|
|
115
|
+
# Search near each guessed side, but not so far that a small box snaps onto a neighbour's edge.
|
|
116
|
+
win_y = round(min(SNAP_WINDOW * h, SNAP_BOX_FRACTION * (bottom - top)))
|
|
117
|
+
win_x = round(min(SNAP_WINDOW * w, SNAP_BOX_FRACTION * (right - left)))
|
|
118
|
+
top = _snap(rows, top, win_y, nearest) + INSET
|
|
119
|
+
bottom = _snap(rows, bottom, win_y, nearest) - INSET
|
|
120
|
+
left = _snap(cols, left, win_x, nearest) + INSET
|
|
121
|
+
right = _snap(cols, right, win_x, nearest) - INSET
|
|
122
|
+
left, top = max(0, left), max(0, top)
|
|
123
|
+
right, bottom = min(w, right), min(h, bottom)
|
|
124
|
+
width, height = (right - left) // 2 * 2, (bottom - top) // 2 * 2
|
|
125
|
+
return width, height, left, top
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
MASK_MARGIN = 0.01 # widen the camera mask by this fraction of the frame on each side
|
|
129
|
+
MAX_MASK_AREA = 0.25 # a "camera" covering more of the slide area than this is not an overlay
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def _mask(frames: list[Path], camera: list[float], area: tuple[int, int, int, int]) -> list[float] | None:
|
|
133
|
+
"""The camera box snapped to its edges, as [left, top, right, bottom] fractions of `area` (w, h, x, y)."""
|
|
134
|
+
cw, ch, cx, cy = _refine(frames, camera, nearest=True)
|
|
135
|
+
full_w, full_h = Image.open(frames[0]).size
|
|
136
|
+
mx, my = MASK_MARGIN * full_w, MASK_MARGIN * full_h
|
|
137
|
+
aw, ah, ax, ay = area
|
|
138
|
+
mask = [(cx - mx - ax) / aw, (cy - my - ay) / ah, (cx + cw + mx - ax) / aw, (cy + ch + my - ay) / ah]
|
|
139
|
+
mask = [min(1.0, max(0.0, v)) for v in mask]
|
|
140
|
+
size = (mask[2] - mask[0]) * (mask[3] - mask[1])
|
|
141
|
+
return mask if 0 < size <= MAX_MASK_AREA else None
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def _preview(frame: Path, crop: str | None, mask: list[float] | None, dest: Path) -> None:
|
|
145
|
+
im = Image.open(frame).convert("RGB")
|
|
146
|
+
draw = ImageDraw.Draw(im)
|
|
147
|
+
w, h, x, y = map(int, crop.split(":")) if crop else (*im.size, 0, 0)
|
|
148
|
+
if crop:
|
|
149
|
+
draw.rectangle([x, y, x + w - 1, y + h - 1], outline=(255, 0, 0), width=4)
|
|
150
|
+
if mask:
|
|
151
|
+
draw.rectangle([x + mask[0] * w, y + mask[1] * h, x + mask[2] * w, y + mask[3] * h],
|
|
152
|
+
outline=(0, 120, 255), width=4)
|
|
153
|
+
im.save(dest, quality=85)
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def auto_crop(video: Path, work_dir: Path, llm: LLM) -> dict | None:
|
|
157
|
+
"""Find the presentation area and any speaker camera overlaid on it.
|
|
158
|
+
|
|
159
|
+
Returns {"crop": "w:h:x:y" or None for the full frame, "mask": [left, top, right, bottom] as
|
|
160
|
+
fractions of the slide area or None, "layout", "model_box", "model_camera"}. The mask is the
|
|
161
|
+
overlaid camera, which slide detection ignores. Writes `preview.jpg` (crop in red, mask in
|
|
162
|
+
blue) into `work_dir`. If the LLM fails or answers
|
|
163
|
+
nonsense, logs why and returns None, so the caller can fall back without caching a result.
|
|
164
|
+
"""
|
|
165
|
+
log(f"Finding the slide area with {llm.name}")
|
|
166
|
+
frames = _sample(video, work_dir)
|
|
167
|
+
try:
|
|
168
|
+
try:
|
|
169
|
+
box, camera, layout = _ask_model(frames, llm)
|
|
170
|
+
except (LLMError, ValueError) as e:
|
|
171
|
+
log(f" Automatic crop failed ({e}); using the full frame. Pass --crop to set it by hand.")
|
|
172
|
+
return None
|
|
173
|
+
log(f" Layout: {layout}")
|
|
174
|
+
full_w, full_h = Image.open(frames[0]).size
|
|
175
|
+
crop, area = None, (full_w, full_h, 0, 0)
|
|
176
|
+
if box is not None:
|
|
177
|
+
w, h, x, y = _refine(frames, box)
|
|
178
|
+
if w * h <= 0.95 * full_w * full_h:
|
|
179
|
+
crop, area = f"{w}:{h}:{x}:{y}", (w, h, x, y)
|
|
180
|
+
mask = _mask(frames, camera, area) if camera else None
|
|
181
|
+
_preview(frames[len(frames) // 2], crop, mask, work_dir / "preview.jpg")
|
|
182
|
+
finally:
|
|
183
|
+
for f in frames:
|
|
184
|
+
f.unlink()
|
|
185
|
+
log(f" Crop: {crop or 'none (full frame)'}; camera mask: {'yes' if mask else 'none'}; "
|
|
186
|
+
f"check {work_dir / 'preview.jpg'}")
|
|
187
|
+
return {"crop": crop, "mask": mask, "layout": layout, "model_box": box, "model_camera": camera}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
"""LLM backends behind one interface: `ask(prompt, files) -> str`.
|
|
2
|
+
|
|
3
|
+
Callers pass a prompt and absolute paths to text and image files; each adapter decides how to
|
|
4
|
+
deliver them (an agent CLI reads them from disk, an HTTP model gets them inline). Every failure
|
|
5
|
+
surfaces as `LLMError`.
|
|
6
|
+
|
|
7
|
+
To add a backend, write an adapter module with a class that has a `name` attribute and an
|
|
8
|
+
`ask(prompt, files)` method, then add one entry to `ADAPTERS` below.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from collections.abc import Callable, Sequence
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
from typing import Protocol
|
|
14
|
+
|
|
15
|
+
from talk_notes.llm.base import LLMError
|
|
16
|
+
from talk_notes.llm.claude_code import ClaudeCodeLLM
|
|
17
|
+
from talk_notes.llm.fake import FakeLLM
|
|
18
|
+
from talk_notes.llm.ollama import DEFAULT_URL as DEFAULT_OLLAMA_URL
|
|
19
|
+
from talk_notes.llm.ollama import OllamaLLM
|
|
20
|
+
|
|
21
|
+
__all__ = ["ADAPTERS", "DEFAULT_OLLAMA_URL", "LLM", "ClaudeCodeLLM", "FakeLLM", "LLMError", "OllamaLLM", "make_llm"]
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class LLM(Protocol):
|
|
25
|
+
name: str
|
|
26
|
+
|
|
27
|
+
def ask(self, prompt: str, files: Sequence[Path] = ()) -> str:
|
|
28
|
+
"""Answer `prompt`, taking the text and image `files` into account. Raises LLMError."""
|
|
29
|
+
...
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
# Backend name (as used by --llm) -> factory taking (model, ollama_url).
|
|
33
|
+
ADAPTERS: dict[str, Callable[[str | None, str], LLM]] = {
|
|
34
|
+
"claude": lambda model, ollama_url: ClaudeCodeLLM(model),
|
|
35
|
+
"ollama": lambda model, ollama_url: OllamaLLM(model, ollama_url),
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def make_llm(name: str, model: str | None = None, ollama_url: str = DEFAULT_OLLAMA_URL) -> LLM:
|
|
40
|
+
try:
|
|
41
|
+
factory = ADAPTERS[name]
|
|
42
|
+
except KeyError:
|
|
43
|
+
raise LLMError(f"unknown LLM backend {name!r}; choose one of {', '.join(ADAPTERS)}") from None
|
|
44
|
+
return factory(model, ollama_url)
|
talk_notes/llm/base.py
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import os
|
|
2
|
+
from collections.abc import Sequence
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
|
|
5
|
+
IMAGE_SUFFIXES = {".jpg", ".jpeg", ".png", ".webp", ".gif"}
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class LLMError(Exception):
|
|
9
|
+
"""An LLM backend could not produce an answer: not installed, unreachable, failed or empty."""
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def common_dir(files: Sequence[Path]) -> Path:
|
|
13
|
+
"""The deepest folder containing all `files` (the current folder if there are none)."""
|
|
14
|
+
if not files:
|
|
15
|
+
return Path.cwd()
|
|
16
|
+
return Path(os.path.commonpath([str(Path(f).resolve().parent) for f in files]))
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def is_image(path: Path) -> bool:
|
|
20
|
+
return path.suffix.lower() in IMAGE_SUFFIXES
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import shutil
|
|
2
|
+
import subprocess
|
|
3
|
+
from collections.abc import Sequence
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
|
|
6
|
+
from talk_notes.llm.base import LLMError, common_dir
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class ClaudeCodeLLM:
|
|
10
|
+
"""Runs `claude -p` read-only in the folder holding the files and returns what it prints."""
|
|
11
|
+
|
|
12
|
+
def __init__(self, model: str | None = None, executable: str = "claude", timeout: float = 1800):
|
|
13
|
+
self.model = model
|
|
14
|
+
self.executable = executable
|
|
15
|
+
self.timeout = timeout
|
|
16
|
+
self.name = f"Claude Code ({model})" if model else "Claude Code"
|
|
17
|
+
|
|
18
|
+
def ask(self, prompt: str, files: Sequence[Path] = ()) -> str:
|
|
19
|
+
exe = shutil.which(self.executable)
|
|
20
|
+
if not exe:
|
|
21
|
+
raise LLMError(f"`{self.executable}` CLI not found; install Claude Code or use --llm ollama")
|
|
22
|
+
files = [Path(f).resolve() for f in files]
|
|
23
|
+
cwd = common_dir(files)
|
|
24
|
+
if files:
|
|
25
|
+
listing = "\n".join(f"- {f.relative_to(cwd)}" for f in files)
|
|
26
|
+
prompt += f"\n\nRead each of these files from the current folder, including every image:\n{listing}"
|
|
27
|
+
cmd = [exe, "-p", prompt, "--allowedTools", "Read"]
|
|
28
|
+
if self.model:
|
|
29
|
+
cmd += ["--model", self.model]
|
|
30
|
+
try:
|
|
31
|
+
result = subprocess.run(cmd, cwd=cwd, stdin=subprocess.DEVNULL, capture_output=True, text=True, check=False,
|
|
32
|
+
timeout=self.timeout)
|
|
33
|
+
except subprocess.TimeoutExpired:
|
|
34
|
+
raise LLMError(f"Claude Code did not answer within {self.timeout:.0f}s") from None
|
|
35
|
+
if result.returncode != 0:
|
|
36
|
+
detail = (result.stderr or result.stdout).strip()[-500:]
|
|
37
|
+
raise LLMError(f"Claude Code exited with {result.returncode}: {detail}")
|
|
38
|
+
answer = result.stdout.strip()
|
|
39
|
+
if not answer:
|
|
40
|
+
raise LLMError("Claude Code returned an empty answer")
|
|
41
|
+
return answer
|
talk_notes/llm/fake.py
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
from collections.abc import Callable, Sequence
|
|
2
|
+
from pathlib import Path
|
|
3
|
+
|
|
4
|
+
from talk_notes.llm.base import LLMError
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class FakeLLM:
|
|
8
|
+
"""Scripted answers for tests. Records every call in `calls` as (prompt, files)."""
|
|
9
|
+
|
|
10
|
+
name = "fake"
|
|
11
|
+
|
|
12
|
+
def __init__(self, answers: Sequence[str | Exception] | Callable[[str, list[Path]], str] = ()):
|
|
13
|
+
self._answers = answers if callable(answers) else list(answers)
|
|
14
|
+
self.calls: list[tuple[str, list[Path]]] = []
|
|
15
|
+
|
|
16
|
+
def ask(self, prompt: str, files: Sequence[Path] = ()) -> str:
|
|
17
|
+
files = [Path(f) for f in files]
|
|
18
|
+
self.calls.append((prompt, files))
|
|
19
|
+
if callable(self._answers):
|
|
20
|
+
return self._answers(prompt, files)
|
|
21
|
+
if not self._answers:
|
|
22
|
+
raise LLMError("FakeLLM has no scripted answer left")
|
|
23
|
+
answer = self._answers.pop(0)
|
|
24
|
+
if isinstance(answer, Exception):
|
|
25
|
+
raise answer
|
|
26
|
+
return answer
|
talk_notes/llm/ollama.py
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
import base64
|
|
2
|
+
import hashlib
|
|
3
|
+
import io
|
|
4
|
+
import json
|
|
5
|
+
import re
|
|
6
|
+
import urllib.error
|
|
7
|
+
import urllib.parse
|
|
8
|
+
import urllib.request
|
|
9
|
+
from collections.abc import Sequence
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
|
|
12
|
+
from PIL import Image
|
|
13
|
+
|
|
14
|
+
from talk_notes.llm.base import LLMError, common_dir, is_image
|
|
15
|
+
from talk_notes.util import log
|
|
16
|
+
|
|
17
|
+
DEFAULT_URL = "http://localhost:11434"
|
|
18
|
+
DEFAULT_MODEL = "qwen3-vl:8b-instruct"
|
|
19
|
+
NUM_CTX = 32768
|
|
20
|
+
# Context for describing one image: its tokens, the prompt and MAX_DESCRIPTION_TOKENS. A smaller
|
|
21
|
+
# context needs less VRAM, so more of the model runs on the GPU (about 2.5x faster on 8 GB).
|
|
22
|
+
DESCRIBE_NUM_CTX = 8192
|
|
23
|
+
# Longest answers allowed, in tokens. Small models can get stuck repeating themselves, which
|
|
24
|
+
# otherwise goes on until the context is full. Thinking tokens count towards the limit.
|
|
25
|
+
MAX_ANSWER_TOKENS = 16000
|
|
26
|
+
MAX_DESCRIPTION_TOKENS = 2048
|
|
27
|
+
# Images are sent at most this large (long side, pixels): enough for slide text and for finding
|
|
28
|
+
# a layout, and much faster than full HD on CPU. Answers about geometry are in fractions anyway.
|
|
29
|
+
MAX_IMAGE_SIDE = 1024
|
|
30
|
+
# Above this many images per request, images are described one by one first and the request is
|
|
31
|
+
# sent as text only. Eight images at MAX_IMAGE_SIDE fit well within NUM_CTX.
|
|
32
|
+
MAX_INLINE_IMAGES = 8
|
|
33
|
+
CACHE_DIR = ".llm-cache"
|
|
34
|
+
|
|
35
|
+
DESCRIBE_PROMPT = """\
|
|
36
|
+
This image is from a recorded tech talk. Transcribe all text on it exactly, keeping its structure
|
|
37
|
+
(headings, bullets, code blocks). Then describe any diagram, chart or picture in one or two
|
|
38
|
+
sentences. If it shows no slide or screen (only the speaker or audience), answer just: NO SLIDE.
|
|
39
|
+
"""
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _encode(image: Path) -> bytes:
|
|
43
|
+
"""The image's bytes, downscaled to MAX_IMAGE_SIDE if it is larger."""
|
|
44
|
+
try:
|
|
45
|
+
with Image.open(image) as im:
|
|
46
|
+
if max(im.size) <= MAX_IMAGE_SIDE:
|
|
47
|
+
return image.read_bytes()
|
|
48
|
+
im = im.convert("RGB")
|
|
49
|
+
im.thumbnail((MAX_IMAGE_SIDE, MAX_IMAGE_SIDE))
|
|
50
|
+
buf = io.BytesIO()
|
|
51
|
+
im.save(buf, "JPEG", quality=90)
|
|
52
|
+
return buf.getvalue()
|
|
53
|
+
except OSError as e:
|
|
54
|
+
raise LLMError(f"cannot read image {image}: {e}") from None
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
class OllamaLLM:
|
|
58
|
+
"""Talks to a local Ollama server; sends text and images inline."""
|
|
59
|
+
|
|
60
|
+
def __init__(self, model: str | None = None, url: str = DEFAULT_URL, timeout: float = 3600):
|
|
61
|
+
self.model = model or DEFAULT_MODEL
|
|
62
|
+
self.url = url.rstrip("/")
|
|
63
|
+
self.timeout = timeout
|
|
64
|
+
# A local Ollama must not go through HTTP(S)_PROXY, which urllib applies even to localhost.
|
|
65
|
+
host = urllib.parse.urlsplit(self.url).hostname or ""
|
|
66
|
+
local = host in ("localhost", "::1") or host.startswith("127.")
|
|
67
|
+
self._opener = urllib.request.build_opener(urllib.request.ProxyHandler({}) if local else
|
|
68
|
+
urllib.request.ProxyHandler())
|
|
69
|
+
self.name = f"Ollama ({self.model})"
|
|
70
|
+
|
|
71
|
+
def ask(self, prompt: str, files: Sequence[Path] = ()) -> str:
|
|
72
|
+
files = [Path(f).resolve() for f in files]
|
|
73
|
+
root = common_dir(files)
|
|
74
|
+
images = [f for f in files if is_image(f)]
|
|
75
|
+
parts = [prompt]
|
|
76
|
+
for f in files:
|
|
77
|
+
if not is_image(f):
|
|
78
|
+
parts.append(f"\n\n--- File {f.relative_to(root)} ---\n{f.read_text()}")
|
|
79
|
+
if len(images) <= MAX_INLINE_IMAGES:
|
|
80
|
+
if images:
|
|
81
|
+
names = ", ".join(str(f.relative_to(root)) for f in images)
|
|
82
|
+
parts.append(f"\n\nAttached images, in order: {names}")
|
|
83
|
+
return self._chat("".join(parts), images)
|
|
84
|
+
cache = root / CACHE_DIR
|
|
85
|
+
for n, image in enumerate(images, 1):
|
|
86
|
+
log(f" Describing image {n}/{len(images)} with {self.name}")
|
|
87
|
+
parts.append(f"\n\n--- Image {image.relative_to(root)} (described) ---\n{self._describe(image, cache)}")
|
|
88
|
+
return self._chat("".join(parts), [])
|
|
89
|
+
|
|
90
|
+
def _describe(self, image: Path, cache: Path) -> str:
|
|
91
|
+
key = hashlib.sha256(self.model.encode() + DESCRIBE_PROMPT.encode() + str(MAX_IMAGE_SIDE).encode()
|
|
92
|
+
+ image.read_bytes()).hexdigest()
|
|
93
|
+
cached = cache / f"{key}.txt"
|
|
94
|
+
if cached.exists():
|
|
95
|
+
return cached.read_text()
|
|
96
|
+
text = self._chat(DESCRIBE_PROMPT, [image], MAX_DESCRIPTION_TOKENS, DESCRIBE_NUM_CTX)
|
|
97
|
+
cache.mkdir(parents=True, exist_ok=True)
|
|
98
|
+
cached.write_text(text)
|
|
99
|
+
return text
|
|
100
|
+
|
|
101
|
+
def _chat(self, content: str, images: Sequence[Path], max_tokens: int = MAX_ANSWER_TOKENS,
|
|
102
|
+
num_ctx: int = NUM_CTX) -> str:
|
|
103
|
+
message = {"role": "user", "content": content}
|
|
104
|
+
if images:
|
|
105
|
+
message["images"] = [base64.b64encode(_encode(f)).decode() for f in images]
|
|
106
|
+
body = json.dumps({"model": self.model, "messages": [message], "stream": False,
|
|
107
|
+
"options": {"num_ctx": num_ctx, "num_predict": max_tokens}}).encode()
|
|
108
|
+
req = urllib.request.Request(f"{self.url}/api/chat", body, {"Content-Type": "application/json"})
|
|
109
|
+
try:
|
|
110
|
+
with self._opener.open(req, timeout=self.timeout) as resp:
|
|
111
|
+
data = json.loads(resp.read())
|
|
112
|
+
except urllib.error.HTTPError as e:
|
|
113
|
+
raise LLMError(f"Ollama returned HTTP {e.code}: {e.read().decode(errors='replace')[:300]}") from None
|
|
114
|
+
except (urllib.error.URLError, TimeoutError, OSError) as e:
|
|
115
|
+
raise LLMError(f"cannot reach Ollama at {self.url}: {e}") from None
|
|
116
|
+
if data.get("done_reason") == "length":
|
|
117
|
+
raise LLMError(f"Ollama ({self.model}) hit the length limit before finishing its answer, "
|
|
118
|
+
"possibly stuck repeating itself; run again to retry")
|
|
119
|
+
text = re.sub(r"<think>.*?</think>", "", data.get("message", {}).get("content", ""), flags=re.DOTALL).strip()
|
|
120
|
+
if not text:
|
|
121
|
+
raise LLMError(f"Ollama ({self.model}) returned an empty answer")
|
|
122
|
+
return text
|