aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--deckit/modules/assistant.py102
-rw-r--r--tests/test_assistant.py87
2 files changed, 187 insertions, 2 deletions
diff --git a/deckit/modules/assistant.py b/deckit/modules/assistant.py
index 3069876..b608df2 100644
--- a/deckit/modules/assistant.py
+++ b/deckit/modules/assistant.py
@@ -106,6 +106,18 @@ def hears(models, wanted):
return inputs is None or "audio" in inputs
+def qarma_args(item, kinds):
+ """The file dialog for a preset or op: filtered to its kinds' suffixes,
+ several files unless the op takes one."""
+ args = ["qarma", "--file-selection", f"--title={item['label']}", "--separator=\n"]
+ if item.get("max") != 1:
+ args.append("--multiple")
+ exts = sorted({e for k in item.get("kinds", []) for e in kinds.get(k, [])})
+ if exts:
+ args.append(f"--file-filter={item['label']} | " + " ".join("*" + e for e in exts))
+ return args
+
+
def make(cfg: dict) -> Module:
shell = os.path.expanduser(cfg.get("assistant", {}).get("shell", ""))
lock = threading.Lock() # guards st
@@ -199,6 +211,92 @@ def make(cfg: dict) -> Module:
os.replace(tmp, VOICE)
send(with_model({"type": "ask", "text": "", "audio": str(VOICE)}))
+ def load_catalog():
+ try:
+ out = subprocess.run(["qs", "-p", shell, "ipc", "call", "assistant", "catalog"],
+ capture_output=True, text=True, timeout=5, check=True).stdout
+ cat, err = json.loads(out), ""
+ except (OSError, subprocess.SubprocessError, ValueError) as e:
+ cat, err = None, f"no presets from keystone: {e}"
+ with lock:
+ st.update(catalog=cat, catalogError=err)
+ return cat
+
+ def choose(cat, item):
+ """Paths picked in qarma on the PC; [] when the dialog is cancelled."""
+ p = subprocess.Popen(qarma_args(item, cat.get("kinds", {})),
+ stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True)
+ conn["qarma"] = p
+ out, _ = p.communicate()
+ conn["qarma"] = None
+ return [x for x in out.split("\n") if x.startswith("/")] if p.returncode == 0 else []
+
+ def set_op(**kw):
+ with lock:
+ st["op"].update(**kw)
+
+ def run_pick(cat, item, kind):
+ try:
+ paths = choose(cat, item)
+ except (OSError, subprocess.SubprocessError) as e:
+ with lock:
+ st.update(picking=None, notice=f"qarma: {e}")
+ return
+ with lock:
+ st["picking"] = None
+ if not paths:
+ return
+ try:
+ if kind == "preset":
+ send(with_model({"type": "ask", "text": item["prompt"], "files": paths}))
+ return
+ with lock:
+ st["op"] = {"label": item["label"], "running": True, "ok": False, "out": [], "error": ""}
+ if len(paths) < item.get("min", 1):
+ set_op(running=False, error=f"{item['label']} needs at least {item['min']} files")
+ elif item["op"] == "md":
+ # As the canvas: the daemon writes it; `written` ends the op.
+ send({"type": "write", "files": paths[:1], "prompt": cat["mdPrompt"],
+ "dir": cat["outDir"], "name": Path(paths[0]).stem + ".md"})
+ else:
+ try:
+ out = subprocess.run([cat["fileops"], item["op"], cat["outDir"], *paths],
+ capture_output=True, text=True).stdout
+ r = json.loads(out.strip().splitlines()[-1])
+ except (OSError, ValueError, IndexError):
+ r = {"ok": False, "error": "fileops gave no answer"}
+ set_op(running=False, ok=bool(r.get("ok")), out=r.get("out") or [], error=r.get("error", ""))
+ except ModuleError as e:
+ with lock:
+ if st["op"] and st["op"]["running"]:
+ st["op"].update(running=False, error=str(e))
+ else:
+ st["notice"] = str(e)
+
+ def pick(body):
+ cat = load_catalog()
+ if not cat:
+ raise ModuleError(st["catalogError"])
+ if isinstance(body.get("preset"), str):
+ kind, items, label = "preset", cat.get("presets", []), body["preset"]
+ elif isinstance(body.get("op"), str):
+ kind, items, label = "op", cat.get("ops", []), body["op"]
+ else:
+ raise ModuleError("preset or op required")
+ item = next((i for i in items if i.get("label") == label), None)
+ if item is None:
+ raise ModuleError(f"unknown {kind}: {label}")
+ with lock:
+ if st["picking"] or (st["op"] or {}).get("running"):
+ raise ModuleError("busy")
+ st.update(picking=label, op=None)
+ threading.Thread(target=run_pick, args=(cat, item, kind), daemon=True).start()
+
+ def cancel(body):
+ p = conn["qarma"]
+ if p is not None:
+ p.terminate()
+
def close():
stop.set()
s = conn["sock"]
@@ -213,8 +311,8 @@ def make(cfg: dict) -> Module:
actions={"ask": ask, "stop": lambda b: send({"type": "stop"}),
"new": lambda b: send({"type": "new"}),
"models": lambda b: send({"type": "models"}),
- "model": model, "voice": voice},
+ "model": model, "voice": voice, "pick": pick, "cancel": cancel},
uploads={"voice": ("audio/wav", MAX_VOICE)},
- start=lambda: threading.Thread(target=loop, daemon=True).start(),
+ start=lambda: [threading.Thread(target=f, daemon=True).start() for f in (loop, load_catalog)],
stop=close,
)
diff --git a/tests/test_assistant.py b/tests/test_assistant.py
index b384a6c..a3fb2b7 100644
--- a/tests/test_assistant.py
+++ b/tests/test_assistant.py
@@ -16,6 +16,7 @@
import json
import os
import socket
+import stat
import sys
import tempfile
import threading
@@ -153,6 +154,8 @@ class Client(unittest.TestCase):
self.m = a.make({"assistant": {"shell": "/nonexistent"}})
self.m.start()
self.assertTrue(until(lambda: self.m.state()["connected"]))
+ # The daemon has registered the connection (and said hello) once it hears us.
+ self.assertTrue(until(lambda: {"type": "models"} in self.d.got))
def tearDown(self):
self.m.stop()
@@ -203,5 +206,89 @@ class Client(unittest.TestCase):
self.assertEqual(self.m.state()["pending"]["reply"], "a")
+CATALOG = {"presets": [{"label": "Translate", "icon": "", "kinds": ["pdf", "text"],
+ "prompt": "Translate this into English."}],
+ "ops": [{"label": "To .md", "icon": "", "op": "md", "kinds": ["pdf"], "max": 1},
+ {"label": "Merge", "icon": "", "op": "pdf-merge", "kinds": ["pdf"], "min": 2},
+ {"label": ".zip", "icon": "", "op": "zip", "kinds": ["any"]}],
+ "kinds": {"pdf": [".pdf"], "text": [".md", ".txt"]},
+ "fileops": "", "outDir": "/tmp/out", "mdPrompt": "As Markdown.", "preferred": ""}
+
+
+class QarmaArgs(unittest.TestCase):
+ def test_filter_and_multiple(self):
+ args = a.qarma_args(CATALOG["presets"][0], CATALOG["kinds"])
+ self.assertIn("--multiple", args)
+ self.assertIn("--file-filter=Translate | *.md *.pdf *.txt", args)
+
+ def test_single_file_op_and_any_kind(self):
+ self.assertNotIn("--multiple", a.qarma_args(CATALOG["ops"][0], CATALOG["kinds"]))
+ self.assertFalse([x for x in a.qarma_args(CATALOG["ops"][2], CATALOG["kinds"])
+ if x.startswith("--file-filter")])
+
+
+def stub(dirpath, name, body):
+ p = Path(dirpath) / name
+ p.write_text("#!/bin/sh\n" + body + "\n")
+ p.chmod(p.stat().st_mode | stat.S_IXUSR)
+ return p
+
+
+class Pick(Client):
+ def setUp(self):
+ self.bin = tempfile.mkdtemp(dir="/tmp")
+ cat = dict(CATALOG, fileops=str(Path(self.bin) / "fileops"))
+ stub(self.bin, "qs", "cat <<'EOF'\n" + json.dumps(cat) + "\nEOF")
+ self.path = os.environ["PATH"]
+ os.environ["PATH"] = self.bin + ":" + self.path
+ super().setUp()
+
+ def tearDown(self):
+ os.environ["PATH"] = self.path
+ super().tearDown()
+
+ def test_preset_asks_with_the_picked_files(self):
+ stub(self.bin, "qarma", "printf '/docs/a.pdf'")
+ self.m.actions["pick"]({"preset": "Translate"})
+ self.assertTrue(until(lambda: {"type": "ask", "text": "Translate this into English.",
+ "files": ["/docs/a.pdf"]} in self.d.got))
+ self.assertIsNone(self.m.state()["picking"])
+
+ def test_cancelled_dialog_does_nothing(self):
+ stub(self.bin, "qarma", "exit 1")
+ self.m.actions["pick"]({"preset": "Translate"})
+ self.assertTrue(until(lambda: self.m.state()["picking"] is None))
+ self.assertFalse([c for c in self.d.got if c["type"] == "ask"])
+
+ def test_op_runs_fileops(self):
+ stub(self.bin, "qarma", "printf '/v/a.pdf\\n/v/b.pdf'")
+ stub(self.bin, "fileops", 'echo \'{"ok": true, "out": ["/tmp/out/a+b.pdf"]}\'')
+ self.m.actions["pick"]({"op": "Merge"})
+ self.assertTrue(until(lambda: (self.m.state()["op"] or {}).get("ok")))
+ self.assertEqual(self.m.state()["op"]["out"], ["/tmp/out/a+b.pdf"])
+
+ def test_op_min_is_checked(self):
+ stub(self.bin, "qarma", "printf '/v/a.pdf'")
+ self.m.actions["pick"]({"op": "Merge"})
+ self.assertTrue(until(lambda: (self.m.state()["op"] or {}).get("error")))
+ self.assertIn("at least 2", self.m.state()["op"]["error"])
+
+ def test_md_goes_to_the_daemon(self):
+ stub(self.bin, "qarma", "printf '/docs/scan.pdf'")
+ self.m.actions["pick"]({"op": "To .md"})
+ self.assertTrue(until(lambda: {"type": "write", "files": ["/docs/scan.pdf"], "prompt": "As Markdown.",
+ "dir": "/tmp/out", "name": "scan.md"} in self.d.got))
+
+ def test_unknown_label_and_busy(self):
+ stub(self.bin, "qarma", "sleep 2")
+ with self.assertRaises(a.ModuleError):
+ self.m.actions["pick"]({"preset": "Nope"})
+ self.m.actions["pick"]({"preset": "Translate"})
+ with self.assertRaises(a.ModuleError):
+ self.m.actions["pick"]({"preset": "Translate"})
+ self.m.actions["cancel"]({})
+ self.assertTrue(until(lambda: self.m.state()["picking"] is None, 3))
+
+
if __name__ == "__main__":
unittest.main()