diff --git a/changes/settings-first-run.md b/changes/settings-first-run.md new file mode 100644 index 00000000..c390a21d --- /dev/null +++ b/changes/settings-first-run.md @@ -0,0 +1,6 @@ +**少了 API Key 时,命令和 Studio 都用一句话说清去哪设、去哪拿、不用它还能怎么做** +- Why: 配音、对时间、出图、作曲缺 key 时,原来各说各的("set GEMINI_API_KEY (Google AI Studio → Get API key)"),只说了环境变量;Studio 里只看得到"配音结束时报了问题",人不知道片子在等什么、该去哪里补。 +- 缺 key 停下的命令(`bin/vh tts` 各家、`--align gemini`、`voices audition`、`pace --align gemini`、`music --provider lyria`、`image gen`)都说同一句:哪一家、哪个 key,在 Studio 的设置 → 服务里填上(或者设环境变量),去哪拿,不用它时这台电脑上还能怎么做。能怎么做看这台电脑:Apple Silicon 上是本地配音、本地对时间;Intel Mac 上是 macOS 自带的声音;Linux 上没有本地的,就直说;作曲哪里都能在本地做;出图装了 Codex 时可以走 ChatGPT 的订阅。这句由 `tools/keys.py` 写,记进这次运行的记录,代码是新的 `no_key`,还记下 key 拿来做什么(配音、对时间、作曲、出图)。 +- `bin/vh status` 和 Studio 的现状行在片子等 key 时说:"配音停下了:还没有 Gemini 的 API Key。在设置 → 服务里填上,再让 agent 接着做。"Studio 里那一行带一个按钮,点了直接到设置 → 服务。下面那句按 key 拿来做什么来说(配音的 key 说本地声音,对时间的 key 说本地对时间)。key 设上了(Studio 里或环境变量里)、后来同类的活做成了、或者后来别的命令失败了,这句就不说了。 +- `music --provider lyria` 的运行现在会记下结束,不再被当成中断。 +- 不花钱:检查在调用之前,什么都没调就停。 diff --git a/tools/activity.py b/tools/activity.py index 20fa34bf..3766ca4e 100644 --- a/tools/activity.py +++ b/tools/activity.py @@ -350,7 +350,7 @@ def event(project, kind, **fields): # ---------- reading ---------- -_STR = ("run", "cmd", "cwd", "summary", "unit", "parent", "file", "round", "level", "code", "kept", "project") +_STR = ("run", "cmd", "cwd", "summary", "unit", "parent", "file", "round", "level", "code", "kept", "project", "need") _INT = ("pid", "exit", "decisions") _NUM = ("duration", "done", "total", "pass", "passes") @@ -543,6 +543,8 @@ def runs(records, now=None, same_process=True): run["summary"] = r["summary"] elif ev == "note" and r.get("level") == "error": run["error"] = {"code": r.get("code") or "failed", "message": r.get("summary") or ""} + if r.get("code") == "no_key": # what the key was for (voice, timing, music, image) and its names (tools/keys.py) + run["error"].update(need=r.get("need"), keys=[k for k in r.get("keys") or [] if isinstance(k, str)] if isinstance(r.get("keys"), list) else []) elif ev == "note": if r.get("summary"): run["summary"] = r["summary"] diff --git a/tools/assets/image.py b/tools/assets/image.py index 3ba109da..72833c89 100644 --- a/tools/assets/image.py +++ b/tools/assets/image.py @@ -621,7 +621,7 @@ def cmd_gen(a): return 0 if a.provider == "gemini": if not a.offline and not keys.get("GEMINI_API_KEY"): - raise Usage("set GEMINI_API_KEY (Google AI Studio → Get API key), or save it in Studio's settings (Services)") + raise Usage(keys.stopping("GEMINI_API_KEY", "image")) if not plan["budget"]["ok"]: raise Failed(f"{plan['budget']['message']} (bin/vh image gen --dry-run shows the estimate)") if refs: diff --git a/tools/audio/lyria.py b/tools/audio/lyria.py index 7b679b48..9c097ef2 100644 --- a/tools/audio/lyria.py +++ b/tools/audio/lyria.py @@ -133,7 +133,7 @@ def cmd_gen(a): say(" nothing called (--dry-run)") return 0 if not a.offline and not keys.get("GEMINI_API_KEY"): - raise Usage("set GEMINI_API_KEY (Google AI Studio → Get API key), or save it in Studio's settings (Services)") + raise Usage(keys.stopping("GEMINI_API_KEY", "music")) if not chk["ok"]: raise Failed(f"{chk['message']} (--dry-run shows the price)") folder = project / GENMUSIC / cid @@ -255,7 +255,8 @@ def main(argv): if __name__ == "__main__": + import activity # bin/vh exec's into this (cmd_music): this process writes the run's end, or the run reads as cut off try: - sys.exit(main(sys.argv[1:])) + sys.exit(activity.exiting(lambda: main(sys.argv[1:]))) except BrokenPipeError: sys.exit(0) diff --git a/tools/audio/pace.py b/tools/audio/pace.py index d8fe29d6..70e795d6 100644 --- a/tools/audio/pace.py +++ b/tools/audio/pace.py @@ -678,7 +678,7 @@ def captions(old, skip_lint=False): f" --resume first, or pass --align gemini|whisper here to transcribe the take") if (missing and not found) or (a.align != "map" and not a.dry_run): # before anything is written if a.align == "gemini" and not tts.keys.get("GEMINI_API_KEY"): - sys.exit("set GEMINI_API_KEY (Google AI Studio → Get API key) for --align gemini; nothing was written") + sys.exit(tts.keys.stopping("GEMINI_API_KEY", "timing", "--align gemini needs it; nothing was written", align="--align whisper")) if a.align == "whisper" and importlib.util.find_spec("mlx_whisper") is None: sys.exit("--align whisper needs mlx-whisper (Apple Silicon; bin/vh pace adds it with --align whisper); nothing was written") if missing: # the take's own word times, transcribed once and kept beside it @@ -759,7 +759,7 @@ def save(): rc = 0 if a.align != "map": if a.align == "gemini" and not tts.keys.get("GEMINI_API_KEY"): - sys.exit("set GEMINI_API_KEY for --align gemini: the paced take is written with mapped word times") + sys.exit(tts.keys.stopping("GEMINI_API_KEY", "timing", "--align gemini needs it; the paced take is written with mapped word times", align="--align whisper")) try: fresh = align_take(new, wav, a.align, a.lang, tmp, out["duration"]) except Exception as e: # quota, network: the mapped word times stay diff --git a/tools/audio/tts.py b/tools/audio/tts.py index 2e5eff07..6c4c0ffb 100644 --- a/tools/audio/tts.py +++ b/tools/audio/tts.py @@ -141,7 +141,7 @@ pronunciation_dict.tone. text_normalization is on: "1953 年" is read 一千九百五十三年, so write years as 一九五三年 in the spoken text. """ -import argparse, base64, difflib, hashlib, json, os, platform, re, shutil, signal, subprocess, sys, tempfile, time, unicodedata +import argparse, base64, difflib, hashlib, json, os, re, shutil, signal, subprocess, sys, tempfile, time, unicodedata import urllib.error, urllib.parse, urllib.request, wave from concurrent.futures import Future, ThreadPoolExecutor from pathlib import Path @@ -218,7 +218,7 @@ def gemini_call(path, body=None, method=None, query=None, timeout=180, tries=3): so does one asking for more than 90 s. The delay and the quota are read from the first 8 KB of the body: a long quota message puts "retry in Ns" past the first 500 bytes, which are all that the error message repeats. A call that fails for good raises GeminiError.""" - key = keys.get("GEMINI_API_KEY") or sys.exit("set GEMINI_API_KEY (Google AI Studio → Get API key)") + key = keys.get("GEMINI_API_KEY") or sys.exit(keys.stopping("GEMINI_API_KEY")) url = f"{GEMINI_API}/{path}" + (f"?{urllib.parse.urlencode(query, doseq=True)}" if query else "") data = None if body is None else json.dumps(body).encode() k = limited = 0 @@ -250,17 +250,13 @@ def gemini_call(path, body=None, method=None, query=None, timeout=180, tries=3): # ---------- providers: each writes a WAV at `out` and may return word/char timings ---------- -KEY_OF = {"gemini": "GEMINI_API_KEY (Google AI Studio → Get API key)", "gemini-lite": "GEMINI_API_KEY (Google AI Studio → Get API key)", - "minimax": "MINIMAX_TOKEN_PLAN_KEY (Token Plan) or MINIMAX_API_KEY (pay-as-you-go), from platform.minimax.io", - "elevenlabs": "ELEVENLABS_API_KEY (elevenlabs.io)", "dashscope": "DASHSCOPE_API_KEY (Alibaba Cloud Model Studio, 阿里云百炼)"} +KEY_OF = {"gemini": ["GEMINI_API_KEY"], "gemini-lite": ["GEMINI_API_KEY"], "minimax": ["MINIMAX_TOKEN_PLAN_KEY", "MINIMAX_API_KEY"], # Token Plan first + "elevenlabs": ["ELEVENLABS_API_KEY"], "dashscope": ["DASHSCOPE_API_KEY"]} def no_key(provider): - """Exit (1) on a provider with no key: the key it needs, and what works with none on this machine.""" - if sys.platform == "darwin" and platform.machine() == "arm64": - free = "the local default needs no key: leave the provider out, bin/vh tts (qwen, free, about " + firstuse.gb(firstuse.total(["qwen"])) + " on first use)" - else: - free = "the local default (qwen) needs no key but only runs on Apple Silicon; here --provider edge needs none (free, online)" - sys.exit(f"set {KEY_OF[provider]} for {provider}; {free}") + """Exit (1) on a provider with no key: tools/keys.py's sentence (where to set it, where to get one), and what works with + none on this machine; on the run's record as no_key.""" + sys.exit(keys.stopping(KEY_OF[provider], "voice", size=firstuse.gb(firstuse.total(["qwen"])))) # (what works with none: per platform, tools/keys.py) def hf_cached(model_id): """The model is on this machine: a local folder, or a snapshot in the Hugging Face cache, found where the Hub itself @@ -1122,10 +1118,9 @@ def audition(a): if a.align == "local": need_local_asr() if (gemini or a.align == "gemini") and not keys.get("GEMINI_API_KEY"): - sys.exit("voices audition: set GEMINI_API_KEY (Google AI Studio → Get API key)" - + (f" for --provider {a.provider}" if gemini else " for --align gemini") + "; nothing was synthesized") + sys.exit("voices audition: " + keys.stopping("GEMINI_API_KEY", "voice" if gemini else "timing", (f"--provider {a.provider}" if gemini else "--align gemini") + " needs it; nothing was synthesized")) if a.provider == "minimax" and not minimax_key()[0]: - sys.exit("voices audition: set MINIMAX_TOKEN_PLAN_KEY or MINIMAX_API_KEY for --provider minimax; nothing was synthesized") + sys.exit("voices audition: " + keys.stopping(KEY_OF["minimax"], "voice", "nothing was synthesized")) try: import voicefeat except ImportError: @@ -1268,7 +1263,7 @@ def main(): if a.align == "local": # before anything is synthesized or deleted need_local_asr() if align and a.align != "local" and not keys.get("GEMINI_API_KEY"): - sys.exit("set GEMINI_API_KEY (Google AI Studio → Get API key): --align gemini / --join transcribe with Gemini (or --align local)") + sys.exit(keys.stopping("GEMINI_API_KEY", "timing", "--align gemini and --join transcribe time the words with Gemini")) if man and a.provider == "minimax" and join != "none" and man.get("gap") != a.gap: sys.exit(f"--resume: --gap was {man.get('gap')} for the run, now {a.gap}; in a joined minimax request it is part of the" f" text: pass --gap {man.get('gap')}, or drop --resume to start over") @@ -1287,7 +1282,7 @@ def linked(texts): # one minimax request: the lines linked by a pause mark of blocks.append([s]) wavs = [f"{i+1:02d}.wav" for i in range(len(segs))] if join == "none" else [f"_block{i+1:02d}.wav" for i in range(len(blocks))] voiced = a.resume and all((vo / f).exists() and ((vo / f).with_suffix(".words.json").exists() or not timed) for f in wavs) # the synthesis loops' own test - if not voiced and a.provider in ("elevenlabs", "dashscope", "gemini", "gemini-lite") and not keys.get(KEY_OF[a.provider].split()[0]): + if not voiced and a.provider in ("elevenlabs", "dashscope", "gemini", "gemini-lite") and not keys.get(KEY_OF[a.provider][0]): no_key(a.provider) # before anything is synthesized or deleted; --resume with all voiced needs none if a.provider == "minimax": minimax_settings() # a value out of range exits here, not mid-run diff --git a/tools/desk/README.md b/tools/desk/README.md index 7e927efb..f364d038 100644 --- a/tools/desk/README.md +++ b/tools/desk/README.md @@ -325,7 +325,7 @@ JSON 的格式: 下面这些命令加了 `--json`,失败时 stdout 是一行 `{"version": 1, "error": {"code", "message", "hint"}}`,给人看的那一行照旧在 stderr,退出码和不加 `--json` 时一样:`status`、`activity`、`versions`、`check`、`assets`、`edit`、`proxy`、`thumbs`、`peaks`、`artifacts`、`projects`、`cancel`、`history`、`timeline --resolved`、`commands`、`doctor`、`desk data`(它总是 JSON)、`gate`、`new`,连同 `bin/vh` 自己在 Python 起来之前发现的(打错的命令、`--json` 时没有 python3,退出码 127)。 -`code` 是稳定的,按它分支,别按文字:`usage`(参数错)、`no_project`(没有这个项目,或者这个文件夹不是)、`not_found`(项目在,它说的文件、片子、版本、run 不在)、`invalid`(文件在,读不成它该是的样子:不是 JSON、不合 schema、还有占位)、`exists`(要写的东西已经有了)、`refused`(规矩不让:页面犯了规)、`missing_tool`(少一个程序)、`timeout`(等到头了)、`failed`(别的)。`hint` 有话说时是一句接下来怎么办,否则 `null`。 +`code` 是稳定的,按它分支,别按文字:`usage`(参数错)、`no_project`(没有这个项目,或者这个文件夹不是)、`not_found`(项目在,它说的文件、片子、版本、run 不在)、`invalid`(文件在,读不成它该是的样子:不是 JSON、不合 schema、还有占位)、`exists`(要写的东西已经有了)、`refused`(规矩不让:页面犯了规)、`missing_tool`(少一个程序)、`no_key`(一家服务的 API Key 没设:说哪一家、去设置 → 服务里填,片子等着它时 `bin/vh status` 和 Studio 也这么说)、`timeout`(等到头了)、`failed`(别的)。`hint` 有话说时是一句接下来怎么办,否则 `null`。 几种记录有自己的字段,不是这个形状:`bin/vh check --json` 读不了片子时打它的记录,`error` 是字符串,退出码 1(这是对这支片子的判决);`bin/vh doctor --json` 没有 python3 时 `error` 也是字符串,退出码 0;清单和检查(`artifacts list --strict`、`assets check`、`edit check`)退出码 1 时打它们的记录。所以先看 `error` 是不是对象。 @@ -384,7 +384,7 @@ JSON 的格式: - `state` 七种:`done`(REVIEW.md 里有它的"定了":先看关于最新那一页的最后一节,审阅台为提交写的那节、或写了 `gate-.html` 的那节,模板的三节都预先写了;没有这种节,就看这一站自己的节,而且 REVIEW.md 要晚于这一页,`note` 里会说是按日期算的。关卡 ① 和 `bin/vh render`、`check` 用同一条规则(`tools/gatecheck.py`):关卡 ① 的节里有定了和人的原话;`record` 另有 `concept_on_record`、`concept_from`(`REVIEW.md`,或者老项目 DECISIONS.md 里立意那一行)和 `concept`(关卡 ① 定了那一行的原文:写的是哪张卡就是哪张卡,只写"通过"就是"通过"))、`skipped`(quick 档:这一站没有自己的页面,Director 也没要它(`stop=`、`x=own`);或者 REVIEW.md 里有用户原话授权跳过)、`waiting_person`(这一页发出去了(`bin/vh gate` 出的页面:写好还没发的 gate JSON 不算,上一次被 `bin/vh gate` 拒绝、退出码 1 的也不算,那一次什么都没发给人),是这一轮(`out/review/.current`),还没有回音)、`waiting_agent`(人提交了还没交给 agent,或者交了但 REVIEW.md 还没写定了;或者这一轮已经往后走、这一页没有记录;或者关卡 ① 定了,但缺人的原话,render 和 check 会拒绝)、`in_progress`(前面都过了,agent 正朝这一站做)、`not_started`、`no_record`(standard、studio 的项目没有 REVIEW.md,模板有它之前做的:无从读起,gatecheck 也不查)。交付:`bin/vh deliver` 写过记录,或成片(`out/final*`、`out/final/`、直接放在 `media/` 下的文件、Manim 1080p 及以上的渲染;不含它 480p15、720p30 的草稿,也不含 `bin/vh patch` 留下的 `.failed`)有一份通过的检查记录、而且就是这支成片的(记录里的 `size` 和 `mtime_ns` 和它现在的一样;没有这两个字段的老记录,要比它晚),而且关卡 ③ 过了(`done` 或 `skipped`),就是 `done`;关卡 ③ 还没过时 `note` 会说;各站都过了是 `in_progress`;没有 REVIEW.md 是 `no_record`。 - `waiting_on`:`person`、`agent`、`nobody`(交付了)或 `unknown`(没有 REVIEW.md,又没有命令在跑);REVIEW.md 写了暂停(`paused: true`)也是 `person`。机器写的记录(检查记录、`.render.json`、`.deliver.json`、审阅台的提交)里类型不对的字段当作没有。`next`:一句话,谁下一步做什么。 - `next_step`:下一步,按项目停在哪一站算出来:`who`(`person`、`agent`、`nobody`、`unknown`)、`do`(一句话,还没填的 `{…}` 和 gate 骨架里的占位有几处都说出来;Director 写了 `x=own`、还没有记录的事排在最前面,记录是它那一站过了,或者 DECISIONS.md 里它那一行写了已定)、`commands`(能直接跑的命令,`` 这类尖括号是要换的)、`read`(该读的:`<文件>#<节>` 由 `bin/vh know --show` 打印,没有 `#` 的整篇读)、`unfilled`(`BRIEF.md`、`STYLE.md`、`STORYBOARD.md` 各还有几处 `{…}`,不算代码块和行内代码里的,也不算模板的 `{none}` 和 `{fill: #e33}` 这种带值的花括号;交付以后 `who` 是 `nobody`,这里是空的,没有要填的了)。 -- `now`:这支片子现在怎么样,说给人听的(`tools/standing.py`,Studio 说的也是这些字;字都在它开头的 `WORDS` 表里,中英文挨着)。只说磁盘能证明的:最后记下的事和它在什么时候(命令的开始和结束、交出的意见、Studio 对话的事件、片子自己文件的改动)、现在有没有进程在跑、等着的进程和它等的 agent 活不活着、Studio 的一轮怎么结束的、一条命令是在哪个 agent 程序下跑的(那个 agent 还活着,就是有 agent 开着这支片子)。磁盘不知道 agent 是不是正在两条命令之间想事情,所以安静的片子只说"上一次动静:12 分钟前,渲染做完了",从不说没人在做;"停下了"要有正面的证据;"让 agent 接着做"是一个可以点的选项,不是"没人在做"的断言。字段:`code`、`who`(下一步该谁动,和 `waiting_on` 一致)、`you`(人跟它有什么事:`decide` 在等人定,`nudge` 要人说一声,`offer` 人可以点,`none`)、`tone`(点的颜色:`you` 琥珀、`busy` 紫、`quiet` 灰)、`say`(`{zh, en}` 一句短话,两秒读完)、`more`(`{zh, en}` 或 `null`:下面那一行)、`short`(`{zh, en}` 卡片上的几个字,不带路径,也不带不在词表里的命令名)、`act`(至多一件事:`{kind: "open", mod, sub, label}` 去 Studio 的哪个模块;`{kind: "tell", label, text, confirm, secondary}` 对 agent 说的那句话,`confirm` 是先问一次(最近 30 分钟里还有动静,或者有 agent 开着),`secondary` 是它不是主要该做的事、写成第二行的小字;`{kind: "none"}`)、`facts`(`paths`:这些话里点到的项目文件,Studio 里点得开;还有 `stop`、`listening`、`pending`、`cmd`、`film`、`subtitles`、`version` 这些)。 +- `now`:这支片子现在怎么样,说给人听的(`tools/standing.py`,Studio 说的也是这些字;字都在它开头的 `WORDS` 表里,中英文挨着)。只说磁盘能证明的:最后记下的事和它在什么时候(命令的开始和结束、交出的意见、Studio 对话的事件、片子自己文件的改动)、现在有没有进程在跑、等着的进程和它等的 agent 活不活着、Studio 的一轮怎么结束的、一条命令是在哪个 agent 程序下跑的(那个 agent 还活着,就是有 agent 开着这支片子)。磁盘不知道 agent 是不是正在两条命令之间想事情,所以安静的片子只说"上一次动静:12 分钟前,渲染做完了",从不说没人在做;"停下了"要有正面的证据;"让 agent 接着做"是一个可以点的选项,不是"没人在做"的断言。字段:`code`、`who`(下一步该谁动,和 `waiting_on` 一致)、`you`(人跟它有什么事:`decide` 在等人定,`nudge` 要人说一声,`offer` 人可以点,`none`)、`tone`(点的颜色:`you` 琥珀、`busy` 紫、`quiet` 灰)、`say`(`{zh, en}` 一句短话,两秒读完)、`more`(`{zh, en}` 或 `null`:下面那一行)、`short`(`{zh, en}` 卡片上的几个字,不带路径,也不带不在词表里的命令名)、`act`(至多一件事:`{kind: "open", mod, sub, label}` 去 Studio 的哪个模块;`{kind: "settings", sub, label}` 去设置页的哪一节(片子等一家服务的 API Key 时:`code` 是 `needs_key`,`facts.keys` 是还没设的 key 名,`facts.service` 是哪一家,`facts.need` 是 key 拿来做什么:`voice`、`timing`、`music`、`image`;下面那一行按它和这台电脑有什么来说不用 key 的办法,没有就直说没有。从整份记录里找(`activity.key_stop`),不看最近几条:有一个 key 设上了、后来同类的活做成了(配音成了,配音和对时间的停都算过去)、或者后来有别的命令失败了,就不再这么说。只在终端的环境变量里设了 key、Studio 又是从别处打开的,Studio 看不到这个变量,会一直说在等,直到那条命令在那个终端里再跑一次);`{kind: "tell", label, text, confirm, secondary}` 对 agent 说的那句话,`confirm` 是先问一次(最近 30 分钟里还有动静,或者有 agent 开着),`secondary` 是它不是主要该做的事、写成第二行的小字;`{kind: "none"}`)、`facts`(`paths`:这些话里点到的项目文件,Studio 里点得开;还有 `stop`、`listening`、`pending`、`cmd`、`film`、`subtitles`、`version`、`keys`、`service` 这些)。 `code` 按这个先后取第一个对上的:`paused`(REVIEW.md 写了暂停);`revision_ready`(有一条复审等人看);`waiting_you`(一站的页发出去了等人:`facts.listening` 按上面 `.listening` 的三样算,真就"你交了,agent 就接着做",不然"交了以后,要跟 agent 说一声";声音那一站是"等你听");最新的一份意见还没人取时,不管别的在不在跑都先说它:等着的人活着是 `notes_sent`,不然 `notes_unheard`(有命令在跑时写"渲染还在跑,但你 21:30 交的这一份没人取");`notes_taken`(意见交到 agent 手里了,而且这会儿真有东西在为这支片子做:`bin/vh` 命令在跑,或 Studio 的一个对话拿着锁;没东西在跑时不说"正在改");`running`(`bin/vh` 命令在跑,带进度;pid 被后来的进程占去的不算在跑);`working`(Studio 的一个对话拿着锁,锁的 pid 也照这样核对);`delivered`(最新的一份交付记录:哪支成片、旁边的字幕、`versions` 里正好是它的那一版);`no_record`;然后是轮到 agent、现在没东西在跑的几种。先把所有动静排一遍(结束了的命令:做完了、结束时报了问题、被停下了、中断了;发出的审阅页;开始等你的意见;它取走了你的意见;Studio 对话的最后一件事;片子自己的文件里最新改的那个:先看片子的文件夹,再一层层往下(广度优先,四层),不看 `out/`、`media/`、`renders/` 和 Studio 自己写的 `REVIEW.md`;`assets/`、`audio/`、帧序列这种重的文件夹(按名字,或者一个文件夹里超过 300 项)只看文件夹自己的时间,不一个个看;看到 4000 项还没看完就停,这时说的是"看到的最近一次动静","之后没有别的动静"这种话不说),取最新的那一件:它是一条没有结束记录、进程也没了的命令,或者 Studio 的一轮被停下、出错、做到一半断了,而且没有 agent 开着,才是 `stopped`("agent 停下了:渲染中断了。",下面一行是什么时候、到第几帧、之后没有别的动静、下一站);做这支片子的 agent 还开着,是 `agent_open`("现在没有命令在跑;上次做这支片子的 agent 还开着。","让 agent 接着做"降成第二行、点之前先问一次):只在这个 agent 程序最近一次做的就是这支片子,或者这支片子最新的动静在 6 小时以内时这么说;一个开了很久、做过许多支片子的程序(比如 Studio 那一列背后的那个)不让它做过的每支片子都显得"开着",那些片子照常说它们自己的情况,再加一句"做过它的 agent 程序还开着,可能在忙别的片子。";各站都过了还没交付是 `ship_missing`;下一步是装引擎是 `setup`;其余是 `idle`("现在没有命令在跑。",下面一行"上一次动静:……")。一条命令出错结束(`check` 没过、`gate` 拒绝)是它的结果,不是停下了:写成"上一次动静:3 分钟前,检查查出 2 处要改",下一步还是 agent 的。 diff --git a/tools/desk/static/studio.js b/tools/desk/static/studio.js index c32abdb5..f9691893 100644 --- a/tools/desk/static/studio.js +++ b/tools/desk/static/studio.js @@ -479,6 +479,7 @@ function renderNow() { // where this film stands, in bin/vh status's own sente const armed = a.kind === "tell" && a.confirm && NOWARM === PKEY; // an offer that asks once more: the first click arms it const quiet = a.secondary && !armed, cls = quiet ? "btn btn-quiet xs now-second" : a.secondary ? "btn" : "btn btn-primary"; // a second line, or the one thing to do const btn = a.kind === "tell" ? `${armed ? `` : ""}` + : a.kind === "settings" ? `${esc(a.label[L])}` // only the person can give it (an API Key): the settings page's section : mod && mod !== MOD ? `${esc(a.label[L])} →` : ""; // already on that page: no button to it const opens = (txt) => ((n.facts || {}).paths || []).reduce((h, p) => h.split(esc(p)).join(`${esc(p)}`), esc(txt)); // a file the words name opens const html = `

${esc(n.say[L])}

${n.more ? `

${opens(n.more[L])}

` : ""}${armed ? `

${esc(t("now_sure_note"))}

` : ""}${btn ? `
${btn}
` : ""}${plan ? `

${esc(plan[L])}

` : ""}`; diff --git a/tools/desk/test_agents.py b/tools/desk/test_agents.py index 6a6eff09..47024a7c 100644 --- a/tools/desk/test_agents.py +++ b/tools/desk/test_agents.py @@ -1901,6 +1901,48 @@ def unit(): # the order of what is said, and what each sentence never claims, pending_busy = one(stations=both_, activity={"running": [render]}) taken = one(stations=handed, activity={"running": [render]}) unknown = one(activity={"running": [{"cmd": "foo-bar"}]}) + import keys # a film waiting on a service's API Key: on no store of anyone's, with no key in the environment, on a platform made up + kept = {k: os.environ.pop(k) for k in [*keys.KEY_NAMES, "OVH_KEYSTORE"] if k in os.environ} + os.environ["OVH_KEYSTORE"] = "none"; keys._CACHE.pop("kind", None); keys.forget() + real_machine, real_codex = keys.machine, keys.has_codex + try: + keys.machine, keys.has_codex = (lambda: ("darwin", "arm64")), (lambda: False) + nk = lambda cmd, names, need=None, t=now - 900: {"cmd": cmd, "state": "failed", "exit": 1, "start": t - 10, "end": t, # noqa: E731 + "error": dict({"code": "no_key", "message": keys.missing(names)}, **({"need": need, "keys": [names] if isinstance(names, str) else names} if need else {}))} + ok = lambda cmd, t: {"cmd": cmd, "state": "ok", "exit": 0, "start": t - 10, "end": t} # noqa: E731 + bad = lambda cmd, t, **k: dict({"cmd": cmd, "state": "failed", "exit": 1, "start": t - 10, "end": t}, **k) # noqa: E731 + two_lines = lambda n: [n["code"], n["more"]["zh"].split("。")[1] + "。" if n["code"] == "needs_key" else None] # noqa: E731 + key_tts = one(activity={"recent": [nk("tts", "GEMINI_API_KEY")]}) + key_mm = one(activity={"recent": [nk("tts", ["MINIMAX_TOKEN_PLAN_KEY", "MINIMAX_API_KEY"], "voice")]}) + key_image = one(activity={"recent": [nk("image", "GEMINI_API_KEY", "image"), ok("render", now - 30)]}) # another kind of work after it: still waiting + key_timing = one(activity={"recent": [nk("tts", "GEMINI_API_KEY", "timing")]}) # tts --align gemini on the local voice: the timing line, not the voice one + settled = { # what a later run does to it + "tts_again": one(activity={"recent": [nk("tts", "GEMINI_API_KEY", "voice"), ok("tts", now - 30)]})["code"], + "voices_then_tts": one(activity={"recent": [nk("voices", "GEMINI_API_KEY", "voice"), ok("tts", now - 60), ok("render", now - 30)]})["code"], + "pace_then_tts": one(activity={"recent": [nk("pace", "GEMINI_API_KEY", "timing"), ok("tts", now - 30)]})["code"], + "pace_then_render": one(activity={"recent": [nk("pace", "GEMINI_API_KEY", "timing"), ok("render", now - 30)]})["code"], + "image_then_failed_check": one(activity={"recent": [nk("image", "GEMINI_API_KEY", "image"), bad("check", now - 30)]})["code"], + "image_then_stopped": one(activity={"recent": [nk("image", "GEMINI_API_KEY", "image"), dict(bad("render", now - 30), exit=130, cancelled=True)]})["code"], + "image_then_image": one(activity={"recent": [nk("image", "GEMINI_API_KEY", "image"), ok("image", now - 30)]})["code"], + "old_way": one(activity={"recent": [bad("tts", now - 90, error={"code": "failed", "message": "set GEMINI_API_KEY"})]})["code"], + "whole_log": one(activity={"recent": [ok("render", now - 50 + i) for i in range(5)], "key_stop": nk("tts", "GEMINI_API_KEY", "voice")})["code"], + "whole_log_none": one(activity={"recent": [nk("tts", "GEMINI_API_KEY", "voice")], "key_stop": None})["code"], + } + keys.has_codex = lambda: True + key_codex = one(activity={"recent": [nk("image", "GEMINI_API_KEY", "image")]}) + keys.has_codex = lambda: False + keys.machine = lambda: ("darwin", "x86_64") # an Intel Mac: macOS's own voice; no local timing + intel = [two_lines(one(activity={"recent": [nk("tts", "GEMINI_API_KEY", need)]})) for need in ("voice", "timing")] + keys.machine = lambda: ("linux", "x86_64") # Linux: no voice or timing of its own; music still composed here + linux = [two_lines(one(activity={"recent": [nk(c, "GEMINI_API_KEY", need)]})) for c, need in (("tts", "voice"), ("pace", "timing"), ("music", "music"))] + words = {"voice": keys.local_way("voice")[1], "timing": keys.local_way("timing", "--align whisper")[1]} # what the command says there + keys.machine = lambda: ("darwin", "arm64") + os.environ["GEMINI_API_KEY"] = "madeUpForThisCheck1" + key_set = one(activity={"recent": [nk("tts", "GEMINI_API_KEY", "voice")]}) + del os.environ["GEMINI_API_KEY"] + finally: + keys.machine, keys.has_codex = real_machine, real_codex + os.environ.pop("OVH_KEYSTORE", None); os.environ.update(kept); keys._CACHE.pop("kind", None); keys.forget() got = { "paused": one(paused=True)["code"], "revision": one(review={"revisions": [{"state": "pending", "available": True}]})["code"], "setup": one(next_step={"do": "the engine's scaffold is not there: this makes it"})["code"], "idle": one()["code"], @@ -1932,6 +1974,12 @@ def unit(): # the order of what is said, and what each sentence never claims, for v in ("TTS voice, no music", "Charon, 不要背景音乐", "none (music only)")], "short": all(not any(x in json.dumps(y["short"]) for x in ("/", ".mp4", "bin/vh")) for y in (gone, found, taken, unknown)), "ago": ["3 天", "2 小时"], + "key_tts": [key_tts["code"], key_tts["you"], key_tts["tone"], key_tts["say"], key_tts["more"]["zh"], key_tts["short"]["zh"], key_tts["act"], + key_tts["facts"]["keys"], key_tts["facts"]["service"]], + "key_mm": [key_mm["say"]["en"], key_mm["facts"]["keys"]], + "key_image": [key_image["say"]["zh"], key_image["more"]["en"]], + "key_timing": key_timing["more"]["en"], "key_codex": key_codex["more"]["zh"], "key_set": key_set["code"], "settled": settled, + "key_intel": intel, "key_linux": linux, "key_linux_words": [w.split(" (")[0] for w in words.values()], } want = {"paused": "paused", "revision": "revision_ready", "setup": "setup", "idle": "idle", "running": "正在配音,12 / 30 句。", "gone": ["stopped", "agent 停下了:渲染中断了。", "nudge", False], @@ -1949,13 +1997,27 @@ def unit(): # the order of what is said, and what each sentence never claims, "plan_music": {"zh": "2 分 30 秒横屏,没有旁白,停在立意、定声音、初版", "en": "2 min 30 s landscape, no narration, it stops at the concept, the final sound, the first draft"}, "plan_cn": {"zh": "没有旁白,中间不停,做完给你看", "en": "No narration, no stops on the way: you see it finished"}, "plan_odd": {"zh": "立意、分镜、初版都给你看", "en": "You see the concept, the storyboard and the first draft"}, "short": True, - "plan_voice": ["有旁白", "有旁白", "没有旁白"], "ago": [standing.ago(2.99 * 86400)[0], standing.ago(100 * 60)[0]]} + "plan_voice": ["有旁白", "有旁白", "没有旁白"], "ago": [standing.ago(2.99 * 86400)[0], standing.ago(100 * 60)[0]], + "key_tts": ["needs_key", "decide", "you", {"zh": "配音停下了:还没有 Gemini 的 API Key。", "en": "The voice-over stopped: there's no Gemini API Key yet."}, + "在设置 → 服务里填上,再让 agent 接着做。不想用在线服务,也可以让 agent 换成这台电脑上的声音。", "等 API Key", + {"kind": "settings", "mod": None, "sub": "services", "label": {"zh": "去设置 → 服务", "en": "Open Settings → Services"}}, ["GEMINI_API_KEY"], "gemini"], + "key_mm": ["The voice-over stopped: there's no MiniMax API Key yet.", ["MINIMAX_TOKEN_PLAN_KEY", "MINIMAX_API_KEY"]], + "key_image": ["出图停下了:还没有 Gemini 的 API Key。", "Set it up in Settings → Services, then ask the agent to carry on. This computer has no way to do it without an API Key."], + "key_timing": "Set it up in Settings → Services, then ask the agent to carry on. Or ask the agent to time the words on this computer, with no service.", + "key_codex": "在设置 → 服务里填上,再让 agent 接着做。也可以让 agent 用 Codex 出图,走 ChatGPT 的订阅,不用 API Key。", "key_set": "idle", + "settled": {"tts_again": "idle", "voices_then_tts": "idle", "pace_then_tts": "idle", "pace_then_render": "needs_key", "image_then_failed_check": "idle", + "image_then_stopped": "needs_key", "image_then_image": "idle", "old_way": "idle", "whole_log": "needs_key", "whole_log_none": "idle"}, + "key_intel": [["needs_key", "不想用在线服务,也可以让 agent 换成 macOS 自带的声音(够打草稿)。"], ["needs_key", "这台电脑上没有不用 API Key 的办法。"]], + "key_linux": [["needs_key", "这台电脑上没有不用 API Key 的办法。"], ["needs_key", "这台电脑上没有不用 API Key 的办法。"], ["needs_key", "不想用在线服务,也可以让 agent 在这台电脑上作曲。"]], + "key_linux_words": ["this computer has no voice of its own that needs no key", "this computer has no way of its own to time the words"]} return None if got == want else {k: v for k, v in got.items() if want.get(k) != v} check("what each state never says falsely: a run cut off with nothing after it is the only command that stops the agent (a finished run with " "findings, one stopped on purpose, a later run that went fine, the console ending, are not); the newest notes nobody took come first; " "working on them only while something runs; never that nobody works on the film; whose move as waiting_on; a command not in the table " "is no name on the page; the final sound is listened to and the sound plan looked at, plurals agree; the plan says what the BRIEF says plainly (none (music only), 2 min 30 s, " - "a checkpoint) and leaves out what it does not", unit) + "a checkpoint) and leaves out what it does not; a command that stopped for a service's API Key says so, what to do and where (Settings → Services), " + "with the line under it chosen by what the key was for and by what this computer has (a made-up Apple Silicon Mac, Intel Mac and Linux; Codex there or not), " + "until the key is set, a later run did the same kind of work fine, or a later run failed; read from the whole log", unit) def title(): # a film begun on the space, its BRIEF still the template's: the person's own sentence, shortened, not the dated folder import server diff --git a/tools/desk/test_settings.py b/tools/desk/test_settings.py index e8988c01..f108a705 100644 --- a/tools/desk/test_settings.py +++ b/tools/desk/test_settings.py @@ -526,6 +526,56 @@ def column_check(): return None if r.returncode == 0 else "not found in the column's environment" +def first_run_check(): + """A film whose voice-over stopped for want of Gemini's API Key: the command says the one sentence (where to set it, where + to get one, what works without), its record has the code no_key, and bin/vh status says the film waits on the key, with + the way to Settings → Services; once the key is saved in Studio, it says so no more. (No call is made: the check comes + first, and the store is these checks' own.)""" + if not shutil.which("uv"): + return None + film = T / "first-run" + shutil.rmtree(film, ignore_errors=True) + shutil.copytree(HERE / "fixtures" / "demo", film) + (film / "audio" / "script.txt").write_text("你好,这是一句试音。\n", encoding="utf-8") + env = dict(ENV, OVH_ACTIVITY_AGENT="0") + vh = lambda *a: subprocess.run(["bash", str(ROOT / "bin" / "vh"), *a], env=env, capture_output=True, text=True, timeout=180) # noqa: E731 + rc, out = py("import keys as K\nK.clear('GEMINI_API_KEY')") + if rc: + return out[-300:] + r = vh("tts", str(film), "gemini") + if r.returncode != 1 or "Studio's Settings → Services" not in r.stderr or "GEMINI_API_KEY" not in r.stderr or "aistudio.google.com" not in r.stderr: + return f"bin/vh tts gemini with no key: exit {r.returncode}, {r.stderr[-300:]!r}" + if list((film / "audio").glob("voiceover*")): + return "something was voiced" + notes = [json.loads(x) for x in (film / ".ovh" / "activity.jsonl").read_text().splitlines() if '"note"' in x] + if not any(n.get("level") == "error" and n.get("code") == "no_key" for n in notes): + return f"the run's record: {notes[-1:]}" + now = json.loads(vh("status", str(film), "--json").stdout)["now"] + if now["code"] != "needs_key" or now["act"].get("kind") != "settings" or now["act"].get("sub") != "services" or now["facts"].get("keys") != ["GEMINI_API_KEY"]: + return f"bin/vh status while the film waits: {now['code']} {now['act']}" + if "now: The voice-over stopped: there's no Gemini API Key yet." not in vh("status", str(film)).stdout: + return "bin/vh status's now: line" + if now.get("facts", {}).get("need") != "voice": + return f"what the key was for: {now.get('facts')}" + r = vh("music", str(film), "--provider", "lyria", "--prompt", "a calm tide") # bin/vh exec's into lyria.py: it ends its own run + runs = json.loads(vh("activity", str(film), "--json").stdout)["runs"] + mus = [x for x in runs if x.get("cmd") == "music"] + if r.returncode != 2 or "Studio's Settings → Services" not in r.stderr or not mus or mus[-1].get("state") != "failed" or mus[-1].get("exit") != 2: + return f"bin/vh music --provider lyria with no key: exit {r.returncode}, its run {mus[-1:] and {k: mus[-1].get(k) for k in ('state', 'exit')}}, {r.stderr[-200:]!r}" + now = json.loads(vh("status", str(film), "--json").stdout)["now"] + if now["code"] != "needs_key" or now["facts"].get("cmd") != "music" or now["facts"].get("need") != "music": + return f"bin/vh status after the music stop: {now['code']} {now['facts']}" + rc, out = py(f"import keys as K\nK.save('GEMINI_API_KEY', {FAKE!r})") + try: + if rc: + return out[-300:] + now = json.loads(vh("status", str(film), "--json").stdout)["now"] + if now["code"] == "needs_key": + return "the key saved in Studio, and the film is still said to wait on it" + finally: + py("import keys as K\nK.clear('GEMINI_API_KEY')") + + def words_check(): src = (HERE / "static" / "settings.js").read_text(encoding="utf-8") zh = src[src.index(" zh: {"):src.index(" en: {")] @@ -545,6 +595,7 @@ def words_check(): check("tools/keys.py on a store of these checks' own: saved, found, the environment first, taken out; what is not a key or a key's name refused; the store asked once per name (a missing key and a store with no answer too), a save or removal seen at once" + ("" if MAC else "; the key never an argument"), keys_module_check) check("bin/vh doctor finds a key saved in Studio, says so, and probes with it (a recording), with each of MiniMax's two when both are saved, never printing one", doctor_keys_check) check("a command run in the agent column's environment (no key in it) finds a key saved in Studio", column_check) + check("a voice-over, then Lyria's music, with no key: each command says where to set it and where to get one (code no_key and what the key was for on its record; the music run ends as failed, not cut off); bin/vh status says the film waits on the key, with the way to Settings → Services, and no more once it is saved", first_run_check) run() except Exception as e: say(False, "the console for the settings page", f"{type(e).__name__}: {e}") diff --git a/tools/jsonerr.py b/tools/jsonerr.py index aaad3039..3a870eea 100644 --- a/tools/jsonerr.py +++ b/tools/jsonerr.py @@ -15,6 +15,7 @@ exists what it would make is there already refused a rule says no: a page that breaks one, a render before gate ① is on record missing_tool a program it needs is not installed (the hint says which way to get it) + no_key a service's API Key is not set (tools/keys.py says which and where; bin/vh status says it while the film waits) timeout it waited as long as it was told to failed anything else that went wrong while it worked (exit 1 as a rule) A record the command prints of its own stays as it is: bin/vh check --json on a film it cannot read, bin/vh doctor --json @@ -50,17 +51,17 @@ def record(code, message, hint=None): return {"version": 1, "error": {"code": code, "message": message, "hint": hint if hint is not None else HINTS.get(code)}} -def _note(code, message): +def _note(code, message, **extra): try: import activity - activity.note(message, level="error", code=code) + activity.note(message, level="error", code=code, **extra) except Exception: # the failure is said all the same pass -def report(code, message, hint=None): - """The failure on record, once a run: JSON on stdout with --json (unless a record is out already), a note in the log. The - line a person reads is the caller's.""" +def report(code, message, hint=None, **extra): + """The failure on record, once a run: JSON on stdout with --json (unless a record is out already), a note in the log + (with extra's fields: no_key's need and keys). The line a person reads is the caller's.""" global _said if _said: return @@ -71,7 +72,7 @@ def report(code, message, hint=None): hint = activity.scrub(activity._text(str(hint))) if hint is not None else None except Exception: message = str(message) - _note(code, message) + _note(code, message, **extra) if wanted() and not (_out is not None and _out.count): print(json.dumps(record(code, message, hint), ensure_ascii=False), flush=True) diff --git a/tools/keys.py b/tools/keys.py index aeefab46..13661fc3 100644 --- a/tools/keys.py +++ b/tools/keys.py @@ -5,6 +5,11 @@ A key never goes into a file, a log, a URL, an event or the page, and never onto a command line (where the process list shows it): it is written to the store through standard input. Only names in KEY_NAMES are read or written here. +A command that stops because a key is missing says one sentence, the same everywhere (missing()): which service and key, +where to set it (Studio's Settings → Services, or the environment), where to get one, and what works with none; stopping() +also puts it on the run's record with the code no_key (tools/jsonerr.py), which bin/vh status and Studio say while the +film waits on that key (tools/standing.py). + usage: python3 tools/keys.py has exit 0 when a command would find that key (environment or store), else 1 python3 tools/keys.py where each name: env, studio or -, and what kind of store this computer has (there is no command that prints a key) @@ -25,7 +30,7 @@ OVH_KEYSTORE=none for all its checks and passes it on where a check builds an environment of its own (acp.clean_env keeps it too); a check that never set it still runs with a scratch HOME, whose search list has no keychain of the person's. """ -import json, os, re, shutil, subprocess, sys +import json, os, platform, re, shutil, subprocess, sys from pathlib import Path ROOT = Path(__file__).resolve().parent.parent @@ -176,6 +181,83 @@ def clear(name): raise NotKept(f"{name} is still saved ({kind} did not take it out)") +SERVICE = {"gemini": "Gemini", "minimax": "MiniMax", "elevenlabs": "ElevenLabs", "dashscope": "Alibaba Cloud Model Studio"} # as Studio's page names them + + +def module_of(name): + """tools/modules.json's service whose keys include this name, or None.""" + try: + t = json.loads((ROOT / "tools" / "modules.json").read_text(encoding="utf-8")) + except (OSError, ValueError): + return None + return next((m for m in t.get("modules") or [] if name in ((m.get("needs") or {}).get("keys") or [])), None) + + +def missing(names, instead=None): + """The sentence for a command that stops because none of these keys (one service's) is set.""" + names = [names] if isinstance(names, str) else list(names) + m = module_of(names[0]) or {} + said = " or ".join(names) + s = f"no {SERVICE.get(m.get('name'), m.get('name') or 'service')} API Key ({said}): paste one into Studio's Settings → Services" + if m.get("key_url"): + s += f" (get one at {m['key_url']})" + s += f", or set {said} in the environment" + return s + (f"; {instead}" if instead else "") + + +def machine(): + """(sys.platform, the processor): what decides the ways that need no key (a check fakes it).""" + return sys.platform, platform.machine() + + +def has_codex(): + return shutil.which("codex") is not None # as bin/vh doctor finds it (tools/modules.json's codex: the program on PATH) + + +def local_way(need, align="--align local", size=None): + """What does the same work with no API Key here: (word, the command's words). word is what tools/standing.py says + (voice, voice_say, timing, music, image_codex), None when this computer has no such way (the words say so plainly, or + are None). need: voice | timing | music | image.""" + plat, cpu = machine() + apple = plat == "darwin" and cpu == "arm64" + if need == "voice": + if apple: + return "voice", "or leave the provider out for this computer's own voice, which needs no key (qwen, free" + (f", about {size} on first use)" if size else ")") + if plat == "darwin": + return "voice_say", "or --provider say, macOS's own voice on this computer, which needs no key (free; good enough for a draft)" + return None, "this computer has no voice of its own that needs no key (the local one, qwen, runs only on Apple Silicon); --provider edge needs none, but it is an online service" + if need == "timing": + if apple: + return "timing", f"or {align}, which times the words on this computer with no key" + return None, f"this computer has no way of its own to time the words ({align} runs only on Apple Silicon)" + if need == "music": + return "music", "or bin/vh music without --provider, composed on this computer with no key" + if need == "image": + return ("image_codex", "or --provider codex, on the ChatGPT plan Codex is signed in with (no API Key)") if has_codex() else (None, None) + return None, None + + +def stopping(names, need=None, tail=None, align="--align local", size=None): + """missing() with what works with no key here (local_way), put on the run's record with the code no_key, what the key + was for (need) and its names (once a run; nothing outside a logged run): → the sentence, for the caller to print and + stop with.""" + names = [names] if isinstance(names, str) else list(names) + instead = "; ".join(x for x in (local_way(need, align, size)[1], tail) if x) or None + msg = missing(names, instead) + try: + import jsonerr + jsonerr.report("no_key", msg, "Studio's Settings → Services takes the key", need=need, keys=names) + except Exception: # the sentence is said all the same + pass + return msg + + +def wanted(names): + """The key names a no_key message names that are still not set: [] once any of them is (the film waits no more).""" + names = [n for n in names if n in KEY_NAMES] + return [] if any(get(n) for n in names) else names + + def main(argv): if argv[:1] in (["-h"], ["--help"]) or not argv: print(__doc__.strip()); return 0 if argv else 2 diff --git a/tools/schemas/output/activity.schema.json b/tools/schemas/output/activity.schema.json index e44ad1d5..69f6b1f0 100644 --- a/tools/schemas/output/activity.schema.json +++ b/tools/schemas/output/activity.schema.json @@ -61,7 +61,9 @@ "required": ["code", "message"], "properties": { "code": {"type": "string"}, - "message": {"type": "string"} + "message": {"type": "string"}, + "need": {"description": "code no_key: what the key was for", "enum": ["voice", "timing", "music", "image", null]}, + "keys": {"description": "code no_key: the key names it stopped for", "type": "array", "items": {"type": "string"}} } }, "cancelled": {"type": "boolean"}, diff --git a/tools/schemas/output/error.schema.json b/tools/schemas/output/error.schema.json index 0fd9c3f5..430dfce6 100644 --- a/tools/schemas/output/error.schema.json +++ b/tools/schemas/output/error.schema.json @@ -11,7 +11,7 @@ "type": "object", "required": ["code", "message", "hint"], "properties": { - "code": {"enum": ["usage", "no_project", "not_found", "invalid", "exists", "refused", "missing_tool", "timeout", "failed"]}, + "code": {"enum": ["usage", "no_project", "not_found", "invalid", "exists", "refused", "missing_tool", "no_key", "timeout", "failed"]}, "message": {"type": "string"}, "hint": {"type": ["string", "null"]} } diff --git a/tools/schemas/output/projects.schema.json b/tools/schemas/output/projects.schema.json index 7d3430f8..7b03ecb0 100644 --- a/tools/schemas/output/projects.schema.json +++ b/tools/schemas/output/projects.schema.json @@ -95,7 +95,7 @@ }, "$defs": { "words": {"type": "object", "required": ["zh", "en"], "properties": {"zh": {"type": "string"}, "en": {"type": "string"}}}, - "now": {"description": "Where the film stands for the person, in a sentence, and the one thing to do (tools/standing.py): what Studio says too", "type": ["object", "null"], "required": ["code", "who", "you", "tone", "say", "more", "short", "act", "facts"], "properties": {"code": {"enum": ["paused", "revision_ready", "waiting_you", "notes_unheard", "notes_sent", "notes_taken", "running", "working", "delivered", "no_record", "stopped", "agent_open", "ship_missing", "setup", "idle", "unknown"]}, "who": {"enum": ["person", "agent", "nobody", "unknown"]}, "say": {"$ref": "#/$defs/words"}, "more": {"anyOf": [{"type": "null"}, {"$ref": "#/$defs/words"}]}, "short": {"$ref": "#/$defs/words"}, "act": {"type": "object", "required": ["kind"], "properties": {"kind": {"enum": ["open", "tell", "none"]}, "mod": {"type": "string"}, "sub": {"type": ["string", "null"]}, "label": {"$ref": "#/$defs/words"}, "text": {"$ref": "#/$defs/words"}, "confirm": {"type": "boolean"}, "secondary": {"type": "boolean"}}}, "facts": {"type": "object", "properties": {"paths": {"type": "array", "items": {"type": "string"}}, "stop": {"type": "string"}, "listening": {"type": "boolean"}, "pending": {"type": "integer"}, "revisions": {"type": "integer"}, "cmd": {"type": ["string", "null"]}, "film": {"type": ["string", "null"]}, "subtitles": {"type": "array", "items": {"type": "string"}}, "version": {"type": ["string", "null"]}}}, "you": {"enum": ["decide", "nudge", "offer", "none"]}, "tone": {"enum": ["you", "busy", "quiet"]}}}, + "now": {"description": "Where the film stands for the person, in a sentence, and the one thing to do (tools/standing.py): what Studio says too", "type": ["object", "null"], "required": ["code", "who", "you", "tone", "say", "more", "short", "act", "facts"], "properties": {"code": {"enum": ["paused", "revision_ready", "waiting_you", "notes_unheard", "notes_sent", "notes_taken", "running", "working", "delivered", "no_record", "stopped", "agent_open", "ship_missing", "setup", "needs_key", "idle", "unknown"]}, "who": {"enum": ["person", "agent", "nobody", "unknown"]}, "say": {"$ref": "#/$defs/words"}, "more": {"anyOf": [{"type": "null"}, {"$ref": "#/$defs/words"}]}, "short": {"$ref": "#/$defs/words"}, "act": {"type": "object", "required": ["kind"], "properties": {"kind": {"enum": ["open", "tell", "settings", "none"]}, "mod": {"type": ["string", "null"]}, "sub": {"type": ["string", "null"]}, "label": {"$ref": "#/$defs/words"}, "text": {"$ref": "#/$defs/words"}, "confirm": {"type": "boolean"}, "secondary": {"type": "boolean"}}}, "facts": {"type": "object", "properties": {"paths": {"type": "array", "items": {"type": "string"}}, "stop": {"type": "string"}, "listening": {"type": "boolean"}, "pending": {"type": "integer"}, "revisions": {"type": "integer"}, "cmd": {"type": ["string", "null"]}, "film": {"type": ["string", "null"]}, "subtitles": {"type": "array", "items": {"type": "string"}}, "version": {"type": ["string", "null"]}, "keys": {"type": "array", "items": {"type": "string"}}, "service": {"type": ["string", "null"]}, "need": {"enum": ["voice", "timing", "music", "image", null]}}}, "you": {"enum": ["decide", "nudge", "offer", "none"]}, "tone": {"enum": ["you", "busy", "quiet"]}}}, "plan": {"description": "The film in a line from its BRIEF and its stops", "anyOf": [{"type": "null"}, {"$ref": "#/$defs/words"}]} } } diff --git a/tools/schemas/output/status.schema.json b/tools/schemas/output/status.schema.json index 5cc8b656..04f50716 100644 --- a/tools/schemas/output/status.schema.json +++ b/tools/schemas/output/status.schema.json @@ -221,7 +221,8 @@ "properties": { "running": {"type": "array"}, "listening": {"type": "array"}, - "recent": {"type": "array", "items": {"$ref": "#/$defs/run"}} + "recent": {"type": "array", "items": {"$ref": "#/$defs/run"}}, + "key_stop": {"description": "the newest run that stopped for want of an API Key (error code no_key) that no later run settled, from the whole log (tools/standing.py key_stop), or null", "anyOf": [{"type": "null"}, {"$ref": "#/$defs/run"}]} } }, "media": { @@ -254,7 +255,7 @@ }, "$defs": { "words": {"type": "object", "required": ["zh", "en"], "properties": {"zh": {"type": "string"}, "en": {"type": "string"}}}, - "now": {"description": "Where the film stands for the person, in a sentence, and the one thing to do (tools/standing.py): what Studio says too", "type": ["object", "null"], "required": ["code", "who", "you", "tone", "say", "more", "short", "act", "facts"], "properties": {"code": {"enum": ["paused", "revision_ready", "waiting_you", "notes_unheard", "notes_sent", "notes_taken", "running", "working", "delivered", "no_record", "stopped", "agent_open", "ship_missing", "setup", "idle", "unknown"]}, "who": {"enum": ["person", "agent", "nobody", "unknown"]}, "say": {"$ref": "#/$defs/words"}, "more": {"anyOf": [{"type": "null"}, {"$ref": "#/$defs/words"}]}, "short": {"$ref": "#/$defs/words"}, "act": {"type": "object", "required": ["kind"], "properties": {"kind": {"enum": ["open", "tell", "none"]}, "mod": {"type": "string"}, "sub": {"type": ["string", "null"]}, "label": {"$ref": "#/$defs/words"}, "text": {"$ref": "#/$defs/words"}, "confirm": {"type": "boolean"}, "secondary": {"type": "boolean"}}}, "facts": {"type": "object", "properties": {"paths": {"type": "array", "items": {"type": "string"}}, "stop": {"type": "string"}, "listening": {"type": "boolean"}, "pending": {"type": "integer"}, "revisions": {"type": "integer"}, "cmd": {"type": ["string", "null"]}, "film": {"type": ["string", "null"]}, "subtitles": {"type": "array", "items": {"type": "string"}}, "version": {"type": ["string", "null"]}}}, "you": {"enum": ["decide", "nudge", "offer", "none"]}, "tone": {"enum": ["you", "busy", "quiet"]}}}, + "now": {"description": "Where the film stands for the person, in a sentence, and the one thing to do (tools/standing.py): what Studio says too", "type": ["object", "null"], "required": ["code", "who", "you", "tone", "say", "more", "short", "act", "facts"], "properties": {"code": {"enum": ["paused", "revision_ready", "waiting_you", "notes_unheard", "notes_sent", "notes_taken", "running", "working", "delivered", "no_record", "stopped", "agent_open", "ship_missing", "setup", "needs_key", "idle", "unknown"]}, "who": {"enum": ["person", "agent", "nobody", "unknown"]}, "say": {"$ref": "#/$defs/words"}, "more": {"anyOf": [{"type": "null"}, {"$ref": "#/$defs/words"}]}, "short": {"$ref": "#/$defs/words"}, "act": {"type": "object", "required": ["kind"], "properties": {"kind": {"enum": ["open", "tell", "settings", "none"]}, "mod": {"type": ["string", "null"]}, "sub": {"type": ["string", "null"]}, "label": {"$ref": "#/$defs/words"}, "text": {"$ref": "#/$defs/words"}, "confirm": {"type": "boolean"}, "secondary": {"type": "boolean"}}}, "facts": {"type": "object", "properties": {"paths": {"type": "array", "items": {"type": "string"}}, "stop": {"type": "string"}, "listening": {"type": "boolean"}, "pending": {"type": "integer"}, "revisions": {"type": "integer"}, "cmd": {"type": ["string", "null"]}, "film": {"type": ["string", "null"]}, "subtitles": {"type": "array", "items": {"type": "string"}}, "version": {"type": ["string", "null"]}, "keys": {"type": "array", "items": {"type": "string"}}, "service": {"type": ["string", "null"]}, "need": {"enum": ["voice", "timing", "music", "image", null]}}}, "you": {"enum": ["decide", "nudge", "offer", "none"]}, "tone": {"enum": ["you", "busy", "quiet"]}}}, "plan": {"description": "The film in a line from its BRIEF and its stops", "anyOf": [{"type": "null"}, {"$ref": "#/$defs/words"}]}, "run": { "type": "object", diff --git a/tools/standing.py b/tools/standing.py index b96847fd..1c2f4298 100644 --- a/tools/standing.py +++ b/tools/standing.py @@ -59,7 +59,7 @@ "cmd.captions": ("做字幕", "making the subtitles", "the subtitles"), "cmd.cues": ("对时间", "lining up the timing", "the timing"), "cmd.readcheck": ("查字停得够不够久", "checking the words stay long enough to read", "the reading-time check"), "cmd.textcheck": ("查画面文字", "checking the text on screen", "the text check"), "cmd.timeline": ("排时间线", "laying out the timeline", "the timeline"), "cmd.peaks": ("画波形", "drawing the waveform", "the waveform"), - "cmd.bgm": ("配乐", "picking the music", "the music"), "cmd.voices": ("试听声音", "trying voices", "the voice trial"), + "cmd.bgm": ("配乐", "picking the music", "the music"), "cmd.voices": ("试听声音", "trying voices", "the voice trial"), "cmd.pace": ("调配音的快慢", "evening out the voice's pace", "the voice's pace"), "cmd.edit": ("排剪辑表", "laying out the edit", "the edit"), "cmd.footage": ("找素材", "finding footage", "the footage"), "cmd.rhythm": ("画节奏图", "drawing the rhythm chart", "the rhythm chart"), "cmd.beats": ("找节拍", "finding the beats", "the beats"), "cmd.determinism": ("查同一帧重渲是否一样", "checking a frame renders the same twice", "the same-frame check"), "cmd.hf": ("跑引擎", "running the engine", "the engine run"), @@ -124,6 +124,18 @@ "gap.cut": ("初版还没定", "the first draft is not decided yet"), "gap.check": ("成片没过检查", "the film has not passed its check"), "gap.final": ("正式版还没做好或还没检查", "the final is not made or not checked yet"), "setup": ("引擎还没装好。", "The engine is not set up yet."), + # a command stopped because a service's API Key is not set, and it still is not (tools/keys.py) + "needs_key": ("{x}停下了:还没有 {s} 的 API Key。", "{T} stopped: there's no {s} API Key yet."), + "needs_key.more": ("在设置 → 服务里填上,再让 agent 接着做。", "Set it up in Settings → Services, then ask the agent to carry on."), + "needs_key.voice": ("不想用在线服务,也可以让 agent 换成这台电脑上的声音。", "Or ask the agent to use this computer's own voice, with no service."), + "needs_key.voice_say": ("不想用在线服务,也可以让 agent 换成 macOS 自带的声音(够打草稿)。", "Or ask the agent to use macOS's own voice, with no service (good enough for a draft)."), + "needs_key.image_codex": ("也可以让 agent 用 Codex 出图,走 ChatGPT 的订阅,不用 API Key。", "Or ask the agent to make the pictures with Codex, on the ChatGPT plan, with no API Key."), + "needs_key.only": ("这台电脑上没有不用 API Key 的办法。", "This computer has no way to do it without an API Key."), + "needs_key.timing": ("不想用在线服务,也可以让 agent 在这台电脑上对时间。", "Or ask the agent to time the words on this computer, with no service."), + "needs_key.music": ("不想用在线服务,也可以让 agent 在这台电脑上作曲。", "Or ask the agent to compose the music on this computer, with no service."), + "needs_key.short": ("等 API Key", "waiting for an API Key"), + "svc.gemini": ("Gemini", "Gemini"), "svc.minimax": ("MiniMax", "MiniMax"), "svc.elevenlabs": ("ElevenLabs", "ElevenLabs"), + "svc.dashscope": ("阿里云百炼", "Alibaba Cloud Model Studio"), "setup.more": ("agent 接着做时会先装它(要联网)。", "The agent sets it up first when it carries on (it needs the network)."), "setup.short": ("引擎还没装好", "engine not set up"), "unknown": ("读不出这支片子现在到哪了。", "Where this film stands could not be worked out."), "unknown.short": ("读不出", "unreadable"), @@ -133,6 +145,7 @@ "next": ("下一步是{s}。", "Next: {s}."), "next.notes": ("下一步:照你的意见改{s}。", "Next: {s}, changed as your notes say."), # the buttons, and the words a tell button sends (only these words, numbers and times: nothing else from the project) "act.look": ("去{v}{s}", "{V} {s}"), "act.revision": ("去复审", "Review the change"), "act.ship": ("打开交付", "Open the delivery"), + "act.settings": ("去设置 → 服务", "Open Settings → Services"), "act.go_cut": ("去看初版", "Go to the first draft"), "act.go_ship": ("去看交付", "Go to the delivery"), "act.carry": ("让 agent 接着做", "Ask the agent to carry on"), "act.fetch": ("让 agent 来看意见", "Ask the agent to read your notes"), "act.carry_open": ("它要是没反应,在这里叫一个 agent 接着做", "If it does not answer, ask an agent here to carry on"), @@ -434,6 +447,62 @@ def act_open(mod, label, sub=None): return {"kind": "open", "mod": mod, "sub": sub, "label": label} +def act_settings(label, sub): + return {"kind": "settings", "mod": None, "sub": sub, "label": label} + + +DOES = {"tts": {"voice", "timing"}, "voices": {"voice"}, "pace": {"timing"}, "music": {"music"}, "image": {"image"}} # the kinds of work a run that ended fine did +NEED_OF = {"tts": "voice", "voices": "voice", "pace": "timing", "music": "music", "image": "image"} # a record that does not say what its key was for + + +def need_of(r): + return (r.get("error") or {}).get("need") or NEED_OF.get(r.get("cmd")) + + +def key_stop(runs): + """The newest finished run that stopped for want of an API Key (code no_key) that nothing after it settled, or None. + A later run that did the same kind of work fine settles it (a voice-over clears a voice or a timing stop; a picture an + image stop); a later run of anything that failed or was cut off takes the line, since it is newer news; one stopped on + purpose, and the console's own run, count for neither. The whole log is read (bin/vh status passes it as + activity.key_stop), not a window of the last few runs.""" + done = [r for r in runs if r.get("state") in ("ok", "failed", "gone") and r.get("cmd") != "desk"] + at = max((i for i, r in enumerate(done) if r.get("state") == "failed" and (r.get("error") or {}).get("code") == "no_key"), default=None) + if at is None: + return None + need = need_of(done[at]) + for r in done[at + 1:]: + if r.get("cancelled") or r.get("exit") in (130, 143): + continue + if r.get("state") == "gone" or r.get("exit") != 0: + return None + if need in DOES.get(r.get("cmd"), ()): + return None + return done[at] + + +def needs_key(o): + """The run that stopped for want of a service's API Key (key_stop) while that key is still not set: (run, the key names + it waits on, the service, what the key was for), or None. Once a key it names is set (in Studio or the environment), + the film waits no more.""" + act = o.get("activity") or {} + r = act["key_stop"] if "key_stop" in act else key_stop(act.get("recent") or []) + if not r: + return None + try: + import keys + except Exception: + return None + err = r.get("error") or {} + names = [n for n in err.get("keys") or [] if n in keys.KEY_NAMES] or [n for n in keys.KEY_NAMES if re.search(r"\b" + n + r"\b", err.get("message") or "")] + try: + left = keys.wanted(names) + except Exception: + left = [] + if not left: + return None + return r, left, (keys.module_of(left[0]) or {}).get("name"), need_of(r) + + def act_tell(label, text, confirm=False, secondary=False): return {"kind": "tell", "label": label, "text": text, "confirm": bool(confirm), "secondary": bool(secondary)} @@ -529,6 +598,18 @@ def seen(s): paths=([film] if film and not gone else []) + subs, film=film, subtitles=subs, version=vid) if any(s["state"] == "no_record" for s in st): return say("no_record", who, "none", both("no_record"), [both("no_record.more")]) + nk = needs_key(o) + if nk: # only the person can give a key: what to do and where, and what works without one + r, names, svc, need = nk + c, sv = cmd_words(r), both(f"svc.{svc}") if f"svc.{svc}" in WORDS else two(svc or "", svc or "") + try: # what does the same work with no key on this computer (the platform decides: tools/keys.py) + import keys + way = keys.local_way(need)[0] if need else None + except Exception: + way = None + return say("needs_key", who, "decide", two(w("needs_key", 0, x=c[0], s=sv["zh"]), w("needs_key", 1, T=cap(c[2]), s=sv["en"])), + [both("needs_key.more"), both(f"needs_key.{way}" if way else "needs_key.only")], both("needs_key.short"), + act_settings(both("act.settings"), "services"), cmd=r.get("cmd"), keys=names, service=svc, need=need) # the agent's move, and nothing works on the film now: the last thing seen and when; "stopped" only on positive evidence do = (o.get("next_step") or {}).get("do") or "" made = (o.get("media") or {}).get("film") or next((r["path"] for r in o.get("renders") or []), None) diff --git a/tools/status.py b/tools/status.py index 93288462..e98ae167 100644 --- a/tools/status.py +++ b/tools/status.py @@ -969,7 +969,7 @@ def vinfo(v, s): "open": {"review_items": open_items, "facts_to_verify": facts}, "renders": [vinfo(v, s) for v, s in vids[:10]], "deliveries": deliveries, "versions": vers, "check": check_summary(project, *checks[0]) if checks else None, "assets": assets, "cast": cast, "research": research, - "activity": {"running": working, "listening": listening, "recent": recent}, + "activity": {"running": working, "listening": listening, "recent": recent, "key_stop": standing.key_stop(runs)}, # (the whole log: a stop for an API Key nothing settled) "media": None, "next_step": None, "now": None, "plan": None} try: # what cannot be read is said, never a failure of status out["media"] = media(project)