diff options
Diffstat (limited to 'deckit/modules')
| -rw-r--r-- | deckit/modules/assistant.py | 102 |
1 files changed, 100 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, ) |
