dsh-singinglab
Version:
A music player for DeepSeek Harness where 大肥鱼 sings: tell her a song, she learns it on your machine and plays it.
1,590 lines • 70.3 kB
JavaScript
import {
Bili,
compose,
guessTitle,
parseVideoRef,
pushCommand,
runtime,
setStarted
} from "./chunks/chunk-D3K3RT55.js";
// src/index.ts
import { createReadStream as createReadStream2 } from "node:fs";
import { mkdir as mkdir7, readFile as readFile8, stat as stat6, writeFile as writeFile7 } from "node:fs/promises";
import { homedir } from "node:os";
import { join as join10 } from "node:path";
import { Readable as Readable2 } from "node:stream";
import { fileURLToPath } from "node:url";
// src/covers.ts
import { mkdir, readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
var UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0 Safari/537.36";
var RETRY_MS = 60 * 60 * 1e3;
var Covers = class {
constructor(dir) {
this.dir = dir;
}
dir;
inflight = /* @__PURE__ */ new Map();
failedAt = /* @__PURE__ */ new Map();
/** 同时最多查 3 个,歌库一下子滚出几百张封面时别把 B 站接口打爆 */
running = 0;
waiting = [];
async slot(job) {
if (this.running >= 3) await new Promise((resolve) => this.waiting.push(resolve));
this.running++;
try {
return await job();
} finally {
this.running--;
this.waiting.shift()?.();
}
}
async get(bvid) {
const file = join(this.dir, `${bvid}.jpg`);
const cached = await readFile(file).catch(() => null);
if (cached) return cached;
if (Date.now() - (this.failedAt.get(bvid) ?? 0) < RETRY_MS) return null;
let job = this.inflight.get(bvid);
if (!job) {
job = this.slot(() => this.fetchCover(bvid, file)).finally(() => this.inflight.delete(bvid));
this.inflight.set(bvid, job);
}
return job;
}
async fetchCover(bvid, file) {
try {
const info = await fetch(`https://api.bilibili.com/x/web-interface/view?bvid=${bvid}`, {
headers: { "user-agent": UA, referer: "https://www.bilibili.com/" },
signal: AbortSignal.timeout(1e4)
}).then((r) => r.json());
const pic = info.code === 0 ? info.data?.pic : void 0;
if (!pic) throw new Error(`no cover (${info.code})`);
const url = `${pic.replace(/^http:/, "https:")}@960w_600h_1c.jpg`;
const res = await fetch(url, { headers: { "user-agent": UA, referer: "https://www.bilibili.com/" }, signal: AbortSignal.timeout(15e3) });
if (!res.ok) throw new Error(`cover http ${res.status}`);
const bytes = new Uint8Array(await res.arrayBuffer());
await mkdir(this.dir, { recursive: true });
await writeFile(file, bytes);
return bytes;
} catch {
this.failedAt.set(bvid, Date.now());
return null;
}
}
};
// src/editor.ts
import { spawn } from "node:child_process";
import { readFile as readFile2, stat, writeFile as writeFile2 } from "node:fs/promises";
import { join as join2 } from "node:path";
import { createInterface } from "node:readline";
var IDLE_MS = 5 * 6e4;
var CALL_TIMEOUT_MS = 5 * 6e4;
var EditWorker = class {
constructor(script) {
this.script = script;
}
script;
child = null;
python = "";
pending = /* @__PURE__ */ new Map();
nextId = 1;
idle = null;
queue = Promise.resolve();
stderr = "";
/** 排队调一个命令;进程没起就起 */
call(rt, msg) {
const run3 = this.queue.then(() => this.send(rt, msg));
this.queue = run3.catch(() => {
});
return run3;
}
close() {
if (this.idle) clearTimeout(this.idle);
this.child?.kill();
this.child = null;
}
start(rt) {
if (this.child && this.python === rt.python) return this.child;
this.close();
const child = spawn(rt.python, [this.script], { stdio: ["pipe", "pipe", "pipe"], windowsHide: true, env: { ...rt.env, PYTHONUNBUFFERED: "1" } });
this.child = child;
this.python = rt.python;
this.stderr = "";
child.stderr.setEncoding("utf8").on("data", (c) => {
this.stderr = (this.stderr + c).slice(-2e3);
});
createInterface({ input: child.stdout }).on("line", (line) => {
let reply;
try {
reply = JSON.parse(line);
} catch {
return;
}
const p = this.pending.get(reply.id);
if (!p) return;
this.pending.delete(reply.id);
clearTimeout(p.timer);
if (reply.ok) p.resolve(reply);
else p.reject(new Error(reply.error ?? "\u4FEE\u97F3\u8FDB\u7A0B\u51FA\u9519\u4E86"));
});
child.on("exit", (code) => {
if (this.child === child) this.child = null;
const tail = this.stderr.trim().split("\n").slice(-3).join(" ");
for (const [id, p] of this.pending) {
clearTimeout(p.timer);
p.reject(new Error(`\u4FEE\u97F3\u8FDB\u7A0B\u9000\u51FA\u4E86\uFF08${code}\uFF09${tail ? `\uFF1A${tail.slice(-300)}` : ""}`));
this.pending.delete(id);
}
});
child.on("error", () => {
});
return child;
}
send(rt, msg) {
const child = this.start(rt);
if (this.idle) clearTimeout(this.idle);
const id = this.nextId++;
return new Promise((resolve, reject) => {
const timer = setTimeout(() => {
this.pending.delete(id);
reject(new Error("\u4FEE\u97F3\u8FDB\u7A0B\u592A\u4E45\u6CA1\u56DE\u8BDD"));
this.close();
}, CALL_TIMEOUT_MS);
this.pending.set(id, {
resolve: (v) => {
this.armIdle();
resolve(v);
},
reject: (e) => {
this.armIdle();
reject(e);
},
timer
});
child.stdin.write(`${JSON.stringify({ ...msg, id })}
`);
});
}
armIdle() {
if (this.idle) clearTimeout(this.idle);
this.idle = setTimeout(() => this.close(), IDLE_MS);
this.idle.unref?.();
}
};
var editDir = (songDir) => join2(songDir, "edit");
async function hasEdit(songDir) {
return stat(join2(editDir(songDir), "dry.flac")).then((s) => s.isFile(), () => false);
}
async function readEditState(songDir) {
const raw = JSON.parse((await readFile2(join2(editDir(songDir), "edit.json"), "utf8")).replace(/^/, ""));
return { format: 1, autoKey: Number(raw.autoKey) || 0, key: Number(raw.key ?? raw.autoKey) || 0, keyScores: raw.keyScores, ops: Array.isArray(raw.ops) ? raw.ops : [] };
}
async function writeEditState(songDir, state) {
await writeFile2(join2(editDir(songDir), "edit.json"), JSON.stringify(state));
}
async function readNpy(file) {
const buf = await readFile2(file).catch(() => null);
if (!buf || buf.toString("latin1", 1, 6) !== "NUMPY") return null;
const major = buf[6];
const headerLen = major === 1 ? buf.readUInt16LE(8) : buf.readUInt32LE(8);
const start = (major === 1 ? 10 : 12) + headerLen;
const header = buf.toString("latin1", major === 1 ? 10 : 12, start);
const descr = /'descr':\s*'([<>|]?)(f4|f8)'/.exec(header)?.[2];
const body = buf.subarray(start);
if (descr === "f4") return new Float32Array(body.buffer.slice(body.byteOffset, body.byteOffset + body.byteLength));
if (descr === "f8") {
const f64 = new Float64Array(body.buffer.slice(body.byteOffset, body.byteOffset + (body.byteLength - body.byteLength % 8)));
return Float32Array.from(f64);
}
return null;
}
var b64 = (a) => Buffer.from(a.buffer, a.byteOffset, a.byteLength).toString("base64");
// src/learner.ts
import { spawn as spawn2 } from "node:child_process";
import { createWriteStream, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
import { constants, setPriority } from "node:os";
import { join as join3 } from "node:path";
import { Readable } from "node:stream";
import { pipeline } from "node:stream/promises";
var STEPS = [
{ step: "download", label: "\u53BB B \u7AD9\u53D6\u8FD9\u9996\u6B4C", weight: 3 },
{ step: "separate", label: "\u628A\u4EBA\u58F0\u548C\u4F34\u594F\u5206\u5F00", weight: 11 },
{ step: "karaoke", label: "\u627E\u51FA\u4E3B\u5531", weight: 21 },
{ step: "dereverb", label: "\u64E6\u5E72\u51C0\u4EBA\u58F0", weight: 9 },
{ step: "gate", label: "\u786E\u8BA4\u662F\u4E00\u9996\u6B4C", weight: 1 },
{ step: "lyrics", label: "\u5BF9\u6B4C\u8BCD", weight: 24 },
{ step: "pitch", label: "\u542C\u51C6\u6BCF\u4E2A\u97F3", weight: 20 },
{ step: "key", label: "\u627E\u9002\u5408\u5979\u7684\u8C03", weight: 1 },
{ step: "quality", label: "\u68C0\u67E5\u5B66\u5F97\u597D\u4E0D\u597D", weight: 1 },
{ step: "rvc", label: "\u6362\u6210\u5979\u7684\u58F0\u97F3", weight: 9 },
{ step: "analyze", label: "\u627E\u8282\u62CD", weight: 1 },
{ step: "mix", label: "\u6DF7\u97F3", weight: 4 }
];
var TOTAL = STEPS.reduce((s, x) => s + x.weight, 0);
var LEARN_TIMEOUT_MS = 25 * 6e4;
var KEEP_FINISHED = 30;
function stepProgress(line) {
const at = STEPS.findIndex((s) => s.step === line.step);
if (at < 0 || !line.state) return null;
const passed = STEPS.slice(0, at).reduce((sum, s) => sum + s.weight, 0);
const finished = line.state === "done" || line.state === "cached" || line.state === "skipped" || line.state === "report";
return {
progress: (passed + (finished ? STEPS[at].weight : STEPS[at].weight * 0.15)) / TOTAL,
label: finished ? STEPS[at + 1]?.label ?? "\u6536\u5C3E" : STEPS[at].label
};
}
function run(command, args) {
return new Promise((resolve, reject) => {
const child = spawn2(command, args, { stdio: ["ignore", "ignore", "pipe"], windowsHide: true });
let tail = "";
child.stderr.setEncoding("utf8").on("data", (c) => {
tail = (tail + c).slice(-300);
});
child.on("error", reject);
child.on("close", (code) => code === 0 ? resolve() : reject(new Error(`${command} \u5931\u8D25\uFF08${code}\uFF09\uFF1A${tail.trim().slice(-200)}`)));
});
}
var Learner = class {
constructor(bili, options) {
this.bili = bili;
this.options = options;
mkdirSync(options.songsDir, { recursive: true });
try {
const saved = JSON.parse(readFileSync(options.stateFile, "utf8"));
this.jobs = saved.map((j) => j.state === "running" ? { ...j, state: "queued", label: "\u6392\u961F\u4E2D", progress: 0 } : j);
} catch {
}
void this.next();
}
bili;
options;
jobs = [];
/** 一首学完或没学成时通知(AI 工具用它告诉让学的那个会话) */
ended = /* @__PURE__ */ new Set();
stopRunning = null;
busy = false;
save() {
try {
writeFileSync(this.options.stateFile, JSON.stringify(this.jobs, null, 1));
} catch {
}
this.options.onChange();
}
patch(job, p) {
Object.assign(job, p);
this.save();
}
learn(req) {
const page = Math.max(1, Math.floor(req.page ?? 1));
const id = `${req.bvid}-p${page}`;
const active = this.jobs.find((j) => j.id === id && (j.state === "queued" || j.state === "running"));
if (active) {
if (req.autoplay) active.autoplay = true;
if (req.session) active.session = req.session;
return active;
}
this.jobs = this.jobs.filter((j) => j.id !== id);
const job = {
id,
bvid: req.bvid,
page,
title: req.title.trim().slice(0, 60) || req.bvid,
artist: (req.artist ?? "").trim().slice(0, 40),
who: "",
cover: "",
state: "queued",
label: "\u6392\u961F\u4E2D",
progress: 0,
autoplay: req.autoplay ?? true,
...req.session ? { session: req.session } : {},
...req.relearn ? { relearn: true } : {},
queuedAt: Date.now()
};
this.jobs.push(job);
const finished = this.jobs.filter((j) => j.state === "done" || j.state === "failed");
if (finished.length > KEEP_FINISHED) {
const drop = new Set(finished.slice(0, finished.length - KEEP_FINISHED));
this.jobs = this.jobs.filter((j) => !drop.has(j));
}
this.save();
void this.next();
return job;
}
/** 取消:排队的直接拿掉,正在学的停掉 */
cancel(id) {
const job = this.jobs.find((j) => j.id === id);
if (!job) return false;
if (job.state === "queued") {
this.jobs = this.jobs.filter((j) => j !== job);
this.save();
return true;
}
if (job.state === "running") {
this.patch(job, { reason: "\u53D6\u6D88\u4E86" });
this.stopRunning?.();
return true;
}
this.jobs = this.jobs.filter((j) => j !== job);
this.save();
return true;
}
close() {
this.stopRunning?.();
}
async next() {
if (this.busy) return;
const job = this.jobs.find((j) => j.state === "queued");
if (!job) return;
this.busy = true;
this.patch(job, { state: "running", startedAt: Date.now(), label: STEPS[0].label, progress: 0, reason: void 0 });
try {
await this.work(job);
this.patch(job, { state: "done", progress: 1, label: "\u5B66\u4F1A\u4E86", endedAt: Date.now() });
} catch (err) {
this.patch(job, { state: "failed", reason: job.reason === "\u53D6\u6D88\u4E86" ? "\u53D6\u6D88\u4E86" : err.message, endedAt: Date.now() });
} finally {
this.busy = false;
this.stopRunning = null;
for (const listener of this.ended) {
try {
listener(job);
} catch {
}
}
void this.next();
}
}
async work(job) {
const lack = await this.options.check();
if (lack) throw new Error(lack);
const final = join3(this.options.songsDir, job.id);
const learned = existsSync(join3(final, "song.json")) && existsSync(join3(final, "mix.mp3"));
if (learned && !job.relearn) return;
const out = learned ? join3(this.options.songsDir, `.relearn-${job.id}`) : final;
if (learned) rmSync(out, { recursive: true, force: true });
const info = await this.bili.info(job.bvid);
if (!info) throw new Error("B \u7AD9\u4E0A\u627E\u4E0D\u5230\u8FD9\u4E2A\u89C6\u9891\uFF08\u53EF\u80FD\u5220\u4E86\u6216\u8005\u8981\u767B\u5F55\u624D\u80FD\u770B\uFF09");
const part = info.parts.find((p) => p.page === job.page) ?? info.parts[0];
if (!part) throw new Error("\u8FD9\u4E2A\u89C6\u9891\u6CA1\u6709\u53EF\u4EE5\u64AD\u653E\u7684\u5206 P");
this.patch(job, { who: info.up, cover: info.cover });
const maxSec = this.options.maxSec();
if (part.durationSec > maxSec) throw new Error(`\u8FD9\u9996\u6709 ${Math.round(part.durationSec / 60)} \u5206\u949F\uFF0C\u592A\u957F\u4E86\uFF08\u6700\u957F ${Math.round(maxSec / 60)} \u5206\u949F\uFF09`);
mkdirSync(out, { recursive: true });
const audio = join3(out, "source.m4a");
if (!existsSync(audio)) {
const src = await this.bili.audio(job.bvid, part.cid);
if (!src) throw new Error("B \u7AD9\u6CA1\u7ED9\u8FD9\u4E2A\u89C6\u9891\u7684\u97F3\u9891");
const res = await fetch(src.url, { headers: src.headers, signal: AbortSignal.timeout(12e4) });
if (!res.ok || !res.body) throw new Error(`\u97F3\u9891\u4E0B\u8F7D\u5931\u8D25\uFF08${res.status}\uFF09`);
await pipeline(Readable.fromWeb(res.body), createWriteStream(`${audio}.part`));
renameSync(`${audio}.part`, audio);
}
this.patch(job, { progress: 3 / TOTAL, label: STEPS[1].label });
const meta = { title: job.title, artist: job.artist, source: `https://www.bilibili.com/video/${job.bvid}?p=${part.page}`, who: info.up };
const plan = await this.options.plan(out);
if (plan.remote) await this.prepareRemote(job, out, audio, meta, plan, maxSec);
else {
await this.runPrepare(job, plan.python, [
this.options.script,
"--config",
plan.config,
"--audio",
audio,
"--out",
out,
"--title",
meta.title,
"--artist",
meta.artist,
"--source",
meta.source,
"--who",
meta.who,
"--max-sec",
String(maxSec),
...plan.key !== null ? ["--key", String(plan.key)] : []
], plan.env);
}
rmSync(audio, { force: true });
if (!existsSync(join3(out, "song.json")) || !existsSync(join3(out, "mix.mp3"))) throw new Error("\u5B66\u5B8C\u4E86\u5374\u6CA1\u6709\u751F\u6210\u6B4C\u66F2\u6587\u4EF6");
if (out !== final) {
for (const name2 of readdirSync(out)) {
rmSync(join3(final, name2), { recursive: true, force: true });
renameSync(join3(out, name2), join3(final, name2));
}
rmSync(out, { recursive: true, force: true });
}
}
/** 传音频过去,在那台机器上跑 prepare.py(那台机器的 sing.json 旁边要有同一套 prepare.py),把歌曲包取回来 */
async prepareRemote(job, out, audio, meta, s, maxSec) {
const at = s.remote.lastIndexOf(":");
const host = at > 0 ? s.remote.slice(0, at) : s.remote, port = at > 0 ? s.remote.slice(at + 1) : "22";
const ssh = ["-p", port, "-o", "BatchMode=yes", "-o", "ConnectTimeout=15", host];
const scp = ["-P", port, "-q", "-o", "BatchMode=yes"];
const dir = s.config.slice(0, s.config.lastIndexOf("/"));
const root = `${dir}/jobs/singinglab-${job.id}`;
writeFileSync(join3(out, "meta.json"), JSON.stringify(meta));
await run("ssh", [...ssh, `mkdir -p ${root}`]);
await run("scp", [...scp, audio, join3(out, "meta.json"), `${host}:${root}/`]);
await this.runPrepare(job, "ssh", [
...ssh,
`${s.python} ${dir}/prepare.py --config ${s.config} --audio ${root}/source.m4a --out ${root}/out --meta ${root}/meta.json --max-sec ${maxSec}${s.key !== null ? ` --key ${s.key}` : ""}`
], s.env);
await run("scp", [...scp, `${host}:${root}/out/song.json`, `${host}:${root}/out/mix.mp3`, out]);
rmSync(join3(out, "meta.json"), { force: true });
await run("ssh", [...ssh, `rm -rf ${root}`]).catch(() => {
});
}
runPrepare(job, command, args, env) {
return new Promise((resolve, reject) => {
const child = spawn2(command, args, { stdio: ["ignore", "pipe", "pipe"], windowsHide: true, env });
try {
if (child.pid) setPriority(child.pid, constants.priority.PRIORITY_BELOW_NORMAL);
} catch {
}
const timer = setTimeout(() => child.kill(), LEARN_TIMEOUT_MS);
this.stopRunning = () => child.kill();
let reason = "", tail = "", buffer = "";
child.stdout.setEncoding("utf8").on("data", (chunk) => {
buffer += chunk;
const lines = buffer.split("\n");
buffer = lines.pop() ?? "";
for (const raw of lines) {
try {
const line = JSON.parse(raw);
if (line.state === "failed") reason = line.reason ?? "";
const p = stepProgress(line);
if (p) this.patch(job, p);
} catch {
}
}
});
child.stderr.setEncoding("utf8").on("data", (c) => {
tail = (tail + c).slice(-500);
});
child.on("error", (err) => {
clearTimeout(timer);
reject(err);
});
child.on("close", (code) => {
clearTimeout(timer);
if (code === 0) return resolve();
reject(new Error(reason || (code === null ? "\u5B66\u5F97\u592A\u4E45\uFF0C\u505C\u4E86" : `\u5B66\u6B4C\u7A0B\u5E8F\u51FA\u9519\uFF08${code}\uFF09\uFF1A${tail.trim().slice(-200)}`)));
});
});
}
};
// src/shelf.ts
import { createHash } from "node:crypto";
import { createReadStream, createWriteStream as createWriteStream2, existsSync as existsSync2 } from "node:fs";
import { copyFile, link, mkdir as mkdir2, readdir, readFile as readFile3, rename, stat as stat2, unlink, writeFile as writeFile3 } from "node:fs/promises";
import { join as join4 } from "node:path";
var UA2 = "dsh-singinglab";
var Shelf = class {
constructor(catalog, dir, onChange) {
this.catalog = catalog;
this.dir = dir;
this.onChange = onChange;
}
catalog;
dir;
onChange;
busy = /* @__PURE__ */ new Map();
errors = /* @__PURE__ */ new Map();
queue = Promise.resolve();
model(id) {
return this.catalog.models.find((m) => m.id === id);
}
path(id, file) {
return file ? join4(this.dir, id, file) : join4(this.dir, id);
}
bytes(id) {
return this.model(id)?.files.reduce((s, f) => s + f.size, 0) ?? 0;
}
async installed(id) {
const m = this.model(id);
if (!m) return false;
for (const f of m.files) {
const st = await stat2(this.path(id, f.name)).catch(() => null);
if (!st || st.size !== f.size) return false;
}
return true;
}
async status() {
return Promise.all(this.catalog.models.map(async (m) => ({
id: m.id,
installed: await this.installed(m.id),
bytes: this.bytes(m.id),
...this.busy.has(m.id) ? { downloading: this.busy.get(m.id) } : {},
...this.errors.has(m.id) ? { error: this.errors.get(m.id) } : {}
})));
}
/** 下一个模型(排队,一次下一个);已经下好的直接返回 */
download(id, mirror) {
const job = this.queue.then(() => this.downloadNow(id, mirror));
this.queue = job.catch(() => {
});
return job;
}
async downloadNow(id, mirror) {
const m = this.model(id);
if (!m) throw new Error(`\u8D27\u67B6\u4E0A\u6CA1\u6709 ${id}`);
if (await this.installed(id)) return;
this.errors.delete(id);
const total = this.bytes(id);
let base = 0;
try {
await mkdir2(this.path(id), { recursive: true });
for (const f of m.files) {
const target = this.path(id, f.name);
const st = await stat2(target).catch(() => null);
if (st?.size === f.size) {
base += f.size;
continue;
}
const sources = f.sources.map((s) => s.replace("{mirror}", mirror.replace(/\/$/, ""))).filter((s) => !s.startsWith("{") && !(s.startsWith("/") && !mirror));
let lastErr = "\u6CA1\u6709\u80FD\u7528\u7684\u4E0B\u8F7D\u5730\u5740\uFF08\u56FD\u5185\u955C\u50CF\u8FD8\u6CA1\u914D\u7F6E\uFF09";
let ok = false;
for (const url of sources.filter((s) => /^https?:\/\//.test(s))) {
try {
await this.fetchFile(url, target, f, (done) => {
this.busy.set(id, { done: base + done, total, file: f.name });
this.onChange();
});
ok = true;
break;
} catch (err) {
lastErr = `${new URL(url).host}\uFF1A${err.message}`;
}
}
if (!ok) throw new Error(lastErr);
base += f.size;
}
} catch (err) {
this.errors.set(id, err.message);
throw err;
} finally {
this.busy.delete(id);
this.onChange();
}
}
/** 断点续传下一个文件,边下边算 sha256;不对就删掉重来 */
async fetchFile(url, target, f, progress) {
const part = `${target}.part`;
const hash = createHash("sha256");
let have = (await stat2(part).catch(() => null))?.size ?? 0;
if (have > f.size) {
await unlink(part).catch(() => {
});
have = 0;
}
if (have > 0) {
await new Promise((resolve, reject) => createReadStream(part).on("data", (c) => hash.update(c)).on("end", resolve).on("error", reject));
}
const res = await fetch(url, { headers: { "User-Agent": UA2, ...have ? { Range: `bytes=${have}-` } : {} }, redirect: "follow", signal: AbortSignal.timeout(3e4) });
if (!res.ok || !res.body) throw new Error(`HTTP ${res.status}`);
if (have && res.status !== 206) {
await res.body.cancel().catch(() => {
});
await unlink(part).catch(() => {
});
return this.fetchFile(url, target, f, progress);
}
const out = createWriteStream2(part, { flags: have ? "a" : "w" });
let done = have;
let last = 0;
const reader = res.body.getReader();
try {
for (; ; ) {
const chunk = await Promise.race([reader.read(), new Promise((_, rej) => setTimeout(() => rej(new Error("\u4E0B\u8F7D\u5361\u4F4F\u4E86")), 6e4))]);
if (chunk.done) break;
hash.update(chunk.value);
done += chunk.value.length;
if (!out.write(chunk.value)) await new Promise((r) => out.once("drain", () => r()));
if (Date.now() - last > 400) {
last = Date.now();
progress(done);
}
}
} finally {
await new Promise((r) => out.end(r));
}
progress(done);
if (done !== f.size) throw new Error(`\u5927\u5C0F\u4E0D\u5BF9\uFF08${done} / ${f.size}\uFF09`);
const sha = hash.digest("hex");
if (sha !== f.sha256) {
await unlink(part).catch(() => {
});
throw new Error("\u6821\u9A8C\u4E0D\u5BF9\uFF08\u6587\u4EF6\u5185\u5BB9\u548C\u9884\u671F\u7684\u4E0D\u4E00\u6837\uFF09");
}
await rename(part, target);
}
/** 从电脑里已有的文件导入:在这些目录里(往下找三层)按文件名和大小找,sha256 对上就链接/拷贝过来。返回导入了哪些模型 */
async importFrom(dirs) {
const found = /* @__PURE__ */ new Map();
const walk = async (dir, depth) => {
const entries = await readdir(dir, { withFileTypes: true }).catch(() => []);
for (const e of entries) {
const p = join4(dir, e.name);
if (e.isDirectory() && depth < 3) await walk(p, depth + 1);
else if (e.isFile()) {
const st = await stat2(p).catch(() => null);
if (st) found.set(`${e.name}|${st.size}`, p);
}
}
};
for (const d of dirs) await walk(d, 0);
const done = [];
for (const m of this.catalog.models) {
if (await this.installed(m.id)) continue;
const hits = m.files.map((f) => found.get(`${f.name}|${f.size}`));
if (hits.some((h) => !h)) continue;
let ok = true;
for (let i = 0; i < m.files.length && ok; i++) {
if (await sha256(hits[i]) !== m.files[i].sha256) ok = false;
}
if (!ok) continue;
await mkdir2(this.path(m.id), { recursive: true });
for (let i = 0; i < m.files.length; i++) await linkOrCopy(hits[i], this.path(m.id, m.files[i].name));
done.push(m.id);
}
this.onChange();
return done;
}
};
function sha256(file) {
return new Promise((resolve, reject) => {
const h = createHash("sha256");
createReadStream(file).on("data", (c) => h.update(c)).on("end", () => resolve(h.digest("hex"))).on("error", reject);
});
}
async function linkOrCopy(from, to) {
if (existsSync2(to)) await unlink(to).catch(() => {
});
try {
await link(from, to);
} catch {
await copyFile(from, to);
}
}
async function loadCatalog(file) {
return JSON.parse(await readFile3(file, "utf8"));
}
// src/studio.ts
import { mkdir as mkdir6, readFile as readFile6, stat as stat4, writeFile as writeFile6 } from "node:fs/promises";
import { join as join8 } from "node:path";
// src/recipe.ts
import { existsSync as existsSync3 } from "node:fs";
import { mkdir as mkdir3 } from "node:fs/promises";
import { dirname, join as join5 } from "node:path";
function resolveRecipe(catalog, choice) {
if (choice.id === "custom" && choice.custom) return { id: "custom", name: "\u81EA\u5B9A\u4E49", use: choice.custom };
const r = catalog.recipes.find((x) => x.id === choice.id) ?? catalog.recipes[0];
return { id: r.id, name: r.name, use: r.use };
}
function modelsFor(use) {
return [use.separate, use.karaoke, use.dereverb, use.lyrics, "rvc-base"].filter((x) => !!x);
}
async function buildConfig(catalog, use, shelf, setup, voice) {
if (!voice) throw new Error("\u8FD8\u6CA1\u6709\u5979\u7684\u58F0\u97F3\uFF1A\u5148\u5728\u300C\u5B66\u6B4C\u8BBE\u7F6E \u2192 \u58F0\u97F3\u300D\u91CC\u5BFC\u5165\u4E00\u4E2A RVC \u58F0\u97F3\u6A21\u578B");
for (const id of modelsFor(use)) {
if (!await shelf.installed(id)) throw new Error(`\u8FD8\u7F3A\u6A21\u578B\u300C${shelf.model(id)?.name ?? id}\u300D\uFF0C\u5148\u5728\u5B66\u6B4C\u8BBE\u7F6E\u91CC\u4E0B\u8F7D`);
}
const base = shelf.model("rvc-base");
for (const [file, rel] of Object.entries(base.place ?? {})) {
const to = join5(setup.codeDir, rel);
if (!existsSync3(to)) {
await mkdir3(dirname(to), { recursive: true });
await linkOrCopy(shelf.path("rvc-base", file), to);
}
}
const msst = (id) => {
if (!id) return void 0;
const m = catalog.models.find((x) => x.id === id);
return { type: m.msst.type, config: shelf.path(id, m.msst.config), checkpoint: shelf.path(id, m.msst.checkpoint) };
};
const config = {
msstPython: setup.python,
msstDir: join5(setup.codeDir, "msst"),
separator: msst(use.separate),
...use.karaoke ? { karaoke: msst(use.karaoke) } : {},
...use.dereverb ? { dereverb: msst(use.dereverb) } : {},
rvcPython: setup.python,
applioDir: join5(setup.codeDir, "applio"),
rvcModel: voice.model,
rvcIndex: voice.index ?? "",
...use.lyrics ? { whisperModel: shelf.path(use.lyrics) } : {},
pitchFix: use.pitch,
indexRate: voice.indexRate ?? 0.3,
protect: 0.33
};
const key = use.key === "auto" ? null : use.key === "none" ? 0 : Number(use.key) || 0;
return { config, key };
}
// src/setup.ts
import { spawn as spawn3 } from "node:child_process";
import { existsSync as existsSync4 } from "node:fs";
import { chmod, copyFile as copyFile2, cp, mkdir as mkdir4, readFile as readFile4, rm, writeFile as writeFile4 } from "node:fs/promises";
import { join as join6 } from "node:path";
import { inflateRawSync } from "node:zlib";
var TSINGHUA = "https://pypi.tuna.tsinghua.edu.cn/simple";
var PY_MIRROR = "https://registry.npmmirror.com/-/binary/python-build-standalone";
var TORCH = "2.11.0";
var Setup = class {
constructor(root, engineSrc, onChange) {
this.root = root;
this.engineSrc = engineSrc;
this.onChange = onChange;
}
root;
engineSrc;
onChange;
steps = [
{ id: "gpu", name: "\u770B\u770B\u663E\u5361", state: "pending" },
{ id: "uv", name: "\u5B89\u88C5\u5DE5\u5177 uv", state: "pending" },
{ id: "python", name: "\u5B89\u88C5 Python 3.11", state: "pending" },
{ id: "venv", name: "\u5EFA\u5B66\u6B4C\u4E13\u7528\u73AF\u5883", state: "pending" },
{ id: "torch", name: "\u5B89\u88C5 PyTorch\uFF08\u7EA6 3 GB\uFF09", state: "pending" },
{ id: "deps", name: "\u5B89\u88C5\u5176\u4F59\u4F9D\u8D56", state: "pending" },
{ id: "code", name: "\u653E\u597D\u5B66\u6B4C\u5F15\u64CE", state: "pending" },
{ id: "check", name: "\u81EA\u68C0", state: "pending" }
];
running = false;
gpu = null;
get python() {
return process.platform === "win32" ? join6(this.root, "venv", "Scripts", "python.exe") : join6(this.root, "venv", "bin", "python");
}
get codeDir() {
return join6(this.root, "code");
}
get uv() {
return join6(this.root, process.platform === "win32" ? "uv.exe" : "uv");
}
get readyFile() {
return join6(this.root, "ready.json");
}
/** 装好了没有(自检通过过一次,且 Python 还在) */
async ready() {
try {
const info = JSON.parse(await readFile4(this.readyFile, "utf8"));
return { ok: existsSync4(this.python) && existsSync4(join6(this.codeDir, "applio")), info };
} catch {
return { ok: false };
}
}
mark(id, state, detail, sec) {
const s = this.steps.find((x) => x.id === id);
s.state = state;
s.detail = detail;
if (sec !== void 0) s.sec = sec;
this.onChange();
}
/** 从头装(已经做好的步骤会很快过去);同时只跑一次 */
async install() {
if (this.running) return;
this.running = true;
for (const s of this.steps) {
s.state = "pending";
s.detail = void 0;
s.sec = void 0;
}
this.onChange();
try {
await mkdir4(this.root, { recursive: true });
await this.step("gpu", async () => {
this.gpu = await detectGpu();
return this.gpu ? `${this.gpu.name}\uFF0C\u663E\u5B58 ${Math.round(this.gpu.memoryMB / 1024)} GB\uFF0C\u9A71\u52A8 ${this.gpu.driver}` : "\u6CA1\u627E\u5230 N \u5361\uFF1A\u80FD\u5B66\uFF0C\u4F46\u4F1A\u975E\u5E38\u6162\uFF08\u53EA\u7528 CPU\uFF09";
});
await this.step("uv", () => this.installUv());
const env = this.env();
await this.step("python", async () => {
await run2(this.uv, ["python", "install", "3.11"], env);
return "Python 3.11";
});
await this.step("venv", async () => {
if (existsSync4(this.python)) return "\u5DF2\u7ECF\u6709\u4E86";
await run2(this.uv, ["venv", join6(this.root, "venv"), "--python", "3.11"], env);
return "";
});
await this.step("torch", async () => {
const flavor = !this.gpu ? "cpu" : Number(this.gpu.driver.split(".")[0]) >= 570 ? "cu128" : "cu126";
const have = await run2(this.python, ["-c", "import torch; print(torch.__version__)"], env).then((o) => o.trim(), () => "");
if (have.startsWith(TORCH) && have.includes(`+${flavor}`)) return `PyTorch ${have}\uFF08\u5DF2\u7ECF\u6709\u4E86\uFF09`;
const pkgs = [`torch==${TORCH}`, `torchaudio==${TORCH}`];
const base = ["pip", "install", "--python", this.python, ...pkgs, ...have ? ["--reinstall-package", "torch", "--reinstall-package", "torchaudio"] : []];
try {
await run2(this.uv, [...base, "--index-url", `https://download.pytorch.org/whl/${flavor}`], env);
} catch {
await run2(this.uv, [...base, "--index-url", TSINGHUA, "--find-links", `https://mirrors.aliyun.com/pytorch-wheels/${flavor}/`], env);
}
return `PyTorch ${TORCH}\uFF08${flavor}\uFF09`;
});
await this.step("deps", async () => {
await run2(this.uv, ["pip", "install", "--python", this.python, "-r", join6(this.engineSrc, "requirements.txt"), "--index-url", TSINGHUA], env);
const ff = (await run2(this.python, ["-c", "import imageio_ffmpeg; print(imageio_ffmpeg.get_ffmpeg_exe())"], env)).trim().split(/\r?\n/).pop().trim();
await mkdir4(join6(this.root, "bin"), { recursive: true });
const ffTo = join6(this.root, "bin", process.platform === "win32" ? "ffmpeg.exe" : "ffmpeg");
await copyFile2(ff, ffTo);
if (process.platform !== "win32") await chmod(ffTo, 493);
await run2(this.uv, ["cache", "clean"], env).catch(() => "");
return "";
});
await this.step("code", async () => {
await rm(this.codeDir, { recursive: true, force: true });
await cp(this.engineSrc, this.codeDir, { recursive: true });
return "";
});
await this.step("check", async () => {
const out = await run2(this.python, ["-c", CHECK], env);
const info = JSON.parse(out.trim().split("\n").pop());
await writeFile4(this.readyFile, JSON.stringify({ ...info, at: Date.now() }, null, 2));
return info.cuda ? `\u80FD\u7528\u663E\u5361\uFF1A${info.device}` : "\u53EA\u80FD\u7528 CPU\uFF08\u4F1A\u5F88\u6162\uFF09";
});
} finally {
this.running = false;
this.onChange();
}
}
async step(id, body) {
const t = Date.now();
this.mark(id, "running");
try {
const detail = await body();
this.mark(id, "done", detail, Math.round((Date.now() - t) / 1e3));
} catch (err) {
this.mark(id, "failed", err.message.slice(-400), Math.round((Date.now() - t) / 1e3));
throw err;
}
}
env() {
return {
...process.env,
UV_PYTHON_INSTALL_MIRROR: PY_MIRROR,
UV_PYTHON_INSTALL_DIR: join6(this.root, "python"),
UV_CACHE_DIR: join6(this.root, "uv-cache"),
UV_LINK_MODE: "copy",
UV_HTTP_TIMEOUT: "120",
PYTHONUTF8: "1"
};
}
/** uv 的安装包(wheel)就是个 zip,里面有 uv 可执行文件 */
async installUv() {
if (existsSync4(this.uv)) return "\u5DF2\u7ECF\u6709\u4E86";
const tag = process.platform === "win32" ? "win_amd64" : process.arch === "arm64" ? "manylinux_2_17_aarch64" : "manylinux_2_17_x86_64";
const index = await (await fetch(`${TSINGHUA}/uv/`, { signal: AbortSignal.timeout(3e4) })).text();
const links = [...index.matchAll(/href="([^"]+\/(uv-([\d.]+)-py3-none-[^"#]*?\.whl))(#[^"]*)?"/g)].filter((m) => m[2].includes(tag));
const last = links.at(-1);
if (!last) throw new Error(`\u6E05\u534E\u6E90\u4E0A\u627E\u4E0D\u5230 uv \u7684\u5B89\u88C5\u5305\uFF08${tag}\uFF09`);
const url = new URL(last[1], `${TSINGHUA}/uv/`).href;
const zip = Buffer.from(await (await fetch(url, { signal: AbortSignal.timeout(18e4) })).arrayBuffer());
const want = process.platform === "win32" ? /\/scripts\/uv\.exe$/ : /\/scripts\/uv$/;
const bin = unzipOne(zip, (name2) => want.test(name2));
if (!bin) throw new Error("uv \u5B89\u88C5\u5305\u91CC\u6CA1\u627E\u5230 uv");
await writeFile4(this.uv, bin, { mode: 493 });
return `uv ${last[3]}`;
}
};
var CHECK = `
import json, torch, librosa, faiss, faster_whisper, einops, rotary_embedding_torch, PoPE_pytorch, ml_collections, transformers
ok = torch.cuda.is_available()
print(json.dumps({"torch": torch.__version__, "cuda": ok, "device": torch.cuda.get_device_name(0) if ok else None}))
`;
var NVIDIA_SMI = ["nvidia-smi", "/usr/lib/wsl/lib/nvidia-smi", "C:\\Windows\\System32\\nvidia-smi.exe", "C:\\Program Files\\NVIDIA Corporation\\NVSMI\\nvidia-smi.exe"];
async function detectGpu() {
for (const smi of NVIDIA_SMI) {
try {
const out = await run2(smi, ["--query-gpu=name,memory.total,driver_version", "--format=csv,noheader,nounits"], process.env);
const rows = out.trim().split(/\r?\n/).map((l) => l.split(",").map((x) => x.trim()));
const pick = Number(process.env.CUDA_VISIBLE_DEVICES?.split(",")[0]);
const [name2, mem, driver] = rows[Number.isInteger(pick) && rows[pick] ? pick : 0];
if (name2) return { name: name2, memoryMB: Number(mem) || 0, driver };
} catch {
}
}
return null;
}
function run2(cmd, args, env) {
return new Promise((resolve, reject) => {
const child = spawn3(cmd, args, { env, windowsHide: true, stdio: ["ignore", "pipe", "pipe"] });
let out = "", err = "";
child.stdout.setEncoding("utf8").on("data", (c) => {
out = (out + c).slice(-2e4);
});
child.stderr.setEncoding("utf8").on("data", (c) => {
err = (err + c).slice(-4e3);
});
child.on("error", reject);
child.on("close", (code) => code === 0 ? resolve(out) : reject(new Error(`${cmd.split(/[\\/]/).pop()} \u5931\u8D25\uFF08${code}\uFF09\uFF1A${(err || out).trim().split("\n").slice(-6).join(" / ")}`)));
});
}
function unzipOne(zip, match) {
let eocd = -1;
for (let i = zip.length - 22; i >= Math.max(0, zip.length - 65557); i--) {
if (zip.readUInt32LE(i) === 101010256) {
eocd = i;
break;
}
}
if (eocd < 0) return null;
const count = zip.readUInt16LE(eocd + 10);
let p = zip.readUInt32LE(eocd + 16);
for (let n = 0; n < count; n++) {
if (zip.readUInt32LE(p) !== 33639248) return null;
const method = zip.readUInt16LE(p + 10);
const csize = zip.readUInt32LE(p + 20);
const nameLen = zip.readUInt16LE(p + 28), extraLen = zip.readUInt16LE(p + 30), commentLen = zip.readUInt16LE(p + 32);
const local = zip.readUInt32LE(p + 42);
const name2 = zip.toString("utf8", p + 46, p + 46 + nameLen);
if (match(name2)) {
const lNameLen = zip.readUInt16LE(local + 26), lExtraLen = zip.readUInt16LE(local + 28);
const data = zip.subarray(local + 30 + lNameLen + lExtraLen, local + 30 + lNameLen + lExtraLen + csize);
return method === 0 ? Buffer.from(data) : inflateRawSync(data);
}
p += 46 + nameLen + extraLen + commentLen;
}
return null;
}
// src/voices.ts
import { copyFile as copyFile3, mkdir as mkdir5, readdir as readdir2, readFile as readFile5, rm as rm2, stat as stat3, writeFile as writeFile5 } from "node:fs/promises";
import { basename, join as join7 } from "node:path";
var ID = /^[\w.-]{1,60}$/;
var Voices = class {
constructor(dir) {
this.dir = dir;
}
dir;
async list() {
const names = await readdir2(this.dir).catch(() => []);
const out = [];
for (const id of names) {
try {
const meta = JSON.parse(await readFile5(join7(this.dir, id, "voice.json"), "utf8"));
const model = join7(this.dir, id, "model.pth");
const index = join7(this.dir, id, "model.index");
if (!await stat3(model).catch(() => null)) continue;
out.push({ id, name: meta.name ?? id, model, ...await stat3(index).catch(() => null) ? { index } : {}, indexRate: meta.indexRate, addedAt: meta.addedAt ?? 0 });
} catch {
}
}
return out.sort((a, b) => b.addedAt - a.addedAt);
}
async get(id) {
const all = await this.list();
return all.find((v) => v.id === id) ?? all[0] ?? null;
}
newId(name2) {
const base = name2.replace(/\.(pth|index)$/i, "").replace(/[^\w.-]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 40) || "voice";
return `${base}-${Date.now().toString(36)}`;
}
/** 网页上传:文件内容直接写进去。kind 是 model 还是 index */
async put(id, name2, kind, bytes) {
const vid = id && ID.test(id) ? id : this.newId(name2);
const dir = join7(this.dir, vid);
await mkdir5(dir, { recursive: true });
await writeFile5(join7(dir, kind === "model" ? "model.pth" : "model.index"), bytes);
const metaFile = join7(dir, "voice.json");
const meta = await readFile5(metaFile, "utf8").then(JSON.parse).catch(() => ({ name: name2.replace(/\.(pth|index)$/i, ""), addedAt: Date.now() }));
await writeFile5(metaFile, JSON.stringify(meta, null, 2));
return vid;
}
/** 从电脑上的路径导入(.pth,旁边同名或唯一的 .index 一起带上) */
async importPath(pth, name2) {
if (!/\.pth$/i.test(pth)) throw new Error("RVC \u58F0\u97F3\u6A21\u578B\u662F .pth \u6587\u4EF6");
const vid = this.newId(name2 || basename(pth));
const dir = join7(this.dir, vid);
await mkdir5(dir, { recursive: true });
await copyFile3(pth, join7(dir, "model.pth"));
const folder = join7(pth, "..");
const idx = (await readdir2(folder).catch(() => [])).filter((f) => /\.index$/i.test(f));
if (idx.length) await copyFile3(join7(folder, idx.length === 1 ? idx[0] : idx.find((f) => f.includes(basename(pth, ".pth"))) ?? idx[0]), join7(dir, "model.index"));
await writeFile5(join7(dir, "voice.json"), JSON.stringify({ name: name2 || basename(pth, ".pth"), addedAt: Date.now() }, null, 2));
return vid;
}
async remove(id) {
if (!ID.test(id)) return;
await rm2(join7(this.dir, id), { recursive: true, force: true });
}
async rename(id, name2) {
const metaFile = join7(this.dir, id, "voice.json");
const meta = JSON.parse(await readFile5(metaFile, "utf8"));
await writeFile5(metaFile, JSON.stringify({ ...meta, name: name2.slice(0, 40) }, null, 2));
}
};
// src/studio.ts
var Studio = class {
constructor(catalog, dataDir2, engineSrc, settings, onChange) {
this.catalog = catalog;
this.settings = settings;
this.setup = new Setup(join8(dataDir2, "engine"), engineSrc, onChange);
this.shelf = new Shelf(catalog, join8(dataDir2, "models"), onChange);
this.voices = new Voices(join8(dataDir2, "voices"));
}
catalog;
settings;
setup;
shelf;
voices;
preparing = false;
prepareError = null;
get manual() {
const s = this.settings();
return !!(s.python && s.config);
}
get mirror() {
return this.settings().mirror || this.catalog.mirror || "";
}
recipe() {
return resolveRecipe(this.catalog, this.settings().recipe);
}
/** 还缺什么(按要补的顺序) */
async needs() {
if (this.manual) return [];
const out = [];
if (!(await this.setup.ready()).ok) out.push({ kind: "env", name: "\u5B66\u6B4C\u73AF\u5883\uFF08Python + PyTorch\uFF0C\u7EA6 5 GB\uFF09", bytes: 5e9 });
for (const id of modelsFor(this.recipe().use)) {
if (!await this.shelf.installed(id)) out.push({ kind: "model", id, name: this.shelf.model(id)?.name ?? id, bytes: this.shelf.bytes(id) });
}
if (!(await this.voices.list()).length) out.push({ kind: "voice", name: "\u5979\u7684\u58F0\u97F3\uFF08RVC \u6A21\u578B .pth\uFF09" });
return out;
}
/** 给 Learner:一句话说缺什么 */
async check() {
const n = await this.needs();
if (!n.length) return null;
const first = n[0];
if (first.kind === "voice" && n.length === 1) return "\u8FD8\u6CA1\u6709\u5979\u7684\u58F0\u97F3\uFF1A\u5728\u300C\u5B66\u6B4C\u8BBE\u7F6E \u2192 \u58F0\u97F3\u300D\u5BFC\u5165\u4E00\u4E2A RVC \u6A21\u578B\uFF08.pth\uFF09";
return `\u5B66\u6B4C\u8FD8\u6CA1\u51C6\u5907\u597D\uFF1A\u8FD8\u7F3A${n.map((x) => x.name).join("\u3001")}\u3002\u5728\u300C\u5B66\u6B4C\u8BBE\u7F6E\u300D\u70B9\u300C\u4E00\u952E\u51C6\u5907\u300D\u5C31\u884C`;
}
/** 一键准备:缺什么补什么,不问用户 */
async prepare() {
if (this.preparing) return;
this.preparing = true;
this.prepareError = null;
try {
if (!(await this.setup.ready()).ok) await this.setup.install();
for (const id of modelsFor(this.recipe().use)) await this.shelf.download(id, this.mirror);
} catch (err) {
this.prepareError = err.message;
} finally {
this.preparing = false;
}
}
/** 跑学歌程序的环境变量:插件自己的环境要带上 ffmpeg 所在的 bin 目录 */
env(managed) {
const baseEnv = { ...process.env, PYTHONUTF8: "1", PYTHONIOENCODING: "utf-8" };
if (!managed) return baseEnv;
const sep = process.platform === "win32" ? ";" : ":";
return { ...baseEnv, KMP_DUPLICATE_LIB_OK: "TRUE", HF_HUB_OFFLINE: "1", PATH: `${join8(this.setup.root, "bin")}${sep}${process.env.PATH ?? ""}` };
}
/** 修音页的常驻进程用什么跑:学这首歌时的配置(配方模式在歌的目录里有 recipe.json;手动模式用设置里的 sing.json) */
async editRuntime(songDir) {
const own = join8(songDir, "recipe.json");
const managed = await stat4(own).then((st) => st.isFile(), () => false);
const cfgPath = managed ? own : this.settings().config;
if (!cfgPath) throw new Error("\u627E\u4E0D\u5230\u5B66\u8FD9\u9996\u6B4C\u65F6\u7528\u7684\u914D\u7F6E\uFF0C\u4FEE\u4E0D\u4E86");
const cfg = JSON.parse((await readFile6(cfgPath, "utf8")).replace(/^\uFEFF/, ""));
const python = String(cfg.rvcPython || (managed ? this.setup.python : this.settings().python));
return { python, env: this.env(managed), cfg: cfgPath };
}
async plan(out) {
const s = this.settings();
if (this.manual) return { python: s.python, config: s.config, key: null, remote: s.remote, env: this.env(false), recipe: "manual" };
const recipe = this.recipe();
const voice = await this.voices.get(s.voice);
const { config, key } = await buildConfig(this.catalog, recipe.use, this.shelf, this.setup, voice);
await mkdir6(out, { recursive: true });
const file = join8(out, "recipe.json");
await writeFile6(file, JSON.stringify({ recipe: recipe.id, voice: voice?.name, ...config }, null, 2));
return { python: this.setup.python, config: file, key, remote: "", recipe: recipe.id, env: this.env(true) };
}
async status() {
const recipe = this.recipe();
const models = await this.shelf.status();
return {
mode: this.manual ? "manual" : "recipe",
ready: !(await this.needs()).length,
needs: await this.needs(),
preparing: this.preparing || this.setup.running,
prepareError: this.prepareError,
env: { ready: (await this.setup.ready()).ok, steps: this.setup.steps, gpu: this.setup.gpu },
recipe,
recipes: this.catalog.recipes,
steps: this.catalog.steps,
models: this.catalog.models.map((m) => ({ ...m, files: void 0, msst: void 0, place: void 0, ...models.find((x) => x.id === m.id) })),
voices: await this.voices.list(),
voice: (await this.voices.get(this.settings().voice))?.id ?? null,
mirror: !!this.mirror
};
}
};
// src/library.ts
import { readdir as readdir3, readFile as readFile7, stat as stat5 } from "node:fs/promises";
import { join as join9 } from "node:path";
var ID2 = /^[\w-][\w.-]{0,79}$/;
var validId = (id) => !!id && ID2.test(id) && id !== "." && id !== "..";
var bvidOf = (id, source) => (id.match(/^(BV[0-9A-Za-z]{10})/) ?? source.match(/(BV[0-9A-Za-z]{10})/))?.[1] ?? null;
function summarize(id, d, learnedAt) {
const source = typeof d.source === "string" ? d.source : "";
const lyrics = Array.isArray(d.lyrics) ? d.lyrics.filter((l) => typeof l?.start === "number" && typeof l?.text === "string") : [];
return {
id,
title: String(d.title ?? id),
artist: String(d.artist ?? ""),
who: String(d.who ?? ""),
durationSec: Number(d.durationSec) || 0,
bvid: bvidOf(id, source),
hasLyrics: lyrics.length > 0,
keyShift: Number(d.keyShift) || 0,
learnedAt,
bpm: typeof d.bpm === "number" ? d.bpm : null,
beats: Array.isArray(d.beats) ? d.beats : [],
downbeats: Array.isArray(d.downbeats) ? d.downbeats : [],
sections: Array.isArray(d.sections) ? d.sections : [],
lyrics,
source
};
}
var brief = (s) => ({
id: s.id,
title: s.title,
artist: s.artist,
who: s.who,
durationSec: s.durationSec,
bvid: s.bvid,
hasLyrics: s.hasLyrics,
keyShift: s.keyShift,
learnedAt: s.learnedAt
});
var Library = class {
dirs;
cache = /* @__PURE__ */ new Map();
constructor(dirs) {
this.dirs = dirs;
}
setDirs(dirs) {
this.dirs = dirs;
this.cache.clear();
}
/** 歌所在的目录(找不到返回 null) */
async locate(id) {
const hit = this.cache.get(id);
if (hit) return hit.dir;
for (const root of this.dirs) {
const dir = join9(root, id);
if (await stat5(join9(dir, "song.json")).then((s) => s.isFile(), () => false)) return dir;
}
return null;
}
async load(id, dir) {
const file = join9(dir, "song.json");
const st = await stat5(file).catch(() => null);
if (!st) return null;
const hit = this.cache.get(id);
if (hit && hit.mtime === st.mtimeMs) return hit.song;
try {
const song = summarize(id, JSON.parse(await readFile7(file, "utf8")), st.mtimeMs);
this.cache.set(id, { mtime: st.mtimeMs, song, dir });
return song;
} catch {
return null;
}
}
async list() {
const seen = /* @__PURE__ */ new Set();
const out = [];
for (const root of this.dirs) {
const names = await readdir3(root).catch(() => []);
await Promise.all(names.map(async (name2) => {
if (!validId(name2) || seen.has(name2)) return;
seen.add(name2);
const song = await this.load(name2, join9(root, name2));
if (song) out.push(brief(song));
}));
}
return out.sort((a, b) => b.learnedAt - a.learnedAt);
}
async detail(id) {
const dir = await this.locate(id);
return dir ? this.load(id, dir) : null;
}
/** 歌所在的目录(修音页要读写里面的 edit/) */
async dirOf(id) {
return this.locate(id);
}
async audioPath(id) {
const dir = await this.locate(id);
if (!dir) return null;
const file = join9(dir, "mix.mp3");
return await stat5(file).then((s) => s.isFile(), () => false) ? file : null;
}
};
// src/index.ts
var name = "dsh-singinglab";
var inject = ["connection"];
var DEFAULTS = { libraries: [], python: "", config: "", remote: "", maxSec: 600, songsDir: "", recipe: { id: "recommended" }, voice: null, mirror: "" };
var dataDir = join10(process.env.DSH_HOME ?? join10(homedir(), ".dsh"), "dsh-singinglab");
var assetsDir = fileURLToPath(new URL("../assets/", import.meta.url));
var engineDir = fileURLToPath(new URL("../engine/", import.meta.url));
var ASSET_TYPES = {
".json": "application/json",
".webp": "image/webp",
".png": "image/png",
".jpg": "image/jpeg",
".jpeg": "image/jpeg"
};
var settingsFile = join10(dataDir, "settings.json");
var json = (value, status = 200) => new Response(JSON.stringify(value), { status, headers: { "content-type": "application/json", "cache-control": "no-store" } });
function normalize(raw) {
const str = (v, d) => typeof v === "string" ? v.trim() : d;
return {
libraries: Array.isArray(raw?.libraries) ? raw.libraries.filter((d) => typeof d === "string" && d.trim()) : DEFAULTS.libraries,
python: str(raw?.python, DEFAULTS.python),
config: str(raw?.config, DEFAULTS.config),
remote: str(raw?.remote, DEFAULTS.remote),
maxSec: Number(raw?.maxSec) > 0 ? Number(raw.maxSec) : DEFAULTS.maxSec,
songsDir: str(raw?.songsDir, DEFAULTS.songsDir),
recipe: raw?.recipe && typeof raw.recipe.id === "string" ? { id: raw.recipe.id, ...raw.recipe.custom ? { custom: raw.recipe.custom } : {} } : DEFAULTS.recipe,
voice: typeof raw?.voice === "string" && raw.voice ? raw.voice : null,
mirror: str(raw?.mirror, DEFAULTS.mirror)
};
}
async function readSettings() {
try {
return normalize(JSON.parse((await readFile8(settingsFile, "utf8")).replace(/^\uFEFF/, "")));
} catch {
return { ...DEFAULTS };
}
}
var songsDirOf = (s) => s.songsDir || join10(dataDir, "songs");
var libraryDirs = (s) => [songsDirOf(s), ...s.libraries];
async function serveFile(request, file, type, cache = "private, max-age=3600") {
const size = (await stat6(file)).size;
const range = request.headers.get("range")?.match(/^bytes=(\d*)-(\d*)$/);
const base = { "content-type": type, "accept-ranges": "bytes", "cache-control": cache };
if (!range || range[1] === "" && range[2] === "") {
return new Response(Readable2.toWeb(createReadStream2(file)), { headers: { ...base, "content-length": String(size) } });
}
let start = range[1] === "" ? size - Number(range[2]) : Number(range[1]);
let end = range[1] === "" || range[2] === "" ? size - 1 : Math.min(Number(range[2]), size - 1);
start = Math.max(0, start);
if (start > end || start >= size) return new Response(null, { status: 416, headers: { "content-range": `bytes */${size}` } });
return new Response(Readable2.toWeb(createReadStream2(file, { start, end })), {
status: 206,
headers: { ...base, "content-length": String(end - start + 1), "content-range": `bytes ${start}-${end}/${size}` }
});
}
function apply(ctx) {
let settings = { ...DEFAULTS };
const library = new Library(libraryDirs(settings));
const covers = new Covers(join10(dataDir, "covers"));
const bili = new Bili();
let learner = null;
let studio = null;
const save = async () => {
await mkdir7(dataDir, { recursive: true });
await writeFile7(settingsFile, JSON.stringify(settings, null, 2));
};
const ready = (async () => {
settings = await readSettings();
await mkdir7(songsDirOf(settings), { recursive: true }).catch(() => {
});
library.setDirs(libraryDirs(settings));
studio = new Studio(await loadCatalog(join10(assetsDir, "catalog.json")), dataDir, engineDir, () => settings, () => {
});
const st = studio;
learner = new Learner(bili, {
songsDir: songsDirOf(settings),
stateFile: join10(dataDir, "jobs.json"),
script: join10(assetsDir, "sing", "prepare.py"),
maxSec: () => settings.maxSec,
check: () => st.check(),
plan: (out) => st.plan(out),
onChange: () => {
}
});
Object.assign(runtime, { studio, learner, library, bili });
setStarted();
})();
runtime.ready = ready;
ctx.effect(() => () => learner?.close(), "dsh-singinglab learner");
const worker = new EditWorker(join10(assetsDir, "sing", "edit_worker.py"));
ctx.effect(() => () => worker.close(), "dsh-singinglab edit worker");
const route = (path, methods, fetch2) => ctx.effect(() => ctx.connection.fetch.register({
path,
methods,
requestBody: "buffered",
fetch: async (request) => {
await ready;
try {
return await fetch2(request);
} catch (err) {
return json({ ok: false, error: err.message }, 500);
}
}
}), `dsh-singinglab ${path}`);
const idOf = (request) => new URL(request.url).searchParams.get("id");
route("/api/dsh-singinglab/library", ["GET"], async () => json({ ok: true, songs: await library.list() }));
route("/api/dsh-singinglab/song", ["GET"], async (request) => {
const id = idOf(request);
if (!validId(id)) return json({ ok: false, error: "bad id" }, 400);
const song = await library.detail(id);
return song ? json({ ok: true, song }) : json({ ok: false, error: "\u6B4C\u5E93\u91CC\u6CA1\u6709\u8FD9\u9996" }, 404);
});
route("/api/dsh-singinglab/audio", ["GET"], async (request) => {
const id = idOf(request);
if (!validId(id)) return json({ ok: false, error: "bad id" }, 400);
const file = await library.audioPath(id);
return file ? serveFile(request, file, "audio/mpeg", "no-cache") : json({ ok: false, error: "\u6CA1\u6709\u97F3\u9891" }, 404);
});
const editable = async (id) => {
if (!validId(id)) throw new Error("bad id");
const dir = await library.dirOf(id);
if (!dir) throw new Error("\u6B4C\u5E93\u91CC\u6CA1\u6709\u8FD9\u9996");
if (!dir.startsWith(songsDirOf(settings))) throw new Error("\u8FD9\u9996\u5728\u53EA\u8BFB\u7684\u6B4C\u5E93\u76EE\u5F55\u91CC\uFF0C\u4FEE\u4E0D\u4E86");
if (!await hasEdit(dir)) throw Object.assign(new Error("\u8FD9\u9996\u662F\u4EE5\u524D\u5B66\u7684\uFF0C\u6CA1\u7559\u4E0B\u4FEE\u97F3\u8981\u7528\u7684\u5206\u8F68\uFF1A\u91CD\u5B66\u4E00\u904D\u5C31\u80FD\u4FEE"), { relearn: true });
return { dir, edit: editDir(dir), rt: await studio.editRuntime(dir) };
};
const f0In = (s) => typeof s === "string" && s.length < 4e6 ? s : null;
const STEMS = [
["orig", "orig.mp3", "audio/mpeg"],
["inst", "inst.mp3", "audio/mpeg"],
["vocals", "vocals.mp3", "audio/mpeg"],
["lead", "lead.mp3", "audio/mpeg"],
["back", "back.mp3", "audio/mpeg"],
["dry", "dry.flac", "audio/flac"]
];
const stemsIn = async (edit) => (await Promise.all(STEMS.map(async ([k, f]) => await stat6(join10(edit, f)).then(() => true, () => false) ? k : null))).filter((k) => !!k);
runtime.pitch = {
async open(id) {
const { dir, edit } = await editable(id);
const [raw, plan, state, song] = await Promise.all([readNpy(join10(edit, "raw.npy")), readNpy(join10(edit, "plan.npy")), readEditState(dir), library.detail(id)]);
if (!raw || !song) throw new Error("\u8FD9\u9996\u7684\u97F3\u9AD8\u8BFB\u4E0D\u5230");
return { song, raw, plan, state };
},
async save(id, ops, key) {
const { dir, edit, rt } = await editable(id);
const [raw, plan, state] = await Promise.all([readNpy(join10(edit, "raw.npy")), readNpy(join10(edit, "plan.npy")), readEditState(dir)]);
if (!raw) throw new Error("\u8FD9\u9996\u7684\u97F3\u9AD8\u8BFB\u4E0D\u5230");
const k = Math.max(-24, Math.min(24, Math.round(key)));
await writeEditState(dir, { ...state, key: k, ops: ops.slice(0, 2e3) });
const out = await worker.call(rt, { cmd: "save", dir: edit, cfg: rt.cfg, f0: b64(compose(raw, plan, ops)), key: k });
pushCommand({ type: "edited", songId: id });
return { sec: out.sec };
}
};
route("/api/dsh-singinglab/edit", ["GET"], async (request) => {
const id = idOf(request);
try {
const { dir, edit, rt } = await editable(id);
const info = await worker.call(rt, { cmd: "info", dir: edit, cfg: rt.cfg });
const [raw, plan, state, song] = await Promise.all([readNpy(join10(edit, "raw.npy")), readNpy(join10(edit, "plan.npy")), readEditState(dir), library.detail(id)]);
if (!raw) return json({ ok: false, error: "\u6CA1\u6709\u6D4B\u5230\u7684\u97F3\u9AD8" }, 500);
void worker.call(rt, { cmd: "warm", dir: edit, cfg: rt.cfg, key: state.key }).catch(() => {
});
return json({
ok: true,
id,
title: song?.title ?? id,
artist: song?.artist ?? "",
durationSec: info.durationSec,
frames: info.frames,
raw: b64(raw),
plan: plan ? b64(plan) : null,
state,
lyrics: song?.lyrics ?? [],
layers: await stemsIn(edit)
});
} catch (err) {
return json({ ok: false, error: err.message, relearn: !!err.relearn }, 409);
}
});
route("/api/dsh-singinglab/edit-spec", ["GET"], async (request) => {
const layer = new URL(request.url).searchParams.get("layer") ?? "vocals";
if (!STEMS.some(([k]) => k === layer)) return json({ ok: false, error: "bad layer" }, 400);
const { edit, rt } = await editable(idOf(request));
const out = await worker.call(rt, { cmd: "spec", dir: edit, layer });
return new Response(await readFile8(out.file), { headers: { "content-type": "image/png", "cache-control": "private, max-age=600" } });
});
route("/api/dsh-singinglab/edit-audio", ["GET"], async (request) => {
const q = new URL(request.url).searchParams;
const { edit, rt } = await editable(idOf(request));
const name2 = q.get("name");
const stem = STEMS.find(([k]) => k === name2);
if (stem) return serveFile(request, join10(edit, stem[1]), stem[2]);
if (name2 === "phrase") return serveFile(request, join10(edit, "phrase.wav"), "audio/wav", "no-store");
if (name2 === "accomp") {
const out = await worker.call(rt, { cmd: "accomp", dir: edit, key: Number(q.get("key")) || 0 });
return serveFile(request, out.file, "audio/mpeg");
}
return json({ ok: false, error: "bad name" }, 400);
});
route("/api/dsh-singinglab/edit-phrase", ["POST"], async (request) => {
const body = await request.json().catch(() => ({}));
const { edit, rt } = await editable(body.id ?? null);
const f0 = f0In(body.f0);
if (!f0 || !(Number(body.end) > Number(body.start))) return json({ ok: false, error: "\u8981\u6E32\u67D3\u54EA\u4E00\u6BB5\uFF1F" }, 400);
const out = await worker.call(rt, { cmd: "phrase", dir: edit, cfg: rt.cfg, start: Number(body.start), end: Math.min(Number(body.end), Number(body.start) + 60), f0, key: Number(body.key) || 0 });
return json({ ok: true, start: out.start, end: out.end, renderSec: out.renderSec });
});
route("/api/dsh-singinglab/edit-save", ["POST"], async (request) => {
const body = await request.json().catch(() => ({}));
const { dir, edit, rt } = await editable(body.id ?? null);
const f0 = f0In(body.f0);
if (!f0) return json({ ok: false, error: "\u6CA1\u6709\u97F3\u9AD8" }, 400);
const key = Math.max(-24, Math.min(24, Math.round(Number(body.key) || 0)));
const state = await readEditState(dir);
await writeEditState(dir, { ...state, key, ops: Array.isArray(body.ops) ? body.ops.slice(0, 2e3) : state.ops });
const out = await worker.call(rt, { cmd: "save", dir: edit, cfg: rt.cfg, f0, key });
return json({ ok: true, sec: out.sec, editedAt: out.editedAt });
});
route("/api/dsh-singinglab/cover", ["GET"], async (request) => {
const id = idOf(request);
if (!validId(id)) return json({ ok: false, error: "bad id" }, 400);
const song = await library.detail(id);
const bvid = song?.bvid ?? /^(BV[0-9A-Za-z]{10})-p\d+$/.exec(id)?.[1] ?? null;
const bytes = bvid ? await covers.get(bvid) : null;
if (!bytes) return new Response(null, { status: 404, headers: { "cache-control": "no-store" } });
return new Response(bytes, { headers: { "content-type": "image/jpeg", "cache-control": "private, max-age=86400" } });
});
route("/api/dsh-singinglab/asset", ["GET"], async (request) => {
const name2 = new URL(request.url).searchParams.get("name");
if (!name2 || !/^[\w.-]{1,80}$/.test(name2) || name2.startsWith(".")) return json({ ok: false, error: "bad name" }, 400);
const file = join10(assetsDir, name2);
if (!await stat6(file).then((s) => s.isFile(), () => false)) return json({ ok: false, error: "\u6CA1\u6709\u8FD9\u4E2A\u6587\u4EF6" }, 404);
const type = ASSET_TYPES[name2.slice(name2.lastIndexOf(".")).toLowerCase()] ?? "application/octet-stream";
return new Response(await readFile8(file), { headers: { "content-type": type, "cache-control": "private, max-age=600" } });
});
route("/api/dsh-singinglab/settings", ["GET", "POST"], async (request) => {
if (request.method === "POST") {
const body = await request.json().catch(() => ({}));
settings = normalize({ ...settings, ...body });
await save();
library.setDirs(libraryDirs(settings));
}
return json({ ok: true, settings, dataDir, missing: await studio.check() });
});
route("/api/dsh-singinglab/img", ["GET"], async (request) => {
const u = new URL(request.url).searchParams.get("u") ?? "";
if (!/^https:\/\/i\d\.hdslb\.com\/bfs\/[\w/.-]+\.(?:jpe?g|png|webp)$/i.test(u)) return json({ ok: false, error: "bad url" }, 400);
const res = await fetch(`${u}@480w_300h_1c.jpg`, { headers: { Referer: "https://www.bilibili.com/" }, signal: AbortSignal.timeout(1e4) }).catch(() => null);
if (!res?.ok) return new Response(null, { status: 404 });
return new Response(new Uint8Array(await res.arrayBuffer()), { headers: { "content-type": "image/jpeg", "cache-control": "private, max-age=86400" } });
});
route("/api/dsh-singinglab/search", ["POST"], async (request) => {
const body = await request.json().catch(() => ({}));
const q = String(body.q ?? "").trim().slice(0, 80);
if (!q) return json({ ok: false, error: "\u8981\u641C\u4EC0\u4E48\uFF1F" }, 400);
const ref = parseVideoRef(q);
if (ref) {
const info = await bili.info(ref.bvid);
if (!info) return json({ ok: false, error: "\u627E\u4E0D\u5230\u8FD9\u4E2A\u89C6\u9891" }, 404);
const part = info.parts.find((p) => p.page === ref.page) ?? info.parts[0];
return json({ ok: true, hits: [{ bvid: info.bvid, page: part?.page ?? 1, title: info.title, up: info.up, durationSec: part?.durationSec ?? info.durationSec, views: 0, cover: info.cover, guess: guessTitle(info.title) }] });
}
const hits = await bili.search(q);
if (!hits) return json({ ok: false, error: "B \u7AD9\u641C\u7D22\u6682\u65F6\u7528\u4E0D\u4E86\uFF0C\u8FC7\u4E00\u4F1A\u513F\u518D\u8BD5" }, 502);
return json({ ok: true, hits: hits.map((h) => ({ ...h, page: 1, guess: guessTitle(h.title, q) })) });
});
route("/api/dsh-singinglab/learn", ["POST"], async (request) => {
const body = await request.json().catch(() => ({}));
const ref = parseVideoRef(String(body.bvid ?? ""));
if (!ref || !learner) return json({ ok: false, error: "\u6CA1\u6709 BV \u53F7" }, 400);
const lack = await studio.check();
if (lack) return json({ ok: false, error: lack, needs: await studio.needs() }, 409);
const job = learner.learn({ bvid: ref.bvid, page: body.page ?? ref.page, title: String(body.title ?? ""), artist: body.artist, autoplay: body.autoplay !== false, relearn: body.relearn === true });
return json({ ok: true, job });
});
route("/api/dsh-singinglab/jobs", ["GET"], async (request) => {
const after = Number(new URL(request.url).searchParams.get("after") ?? 0);
return json({ ok: true, jobs: learner?.jobs ?? [], missing: await studio.check(), commands: runtime.commands.filter((c) => c.id > after) });
});
route("/api/dsh-singinglab/studio", ["GET"], async () => json({ ok: true, ...await studio.status() }));
route("/api/dsh-singinglab/prepare", ["POST"], async () => {
void studio.prepare();
return json({ ok: true, started: true });
});
route("/api/dsh-singinglab/recipe", ["POST"], async (request) => {
const body = await request.json().catch(() => ({}));
if (typeof body.id !== "string") return json({ ok: false, error: "\u8981\u54EA\u4E2A\u914D\u65B9\uFF1F" }, 400);
settings = normalize({ ...settings, recipe: body });
await save();
return json({ ok: true, recipe: studio.recipe(), needs: await studio.needs() });
});
route("/api/dsh-singinglab/model", ["POST"], async (request) => {
const body = await request.json().catch(() => ({}));
if (!body.id || !studio.shelf.model(body.id)) return json({ ok: false, error: "\u8D27\u67B6\u4E0A\u6CA1\u6709\u8FD9\u4E2A\u6A21\u578B" }, 404);
void studio.shelf.download(body.id, studio.mirror).catch(() => {
});
return json({ ok: true, started: true });
});
route("/api/dsh-singinglab/import", ["POST"], async (request) => {
const body = await request.json().catch(() => ({}));
const dirs = (body.dirs ?? []).filter((d) => typeof d === "string" && d.trim());
if (!dirs.length) return json({ ok: false, error: "\u8981\u4ECE\u54EA\u4E2A\u6587\u4EF6\u5939\u5BFC\u5165\uFF1F" }, 400);
return json({ ok: true, imported: await studio.shelf.importFrom(dirs) });
});
route("/api/dsh-singinglab/voice", ["POST"], async (request) => {
const q = new URL(request.url).searchParams;
const kind = q.get("kind") === "index" ? "index" : "model";
const name2 = (q.get("name") ?? "voice").slice(0, 80);
const bytes = new Uint8Array(await request.arrayBuffer());
if (bytes.length < 1e3) return json({ ok: false, error: "\u6587\u4EF6\u662F\u7A7A\u7684" }, 400);
const id = await studio.voices.put(q.get("id"), name2, kind, bytes);
if (kind === "model" && !settings.voice) {
settings = normalize({ ...settings, voice: id });
await save();
}
return json({ ok: true, id });
});
route("/api/dsh-singinglab/voice-import", ["POST"], async (request) => {
const body = await request.json().catch(() => ({}));
if (!body.path) return json({ ok: false, error: "\u6A21\u578B\u6587\u4EF6\u5728\u54EA\uFF1F" }, 400);
const id = await studio.voices.importPath(body.path, body.name);
settings = normalize({ ...settings, voice: id });
await save();
return json({ ok: true, id });
});
route("/api/dsh-singinglab/voice-use", ["POST"], async (request) => {
const body = await request.json().catch(() => ({}));
settings = normalize({ ...settings, voice: body.id ?? null });
await save();
return json({ ok: true });
});
route("/api/dsh-singinglab/voice-remove", ["POST"], async (request) => {
const body = await request.json().catch(() => ({}));
if (body.id) await studio.voices.remove(body.id);
if (settings.voice === body.id) {
settings = normalize({ ...settings, voice: null });
await save();
}
return json({ ok: true });
});
route("/api/dsh-singinglab/voice-rename", ["POST"], async (request) => {
const body = await request.json().catch(() => ({}));
if (body.id && body.name) await studio.voices.rename(body.id, body.name);
return json({ ok: true });
});
route("/api/dsh-singinglab/cancel", ["POST"], async (request) => {
const body = await request.json().catch(() => ({}));
return json({ ok: !!learner?.cancel(String(body.id ?? "")) });
});
}
export {
apply,
inject,
name
};
//# sourceMappingURL=index.js.map