Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 41 additions & 21 deletions backend/controllers/receiptController.js
Original file line number Diff line number Diff line change
@@ -1,16 +1,19 @@
const Receipt = require('../models/Receipt');
const IncomeExpense = require('../models/IncomeExpense');
const { GoogleGenerativeAI } = require("@google/generative-ai");
const fs = require('fs');
const Receipt = require("../models/Receipt");
const IncomeExpense = require("../models/IncomeExpense");
const { GoogleGenAI } = require("@google/genai");

const genAI = new GoogleGenerativeAI(process.env.GEMINI_API_KEY);
const fs = require("fs");

const client = new GoogleGenAI({
apiKey: process.env.GEMINI_API_KEY,
});

// Helper function to convert a file to a format Gemini can understand
function fileToGenerativePart(path, mimeType) {
return {
inlineData: {
data: fs.readFileSync(path).toString("base64"),
mimeType
mimeType,
},
};
}
Expand All @@ -20,12 +23,10 @@ function fileToGenerativePart(path, mimeType) {
// @access Private
const uploadReceipt = async (req, res) => {
if (!req.file) {
return res.status(400).json({ message: 'Please upload a file' });
return res.status(400).json({ message: "Please upload a file" });
}

try {
const model = genAI.getGenerativeModel({ model: "gemini-1.5-flash-latest" });

const prompt = `
Analyze this receipt image. Extract the following details:
- merchant: The name of the store or merchant.
Expand All @@ -36,24 +37,39 @@ const uploadReceipt = async (req, res) => {
Return the result as a single, minified JSON object. For example:
{"merchant":"Walmart","amount":42.97,"date":"2025-09-13","category":"Groceries"}
`;

const imagePart = fileToGenerativePart(req.file.path, req.file.mimetype);

const result = await model.generateContent([prompt, imagePart]);
const response = await result.response;
let text = response.text();
const result = await client.models.generateContent({
model: "gemini-2.5-flash-lite",
contents: [{ role: "user", parts: [{ text: prompt }, imagePart] }],
});

const raw =
result.candidates?.[0]?.content?.parts?.map((p) => p.text).join("\n\n") ??
"";

text = text.replace(/```json/g, '').replace(/```/g, '').trim();
const extractedData = JSON.parse(text);
const cleanedText = raw
.replace(/^[\s`]*```json[\s`]*/i, "") // Remove opening ```json with spaces
.replace(/[\s`]*```$/i, "") // Remove closing ```
.trim();

let extractedData;
try {
extractedData = JSON.parse(cleanedText);
} catch (e) {
console.warn("[Gemini] Invalid JSON, fallback to defaults.", e);
extractedData = {};
}

const newReceipt = new Receipt({
user: req.user.id,
fileUrl: `/uploads/${req.file.filename}`,
extractedData: {
amount: extractedData.amount || 0,
category: extractedData.category || 'Miscellaneous',
category: extractedData.category || "Miscellaneous",
date: extractedData.date ? new Date(extractedData.date) : new Date(),
merchant: extractedData.merchant || 'Unknown Merchant',
merchant: extractedData.merchant || "Unknown Merchant",
},
});

Expand All @@ -73,10 +89,14 @@ const uploadReceipt = async (req, res) => {
}

res.status(201).json(savedReceipt);

} catch (error) {
console.error('Error with Gemini API:', error);
res.status(500).json({ message: 'Failed to process receipt with AI', error: error.message });
console.error("Error with Gemini API:", error);
res
.status(500)
.json({
message: "Failed to process receipt with AI",
error: error.message,
});
} finally {
// Deleting the temporary file from the server
fs.unlinkSync(req.file.path);
Expand All @@ -85,4 +105,4 @@ const uploadReceipt = async (req, res) => {

module.exports = {
uploadReceipt,
};
};
Loading
Loading