ai.service.ts235 lines, 7.5 KB
| 1 | import { |
| 2 | GenerateContentRequest, |
| 3 | GoogleGenerativeAI, |
| 4 | } from "@google/generative-ai"; |
| 5 | import { AppError } from "../utils/errors"; |
| 6 | import { StatusCodes } from "http-status-codes"; |
| 7 | import logger from "../utils/logger"; |
| 8 | |
| 9 | // Interface for video chapters |
| 10 | export interface Chapter { |
| 11 | title: string; // Title of the chapter |
| 12 | startTime: number; // Start time in seconds |
| 13 | endTime: number; // End time in seconds |
| 14 | } |
| 15 | |
| 16 | export interface AIAnalysis { |
| 17 | summary: string; |
| 18 | keyPoints: string[]; |
| 19 | sentiment: "positive" | "negative" | "neutral"; |
| 20 | topics: string[]; |
| 21 | suggestedTags: string[]; |
| 22 | chapters?: Chapter[]; // Added chapters field |
| 23 | } |
| 24 | |
| 25 | export class AIService { |
| 26 | private static readonly genAI = new GoogleGenerativeAI( |
| 27 | process.env.GOOGLE_API_KEY! |
| 28 | ); |
| 29 | // Use a more capable model if needed for better chapter generation |
| 30 | private static readonly model = AIService.genAI.getGenerativeModel({ |
| 31 | model: "gemini-2.5-pro-exp-03-25", // Updated model |
| 32 | }); |
| 33 | |
| 34 | private static generatePrompt( |
| 35 | transcription: string, |
| 36 | videoInfo?: any |
| 37 | ): string { |
| 38 | // Construct the desired JSON structure including chapters |
| 39 | const jsonStructure = JSON.stringify( |
| 40 | { |
| 41 | summary: "2-3 sentences summarizing the main content", |
| 42 | keyPoints: ["point 1", "point 2", "etc"], |
| 43 | sentiment: "positive|negative|neutral", |
| 44 | topics: ["topic1", "topic2", "etc"], |
| 45 | suggestedTags: ["#tag1", "#tag2", "etc"], |
| 46 | chapters: [ |
| 47 | { |
| 48 | title: "Chapter 1 Title", |
| 49 | startTime: 0, |
| 50 | endTime: 60, |
| 51 | }, |
| 52 | { |
| 53 | title: "Chapter 2 Title", |
| 54 | startTime: 61, |
| 55 | endTime: 120, |
| 56 | }, |
| 57 | // ... etc |
| 58 | ], |
| 59 | }, |
| 60 | null, |
| 61 | 2 |
| 62 | ); |
| 63 | |
| 64 | let prompt = `You are an expert video content analyzer. Your task is to analyze the provided video transcription, generate meaningful chapters with timestamps, and return a valid JSON response. |
| 65 | |
| 66 | **Instructions:** |
| 67 | 1. Read the entire transcription carefully. |
| 68 | 2. Identify logical sections or topics discussed in the video. |
| 69 | 3. For each section, create a concise and descriptive chapter title. |
| 70 | 4. Determine the approximate start and end times (in seconds) for each chapter based on when the topic begins and ends in the transcription content flow. Timestamps should reflect natural breaks. |
| 71 | 5. Ensure chapters cover the main parts of the video without excessive overlap or gaps. |
| 72 | 6. Provide a summary, key points, sentiment analysis, topics, and suggested tags as before. |
| 73 | 7. Your response **MUST** be valid JSON and strictly adhere to the following structure: |
| 74 | |
| 75 | \`\`\`json |
| 76 | ${jsonStructure} |
| 77 | \`\`\` |
| 78 | |
| 79 | **IMPORTANT:** |
| 80 | * Do **NOT** include any text, explanations, or formatting outside the main JSON structure. |
| 81 | * The entire response must be parseable by JSON.parse(). |
| 82 | * Ensure 'startTime' and 'endTime' are numbers representing seconds. |
| 83 | |
| 84 | **Analyze this transcription:** |
| 85 | """ |
| 86 | ${transcription} |
| 87 | """ |
| 88 | `; |
| 89 | |
| 90 | if (videoInfo) { |
| 91 | prompt += `\n\n**Additional video context (use for better analysis):** |
| 92 | Title: "${videoInfo.title}" |
| 93 | Author: "${videoInfo.author}" |
| 94 | Duration: ${videoInfo.duration} seconds (Use this duration as a guideline for chapter end times)`; |
| 95 | } |
| 96 | |
| 97 | return prompt; |
| 98 | } |
| 99 | |
| 100 | static async analyzeTranscription( |
| 101 | transcription: string, |
| 102 | videoInfo?: any |
| 103 | ): Promise<AIAnalysis> { |
| 104 | let text: string | undefined; // Declare text outside the try block |
| 105 | |
| 106 | if (!transcription || transcription.trim().length === 0) { |
| 107 | logger.warn( |
| 108 | "AIService: Received empty transcription, skipping analysis." |
| 109 | ); |
| 110 | // Return a default structure or throw an error, depending on requirements |
| 111 | // For now, let's return a minimal valid response |
| 112 | return { |
| 113 | summary: "No transcription available for analysis.", |
| 114 | keyPoints: [], |
| 115 | sentiment: "neutral", |
| 116 | topics: [], |
| 117 | suggestedTags: [], |
| 118 | chapters: [], |
| 119 | }; |
| 120 | } |
| 121 | |
| 122 | const prompt = AIService.generatePrompt(transcription, videoInfo); |
| 123 | |
| 124 | const generateConfig: GenerateContentRequest = { |
| 125 | contents: [{ role: "user", parts: [{ text: prompt }] }], |
| 126 | generationConfig: { |
| 127 | // Ensure response format is JSON |
| 128 | responseMimeType: "application/json", |
| 129 | temperature: 0.6, // Slightly lower temp for more structured output |
| 130 | topK: 40, |
| 131 | topP: 0.95, |
| 132 | maxOutputTokens: 2048, // Increased for potentially longer chapter lists |
| 133 | }, |
| 134 | }; |
| 135 | |
| 136 | try { |
| 137 | logger.info( |
| 138 | `AIService: Sending analysis request to Gemini model: ${this.model.model}` |
| 139 | ); |
| 140 | const result = await this.model.generateContent(generateConfig); |
| 141 | const response = result.response; |
| 142 | |
| 143 | if (!response) { |
| 144 | logger.error("AIService: No response received from Gemini model."); |
| 145 | throw new AppError( |
| 146 | StatusCodes.INTERNAL_SERVER_ERROR, |
| 147 | "No response from AI service" |
| 148 | ); |
| 149 | } |
| 150 | |
| 151 | text = response.text(); // Assign value inside the try block |
| 152 | logger.debug( |
| 153 | `AIService: Raw response text received: ${text.substring(0, 200)}...` |
| 154 | ); |
| 155 | |
| 156 | // Gemini should return valid JSON directly with responseMimeType set |
| 157 | const analysis = JSON.parse(text) as AIAnalysis; |
| 158 | logger.info("AIService: Successfully parsed analysis response."); |
| 159 | |
| 160 | // Validate required fields |
| 161 | if ( |
| 162 | !analysis.summary || |
| 163 | !Array.isArray(analysis.keyPoints) || |
| 164 | !analysis.sentiment |
| 165 | ) { |
| 166 | logger.error( |
| 167 | "AIService: Invalid response format - missing required fields.", |
| 168 | analysis |
| 169 | ); |
| 170 | throw new AppError( |
| 171 | StatusCodes.BAD_REQUEST, |
| 172 | "Invalid AI response format (missing fields)" |
| 173 | ); |
| 174 | } |
| 175 | |
| 176 | // Validate sentiment |
| 177 | if (!["positive", "negative", "neutral"].includes(analysis.sentiment)) { |
| 178 | logger.warn( |
| 179 | `AIService: Invalid sentiment value '${analysis.sentiment}', defaulting to neutral.` |
| 180 | ); |
| 181 | analysis.sentiment = "neutral"; |
| 182 | } |
| 183 | |
| 184 | // Validate chapters structure (basic validation) |
| 185 | if (analysis.chapters && !Array.isArray(analysis.chapters)) { |
| 186 | logger.warn( |
| 187 | "AIService: Chapters field is present but not an array, discarding." |
| 188 | ); |
| 189 | analysis.chapters = []; |
| 190 | } else if (analysis.chapters) { |
| 191 | analysis.chapters = analysis.chapters.filter( |
| 192 | (ch) => |
| 193 | typeof ch.title === "string" && |
| 194 | typeof ch.startTime === "number" && |
| 195 | typeof ch.endTime === "number" && |
| 196 | ch.startTime >= 0 && |
| 197 | ch.endTime >= ch.startTime |
| 198 | ); |
| 199 | } |
| 200 | |
| 201 | // Return normalized structure |
| 202 | return { |
| 203 | summary: analysis.summary, |
| 204 | keyPoints: analysis.keyPoints || [], |
| 205 | sentiment: analysis.sentiment, |
| 206 | topics: analysis.topics || [], |
| 207 | suggestedTags: analysis.suggestedTags || [], |
| 208 | chapters: analysis.chapters || [], |
| 209 | }; |
| 210 | } catch (error: any) { |
| 211 | if (error instanceof SyntaxError) { |
| 212 | logger.error( |
| 213 | `AIService: Failed to parse JSON response from AI. Error: ${error.message}`, |
| 214 | { rawResponse: text } |
| 215 | ); |
| 216 | throw new AppError( |
| 217 | StatusCodes.INTERNAL_SERVER_ERROR, |
| 218 | "Failed to parse AI response" |
| 219 | ); |
| 220 | } else if (error instanceof AppError) { |
| 221 | // Re-throw AppErrors directly |
| 222 | throw error; |
| 223 | } else { |
| 224 | logger.error(`AIService: Error during AI analysis: ${error.message}`, { |
| 225 | stack: error.stack, |
| 226 | error, |
| 227 | }); |
| 228 | throw new AppError( |
| 229 | StatusCodes.INTERNAL_SERVER_ERROR, |
| 230 | "AI analysis failed" |
| 231 | ); |
| 232 | } |
| 233 | } |
| 234 | } |
| 235 | } |