|
| 1 | +import { NextRequest, NextResponse } from 'next/server' |
| 2 | +import { GoogleGenerativeAI } from '@google/generative-ai' |
| 3 | + |
| 4 | +const genAI = new GoogleGenerativeAI(process.env.GEMINI_API_KEY || '') |
| 5 | + |
| 6 | +export async function POST(request: NextRequest) { |
| 7 | + try { |
| 8 | + const formData = await request.formData() |
| 9 | + const files = formData.getAll('files') as File[] |
| 10 | + |
| 11 | + if (!files.length) { |
| 12 | + return NextResponse.json({ error: 'No files provided' }, { status: 400 }) |
| 13 | + } |
| 14 | + |
| 15 | + const model = genAI.getGenerativeModel({ model: 'gemini-1.5-flash' }) |
| 16 | + |
| 17 | + const results = [] |
| 18 | + |
| 19 | + for (const file of files) { |
| 20 | + const bytes = await file.arrayBuffer() |
| 21 | + const buffer = Buffer.from(bytes) |
| 22 | + |
| 23 | + const imagePart = { |
| 24 | + inlineData: { |
| 25 | + data: buffer.toString('base64'), |
| 26 | + mimeType: file.type, |
| 27 | + }, |
| 28 | + } |
| 29 | + |
| 30 | + const prompt = `Analyze this image and provide: |
| 31 | +1. A descriptive title for a presentation slide |
| 32 | +2. Key points that could be extracted from this image |
| 33 | +3. Suggested slide content or talking points |
| 34 | +4. Any text visible in the image |
| 35 | +
|
| 36 | +Please format the response as JSON with the following structure: |
| 37 | +{ |
| 38 | + "title": "slide title", |
| 39 | + "keyPoints": ["point 1", "point 2", "point 3"], |
| 40 | + "content": "detailed description", |
| 41 | + "extractedText": "any text found in image" |
| 42 | +}` |
| 43 | + |
| 44 | + const result = await model.generateContent([prompt, imagePart]) |
| 45 | + const response = await result.response |
| 46 | + const text = response.text() |
| 47 | + |
| 48 | + try { |
| 49 | + const parsed = JSON.parse(text) |
| 50 | + results.push({ |
| 51 | + filename: file.name, |
| 52 | + analysis: parsed |
| 53 | + }) |
| 54 | + } catch (e) { |
| 55 | + results.push({ |
| 56 | + filename: file.name, |
| 57 | + analysis: { |
| 58 | + title: 'Generated Slide', |
| 59 | + keyPoints: ['Content extracted from image'], |
| 60 | + content: text, |
| 61 | + extractedText: '' |
| 62 | + } |
| 63 | + }) |
| 64 | + } |
| 65 | + } |
| 66 | + |
| 67 | + return NextResponse.json({ results }) |
| 68 | + |
| 69 | + } catch (error) { |
| 70 | + console.error('Error analyzing images:', error) |
| 71 | + return NextResponse.json( |
| 72 | + { error: 'Failed to analyze images' }, |
| 73 | + { status: 500 } |
| 74 | + ) |
| 75 | + } |
| 76 | +} |
0 commit comments