UNPKG

dsh-singinglab

Version:

A music player for DeepSeek Harness where 大肥鱼 sings: tell her a song, she learns it on your machine and plays it.

351 lines (347 loc) • 10.4 kB
// src/bili.ts import crypto from "node:crypto"; var UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36"; var TIMEOUT_MS = 1e4; var SESSION_TTL_MS = 30 * 6e4; var MIXIN_TABLE = [ 46, 47, 18, 2, 53, 8, 23, 32, 15, 50, 10, 31, 58, 3, 45, 35, 27, 43, 5, 49, 33, 9, 42, 19, 29, 28, 14, 39, 12, 38, 41, 13, 37, 48, 7, 16, 24, 55, 40, 61, 26, 17, 0, 1, 60, 51, 30, 4, 22, 25, 54, 21, 56, 59, 6, 63, 57, 62, 11, 36, 20, 34, 44, 52 ]; function clean(value, max = 120) { const text = String(value ?? "").replace(/<[^>]*>/g, "").replace(/&(amp|lt|gt|quot|#39|nbsp);/g, (_, e) => ({ amp: "&", lt: "<", gt: ">", quot: '"', "#39": "'", nbsp: " " })[e] ?? "").replace(/[\u0000-\u001f\u007f]/g, " ").replace(/\s+/g, " ").trim(); return text.length > max ? `${text.slice(0, max - 1)}\u2026` : text; } var clockSec = (text) => String(text ?? "").split(":").reduce((sum, n) => sum * 60 + (Number(n) || 0), 0); var https = (url) => String(url ?? "").replace(/^(?:http:)?\/\//, "https://"); function signWbi(params, mixinKey, nowSec = Math.floor(Date.now() / 1e3)) { const all = { ...params, wts: nowSec }; const query = Object.keys(all).sort().map((k) => `${encodeURIComponent(k)}=${encodeURIComponent(String(all[k]).replace(/[!'()*]/g, ""))}`).join("&"); return `${query}&w_rid=${crypto.createHash("md5").update(query + mixinKey).digest("hex")}`; } function parseVideoRef(text) { const bvid = /BV[0-9A-Za-z]{10}/.exec(text)?.[0]; if (!bvid) return null; const page = Number(/[?&]p=(\d+)/.exec(text)?.[1]) || void 0; return { bvid, ...page ? { page } : {} }; } var Bili = class { session = null; sessionAt = 0; tail = Promise.resolve(); auth() { if (!this.session || Date.now() - this.sessionAt > SESSION_TTL_MS) { this.sessionAt = Date.now(); this.session = (async () => { const spi = await fetch("https://api.bilibili.com/x/frontend/finger/spi", { headers: { "User-Agent": UA }, signal: AbortSignal.timeout(TIMEOUT_MS) }).then((r) => r.json()); const cookie = `buvid3=${spi.data?.b_3 ?? ""}; buvid4=${encodeURIComponent(spi.data?.b_4 ?? "")}`; const nav = await fetch("https://api.bilibili.com/x/web-interface/nav", { headers: { "User-Agent": UA, Cookie: cookie, Referer: "https://www.bilibili.com/" }, signal: AbortSignal.timeout(TIMEOUT_MS) }).then((r) => r.json()); const img = nav.data?.wbi_img; if (!img) throw new Error("B \u7AD9\u7B7E\u540D\u5BC6\u94A5\u62FF\u4E0D\u5230"); const key = (url) => url.slice(url.lastIndexOf("/") + 1).split(".")[0]; const raw = key(img.img_url) + key(img.sub_url); return { cookie, mixinKey: MIXIN_TABLE.map((i) => raw[i]).join("").slice(0, 32) }; })(); this.session.catch(() => { this.session = null; }); } return this.session; } /** 一个接一个发 */ get(url) { const run = async () => { try { const s = await this.auth(); const target = typeof url === "string" ? url : await url(); const res = await fetch(target, { headers: { "User-Agent": UA, Referer: "https://www.bilibili.com/", Cookie: s.cookie }, signal: AbortSignal.timeout(TIMEOUT_MS) }); if (!res.ok) return null; return await res.json(); } catch { return null; } }; const turn = this.tail.then(run, run); this.tail = turn; return turn; } signed(base, params) { return async () => `${base}?${signWbi(params, (await this.auth()).mixinKey)}`; } async search(query, page = 1, retry = true) { const body = await this.get(this.signed("https://api.bilibili.com/x/web-interface/wbi/search/type", { search_type: "video", keyword: query, page })); if (retry && (body?.code !== 0 || !body.data?.result?.length)) { this.session = null; await new Promise((r) => setTimeout(r, 1200)); return this.search(query, page, false); } if (body?.code !== 0) return null; return (body.data?.result ?? []).filter((v) => v?.bvid).slice(0, 20).map((v) => ({ bvid: v.bvid, title: clean(v.title, 90), up: clean(v.author, 30), durationSec: clockSec(v.duration), views: Number(v.play) || 0, cover: https(v.pic) })); } async info(bvid) { const body = await this.get(`https://api.bilibili.com/x/web-interface/view?bvid=${bvid}`); const d = body?.code === 0 ? body.data : null; if (!d?.bvid) return null; return { bvid: d.bvid, title: clean(d.title, 100), up: clean(d.owner?.name, 30), durationSec: Number(d.duration) || 0, cover: https(d.pic), parts: (d.pages ?? []).map((p) => ({ cid: Number(p.cid), page: Number(p.page), title: clean(p.part, 60), durationSec: Number(p.duration) || 0 })) }; } /** 码率最高的那条音频和读它要带的请求头 */ async audio(bvid, cid) { const body = await this.get( this.signed("https://api.bilibili.com/x/player/wbi/playurl", { bvid, cid, fnval: 16, fourk: 0 }) ); const audio = (body?.code === 0 ? body.data?.dash?.audio ?? [] : []).filter((a) => a.baseUrl || a.base_url); audio.sort((a, b) => (b.bandwidth ?? 0) - (a.bandwidth ?? 0)); const url = audio[0]?.baseUrl ?? audio[0]?.base_url; return url ? { url, headers: { Referer: "https://www.bilibili.com/", "User-Agent": UA } } : null; } }; function guessTitle(videoTitle, query = "") { const q = query.trim(); if (q && q.length <= 20 && videoTitle.toLowerCase().includes(q.toLowerCase())) return q; const t = videoTitle.replace(/【[^】]*】|\[[^\]]*\]|([^)]*)|\([^)]*\)/g, " ").replace(/\b(MV|PV|Official|Lyrics?|Video|Audio|HD|4K|Hi-?Res)\b/gi, " ").replace(/官方|高音质|无损|完整版|动态歌词|歌词版|中文字幕|中字|修复版|重制版|\d{3,4}[Pp]|\d+FPS|音质/g, " ").replace(/\s+/g, " ").trim(); const quoted = /《([^》]{1,40})》/.exec(videoTitle)?.[1] ?? /「([^」]{1,40})」/.exec(videoTitle)?.[1]; return (quoted ?? t ?? videoTitle).slice(0, 40) || videoTitle.slice(0, 40); } // src/runtime.ts var runtime = { ready: null, studio: null, learner: null, library: null, bili: null, pitch: null, commands: [] }; var markStarted = () => { }; var started = new Promise((resolve) => { markStarted = resolve; }); function setStarted() { markStarted(); } var nextCommand = 1; function pushCommand(cmd) { runtime.commands.push({ ...cmd, id: nextCommand++ }); if (runtime.commands.length > 20) runtime.commands.splice(0, runtime.commands.length - 20); } // src/pitch.ts var FPS = 100; var NAMES = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"]; var midiOf = (hz) => 69 + 12 * Math.log2(hz / 440); var hzOf = (m) => 440 * 2 ** ((m - 69) / 12); var noteName = (m) => `${NAMES[(Math.round(m) % 12 + 12) % 12]}${Math.floor(Math.round(m) / 12) - 1}`; var HOARSE_FROM = 42; var HOARSE = [ 0.68, 0.73, 0.68, 0.74, 0.57, 0.56, 0.39, 0.34, 0.24, 0.19, 0.24, 0.14, 0.16, 0.14, 0.14, 0.17, 0.1, 0.08, 0.07, 0.08, 0.05, 0.05, 0.05, 0.05, 0.04, 0.04, 0.04, 0.05, 0.03, 0.03, 0.04, 0.03, 0.04, 0.07, 0.06, 0.28, 0.56, 0.83, 0.97, 0.98, 1, 0.99, 1, 1 ]; var hoarseAt = (m) => HOARSE[Math.min(HOARSE.length - 1, Math.max(0, Math.round(m) - HOARSE_FROM))]; var HER_LOW = 58; var HER_HIGH = 76; var marksOf = (ops) => ops.flatMap((o) => o.kind === "cut" ? [{ kind: "cut", a: o.a }] : o.kind === "join" ? [{ kind: "join", a: o.a, b: o.b }] : []); var medianMidi = (f, a, b) => { const ms = []; for (let i = a; i < b; i++) if (f[i] > 0) ms.push(midiOf(f[i])); ms.sort((x, y) => x - y); return ms.length ? ms[ms.length >> 1] : 0; }; function notesOf(f, marks = [], offset = 0) { let out = autoNotes(f); for (const m of marks) { if (m.kind === "cut") { const c = m.a - offset; out = out.flatMap((n) => c - n.a >= 2 && n.b - c >= 2 ? [{ a: n.a, b: c, midi: medianMidi(f, n.a, c) }, { a: c, b: n.b, midi: medianMidi(f, c, n.b) }] : [n]); } else { const a = m.a - offset, b = m.b - offset; const hit = out.filter((n) => n.a < b && n.b > a); if (hit.length < 2) continue; const lo = Math.min(...hit.map((n) => n.a)), hi = Math.max(...hit.map((n) => n.b)); out = [...out.filter((n) => !hit.includes(n)), { a: lo, b: hi, midi: medianMidi(f, lo, hi) }].sort((x, y) => x.a - y.a); } } return out; } function autoNotes(f) { const out = []; let a = -1; const push = (b) => { if (a >= 0 && b - a >= 4) { const ms = Array.from(f.subarray(a, b)).map(midiOf).sort((x, y) => x - y); out.push({ a, b, midi: ms[ms.length >> 1] }); } }; for (let i = 0; i <= f.length; i++) { const v = i < f.length && f[i] > 0; if (!v) { push(i); a = -1; continue; } if (a < 0) { a = i; continue; } if (Math.abs(midiOf(f[i]) - midiOf(f[i - 1])) > 0.8) { push(i); a = i; } } return out; } function compose(raw, plan, ops) { const f = Float32Array.from(plan ?? raw); for (let k = 0; k < ops.length; k++) { const op = ops[k]; if (op.kind === "cut" || op.kind === "join") continue; const a = Math.max(0, op.a), b = Math.min(f.length, op.b); if (op.kind === "snap" || op.kind === "tune") { const center = op.kind === "snap" ? 1 : op.center, flatten = op.kind === "snap" ? 0 : op.flatten; for (const n of notesOf(f.subarray(a, b), marksOf(ops.slice(0, k)), a)) { const target = n.midi + (Math.round(n.midi) - n.midi) * center; for (let i = a + n.a; i < a + n.b; i++) if (f[i] > 0) f[i] = hzOf(target + (midiOf(f[i]) - n.midi) * (1 - flatten)); } continue; } for (let i = a; i < b; i++) { if (op.kind === "source") f[i] = op.source === "raw" ? raw[i] : (plan ?? raw)[i]; else if (op.kind === "draw") { const hz = op.hz[i - op.a]; if (f[i] > 0 && hz > 0) f[i] = hz; } else if (f[i] > 0) f[i] *= 2 ** (op.semitones / 12); } } return f; } export { parseVideoRef, Bili, guessTitle, runtime, started, setStarted, pushCommand, FPS, midiOf, noteName, hoarseAt, HER_LOW, HER_HIGH, marksOf, notesOf, compose }; //# sourceMappingURL=chunk-D3K3RT55.js.map