dsh-eplan 0.0.0-stage → 0.14.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +219 -3
- package/cordis.patch.yml +182 -0
- package/docs/INSTALL.md +86 -0
- package/docs/LESSONS.md +224 -0
- package/docs/interfaces.md +183 -0
- package/docs/merged-skills/eplan-setup.md +63 -0
- package/docs/merged-skills/eplan-troubleshooting.md +149 -0
- package/icon.png +0 -0
- package/icon.svg +13 -0
- package/knowledge/KNOWLEDGE.md +413 -0
- package/knowledge/symbols/BP.png +0 -0
- package/knowledge/symbols/CDPST.png +0 -0
- package/knowledge/symbols/CO.png +0 -0
- package/knowledge/symbols/FA3.png +0 -0
- package/knowledge/symbols/TLRO.png +0 -0
- package/knowledge/symbols/TLRU.png +0 -0
- package/knowledge/symbols/TOUL.png +0 -0
- package/knowledge/symbols/TOUR.png +0 -0
- package/knowledge/symbols/manifest.json +91 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/native/bridge/build.ps1 +73 -0
- package/native/bridge/src/Json.cs +383 -0
- package/native/bridge/src/Program.cs +1133 -0
- package/native/host/build.ps1 +74 -0
- package/native/host/src/ActionsTool.cs +225 -0
- package/native/host/src/BoxTool.cs +196 -0
- package/native/host/src/CheckTool.cs +186 -0
- package/native/host/src/Context.cs +169 -0
- package/native/host/src/DarkScheme.cs +111 -0
- package/native/host/src/DiagnoseTool.cs +115 -0
- package/native/host/src/Dispatcher.cs +51 -0
- package/native/host/src/DrawTool.cs +316 -0
- package/native/host/src/Entry.cs +111 -0
- package/native/host/src/ExportTool.cs +213 -0
- package/native/host/src/InspectTool.cs +367 -0
- package/native/host/src/KnowledgeTool.cs +166 -0
- package/native/host/src/LookTool.cs +257 -0
- package/native/host/src/OpLog.cs +289 -0
- package/native/host/src/PageCreateTool.cs +521 -0
- package/native/host/src/PageOpenTool.cs +62 -0
- package/native/host/src/PagesTool.cs +95 -0
- package/native/host/src/Paths.cs +91 -0
- package/native/host/src/PlacementEditTool.cs +234 -0
- package/native/host/src/ProbePropsTool.cs +152 -0
- package/native/host/src/ProjectCreateTool.cs +176 -0
- package/native/host/src/ProjectTool.cs +167 -0
- package/native/host/src/PropWriter.cs +70 -0
- package/native/host/src/PropsTool.cs +257 -0
- package/native/host/src/StatusTool.cs +168 -0
- package/native/host/src/SymbolInfoTool.cs +144 -0
- package/native/host/src/SymbolInsertTool.cs +261 -0
- package/native/host/src/SymbolsTool.cs +94 -0
- package/native/host/src/TagLocTool.cs +108 -0
- package/native/script/EplanMcpBootstrap.cs +221 -0
- package/native/script/build-symbol-gallery.mjs +231 -0
- package/native/script/prepare-install.ps1 +57 -0
- package/native/script/prune.mjs +132 -0
- package/native/script/verify-bootstrap.ps1 +62 -0
- package/package.json +53 -4
- package/preset/bootstrap.js +498 -0
- package/preset/experience-nudge.js +47 -0
- package/preset/image-budget.js +175 -0
- package/preset/knowledge-tool.js +180 -0
- package/preset/mcp-link.js +100 -0
- package/preset/prompt-surface.js +76 -0
- package/preset/restrict-tools.js +141 -0
- package/preset/skill-docs.js +181 -0
- package/preset/video-digest.js +294 -0
- package/preset/video-tool.js +92 -0
- package/server/compact.mjs +623 -0
- package/server/edit-args.mjs +67 -0
- package/server/fuzzy.mjs +57 -0
- package/server/launch-decision.mjs +26 -0
- package/server/measure.mjs +320 -0
- package/server/pdf.mjs +185 -0
- package/server/pdf2png.ps1 +99 -0
- package/server/server.mjs +3797 -0
- package/server/video.mjs +857 -0
- package/setup.mjs +223 -0
- package/skills/eplan-annotations/SKILL.md +55 -0
- package/skills/eplan-drawing/SKILL.md +206 -0
- package/skills/eplan-project/SKILL.md +41 -0
- package/skills/eplan-review/SKILL.md +80 -0
- package/skills/eplan-symbols/SKILL.md +142 -0
- package/test/check-docs.mjs +106 -0
- package/test/foreground.ps1 +21 -0
- package/test/smoke-all.mjs +229 -0
package/server/video.mjs
ADDED
|
@@ -0,0 +1,857 @@
|
|
|
1
|
+
// 视频摘要管线:把一段录屏压成「几段 + 每段一张整页图 + 讲解文字」。
|
|
2
|
+
//
|
|
3
|
+
// 设计原则(2026-11-23 用户要求):
|
|
4
|
+
// 1. 模型不该反复看视频、抽帧、放大细节 —— 那是工具的活。发送时就把视频变成摘要。
|
|
5
|
+
// 2. 切分依据是**页码变化**(标题栏/标签),不是整屏 scene 阈值:
|
|
6
|
+
// 画图时画面一直在小改,全局 scene 只能给出 1 帧(实测 248 s 录屏只出 1 帧)。
|
|
7
|
+
// 3. 没有讲解就要**明说没有**,并且转写失败必须带出原因,不许静默给空字符串。
|
|
8
|
+
//
|
|
9
|
+
// 只做事实,不做猜测:探测、切分、取图、量响度、切语音都由这里算;
|
|
10
|
+
// 转写由调用方注入(DSH 的 speechToText 服务在 Host 进程内,这里够不到)。
|
|
11
|
+
//
|
|
12
|
+
// 命令行:
|
|
13
|
+
// node video.mjs --path <视频> [--max-pages 6] [--at 136] [--series]
|
|
14
|
+
// 输出一行 JSON 到 stdout。
|
|
15
|
+
|
|
16
|
+
import { spawn } from 'node:child_process'
|
|
17
|
+
import { copyFileSync, mkdirSync, existsSync, statSync, rmSync, readFileSync, writeFileSync } from 'node:fs'
|
|
18
|
+
import { join, resolve as resolvePath } from 'node:path'
|
|
19
|
+
import { homedir, tmpdir } from 'node:os'
|
|
20
|
+
import { createHash } from 'node:crypto'
|
|
21
|
+
|
|
22
|
+
const FFMPEG_CANDIDATES = [
|
|
23
|
+
process.env.EPLAN_MCP_FFMPEG,
|
|
24
|
+
join(process.env.LOCALAPPDATA ?? '', 'Programs', 'ffmpeg', 'bin', 'ffmpeg.exe'),
|
|
25
|
+
'C:/ffmpeg/bin/ffmpeg.exe',
|
|
26
|
+
].filter(Boolean)
|
|
27
|
+
|
|
28
|
+
export function findBinary(name) {
|
|
29
|
+
const explicit = name === 'ffmpeg' ? process.env.EPLAN_MCP_FFMPEG : process.env.EPLAN_MCP_FFPROBE
|
|
30
|
+
if (explicit && existsSync(explicit)) return explicit
|
|
31
|
+
for (const candidate of FFMPEG_CANDIDATES) {
|
|
32
|
+
const sibling = candidate.replace(/ffmpeg\.exe$/i, `${name}.exe`)
|
|
33
|
+
if (existsSync(sibling)) return sibling
|
|
34
|
+
}
|
|
35
|
+
return `${name}.exe` // 交给 PATH,找不到由 spawn 报 ENOENT。
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** 跑一个进程,按需收集 stdout / stderr。 */
|
|
39
|
+
function run(bin, args, { collectStdout = true, cwd } = {}) {
|
|
40
|
+
return new Promise((resolvePromise, reject) => {
|
|
41
|
+
const child = spawn(bin, args, { windowsHide: true, cwd })
|
|
42
|
+
const out = []
|
|
43
|
+
const err = []
|
|
44
|
+
child.stdout?.on('data', (chunk) => { if (collectStdout) out.push(chunk) })
|
|
45
|
+
child.stderr?.on('data', (chunk) => { err.push(chunk) })
|
|
46
|
+
child.on('error', (error) => reject(error))
|
|
47
|
+
child.on('close', (code) => {
|
|
48
|
+
resolvePromise({
|
|
49
|
+
code,
|
|
50
|
+
stdout: Buffer.concat(out).toString('utf8'),
|
|
51
|
+
stderr: Buffer.concat(err).toString('utf8'),
|
|
52
|
+
})
|
|
53
|
+
})
|
|
54
|
+
})
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function fail(code, message) {
|
|
58
|
+
const error = new Error(message)
|
|
59
|
+
error.code = code
|
|
60
|
+
return error
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
// ---------------------------------------------------------------------------
|
|
64
|
+
// 硬件解码。
|
|
65
|
+
//
|
|
66
|
+
// 采样一遍整段录屏要把每一帧都解码,这是这条流水线里最贵的一步。
|
|
67
|
+
// 实测(1080p H.264、631 s、fps=1 采样一遍,同一台机器):
|
|
68
|
+
//
|
|
69
|
+
// 纯 CPU 20.0 s
|
|
70
|
+
// cuda + 只在采样后下载(本文件用法) 9.5 s
|
|
71
|
+
// d3d11va + 只在采样后下载 10.9 s
|
|
72
|
+
// cuda 不带 output_format(隐式逐帧下载) 27–52 s ← 比 CPU 还慢
|
|
73
|
+
//
|
|
74
|
+
// 结论不是「开硬件解码就快」,而是「哪些帧被拷回内存」:
|
|
75
|
+
// 把 fps 放在 GPU 上跑、每秒只 hwdownload 那一帧才省;逐帧下载会把省下的
|
|
76
|
+
// 解码时间全赔在显存→内存的拷贝上。所以这里固定用
|
|
77
|
+
// `-hwaccel X -hwaccel_output_format Y` + 滤镜里 fps 之后立刻 hwdownload。
|
|
78
|
+
//
|
|
79
|
+
// 单帧取图(grabFrame)**不**走硬件:每次调用要建一次解码上下文,
|
|
80
|
+
// 实测比软件解码慢,而单帧本来就是几十毫秒的事。
|
|
81
|
+
// ---------------------------------------------------------------------------
|
|
82
|
+
let hwProbe = null
|
|
83
|
+
// 这次进程里已经证明硬件解码跑不动(个别编码/驱动组合),别再试第二遍。
|
|
84
|
+
let hwFailed = false
|
|
85
|
+
|
|
86
|
+
/** 让测试和长跑进程能重新探测(换机器、换驱动、改环境变量的场景)。 */
|
|
87
|
+
export function resetHardwareState() {
|
|
88
|
+
hwProbe = null
|
|
89
|
+
hwFailed = false
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** ffmpeg 这台机器上到底支持哪些硬件解码器,只问一次。 */
|
|
93
|
+
async function availableAccel(ffmpeg) {
|
|
94
|
+
if (hwProbe) return hwProbe
|
|
95
|
+
let models = []
|
|
96
|
+
try {
|
|
97
|
+
const result = await run(ffmpeg, ['-hide_banner', '-hwaccels'])
|
|
98
|
+
models = result.stdout
|
|
99
|
+
.split('\n')
|
|
100
|
+
.map((line) => line.trim().toLowerCase())
|
|
101
|
+
.filter((line) => line && !line.endsWith(':'))
|
|
102
|
+
} catch {
|
|
103
|
+
models = [] // 连 -hwaccels 都跑不了就当没有硬件,走软件解码。
|
|
104
|
+
}
|
|
105
|
+
hwProbe = { models }
|
|
106
|
+
return hwProbe
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* 决定这次采样用不用硬件解码。
|
|
111
|
+
*
|
|
112
|
+
* 短片段不用:建一次解码上下文在 12 秒测试片上实测 342 ms,而纯软件只要 90 ms,
|
|
113
|
+
* 硬件解码省下的是「解码每一帧」的时间,片太短还没摊平初始化的开销。
|
|
114
|
+
* 默认门槛 120 秒,可用 EPLAN_MCP_HWACCEL_MIN_SECONDS 调;
|
|
115
|
+
* 显式写 EPLAN_MCP_HWACCEL=cuda / d3d11va 表示强制用(短片段也照用)。
|
|
116
|
+
*/
|
|
117
|
+
async function pickHwAccel(ffmpeg, seconds = 0) {
|
|
118
|
+
if (hwFailed) return null
|
|
119
|
+
const setting = String(process.env.EPLAN_MCP_HWACCEL ?? 'auto').trim().toLowerCase()
|
|
120
|
+
if (setting === 'off' || setting === 'none' || setting === '0') return null
|
|
121
|
+
|
|
122
|
+
const forced = setting !== 'auto' && setting !== 'always'
|
|
123
|
+
if (!forced) {
|
|
124
|
+
const minSeconds = Number(process.env.EPLAN_MCP_HWACCEL_MIN_SECONDS ?? 120)
|
|
125
|
+
if (Number.isFinite(minSeconds) && seconds < minSeconds) return null
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
const { models } = await availableAccel(ffmpeg)
|
|
129
|
+
const preferred = forced ? [setting] : ['cuda', 'd3d11va']
|
|
130
|
+
const model = preferred.find((name) => models.includes(name)) ?? null
|
|
131
|
+
if (!model) return null
|
|
132
|
+
const format = model === 'cuda' ? 'cuda' : model === 'd3d11va' ? 'd3d11' : model
|
|
133
|
+
process.stderr.write(`[eplan-mcp] 视频解码走硬件:${model}(${Math.round(seconds)} 秒素材)\n`)
|
|
134
|
+
return { model, format }
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
function round2(value) { return Math.round(value * 100) / 100 }
|
|
138
|
+
|
|
139
|
+
function clamp(value, low, high) { return Math.min(high, Math.max(low, value)) }
|
|
140
|
+
|
|
141
|
+
/** 秒 → m:ss 便于人读。 */
|
|
142
|
+
export function clock(seconds) {
|
|
143
|
+
const total = Math.max(0, Math.round(seconds))
|
|
144
|
+
const minutes = Math.floor(total / 60)
|
|
145
|
+
const rest = total % 60
|
|
146
|
+
return `${minutes}:${String(rest).padStart(2, '0')}`
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/** 视频元信息。 */
|
|
150
|
+
export async function probe(path) {
|
|
151
|
+
if (!existsSync(path)) throw fail('VIDEO_NOT_FOUND', `找不到视频文件:${path}`)
|
|
152
|
+
const ffprobe = findBinary('ffprobe')
|
|
153
|
+
let result
|
|
154
|
+
try {
|
|
155
|
+
result = await run(ffprobe, ['-v', 'error', '-print_format', 'json', '-show_format', '-show_streams', path])
|
|
156
|
+
} catch (error) {
|
|
157
|
+
throw fail('VIDEO_NO_FFMPEG', `调用 ffprobe 失败:${error.message}。可以用 EPLAN_MCP_FFMPEG 指定 ffmpeg 路径。`)
|
|
158
|
+
}
|
|
159
|
+
if (result.code !== 0) throw fail('VIDEO_UNREADABLE', `ffprobe 读不了这个文件:${result.stderr.trim()}`)
|
|
160
|
+
const info = JSON.parse(result.stdout)
|
|
161
|
+
const video = (info.streams ?? []).find((stream) => stream.codec_type === 'video')
|
|
162
|
+
const audio = (info.streams ?? []).find((stream) => stream.codec_type === 'audio')
|
|
163
|
+
if (!video) throw fail('VIDEO_NO_STREAM', '这个文件里没有视频轨。')
|
|
164
|
+
const [num, den] = String(video.r_frame_rate ?? '0/1').split('/').map(Number)
|
|
165
|
+
return {
|
|
166
|
+
path: resolvePath(path),
|
|
167
|
+
bytes: statSync(path).size,
|
|
168
|
+
duration: Number(info.format?.duration ?? video.duration ?? 0),
|
|
169
|
+
width: Number(video.width),
|
|
170
|
+
height: Number(video.height),
|
|
171
|
+
fps: den ? Math.round((num / den) * 100) / 100 : null,
|
|
172
|
+
videoCodec: video.codec_name ?? null,
|
|
173
|
+
hasAudio: Boolean(audio),
|
|
174
|
+
audioCodec: audio?.codec_name ?? null,
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/**
|
|
179
|
+
* 逐秒采样两种画面:整屏(缩到 192×120)与标题栏(顶部 7%,384×28)。
|
|
180
|
+
* 输出灰度原始帧,差值在 Node 里算 —— 比解析 ffmpeg 的 stderr 稳,也能拿到变化面积。
|
|
181
|
+
*/
|
|
182
|
+
export async function motionSeries(path, meta, workDir) {
|
|
183
|
+
const ffmpeg = findBinary('ffmpeg')
|
|
184
|
+
const canvasW = 192
|
|
185
|
+
const canvasH = Math.max(8, Math.round(canvasW * meta.height / meta.width / 2) * 2)
|
|
186
|
+
const stripH = Math.max(8, Math.round(meta.height * 0.07 / 2) * 2)
|
|
187
|
+
const stripW = 384
|
|
188
|
+
const canvasFile = join(workDir, 'canvas.raw')
|
|
189
|
+
const stripFile = join(workDir, 'strip.raw')
|
|
190
|
+
|
|
191
|
+
// 软件解码的滤镜图:两路都用 fps=1 之后自己的缩放。
|
|
192
|
+
const softwareGraph =
|
|
193
|
+
`[0:v]fps=1,scale=${canvasW}:${canvasH},format=gray[a];`
|
|
194
|
+
+ `[0:v]fps=1,crop=iw:${stripH}:0:0,scale=${stripW}:${Math.max(8, Math.round(stripH / 6))},format=gray[b]`
|
|
195
|
+
|
|
196
|
+
// 硬件解码的滤镜图:fps 在 GPU 上跑,只把每秒那一帧下载回内存,
|
|
197
|
+
// 然后 split 成两路(下载一次,别每路各下一次)。
|
|
198
|
+
const hardwareGraph =
|
|
199
|
+
`[0:v]fps=1,hwdownload,format=nv12,split=2[whole][strip];`
|
|
200
|
+
+ `[whole]scale=${canvasW}:${canvasH},format=gray[a];`
|
|
201
|
+
+ `[strip]crop=iw:${stripH}:0:0,scale=${stripW}:${Math.max(8, Math.round(stripH / 6))},format=gray[b]`
|
|
202
|
+
|
|
203
|
+
const build = (hw) => [
|
|
204
|
+
'-hide_banner', '-loglevel', 'error',
|
|
205
|
+
...(hw?.model ? ['-hwaccel', hw.model, '-hwaccel_output_format', hw.format] : []),
|
|
206
|
+
'-i', path,
|
|
207
|
+
'-filter_complex', hw?.model ? hardwareGraph : softwareGraph,
|
|
208
|
+
'-map', '[a]', '-f', 'rawvideo', '-pix_fmt', 'gray', '-y', canvasFile,
|
|
209
|
+
'-map', '[b]', '-f', 'rawvideo', '-pix_fmt', 'gray', '-y', stripFile,
|
|
210
|
+
]
|
|
211
|
+
|
|
212
|
+
const hardware = await pickHwAccel(ffmpeg, meta.duration)
|
|
213
|
+
let result
|
|
214
|
+
try {
|
|
215
|
+
result = await run(ffmpeg, build(hardware))
|
|
216
|
+
if (hardware?.model && (result.code !== 0 || !existsSync(canvasFile))) {
|
|
217
|
+
// GPU 解码在个别编码/驱动组合上会失败(老 VP9、AV1、虚拟显卡等)。
|
|
218
|
+
// 记住这次失败,整段降级回软件解码,别让用户看到一次失败就整条链路挂掉。
|
|
219
|
+
process.stderr.write(
|
|
220
|
+
`[eplan-mcp] 硬件解码不可用,回退软件解码:${result.stderr.trim().slice(0, 160)}\n`,
|
|
221
|
+
)
|
|
222
|
+
hwFailed = true
|
|
223
|
+
result = await run(ffmpeg, build(null))
|
|
224
|
+
}
|
|
225
|
+
} catch (error) {
|
|
226
|
+
throw fail('VIDEO_NO_FFMPEG', `调用 ffmpeg 失败:${error.message}`)
|
|
227
|
+
}
|
|
228
|
+
if (result.code !== 0 || !existsSync(canvasFile)) {
|
|
229
|
+
throw fail('VIDEO_SAMPLE_FAILED', `采样失败:${result.stderr.trim().slice(0, 400)}`)
|
|
230
|
+
}
|
|
231
|
+
const canvasBytes = canvasW * canvasH
|
|
232
|
+
const stripPixels = Math.max(8, Math.round(stripH / 6))
|
|
233
|
+
const stripBytes = stripW * stripPixels
|
|
234
|
+
const canvas = readFileSync(canvasFile)
|
|
235
|
+
const strip = existsSync(stripFile) ? readFileSync(stripFile) : Buffer.alloc(0)
|
|
236
|
+
const frames = Math.floor(canvas.length / canvasBytes)
|
|
237
|
+
const canvasSeries = []
|
|
238
|
+
const stripSeries = []
|
|
239
|
+
for (let index = 1; index < frames; index += 1) {
|
|
240
|
+
const previous = canvas.subarray((index - 1) * canvasBytes, index * canvasBytes)
|
|
241
|
+
const current = canvas.subarray(index * canvasBytes, (index + 1) * canvasBytes)
|
|
242
|
+
let sum = 0
|
|
243
|
+
let changed = 0
|
|
244
|
+
for (let pixel = 0; pixel < canvasBytes; pixel += 1) {
|
|
245
|
+
const delta = Math.abs(current[pixel] - previous[pixel])
|
|
246
|
+
sum += delta
|
|
247
|
+
if (delta > 24) changed += 1
|
|
248
|
+
}
|
|
249
|
+
canvasSeries.push({
|
|
250
|
+
t: index,
|
|
251
|
+
mean: round2(sum / canvasBytes),
|
|
252
|
+
changed: round2(changed / canvasBytes),
|
|
253
|
+
})
|
|
254
|
+
const stripIndex = index * stripBytes
|
|
255
|
+
if (strip.length >= stripIndex + stripBytes) {
|
|
256
|
+
const stripPrevious = strip.subarray(stripIndex - stripBytes, stripIndex)
|
|
257
|
+
const stripCurrent = strip.subarray(stripIndex, stripIndex + stripBytes)
|
|
258
|
+
let stripSum = 0
|
|
259
|
+
let stripChanged = 0
|
|
260
|
+
for (let pixel = 0; pixel < stripBytes; pixel += 1) {
|
|
261
|
+
const delta = Math.abs(stripCurrent[pixel] - stripPrevious[pixel])
|
|
262
|
+
stripSum += delta
|
|
263
|
+
if (delta > 24) stripChanged += 1
|
|
264
|
+
}
|
|
265
|
+
stripSeries.push({
|
|
266
|
+
t: index,
|
|
267
|
+
mean: round2(stripSum / stripBytes),
|
|
268
|
+
changed: round2(stripChanged / stripBytes),
|
|
269
|
+
})
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
return { canvas: canvasSeries, strip: stripSeries, frames, canvasSize: { width: canvasW, height: canvasH } }
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
function median(values) {
|
|
276
|
+
if (values.length === 0) return 0
|
|
277
|
+
const sorted = [...values].sort((a, b) => a - b)
|
|
278
|
+
return sorted[Math.floor(sorted.length / 2)]
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
/**
|
|
282
|
+
* 强边界:标题栏大改(页码/标签变了)或整屏重画。
|
|
283
|
+
*
|
|
284
|
+
* 实测校准(248 s 录屏):画同一页时每秒都在小改,标题栏 0.14~0.69 的抖动是
|
|
285
|
+
* 鼠标划过标签/窗口;真正的阶段切换都是 0.93 以上。所以门限取 0.5(并随噪声抬高),
|
|
286
|
+
* 整屏重画取 0.88,且两个边界至少隔 15 秒 —— 否则一页纸会被切成一堆碎段。
|
|
287
|
+
*/
|
|
288
|
+
export function strongBoundaries(series, meta, {
|
|
289
|
+
minSegment = 15,
|
|
290
|
+
stripFloor = 0.5,
|
|
291
|
+
repaintFloor = 0.88,
|
|
292
|
+
} = {}) {
|
|
293
|
+
const canvas = series?.canvas ?? []
|
|
294
|
+
const strip = series?.strip ?? []
|
|
295
|
+
if (canvas.length === 0) {
|
|
296
|
+
return [{ index: 1, t0: 0, t1: meta.duration, seconds: meta.duration, reason: 'single', switchScore: null }]
|
|
297
|
+
}
|
|
298
|
+
const stripValues = strip.filter((point) => point.t > 2).map((point) => point.changed)
|
|
299
|
+
const floor = Math.max(stripFloor, median(stripValues) * 4)
|
|
300
|
+
const boundaries = []
|
|
301
|
+
for (const point of strip) {
|
|
302
|
+
if (point.t < 2) continue
|
|
303
|
+
if (point.changed >= floor && point.mean >= 6) {
|
|
304
|
+
boundaries.push({ t: point.t, reason: 'title', score: point.changed })
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
for (const point of canvas) {
|
|
308
|
+
if (point.t < 2) continue
|
|
309
|
+
if (point.changed >= repaintFloor) boundaries.push({ t: point.t, reason: 'repaint', score: point.changed })
|
|
310
|
+
}
|
|
311
|
+
boundaries.sort((a, b) => a.t - b.t)
|
|
312
|
+
|
|
313
|
+
// 距离太近的边界合并(保留分数高的那个),再切段。
|
|
314
|
+
const kept = []
|
|
315
|
+
for (const boundary of boundaries) {
|
|
316
|
+
const last = kept[kept.length - 1]
|
|
317
|
+
if (last && boundary.t - last.t < minSegment) {
|
|
318
|
+
if (boundary.score > last.score) kept[kept.length - 1] = boundary
|
|
319
|
+
continue
|
|
320
|
+
}
|
|
321
|
+
kept.push(boundary)
|
|
322
|
+
}
|
|
323
|
+
const edges = [0, ...kept.map((boundary) => boundary.t), meta.duration]
|
|
324
|
+
const segments = []
|
|
325
|
+
for (let index = 0; index < edges.length - 1; index += 1) {
|
|
326
|
+
const t0 = edges[index]
|
|
327
|
+
const t1 = edges[index + 1]
|
|
328
|
+
if (t1 - t0 < 1) continue
|
|
329
|
+
segments.push({
|
|
330
|
+
index: segments.length + 1,
|
|
331
|
+
t0: round2(t0),
|
|
332
|
+
t1: round2(t1),
|
|
333
|
+
seconds: round2(t1 - t0),
|
|
334
|
+
reason: index === 0 ? 'start' : kept[index - 1]?.reason ?? 'start',
|
|
335
|
+
switchScore: index === 0 ? null : kept[index - 1]?.score ?? null,
|
|
336
|
+
})
|
|
337
|
+
}
|
|
338
|
+
return segments.length > 0 ? segments : [{ index: 1, t0: 0, t1: meta.duration, seconds: meta.duration, reason: 'single', switchScore: null }]
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
/** 段内挑一帧「最稳」的画面:避开切换瞬间,靠后取(同一页越画越全,后段更像成品)。 */
|
|
342
|
+
export function stableTime(segment, series) {
|
|
343
|
+
const canvas = series?.canvas ?? []
|
|
344
|
+
const from = segment.t0 + Math.max(1, segment.seconds * 0.35)
|
|
345
|
+
const to = segment.t1 - 0.5
|
|
346
|
+
const candidates = canvas.filter((point) => point.t >= from && point.t <= to)
|
|
347
|
+
if (candidates.length === 0) {
|
|
348
|
+
const middle = canvas.filter((point) => point.t >= segment.t0 + 0.5 && point.t <= segment.t1)
|
|
349
|
+
if (middle.length === 0) return round2((segment.t0 + segment.t1) / 2)
|
|
350
|
+
let bestMiddle = middle[0]
|
|
351
|
+
for (const point of middle) if (point.mean < bestMiddle.mean) bestMiddle = point
|
|
352
|
+
return round2(bestMiddle.t)
|
|
353
|
+
}
|
|
354
|
+
let best = candidates[0]
|
|
355
|
+
// 并列时取**靠后**的那一帧:同一页画到后面更完整,早的帧往往还没画完。
|
|
356
|
+
for (const point of candidates) if (point.mean <= best.mean) best = point
|
|
357
|
+
return round2(best.t)
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
/**
|
|
361
|
+
* 排阶段:先按强边界切,再补切最长的段,直到够 maxPages 张图;
|
|
362
|
+
* 段数超过 maxPages 时丢掉分数最低的边界(首尾段永远保留,结尾不能丢)。
|
|
363
|
+
* 每段出一张图 —— 逐张给,绝不拼成一张拼图。
|
|
364
|
+
*/
|
|
365
|
+
export function planStages(series, meta, maxPages = 6, { minSplit = 16 } = {}) {
|
|
366
|
+
const limit = Math.max(1, maxPages)
|
|
367
|
+
let segments = strongBoundaries(series, meta)
|
|
368
|
+
while (segments.length < limit) {
|
|
369
|
+
let target = null
|
|
370
|
+
for (const segment of segments) {
|
|
371
|
+
if (segment.seconds < minSplit) continue
|
|
372
|
+
if (!target || segment.seconds > target.seconds) target = segment
|
|
373
|
+
}
|
|
374
|
+
if (!target) break
|
|
375
|
+
const middle = Math.round((target.t0 + target.t1) / 2)
|
|
376
|
+
const index = segments.indexOf(target)
|
|
377
|
+
segments.splice(index, 1,
|
|
378
|
+
{ ...target, t1: middle, seconds: round2(middle - target.t0) },
|
|
379
|
+
{ index: 0, t0: middle, t1: target.t1, seconds: round2(target.t1 - middle), reason: 'split', switchScore: null },
|
|
380
|
+
)
|
|
381
|
+
}
|
|
382
|
+
while (segments.length > limit) {
|
|
383
|
+
// 只剩两段时只能把它们并成一段(上限=1 这种极端请求)。
|
|
384
|
+
if (segments.length === 2) {
|
|
385
|
+
segments = [{ ...segments[0], t1: segments[1].t1, seconds: round2(segments[1].t1 - segments[0].t0) }]
|
|
386
|
+
continue
|
|
387
|
+
}
|
|
388
|
+
let weakest = -1
|
|
389
|
+
for (let index = 1; index < segments.length - 1; index += 1) {
|
|
390
|
+
if (weakest < 0 || (segments[index].switchScore ?? 0) < (segments[weakest].switchScore ?? 0)) weakest = index
|
|
391
|
+
}
|
|
392
|
+
if (weakest < 0) break
|
|
393
|
+
const removed = segments.splice(weakest, 1)[0]
|
|
394
|
+
segments[weakest - 1] = {
|
|
395
|
+
...segments[weakest - 1],
|
|
396
|
+
t1: removed.t1,
|
|
397
|
+
seconds: round2(removed.t1 - segments[weakest - 1].t0),
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
return segments.map((segment, index) => ({ ...segment, index: index + 1 }))
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
/** 可见目录:带 .png 后缀的副本,人和模型都能直接打开。 */
|
|
404
|
+
export function visibleDirFor(key) {
|
|
405
|
+
const base = process.env.LOCALAPPDATA ?? join(homedir(), 'AppData', 'Local')
|
|
406
|
+
return join(base, 'eplan-mcp', 'video-digest', key)
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
/**
|
|
410
|
+
* 抓一帧:可选裁剪/缩放,写两份(工作目录 + 可见目录)。
|
|
411
|
+
*
|
|
412
|
+
* 为什么默认 JPEG(q3,4:4:4 无色度抽样)而不是 PNG:实测 2880×1800 录屏截一帧
|
|
413
|
+
* 缩到 1920 宽的 PNG 有 **700 KB**,6 段摘要一次进上下文就是 3.9 MB(2026-11-23
|
|
414
|
+
* session-a18a4a7f 的真实数字)。同一帧 JPEG q3 只有它的 1/4,细线仍然清楚。
|
|
415
|
+
* 4:4:4 是为了不让红色导线和黑色文字边缘糊掉。
|
|
416
|
+
* @returns {{path:string, visiblePath:string, bytes:number, t:number, region:object, mimeType:string}}
|
|
417
|
+
*/
|
|
418
|
+
export async function grabFrame(
|
|
419
|
+
path,
|
|
420
|
+
meta,
|
|
421
|
+
time,
|
|
422
|
+
outDir,
|
|
423
|
+
{ name = 'frame.png', visibleDir, maxEdge = 1920, crop, format = 'jpeg', quality = 3 } = {},
|
|
424
|
+
) {
|
|
425
|
+
const ffmpeg = findBinary('ffmpeg')
|
|
426
|
+
const jpeg = format === 'jpeg'
|
|
427
|
+
const base = String(name).replace(/\.(png|jpe?g)$/i, '')
|
|
428
|
+
const file = join(outDir, `${base}${jpeg ? '.jpg' : '.png'}`)
|
|
429
|
+
const longEdge = Math.max(meta.width, meta.height)
|
|
430
|
+
const scale = longEdge > maxEdge ? `scale=${Math.round(maxEdge)}:-2` : null
|
|
431
|
+
const filters = [crop, scale].filter(Boolean)
|
|
432
|
+
const encode = jpeg ? ['-q:v', String(quality), '-pix_fmt', 'yuvj444p'] : []
|
|
433
|
+
const region = crop ? parseCrop(crop) : { x: 0, y: 0, w: meta.width, h: meta.height }
|
|
434
|
+
const result = await run(ffmpeg, [
|
|
435
|
+
'-hide_banner', '-loglevel', 'error',
|
|
436
|
+
'-ss', String(Math.max(0, time)), '-i', path,
|
|
437
|
+
'-frames:v', '1', ...(filters.length > 0 ? ['-vf', filters.join(',')] : []),
|
|
438
|
+
...encode,
|
|
439
|
+
'-y', file,
|
|
440
|
+
])
|
|
441
|
+
if (result.code !== 0 || !existsSync(file)) {
|
|
442
|
+
throw fail('VIDEO_FRAME_FAILED', `取帧失败(t=${time}):${result.stderr.trim().slice(0, 300)}`)
|
|
443
|
+
}
|
|
444
|
+
let visible = file
|
|
445
|
+
if (visibleDir) {
|
|
446
|
+
try {
|
|
447
|
+
mkdirSync(visibleDir, { recursive: true })
|
|
448
|
+
visible = join(visibleDir, `${base}${jpeg ? '.jpg' : '.png'}`)
|
|
449
|
+
copyFileSync(file, visible)
|
|
450
|
+
} catch {
|
|
451
|
+
visible = file
|
|
452
|
+
}
|
|
453
|
+
}
|
|
454
|
+
return {
|
|
455
|
+
path: file,
|
|
456
|
+
visiblePath: visible,
|
|
457
|
+
bytes: statSync(file).size,
|
|
458
|
+
t: round2(time),
|
|
459
|
+
region,
|
|
460
|
+
mimeType: jpeg ? 'image/jpeg' : 'image/png',
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
function parseCrop(crop) {
|
|
465
|
+
const match = /^crop=(\d+):(\d+):(\d+):(\d+)$/.exec(crop)
|
|
466
|
+
if (!match) return { x: 0, y: 0, w: null, h: null }
|
|
467
|
+
const [, w, h, x, y] = match.map(Number)
|
|
468
|
+
return { x, y, w, h }
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
/** 整段响度:判「有没有讲解」用 max,判「是不是全静音」看 mean。 */
|
|
472
|
+
export async function loudness(path, meta) {
|
|
473
|
+
if (!meta.hasAudio) return { maxVolume: null, meanVolume: null, silent: true }
|
|
474
|
+
const ffmpeg = findBinary('ffmpeg')
|
|
475
|
+
const result = await run(ffmpeg, ['-hide_banner', '-nostats', '-i', path, '-af', 'volumedetect', '-f', 'null', '-'])
|
|
476
|
+
const maxMatch = /max_volume:\s*(-?[0-9.]+)\s*dB/.exec(result.stderr)
|
|
477
|
+
const meanMatch = /mean_volume:\s*(-?[0-9.]+)\s*dB/.exec(result.stderr)
|
|
478
|
+
const maxVolume = maxMatch ? Number(maxMatch[1]) : null
|
|
479
|
+
const meanVolume = meanMatch ? Number(meanMatch[1]) : null
|
|
480
|
+
const silent = maxVolume === null || maxVolume < -55
|
|
481
|
+
return { maxVolume, meanVolume, silent }
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
/** 抽成 16k 单声道 WAV,给语音转写用。 */
|
|
485
|
+
export async function extractAudio(path, meta, outDir) {
|
|
486
|
+
if (!meta.hasAudio) return null
|
|
487
|
+
const ffmpeg = findBinary('ffmpeg')
|
|
488
|
+
const wav = join(outDir, 'audio.wav')
|
|
489
|
+
const result = await run(ffmpeg, [
|
|
490
|
+
'-hide_banner', '-loglevel', 'error', '-i', path,
|
|
491
|
+
'-vn', '-ac', '1', '-ar', '16000', '-acodec', 'pcm_s16le', '-y', wav,
|
|
492
|
+
])
|
|
493
|
+
if (result.code !== 0 || !existsSync(wav)) return null
|
|
494
|
+
return { path: wav, bytes: statSync(wav).size }
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
/**
|
|
498
|
+
* 语音片段:按实测响度自适应门限找静音,取静音之间的部分,过长再切开。
|
|
499
|
+
*
|
|
500
|
+
* 写死 -35 dB 的后果实测过:一段 248 s 录屏(mean -39 dB)只切出 1.86 s,
|
|
501
|
+
* 讲解直接丢光。这里用 max_volume 往下 22 dB 作门限,并夹在 [-55, -22]。
|
|
502
|
+
*/
|
|
503
|
+
export async function speechSpans(wavPath, {
|
|
504
|
+
maxVolume = null,
|
|
505
|
+
minSegmentSeconds = 0.8,
|
|
506
|
+
maxSegmentSeconds = 20,
|
|
507
|
+
gapSeconds = 0.5,
|
|
508
|
+
} = {}) {
|
|
509
|
+
const ffmpeg = findBinary('ffmpeg')
|
|
510
|
+
const noiseDb = clamp((maxVolume ?? -20) - 22, -55, -22)
|
|
511
|
+
const result = await run(ffmpeg, [
|
|
512
|
+
'-hide_banner', '-nostats', '-i', wavPath,
|
|
513
|
+
'-af', `silencedetect=noise=${noiseDb}dB:d=0.35`, '-f', 'null', '-',
|
|
514
|
+
])
|
|
515
|
+
const silences = []
|
|
516
|
+
let current = null
|
|
517
|
+
for (const line of result.stderr.split('\n')) {
|
|
518
|
+
const start = /silence_start:\s*(-?[0-9.]+)/.exec(line)
|
|
519
|
+
const end = /silence_end:\s*(-?[0-9.]+)/.exec(line)
|
|
520
|
+
if (start) current = { start: Math.max(0, Number(start[1])), end: null }
|
|
521
|
+
if (end && current) { current.end = Number(end[1]); silences.push(current); current = null }
|
|
522
|
+
}
|
|
523
|
+
if (current) { current.end = Number.POSITIVE_INFINITY; silences.push(current) }
|
|
524
|
+
|
|
525
|
+
const audioSeconds = (statSync(wavPath).size - 44) / 32000
|
|
526
|
+
const spans = []
|
|
527
|
+
let cursor = 0
|
|
528
|
+
for (const silence of silences) {
|
|
529
|
+
if (silence.start - cursor >= minSegmentSeconds) spans.push({ t0: cursor, t1: silence.start })
|
|
530
|
+
cursor = Math.max(cursor, Number.isFinite(silence.end) ? silence.end : audioSeconds)
|
|
531
|
+
}
|
|
532
|
+
if (audioSeconds - cursor >= minSegmentSeconds) spans.push({ t0: cursor, t1: audioSeconds })
|
|
533
|
+
if (spans.length === 0 && audioSeconds > 0) spans.push({ t0: 0, t1: audioSeconds })
|
|
534
|
+
|
|
535
|
+
const cut = []
|
|
536
|
+
for (const span of spans) {
|
|
537
|
+
const length = span.t1 - span.t0
|
|
538
|
+
if (length <= maxSegmentSeconds) { cut.push({ t0: round2(span.t0), t1: round2(span.t1) }); continue }
|
|
539
|
+
const parts = Math.ceil(length / maxSegmentSeconds)
|
|
540
|
+
const step = length / parts
|
|
541
|
+
for (let index = 0; index < parts; index += 1) {
|
|
542
|
+
cut.push({ t0: round2(span.t0 + index * step), t1: round2(span.t0 + (index + 1) * step) })
|
|
543
|
+
}
|
|
544
|
+
}
|
|
545
|
+
const merged = []
|
|
546
|
+
for (const segment of cut) {
|
|
547
|
+
const last = merged[merged.length - 1]
|
|
548
|
+
if (last && segment.t0 - last.t1 < gapSeconds && segment.t1 - last.t0 <= maxSegmentSeconds * 1.2) {
|
|
549
|
+
last.t1 = segment.t1
|
|
550
|
+
} else {
|
|
551
|
+
merged.push({ ...segment })
|
|
552
|
+
}
|
|
553
|
+
}
|
|
554
|
+
return { spans: merged, noiseDb, audioSeconds: round2(audioSeconds) }
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
/** WAV 头 + 16bit PCM(16k 单声道),供转写服务使用。 */
|
|
558
|
+
export function encodeWav(samples) {
|
|
559
|
+
const header = Buffer.alloc(44)
|
|
560
|
+
const dataSize = samples.length * 2
|
|
561
|
+
header.write('RIFF', 0)
|
|
562
|
+
header.writeUInt32LE(36 + dataSize, 4)
|
|
563
|
+
header.write('WAVE', 8)
|
|
564
|
+
header.write('fmt ', 12)
|
|
565
|
+
header.writeUInt32LE(16, 16)
|
|
566
|
+
header.writeUInt16LE(1, 20)
|
|
567
|
+
header.writeUInt16LE(1, 22)
|
|
568
|
+
header.writeUInt32LE(16000, 24)
|
|
569
|
+
header.writeUInt32LE(16000 * 2, 28)
|
|
570
|
+
header.writeUInt16LE(2, 32)
|
|
571
|
+
header.writeUInt16LE(16, 34)
|
|
572
|
+
header.write('data', 36)
|
|
573
|
+
header.writeUInt32LE(dataSize, 40)
|
|
574
|
+
const pcm = Buffer.alloc(dataSize)
|
|
575
|
+
for (let index = 0; index < samples.length; index += 1) {
|
|
576
|
+
const clamped = Math.max(-1, Math.min(1, samples[index]))
|
|
577
|
+
pcm.writeInt16LE(Math.round(clamped * 32767), index * 2)
|
|
578
|
+
}
|
|
579
|
+
return Buffer.concat([header, pcm])
|
|
580
|
+
}
|
|
581
|
+
|
|
582
|
+
/** 把整段 WAV 解成 Float32,便于按片段切。 */
|
|
583
|
+
export function decodeWav(buffer) {
|
|
584
|
+
const int16 = new Int16Array(buffer.buffer, buffer.byteOffset + 44, (buffer.byteLength - 44) >> 1)
|
|
585
|
+
const samples = new Float32Array(int16.length)
|
|
586
|
+
for (let index = 0; index < int16.length; index += 1) samples[index] = int16[index] / 32768
|
|
587
|
+
return samples
|
|
588
|
+
}
|
|
589
|
+
|
|
590
|
+
/**
|
|
591
|
+
* 全流程:元信息 → 响度 → 切页 → 每页一张图 → 语音片段。
|
|
592
|
+
* 转写由调用方传入(`transcribe(spans, audioPath)` 返回 [{t0,t1,text,error?}])。
|
|
593
|
+
*/
|
|
594
|
+
export async function digest(path, {
|
|
595
|
+
maxPages = 6,
|
|
596
|
+
workRoot,
|
|
597
|
+
transcribe,
|
|
598
|
+
// 1600 宽足够看清手册上的接线图与端子号;再大只是把上下文撑满(见 grabFrame 注释)。
|
|
599
|
+
maxEdge = 1600,
|
|
600
|
+
frameQuality = 3,
|
|
601
|
+
at = null,
|
|
602
|
+
} = {}) {
|
|
603
|
+
const meta = await probe(path)
|
|
604
|
+
// mtime 也进 key:同一个路径换了内容(重新导出录屏)必须重算,不能吃旧缓存。
|
|
605
|
+
const stamp = Math.round(statSync(path).mtimeMs)
|
|
606
|
+
const key = createHash('sha1').update(`${meta.path}:${meta.bytes}:${stamp}`).digest('hex').slice(0, 12)
|
|
607
|
+
const outDir = workRoot ? join(workRoot, key) : join(tmpdir(), 'eplan-mcp', 'video-digest', key)
|
|
608
|
+
const visibleDir = visibleDirFor(key)
|
|
609
|
+
const wantsFrame = at !== null && Number.isFinite(Number(at))
|
|
610
|
+
|
|
611
|
+
const shotAt = async (time, options) => grabFrame(path, meta, time, outDir, { visibleDir, ...options })
|
|
612
|
+
|
|
613
|
+
// ── 命中缓存 ────────────────────────────────────────────────────────────
|
|
614
|
+
// 2026-11-24 session-400917a2 的账:同一段 12:24 录屏被 video({at:245/500/565/700/742})
|
|
615
|
+
// 调了 5 次,每次 1.1~1.8 分钟(全片解码 + 重新转写),要的其实只是某秒的一张图。
|
|
616
|
+
// 现在命中即返回:只要图就只抓那一帧,段数变了就用缓存采样重排,绝不重新解码。
|
|
617
|
+
const cached = readDigestCache(outDir, maxEdge, frameQuality)
|
|
618
|
+
if (cached) {
|
|
619
|
+
let segments = cached.segments
|
|
620
|
+
let pages = cached.pages
|
|
621
|
+
// 只要某一秒的图就别重排:调用方要的是那一帧,重排既慢又会把缓存的段数改掉。
|
|
622
|
+
if (!wantsFrame && cached.maxPages !== maxPages) {
|
|
623
|
+
segments = planStages(cached.series, meta, maxPages)
|
|
624
|
+
pages = []
|
|
625
|
+
for (const segment of segments) {
|
|
626
|
+
const time = stableTime(segment, cached.series)
|
|
627
|
+
const shot = await shotAt(time, {
|
|
628
|
+
name: `stage-${String(segment.index).padStart(2, '0')}.png`,
|
|
629
|
+
maxEdge,
|
|
630
|
+
quality: frameQuality,
|
|
631
|
+
})
|
|
632
|
+
pages.push({ ...segment, shotAt: shot.t, shot })
|
|
633
|
+
}
|
|
634
|
+
writeDigestCache(outDir, { ...cached, maxPages, segments, pages })
|
|
635
|
+
}
|
|
636
|
+
|
|
637
|
+
const extra = []
|
|
638
|
+
if (wantsFrame) {
|
|
639
|
+
const shot = await shotAt(Number(at), { name: 'at.png', maxEdge: Math.max(maxEdge, 2000), quality: 2 })
|
|
640
|
+
extra.push({ t: shot.t, shot })
|
|
641
|
+
}
|
|
642
|
+
|
|
643
|
+
const text = renderDigest({ meta, pages, speech: cached.speech, visibleDir, extra })
|
|
644
|
+
writeFileSync(join(outDir, 'digest.json'), JSON.stringify({ meta, segments, pages, loud: cached.loud, speech: cached.speech, extra }, null, 2), 'utf8')
|
|
645
|
+
return {
|
|
646
|
+
ok: true,
|
|
647
|
+
key,
|
|
648
|
+
meta,
|
|
649
|
+
segments,
|
|
650
|
+
pages,
|
|
651
|
+
loud: cached.loud,
|
|
652
|
+
speech: cached.speech,
|
|
653
|
+
extra,
|
|
654
|
+
text,
|
|
655
|
+
workDir: outDir,
|
|
656
|
+
visibleDir,
|
|
657
|
+
cached: true,
|
|
658
|
+
}
|
|
659
|
+
}
|
|
660
|
+
|
|
661
|
+
// ── 冷启动:完整跑一遍,结果落盘 ─────────────────────────────────────────
|
|
662
|
+
rmSync(outDir, { recursive: true, force: true })
|
|
663
|
+
mkdirSync(outDir, { recursive: true })
|
|
664
|
+
|
|
665
|
+
const series = await motionSeries(path, meta, outDir)
|
|
666
|
+
const segments = planStages(series, meta, maxPages)
|
|
667
|
+
const pages = []
|
|
668
|
+
for (const segment of segments) {
|
|
669
|
+
const time = stableTime(segment, series)
|
|
670
|
+
const shot = await shotAt(time, {
|
|
671
|
+
name: `stage-${String(segment.index).padStart(2, '0')}.png`,
|
|
672
|
+
maxEdge,
|
|
673
|
+
quality: frameQuality,
|
|
674
|
+
})
|
|
675
|
+
pages.push({ ...segment, shotAt: shot.t, shot })
|
|
676
|
+
}
|
|
677
|
+
|
|
678
|
+
const loud = await loudness(path, meta)
|
|
679
|
+
let speech = { verdict: 'none', note: '这段录像没有音轨。', spans: [], transcript: [], totalSeconds: 0, coverage: 0, noiseDb: null }
|
|
680
|
+
if (meta.hasAudio && !loud.silent) {
|
|
681
|
+
const audio = await extractAudio(path, meta, outDir)
|
|
682
|
+
if (audio) {
|
|
683
|
+
const detected = await speechSpans(audio.path, { maxVolume: loud.maxVolume })
|
|
684
|
+
const totalSeconds = round2(detected.spans.reduce((sum, span) => sum + (span.t1 - span.t0), 0))
|
|
685
|
+
const coverage = meta.duration > 0 ? round2(totalSeconds / meta.duration) : 0
|
|
686
|
+
let transcript = []
|
|
687
|
+
if (transcribe && detected.spans.length > 0 && totalSeconds >= 1) {
|
|
688
|
+
try {
|
|
689
|
+
transcript = await transcribe(detected.spans, audio.path)
|
|
690
|
+
} catch (error) {
|
|
691
|
+
transcript = detected.spans.map((span) => ({ ...span, text: '', error: error.message }))
|
|
692
|
+
}
|
|
693
|
+
}
|
|
694
|
+
speech = describeSpeech({ meta, loud, detected, transcript, totalSeconds, coverage })
|
|
695
|
+
}
|
|
696
|
+
}
|
|
697
|
+
|
|
698
|
+
const extra = []
|
|
699
|
+
if (wantsFrame) {
|
|
700
|
+
const shot = await shotAt(Number(at), { name: 'at.png', maxEdge: Math.max(maxEdge, 2000), quality: 2 })
|
|
701
|
+
extra.push({ t: shot.t, shot })
|
|
702
|
+
}
|
|
703
|
+
|
|
704
|
+
const text = renderDigest({ meta, pages, speech, visibleDir, extra })
|
|
705
|
+
writeFileSync(join(outDir, 'digest.json'), JSON.stringify({ meta, segments, pages, loud, speech, extra }, null, 2), 'utf8')
|
|
706
|
+
writeDigestCache(outDir, { maxPages, maxEdge, frameQuality, meta, series, segments, pages, loud, speech })
|
|
707
|
+
return { ok: true, key, meta, segments, pages, loud, speech, extra, text, workDir: outDir, visibleDir, cached: false }
|
|
708
|
+
}
|
|
709
|
+
|
|
710
|
+
const DIGEST_CACHE_VERSION = 2
|
|
711
|
+
|
|
712
|
+
function writeDigestCache(outDir, data) {
|
|
713
|
+
try {
|
|
714
|
+
writeFileSync(join(outDir, 'digest-cache.json'), JSON.stringify({ version: DIGEST_CACHE_VERSION, ...data }), 'utf8')
|
|
715
|
+
} catch (error) {
|
|
716
|
+
// 缓存写不进去只影响下次要不要重算,不影响这次交付。
|
|
717
|
+
process.stderr.write(`[eplan-mcp] 摘要缓存写不进去: ${error.message}\n`)
|
|
718
|
+
}
|
|
719
|
+
}
|
|
720
|
+
|
|
721
|
+
/**
|
|
722
|
+
* 读缓存。三条不信:版本不对、渲染参数变了、帧文件被系统清了。
|
|
723
|
+
* 只信磁盘上的实际文件,不信记录 —— 临时目录会被清理,指针比内容活得久。
|
|
724
|
+
*/
|
|
725
|
+
function readDigestCache(outDir, maxEdge, frameQuality) {
|
|
726
|
+
let data
|
|
727
|
+
try {
|
|
728
|
+
data = JSON.parse(readFileSync(join(outDir, 'digest-cache.json'), 'utf8'))
|
|
729
|
+
} catch {
|
|
730
|
+
return null
|
|
731
|
+
}
|
|
732
|
+
if (data?.version !== DIGEST_CACHE_VERSION) return null
|
|
733
|
+
if (data.maxEdge !== maxEdge || data.frameQuality !== frameQuality) return null
|
|
734
|
+
if (!Array.isArray(data.pages) || !Array.isArray(data.segments) || !data.series?.canvas) return null
|
|
735
|
+
if (!data.meta || !data.speech || typeof data.meta.duration !== 'number') return null
|
|
736
|
+
for (const page of data.pages) {
|
|
737
|
+
if (!page?.shot?.path || !existsSync(page.shot.path)) return null
|
|
738
|
+
}
|
|
739
|
+
return data
|
|
740
|
+
}
|
|
741
|
+
|
|
742
|
+
/** 判定「讲解」属于哪一种状态,并把原因写清楚 —— 空字符串绝不许悄悄过去。 */
|
|
743
|
+
function describeSpeech({ meta, loud, detected, transcript, totalSeconds, coverage }) {
|
|
744
|
+
const base = {
|
|
745
|
+
spans: detected.spans.map((span, index) => {
|
|
746
|
+
const entry = transcript[index] ?? {}
|
|
747
|
+
return {
|
|
748
|
+
index: index + 1,
|
|
749
|
+
t0: span.t0,
|
|
750
|
+
t1: span.t1,
|
|
751
|
+
text: String(entry.text ?? '').trim(),
|
|
752
|
+
...(entry.error ? { error: String(entry.error).slice(0, 300) } : {}),
|
|
753
|
+
}
|
|
754
|
+
}),
|
|
755
|
+
totalSeconds,
|
|
756
|
+
coverage,
|
|
757
|
+
maxVolume: loud.maxVolume,
|
|
758
|
+
meanVolume: loud.meanVolume,
|
|
759
|
+
noiseDb: detected.noiseDb,
|
|
760
|
+
}
|
|
761
|
+
if (totalSeconds < 1 || detected.spans.length === 0) {
|
|
762
|
+
return {
|
|
763
|
+
...base,
|
|
764
|
+
transcript: [],
|
|
765
|
+
verdict: 'none',
|
|
766
|
+
headline: '无',
|
|
767
|
+
note: `全片 ${clock(meta.duration)} 没有可识别的语音(峰值 ${loud.maxVolume} dB,门限 ${detected.noiseDb} dB)。`,
|
|
768
|
+
}
|
|
769
|
+
}
|
|
770
|
+
const errors = base.spans.filter((span) => span.error)
|
|
771
|
+
const spoken = base.spans.filter((span) => span.text && !span.error)
|
|
772
|
+
if (errors.length > 0 && spoken.length === 0) {
|
|
773
|
+
return { ...base, transcript: base.spans, verdict: 'failed', headline: '失败', note: errors[0].error }
|
|
774
|
+
}
|
|
775
|
+
if (spoken.length === 0) {
|
|
776
|
+
return {
|
|
777
|
+
...base,
|
|
778
|
+
transcript: base.spans,
|
|
779
|
+
verdict: 'empty',
|
|
780
|
+
headline: '空',
|
|
781
|
+
note: `有 ${totalSeconds} 秒响动,转写结果为空(可能是噪声、按键声或外语)。`,
|
|
782
|
+
}
|
|
783
|
+
}
|
|
784
|
+
const note = errors.length > 0 ? `部分片段转写失败(${errors.length}/${base.spans.length})。` : null
|
|
785
|
+
return { ...base, transcript: base.spans, verdict: 'transcribed', headline: null, note }
|
|
786
|
+
}
|
|
787
|
+
|
|
788
|
+
/**
|
|
789
|
+
* 摘要正文:只陈述事实(几段、每段什么时间、讲解说了什么、图在哪)。
|
|
790
|
+
*
|
|
791
|
+
* 写法约束:这里是**给用户看得到的内容**,不是写给模型的内心独白。
|
|
792
|
+
* 所以不出现「逐张给图」「不要再调 video()」「已预处理完毕」这类祈使句,
|
|
793
|
+
* 也不出现括号形式的操作提示 —— 那些属于系统提示词,不属于这条消息。
|
|
794
|
+
* 要看某一秒的图怎么办,写在 persona 里说明,不写在摘要里。
|
|
795
|
+
*/
|
|
796
|
+
export function renderDigest({ meta, pages, speech, visibleDir, extra = [] }) {
|
|
797
|
+
const lines = []
|
|
798
|
+
lines.push(`录屏 ${clock(meta.duration)} · ${meta.width}×${meta.height} · ${meta.fps ?? '?'} fps · ${pages.length} 段画面`)
|
|
799
|
+
if (speech.verdict === 'transcribed') {
|
|
800
|
+
lines.push(`讲解:${speech.transcript.filter((span) => span.text).length} 段,共 ${speech.totalSeconds} 秒,覆盖 ${Math.round(speech.coverage * 100)}%`)
|
|
801
|
+
} else if (speech.headline) {
|
|
802
|
+
lines.push(`讲解:${speech.headline}${speech.note ? ` —— ${speech.note}` : ''}`)
|
|
803
|
+
} else {
|
|
804
|
+
lines.push(`讲解:${speech.note ?? '未知'}`)
|
|
805
|
+
}
|
|
806
|
+
lines.push('')
|
|
807
|
+
lines.push('画面阶段:')
|
|
808
|
+
for (const page of pages) {
|
|
809
|
+
lines.push(` ${page.index}. ${clock(page.t0)}–${clock(page.t1)},${page.seconds} 秒,代表帧在 ${clock(page.shotAt)}(第 ${page.index} 张图)`)
|
|
810
|
+
}
|
|
811
|
+
if (extra.length > 0) {
|
|
812
|
+
for (const item of extra) lines.push(` 指定时间点 ${clock(item.t)}(第 ${pages.length + 1} 张图)`)
|
|
813
|
+
}
|
|
814
|
+
if (speech.verdict === 'transcribed') {
|
|
815
|
+
lines.push('')
|
|
816
|
+
lines.push('讲解原文:')
|
|
817
|
+
for (const span of speech.transcript) {
|
|
818
|
+
if (!span.text) continue
|
|
819
|
+
lines.push(` [${clock(span.t0)}] ${span.text}`)
|
|
820
|
+
}
|
|
821
|
+
}
|
|
822
|
+
lines.push('')
|
|
823
|
+
lines.push(`原图目录:${visibleDir}`)
|
|
824
|
+
return lines.join('\n')
|
|
825
|
+
}
|
|
826
|
+
|
|
827
|
+
// ---- CLI ----
|
|
828
|
+
const invokedDirectly = process.argv[1] && resolvePath(process.argv[1]).replace(/\\/g, '/').endsWith('/video.mjs')
|
|
829
|
+
if (invokedDirectly) {
|
|
830
|
+
const argv = process.argv.slice(2)
|
|
831
|
+
const arg = (name, fallback) => {
|
|
832
|
+
const index = argv.indexOf(`--${name}`)
|
|
833
|
+
return index >= 0 && argv[index + 1] ? argv[index + 1] : fallback
|
|
834
|
+
}
|
|
835
|
+
const path = arg('path')
|
|
836
|
+
if (!path) {
|
|
837
|
+
console.error('用法:node video.mjs --path <视频> [--max-pages 6] [--at 秒] [--series]')
|
|
838
|
+
process.exit(2)
|
|
839
|
+
}
|
|
840
|
+
try {
|
|
841
|
+
if (argv.includes('--series')) {
|
|
842
|
+
const meta = await probe(path)
|
|
843
|
+
const outDir = join(tmpdir(), 'eplan-mcp', 'video-series', createHash('sha1').update(path).digest('hex').slice(0, 8))
|
|
844
|
+
rmSync(outDir, { recursive: true, force: true })
|
|
845
|
+
mkdirSync(outDir, { recursive: true })
|
|
846
|
+
const series = await motionSeries(path, meta, outDir)
|
|
847
|
+
const segments = planStages(series, meta, Number(arg('max-pages', 6)))
|
|
848
|
+
process.stdout.write(JSON.stringify({ ok: true, meta, segments, canvas: series.canvas, strip: series.strip }) + '\n')
|
|
849
|
+
} else {
|
|
850
|
+
const result = await digest(path, { maxPages: Number(arg('max-pages', 6)), at: arg('at', null) })
|
|
851
|
+
process.stdout.write(JSON.stringify(result) + '\n')
|
|
852
|
+
}
|
|
853
|
+
} catch (error) {
|
|
854
|
+
process.stdout.write(JSON.stringify({ ok: false, code: error.code ?? 'VIDEO_FAILED', message: error.message }) + '\n')
|
|
855
|
+
process.exitCode = 1
|
|
856
|
+
}
|
|
857
|
+
}
|