| 1 | import * as fs from 'node:fs' |
| 2 | import * as os from 'node:os' |
| 3 | import * as path from 'node:path' |
| 4 | import { createSdkMcpServer, McpSdkServerConfigWithInstance } from '@anthropic-ai/claude-agent-sdk' |
| 5 | import { Injectable, Logger } from '@nestjs/common' |
| 6 | import { AssetsService } from '@yikart/assets' |
| 7 | import { UserType } from '@yikart/common' |
| 8 | import { AssetType } from '@yikart/mongodb' |
| 9 | import { execa } from 'execa' |
| 10 | import { z } from 'zod' |
| 11 | import { AiAvailabilityService } from '../../ai-availability' |
| 12 | import { ChatService } from '../../ai/chat' |
| 13 | import { McpServerName } from '../agent.constants' |
| 14 | import { FFMPEG_REMOTE_PROTOCOL_WHITELIST, resolveSafeMediaUrl, successResult, wrapTool } from './mcp.utils' |
| 15 | |
| 16 | const generateSubtitleSchema = z.object({ |
| 17 | mediaUrl: z.string().describe('Video or audio URL to transcribe'), |
| 18 | language: z.string().optional().describe('Target language code, e.g., "zh-CN", "en-US"'), |
| 19 | }) |
| 20 | |
| 21 | export enum SubtitleToolName { |
| 22 | GenerateSubtitle = 'generateSubtitle', |
| 23 | } |
| 24 | |
| 25 | interface SubtitleEntry { |
| 26 | index: number |
| 27 | startTime: number |
| 28 | endTime: number |
| 29 | text: string |
| 30 | } |
| 31 | |
| 32 | @Injectable() |
| 33 | export class SubtitleMcp { |
| 34 | private readonly logger = new Logger(SubtitleMcp.name) |
| 35 | |
| 36 | constructor( |
| 37 | private readonly chatService: ChatService, |
| 38 | private readonly assetsService: AssetsService, |
| 39 | private readonly aiAvailability: AiAvailabilityService, |
| 40 | ) {} |
| 41 | |
| 42 | /** |
| 43 | * 使用 FFmpeg 从 URL 提取音频 |
| 44 | */ |
| 45 | private async extractAudioWithFFmpeg(mediaUrl: string): Promise<Buffer> { |
| 46 | const safeMediaUrl = await resolveSafeMediaUrl(mediaUrl) |
| 47 | |
| 48 | const tempDir = os.tmpdir() |
| 49 | const outputPath = path.join(tempDir, `audio-${Date.now()}.aac`) |
| 50 | |
| 51 | try { |
| 52 | await execa('ffmpeg', [ |
| 53 | '-protocol_whitelist', |
| 54 | FFMPEG_REMOTE_PROTOCOL_WHITELIST, |
| 55 | '-i', |
| 56 | safeMediaUrl, |
| 57 | '-vn', |
| 58 | '-acodec', |
| 59 | 'aac', |
| 60 | '-b:a', |
| 61 | '128k', |
| 62 | '-y', |
| 63 | outputPath, |
| 64 | ]) |
| 65 | |
| 66 | return fs.readFileSync(outputPath) |
| 67 | } |
| 68 | finally { |
| 69 | if (fs.existsSync(outputPath)) { |
| 70 | fs.unlinkSync(outputPath) |
| 71 | } |
| 72 | } |
| 73 | } |
| 74 | |
| 75 | /** |
| 76 | * 构建字幕转录提示词 |
| 77 | */ |
| 78 | private buildSubtitlePrompt(language?: string): string { |
| 79 | const targetLang = language || 'the original spoken language' |
| 80 | return `Transcribe this audio to ${targetLang} with precise timestamps. |
| 81 | |
| 82 | Requirements: |
| 83 | 1. Each subtitle entry should be 1-2 sentences, max 2 lines |
| 84 | 2. Timestamps must be accurate to the audio (in milliseconds) |
| 85 | 3. Use proper punctuation |
| 86 | 4. Return a JSON object with an "entries" array |
| 87 | |
| 88 | Each entry must have: |
| 89 | - index: number (starting from 1) |
| 90 | - startTime: number (milliseconds) |
| 91 | - endTime: number (milliseconds) |
| 92 | - text: string (subtitle text) |
| 93 | |
| 94 | Example output format: |
| 95 | { |
| 96 | "entries": [ |
| 97 | { "index": 1, "startTime": 0, "endTime": 2500, "text": "Hello, welcome to our video." }, |
| 98 | { "index": 2, "startTime": 2600, "endTime": 5000, "text": "Today we will discuss..." } |
| 99 | ] |
| 100 | }` |
| 101 | } |
| 102 | |
| 103 | /** |
| 104 | * 将毫秒转换为 SRT 时间格式 (HH:MM:SS,mmm) |
| 105 | */ |
| 106 | private formatSrtTime(ms: number): string { |
| 107 | const hours = Math.floor(ms / 3600000) |
| 108 | const minutes = Math.floor((ms % 3600000) / 60000) |
| 109 | const seconds = Math.floor((ms % 60000) / 1000) |
| 110 | const milliseconds = ms % 1000 |
| 111 | |
| 112 | return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')},${milliseconds.toString().padStart(3, '0')}` |
| 113 | } |
| 114 | |
| 115 | /** |
| 116 | * 从结构化数据生成 SRT 格式字幕 |
| 117 | */ |
| 118 | private generateSrtFromEntries(entries: SubtitleEntry[]): string { |
| 119 | return entries.map((entry) => { |
| 120 | const startTime = this.formatSrtTime(entry.startTime) |
| 121 | const endTime = this.formatSrtTime(entry.endTime) |
| 122 | return `${entry.index}\n${startTime} --> ${endTime}\n${entry.text}\n` |
| 123 | }).join('\n') |
| 124 | } |
| 125 | |
| 126 | createGenerateSubtitleTool(userId: string, userType: UserType) { |
| 127 | return wrapTool( |
| 128 | this.logger, |
| 129 | SubtitleToolName.GenerateSubtitle, |
| 130 | `Generate SRT subtitles from video or audio using AI transcription. |
| 131 | |
| 132 | Parameters: |
| 133 | - mediaUrl: URL of the video or audio file to transcribe |
| 134 | - language (optional): Target language code (e.g., "zh-CN", "en-US", "ja-JP") |
| 135 | |
| 136 | Returns the generated SRT subtitle file URL. |
| 137 | |
| 138 | Use this tool when user wants to: |
| 139 | - 给视频加字幕 / Add subtitles to video |
| 140 | - 生成字幕 / Generate subtitles |
| 141 | - 视频转录 / Transcribe video |
| 142 | - 提取视频文字 / Extract text from video`, |
| 143 | generateSubtitleSchema.shape, |
| 144 | async ({ mediaUrl, language }) => { |
| 145 | this.logger.log({ mediaUrl, language }, 'Starting subtitle generation') |
| 146 | |
| 147 | // Step 1: 使用 FFmpeg 提取音频 |
| 148 | this.logger.debug('Extracting audio from media URL') |
| 149 | const audioBuffer = await this.extractAudioWithFFmpeg(mediaUrl) |
| 150 | this.logger.debug({ size: audioBuffer.length }, 'Audio extracted') |
| 151 | |
| 152 | // Step 2: 构建提示词 |
| 153 | const prompt = this.buildSubtitlePrompt(language) |
| 154 | |
| 155 | // Step 3: 调用 Gemini 进行转录 |
| 156 | this.logger.debug('Calling Gemini for transcription') |
| 157 | const response = await this.chatService.userGeminiGenerateContent({ |
| 158 | userId, |
| 159 | userType, |
| 160 | model: 'gemini-3.5-flash', |
| 161 | contents: [{ |
| 162 | role: 'user', |
| 163 | parts: [ |
| 164 | { |
| 165 | inlineData: { |
| 166 | mimeType: 'audio/aac', |
| 167 | data: audioBuffer.toString('base64'), |
| 168 | }, |
| 169 | }, |
| 170 | { text: prompt }, |
| 171 | ], |
| 172 | }], |
| 173 | config: { |
| 174 | responseMimeType: 'application/json', |
| 175 | }, |
| 176 | }) |
| 177 | |
| 178 | // Step 4: 解析响应 |
| 179 | const responseText = response.text |
| 180 | if (!responseText) { |
| 181 | throw new Error('No response from Gemini') |
| 182 | } |
| 183 | |
| 184 | const subtitleData = JSON.parse(responseText) as { entries: SubtitleEntry[] } |
| 185 | if (!subtitleData.entries || subtitleData.entries.length === 0) { |
| 186 | throw new Error('No subtitle entries in response') |
| 187 | } |
| 188 | |
| 189 | this.logger.debug({ entryCount: subtitleData.entries.length }, 'Subtitle entries parsed') |
| 190 | |
| 191 | // Step 5: 生成 SRT 格式 |
| 192 | const srtContent = this.generateSrtFromEntries(subtitleData.entries) |
| 193 | |
| 194 | // Step 6: 上传 SRT 文件 |
| 195 | this.logger.debug('Uploading SRT file') |
| 196 | const srtBuffer = Buffer.from(srtContent, 'utf-8') |
| 197 | const result = await this.assetsService.uploadFromBuffer(userId, srtBuffer, { |
| 198 | type: AssetType.Subtitle, |
| 199 | mimeType: 'text/plain', |
| 200 | filename: `subtitle-${Date.now()}.srt`, |
| 201 | }) |
| 202 | |
| 203 | return successResult(`Subtitle generated successfully! |
| 204 | |
| 205 | **SRT File URL:** ${result.url} |
| 206 | **Entries:** ${subtitleData.entries.length} |
| 207 | |
| 208 | You can use this SRT URL in video editing to add subtitles.`) |
| 209 | }, |
| 210 | this.aiAvailability, |
| 211 | ) |
| 212 | } |
| 213 | |
| 214 | createServer(userId: string, userType: UserType): McpSdkServerConfigWithInstance { |
| 215 | return createSdkMcpServer({ |
| 216 | name: McpServerName.Subtitle, |
| 217 | version: '1.0.0', |
| 218 | tools: [ |
| 219 | this.createGenerateSubtitleTool(userId, userType), |
| 220 | ], |
| 221 | }) |
| 222 | } |
| 223 | } |
| 224 |