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 +++++++++++++++++++++++++++++++++++++++++++++++++++++------- 1 file changed, 62 insertions(+), 8 deletions(-) (limited to 'assistant.py') 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 -- cgit v1.2.3