| 'use server'; |
| |
| |
| |
| |
| |
| |
| |
|
|
| import { ai } from '@/ai/genkit'; |
| import { z } from 'genkit'; |
| import pdf from 'pdf-parse'; |
|
|
| const AiDocumentSummarizationInputSchema = z.object({ |
| fileContentBase64: z.string().describe('The file content as a base64 encoded string.'), |
| mimeType: z.string().describe('The mime type of the file.'), |
| }); |
| export type AiDocumentSummarizationInput = z.infer<typeof AiDocumentSummarizationInputSchema>; |
|
|
| const AiDocumentSummarizationOutputSchema = z.object({ |
| summary: z.string().describe('A concise and accurate summary of the document.'), |
| documentContent: z.string().describe('The extracted text content of the document.'), |
| }); |
| export type AiDocumentSummarizationOutput = z.infer<typeof AiDocumentSummarizationOutputSchema>; |
|
|
| export async function summarizeDocument( |
| input: AiDocumentSummarizationInput |
| ): Promise<AiDocumentSummarizationOutput> { |
| return aiDocumentSummarizationFlow(input); |
| } |
|
|
| const PromptInputSchema = z.object({ |
| documentContent: z.string().describe('The full text content of the document to be summarized.'), |
| }); |
|
|
| const PromptOutputSchema = z.object({ |
| summary: z.string().describe('A concise and accurate summary of the document.'), |
| }); |
|
|
| const aiDocumentSummarizationPrompt = ai.definePrompt({ |
| name: 'aiDocumentSummarizationPrompt', |
| input: { schema: PromptInputSchema }, |
| output: { schema: PromptOutputSchema }, |
| prompt: `You are an AI assistant specialized in summarizing documents. Your goal is to provide a concise and accurate summary of the given document, highlighting its main points and key information. The summary should be easy to understand and capture the essence of the document. |
| |
| Document Content: |
| {{{ |
| documentContent |
| }}}`, |
| }); |
|
|
| const aiDocumentSummarizationFlow = ai.defineFlow( |
| { |
| name: 'aiDocumentSummarizationFlow', |
| inputSchema: AiDocumentSummarizationInputSchema, |
| outputSchema: AiDocumentSummarizationOutputSchema, |
| }, |
| async (input) => { |
| let documentContent: string; |
| const fileBuffer = Buffer.from(input.fileContentBase64, 'base64'); |
|
|
| if (input.mimeType === 'application/pdf') { |
| try { |
| const data = await pdf(fileBuffer); |
| documentContent = data.text; |
| } catch (e) { |
| console.error('Error parsing PDF', e); |
| return { summary: 'Failed to parse the PDF document.', documentContent: 'Could not read PDF content.' }; |
| } |
| } else { |
| documentContent = fileBuffer.toString('utf-8'); |
| } |
|
|
| if (!documentContent.trim()) { |
| return { summary: 'The document appears to be empty or could not be read.', documentContent }; |
| } |
|
|
| const { output } = await aiDocumentSummarizationPrompt({ documentContent }); |
| return { summary: output!.summary, documentContent }; |
| } |
| ); |
|
|