From a479b6599b4dd027de756de84dbbafc524e2db09 Mon Sep 17 00:00:00 2001 From: zhanglinghao Date: Sun, 22 Nov 2026 17:06:27 +0800 Subject: [PATCH 1/9] A voice billed per use is held against the film's budget: MiniMax pay-as-you-go, ElevenLabs, DashScope bin/vh tts and bin/vh voices audition read the film's Budget before the first request and before anything is deleted (the key is checked first), each request is held and settled at what the answer says was billed (ElevenLabs': the estimate, an upper bound), and the run ends with what it spent. Prices from the providers' own pages, read 2026-11-22, in tools/audio/speechcost.py; an unknown model or endpoint needs a Budget line and is recorded as cost not known. Local voices, edge, Gemini and the Token Plan key are used as before. budget.py: two holds in one millisecond no longer share an id. --- README.md | 2 +- README.zh-CN.md | 2 +- changes/paid-speech-budget.md | 9 ++ playbook/04-audio.md | 6 +- tools/assets/budget.py | 5 +- tools/audio/README.md | 20 ++- tools/audio/speechcost.py | 223 ++++++++++++++++++++++++++++++++ tools/audio/tts.py | 190 +++++++++++++++++++++------ tools/ci.sh | 233 ++++++++++++++++++++++++++++++++++ tools/commands.json | 13 +- tools/desk/static/settings.js | 4 +- 11 files changed, 655 insertions(+), 52 deletions(-) create mode 100644 changes/paid-speech-budget.md create mode 100644 tools/audio/speechcost.py diff --git a/README.md b/README.md index 0efe3878..55353ead 100644 --- a/README.md +++ b/README.md @@ -418,7 +418,7 @@ Where there is no such store, put the key in the file your terminal reads each t echo 'export GEMINI_API_KEY=paste-your-key-here' >> ~/.zshrc ``` -The settings page lists the other services' names. A key set this way is used before one saved in Studio, name by name. An API Key isn't a budget: pictures and Lyria music are not made without a budget, while voices, word timing and auditions with these services are called directly and bill that account. +The settings page lists the other services' names. A key set this way is used before one saved in Studio, name by name. An API Key isn't a budget: pictures, Lyria music and voices billed per use (MiniMax pay-as-you-go, ElevenLabs, Alibaba Cloud Model Studio) are not made without a budget, while this computer's own voices, Gemini (word timing and auditions too, its free tier first) and MiniMax's Token Plan key are used as before. ## Install options and updates diff --git a/README.zh-CN.md b/README.zh-CN.md index 971304e8..b1c0e05b 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -418,7 +418,7 @@ AI 听不见,所以声音尽量做成能计算、能测量的。 echo 'export GEMINI_API_KEY=把你的key粘贴在这里' >> ~/.zshrc ``` -其他几家的变量名,设置页上都写着。这样设的 key,比 Studio 里存的同名 key 先用。有 API Key 不等于有预算:出图和 Lyria 作曲没写预算就不调;用这几家配音、逐字对时、试音,是直接调用,花的是那个账户的钱。 +其他几家的变量名,设置页上都写着。这样设的 key,比 Studio 里存的同名 key 先用。有 API Key 不等于有预算:出图、Lyria 作曲和按次计费的配音(MiniMax 按量付费、ElevenLabs、阿里云百炼)没写预算就不调;本机的声音、Gemini(逐字对时、试音也一样,先用免费额度)和 MiniMax 的 Token Plan key 照旧用。 ## 安装、更新和国内网络 diff --git a/changes/paid-speech-budget.md b/changes/paid-speech-budget.md new file mode 100644 index 00000000..8074a857 --- /dev/null +++ b/changes/paid-speech-budget.md @@ -0,0 +1,9 @@ +**按次计费的配音也要预算:MiniMax 按量付费、ElevenLabs、阿里云百炼没写预算就不调** +- Why: Studio 设置页存的 key 现在每条命令都读得到,Studio 对话里的 agent 也能调这几家收费的配音;出图和 Lyria 作曲早就要预算,配音还是直接调用、花账户的钱。 +- `bin/vh tts` 和 `bin/vh voices audition` 用 `elevenlabs`、`dashscope`,或者只有按量付费 key(`MINIMAX_API_KEY`)的 `minimax` 时,先读片子的预算(BRIEF 的 `Budget:`,没有再看 `LOCAL.md` 的默认预算)。没有预算、预算是 0,或者这次会超出,就不调,说清要写什么、还差多少;这一步在发出第一个请求、删掉旧配音之前。缺 key 和缺预算都有时,先说缺 key。 +- 每个请求先按字数占住估价,回答回来按它报的计费字数结账(MiniMax 的 `usage_characters`、百炼的 `usage.characters`),记进片子的 `assets/spend.jsonl`;结束时多一行:几个请求、花了多少、预算还剩多少。ElevenLabs 的回答不报字数,按估价记,是上限(套餐里含的字数不按次扣),那一行和账上都写明。报错的回答和没发出去的请求记 0;超时的保留估价,并且说可能已经扣了。 +- 价格照各家价格页(2026-11-22 读,页面地址写在 `tools/audio/speechcost.py` 里,`python3 tools/audio/speechcost.py` 列出):MiniMax 国际站 speech-2.8-hd 每百万字符 $100、turbo $60,国内站每万字符 ¥3.5、¥2;ElevenLabs 多语种 v2 每千字符 $0.08;百炼 qwen3-tts-flash 北京每万字符 ¥0.8、新加坡 $0.1。MiniMax 和百炼一个汉字算 2 个字符。表里没有的模型或接入点,只要有不为 0 的预算就调,记成"价钱不知道,可能已扣费"。 +- 试音按文本文件所在的片子读预算、记账;文本不在任何片子里时不调。 +- 照旧用,不要预算:本机的声音(`qwen`、`say`)、不要 key 的 `edge`、Gemini 配音和 `--align gemini`(先用免费额度)、MiniMax 的 Token Plan key(花套餐额度,tts 先用它)。 +- 两个预算占位在同一毫秒里时,记账的编号以前会重,结掉一个会把另一个也当成结了;编号现在加了一个计数。 +- Studio 设置页和 README"API Key"一节关于预算的那句话照新规则改了。 diff --git a/playbook/04-audio.md b/playbook/04-audio.md index c03dc39d..563ee13f 100644 --- a/playbook/04-audio.md +++ b/playbook/04-audio.md @@ -64,9 +64,11 @@ bin/vh beats <任意音乐文件> # 外来音乐的节 |---|---| | `qwen`(默认) | 本地开源 Qwen3-TTS,免费、离线,首次下载约 2.6 GB(`bin/vh tts` 开始前先说,并显示进度);0.6B 模型念英文短句偶尔停不下来,每条都要查 | | `gemini` | 云端,表演力最好,能用一句话导演语气,适合讲解旁白和双人对话;要 `GEMINI_API_KEY` | -| `minimax` | 云端 MiniMax(`speech-2.8-hd`),中文音色多(`Chinese (Mandarin)_*`)。`--join all` 整份稿一个请求,从头到尾一个声音;自带逐字时间,不用转写;支持停顿标记 `<#0.4#>` 和发音词典 `@pronounce`。语气只认一个情绪词。要 `MINIMAX_TOKEN_PLAN_KEY` 或 `MINIMAX_API_KEY`,细节见 `tools/audio/README.md` 的"MiniMax" | +| `minimax` | 云端 MiniMax(`speech-2.8-hd`),中文音色多(`Chinese (Mandarin)_*`)。`--join all` 整份稿一个请求,从头到尾一个声音;自带逐字时间,不用转写;支持停顿标记 `<#0.4#>` 和发音词典 `@pronounce`。语气只认一个情绪词。要 `MINIMAX_TOKEN_PLAN_KEY` 或 `MINIMAX_API_KEY`,细节见 `tools/audio/README.md` 的"MiniMax"。Token Plan 的 key 先用,花套餐额度,不要预算;只有按量付费的 `MINIMAX_API_KEY` 时按次计费,要预算(见下) | | `say` / `edge` | 打草稿;只能念,不能演 | -| `elevenlabs` / `dashscope` | 接口已留,还没实测 | +| `elevenlabs` / `dashscope` | 接口已留,还没实测;都按次计费,要预算(见下) | + +**按次计费的配音要预算**:MiniMax 按量付费的 key、ElevenLabs、阿里云百炼(`dashscope`)按字数计费,和生图、Lyria 一样,BRIEF 的 `Budget:` 和 `LOCAL.md` 的默认预算都没写就不调(`bin/vh tts` 和 `bin/vh voices audition` 在发出第一个请求、删掉旧的配音之前就停下,说清要写什么);写一个数或 `不限` 就算授权。整次合成先按字数估一遍,超出预算就不调,说清还差多少;每个请求先占住估价,再按回答里的计费字数结账(ElevenLabs 的回答不报字数,按估价记,是上限:套餐里含的字数不按次扣),都记进片子的 `assets/spend.jsonl`。缺 key 和缺预算都有时,先说缺 key。价格和出处:`python3 tools/audio/speechcost.py`。本地的 `qwen`、`say`,不要 key 的 `edge`,`gemini`(先用免费额度)和 `--align gemini` 照旧用,不要预算。 **每条配音都要查**:加 `--align gemini` 让机器逐句转写、对稿(见下一节),或者至少看一眼 `timeline..json` 里每句的时长。被标出来的句子重跑,或者换 provider。 - 相似度只抓得住跑偏的句子:长句里多一个"啊",或者"32 亿"念成了"3.2 亿",相似度几乎不变,掉不到 0.85 以下,不会被标出来。一支 2026-10 的片子每次合成后,把每章的音频和那章的稿子一起交给 Gemini,让它逐句说出念得和稿子不一样的地方:三次抓到多余的"啊""呢",一次抓到念错的数字。 diff --git a/tools/assets/budget.py b/tools/assets/budget.py index 90af0fb9..d306b80d 100644 --- a/tools/assets/budget.py +++ b/tools/assets/budget.py @@ -25,7 +25,7 @@ ledger.add(project, file, id="hero", cost={"amount": total, "currency": "USD"}, …) # adds only what the log lacks check() answers the same question without holding anything (an estimate shown before asking). """ -import contextlib, fcntl, json, os, re, sys, time +import contextlib, fcntl, itertools, json, os, re, sys, time from pathlib import Path HERE = Path(__file__).resolve().parent @@ -44,6 +44,7 @@ ZERO = re.compile(r"^[ \t]*(?:0+(?:\.0+)?|none|no|off|nothing|无|不花钱|零)[ \t]*[。.]?[ \t]*$", re.I) UNLIMITED = re.compile(r"^[ \t]*(?:不限|无上限|不设上限|unlimited|no limit|no cap)[ \t]*[。.]?[ \t]*$", re.I) EPS = 1e-9 +_SEQ = itertools.count(1) # a hold's id: the time, the process and this count (two holds in one millisecond are two) BRIEF_LINE = r"^[ \t]*[-*][ \t]*(?:\*\*)?Budget(?:\*\*)?[ \t]*[::][ \t]*(.*?)[ \t]*$" LOCAL_LINE = r"^[ \t]*[-*]?[ \t]*(?:\*\*)?(?:默认预算|预算|default[ \t]+budget|budget)(?:\*\*)?[ \t]*[::][ \t]*(.*?)[ \t]*$" @@ -259,7 +260,7 @@ def hold(project, amount, currency, what, tool=None, asset=None): c = check(project, amount, currency) if not c["ok"]: raise Refused(f"{what}: {c['message']}", c) - rec = _append(project, {"kind": "hold", "id": f"h{int(time.time() * 1000)}-{os.getpid()}", "amount": amount, "currency": currency, + rec = _append(project, {"kind": "hold", "id": f"h{int(time.time() * 1000)}-{os.getpid()}-{next(_SEQ)}", "amount": amount, "currency": currency, "what": str(what)[:300], "tool": tool or os.environ.get("OVH_ACTIVITY_CMD") or None, "asset": asset, "estimate": amount}) h = Hold(project, rec) try: diff --git a/tools/audio/README.md b/tools/audio/README.md index 738fa4f5..9e156fd7 100644 --- a/tools/audio/README.md +++ b/tools/audio/README.md @@ -15,8 +15,8 @@ | `qwen`(默认) | **本地开源** Qwen3-TTS(Apache-2.0),mlx-audio 运行在 Apple Silicon 上。中文音色:Serena(温暖女声)、Vivian、Uncle_Fu、Dylan(京腔)、Eric(川话);英文音色:Aiden(默认)、Ryan(语速慢,0.6B 模型用它时经常拖出几秒到几十秒的含糊声) | 首次运行下载约 2GB;换 1.7B 模型(`QWEN_TTS_MODEL`)后可以用 `--instruct` 控制语气 | 句级 | ✅ 已实测中英 | | `say` | macOS 自带,离线,适合打草稿 | 无 | 句级 | ✅ 已实测 | | `edge` | 微软免费在线音色 | 联网;非官方接口 | 句级 | ✅ 已实测英文 | -| `dashscope` | 阿里云百炼 Qwen3-TTS(`qwen3-tts-flash`),云端 | `DASHSCOPE_API_KEY` | 句级 | 接口已留,待实测 | -| `elevenlabs` | 高质量多语种配音 | `ELEVENLABS_API_KEY`、voice_id | **词级**(接口给字符级,`bin/vh tts` 拼成词) | 接口已留,待实测 | +| `dashscope` | 阿里云百炼 Qwen3-TTS(`qwen3-tts-flash`),云端,**按次计费** | `DASHSCOPE_API_KEY`;片子的预算 | 句级 | 接口已留,待实测 | +| `elevenlabs` | 高质量多语种配音,**按次计费** | `ELEVENLABS_API_KEY`、voice_id;片子的预算 | **词级**(接口给字符级,`bin/vh tts` 拼成词) | 接口已留,待实测 | | `gemini` / `gemini-lite` | Google Gemini 3.8 Flash TTS(2026-09-23 发布)/ Flash-Lite TTS,云端。表演力强,适合讲解旁白和双人对话。Flash 支持 130 种语言,Lite 支持 101 种,都含中文,语言按文本自动识别。`--voice` 用 30 个 studio 音色之一(默认 Kore,每个都能说所有支持的语言)、音色库 id 或自己设计的 `voice_…`(见下文"音色");`bin/vh tts` 的第 5 个参数(`--instruct`)用一句话描述语气,例如"平静、笃定的纪录片旁白";稿子里可以直接写 ``、``、`` 这类标签,只有 gemini 会演出来,其他 provider 和字幕都会自动去掉 | `GEMINI_API_KEY`(Google AI Studio)。有免费档,但免费档的内容可能被 Google 用来改进产品;付费价格见下文"费用" | 句级;加 `--align gemini` 后为词级 | ✅ `gemini`:2026-09-30 实测中英(Kore / Charon),一次通过,逗号处有自然停顿;双人对话、整段合成、设计音色同日实测。`gemini-lite` 走同一条代码路径(只换模型 id),没有单独实测 | | `minimax` | MiniMax T2A v2(`speech-2.8-hd`),国际站 `api.minimax.io`,云端。中文系统音色是 `Chinese (Mandarin)_*`(默认 `Chinese (Mandarin)_Reliable_Executive`),英文默认 `English_expressive_narrator`。句子里可以写停顿标记 `<#0.4#>`,稿子里可以写发音词典 `@pronounce`;`--join all` 整份稿一个请求,音色不漂。见下文"MiniMax" | `MINIMAX_TOKEN_PLAN_KEY`(Token Plan,优先)或 `MINIMAX_API_KEY`(按量付费) | **词级**(请求自带逐字时间,不用转写) | ✅ 2026-10-07 实测中英:逐句、`--join block`、`--join all`、`--resume` | @@ -169,7 +169,8 @@ bin/vh tts projects/

minimax "Chinese (Mandarin)_Reliable_Executive" zh --joi MINIMAX_TTS_SPEED=1.25 bin/vh tts projects/

minimax - zh --join all --gap 0.3 # 默认音色,语速 1.25,句间停 0.3 s ``` -- **key 和接口**:请求发到国际站 `https://api.minimax.io/v1/t2a_v2`。key 先从环境变量读,没有再用 Studio 设置页里存的(`tools/keys.py`),先找 `MINIMAX_TOKEN_PLAN_KEY`(Token Plan 的 Subscription Key,花的是买的 Credits),没有再用 `MINIMAX_API_KEY`(按量付费,账户没有余额时报 `1008 insufficient balance`)。买了 Credits 却只设了按量付费的 key,也是 1008。国际站的 key 发到国内站 `api.minimaxi.com` 会报 `2049 invalid api key`,所以默认走国际站;用国内站(platform.minimaxi.com)的 key 时,设 `MINIMAX_BASE_URL=https://api.minimaxi.com`。报错只写 key 来自哪个变量,不写 key 本身; +- **key 和接口**:请求发到国际站 `https://api.minimax.io/v1/t2a_v2`。key 先从环境变量读,没有再用 Studio 设置页里存的(`tools/keys.py`),先找 `MINIMAX_TOKEN_PLAN_KEY`(Token Plan 的 Subscription Key,花的是买的 Credits),没有再用 `MINIMAX_API_KEY`(按量付费,账户没有余额时报 `1008 insufficient balance`;按次计费,要片子的预算,见下一条)。买了 Credits 却只设了按量付费的 key,也是 1008。国际站的 key 发到国内站 `api.minimaxi.com` 会报 `2049 invalid api key`,所以默认走国际站;用国内站(platform.minimaxi.com)的 key 时,设 `MINIMAX_BASE_URL=https://api.minimaxi.com`。报错只写 key 来自哪个变量,不写 key 本身; +- **按次计费要预算**:只用 `MINIMAX_API_KEY` 时(Token Plan 的 key 先用,那时不要预算),和 `elevenlabs`、`dashscope` 一样,没有预算就不调,见"按次计费的配音"; - **音色**:`--voice` 写系统音色的 id。中文音色都以 `Chinese (Mandarin)_` 开头,例如 `Chinese (Mandarin)_Reliable_Executive`(沉稳的中年男声,默认)、`_News_Anchor`(女声新闻主播)、`_Male_Announcer`、`_Radio_Host`;英文默认 `English_expressive_narrator`。全部系统音色(2026-10-07 有 332 个)用 `POST /v1/get_voice`、body `{"voice_type": "system"}` 列出,`bin/vh voices` 只管 Gemini: ```bash @@ -190,6 +191,19 @@ MINIMAX_TTS_SPEED=1.25 bin/vh tts projects/

minimax - zh --join all --gap 0.3 - 逐句合成时,每句前后各有约 0.3 s 空白,会被自动裁掉; - 一支片子里 `Chinese (Mandarin)_Reliable_Executive` 在语速 1.25 下约 5.35 字/秒(说话时)。 +### 按次计费的配音(MiniMax 按量付费、ElevenLabs、阿里云百炼) + +和生图、Lyria 一样,这几家按字数计费,没有预算就不调:`bin/vh tts` 和 `bin/vh voices audition` 用 `elevenlabs`、`dashscope`,或者只有 `MINIMAX_API_KEY`(没有 Token Plan 的 key)的 `minimax` 时,先读片子的预算(BRIEF 的 `Budget:`,没有再看 `LOCAL.md` 的默认预算;预算的写法见 `tools/assets/budget.py`)。 + +- **先 key,后预算**:两样都缺时先说缺 key,预算没 key 也用不上; +- **整次先估**:在发出第一个请求、删掉旧配音之前,按这次要合成的句子(`--resume` 只算没做完的,`--candidates N` 算 N 份)估字数和价钱。没有预算、预算是 0,或者超出预算,就不调,说清要在 BRIEF 写什么、还差多少。预算的币种要和计费的币种一样:国际站按美元,国内站(`MINIMAX_BASE_URL` 在 minimaxi.com)和百炼北京(默认)按人民币; +- **每个请求先占后结**:请求发出前按估价占住,回答回来按它报的计费字数结账(MiniMax 的 `extra_info.usage_characters`,百炼的 `usage.characters`)。ElevenLabs 的回答不报字数,按估价结,是上限:套餐里含的字数不按次扣,结尾那行和账上都写明。报错的回答(HTTP 错误、MiniMax 的错误码)和根本没发出去的请求记 0;超时或回答被截断的保留估价,因为可能已经扣了,并且说出来。MiniMax 自己重试的每一次都是一个请求; +- **字数怎么算**:按各家价格页的说法,MiniMax 和百炼一个汉字算 2 个字符(MiniMax 国际站的页面没写,按国内站的算法,取大的),ElevenLabs 每个字符算 1 个; +- **记在哪**:片子的 `assets/spend.jsonl`(`bin/vh assets list`、`bin/vh status` 和审阅页里的预算行都读它)。`bin/vh tts` 结束时多一行:这次几个请求、花了多少、预算还剩多少; +- **价格表**:`python3 tools/audio/speechcost.py` 列出每家、每个接入点、每个模型的价格和出处页(2026-11-22 读)。表里没有的模型(`MINIMAX_TTS_MODEL`、`ELEVENLABS_MODEL`、`DASHSCOPE_TTS_MODEL` 设成别的)或接入点(`MINIMAX_BASE_URL`、`DASHSCOPE_BASE_URL` 指到别处):价钱不知道,只要 BRIEF 有一个不为 0 的预算(一个数或 `不限`)就调,每个请求记成"价钱不知道,可能已扣费"; +- **试音**:`bin/vh voices audition` 按文本文件所在的片子(往上找 BRIEF.md)读预算、记账;文本不在任何片子里时不调,说清要放进片子的文件夹。 +- **照旧用,不要预算**:本地的 `qwen`、`say`;不要 key 的 `edge`;`gemini`、`gemini-lite` 和 `--align gemini`(先用免费额度);Token Plan 的 key(花套餐额度)。 + ### 旁白里的标签 - **停顿标记**:`<#0.4#>` 是 MiniMax 的停顿(秒),只有 `minimax` 会停,其他 provider 和字幕都会去掉它,见上一节。 diff --git a/tools/audio/speechcost.py b/tools/audio/speechcost.py new file mode 100644 index 00000000..58412d79 --- /dev/null +++ b/tools/audio/speechcost.py @@ -0,0 +1,223 @@ +"""What a per-use voice costs, and its requests held against the film's budget (tools/assets/budget.py). Stdlib only. + +Billed per use, so not called without a budget (CLAUDE.md: 按次计费的配音), in bin/vh tts and bin/vh voices audition: + minimax with MINIMAX_API_KEY (pay-as-you-go: the account's balance). With MINIMAX_TOKEN_PLAN_KEY, which tts tries + first, the Token Plan's credits are spent instead, and no budget is asked + elevenlabs billed in US dollars per character + dashscope Alibaba Cloud Model Studio (阿里云百炼), per 10,000 characters after a new account's free quota +Used as before, with no budget: qwen and say (on this machine), edge (no key, not billed), gemini, gemini-lite and +--align gemini (the free quota first). + +The prices (PRICES) are the providers' own pages, read on CHECKED; each entry names its page. Characters are counted as +those pages count them: a Chinese character (Han, kanji, hanja) as 2 for MiniMax and DashScope, every character as 1 for +ElevenLabs. MiniMax's international page does not say how it counts; its China page's rule (2) is used there too, the +larger of the two. + +A run: check() before any request and before anything is deleted (the key comes first: a budget is no use without one) +takes the whole run's estimate against the budget; no budget, or one it would go over, and nothing is called, with what to +write. Then each request is held at its own estimate and settled at what the answer says was billed (MiniMax's +extra_info.usage_characters, DashScope's usage.characters × the price) or, for ElevenLabs, whose answer says nothing, at the +estimate: an upper bound, since characters a plan includes are not billed per use (the record says so). An error answer +and a request that never left settle at 0; a timeout or an answer cut off keeps the estimate, as such a request may have +been billed (said). A model or an endpoint the table does not have: called only with a Budget line (an amount or 不限), +and recorded as cost not known, maybe billed. + + python3 tools/audio/speechcost.py [--json] the table: provider, endpoint, model, price, page +""" +import contextlib, json, os, re, sys +from pathlib import Path +from urllib.parse import urlparse + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "assets")) +import budget # noqa: E402 (tools/assets/budget.py: the Budget line, the spend log, hold and settle) + +CHECKED = "2026-11-22" +_MM = "https://platform.minimax.io/docs/guides/pricing" +_MM_CN = "https://platform.minimax.cn/docs/guides/pricing" # platform.minimaxi.com/docs/guides/pricing leads here +_EL = "https://elevenlabs.io/pricing/api" +_ALI = "https://www.alibabacloud.com/help/en/model-studio/model-pricing" +_ALI_CN = "https://help.aliyun.com/zh/model-studio/model-pricing" +# (provider, endpoint) → the price of `per` characters by model, in `currency`; `cjk`: what a Chinese character counts as +PRICES = { + ("minimax", "international"): {"currency": "USD", "per": 1_000_000, "cjk": 2, "page": _MM, + "models": {"speech-2.8-hd": 100.0, "speech-2.6-hd": 100.0, "speech-02-hd": 100.0, + "speech-2.8-turbo": 60.0, "speech-2.6-turbo": 60.0, "speech-02-turbo": 60.0}}, + ("minimax", "china"): {"currency": "CNY", "per": 10_000, "cjk": 2, "page": _MM_CN, + "models": {"speech-2.8-hd": 3.5, "speech-2.6-hd": 3.5, "speech-02-hd": 3.5, + "speech-2.8-turbo": 2.0, "speech-2.6-turbo": 2.0, "speech-02-turbo": 2.0}}, + ("elevenlabs", "api"): {"currency": "USD", "per": 1_000, "cjk": 1, "page": _EL, "upper": True, + "models": {"eleven_multilingual_v2": 0.08, "eleven_v3": 0.08, "eleven_flash_v2_5": 0.04, "eleven_turbo_v2_5": 0.04}}, + ("dashscope", "singapore"): {"currency": "USD", "per": 10_000, "cjk": 2, "page": _ALI, "models": {"qwen3-tts-flash": 0.1}}, + ("dashscope", "beijing"): {"currency": "CNY", "per": 10_000, "cjk": 2, "page": _ALI_CN, "models": {"qwen3-tts-flash": 0.8}}, +} +NAME = {"minimax": "MiniMax pay-as-you-go (MINIMAX_API_KEY)", "elevenlabs": "ElevenLabs", "dashscope": "Alibaba Cloud Model Studio (DashScope)"} +UPPER = "ElevenLabs' answer does not say what it billed: settled at the estimate, an upper bound (characters a plan includes are not billed per use)" +HAN = re.compile(r"[㐀-䶿一-鿿豈-﫿\U00020000-\U0003134f]") + + +def paid(provider, minimax_var=None): + """Who bills this call per use here, or None: the providers above; minimax only through MINIMAX_API_KEY.""" + if provider == "minimax": + return NAME["minimax"] if minimax_var == "MINIMAX_API_KEY" else None + return NAME.get(provider) + + +def endpoint(provider, env=None): + """Which price list the call is billed on: minimax's international platform (the default) or China's + (MINIMAX_BASE_URL on minimaxi.com or minimax.cn); DashScope's Beijing (the SDK's default) or Singapore + (DASHSCOPE_BASE_URL on dashscope-intl). An address the table does not know: None (cost not known).""" + env = os.environ if env is None else env + if provider == "minimax": + base = env.get("MINIMAX_BASE_URL") + host = (urlparse(base).hostname or "") if base else "api.minimax.io" + return "international" if host == "api.minimax.io" else "china" if host.endswith(("minimaxi.com", "minimax.cn")) else None + if provider == "dashscope": + base = env.get("DASHSCOPE_BASE_URL") + host = (urlparse(base).hostname or "") if base else "dashscope.aliyuncs.com" + return "beijing" if host == "dashscope.aliyuncs.com" else "singapore" if host == "dashscope-intl.aliyuncs.com" else None + return "api" if provider == "elevenlabs" else None + + +def film_of(path): + """The film a file is in (the nearest folder at or above it with a BRIEF.md), or None: where its spend is recorded.""" + return budget.ledger.project_of(Path(path).parent) + + +def chars(text, cjk): + """The characters billed for text: every character once, a Chinese one cjk times.""" + return len(text) + (cjk - 1) * len(HAN.findall(text)) + + +def rate(provider, model, env=None): + """{"currency", "each" (a character's price), "cjk", "page", "upper", "endpoint"} or {"currency", "unknown": why}: the + price of a character for this provider, endpoint and model.""" + ep = endpoint(provider, env) + t = PRICES.get((provider, ep)) + if t is None: + cur = {"minimax": "USD", "dashscope": "CNY", "elevenlabs": "USD"}.get(provider, "USD") + where = (env if env is not None else os.environ).get("MINIMAX_BASE_URL" if provider == "minimax" else "DASHSCOPE_BASE_URL") + return {"currency": cur, "cjk": 2, "unknown": f"an endpoint the price table does not have ({where})"} + if model not in t["models"]: + return {"currency": t["currency"], "cjk": t["cjk"], "unknown": f"{model} is not in the price table ({t['page']}, read {CHECKED})"} + return {"currency": t["currency"], "each": t["models"][model] / t["per"], "cjk": t["cjk"], "page": t["page"], + "upper": bool(t.get("upper")), "endpoint": ep, "price": f"{budget.money(t['models'][model], t['currency'])} per {t['per']:,} characters"} + + +class Refused(Exception): + """Not called: no budget, one it would go over, or an unknown price with no Budget line; str(e) says what to write.""" + + +class Meter: + """One run's per-use requests: check() the whole run first, then each request() is held and settled.""" + def __init__(self, project, provider, model, tool, minimax_var=None, env=None): + self.project, self.provider, self.model, self.tool = Path(project), provider, model, tool + self.who = paid(provider, minimax_var) + self.rate = rate(provider, model, env) + self.spent = 0.0 # settled in this run (what the line at the end says) + self.requests = 0 + + def cost(self, text): + return None if "unknown" in self.rate else round(chars(text, self.rate["cjk"]) * self.rate["each"], 6) + + def check(self, texts): + """Before any request: the whole run (texts: each request's text) against the budget. Raises Refused.""" + texts = [t for t in texts if t] + if not texts: + return None + n = sum(chars(t, self.rate["cjk"]) for t in texts) + what = f"{self.tool}: {self.who} · {self.model} · {len(texts)} request(s), about {n:,} characters" + if "unknown" in self.rate: + b = budget.budget_of(self.project) + if b["error"]: + raise Refused(f"{what}: refused: the Budget line in {budget.where_said(b)} has {b['error']}") + if not (b["unlimited"] or any(v > 0 for v in b["amounts"].values())): + raise Refused(f"{what}: refused: it is billed per use and its price is not known here ({self.rate['unknown']}), and " + f"{'the budget is 0' if b['from'] else 'there is no budget'}. Write - Budget: and an amount (or 不限) in " + f"BRIEF.md's Spec to allow it; each request is then recorded as cost not known, maybe billed") + return None + total = round(sum(self.cost(t) for t in texts), 6) + c = budget.check(self.project, total, self.rate["currency"]) + if not c["ok"]: + raise Refused(f"{what} at {self.rate['price']}: {c['message']}") + return c + + @contextlib.contextmanager + def request(self, text, what): + """One request: held at its estimate, then settled. The body calls r.billed(n) with the characters the answer says + were billed, r.billed() when it says nothing (the estimate), r.not_billed() for an error answer or a request that + never left, r.maybe() for one that timed out and is tried again; leaving with any other exception keeps the + estimate as spent too. Both of those say it may have been billed.""" + r = _Request() + what = f"{self.who} {self.model}: {what}" + if "unknown" in self.rate: + try: + yield r + finally: + if not r.unbilled: + budget.spend(self.project, 0, self.rate["currency"], f"{what}: cost not known, maybe billed ({self.rate['unknown']})", tool=self.tool) + self.requests += 1 + return + est = self.cost(text) + with budget.hold(self.project, est, self.rate["currency"], what, tool=self.tool) as h: + try: + yield r + except BaseException: + if r.unbilled: + h.settle(0) + else: + self.spent += est; self.requests += 1 + self._maybe(est) + raise + if r.unbilled: + h.settle(0) + return + if r.doubt: + self._maybe(est) + cost = est if r.count is None or r.doubt else round(r.count * self.rate["each"], 6) + h.settle(cost) + self.spent += cost; self.requests += 1 + + def _maybe(self, est): + print(f" a request may have been billed: its estimate ({budget.money(est, self.rate['currency'])}) stays as spent; " + f"the provider's usage page says what it was", file=sys.stderr, flush=True) + + def line(self): + """The run's paid requests and the budget, for the end of the run.""" + if not self.requests: + return f" {self.who}: no request billed in this run · {budget.line(self.project)}" + cost = "cost not known, maybe billed" if "unknown" in self.rate else budget.money(round(self.spent, 6), self.rate["currency"]) + return (f" {self.who}: {self.requests} request(s), {cost} · {budget.line(self.project)}" + + (f"\n ({UPPER})" if self.rate.get("upper") else "")) + + +class _Request: + def __init__(self): + self.count, self.unbilled, self.doubt = None, False, False + + def billed(self, count=None): + self.count = count if isinstance(count, int) and not isinstance(count, bool) and count >= 0 else None + + def not_billed(self): + self.unbilled = True + + def maybe(self): + self.doubt = True + + +def main(argv): + rows = [{"provider": p, "endpoint": ep, "model": m, "price": v, "per": t["per"], "currency": t["currency"], "chinese_character": t["cjk"], + "page": t["page"], "checked": CHECKED} for (p, ep), t in PRICES.items() for m, v in t["models"].items()] + if argv == ["--json"]: + print(json.dumps({"version": 1, "checked": CHECKED, "prices": rows}, ensure_ascii=False, indent=1)) + return 0 + if argv: + print(__doc__.strip().splitlines()[-1].strip(), file=sys.stderr) + return 2 + print(f"per-use voices (read {CHECKED}; a Chinese character counts as the page says):") + for r in rows: + print(f" {r['provider']:<10} {r['endpoint']:<13} {r['model']:<24} {budget.money(r['price'], r['currency'])} per {r['per']:,} {r['page']}") + return 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv[1:])) diff --git a/tools/audio/tts.py b/tools/audio/tts.py index fdcdc8d3..83c17e99 100644 --- a/tools/audio/tts.py +++ b/tools/audio/tts.py @@ -94,8 +94,16 @@ a transcript the second check is skipped, and that is said. Auditions (bin/vh voices audition): the same text in each voice → /.wav and /audition.json (pitch median, speech rate, and with --align gemini what the transcript disagrees with), for a review page. - -Providers (API keys come from environment variables only, never from files): +Billed per use (elevenlabs, dashscope, and minimax with MINIMAX_API_KEY alone): not called without a budget, like a + generated picture: the film's Budget line in BRIEF.md, else 默认预算 in LOCAL.md (tools/assets/budget.py). After + the key check and before any request or anything deleted, the run's estimate (its characters × the provider's + price, tools/audio/speechcost.py) is checked: no budget, or one it would go over, and nothing is called, said with + what to write. Each request is held, then settled at what the answer says was billed (ElevenLabs': the estimate, + an upper bound), in the film's assets/spend.jsonl; the run ends with a line of what it spent. An audition reads + the budget of the film its text file is in, and refuses a text in no film. Local voices, edge, gemini and the + Token Plan key are used as before. + +Providers (an API key: the environment's, else the one saved in Studio's settings, tools/keys.py; never a file): qwen DEFAULT. Local open-source Qwen3-TTS (Apache-2.0) on Apple Silicon via mlx-audio, offline and free. Model: QWEN_TTS_MODEL (default mlx-community/Qwen3-TTS-12Hz-0.6B-CustomVoice-8bit, ~2 GB download on first use). Voices — zh: Serena (warm female, default), Vivian, Uncle_Fu, Dylan (Beijing), @@ -105,8 +113,9 @@ edge Microsoft Edge online voices via the unofficial edge-tts package (free; may break). dashscope Cloud Qwen3-TTS on Alibaba Cloud Model Studio (阿里云百炼): DASHSCOPE_API_KEY, DASHSCOPE_TTS_MODEL (default qwen3-tts-flash), voice e.g. Cherry, DASHSCOPE_BASE_URL (intl). + Billed per use: needs the film's budget (below). elevenlabs ELEVENLABS_API_KEY; --voice ; ELEVENLABS_MODEL (default eleven_multilingual_v2); - returns character-level timing. + returns character-level timing. Billed per use: needs the film's budget (below). gemini Google Gemini 3.8 Flash TTS (gemini-3.8-flash-tts, released 2026-09-23): GEMINI_API_KEY from Google AI Studio. Free tier (its content may be used to improve Google products) and paid tier: $0.50 / 1M text tokens in, $9 / 1M audio tokens out (≈ $0.00225 per 10 s) through 2026-12-31, doubling to $1 / $18 @@ -124,7 +133,8 @@ 2026-12-31, $1 / $12 from 2027-01-01; for bulk single-speaker narration. minimax MiniMax T2A v2 (speech-2.8-hd) on the international platform, POST https://api.minimax.io/v1/t2a_v2. Key: MINIMAX_TOKEN_PLAN_KEY (Token Plan subscription key, spends its credits) first, else MINIMAX_API_KEY - (pay-as-you-go: "1008 insufficient balance" when the account has no balance). The China host + (pay-as-you-go: "1008 insufficient balance" when the account has no balance; billed per use, so with this + key alone it needs the film's budget, below). The China host api.minimaxi.com rejects international keys (2049); a China-platform key (platform.minimaxi.com) needs MINIMAX_BASE_URL=https://api.minimaxi.com. --voice: a system voice id (default zh "Chinese (Mandarin)_Reliable_Executive", en "English_expressive_narrator"; @@ -143,7 +153,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, re, shutil, signal, subprocess, sys, tempfile, time, unicodedata +import argparse, base64, contextlib, difflib, hashlib, json, os, re, shutil, signal, socket, subprocess, sys, tempfile, time, unicodedata import urllib.error, urllib.parse, urllib.request, wave from concurrent.futures import Future, ThreadPoolExecutor from pathlib import Path @@ -153,6 +163,7 @@ import keys # noqa: E402 an API key: the environment's, else the one saved in Studio's settings (tools/keys.py) RESUME = None # what a stop keeps for a resume, once a line is on disk +METER = None # a run billed per use: its requests held against the film's budget (tools/audio/speechcost.py) SR = 48000 GEMINI_API = "https://generativelanguage.googleapis.com/v1beta" @@ -280,6 +291,37 @@ 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 ---------- +PER_USE = ("minimax", "elevenlabs", "dashscope") # billed per use (minimax: with MINIMAX_API_KEY only): tools/audio/speechcost.py + +def paid_model(provider): + """The model a per-use provider is asked for (what its price is looked up by).""" + return {"minimax": os.environ.get("MINIMAX_TTS_MODEL", "speech-2.8-hd"), "elevenlabs": os.environ.get("ELEVENLABS_MODEL", "eleven_multilingual_v2"), + "dashscope": os.environ.get("DASHSCOPE_TTS_MODEL", "qwen3-tts-flash")}[provider] + +def metered(project, provider, tool): + """A speechcost.Meter when this provider bills this run per use (minimax: only with MINIMAX_API_KEY), else None.""" + if provider not in PER_USE: + return None + import speechcost + var = minimax_key()[1] if provider == "minimax" else None + return speechcost.Meter(project, provider, paid_model(provider), tool, var) if speechcost.paid(provider, var) else None + +class _Free: # a request nobody bills per use: nothing to record + def billed(self, count=None): pass + def not_billed(self): pass + def maybe(self): pass + +def billing(text, out): + """One provider request: held against the budget and settled (speechcost.Meter.request) when the run is billed per use.""" + if METER is None: + return contextlib.nullcontext(_Free()) + m = re.match(r"^\.(.+)\.part(\.\w+)$", out.name) # into_place's name for the take being made + return METER.request(text, m.group(1) + m.group(2) if m else out.name) + +def never_sent(e): + """A request that never left (refused, no such host): nothing was billed.""" + return isinstance(getattr(e, "reason", None), (ConnectionRefusedError, socket.gaierror)) + 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"]} @@ -365,11 +407,20 @@ def p_edge(text, voice, out: Path, tmp: Path, lang, instruct=None): def p_elevenlabs(text, voice, out: Path, tmp: Path, lang, instruct=None): key = keys.get("ELEVENLABS_API_KEY") or no_key("elevenlabs") voice = voice or sys.exit("--voice is required for elevenlabs") - body = json.dumps({"text": text, "model_id": os.environ.get("ELEVENLABS_MODEL", "eleven_multilingual_v2")}).encode() + body = json.dumps({"text": text, "model_id": paid_model("elevenlabs")}).encode() req = urllib.request.Request(f"https://api.elevenlabs.io/v1/text-to-speech/{voice}/with-timestamps?output_format=mp3_44100_128", data=body, headers={"xi-api-key": key, "Content-Type": "application/json"}) - with urllib.request.urlopen(req, timeout=120) as r: - resp = json.loads(r.read()) + with billing(text, out) as bill: # the answer does not say what it billed: the estimate + try: + with urllib.request.urlopen(req, timeout=120) as r: + resp = json.loads(r.read()) + except urllib.error.HTTPError: + bill.not_billed(); raise + except urllib.error.URLError as e: + if never_sent(e): + bill.not_billed() + raise + bill.billed() mp3 = tmp / "el.mp3"; mp3.write_bytes(base64.b64decode(resp["audio_base64"])); to_wav(mp3, out) a = resp.get("alignment") or {} return char_words(a.get("characters", []), a.get("character_start_times_seconds", []), a.get("character_end_times_seconds", [])) @@ -389,13 +440,23 @@ def p_dashscope(text, voice, out: Path, tmp: Path, lang, instruct=None): key = keys.get("DASHSCOPE_API_KEY") or no_key("dashscope") if os.environ.get("DASHSCOPE_BASE_URL"): dashscope.base_http_api_url = os.environ["DASHSCOPE_BASE_URL"] - resp = dashscope.MultiModalConversation.call( - model=os.environ.get("DASHSCOPE_TTS_MODEL", "qwen3-tts-flash"), api_key=key, text=text, - voice=voice or "Cherry", language_type="Chinese" if lang.startswith("zh") else "English", stream=False) - url = resp.output.audio.url if getattr(resp, "output", None) else sys.exit(f"dashscope error: {resp}") + with billing(text, out) as bill: + resp = dashscope.MultiModalConversation.call( + model=paid_model("dashscope"), api_key=key, text=text, + voice=voice or "Cherry", language_type="Chinese" if lang.startswith("zh") else "English", stream=False) + if not getattr(resp, "output", None): # an error answer: nothing synthesized + bill.not_billed(); sys.exit(f"dashscope error: {resp}") + bill.billed(_field(getattr(resp, "usage", None), "characters")) # usage.characters: what the answer says was billed + url = resp.output.audio.url raw = tmp / "ds.wav"; urllib.request.urlretrieve(url, raw); to_wav(raw, out) return None +def _field(o, k): # a field of the DashScope SDK's answer: a dict that also takes attributes + try: + return o[k] + except (KeyError, TypeError, IndexError): + return getattr(o, k, None) + def gemini_model(provider): return os.environ.get("GEMINI_TTS_MODEL", "gemini-3.8-flash-lite-tts" if provider == "gemini-lite" else "gemini-3.8-flash-tts") @@ -494,10 +555,12 @@ def _minimax_get(url, timeout, tries=3): raise MinimaxError(f"minimax: could not download the subtitles: {e}") time.sleep(3 * (k + 1)) -def minimax_tts(text, voice, lang, emotion=None, timeout=600, tries=3): +def minimax_tts(text, voice, lang, emotion=None, timeout=600, tries=3, out=None): """T2A v2 (platform.minimax.io/docs/api-reference/speech-t2a-http), one non-streaming request → (WAV bytes, the subtitle file's items). The key travels in the Authorization header only. 1000, 1001, 1002 and 1039, 5xx and - network errors are retried twice; any other error fails at once, with a hint for a rejected key or no balance.""" + network errors are retried twice; any other error fails at once, with a hint for a rejected key or no balance. + With the pay-as-you-go key every attempt is held against the budget (billing) and settled at the answer's + extra_info.usage_characters; an error status or an HTTP error at 0; a timeout keeps the estimate.""" key, var = minimax_key() if not key: no_key("minimax") @@ -507,7 +570,7 @@ def minimax_tts(text, voice, lang, emotion=None, timeout=600, tries=3): vs = {"voice_id": voice, **minimax_settings(), "text_normalization": True} if emotion: vs["emotion"] = emotion - body = {"model": os.environ.get("MINIMAX_TTS_MODEL", "speech-2.8-hd"), "text": text, "stream": False, "voice_setting": vs, + body = {"model": paid_model("minimax"), "text": text, "stream": False, "voice_setting": vs, "audio_setting": {"sample_rate": 44100, "format": "wav", "channel": 1}, "language_boost": "Chinese" if lang.startswith("zh") else "English", "subtitle_enable": True, "subtitle_type": "word", "output_format": "hex"} @@ -518,24 +581,37 @@ def minimax_tts(text, voice, lang, emotion=None, timeout=600, tries=3): last = k == tries - 1 req = urllib.request.Request(url, data=json.dumps(body).encode(), headers={"Authorization": f"Bearer {key}", "Content-Type": "application/json"}) - try: - with urllib.request.urlopen(req, timeout=timeout) as r: - resp = json.loads(r.read()) - except urllib.error.HTTPError as e: - if e.code >= 500 and not last: - time.sleep(3 * (k + 1)); continue - raise MinimaxError(f"minimax HTTP {e.code}: {e.read()[:BODY_SHOW].decode(errors='replace')}") - except (urllib.error.URLError, TimeoutError) as e: - if not last: - time.sleep(3 * (k + 1)); continue - raise MinimaxError(f"minimax: {e}") - br = resp.get("base_resp") or {} - code = br.get("status_code") - if code in MINIMAX_RETRY and not last: - time.sleep((10 if code in (1002, 1039) else 3) * (k + 1)); continue - if code != 0: - hint = minimax_hint(code, base) - raise MinimaxError(f"minimax error {code}: {br.get('status_msg')} (key from {var})" + (f"; {hint}" if hint else "")) + wait = None + with billing(text, out or Path("minimax.wav")) as bill: # each attempt is a request of its own + try: + with urllib.request.urlopen(req, timeout=timeout) as r: + resp = json.loads(r.read()) + except urllib.error.HTTPError as e: + bill.not_billed() + if e.code < 500 or last: + raise MinimaxError(f"minimax HTTP {e.code}: {e.read()[:BODY_SHOW].decode(errors='replace')}") + wait = 3 * (k + 1) + except (urllib.error.URLError, TimeoutError) as e: # a timeout may have been billed: its estimate stays + if never_sent(e): + bill.not_billed() + elif not last: + bill.maybe() + if last: + raise MinimaxError(f"minimax: {e}") + wait = 3 * (k + 1) + else: + br = resp.get("base_resp") or {} + code = br.get("status_code") + if code != 0: # an error status: nothing synthesized + bill.not_billed() + if code not in MINIMAX_RETRY or last: + hint = minimax_hint(code, base) + raise MinimaxError(f"minimax error {code}: {br.get('status_msg')} (key from {var})" + (f"; {hint}" if hint else "")) + wait = (10 if code in (1002, 1039) else 3) * (k + 1) + else: + bill.billed((resp.get("extra_info") or {}).get("usage_characters")) + if wait: + time.sleep(wait); continue d = resp.get("data") or {} if not d.get("audio") or not d.get("subtitle_file"): raise MinimaxError(f"minimax: no audio or no subtitle file in the response: {json.dumps(resp)[:300]}") @@ -584,7 +660,7 @@ def minimax_words(subs, text): def p_minimax(text, voice, out: Path, tmp: Path, lang, instruct=None): text = split_pauses(text)[1] # a mark must sit between two spoken words voice = voice or ("Chinese (Mandarin)_Reliable_Executive" if lang.startswith("zh") else "English_expressive_narrator") - audio, subs = minimax_tts(text, voice, lang, minimax_emotion(instruct)) + audio, subs = minimax_tts(text, voice, lang, minimax_emotion(instruct), out=out) raw = tmp / "mm.wav"; raw.write_bytes(audio); to_wav(raw, out) words = minimax_words(subs, strip_tags(text, reactions=False)) # prepare() already dropped backchannels if words is None: @@ -1151,13 +1227,31 @@ def audition(a): 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: " + keys.stopping(KEY_OF["minimax"], "voice", "nothing was synthesized")) + if a.provider in ("elevenlabs", "dashscope") and not keys.get(KEY_OF[a.provider][0]): + sys.exit("voices audition: " + keys.stopping(KEY_OF[a.provider], "voice", "nothing was synthesized")) + plain = strip_tags(raw) # what is counted and compared + spoken = PAUSES.sub(_pause, raw) if gemini else strip_tags(raw, pauses=False) if a.provider == "minimax" else plain + units, unit = _units(plain, lang), ("chars/s" if lang == "zh" else "syll/s") + global METER + METER = None + if a.provider in PER_USE: # billed per use: the film's budget, after the key + import speechcost + var = minimax_key()[1] if a.provider == "minimax" else None + if speechcost.paid(a.provider, var): + film = speechcost.film_of(src) + if film is None: + sys.exit(f"voices audition: --provider {a.provider} is billed per use ({speechcost.paid(a.provider, var)}), and {src} is in no" + f" film's folder (no BRIEF.md at or above it): no budget allows it and nothing records it. Put the text in the" + f" film's folder; nothing was synthesized") + METER = metered(film, a.provider, "bin/vh voices audition") + try: + METER.check([spoken] * len(voices)) + except speechcost.Refused as e: + sys.exit(f"voices audition: {e}; nothing was synthesized") try: import voicefeat except ImportError: sys.exit("voices audition measures the takes with numpy: run it as bin/vh voices audition") - plain = strip_tags(raw) # what is counted and compared - spoken = PAUSES.sub(_pause, raw) if gemini else strip_tags(raw, pauses=False) if a.provider == "minimax" else plain - units, unit = _units(plain, lang), ("chars/s" if lang == "zh" else "syll/s") out = Path(a.out) if a.out else src.with_name(f"audition-{src.stem}"); out.mkdir(parents=True, exist_ok=True) rows, bad = [], 0 with tempfile.TemporaryDirectory() as td: @@ -1186,6 +1280,8 @@ def audition(a): (out / "audition.json").write_text(json.dumps(rep, ensure_ascii=False, indent=1), encoding="utf-8") print(f"→ {out}/audition.json and {sum('file' in r for r in rows)} WAV(s)" + ("" if a.align in ("gemini", "local") else " · misread words: --align gemini (or local) transcribes each take")) + if METER: + print(METER.line()) sys.exit(1 if bad else 0) # ---------- main ---------- @@ -1322,6 +1418,24 @@ def linked(texts): # one minimax request: the lines linked by a pause mark of if size > MINIMAX_MAX_CHARS: # before the last take is deleted sys.exit(f"minimax: the request from @{first} would be {size} characters, over the limit of {MINIMAX_MAX_CHARS}: " + {"all": "use --join block (blank lines in script.txt split it)", "block": "split that block with a blank line"}.get(join, "split the line")) + global METER + METER = None if voiced else metered(proj, a.provider, "bin/vh tts") # billed per use: the budget, after the key (no use without one) + if METER: # the whole run against it, before anything is deleted or sent + to_send = lambda s: strip_tags(spoken(s), reactions, pauses=a.provider != "minimax") # what prepare() gives these providers + kept = lambda f: a.resume and f.exists() and (f.with_suffix(".words.json").exists() or not timed) # the loops' own test + whole = lambda blk: (linked([to_send(s) for s in blk]) if timed else ("" if a.lang == "zh" else " ").join(to_send(s) for s in blk)) + if join == "none": + todo = [to_send(s) for i, s in enumerate(segs) if not kept(vo / f"{i+1:02d}.wav")] + elif a.candidates > 1: # N takes of each block not made yet + todo = [whole(blk) for bi, blk in enumerate(blocks) if not (a.resume and (vo / f"_block{bi+1:02d}.wav").exists()) + for c in range(a.candidates) if not kept(vo / f"_block{bi+1:02d}.c{c+1}.wav")] + else: + todo = [whole(blk) for bi, blk in enumerate(blocks) if not kept(vo / f"_block{bi+1:02d}.wav")] + import speechcost + try: + METER.check(todo) + except speechcost.Refused as e: + sys.exit(str(e)) if not a.resume: shutil.rmtree(vo, ignore_errors=True); vo.mkdir(parents=True) grids = {} @@ -1665,6 +1779,8 @@ def take(part): if trimmed > 0.05: print(f" trimmed {trimmed:.2f} s of provider silence at line edges (--keep-edges to keep it)") print(f"→ {joined.relative_to(proj)} ({tl['duration']}s) · audio/timeline.{a.lang}.json · captions: bin/vh captions {a.project}") + if METER: + print(METER.line()) activity.note(f"{len(segs)} line(s), {tl['duration']} s, {a.provider} {a.voice or ''}".rstrip(), [joined, audio / f"timeline.{a.lang}.json"]) import timeline_lint # the checks captions and pace rely on: say now what they would refuse later if (lint := timeline_lint.lint(tl, a.lang)): diff --git a/tools/ci.sh b/tools/ci.sh index 8cb9e17b..b0ac4639 100755 --- a/tools/ci.sh +++ b/tools/ci.sh @@ -6427,10 +6427,243 @@ PY image_checks # bin/vh image: so are its pictures, and its spend the budget's library_checks # the sound library's picks: on record in the project's ledger lyria_checks # a generated track: on record, its price the budget's + paid_speech_checks # a voice billed per use: each request held against the budget sound_tools_checks # check's loudness, qa --listen and --picture, beats --check cast_checks # bin/vh cast: the references image gen sends with --ref cast: } +paid_speech_checks() { # a voice billed per use (tools/audio/speechcost.py, through tools/audio/tts.py): ElevenLabs, DashScope + # and MiniMax with the pay-as-you-go key alone are held against the film's budget, from stand-in answers (no network, + # no key): no budget and nothing is called or deleted (the key said first when both are missing); the Token Plan key + # and the free providers are not metered; each request held, then settled at what the answer says was billed (MiniMax's + # usage_characters, DashScope's usage.characters; ElevenLabs' estimate, an upper bound, said); an error answer and a + # request that never left at 0, a timeout at its estimate; over the budget, by how much; yuan for China's endpoints; an + # endpoint or model the table lacks needs a Budget line and is recorded as cost not known; end to end, a stand-in T2A + # server and bin/vh tts' end line; an audition outside a film refused + local t p a b rc rc2 + if ! command -v ffmpeg >/dev/null || ! command -v ffprobe >/dev/null; then skip "a voice billed per use" "no ffmpeg"; return; fi + t=$(mktemp -d "${TMPDIR:-/tmp}/vh-ci.XXXXXX"); p="$t/k"; mkdir -p "$p/audio/vo/zh" + printf '# BRIEF\n\n## Spec\n\n' > "$p/BRIEF.md"; printf '卫星飞过去了。\n\n夏天你也在呼气。\n' > "$p/audio/script.txt"; echo keep > "$p/audio/vo/zh/01.wav" + ptts() { env -u MINIMAX_TOKEN_PLAN_KEY -u NO_PROXY -u no_proxy OVH_KEYSTORE=none OVH_LOCAL_MD="$t/none.md" HTTPS_PROXY=http://127.0.0.1:9 HTTP_PROXY=http://127.0.0.1:9 "$@"; } + a=$(ptts env -u MINIMAX_API_KEY python3 "$ROOT/tools/audio/tts.py" "$p" --provider minimax 2>&1); rc=$? + b=$(ptts env MINIMAX_API_KEY=ci python3 "$ROOT/tools/audio/tts.py" "$p" --provider minimax 2>&1); rc2=$? + if [ "$rc:$rc2" = 1:1 ] && case "$a" in *"no MiniMax API Key"*) ! case "$a" in *Budget*) true ;; *) false ;; esac ;; *) false ;; esac \ + && case "$b" in *"MiniMax pay-as-you-go (MINIMAX_API_KEY) · speech-2.8-hd · 2 request(s)"*"no budget"*"write - Budget:"*) true ;; *) false ;; esac \ + && [ "$(cat "$p/audio/vo/zh/01.wav")" = keep ] && [ ! -e "$p/assets" ] + then ok "a voice billed per use: with no key the key is said first, with no budget nothing is called, deleted or recorded and what to write is said" + else bad "a voice billed per use, refused ($rc/$rc2): $a | $b"; fi + a=$(python3 - "$ROOT" "$t/u" <<'PY' 2>&1 +import io, json, os, sys, types, urllib.error, urllib.request +from pathlib import Path + +repo, t = Path(sys.argv[1]).resolve(), Path(sys.argv[2]) +os.environ.update(OVH_KEYSTORE="none", OVH_LOCAL_MD=str(t / "no-LOCAL.md"), MINIMAX_API_KEY="ci-pay-as-you-go", ELEVENLABS_API_KEY="ci-el", DASHSCOPE_API_KEY="ci-ds") +for k in ("MINIMAX_TOKEN_PLAN_KEY", "MINIMAX_BASE_URL", "DASHSCOPE_BASE_URL", "MINIMAX_TTS_MODEL", "ELEVENLABS_MODEL", "DASHSCOPE_TTS_MODEL"): + os.environ.pop(k, None) +sys.path.insert(0, str(repo / "tools/audio")) +import tts, speechcost # noqa: E402 +bad = [] +def want(c, what): + if not c: bad.append(what) +def film(name, budget=None): + p = t / name; (p / "audio").mkdir(parents=True, exist_ok=True) + (p / "BRIEF.md").write_text("# BRIEF\n\n## Spec\n\n" + (f"- Budget: {budget}\n" if budget else ""), encoding="utf-8") + return p +def spend(p): + f = p / "assets/spend.jsonl" + return [json.loads(l) for l in f.read_text().splitlines()] if f.exists() else [] +class Ans(io.BytesIO): + def __enter__(self): return self + def __exit__(self, *a): return False +calls = [] +def answer(seq): # urlopen stand-in: each call takes the next item (a dict → JSON, bytes, or an exception) + def urlopen(req, timeout=None): + calls.append(getattr(req, "full_url", req)) + x = seq.pop(0) + if isinstance(x, BaseException): raise x + return Ans(x if isinstance(x, bytes) else json.dumps(x).encode()) + urllib.request.urlopen = urlopen +tts.time.sleep = lambda s: None +text = "卫星飞过去了。Satellites pass." # 6 Han characters (2 each) + 17 others = 29 characters billed +want(speechcost.chars(text, 2) == 29 and speechcost.chars(text, 1) == 23, f"chars: {speechcost.chars(text, 2)} {speechcost.chars(text, 1)}") +ok_mm = {"base_resp": {"status_code": 0}, "data": {"audio": "00", "subtitle_file": "https://x/s.json"}, "extra_info": {"usage_characters": 26}} + +# 1 no budget: refused before anything, saying what to write +p = film("none") +tts.METER = tts.metered(p, "minimax", "bin/vh tts") +try: + tts.METER.check([text]); bad.append("no budget did not refuse") +except speechcost.Refused as e: + want("no budget" in str(e) and "Budget:" in str(e) and "MiniMax pay-as-you-go" in str(e), f"no budget said: {e}") +want(spend(p) == [], "a refusal wrote to the spend log") + +# 2 the Token Plan key: not per use, no meter +os.environ["MINIMAX_TOKEN_PLAN_KEY"] = "ci-plan" +want(tts.metered(p, "minimax", "bin/vh tts") is None, "the Token Plan key was metered") +del os.environ["MINIMAX_TOKEN_PLAN_KEY"] +want(all(tts.metered(p, x, "t") is None for x in ("qwen", "say", "edge", "gemini", "gemini-lite")), "a free provider was metered") + +# 3 a budget: held, settled at usage_characters × $100 per million +p = film("ok", "$1") +tts.METER = tts.metered(p, "minimax", "bin/vh tts"); tts.METER.check([text]) +answer([ok_mm, b"[]"]) +tts.minimax_tts(text, "v", "zh", out=Path(".01.part.wav")) +s = spend(p) +want([x["kind"] for x in s] == ["hold", "settle"] and abs(s[0]["amount"] - 0.0029) < 1e-9 and abs(s[1]["amount"] - 0.0026) < 1e-9 + and "01.wav" in s[1]["what"] and s[1]["tool"] == "bin/vh tts", f"held and settled: {s}") +# 4 an error status: settled at 0, the error raised +answer([{"base_resp": {"status_code": 1004, "status_msg": "auth"}}]) +try: + tts.minimax_tts(text, "v", "zh", out=Path(".02.part.wav")); bad.append("1004 did not raise") +except tts.MinimaxError: + pass +want(spend(p)[-1]["kind"] == "settle" and spend(p)[-1]["amount"] == 0, f"an error status not settled at 0: {spend(p)[-1]}") +# 5 a timeout, then the retry answers: the timed-out attempt keeps its estimate, the retry settles at what was billed +answer([TimeoutError("timed out"), ok_mm, b"[]"]) +tts.minimax_tts(text, "v", "zh", out=Path(".03.part.wav")) +st = [x for x in spend(p) if x["kind"] == "settle"][-2:] +want([round(x["amount"], 6) for x in st] == [0.0029, 0.0026] and st[0]["hold"] != st[1]["hold"], f"timeout then retry: {st}") +# 6 a request that never left: 0 +answer([urllib.error.URLError(ConnectionRefusedError(61, "refused"))] * 3) +try: + tts.minimax_tts(text, "v", "zh", out=Path(".04.part.wav"), tries=1); bad.append("refused did not raise") +except tts.MinimaxError: + pass +want(spend(p)[-1]["amount"] == 0, f"never sent not 0: {spend(p)[-1]}") +# 7 over the budget: refused, saying by how much +p2 = film("small", "$0.001") +m = tts.metered(p2, "minimax", "bin/vh tts") +try: + m.check([text]); bad.append("over the budget did not refuse") +except speechcost.Refused as e: + want("short" in str(e) and "$0.0019" in str(e), f"over said: {e}") +# 8 a China-platform key: yuan, ¥3.5 per 10,000 +os.environ["MINIMAX_BASE_URL"] = "https://api.minimaxi.com" +m = tts.metered(p, "minimax", "bin/vh tts") +want(m.rate["currency"] == "CNY" and abs(m.cost(text) - 0.01015) < 1e-9, f"China platform: {m.rate}") +try: + m.check([text]); bad.append("a USD budget took a CNY call") +except speechcost.Refused as e: + want("no CNY" in str(e), f"currency: {e}") +# 9 an address the table does not know: cost not known, needs a Budget line, recorded so +os.environ["MINIMAX_BASE_URL"] = "http://127.0.0.1:9" +tts.METER = tts.metered(p, "minimax", "bin/vh tts") +tts.METER.check([text]) +answer([ok_mm, b"[]"]); tts.minimax_tts(text, "v", "zh", out=Path(".05.part.wav")) +want("cost not known, maybe billed" in spend(p)[-1]["what"] and spend(p)[-1]["amount"] == 0, f"unknown: {spend(p)[-1]}") +try: + tts.metered(film("none2"), "minimax", "t").check([text]); bad.append("unknown cost with no budget was allowed") +except speechcost.Refused as e: + want("not known" in str(e), f"unknown refused: {e}") +del os.environ["MINIMAX_BASE_URL"] + +# 10 ElevenLabs: settled at the estimate (an upper bound, said); an HTTP error at 0 +tts.to_wav = lambda src, dst: Path(dst).write_bytes(b"") +p = film("el", "$1") +tts.METER = tts.metered(p, "elevenlabs", "bin/vh tts"); tts.METER.check([text]) +answer([{"audio_base64": "", "alignment": {}}]) +tts.p_elevenlabs(text, "voice", Path(t / ".01.part.wav"), t, "zh") +s = spend(p) +want(abs(s[-1]["amount"] - 23 * 0.08 / 1000) < 1e-9, f"elevenlabs at the estimate: {s[-1]}") +want("upper bound" in tts.METER.line() and "1 request(s)" in tts.METER.line(), f"elevenlabs line: {tts.METER.line()}") +answer([urllib.error.HTTPError("u", 401, "no", {}, io.BytesIO(b"{}"))]) +try: + tts.p_elevenlabs(text, "voice", Path(t / ".02.part.wav"), t, "zh"); bad.append("401 did not raise") +except urllib.error.HTTPError: + pass +want(spend(p)[-1]["amount"] == 0, f"elevenlabs 401 not 0: {spend(p)[-1]}") + +# 11 DashScope (Beijing, yuan): settled at usage.characters × ¥0.8 per 10,000; an error answer at 0 +fake = types.ModuleType("dashscope") +class MMC: + nxt = None + @staticmethod + def call(**kw): return MMC.nxt +fake.MultiModalConversation = MMC; sys.modules["dashscope"] = fake +urllib.request.urlretrieve = lambda url, dst: Path(dst).write_bytes(b"") +p = film("ds", "¥1") +tts.METER = tts.metered(p, "dashscope", "bin/vh tts"); tts.METER.check([text]) +MMC.nxt = types.SimpleNamespace(output=types.SimpleNamespace(audio=types.SimpleNamespace(url="https://x/a.wav")), usage={"characters": 30}) +tts.p_dashscope(text, "Cherry", Path(t / ".01.part.wav"), t, "zh") +want(abs(spend(p)[-1]["amount"] - 30 * 0.8 / 10000) < 1e-9 and spend(p)[-1]["currency"] == "CNY", f"dashscope: {spend(p)[-1]}") +MMC.nxt = types.SimpleNamespace(output=None, status_code=400, message="bad") +try: + tts.p_dashscope(text, "Cherry", Path(t / ".02.part.wav"), t, "zh"); bad.append("a DashScope error did not exit") +except SystemExit: + pass +want(spend(p)[-1]["amount"] == 0, f"dashscope error not 0: {spend(p)[-1]}") +tts.METER = None +print("ok" if not bad else "BAD " + " | ".join(bad)) +PY +) + case "$a" in *ok) ok "a voice billed per use: held and settled at what the answer billed (ElevenLabs at its estimate, an upper bound, said), errors and never-sent at 0, a timeout at its estimate, over the budget by how much, yuan for China's endpoints, the Token Plan key and the free providers not metered, an unknown endpoint needs a Budget line" ;; + *) bad "a voice billed per use, the requests: $(printf '%s' "$a" | tail -c 900)" ;; esac + a=$(python3 - "$ROOT" "$t/e" <<'PY' 2>&1 +# table does not have: cost not known), and bin/vh voices audition outside a film. usage: python3 p1_cli.py [vh] +import io, json, math, os, re, struct, subprocess, sys, threading, wave +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from pathlib import Path + +repo, t = Path(sys.argv[1]).resolve(), Path(sys.argv[2]); vh = [sys.executable, str(repo / "tools/audio/tts.py")] +hits = [] +def tone(): + b = io.BytesIO(); w = wave.open(b, "wb"); w.setnchannels(1); w.setsampwidth(2); w.setframerate(48000) + w.writeframes(b"".join(struct.pack("", "", body["text"]) + words = [{"word": ch, "time_begin": 20 * i, "time_end": 20 * i + 18} for i, ch in enumerate(txt) if not ch.isspace()] + ans = {"base_resp": {"status_code": 0}, "data": {"audio": tone().hex(), "subtitle_file": f"http://127.0.0.1:{srv.server_port}/subs.json"}, + "extra_info": {"usage_characters": len(txt)}} + self._send(ans, words) + def do_GET(self): + txt = hits[-1] if hits else "" + self._send([{"text": txt, "time_begin": 0, "time_end": 500, + "timestamped_words": [{"word": ch, "time_begin": 20 * i, "time_end": 20 * i + 18} for i, ch in enumerate(re.sub(r"<#[\d.]+#>", "", txt)) if not ch.isspace()]}]) + def _send(self, obj, _=None): + b = json.dumps(obj).encode(); self.send_response(200); self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(b))); self.end_headers(); self.wfile.write(b) +srv = ThreadingHTTPServer(("127.0.0.1", 0), H); threading.Thread(target=srv.serve_forever, daemon=True).start() +env = {k: v for k, v in os.environ.items() if k not in ("MINIMAX_TOKEN_PLAN_KEY", "NO_PROXY", "no_proxy", "HTTPS_PROXY", "HTTP_PROXY", "https_proxy", "http_proxy")} +env.update(OVH_KEYSTORE="none", OVH_LOCAL_MD=str(t / "no-LOCAL.md"), MINIMAX_API_KEY="ci-pay-as-you-go", MINIMAX_BASE_URL=f"http://127.0.0.1:{srv.server_port}") +p = t / "film"; (p / "audio").mkdir(parents=True, exist_ok=True) +(p / "BRIEF.md").write_text("# BRIEF\n\n## Spec\n\n", encoding="utf-8") +(p / "audio/script.txt").write_text("卫星飞过去了。\n\n夏天你也在呼气。\n", encoding="utf-8") +bad = [] +def tts(*args): + return subprocess.run(vh + [str(p), "--provider", "minimax", *args], capture_output=True, text=True, env=env) +r = tts() +if r.returncode != 1 or "not known here" not in r.stderr + r.stdout or hits: + bad.append(f"unknown cost, no budget: rc {r.returncode}, {len(hits)} request(s): {(r.stderr + r.stdout)[-300:]}") +with open(p / "BRIEF.md", "a", encoding="utf-8") as f: + f.write("- Budget: 不限\n") +r = tts() +spend = [json.loads(l) for l in (p / "assets/spend.jsonl").read_text().splitlines()] if (p / "assets/spend.jsonl").exists() else [] +if r.returncode != 0 or len(hits) != 2 or [x["kind"] for x in spend] != ["payment", "payment"] \ + or not all("cost not known, maybe billed" in x["what"] and x["tool"] == "bin/vh tts" for x in spend) \ + or "2 request(s), cost not known, maybe billed" not in r.stdout or not (p / "audio/voiceover.zh.wav").exists(): + bad.append(f"unknown cost, 不限: rc {r.returncode}, {len(hits)} request(s), spend {spend}: {(r.stderr + r.stdout)[-400:]}") +n = len(hits); r = tts("--resume") +if r.returncode != 0 or len(hits) != n: + bad.append(f"--resume with every line voiced made a request or failed: {len(hits) - n} {(r.stderr + r.stdout)[-300:]}") +# voices audition: a text outside any film is refused before a request +(t / "loose.txt").write_text("卫星飞过去了。\n", encoding="utf-8") +n = len(hits) +a = subprocess.run(vh + ["voices", "audition", "--provider", "minimax", "--voices", "a,b", "--text", str(t / "loose.txt")], capture_output=True, text=True, env=env) +if a.returncode != 1 or "in no film's folder" not in a.stderr + a.stdout or len(hits) != n: + bad.append(f"audition outside a film: rc {a.returncode}: {(a.stderr + a.stdout)[-300:]}") +srv.shutdown() +print("ok" if not bad else "BAD " + " | ".join(bad)) +PY +) + case "$a" in *ok) ok "a voice billed per use, end to end: a stand-in T2A server, cost not known needs a Budget line, two requests on record, the run's end line, --resume asks nothing more; an audition outside a film refused" ;; + *) bad "a voice billed per use, end to end: $(printf '%s' "$a" | tail -c 900)" ;; esac + rm -rf "$t" +} + cast_checks() { # bin/vh cast (tools/cast.py): a project's settled references, one folder an entry, and image gen # --ref cast: (dry runs, and a replay of a recorded answer with --offline: nothing is sent, nothing spent) local t p a b c d rc rc2 rc3 rc4 rc5 rc6 diff --git a/tools/commands.json b/tools/commands.json index 31779b46..522ffec2 100644 --- a/tools/commands.json +++ b/tools/commands.json @@ -1634,12 +1634,14 @@ "stages": ["4"], "reads": [ "/audio/script.txt", - "a cloud provider's key, from the environment or Studio's settings (tools/keys.py)" + "a cloud provider's key, from the environment or Studio's settings (tools/keys.py)", + "for a voice billed per use (elevenlabs, dashscope, minimax with MINIMAX_API_KEY alone): the film's Budget (BRIEF.md, else LOCAL.md)" ], "writes": [ "/audio/voiceover..wav", "/audio/timeline..json", - "/audio/vo//NN.wav" + "/audio/vo//NN.wav", + "/assets/spend.jsonl (a voice billed per use: each request held, then settled)" ], "usage": [ { @@ -1650,7 +1652,8 @@ "--candidates N: N takes a block, the one nearest the narration's median voice kept (N × the synthesis);", "warns of a line far off the take's seconds per character, and (with --align) of a phrase heard twice;", "--resume: continue the last run after a failed synthesis or transcription, same script and command)", - "providers: qwen (default, local open-source Qwen3-TTS; its first use downloads about 2.6 GB, said first, with the progress) | say | edge | dashscope | elevenlabs | gemini | gemini-lite | minimax" + "providers: qwen (default, local open-source Qwen3-TTS; its first use downloads about 2.6 GB, said first, with the progress) | say | edge | dashscope | elevenlabs | gemini | gemini-lite | minimax;", + "billed per use (dashscope, elevenlabs, minimax with MINIMAX_API_KEY alone): not called without the film's budget, the run's estimate checked first (prices: python3 tools/audio/speechcost.py)" ] } ] @@ -1689,10 +1692,12 @@ "stages": ["4", "3"], "reads": [ "--text f.txt (audition)", - "the provider's key, from the environment or Studio's settings (tools/keys.py)" + "the provider's key, from the environment or Studio's settings (tools/keys.py)", + "a voice billed per use: the Budget of the film the text file is in" ], "writes": [ "--out dir: a WAV per voice and audition.json (audition)", + "the film's assets/spend.jsonl (an audition with a voice billed per use)", "--out f.wav (design)" ], "usage": [ diff --git a/tools/desk/static/settings.js b/tools/desk/static/settings.js index 5489b76d..3ec5da72 100644 --- a/tools/desk/static/settings.js +++ b/tools/desk/static/settings.js @@ -44,7 +44,7 @@ const SETTINGS = (() => { e_not_kept: "没存进去:{s}没收下。再粘贴一次试试;还是不行,就照说明写进终端启动时读的文件。", e_not_cleared: "没拿掉:{s}没响应。再试一次。", s_keychain: "钥匙串", s_secret: "密码库", sv_env_note: "在终端里设的环境变量,这一页不一定看得到;在这里填上的,终端里和右边的对话里都用得上。", - sv_budget: "有 API Key 不等于有预算。出图和 Lyria 作曲,片子和这台电脑都没写预算就不调;用这几家配音、给字幕对时间、试音,是直接调用,花的是那个账户的钱(有免费额度的先用免费额度)。这台电脑的默认预算:{x}", + sv_budget: "有 API Key 不等于有预算。出图、Lyria 作曲和按次计费的配音(MiniMax 按量付费、ElevenLabs、阿里云百炼),片子和这台电脑都没写预算就不调;本机的声音、Gemini(先用免费额度)和 MiniMax 的 Token Plan key 照旧用。这台电脑的默认预算:{x}", nokey: "这一页要在 Studio 的窗口里打开才看得到。", reopen: "在 Studio 窗口里打开", }, en: { @@ -85,7 +85,7 @@ const SETTINGS = (() => { e_not_kept: "Not saved: {s} didn't take it. Paste it again; if it still fails, put it in the file your terminal reads when it starts.", e_not_cleared: "Not removed: {s} didn't answer. Try again.", s_keychain: "the Keychain", s_secret: "the password store", sv_env_note: "Environment variables set in your terminal may not show on this page; a key set here works in the terminal and in the chat on the right.", - sv_budget: "An API Key isn't a budget. Pictures and Lyria music are not made unless the film or this computer has a budget; voices, caption timing and auditions with these services are called directly and bill that account (a free tier is used first). This computer's default budget: {x}", + sv_budget: "An API Key isn't a budget. Pictures, Lyria music and voices billed per use (MiniMax pay-as-you-go, ElevenLabs, Alibaba Cloud Model Studio) are not made unless the film or this computer has a budget; this computer's own voices, Gemini (its free tier first) and MiniMax's Token Plan key are used as before. This computer's default budget: {x}", nokey: "This page shows only in Studio's own window.", reopen: "Open in Studio's window", }, }; From 6e68fddc3e698f2c09d2d665ad5ccfba3f1cbc91 Mon Sep 17 00:00:00 2001 From: zhanglinghao Date: Sun, 22 Nov 2026 17:06:53 +0800 Subject: [PATCH 2/9] ci: words_checks reads L8 in the report's line-number column only (a temp folder's name could hold L8 and fail the run) --- tools/ci.sh | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tools/ci.sh b/tools/ci.sh index b0ac4639..273ebed6 100755 --- a/tools/ci.sh +++ b/tools/ci.sh @@ -4910,7 +4910,7 @@ words_checks() { # bin/vh words (tools/words.py): a report on a script's sente local t t=$(mktemp -d "${TMPDIR:-/tmp}/vh-ci.XXXXXX") if python3 - "$t" "$VH_BASH" <<'PY' -import json, os, subprocess, sys +import json, os, re, subprocess, sys t, sh = sys.argv[1], sys.argv[2] def w(path, text): os.makedirs(os.path.dirname(path), exist_ok=True) @@ -4969,7 +4969,7 @@ j = json.loads(vh(p, "--json", "--all").stdout) if [h.get("allowed_by", "").endswith("STYLE.md") for h in next(c for c in j["checks"] if c["id"] == "not_but")["hits"]] != [True]: bad.append("--all does not list the allowed hit with where it was allowed") txt = vh(p).stdout -if "L9 答案很简单:频率在变" not in txt or "L8" in txt or "allowed by the style guide" not in txt or "not checked:" not in txt: +if "L9 答案很简单:频率在变" not in txt or re.search(r"^\s*L8\s", txt, re.M) or "allowed by the style guide" not in txt or "not checked:" not in txt: # L8: the line-number column (a temp path may hold "L8") bad.append(f"the text report: {txt[:400]!r}") q = os.path.join(t, "q") # no SCRIPT.md: what the voice reads w(f"{q}/audio/script.txt", "# a comment: 不是这个,而是那个\n@speakers A=Kore B=Puck\n@a [轻快,不是指示,而是语气] A: 先看这里。 || not this, but that\n@b 卫星飞过去了。 || 不是英文,而是中文\n@c 与其说是速度,不如说是时间。\n") From 0b0e2fca14db668516ba0f10f8ed0ed175338f3f Mon Sep 17 00:00:00 2001 From: zhanglinghao Date: Sun, 22 Nov 2026 17:07:15 +0800 Subject: [PATCH 3/9] ci: the Studio app check reads how the app ended without its window's 'lost' line (the stream's own thread can note it after quit) --- tools/ci.sh | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tools/ci.sh b/tools/ci.sh index 273ebed6..eea254e9 100755 --- a/tools/ci.sh +++ b/tools/ci.sh @@ -4562,7 +4562,8 @@ starts = [e for e in ev if e["event"] == "start"] want(len(starts) == 1 and not starts[0]["code_in_argv"], f"the app started {len(starts)} times, or with a code on its command line: {starts}") want(kinds.count("window") == 1 and kinds.count("raised") >= 3 and "claimed" in kinds and "present" in kinds, f"one window, raised after: {kinds}") want(any(e["event"] == "told" and e["data"].get("go", "").startswith("/p/demo~") for e in ev), "the window was not sent to the film") -want(kinds[-2:] == ["closed", "quit"] or kinds[-1] == "quit", f"the console stopped, the app did not close its window and quit: {kinds[-3:]}") +end = [k for k in kinds if k != "lost"] # a window's stream ending (lost) can be noted after quit: its own thread, a race +want(end[-2:] == ["closed", "quit"] or end[-1] == "quit", f"the console stopped, the app did not close its window and quit: {kinds[-3:]}") want("Studio is open in its own window" in a and "its window is in front" in b and two.count("its window is in front") == 2, f"said: {a!r} | {b!r} | {two!r}") want("Studio is open in a browser window (Studio's own app did not open)" in c, f"an app that cannot start: {c!r}") want("Studio is open in a browser window (Studio's own app no longer finds OpenVideoHarness where it was installed: ask your agent to put the Studio icon back)" in m From 652ad88be0ecdc63fea0cfac6f55835f0eb46f00 Mon Sep 17 00:00:00 2001 From: zhanglinghao Date: Sun, 22 Nov 2026 17:09:00 +0800 Subject: [PATCH 4/9] Page tools start a browser once more when the first did not start (no answer within 60 s, or gone before one); a program that is not there is not tried again --- changes/browser-start-once-more.md | 3 +++ tools/ci.sh | 21 +++++++++++++++++++++ tools/textcheck/browser.mjs | 22 ++++++++++++++++++---- 3 files changed, 42 insertions(+), 4 deletions(-) create mode 100644 changes/browser-start-once-more.md diff --git a/changes/browser-start-once-more.md b/changes/browser-start-once-more.md new file mode 100644 index 00000000..d753456f --- /dev/null +++ b/changes/browser-start-once-more.md @@ -0,0 +1,3 @@ +**页面工具起浏览器时,没起来的那一次再起一个** +- Why: 机器忙的时候,Chrome 冷启动偶尔 60 秒都没回第一句话,`bin/vh readcheck --export` 这类命令就整个失败;紧接着再起一次,通常马上就回。 +- 页面工具(textcheck、readcheck 的导出、frames、render 等)起的浏览器,60 秒没回第一句话,或者回话之前就退出了,就关掉它、再起一个,并且说一句;第二个也没起来才报错。找不到浏览器程序的,不再试。 diff --git a/tools/ci.sh b/tools/ci.sh index eea254e9..852194e9 100755 --- a/tools/ci.sh +++ b/tools/ci.sh @@ -11064,6 +11064,27 @@ const b = await launch(process.argv[1]); const t0 = Date.now(); const r = await Promise.race([b.close().then(() => "closed"), new Promise((ok) => setTimeout(() => ok("hung"), 30000))]); console.log(r, Math.round((Date.now() - t0) / 1000)); process.exit(0);' "$t/stuck" 2>&1) case "$a" in "closed "[0-9]|"closed 1"[0-9]) ok "browser: one that ignores Browser.close and SIGTERM is killed, and close() returns ($a s)" ;; *) bad "browser close on a stuck browser: $a" ;; esac + # a browser that did not start (gone before its first answer here; no answer within 60 s on a busy runner) is started + # once more, said; one that never starts fails after the second; a program that is not there is not tried again + printf '%s\n' 'import json, os, sys' 'mark = sys.argv[1]' \ + 'if not os.path.exists(mark): open(mark, "w").close(); sys.exit(1)' \ + 'buf = b""' 'while True:' ' d = os.read(3, 65536)' ' if not d: break' ' buf += d' \ + ' while b"\0" in buf:' ' raw, buf = buf.split(b"\0", 1); m = json.loads(raw)' \ + ' r = {"Browser.getVersion": {"product": "Stub/1"}, "Target.createTarget": {"targetId": "t1"}, "Target.attachToTarget": {"sessionId": "s1"}}.get(m["method"], {})' \ + ' os.write(4, json.dumps({"id": m["id"], "result": r}).encode() + b"\0")' \ + ' if m["method"] == "Browser.close": sys.exit(0)' > "$t/late.py" + printf '#!/bin/sh\nexec python3 "%s" "%s"\n' "$t/late.py" "$t/late.started" > "$t/late"; printf '#!/bin/sh\nexit 1\n' > "$t/never"; chmod +x "$t/late" "$t/never" + a=$(node --input-type=module -e 'import { launchTab } from "./tools/textcheck/browser.mjs"; +for (const exe of process.argv.slice(1)) { + try { const { browser, sessionId } = await launchTab(exe, [], ["Page"]); console.log("TAB", sessionId); await browser.close(); } + catch (e) { console.log("FAILED", e.message.slice(0, 60)); } +}' "$t/late" "$t/never" "$t/no-such-browser" 2>&1) + case "$a" in "the browser did not start (the browser is gone (exit 1)): starting another +TAB s1 +the browser did not start (the browser is gone (exit 1)): starting another +FAILED the browser is gone (exit 1) +FAILED the browser is gone (ENOENT)"*) ok "browser: one that did not start is started once more (said), one that never starts fails after the second, a program not there is not tried again" ;; + *) bad "browser start, once more: $a" ;; esac a=$(vh frames tools/film/fixture --at 5 --out "$t/e" 2>&1); rc=$? case "$rc:$a" in 2:*"outside the film"*) ok "frames: a time outside the film exits 2" ;; *) bad "frames outside the film: exit $rc: $(printf '%s' "$a" | tail -c 600)" ;; esac if command -v ffmpeg >/dev/null; then diff --git a/tools/textcheck/browser.mjs b/tools/textcheck/browser.mjs index 7a2b8698..cdb728dd 100644 --- a/tools/textcheck/browser.mjs +++ b/tools/textcheck/browser.mjs @@ -70,7 +70,7 @@ export async function launch(exe, flags = []) { proc.stderr.on("data", (d) => { stderr = (stderr + d).slice(-4000); }); const out = proc.stdio[3], inp = proc.stdio[4]; const pending = new Map(), waiters = [], listeners = []; - let chunks = [], id = 0, dead = null, started = false; + let chunks = [], id = 0, dead = null, started = false, unspawned = false; // a browser that exits or crashes fails every call still waiting, so nothing hangs until the watchdog const gone = (why) => { if (dead) return; @@ -82,7 +82,7 @@ export async function launch(exe, flags = []) { }; const exited = new Promise((res) => { proc.on("exit", (code, sig) => { gone(sig || `exit ${code}`); res(); }); - proc.on("error", (e) => { stderr += String(e); gone(e.code || "error"); res(); }); + proc.on("error", (e) => { stderr += String(e); unspawned = true; gone(e.code || "error"); res(); }); // no such program, not runnable }); out.on("error", (e) => gone(e.code || "pipe error")); inp.on("error", (e) => gone(e.code || "pipe error")); @@ -143,7 +143,11 @@ export async function launch(exe, flags = []) { // 60 s: a cold start on a busy CI runner has taken over 30 (a rerun of the same code passed) version = await within(send("Browser.getVersion"), 60000, () => new Error("the browser did not answer within 60 s")); started = true; - } catch (e) { killGroup(proc); await within(exited, 3000); removeProfile(); if (!LIVE.size) disarm(); throw e; } // a Chrome that never answered may ignore SIGTERM + } catch (e) { // a Chrome that never answered may ignore SIGTERM + killGroup(proc); await within(exited, 3000); removeProfile(); if (!LIVE.size) disarm(); + e.notStarted = !unspawned; // it ran but never answered, or was gone first: launchTab starts another, once + throw e; + } return { send, once, on, close, version: version.product }; } @@ -153,11 +157,21 @@ export async function launch(exe, flags = []) { // at a time, none of 3550 for chrome-headless-shell. Then not even a browser-wide command answers, and only a new browser // helps. Without a limit here a tool with no watchdog of its own (render's workers) would wait for ever. const TAB_TRIES = 3; +// A browser that did not start (no answer to its first command within 60 s, or gone before one) is started once more: +// a busy CI runner's cold start has missed the 60 s once where the next start answered at once +const START_TRIES = 2; class NoAnswer extends Error {} export async function launchTab(exe, flags, domains) { const TAB_ANSWER_S = Math.max(30, Number(process.env.OVH_PAGE_TIMEOUT) || 0); // a slow machine's way to give it longer, never less for (let n = 1; ; n++) { - const browser = await launch(exe, flags); + let browser; + for (let k = 1; ; k++) { + try { browser = await launch(exe, flags); break; } + catch (e) { + if (!e.notStarted || k === START_TRIES) throw e; + console.error(`the browser did not start (${e.message}): starting another`); + } + } const answer = (method, params, session) => { let timer; return Promise.race([browser.send(method, params, session), new Promise((_, no) => { timer = setTimeout(() => no(new NoAnswer(`${method} had no answer within ${TAB_ANSWER_S} s`)), TAB_ANSWER_S * 1000); })]).finally(() => clearTimeout(timer)); From 2b513252e7c842b5014e19d8287a90a5ca72e8bc Mon Sep 17 00:00:00 2001 From: zhanglinghao Date: Sun, 22 Nov 2026 17:47:42 +0800 Subject: [PATCH 5/9] ci and the artifact table after the budget gate: tts and voices write and read spend.jsonl; the older tts checks run with a budget, or the Token Plan key, as a voice billed per use now needs; the fake minimax_tts takes out= --- tools/artifacts.json | 6 +++--- tools/ci.sh | 9 +++++---- 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/tools/artifacts.json b/tools/artifacts.json index 9ad7a9a3..f6070e42 100644 --- a/tools/artifacts.json +++ b/tools/artifacts.json @@ -964,8 +964,8 @@ "stages": ["6", "9"], "purpose": "花钱的记录,一行一笔,只追加", "made_by": "tool", - "writers": ["image", "assets", "music"], - "readers": ["assets", "status", "review", "image", "music"], + "writers": ["image", "assets", "music", "tts", "voices"], + "readers": ["assets", "status", "review", "image", "music", "tts", "voices"], "required": null, "version_key": "v", "schema": null, @@ -1136,7 +1136,7 @@ "stages": ["any"], "purpose": "几条命令同时记付费调用时的文件锁;内容没有意义", "made_by": "tool", - "writers": ["image", "assets", "music"], + "writers": ["image", "assets", "music", "tts", "voices"], "readers": ["clean"], "required": null, "version_key": null, diff --git a/tools/ci.sh b/tools/ci.sh index 5df0e454..30ec32c6 100755 --- a/tools/ci.sh +++ b/tools/ci.sh @@ -1286,8 +1286,9 @@ PY if [ -z "$a" ] && [ "$(cat "$t/nk/audio/voiceover.wav")" = take ] && [ ! -e "$t/nk/audio/vo" ]; then ok "tts: a provider with no key says the key it needs and what works with none, before anything is fetched or the last take deleted" else bad "tts with no key:$a"; fi # --resume with every line voiced asks the provider nothing, so it needs no key; with one left it does (the run is made with a - # key and no dashscope package, which fails after writing _run.json) + # key, a budget and no dashscope package, which fails after writing _run.json) if command -v ffmpeg >/dev/null; then + printf -- '- Budget: ¥1\n' >> "$t/nk/BRIEF.md" # dashscope is billed per use: no budget, and it stops before _run.json b=$(PATH="$t/nkbin:$PATH" DASHSCOPE_API_KEY=ci python3 "$ROOT/tools/audio/tts.py" "$t/nk" --provider dashscope 2>&1); rc=$? c=$(env -u DASHSCOPE_API_KEY python3 "$ROOT/tools/audio/tts.py" "$t/nk" --provider dashscope --resume 2>&1); r2=$? ffmpeg -v error -f lavfi -i 'sine=d=0.4:r=24000' -y "$t/nk/audio/vo/zh/01.wav" @@ -1467,8 +1468,8 @@ with tempfile.TemporaryDirectory() as d: # minimax gives its own word times (a stand-in for its API: a burst per character, 0.15 s, or 0.24 s every other take, and # its subtitles): with --candidates, the other take copied over _block01.wav is cut by that take's own words file, and # a take that is no candidate of the block stops the run (no --align gemini to cut it by), saying so - os.environ["MINIMAX_API_KEY"] = "ci-stub"; mm = {"n": 0} - def fake_mm(text, voice, lang, emotion): + os.environ["MINIMAX_TOKEN_PLAN_KEY"] = "ci-stub"; mm = {"n": 0} # the Token Plan key: not billed per use, so no budget asked + def fake_mm(text, voice, lang, emotion, **kw): b = 0.24 if mm["n"] % 2 else 0.15; mm["n"] += 1 x, subs, t = [np.zeros(int(0.05 * SR))], [], 0.05 for part in re.split(r"(<#[\d.]+#>)", text): @@ -6587,7 +6588,7 @@ want(spend(p) == [], "a refusal wrote to the spend log") # 2 the Token Plan key: not per use, no meter os.environ["MINIMAX_TOKEN_PLAN_KEY"] = "ci-plan" want(tts.metered(p, "minimax", "bin/vh tts") is None, "the Token Plan key was metered") -del os.environ["MINIMAX_TOKEN_PLAN_KEY"] +os.environ["MINIMAX_TOKEN_PLAN_KEY"] = "" # empty: not set (tools/keys.py) want(all(tts.metered(p, x, "t") is None for x in ("qwen", "say", "edge", "gemini", "gemini-lite")), "a free provider was metered") # 3 a budget: held, settled at usage_characters × $100 per million From c0249cfdf7df0fa1f51b613c86e58d43b743f05e Mon Sep 17 00:00:00 2001 From: zhanglinghao Date: Sun, 22 Nov 2026 17:58:10 +0800 Subject: [PATCH 6/9] CLAUDE.md: a voice billed per use needs a budget like any paid call; a key comes from the environment or the one saved in Studio The two sentences the maintainer approved: the baseline bullet's last sentence (bin/vh tts, music and voices on local, subscription or free quota as before; MiniMax pay-as-you-go, ElevenLabs and DashScope under the budget) and hard rule 7 (the environment, or the key Studio's settings page keeps in the system's password store, both through tools/keys.py). AGENTS.md regenerated; playbook/05's line on keys says the same. --- AGENTS.md | 4 ++-- CLAUDE.md | 4 ++-- playbook/05-hybrid-genvideo.md | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index a0adeae2..86f089b8 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -40,7 +40,7 @@ - 全屏闪白每秒不超过 3 次; - 字号不低于 BRIEF"在哪看"那一档的下限(`playbook/03-motion-design.md` §4); - 素材许可要记清:用 `bin/vh assets add` 登记,`bin/vh assets check` 自查; -- 付费接口(生图、生视频、按次计费的配音或作曲、买素材)要有预算:BRIEF 的 `Budget:` 和 `LOCAL.md` 的默认预算都没写就不调;用户写一个数或 `不限` 就算授权,对话里说的先写进 BRIEF;会超出的那一次不调,停下说清还差多少。现有的 `bin/vh tts`、`music`、`voices` 走本地、订阅或配额,照旧用; +- 付费接口(生图、生视频、按次计费的配音或作曲、买素材)要有预算:BRIEF 的 `Budget:` 和 `LOCAL.md` 的默认预算都没写就不调;用户写一个数或 `不限` 就算授权,对话里说的先写进 BRIEF;会超出的那一次不调,停下说清还差多少。`bin/vh tts`、`music`、`voices` 走本地、订阅或免费配额的照旧用;按次计费的配音(MiniMax 按量付费、ElevenLabs、阿里云百炼)和其他付费接口一样要有预算; - `TASTE_CHECKLIST.md` 里标【底线】的条目:安全框、读时(够快读一遍;从容多少跟 BRIEF 的 `Pace` 走,是口味)、字号、字不被光烧白、reads 不被盖掉、循环接缝、分镜里声明的卡点、没有占位和编造; - 出片前跑一次 `bin/vh check <成片或项目目录>`(给目录时查最新的一支,并说是哪支)。 @@ -116,7 +116,7 @@ 4. **检查实际结果。** 新做和改过的部分连同受影响的交界重点查,没动的抽查;按要查的问题取联系表(整体)、逐帧 strip(切点和动作)或 crop(脸和细节),对照 `TASTE_CHECKLIST.md`。整片 draft 还要过清单里的打分层:换一个全新上下文的严苛 reviewer,按 8 个维度(含立意)打分;做几轮、怎样算过线按档位(`playbook/01-pipeline.md` 的"努力程度":`standard` 1 轮,修最重要的至多 3 处,不设分数线;`studio` 做工五项都 ≥ 7 才出片),轮数有上限。检查成本很低,不要省。 5. **事实有纪律。** 论文元数据、数字、引文一律照抄原文;拿不准的写进 `NOTES.md`,不编进视频。发布文案(标题、简介、章节)也算,交付前同样逐条对过。 6. **做片子时只改这支片子自己的文件夹。** 它在 `projects/` 下,或者在用户点名的目录里(`bin/vh new … --dir`)。`engines/` 是模板,`references/repos/` 是只读参考;需要时复制到自己的项目里再改。用户要你改的是仓库本身(`bin/vh`、`tools/`、文档)时,不归这一条管,按文末的"改本仓库本身"来。 -7. **不在文件里写 API key。** 一律从环境变量读取;缺 key 时告诉用户需要哪个。 +7. **不在文件里写 API key。** key 从环境变量读,或者用 Studio 设置页存进系统钥匙串的那一份(都经 `tools/keys.py`);缺 key 时告诉用户需要哪个。 ## 规则冲突时 diff --git a/CLAUDE.md b/CLAUDE.md index 25540d68..78de2b0c 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -37,7 +37,7 @@ - 全屏闪白每秒不超过 3 次; - 字号不低于 BRIEF"在哪看"那一档的下限(`playbook/03-motion-design.md` §4); - 素材许可要记清:用 `bin/vh assets add` 登记,`bin/vh assets check` 自查; -- 付费接口(生图、生视频、按次计费的配音或作曲、买素材)要有预算:BRIEF 的 `Budget:` 和 `LOCAL.md` 的默认预算都没写就不调;用户写一个数或 `不限` 就算授权,对话里说的先写进 BRIEF;会超出的那一次不调,停下说清还差多少。现有的 `bin/vh tts`、`music`、`voices` 走本地、订阅或配额,照旧用; +- 付费接口(生图、生视频、按次计费的配音或作曲、买素材)要有预算:BRIEF 的 `Budget:` 和 `LOCAL.md` 的默认预算都没写就不调;用户写一个数或 `不限` 就算授权,对话里说的先写进 BRIEF;会超出的那一次不调,停下说清还差多少。`bin/vh tts`、`music`、`voices` 走本地、订阅或免费配额的照旧用;按次计费的配音(MiniMax 按量付费、ElevenLabs、阿里云百炼)和其他付费接口一样要有预算; - `TASTE_CHECKLIST.md` 里标【底线】的条目:安全框、读时(够快读一遍;从容多少跟 BRIEF 的 `Pace` 走,是口味)、字号、字不被光烧白、reads 不被盖掉、循环接缝、分镜里声明的卡点、没有占位和编造; - 出片前跑一次 `bin/vh check <成片或项目目录>`(给目录时查最新的一支,并说是哪支)。 @@ -113,7 +113,7 @@ 4. **检查实际结果。** 新做和改过的部分连同受影响的交界重点查,没动的抽查;按要查的问题取联系表(整体)、逐帧 strip(切点和动作)或 crop(脸和细节),对照 `TASTE_CHECKLIST.md`。整片 draft 还要过清单里的打分层:换一个全新上下文的严苛 reviewer,按 8 个维度(含立意)打分;做几轮、怎样算过线按档位(`playbook/01-pipeline.md` 的"努力程度":`standard` 1 轮,修最重要的至多 3 处,不设分数线;`studio` 做工五项都 ≥ 7 才出片),轮数有上限。检查成本很低,不要省。 5. **事实有纪律。** 论文元数据、数字、引文一律照抄原文;拿不准的写进 `NOTES.md`,不编进视频。发布文案(标题、简介、章节)也算,交付前同样逐条对过。 6. **做片子时只改这支片子自己的文件夹。** 它在 `projects/` 下,或者在用户点名的目录里(`bin/vh new … --dir`)。`engines/` 是模板,`references/repos/` 是只读参考;需要时复制到自己的项目里再改。用户要你改的是仓库本身(`bin/vh`、`tools/`、文档)时,不归这一条管,按文末的"改本仓库本身"来。 -7. **不在文件里写 API key。** 一律从环境变量读取;缺 key 时告诉用户需要哪个。 +7. **不在文件里写 API key。** key 从环境变量读,或者用 Studio 设置页存进系统钥匙串的那一份(都经 `tools/keys.py`);缺 key 时告诉用户需要哪个。 ## 规则冲突时 diff --git a/playbook/05-hybrid-genvideo.md b/playbook/05-hybrid-genvideo.md index 7b4aafc1..688efc8b 100644 --- a/playbook/05-hybrid-genvideo.md +++ b/playbook/05-hybrid-genvideo.md @@ -413,7 +413,7 @@ done ## 风险 - **片段拼接**:单次上限按模型:Seedance 2.5 和 Wan 3.0 30 s,Veo 3.1 8 s(可延长),Kling 3.0 15 s,Runway Gen-4.5 10 s。拼接处跨镜头的一致性差,切点尽量放在动作中途或转场处。 -- **API key**:一律从环境变量读取(例如 `FAL_KEY`、`ELEVENLABS_API_KEY`),不写进文件。 +- **API key**:从环境变量读取(例如 `FAL_KEY`、`ELEVENLABS_API_KEY`);`tools/modules.json` 里列的服务,也可以用 Studio 设置页存进系统钥匙串的那一份。都不写进文件。 ## 数字人和口播 From cef42c432430d5ea14bd63a294406f8706400382 Mon Sep 17 00:00:00 2001 From: zhanglinghao Date: Sun, 22 Nov 2026 18:16:10 +0800 Subject: [PATCH 7/9] Review of #236: an unlisted model is priced as its endpoint's most expensive one; the estimate is of the body as sent, every character that is not ASCII as 2 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - A model the price table lacks, on an endpoint it has, is priced as that endpoint's most expensive model, with the usual hold and settle, said to be assumed; model names match whatever their case. Only an unknown endpoint (a proxy, a stand-in) is still "cost not known", and each of its requests is still recorded. - The estimate counts the body each request carries (tts.body_of: MiniMax's pause marks as rewritten), and where a Chinese character counts as 2 every non-ASCII character does (〇, full-width punctuation, kana): an upper bound. - Checks: a no-budget refusal from the command line for elevenlabs and dashscope too (nothing deleted, exit 1); --candidates N counted in the run's estimate; the body as sent; the unlisted model, a name in another case, the count. - Docs: LOCAL.md's default counts for an unknown endpoint; minimax.cn as well as minimaxi.com; the refusal exits 1; the gate goes by the key's name. --- changes/paid-speech-budget.md | 2 +- tools/audio/README.md | 8 ++--- tools/audio/speechcost.py | 41 ++++++++++++--------- tools/audio/tts.py | 16 ++++++--- tools/ci.sh | 68 ++++++++++++++++++++++++++++------- 5 files changed, 96 insertions(+), 39 deletions(-) diff --git a/changes/paid-speech-budget.md b/changes/paid-speech-budget.md index 8074a857..ae8a2793 100644 --- a/changes/paid-speech-budget.md +++ b/changes/paid-speech-budget.md @@ -2,7 +2,7 @@ - Why: Studio 设置页存的 key 现在每条命令都读得到,Studio 对话里的 agent 也能调这几家收费的配音;出图和 Lyria 作曲早就要预算,配音还是直接调用、花账户的钱。 - `bin/vh tts` 和 `bin/vh voices audition` 用 `elevenlabs`、`dashscope`,或者只有按量付费 key(`MINIMAX_API_KEY`)的 `minimax` 时,先读片子的预算(BRIEF 的 `Budget:`,没有再看 `LOCAL.md` 的默认预算)。没有预算、预算是 0,或者这次会超出,就不调,说清要写什么、还差多少;这一步在发出第一个请求、删掉旧配音之前。缺 key 和缺预算都有时,先说缺 key。 - 每个请求先按字数占住估价,回答回来按它报的计费字数结账(MiniMax 的 `usage_characters`、百炼的 `usage.characters`),记进片子的 `assets/spend.jsonl`;结束时多一行:几个请求、花了多少、预算还剩多少。ElevenLabs 的回答不报字数,按估价记,是上限(套餐里含的字数不按次扣),那一行和账上都写明。报错的回答和没发出去的请求记 0;超时的保留估价,并且说可能已经扣了。 -- 价格照各家价格页(2026-11-22 读,页面地址写在 `tools/audio/speechcost.py` 里,`python3 tools/audio/speechcost.py` 列出):MiniMax 国际站 speech-2.8-hd 每百万字符 $100、turbo $60,国内站每万字符 ¥3.5、¥2;ElevenLabs 多语种 v2 每千字符 $0.08;百炼 qwen3-tts-flash 北京每万字符 ¥0.8、新加坡 $0.1。MiniMax 和百炼一个汉字算 2 个字符。表里没有的模型或接入点,只要有不为 0 的预算就调,记成"价钱不知道,可能已扣费"。 +- 价格照各家价格页(2026-11-22 读,页面地址写在 `tools/audio/speechcost.py` 里,`python3 tools/audio/speechcost.py` 列出):MiniMax 国际站 speech-2.8-hd 每百万字符 $100、turbo $60,国内站每万字符 ¥3.5、¥2;ElevenLabs 多语种 v2 每千字符 $0.08;百炼 qwen3-tts-flash 北京每万字符 ¥0.8、新加坡 $0.1。MiniMax 和百炼的页面说一个汉字算 2 个字符,这里所有非 ASCII 字符都按 2 个算,估价只多不少。表里没有的模型按同一接入点最贵的模型算,并说明是估的;表里没有的接入点(比如代理),只要有不为 0 的预算就调,记成"价钱不知道,可能已扣费"。 - 试音按文本文件所在的片子读预算、记账;文本不在任何片子里时不调。 - 照旧用,不要预算:本机的声音(`qwen`、`say`)、不要 key 的 `edge`、Gemini 配音和 `--align gemini`(先用免费额度)、MiniMax 的 Token Plan key(花套餐额度,tts 先用它)。 - 两个预算占位在同一毫秒里时,记账的编号以前会重,结掉一个会把另一个也当成结了;编号现在加了一个计数。 diff --git a/tools/audio/README.md b/tools/audio/README.md index 9e156fd7..7b1ca04b 100644 --- a/tools/audio/README.md +++ b/tools/audio/README.md @@ -195,12 +195,12 @@ MINIMAX_TTS_SPEED=1.25 bin/vh tts projects/

minimax - zh --join all --gap 0.3 和生图、Lyria 一样,这几家按字数计费,没有预算就不调:`bin/vh tts` 和 `bin/vh voices audition` 用 `elevenlabs`、`dashscope`,或者只有 `MINIMAX_API_KEY`(没有 Token Plan 的 key)的 `minimax` 时,先读片子的预算(BRIEF 的 `Budget:`,没有再看 `LOCAL.md` 的默认预算;预算的写法见 `tools/assets/budget.py`)。 -- **先 key,后预算**:两样都缺时先说缺 key,预算没 key 也用不上; -- **整次先估**:在发出第一个请求、删掉旧配音之前,按这次要合成的句子(`--resume` 只算没做完的,`--candidates N` 算 N 份)估字数和价钱。没有预算、预算是 0,或者超出预算,就不调,说清要在 BRIEF 写什么、还差多少。预算的币种要和计费的币种一样:国际站按美元,国内站(`MINIMAX_BASE_URL` 在 minimaxi.com)和百炼北京(默认)按人民币; +- **先 key,后预算**:两样都缺时先说缺 key,预算没 key 也用不上。拦不拦看 key 设在哪个名字下:设在 `MINIMAX_TOKEN_PLAN_KEY` 下的都当 Token Plan,不拦,所以别把按量付费的 key 存在这个名字下; +- **整次先估**:在发出第一个请求、删掉旧配音之前,按这次要合成的句子(`--resume` 只算没做完的,`--candidates N` 算 N 份)估字数和价钱。没有预算、预算是 0,或者超出预算,就不调,说清要在 BRIEF 写什么、还差多少,退出码 1。预算的币种要和计费的币种一样:国际站按美元,国内站(`MINIMAX_BASE_URL` 在 minimaxi.com 或 minimax.cn)和百炼北京(默认)按人民币; - **每个请求先占后结**:请求发出前按估价占住,回答回来按它报的计费字数结账(MiniMax 的 `extra_info.usage_characters`,百炼的 `usage.characters`)。ElevenLabs 的回答不报字数,按估价结,是上限:套餐里含的字数不按次扣,结尾那行和账上都写明。报错的回答(HTTP 错误、MiniMax 的错误码)和根本没发出去的请求记 0;超时或回答被截断的保留估价,因为可能已经扣了,并且说出来。MiniMax 自己重试的每一次都是一个请求; -- **字数怎么算**:按各家价格页的说法,MiniMax 和百炼一个汉字算 2 个字符(MiniMax 国际站的页面没写,按国内站的算法,取大的),ElevenLabs 每个字符算 1 个; +- **字数怎么算**:数的是请求里实际发出去的文字(MiniMax 的停顿标记照发出去的样子算)。MiniMax 和百炼的价格页说一个汉字算 2 个字符,这里把所有非 ASCII 字符(〇、全角标点、假名也算)都按 2 个算,估出来只会多不会少(MiniMax 国际站的页面没写,按国内站的算法);ElevenLabs 每个字符算 1 个; - **记在哪**:片子的 `assets/spend.jsonl`(`bin/vh assets list`、`bin/vh status` 和审阅页里的预算行都读它)。`bin/vh tts` 结束时多一行:这次几个请求、花了多少、预算还剩多少; -- **价格表**:`python3 tools/audio/speechcost.py` 列出每家、每个接入点、每个模型的价格和出处页(2026-11-22 读)。表里没有的模型(`MINIMAX_TTS_MODEL`、`ELEVENLABS_MODEL`、`DASHSCOPE_TTS_MODEL` 设成别的)或接入点(`MINIMAX_BASE_URL`、`DASHSCOPE_BASE_URL` 指到别处):价钱不知道,只要 BRIEF 有一个不为 0 的预算(一个数或 `不限`)就调,每个请求记成"价钱不知道,可能已扣费"; +- **价格表**:`python3 tools/audio/speechcost.py` 列出每家、每个接入点、每个模型的价格和出处页(2026-11-22 读)。模型名不分大小写。表里没有的模型(`MINIMAX_TTS_MODEL`、`ELEVENLABS_MODEL`、`DASHSCOPE_TTS_MODEL` 设成别的):按同一接入点最贵的那个模型算,照常占住、结账,并说明价钱是估的。表里没有的接入点(`MINIMAX_BASE_URL`、`DASHSCOPE_BASE_URL` 指到别处,比如代理):价钱不知道,只要预算不为 0(BRIEF 的 `Budget:` 或 `LOCAL.md` 的默认预算,一个数或 `不限`)就调,每个请求记成"价钱不知道,可能已扣费"; - **试音**:`bin/vh voices audition` 按文本文件所在的片子(往上找 BRIEF.md)读预算、记账;文本不在任何片子里时不调,说清要放进片子的文件夹。 - **照旧用,不要预算**:本地的 `qwen`、`say`;不要 key 的 `edge`;`gemini`、`gemini-lite` 和 `--align gemini`(先用免费额度);Token Plan 的 key(花套餐额度)。 diff --git a/tools/audio/speechcost.py b/tools/audio/speechcost.py index 58412d79..8a466680 100644 --- a/tools/audio/speechcost.py +++ b/tools/audio/speechcost.py @@ -8,10 +8,10 @@ Used as before, with no budget: qwen and say (on this machine), edge (no key, not billed), gemini, gemini-lite and --align gemini (the free quota first). -The prices (PRICES) are the providers' own pages, read on CHECKED; each entry names its page. Characters are counted as -those pages count them: a Chinese character (Han, kanji, hanja) as 2 for MiniMax and DashScope, every character as 1 for -ElevenLabs. MiniMax's international page does not say how it counts; its China page's rule (2) is used there too, the -larger of the two. +The prices (PRICES) are the providers' own pages, read on CHECKED; each entry names its page; a model's name is matched +whatever its case. Characters are counted in the body a request carries (tts.body_of), as those pages count them, rounded +up: where a Chinese character counts as 2 (MiniMax, DashScope), every character that is not ASCII counts as 2; ElevenLabs +counts each as 1. MiniMax's international page does not say how it counts; its China page's rule is used there too. A run: check() before any request and before anything is deleted (the key comes first: a budget is no use without one) takes the whole run's estimate against the budget; no budget, or one it would go over, and nothing is called, with what to @@ -19,12 +19,14 @@ extra_info.usage_characters, DashScope's usage.characters × the price) or, for ElevenLabs, whose answer says nothing, at the estimate: an upper bound, since characters a plan includes are not billed per use (the record says so). An error answer and a request that never left settle at 0; a timeout or an answer cut off keeps the estimate, as such a request may have -been billed (said). A model or an endpoint the table does not have: called only with a Budget line (an amount or 不限), -and recorded as cost not known, maybe billed. +been billed (said). A model the table does not have, on an endpoint it has: priced as that endpoint's most expensive +model, with the usual hold and settle, and said to be assumed. An endpoint the table does not have (a proxy, a stand-in): +called only with a budget that is not 0 (BRIEF's Budget or LOCAL.md's 默认预算, an amount or 不限), and each request is +recorded as cost not known, maybe billed. python3 tools/audio/speechcost.py [--json] the table: provider, endpoint, model, price, page """ -import contextlib, json, os, re, sys +import contextlib, json, os, sys from pathlib import Path from urllib.parse import urlparse @@ -52,7 +54,6 @@ } NAME = {"minimax": "MiniMax pay-as-you-go (MINIMAX_API_KEY)", "elevenlabs": "ElevenLabs", "dashscope": "Alibaba Cloud Model Studio (DashScope)"} UPPER = "ElevenLabs' answer does not say what it billed: settled at the estimate, an upper bound (characters a plan includes are not billed per use)" -HAN = re.compile(r"[㐀-䶿一-鿿豈-﫿\U00020000-\U0003134f]") def paid(provider, minimax_var=None): @@ -84,8 +85,10 @@ def film_of(path): def chars(text, cjk): - """The characters billed for text: every character once, a Chinese one cjk times.""" - return len(text) + (cjk - 1) * len(HAN.findall(text)) + """The characters billed for the body a request carries. cjk 1: every character once (ElevenLabs). cjk 2 (the pages that + count a Chinese character as 2): every character that is not ASCII as 2, not only Han: 〇, full-width punctuation and + kana too, so the estimate is an upper bound and a budget that passes the check is not run out half way.""" + return len(text) if cjk == 1 else sum(1 if ord(c) < 128 else 2 for c in text) def rate(provider, model, env=None): @@ -97,10 +100,15 @@ def rate(provider, model, env=None): cur = {"minimax": "USD", "dashscope": "CNY", "elevenlabs": "USD"}.get(provider, "USD") where = (env if env is not None else os.environ).get("MINIMAX_BASE_URL" if provider == "minimax" else "DASHSCOPE_BASE_URL") return {"currency": cur, "cjk": 2, "unknown": f"an endpoint the price table does not have ({where})"} - if model not in t["models"]: - return {"currency": t["currency"], "cjk": t["cjk"], "unknown": f"{model} is not in the price table ({t['page']}, read {CHECKED})"} - return {"currency": t["currency"], "each": t["models"][model] / t["per"], "cjk": t["cjk"], "page": t["page"], - "upper": bool(t.get("upper")), "endpoint": ep, "price": f"{budget.money(t['models'][model], t['currency'])} per {t['per']:,} characters"} + known = {m.lower(): m for m in t["models"]} + hit = known.get(str(model).strip().lower()) # speech-2.8-HD is speech-2.8-hd + assumed = None + if hit is None: # a model the table does not have, on a known endpoint: its + hit = max(t["models"], key=t["models"].get) # highest listed price, said, so a budget still holds + assumed = f"{model} is not in the price table ({t['page']}, read {CHECKED}): priced as its most expensive listed model, {hit}" + price = f"{budget.money(t['models'][hit], t['currency'])} per {t['per']:,} characters" + return {"currency": t["currency"], "each": t["models"][hit] / t["per"], "cjk": t["cjk"], "page": t["page"], "upper": bool(t.get("upper")), + "endpoint": ep, "assumed": assumed, "price": price + (" (assumed)" if assumed else "")} class Refused(Exception): @@ -133,7 +141,7 @@ def check(self, texts): if not (b["unlimited"] or any(v > 0 for v in b["amounts"].values())): raise Refused(f"{what}: refused: it is billed per use and its price is not known here ({self.rate['unknown']}), and " f"{'the budget is 0' if b['from'] else 'there is no budget'}. Write - Budget: and an amount (or 不限) in " - f"BRIEF.md's Spec to allow it; each request is then recorded as cost not known, maybe billed") + f"BRIEF.md's Spec (or 默认预算 in LOCAL.md) to allow it; each request is then recorded as cost not known, maybe billed") return None total = round(sum(self.cost(t) for t in texts), 6) c = budget.check(self.project, total, self.rate["currency"]) @@ -148,7 +156,7 @@ def request(self, text, what): never left, r.maybe() for one that timed out and is tried again; leaving with any other exception keeps the estimate as spent too. Both of those say it may have been billed.""" r = _Request() - what = f"{self.who} {self.model}: {what}" + what = f"{self.who} {self.model}: {what}" + (f" (price assumed: {self.rate['assumed']})" if self.rate.get("assumed") else "") if "unknown" in self.rate: try: yield r @@ -187,6 +195,7 @@ def line(self): return f" {self.who}: no request billed in this run · {budget.line(self.project)}" cost = "cost not known, maybe billed" if "unknown" in self.rate else budget.money(round(self.spent, 6), self.rate["currency"]) return (f" {self.who}: {self.requests} request(s), {cost} · {budget.line(self.project)}" + + (f"\n (price assumed: {self.rate['assumed']})" if self.rate.get("assumed") else "") + (f"\n ({UPPER})" if self.rate.get("upper") else "")) diff --git a/tools/audio/tts.py b/tools/audio/tts.py index 83c17e99..bc47d898 100644 --- a/tools/audio/tts.py +++ b/tools/audio/tts.py @@ -657,8 +657,13 @@ def minimax_words(subs, text): prev = t1s[i] return char_words(list(text), t0s, t1s) +def body_of(provider, text): + """The text a provider's request carries, which is what it bills: MiniMax's with its pause marks at the edges dropped + and each run of them merged and rewritten (split_pauses: <#0.5#> goes as <#0.50#>); the others' as given.""" + return split_pauses(text)[1] if provider == "minimax" else text + def p_minimax(text, voice, out: Path, tmp: Path, lang, instruct=None): - text = split_pauses(text)[1] # a mark must sit between two spoken words + text = body_of("minimax", text) # a mark must sit between two spoken words voice = voice or ("Chinese (Mandarin)_Reliable_Executive" if lang.startswith("zh") else "English_expressive_narrator") audio, subs = minimax_tts(text, voice, lang, minimax_emotion(instruct), out=out) raw = tmp / "mm.wav"; raw.write_bytes(audio); to_wav(raw, out) @@ -1245,7 +1250,7 @@ def audition(a): f" film's folder; nothing was synthesized") METER = metered(film, a.provider, "bin/vh voices audition") try: - METER.check([spoken] * len(voices)) + METER.check([body_of(a.provider, spoken)] * len(voices)) except speechcost.Refused as e: sys.exit(f"voices audition: {e}; nothing was synthesized") try: @@ -1422,15 +1427,16 @@ def linked(texts): # one minimax request: the lines linked by a pause mark of METER = None if voiced else metered(proj, a.provider, "bin/vh tts") # billed per use: the budget, after the key (no use without one) if METER: # the whole run against it, before anything is deleted or sent to_send = lambda s: strip_tags(spoken(s), reactions, pauses=a.provider != "minimax") # what prepare() gives these providers + body = lambda x: body_of(a.provider, x) # what the request carries, as the provider bills it kept = lambda f: a.resume and f.exists() and (f.with_suffix(".words.json").exists() or not timed) # the loops' own test whole = lambda blk: (linked([to_send(s) for s in blk]) if timed else ("" if a.lang == "zh" else " ").join(to_send(s) for s in blk)) if join == "none": - todo = [to_send(s) for i, s in enumerate(segs) if not kept(vo / f"{i+1:02d}.wav")] + todo = [body(to_send(s)) for i, s in enumerate(segs) if not kept(vo / f"{i+1:02d}.wav")] elif a.candidates > 1: # N takes of each block not made yet - todo = [whole(blk) for bi, blk in enumerate(blocks) if not (a.resume and (vo / f"_block{bi+1:02d}.wav").exists()) + todo = [body(whole(blk)) for bi, blk in enumerate(blocks) if not (a.resume and (vo / f"_block{bi+1:02d}.wav").exists()) for c in range(a.candidates) if not kept(vo / f"_block{bi+1:02d}.c{c+1}.wav")] else: - todo = [whole(blk) for bi, blk in enumerate(blocks) if not kept(vo / f"_block{bi+1:02d}.wav")] + todo = [body(whole(blk)) for bi, blk in enumerate(blocks) if not kept(vo / f"_block{bi+1:02d}.wav")] import speechcost try: METER.check(todo) diff --git a/tools/ci.sh b/tools/ci.sh index 30ec32c6..5dad69a9 100755 --- a/tools/ci.sh +++ b/tools/ci.sh @@ -6528,18 +6528,39 @@ paid_speech_checks() { # a voice billed per use (tools/audio/speechcost.py, th # request that never left at 0, a timeout at its estimate; over the budget, by how much; yuan for China's endpoints; an # endpoint or model the table lacks needs a Budget line and is recorded as cost not known; end to end, a stand-in T2A # server and bin/vh tts' end line; an audition outside a film refused - local t p a b rc rc2 + local t p a b c d e rc rc2 rc3 rc4 rc5 if ! command -v ffmpeg >/dev/null || ! command -v ffprobe >/dev/null; then skip "a voice billed per use" "no ffmpeg"; return; fi t=$(mktemp -d "${TMPDIR:-/tmp}/vh-ci.XXXXXX"); p="$t/k"; mkdir -p "$p/audio/vo/zh" printf '# BRIEF\n\n## Spec\n\n' > "$p/BRIEF.md"; printf '卫星飞过去了。\n\n夏天你也在呼气。\n' > "$p/audio/script.txt"; echo keep > "$p/audio/vo/zh/01.wav" ptts() { env -u MINIMAX_TOKEN_PLAN_KEY -u NO_PROXY -u no_proxy OVH_KEYSTORE=none OVH_LOCAL_MD="$t/none.md" HTTPS_PROXY=http://127.0.0.1:9 HTTP_PROXY=http://127.0.0.1:9 "$@"; } a=$(ptts env -u MINIMAX_API_KEY python3 "$ROOT/tools/audio/tts.py" "$p" --provider minimax 2>&1); rc=$? b=$(ptts env MINIMAX_API_KEY=ci python3 "$ROOT/tools/audio/tts.py" "$p" --provider minimax 2>&1); rc2=$? - if [ "$rc:$rc2" = 1:1 ] && case "$a" in *"no MiniMax API Key"*) ! case "$a" in *Budget*) true ;; *) false ;; esac ;; *) false ;; esac \ + c=$(ptts env ELEVENLABS_API_KEY=ci python3 "$ROOT/tools/audio/tts.py" "$p" --provider elevenlabs --voice v 2>&1); rc3=$? + d=$(ptts env DASHSCOPE_API_KEY=ci python3 "$ROOT/tools/audio/tts.py" "$p" --provider dashscope 2>&1); rc4=$? + if [ "$rc:$rc2:$rc3:$rc4" = 1:1:1:1 ] && case "$a" in *"no MiniMax API Key"*) ! case "$a" in *Budget*) true ;; *) false ;; esac ;; *) false ;; esac \ && case "$b" in *"MiniMax pay-as-you-go (MINIMAX_API_KEY) · speech-2.8-hd · 2 request(s)"*"no budget"*"write - Budget:"*) true ;; *) false ;; esac \ + && case "$c" in *"ElevenLabs · eleven_multilingual_v2 · 2 request(s)"*"no budget"*"write - Budget:"*) true ;; *) false ;; esac \ + && case "$d" in *"Alibaba Cloud Model Studio (DashScope) · qwen3-tts-flash · 2 request(s)"*"no budget"*"write - Budget: ¥"*) true ;; *) false ;; esac \ && [ "$(cat "$p/audio/vo/zh/01.wav")" = keep ] && [ ! -e "$p/assets" ] - then ok "a voice billed per use: with no key the key is said first, with no budget nothing is called, deleted or recorded and what to write is said" - else bad "a voice billed per use, refused ($rc/$rc2): $a | $b"; fi + then ok "a voice billed per use: with no key the key is said first; with no budget (minimax pay-as-you-go, elevenlabs, dashscope) nothing is called, deleted or recorded, exit 1, and what to write is said" + else bad "a voice billed per use, refused ($rc/$rc2/$rc3/$rc4): $a | $b | $c | $d"; fi + # the estimate is of the body each request carries: a pause mark written <#0.5#> goes as <#0.50#>, one character more, + # so a budget of exactly the text as written ($0.0037 here, $0.0038 as sent) is refused before anything + mkdir -p "$t/m/audio"; printf '# BRIEF\n\n- Budget: $0.0037\n' > "$t/m/BRIEF.md"; printf '卫星<#0.5#>飞过去了。\n\n夏天你也在呼气。\n' > "$t/m/audio/script.txt" + e=$(ptts env MINIMAX_API_KEY=ci python3 "$ROOT/tools/audio/tts.py" "$t/m" --provider minimax 2>&1); rc5=$? + if [ "$rc5" = 1 ] && case "$e" in *"about 38 characters"*"short"*) true ;; *) false ;; esac && [ ! -e "$t/m/assets/spend.jsonl" ] + then ok "a voice billed per use: the estimate counts the body as sent (a pause mark rewritten to two decimals), so a budget for the text as written is refused" + else bad "a voice billed per use, the body as sent (exit $rc5): $e"; fi + # --candidates N: the run's estimate counts N takes of each block (uv for numpy; the dead proxy only inside it, so uv + # can still reach its index): one take of each fits the budget, two do not, so nothing is called or deleted + if command -v uv >/dev/null; then + printf -- '- Budget: $0.004\n' >> "$p/BRIEF.md" # one take of the two blocks: 30 characters, $0.003; two takes: $0.006 + e=$(env -u MINIMAX_TOKEN_PLAN_KEY -u NO_PROXY -u no_proxy OVH_KEYSTORE=none OVH_LOCAL_MD="$t/none.md" MINIMAX_API_KEY=ci uv run -q --no-project --with numpy -- \ + env HTTPS_PROXY=http://127.0.0.1:9 HTTP_PROXY=http://127.0.0.1:9 python "$ROOT/tools/audio/tts.py" "$p" --provider minimax --join block --candidates 2 2>&1); rc5=$? + if [ "$rc5" = 1 ] && case "$e" in *"· 4 request(s)"*"short"*) true ;; *) false ;; esac && [ "$(cat "$p/audio/vo/zh/01.wav")" = keep ] && [ ! -e "$p/assets/spend.jsonl" ] + then ok "a voice billed per use: --candidates 2 counts two takes of each block in the run's estimate, and a budget for one is refused before anything" + else bad "a voice billed per use, --candidates (exit $rc5): $e"; fi + else skip "a voice billed per use, --candidates" "no uv"; fi a=$(python3 - "$ROOT" "$t/u" <<'PY' 2>&1 import io, json, os, sys, types, urllib.error, urllib.request from pathlib import Path @@ -6572,8 +6593,8 @@ def answer(seq): # urlopen stand-in: each call takes the next item (a dict → return Ans(x if isinstance(x, bytes) else json.dumps(x).encode()) urllib.request.urlopen = urlopen tts.time.sleep = lambda s: None -text = "卫星飞过去了。Satellites pass." # 6 Han characters (2 each) + 17 others = 29 characters billed -want(speechcost.chars(text, 2) == 29 and speechcost.chars(text, 1) == 23, f"chars: {speechcost.chars(text, 2)} {speechcost.chars(text, 1)}") +text = "卫星飞过去了。Satellites pass." # 7 characters not ASCII (2 each, 。 too) + 16 others = 30 characters billed +want(speechcost.chars(text, 2) == 30 and speechcost.chars(text, 1) == 23, f"chars: {speechcost.chars(text, 2)} {speechcost.chars(text, 1)}") ok_mm = {"base_resp": {"status_code": 0}, "data": {"audio": "00", "subtitle_file": "https://x/s.json"}, "extra_info": {"usage_characters": 26}} # 1 no budget: refused before anything, saying what to write @@ -6597,7 +6618,7 @@ tts.METER = tts.metered(p, "minimax", "bin/vh tts"); tts.METER.check([text]) answer([ok_mm, b"[]"]) tts.minimax_tts(text, "v", "zh", out=Path(".01.part.wav")) s = spend(p) -want([x["kind"] for x in s] == ["hold", "settle"] and abs(s[0]["amount"] - 0.0029) < 1e-9 and abs(s[1]["amount"] - 0.0026) < 1e-9 +want([x["kind"] for x in s] == ["hold", "settle"] and abs(s[0]["amount"] - 0.003) < 1e-9 and abs(s[1]["amount"] - 0.0026) < 1e-9 and "01.wav" in s[1]["what"] and s[1]["tool"] == "bin/vh tts", f"held and settled: {s}") # 4 an error status: settled at 0, the error raised answer([{"base_resp": {"status_code": 1004, "status_msg": "auth"}}]) @@ -6610,7 +6631,7 @@ want(spend(p)[-1]["kind"] == "settle" and spend(p)[-1]["amount"] == 0, f"an erro answer([TimeoutError("timed out"), ok_mm, b"[]"]) tts.minimax_tts(text, "v", "zh", out=Path(".03.part.wav")) st = [x for x in spend(p) if x["kind"] == "settle"][-2:] -want([round(x["amount"], 6) for x in st] == [0.0029, 0.0026] and st[0]["hold"] != st[1]["hold"], f"timeout then retry: {st}") +want([round(x["amount"], 6) for x in st] == [0.003, 0.0026] and st[0]["hold"] != st[1]["hold"], f"timeout then retry: {st}") # 6 a request that never left: 0 answer([urllib.error.URLError(ConnectionRefusedError(61, "refused"))] * 3) try: @@ -6624,11 +6645,11 @@ m = tts.metered(p2, "minimax", "bin/vh tts") try: m.check([text]); bad.append("over the budget did not refuse") except speechcost.Refused as e: - want("short" in str(e) and "$0.0019" in str(e), f"over said: {e}") + want("short" in str(e) and "$0.002" in str(e), f"over said: {e}") # 8 a China-platform key: yuan, ¥3.5 per 10,000 os.environ["MINIMAX_BASE_URL"] = "https://api.minimaxi.com" m = tts.metered(p, "minimax", "bin/vh tts") -want(m.rate["currency"] == "CNY" and abs(m.cost(text) - 0.01015) < 1e-9, f"China platform: {m.rate}") +want(m.rate["currency"] == "CNY" and abs(m.cost(text) - 0.0105) < 1e-9, f"China platform: {m.rate}") try: m.check([text]); bad.append("a USD budget took a CNY call") except speechcost.Refused as e: @@ -6645,6 +6666,27 @@ except speechcost.Refused as e: want("not known" in str(e), f"unknown refused: {e}") del os.environ["MINIMAX_BASE_URL"] +# 9b a model the table lacks, on an endpoint it has: priced as its most expensive model, said, and a budget still holds; +# a model's name in another case is the same model; every character that is not ASCII counts 2; the body is what is sent +os.environ["MINIMAX_TTS_MODEL"] = "speech-2.9-hd" +m = tts.metered(film("assumed", "$0.0001"), "minimax", "bin/vh tts") +want(m.rate.get("assumed") and abs(m.rate["each"] - 100 / 1e6) < 1e-12 and "(assumed)" in m.rate["price"], f"an unlisted model: {m.rate}") +try: + m.check([text, text]); bad.append("an unlisted model went past a $0.0001 budget") +except speechcost.Refused as e: + want("short" in str(e) and "(assumed)" in str(e), f"an unlisted model refused: {e}") +os.environ["MINIMAX_TTS_MODEL"] = "Speech-2.8-TURBO" +m = tts.metered(p, "minimax", "bin/vh tts") +want(not m.rate.get("assumed") and abs(m.rate["each"] - 60 / 1e6) < 1e-12, f"a model's name in another case: {m.rate}") +del os.environ["MINIMAX_TTS_MODEL"] +os.environ["ELEVENLABS_MODEL"] = "eleven_monolingual_v1" +m = tts.metered(p, "elevenlabs", "bin/vh tts") +want(m.rate.get("assumed") and abs(m.rate["each"] - 0.08 / 1000) < 1e-12, f"an older ElevenLabs model: {m.rate}") +del os.environ["ELEVENLABS_MODEL"] +want(speechcost.chars("〇かな,", 2) == 8 and speechcost.chars("〇かな,", 1) == 4, f"not ASCII: {speechcost.chars('〇かな,', 2)}") +want(tts.body_of("minimax", "<#0.3#>前面<#0.5#>后面") == "前面<#0.50#>后面" and tts.body_of("elevenlabs", "a<#0.5#>b") == "a<#0.5#>b", + f"the body: {tts.body_of('minimax', '<#0.3#>前面<#0.5#>后面')!r}") + # 10 ElevenLabs: settled at the estimate (an upper bound, said); an HTTP error at 0 tts.to_wav = lambda src, dst: Path(dst).write_bytes(b"") p = film("el", "$1") @@ -6661,7 +6703,7 @@ except urllib.error.HTTPError: pass want(spend(p)[-1]["amount"] == 0, f"elevenlabs 401 not 0: {spend(p)[-1]}") -# 11 DashScope (Beijing, yuan): settled at usage.characters × ¥0.8 per 10,000; an error answer at 0 +# 11 DashScope (Beijing, yuan): settled at usage.characters × ¥0.8 per 10,000 (26 billed, 30 estimated); an error answer at 0 fake = types.ModuleType("dashscope") class MMC: nxt = None @@ -6671,9 +6713,9 @@ fake.MultiModalConversation = MMC; sys.modules["dashscope"] = fake urllib.request.urlretrieve = lambda url, dst: Path(dst).write_bytes(b"") p = film("ds", "¥1") tts.METER = tts.metered(p, "dashscope", "bin/vh tts"); tts.METER.check([text]) -MMC.nxt = types.SimpleNamespace(output=types.SimpleNamespace(audio=types.SimpleNamespace(url="https://x/a.wav")), usage={"characters": 30}) +MMC.nxt = types.SimpleNamespace(output=types.SimpleNamespace(audio=types.SimpleNamespace(url="https://x/a.wav")), usage={"characters": 26}) tts.p_dashscope(text, "Cherry", Path(t / ".01.part.wav"), t, "zh") -want(abs(spend(p)[-1]["amount"] - 30 * 0.8 / 10000) < 1e-9 and spend(p)[-1]["currency"] == "CNY", f"dashscope: {spend(p)[-1]}") +want(abs(spend(p)[-1]["amount"] - 26 * 0.8 / 10000) < 1e-9 and spend(p)[-1]["currency"] == "CNY", f"dashscope: {spend(p)[-1]}") MMC.nxt = types.SimpleNamespace(output=None, status_code=400, message="bad") try: tts.p_dashscope(text, "Cherry", Path(t / ".02.part.wav"), t, "zh"); bad.append("a DashScope error did not exit") From 7ebcd8233a821d58db499b3f583349814764af9d Mon Sep 17 00:00:00 2001 From: zhanglinghao Date: Sun, 22 Nov 2026 18:16:10 +0800 Subject: [PATCH 8/9] bin/vh web: the last-resort deadline allows two starts of each browser (a start that did not answer is now tried once more) --- tools/web/chrome.mjs | 7 ++++--- tools/web/web.py | 7 ++++--- 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/tools/web/chrome.mjs b/tools/web/chrome.mjs index e2f1f6c2..24b2ddb0 100644 --- a/tools/web/chrome.mjs +++ b/tools/web/chrome.mjs @@ -10,10 +10,11 @@ const warnings = []; let browser, timer, stage = "checking the URL"; const fail = (message) => { console.error(`web: ${message}`); process.exit(1); }; // The whole run's last-resort deadline; bin/vh web passes it (tools/web/web.py chrome_budget). Each of the two attempts may -// spend launchTab's own recovery (up to 3 launches: a first answer within 60 s, the tab's within OVH_PAGE_TIMEOUT or 30 s, -// a close) before the page's own steps: the load, the settle, a selector's wait, then the read and the screenshot. +// spend launchTab's own recovery (up to 3 tabs, each on a browser that may take 2 starts: 60 s for a first answer and a +// close each, then the tab's answer within OVH_PAGE_TIMEOUT or 30 s) before the page's own steps: the load, the settle, a +// selector's wait, then the read and the screenshot. const tabAnswer = Math.max(30, Number(process.env.OVH_PAGE_TIMEOUT) || 0); -const budget = opt.budget ?? 2 * (3 * (70 + tabAnswer) + 3 * opt.timeout + (opt.wait ?? 1) + (opt.selector ? opt.wait ?? 5 : 0) + 10) + 10; +const budget = opt.budget ?? 2 * (3 * (2 * 70 + tabAnswer) + 3 * opt.timeout + (opt.wait ?? 1) + (opt.selector ? opt.wait ?? 5 : 0) + 10) + 10; timer = setTimeout(() => fail(`Chrome did not finish within ${budget} s (${stage}, including startup/recovery)`), budget * 1000); const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); class CommandTimeout extends Error { diff --git a/tools/web/web.py b/tools/web/web.py index c2061852..eccee27a 100644 --- a/tools/web/web.py +++ b/tools/web/web.py @@ -238,15 +238,16 @@ def run(exe, url, dump=None, shot=None, a=None): def chrome_budget(a): """The capture's last-resort deadline in seconds, which chrome.mjs computes the same way when run alone: two attempts, - each with launchTab's own recovery (up to 3 launches: 60 s for a first answer, OVH_PAGE_TIMEOUT or 30 s for the tab's, a - close), then the load, the settle, a selector's wait, the read and the screenshot.""" + each with launchTab's own recovery (up to 3 tabs, each on a browser that may take 2 starts: 60 s for a first answer and + a close each, then OVH_PAGE_TIMEOUT or 30 s for the tab's answer), then the load, the settle, a selector's wait, the read + and the screenshot.""" try: tab = max(30.0, float(os.environ.get("OVH_PAGE_TIMEOUT") or 0)) except ValueError: tab = 30.0 settle = a.wait if a.wait is not None else 1 selector = (a.wait if a.wait is not None else 5) if getattr(a, "selector", None) else 0 - return 2 * (3 * (70 + tab) + 3 * a.timeout + settle + selector + 10) + 10 + return 2 * (3 * (2 * 70 + tab) + 3 * a.timeout + settle + selector + 10) + 10 def run_chrome(exe, a, dump, shot): From e031ac25fadda5e36f403ffafb32001ea7e54bff Mon Sep 17 00:00:00 2001 From: zhanglinghao Date: Sun, 22 Nov 2026 18:29:44 +0800 Subject: [PATCH 9/9] ci: the browser start check counts its lines, any reason the browser was gone (Linux says EPIPE or ECONNRESET where macOS says exit 1), in any order --- tools/ci.sh | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/tools/ci.sh b/tools/ci.sh index 5dad69a9..7375a044 100755 --- a/tools/ci.sh +++ b/tools/ci.sh @@ -11208,12 +11208,12 @@ for (const exe of process.argv.slice(1)) { try { const { browser, sessionId } = await launchTab(exe, [], ["Page"]); console.log("TAB", sessionId); await browser.close(); } catch (e) { console.log("FAILED", e.message.slice(0, 60)); } }' "$t/late" "$t/never" "$t/no-such-browser" 2>&1) - case "$a" in "the browser did not start (the browser is gone (exit 1)): starting another -TAB s1 -the browser did not start (the browser is gone (exit 1)): starting another -FAILED the browser is gone (exit 1) -FAILED the browser is gone (ENOENT)"*) ok "browser: one that did not start is started once more (said), one that never starts fails after the second, a program not there is not tried again" ;; - *) bad "browser start, once more: $a" ;; esac + # (counted, not in order: the lines come on stdout and stderr; the reason is the platform's: exit 1, or EPIPE/ECONNRESET on Linux) + if [ "$(printf '%s\n' "$a" | grep -c '^the browser did not start (the browser is gone (.*)): starting another$')" = 2 ] \ + && ! printf '%s\n' "$a" | grep -q 'ENOENT.*starting another' && [ "$(printf '%s\n' "$a" | grep -cx 'TAB s1')" = 1 ] \ + && [ "$(printf '%s\n' "$a" | grep -c '^FAILED the browser is gone (')" = 2 ] && [ "$(printf '%s\n' "$a" | grep -c '^FAILED the browser is gone (ENOENT)')" = 1 ] + then ok "browser: one that did not start is started once more (said), one that never starts fails after the second, a program not there is not tried again" + else bad "browser start, once more: $a"; fi a=$(vh frames tools/film/fixture --at 5 --out "$t/e" 2>&1); rc=$? case "$rc:$a" in 2:*"outside the film"*) ok "frames: a time outside the film exits 2" ;; *) bad "frames outside the film: exit $rc: $(printf '%s' "$a" | tail -c 600)" ;; esac if command -v ffmpeg >/dev/null; then