listen-bridge.mjs 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  1. // Copyright (c) 未来飞马
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this
  5. // file, You can obtain one at https://mozilla.org/MPL/2.0/.
  6. //
  7. // Trademark Notice:
  8. // The MPL-2.0 license grants copyright permissions for source code only.
  9. // It does NOT grant any rights to use trademarks including "未来飞马",
  10. // "Harness Loop", "RSI", and associated slogan "让AI进化提前发生,让AI落地快人一步".
  11. // Any use of these trademarks requires separate written permission.
  12. /**
  13. * 视频桥:抽帧(ffmpeg)+ 音频转写(复用兄弟技能 skill-listen)
  14. *
  15. * 产出:
  16. * - frames[] 按时间轴均匀抽出的关键帧(落地到 --frames-out,交给 vision 做理解)
  17. * - transcript 音轨转写文本(skill-listen / listen-runner.mjs,走 Fmode 网关,凭据仅服务端)
  18. * - durationMs 时长(ffprobe;探测不到则 null)
  19. *
  20. * 缺 ffmpeg / ffprobe 或 skill-listen 时,返回 available:false + 明确安装提示,绝不伪造结果。
  21. * 绝不写任何 token / 凭据。
  22. */
  23. import fs from 'node:fs';
  24. import path from 'node:path';
  25. import { spawnSync } from 'node:child_process';
  26. import { parseArgs } from 'node:util';
  27. import { ensureDir, resolveSiblingScript, truncate } from './lib.mjs';
  28. const LISTEN_REL = path.join('skill-listen', 'scripts', 'listen-runner.mjs');
  29. function hasBinary(name) {
  30. const probe = spawnSync(name, ['-version'], { encoding: 'utf8' });
  31. return probe.status === 0 || Boolean(probe.stdout);
  32. }
  33. export function resolveFfmpeg() {
  34. return process.env.CASE_FFMPEG || 'ffmpeg';
  35. }
  36. export function probeDurationMs(videoPath) {
  37. const probe = spawnSync(process.env.CASE_FFPROBE || 'ffprobe', [
  38. '-v', 'error',
  39. '-show_entries', 'format=duration',
  40. '-of', 'default=noprint_wrappers=1:nokey=1',
  41. videoPath,
  42. ], { encoding: 'utf8' });
  43. const seconds = Number.parseFloat(String(probe.stdout || '').trim());
  44. return Number.isFinite(seconds) && seconds > 0 ? Math.round(seconds * 1000) : null;
  45. }
  46. /**
  47. * 均匀抽帧。
  48. * @returns {{ok:boolean, frames:object[], error:string|null}}
  49. */
  50. export function extractFrames(videoPath, framesOut, options = {}) {
  51. const count = Math.max(1, Math.min(24, Number(options.frameCount) || 6));
  52. ensureDir(framesOut);
  53. const durationMs = options.durationMs || probeDurationMs(videoPath);
  54. const ffmpeg = options.ffmpeg || resolveFfmpeg();
  55. const frames = [];
  56. if (durationMs && durationMs > 0) {
  57. // 均匀取 count 个时间点
  58. for (let i = 0; i < count; i++) {
  59. const tMs = Math.round((durationMs * (i + 0.5)) / count);
  60. const target = path.join(framesOut, `frame-${String(i + 1).padStart(3, '0')}.jpg`);
  61. const run = spawnSync(ffmpeg, [
  62. '-y', '-loglevel', 'error',
  63. '-ss', (tMs / 1000).toFixed(3),
  64. '-i', videoPath,
  65. '-frames:v', '1', '-q:v', '3',
  66. target,
  67. ], { encoding: 'utf8' });
  68. if (run.status === 0 && fs.existsSync(target)) {
  69. frames.push({ index: i + 1, atMs: tMs, localPath: target });
  70. }
  71. }
  72. } else {
  73. // 拿不到时长:按 fps 抽前 count 帧
  74. const run = spawnSync(ffmpeg, [
  75. '-y', '-loglevel', 'error',
  76. '-i', videoPath,
  77. '-frames:v', String(count), '-vf', 'fps=1', '-q:v', '3',
  78. path.join(framesOut, 'frame-%03d.jpg'),
  79. ], { encoding: 'utf8' });
  80. if (run.status === 0) {
  81. for (const name of fs.readdirSync(framesOut).sort().slice(0, count)) {
  82. frames.push({ index: frames.length + 1, atMs: null, localPath: path.join(framesOut, name) });
  83. }
  84. }
  85. }
  86. if (!frames.length) {
  87. return { ok: false, frames: [], error: 'FFMPEG_FRAME_EXTRACT_FAILED(检查 ffmpeg 是否可用及视频是否可解码)' };
  88. }
  89. return { ok: true, frames, error: null };
  90. }
  91. /** 抽出 16kHz 单声道 wav 音轨(转写前压体积,更稳)。 */
  92. export function extractAudio(videoPath, audioOut, options = {}) {
  93. ensureDir(path.dirname(audioOut));
  94. const ffmpeg = options.ffmpeg || resolveFfmpeg();
  95. const run = spawnSync(ffmpeg, [
  96. '-y', '-loglevel', 'error',
  97. '-i', videoPath,
  98. '-vn', '-ar', '16000', '-ac', '1',
  99. '-f', 'wav', audioOut,
  100. ], { encoding: 'utf8' });
  101. if (run.status === 0 && fs.existsSync(audioOut) && fs.statSync(audioOut).size > 1024) {
  102. return { ok: true, audioPath: audioOut, error: null };
  103. }
  104. return { ok: false, audioPath: '', error: 'FFMPEG_AUDIO_EXTRACT_FAILED(视频可能没有音轨)' };
  105. }
  106. /** 调 skill-listen 转写音轨。缺技能时返回 available:false,不抛栈。 */
  107. export async function transcribeAudio(audioPath, options = {}) {
  108. const listenPath = resolveSiblingScript('CASE_LISTEN_SCRIPT', LISTEN_REL);
  109. if (!listenPath) {
  110. return {
  111. available: false,
  112. text: '',
  113. segments: [],
  114. error: `未找到 skill-listen(期望 ${LISTEN_REL})。请先安装:npx skill-listen@latest install`,
  115. };
  116. }
  117. try {
  118. const runner = await import(new URL(`file://${listenPath.split(path.sep).join('/')}`).href);
  119. const durationMs = probeDurationMs(audioPath);
  120. const out = await runner.transcribeFile({
  121. filePath: audioPath,
  122. language: options.language || 'autodialect',
  123. diarize: Boolean(options.diarize),
  124. speakers: options.speakers,
  125. durationMs: durationMs || undefined,
  126. });
  127. return {
  128. available: true,
  129. text: String(out.text || ''),
  130. segments: out.segments || [],
  131. error: null,
  132. };
  133. } catch (error) {
  134. return { available: true, text: '', segments: [], error: `TRANSCRIBE_FAILED: ${error.message}` };
  135. }
  136. }
  137. /**
  138. * 视频处理总入口:抽帧 → 抽音轨 → 转写。
  139. */
  140. export async function processVideo(videoPath, options = {}) {
  141. const workDir = ensureDir(options.workDir || path.join(process.cwd(), 'case-get-outputs', 'video'));
  142. const durationMs = probeDurationMs(videoPath);
  143. const ffmpegOk = hasBinary(options.ffmpeg || resolveFfmpeg());
  144. const report = {
  145. video: path.resolve(videoPath),
  146. durationMs,
  147. frameCount: 0,
  148. frames: [],
  149. transcription: { available: false, text: '', segments: [], error: null },
  150. warnings: [],
  151. };
  152. if (!ffmpegOk) {
  153. report.warnings.push('未找到 ffmpeg:无法抽帧/抽音轨。请安装 ffmpeg 后重试。');
  154. return report;
  155. }
  156. const frameResult = extractFrames(videoPath, path.join(workDir, 'frames'), { frameCount: options.frameCount, durationMs });
  157. report.frames = frameResult.frames;
  158. report.frameCount = frameResult.frames.length;
  159. if (frameResult.error) report.warnings.push(frameResult.error);
  160. const audio = extractAudio(videoPath, path.join(workDir, 'audio.wav'));
  161. if (audio.ok) {
  162. report.transcription = await transcribeAudio(audio.audioPath, options);
  163. if (report.transcription.error) report.warnings.push(report.transcription.error);
  164. } else {
  165. report.transcription = { available: false, text: '', segments: [], error: audio.error };
  166. report.warnings.push(audio.error);
  167. }
  168. report.summary = truncate(report.transcription.text || '', 200);
  169. return report;
  170. }
  171. // ---------------------------------------------------------------------------
  172. // CLI
  173. // ---------------------------------------------------------------------------
  174. async function main() {
  175. const { values, positionals } = parseArgs({
  176. options: {
  177. video: { type: 'string', multiple: true, default: [] },
  178. out: { type: 'string' },
  179. 'work-dir': { type: 'string' },
  180. 'frame-count': { type: 'string' },
  181. diarize: { type: 'boolean', default: false },
  182. speakers: { type: 'string' },
  183. language: { type: 'string' },
  184. help: { type: 'boolean', default: false },
  185. },
  186. allowPositionals: true,
  187. });
  188. if (values.help) {
  189. process.stdout.write([
  190. 'skill-case-get / listen-bridge — 视频抽帧 + 音轨转写(复用 skill-listen)',
  191. '',
  192. ' node listen-bridge.mjs --video a.mp4 [--frame-count 6] [--diarize] [--out video.json]',
  193. '',
  194. '依赖:ffmpeg / ffprobe(抽帧、抽音轨)、skill-listen(转写)。缺任一都会在 warnings 里说明,不伪造结果。',
  195. ].join('\n'));
  196. return 0;
  197. }
  198. const inputs = [...values.video, ...positionals];
  199. if (!inputs.length) {
  200. process.stderr.write('至少需要一个 --video <file>\n');
  201. return 2;
  202. }
  203. const reports = [];
  204. for (const video of inputs) {
  205. reports.push(await processVideo(video, {
  206. workDir: values['work-dir'] || path.join(path.dirname(path.resolve(video)), 'case-get-video'),
  207. frameCount: Number(values['frame-count']) || 6,
  208. diarize: values.diarize,
  209. speakers: values.speakers ? Number(values.speakers) : undefined,
  210. language: values.language,
  211. }));
  212. }
  213. const payload = { ok: reports.every((r) => !r.warnings.length), count: reports.length, reports };
  214. const text = JSON.stringify(payload, null, 2);
  215. if (values.out) {
  216. fs.mkdirSync(path.dirname(path.resolve(values.out)), { recursive: true });
  217. fs.writeFileSync(path.resolve(values.out), `${text}\n`, 'utf8');
  218. } else {
  219. process.stdout.write(`${text}\n`);
  220. }
  221. return payload.ok ? 0 : 1;
  222. }
  223. const invokedDirectly = process.argv[1] && path.resolve(process.argv[1]).endsWith(path.join('scripts', 'listen-bridge.mjs'));
  224. if (invokedDirectly) {
  225. main().then((code) => process.exit(code)).catch((error) => {
  226. process.stderr.write(`listen-bridge 失败:${error.message}\n`);
  227. process.exit(1);
  228. });
  229. }