Spaces:
Running
Running
Download api.js from Buris1212/brainysnap-solver: direct link, hf CLI and curl.
- Browser
- Download file 2.19 kB
-
https://huggingface.co/spaces/Buris1212/brainysnap-solver/resolve/main/api.js
- Command line
-
hf download hf://spaces/Buris1212/brainysnap-solver/api.js
-
curl -L -o api.js https://huggingface.co/spaces/Buris1212/brainysnap-solver/resolve/main/api.js
2.19 kB
| const express = require('express'); | |
| const multer = require('multer'); | |
| const { GoogleGenerativeAI } = require('@google/generative-ai'); | |
| // Remove this since we're not using env variable anymore | |
| const app = express(); | |
| const upload = multer({ limits: { fileSize: 5 * 1024 * 1024 } }); // 5MB limit | |
| // Remove this since we're using user-provided API keys | |
| app.use(express.json()); | |
| app.use(express.static('public')); | |
| // API endpoint to process exam questions | |
| app.post('/api/solve', upload.single('image'), async (req, res) => { | |
| try { | |
| if (!req.file) { | |
| return res.status(400).json({ error: 'No image uploaded' }); | |
| } | |
| if (!req.body.subject) { | |
| return res.status(400).json({ error: 'Subject not specified' }); | |
| } | |
| // Convert image to base64 | |
| const imageBase64 = req.file.buffer.toString('base64'); | |
| // Get API key from headers | |
| const apiKey = req.headers['x-api-key']; | |
| if (!apiKey) { | |
| return res.status(400).json({ error: 'API key not provided' }); | |
| } | |
| // Initialize Gemini model with user's API key | |
| const userGenAI = new GoogleGenerativeAI(apiKey); | |
| const model = userGenAI.getGenerativeModel({ model: "gemini-pro-vision" }); | |
| // Create prompt based on subject | |
| const prompt = `Analyze this ${req.body.subject} exam question and provide: | |
| 1. The exact question text | |
| 2. Step-by-step solution | |
| 3. Final answer | |
| Format the response as JSON with: | |
| { | |
| "question": "extracted question text", | |
| "solution": "complete solution explanation", | |
| "steps": ["step 1", "step 2", ...] | |
| }`; | |
| // Generate content | |
| const result = await model.generateContent([ | |
| prompt, | |
| { inlineData: { data: imageBase64, mimeType: req.file.mimetype } } | |
| ]); | |
| const response = await result.response; | |
| const text = response.text(); | |
| // Parse the response (Gemini may return markdown with JSON) | |
| let jsonResponse; | |
| try { | |
| // Extract JSON from markdown if needed | |
| const jsonMatch = text.match(/ |