From e15acfcf73b108c040f7f5da8d8a2d9a399172f4 Mon Sep 17 00:00:00 2001 From: "Danilo M." Date: Tue, 17 Nov 2026 12:03:30 +0100 Subject: tools: video, transcribe local and online videos video.sh takes an absolute path or an http(s) URL. Uploader subtitles (it/en) when the URL has them, else whisper large-v3-turbo on the CPU, so the loaded model keeps the GPU. The transcript goes to $ASSISTANT_DIR/.md and opens; the model gets the path first and the start of the text. Over 30 minutes it asks first. The daemon now kills a running tool's process group on stop: a transcription can run for minutes. A video attachment reaches the model as its path only, for the tool. Co-Authored-By: Claude Opus 5.5 --- assistant.py | 70 ++++++++-- .../specs/2026-11-17-video-transcript-design.md | 23 ++-- examples/tools/test-video.sh | 134 ++++++++++++++++++ examples/tools/video.sh | 149 +++++++++++++++++++++ examples/tools/video.toml | 12 ++ 5 files changed, 372 insertions(+), 16 deletions(-) create mode 100755 examples/tools/test-video.sh create mode 100755 examples/tools/video.sh create mode 100644 examples/tools/video.toml diff --git a/assistant.py b/assistant.py index 69ed34a..0fe4c83 100644 --- a/assistant.py +++ b/assistant.py @@ -331,6 +331,8 @@ def kind_of(path): return "image" if mime == "application/pdf": return "pdf" + if (mime or "").startswith("video/"): # path only, for the video tool + return "video" if (mime or "").startswith("text/") or os.path.splitext(path)[1].lower() in CODE_SUFFIXES: return "text" if mime is None and looks_like_text(path): # no telling name: a script, a Makefile @@ -394,11 +396,11 @@ def attach(paths, budget): raise Refused(f"cannot read {name}") kind = kind_of(p) if kind == "other": - raise Refused(f"{name}: chat supports text, images and PDF") + raise Refused(f"{name}: chat supports text, images, PDF and video") if kind == "image" and os.path.getsize(p) > MAX_IMAGE: raise Refused(f"{name}: images over 20 MB are refused") loaded.append((p, name, kind)) - share = budget // max(1, sum(k != "image" for _, _, k in loaded)) + share = budget // max(1, sum(k not in ("image", "video") for _, _, k in loaded)) blocks, refs, chips = [], [], [] for p, name, kind in loaded: chip = {"name": name, "kind": kind, "truncated": False} @@ -410,6 +412,9 @@ def attach(paths, budget): refs.append({"type": "image_ref", "name": name, "path": p, "sha256": sha256(p)}) blocks.append(f"--- image: {name}{where} ---") continue + if kind == "video": + blocks.append(f"--- video: {name}{where} ---") + continue if kind == "pdf": pages = pdf_pages(p) chip["pages"] = len(pages) @@ -491,7 +496,8 @@ ctx = {"model": None, "max": 0, "used": 0} # token after its done. lock = threading.RLock() cur = {"id": None, "history": [], "turns": [], "pending": None, "model": None} -inflight = {"conn": None} # the HTTP connection the current reply streams over +inflight = {"conn": None, # the HTTP connection the current reply streams over + "tool": None} # the tool process it waits on writing = {"on": False} # a write in flight, which interrupt() also ends turn = 0 # bumped by every ask, stop, new and open: older replies are stale DB = None @@ -613,6 +619,13 @@ def interrupt(): # waits for an outcome, so it gets one. emit({"type": "error", "message": "stopped", "turn": True}) emit({"type": "state", "state": "idle"}) + # A tool runs in its own process group: killing the group takes its + # children too (whisper under video.sh), not just the script. + if inflight["tool"] is not None: + try: + os.killpg(inflight["tool"].pid, signal.SIGKILL) + except ProcessLookupError: + pass conn = inflight["conn"] if conn is not None and conn.sock is not None: try: @@ -741,7 +754,7 @@ def context_size(model): return ctx["max"] -def run_tool(tools, name, arguments, d=TOOLS_DIR): +def run_tool(tools, name, arguments, d=TOOLS_DIR, mine=None): # Whatever goes wrong becomes the tool's answer, so the model can say it # could not find out; a tool never takes the assistant down. t = tools.get(name) @@ -767,12 +780,23 @@ def run_tool(tools, name, arguments, d=TOOLS_DIR): env=env, start_new_session=True) except OSError as e: return f"error: cannot run {argv[0]}: {e.strerror}" + # mine is the reply's turn: a stop kills the process group (interrupt). + if mine is not None: + with lock: + if turn != mine: + os.killpg(p.pid, signal.SIGKILL) + inflight["tool"] = p try: out, err = p.communicate(timeout=t.get("timeout", 10)) except subprocess.TimeoutExpired: os.killpg(p.pid, signal.SIGKILL) p.communicate() return "error: timed out" + finally: + if mine is not None: + with lock: + if inflight["tool"] is p: + inflight["tool"] = None if p.returncode: last = err.strip().splitlines()[-1:] return ("error: " + (last[0] if last else f"exit status {p.returncode}"))[:2000] @@ -1237,7 +1261,7 @@ def answer(mine, text, files=(), chosen=None): sent = wire(msgs, images) said, used, rounds = "", [], [] # A stop shuts this reply's connection (interrupt), so llama-server's slot - # frees even mid prompt pass. ponytail: a running tool still runs out. + # frees even mid prompt pass, and kills a running tool. for rnd in range(CFG["tool_rounds"] + 1): calls, content = {}, "" # The last round offers no tools, which forces an answer. @@ -1257,13 +1281,12 @@ def answer(mine, text, files=(), chosen=None): for c in calls.values()]} msgs.append(call) sent.append(call) - # ponytail: a stop does not kill a running tool, its result is dropped for c in calls.values(): if not say(mine, "tool", c["name"]): log("interrupted") return used.append(c["name"]) - result = run_tool(offered, c["name"], c["arguments"]) + result = run_tool(offered, c["name"], c["arguments"], mine=mine) log(f"tool {c['name']}({c['arguments']}): {result[:120]!r}") msgs.append({"role": "tool", "tool_call_id": c["id"], "content": result}) sent.append(msgs[-1]) @@ -1560,6 +1583,13 @@ def test(): with open(os.path.join(fd, "long"), "wb") as f: # a character cut by the window f.write(b"a" * 4095 + "\u00e8 tail".encode()) assert kind_of(os.path.join(fd, "long")) == "text" + vid = os.path.join(fd, "clip.mkv") + open(vid, "wb").close() + assert kind_of(vid) == "video" + blocks, refs, chips = attach([vid, code], 100) + assert blocks[0] == f"--- video: clip.mkv ({vid}) ---" and refs == [] + assert chips[0] == {"name": "clip.mkv", "kind": "video", "truncated": False} + assert blocks[1] == attach([code], 100)[0][0] # the video took no share blocks, refs, chips = attach([code, pdf, png], 100000) assert blocks[0].startswith(f"--- file: a.py ({code}) ---\nprint('hi')") and "(truncated)" not in blocks[0] assert "[page 1]\nhello pdf" in blocks[1] and "[page 2]" in blocks[1] @@ -1597,7 +1627,7 @@ def test(): small = attach([code], 24)[0][0] # the share is the cut: two lines assert "(truncated)" in small and small.count("print") == 2 for bad, why in ((["a.py"], "cannot read a.py"), ([fd + "/nope.txt"], "cannot read nope.txt"), - ([fd], "cannot read"), ([other], "x.bin: chat supports text, images and PDF"), + ([fd], "cannot read"), ([other], "x.bin: chat supports text, images, PDF and video"), ([code] * 9, "at most 8 files")): try: attach(bad, 1000) @@ -1813,6 +1843,30 @@ def test(): time.sleep(0.05) assert script["hung_up"] and script["hung_up"] - stopped < 1, script["hung_up"] script["hold"] = False + # Stop during a tool: its whole process group dies, child included. + pidf = os.path.join(d, "tool.pid") + TOOLS["slow"] = {"description": "d", "timeout": 60, "command": [ + "sh", "-c", f"sleep 30 & echo $! > {pidf}; wait"]} + script["replies"] = [[{"tool_calls": [{"index": 0, "id": "s1", "function": { + "name": "slow", "arguments": "{}"}}]}]] + send(type="ask", text="slow tool") + until("tool") + for _ in range(40): + if os.path.exists(pidf) and os.path.getsize(pidf): + break + time.sleep(0.05) + child = int(open(pidf).read()) + send(type="stop") + assert until("done")[-1].get("stopped") is True + for _ in range(20): + try: + os.kill(child, 0) + except ProcessLookupError: + break + time.sleep(0.05) + else: + assert False, "tool child still running after stop" + del TOOLS["slow"] # Stop mid-stream: no token after done, nothing saved. script["replies"] = [[{"content": f"w{i} "} for i in range(50)]] script["delay"] = 0.02 diff --git a/docs/superpowers/specs/2026-11-17-video-transcript-design.md b/docs/superpowers/specs/2026-11-17-video-transcript-design.md index ad1d268..6422200 100644 --- a/docs/superpowers/specs/2026-11-17-video-transcript-design.md +++ b/docs/superpowers/specs/2026-11-17-video-transcript-design.md @@ -1,6 +1,6 @@ # Video transcript tool: design -Date: 2026-11-17. Status: proposed. +Date: 2026-11-17. Status: implemented, live check pending. ## Goal @@ -151,13 +151,20 @@ image: the model gets the path for the tool, nothing else. Chip kind ### Check -`video.sh --test`, like `test-clone.sh`: a generated 5 s clip (`ffmpeg --f lavfi` sine plus `flite` or a stored speech sample from outside the -repo) as mp4 and mkv; a source with no audio; a relative path; the -30-minute refusal on a fake duration; slug collisions; the output -starting with the path line. URL steps against a `file://` source are -not possible with yt-dlp's generic extractor rules, so they are covered -by the live check only. +`test-video.sh`, like `test-clone.sh`: an espeak-ng sentence in an +mp4 (Opus: this ffmpeg has no AAC encoder) through the real whisper, +twice for the slug collision; an mkv with no audio; a relative and a +missing path; a real 31-minute silent webm for the refusal; a stale +temp folder removed, a fresh one kept. yt-dlp is a stub driven by +environment variables: uploader subtitles in it and en (the spoken +language picked, header, NOTE, tags and repeated cues stripped), no +subtitles (audio through whisper), an unavailable video, an unknown +length, a long one, and 400 cues whose output stays under the cap +with the path line first. + +whisper drops the last word of a clip that ends on it, even with 2 s of +silence after (espeak's "tool." in the test); real videos rarely end +mid-sentence. ### Live check diff --git a/examples/tools/test-video.sh b/examples/tools/test-video.sh new file mode 100755 index 0000000..74f7d72 --- /dev/null +++ b/examples/tools/test-video.sh @@ -0,0 +1,134 @@ +#!/bin/bash +# desktop-assistant tool check: video.sh. +# Copyright (C) 2026 Danilo M. +# +# This program is free software; you can redistribute it and/or modify it +# under the terms of the GNU General Public License version 2 as published +# by the Free Software Foundation. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General +# Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program; if not, write to the Free Software Foundation, Inc., +# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +# +# test-video.sh: local clips made with espeak-ng and ffmpeg go through the +# real whisper (CPU, ~10 s each); yt-dlp is a stub driven by STUB_* variables, +# so URL cases never touch the network. Output and temp folders are +# throwaway. Prints "ok" or one FAIL line per broken case. + +set -u +here=$(cd "$(dirname "$0")" && pwd) +tmp=$(mktemp -d) +trap 'rm -rf "$tmp"' EXIT +export ASSISTANT_DIR=$tmp/out XDG_RUNTIME_DIR=$tmp/run VIDEO_NO_OPEN=1 +mkdir -p "$tmp/bin" "$XDG_RUNTIME_DIR" + +cat > "$tmp/bin/yt-dlp" <<'EOF' +#!/bin/bash +[ -n "${STUB_FAIL:-}" ] && { echo "ERROR: $STUB_FAIL" >&2; exit 1; } +out=""; prev="" +for a in "$@"; do [ "$prev" = -o ] && out=$a; prev=$a; done +case " $* " in + *" --print "*) printf '%s\n' "$STUB_META" ;; + *" --write-subs "*) for v in ${STUB_VTT:-}; do cp "$v" "$(dirname "$out")/s.$(basename "$v")"; done ;; + *" -f "*) cp "$STUB_AUDIO" "$(dirname "$out")/a.wav" ;; +esac +EOF +chmod +x "$tmp/bin/yt-dlp" +export PATH=$tmp/bin:$PATH + +fail=0 +check() { [ "$2" = "$3" ] || { echo "FAIL $1: got '$2', want '$3'"; fail=1; }; } +contains() { case "$2" in *"$3"*) ;; *) echo "FAIL $1: '${2:0:300}' lacks '$3'"; fail=1 ;; esac; } +v() { "$here/video.sh" "$@" 2>&1; } + +espeak-ng -v en -w "$tmp/speech.wav" "Hello. This is a short test of the video transcription tool." +ffmpeg -loglevel error -f lavfi -i color=black:s=160x120:d=6 -i "$tmp/speech.wav" -af apad \ + -shortest -c:a libopus "$tmp/Hello Clip.mp4" # padded: whisper drops a word cut at the end +ffmpeg -loglevel error -f lavfi -i color=black:s=160x120:d=2 "$tmp/silent.mkv" +ffmpeg -loglevel error -f lavfi -i anullsrc=r=8000:cl=mono -t 1860 -c:a libopus "$tmp/long.webm" + +# Stale temp folders from killed runs go; a fresh one stays. +mkdir "$XDG_RUNTIME_DIR/video-old" "$XDG_RUNTIME_DIR/video-new" +touch -d '2 days ago' "$XDG_RUNTIME_DIR/video-old" + +# Local video: whisper, the path line first, the Markdown file. +out=$(v "$tmp/Hello Clip.mp4") +check "local path line" "$(head -1 <<<"$out" | cut -d' ' -f1-2)" "transcript: $ASSISTANT_DIR/hello-clip.md" +contains "local how" "$out" "whisper large-v3-turbo" +contains "local text" "$(tr 'A-Z' 'a-z' <<<"$out")" "short test of the video" +md=$(cat "$ASSISTANT_DIR/hello-clip.md" 2>/dev/null) +contains "md title" "$md" "# Hello Clip" +contains "md source" "$md" "Source: $tmp/Hello Clip.mp4" +contains "md duration" "$md" "Duration: 0:0" +check "stale tmp removed" "$(test -e "$XDG_RUNTIME_DIR/video-old" && echo yes || echo no)" no +check "fresh tmp kept" "$(test -e "$XDG_RUNTIME_DIR/video-new" && echo yes || echo no)" yes +check "own tmp removed" "$(command ls -d "$XDG_RUNTIME_DIR"/video-* | wc -l)" 1 + +# Same title again: a free name, nothing overwritten. +out=$(v "$tmp/Hello Clip.mp4") +contains "collision" "$(head -1 <<<"$out")" "$ASSISTANT_DIR/hello-clip-2.md " + +# Refusals: one error line, exit 1, nothing written. +before=$(command ls "$ASSISTANT_DIR" | wc -l) +out=$(v "$tmp/silent.mkv"); check "no audio rc" $? 1 +contains "no audio" "$out" "error: no audio in silent.mkv" +out=$(v "relative.mp4"); check "relative rc" $? 1 +contains "relative" "$out" "error: not an absolute path or an http(s) URL" +out=$(v "$tmp/missing.mp4"); contains "missing" "$out" "error: cannot read" +out=$(v "$tmp/long.webm"); check "long rc" $? 0 +contains "long" "$out" "long: long, 31:00. Ask the user" +check "nothing written" "$(command ls "$ASSISTANT_DIR" | wc -l)" "$before" + +# URL with uploader subtitles in both languages: the spoken one, cleaned. +cat > "$tmp/it.vtt" <<'EOF' +WEBVTT +Kind: captions + +NOTE a comment +that spans lines + +1 +00:00:00.000 --> 00:00:02.000 +Ciao a tutti & benvenuti + +2 +00:00:02.000 --> 00:00:04.000 align:start +Ciao a tutti & benvenuti + +00:00:04.000 --> 00:00:06.000 +Oggi parliamo di Slackware. +EOF +printf 'WEBVTT\n\n00:00:00.000 --> 00:00:02.000\nHello everyone\n' > "$tmp/en.vtt" +out=$(STUB_META=$'125\tit\tUn Titolo: prova!' STUB_VTT="$tmp/en.vtt $tmp/it.vtt" v "https://example.org/v/1") +contains "subs path" "$(head -1 <<<"$out")" "$ASSISTANT_DIR/un-titolo-prova.md (9 words, 2:05, uploader subtitles)" +md=$(cat "$ASSISTANT_DIR/un-titolo-prova.md" 2>/dev/null) +contains "subs text" "$md" $'Ciao a tutti & benvenuti\n\nOggi parliamo di Slackware.' +check "subs dedup" "$(grep -c 'Ciao a tutti' <<<"$md")" 1 +check "subs no english" "$(grep -c 'Hello everyone' <<<"$md")" 0 +check "subs no note" "$(grep -c 'comment\|spans' <<<"$md")" 0 + +# URL without subtitles: the audio download goes through whisper. +out=$(STUB_META=$'5\tNA\tNo Subs' STUB_AUDIO=$tmp/speech.wav v "https://example.org/v/2") +contains "audio path" "$(head -1 <<<"$out")" "$ASSISTANT_DIR/no-subs.md" +contains "audio how" "$out" "whisper large-v3-turbo" + +# URL failures. +out=$(STUB_FAIL="Video unavailable" v "https://example.org/v/3"); check "fail rc" $? 1 +check "fail message" "$out" "error: Video unavailable" +out=$(STUB_META=$'NA\tNA\tLive' v "https://example.org/v/4") +contains "live" "$out" "error: unknown length" +out=$(STUB_META=$'2000\ten\tLong one' v "https://example.org/v/5") +contains "long url" "$out" "long: Long one, 33:20." + +# A long transcript: the path line survives, the output fits the cap. +{ printf 'WEBVTT\n\n'; for i in $(seq 400); do printf '00:00:%02d.000 --> 00:00:%02d.500\nline number %d of the talk\n\n' $((i % 60)) $((i % 60)) "$i"; done; } > "$tmp/big.vtt" +out=$(STUB_META=$'600\ten\tBig Talk' STUB_VTT="$tmp/big.vtt" v "https://example.org/v/6") +contains "big path" "$(head -1 <<<"$out")" "big-talk.md (2400 words" +check "big under cap" "$(( ${#out} < 2000 ))" 1 + +[ $fail = 0 ] && echo ok diff --git a/examples/tools/video.sh b/examples/tools/video.sh new file mode 100755 index 0000000..842a02f --- /dev/null +++ b/examples/tools/video.sh @@ -0,0 +1,149 @@ +#!/bin/bash +# desktop-assistant tool: transcribe the speech in a local or online video. +# Copyright (C) 2026 Danilo M. +# +# This program is free software; you can redistribute it and/or modify it +# under the terms of the GNU General Public License version 2 as published +# by the Free Software Foundation. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General +# Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program; if not, write to the Free Software Foundation, Inc., +# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +# +# video.sh [long]: is an absolute path or an http(s) URL. +# Uploader subtitles (it/en) when a URL has them, else whisper large-v3-turbo +# on the CPU (no VRAM: the loaded model keeps the GPU). Writes +# $ASSISTANT_DIR/.md, opens it, prints its path and the start of the +# text. Over 30 minutes it only reports the length, unless is 1. +# Check: test-video.sh. + +set -uo pipefail + +MODEL=${WHISPER_MODEL:-/data/voice-models/whisper/ggml-large-v3-turbo-q5_0.bin} +LONG_S=1800 +PREVIEW=1500 + +die() { echo "error: $*" >&2; exit 1; } + +hms() { # seconds -> m:ss or h:mm:ss + local s=${1%.*} + if (( s >= 3600 )); then printf '%d:%02d:%02d' $((s / 3600)) $((s % 3600 / 60)) $((s % 60)) + else printf '%d:%02d' $((s / 60)) $((s % 60)); fi +} + +# Cue text of a WebVTT file: no header, cue ids, timings, NOTE/STYLE blocks +# or tags, and a line repeated by the next cue only once. +vtt_text() { + awk ' + /^WEBVTT/ { skip = 1; next } # header lines (Kind:, Language:) up to a blank + /^(NOTE|STYLE|REGION)/ { skip = 1; next } + /^[[:space:]]*$/ { skip = 0; next } + skip { next } + /-->/ { next } + /^[0-9]+$/ { next } + { gsub(/<[^>]*>/, ""); gsub(/&/, "\\&"); gsub(/</, "<"); gsub(/>/, ">") + gsub(/ /, " "); sub(/^[[:space:]]+/, ""); sub(/[[:space:]]+$/, "") + if ($0 != "" && $0 != last) print; last = $0 } + ' "$1" +} + +slug() { + local s + s=$(printf '%s' "$1" | iconv -f utf-8 -t ascii//TRANSLIT 2>/dev/null | tr 'A-Z' 'a-z' \ + | tr -c 'a-z0-9' '-' | tr -s '-') + s=${s#-}; s=${s:0:60}; s=${s%-} + printf '%s' "${s:-video}" +} + +[[ $# -ge 1 && -n $1 ]] || die "no video given" +src=$1 long=${2:-} +[[ -n ${ASSISTANT_DIR:-} ]] || die "ASSISTANT_DIR is not set" +run=${XDG_RUNTIME_DIR:-/tmp} + +# A stop kills this script's process group with SIGKILL, so the trap below +# never runs then: clear what earlier killed runs left behind. +find "$run" -maxdepth 1 -name 'video-*' -type d -mmin +1440 -exec rm -rf {} + 2>/dev/null +tmp=$(mktemp -d "$run/video-XXXXXX") || die "cannot make a temp folder" +trap 'rm -rf "$tmp"' EXIT + +if [[ $src =~ ^https?:// ]]; then + # Separated by a tab: a title may hold any other character. + meta=$(yt-dlp --no-playlist --no-warnings --print '%(duration)s %(language)s %(title)s' \ + -- "$src" 2>"$tmp/err" | head -1) \ + || die "$(tail -1 "$tmp/err" | sed 's/^ERROR: //')" + IFS=$'\t' read -r dur lang title <<<"$meta" + [[ $dur =~ ^[0-9.]+$ ]] || die "unknown length: a live stream, or not a video" +else + [[ $src == /* ]] || die "not an absolute path or an http(s) URL: $src" + [[ -f $src && -r $src ]] || die "cannot read $src" + dur=$(ffprobe -v error -show_entries format=duration -of csv=p=0 "$src") + [[ $dur =~ ^[0-9.]+$ ]] || die "not a video ffmpeg can read: ${src##*/}" + [[ -n $(ffprobe -v error -select_streams a -show_entries stream=index -of csv=p=0 "$src") ]] \ + || die "no audio in ${src##*/}" + title=${src##*/}; title=${title%.*}; lang="" +fi + +if (( ${dur%.*} > LONG_S )) && [[ $long != 1 ]]; then + echo "long: $title, $(hms "$dur"). Ask the user before transcribing: it takes about a minute per 10 minutes of video." + exit 0 +fi + +text="" how="" +if [[ $src =~ ^https?:// ]]; then + # Only subtitles the uploader wrote: auto-generated ones repeat every + # line in rolling cues, and whisper turbo does better. + yt-dlp --no-playlist --no-warnings --skip-download --write-subs --sub-langs 'it.*,en.*' \ + --sub-format vtt -o "$tmp/s.%(ext)s" -- "$src" >/dev/null 2>&1 + subs=("$tmp"/s.*.vtt) + if [[ -f ${subs[0]} ]]; then + pick=${subs[0]} + for s in "${subs[@]}"; do # the spoken language's, when the site says + [[ -n $lang && ${s##*/s.} == "$lang"* ]] && pick=$s + done + text=$(vtt_text "$pick") + [[ -n $text ]] && how="uploader subtitles" + fi + if [[ -z $text ]]; then + yt-dlp --no-playlist --no-warnings -f 'bestaudio/best' -o "$tmp/a.%(ext)s" -- "$src" \ + >/dev/null 2>"$tmp/err" || die "$(tail -1 "$tmp/err" | sed 's/^ERROR: //')" + audio=$(find "$tmp" -maxdepth 1 -name 'a.*' | head -1) + [[ -n $audio ]] || die "the download gave no file" + fi +else + audio=$src +fi + +if [[ -z $text ]]; then + [[ -r $MODEL ]] || die "whisper model missing: $MODEL" + # whisper reads any container through ffmpeg. -ng: CPU, 8 threads beat 16. + whisper-cli -m "$MODEL" -ng -t 8 -l auto -np -otxt -of "$tmp/t" -f "$audio" \ + >/dev/null 2>"$tmp/err" || die "whisper: $(tail -1 "$tmp/err")" + text=$(sed 's/^[[:space:]]*//; /^$/d' "$tmp/t.txt") + [[ -n $text ]] || die "no speech found" + how="whisper large-v3-turbo" +fi + +mkdir -p "$ASSISTANT_DIR" || die "cannot create $ASSISTANT_DIR" +base=$(slug "$title") +out="$ASSISTANT_DIR/$base.md" n=2 +while [[ -e $out ]]; do out="$ASSISTANT_DIR/$base-$n.md"; n=$((n + 1)); done +{ + printf '# %s\n\nSource: %s\nDuration: %s. Transcribed %s with %s.\n\n' \ + "$title" "$src" "$(hms "$dur")" "$(date +%F)" "$how" + # One paragraph per segment or cue line. + printf '%s\n' "$text" | sed 's/$/\n/' +} >"$tmp/out.md" || die "cannot write the transcript" +# Whole or not at all: a stop before this line leaves no file. +mv "$tmp/out.md" "$out" || die "cannot write $out" + +[[ -n ${VIDEO_NO_OPEN:-} ]] || setsid -f xdg-open "$out" >/dev/null 2>&1 +words=$(wc -w <<<"$text") +# The path first: the daemon cuts tool output at 2000 characters. +echo "transcript: $out ($words words, $(hms "$dur"), $how)" +echo "start, not the whole text; to summarize or question it, the user attaches the file:" +printf '%s\n' "${text:0:PREVIEW}" diff --git a/examples/tools/video.toml b/examples/tools/video.toml new file mode 100644 index 0000000..450669d --- /dev/null +++ b/examples/tools/video.toml @@ -0,0 +1,12 @@ +description = "Transcribe the speech in a video, a local file or a public URL (YouTube, social media, web pages). Writes the full transcript to a Markdown file and opens it. Returns the file's path and the start of the text only: you have NOT read the whole transcript, so to summarize or answer questions about it, ask the user to attach the file. Videos over 30 minutes are refused until the user agrees: tell them the length and that it takes a few minutes, then call again with long=1." +command = ["video.sh", "{source}", "{long}"] +cloud = ["hetzner"] +timeout = 1800 + +[params.source] +type = "string" +description = "Absolute path of a local video, from its video block or the user's words, or an http(s) URL." + +[params.long] +type = "string" +description = "1 only after the user agreed to transcribe a video over 30 minutes; empty otherwise." -- cgit v1.2.3