Added working code

This commit is contained in:
BHAGTANIDEEPAK 2025-04-14 17:08:57 +05:30
parent 925f47a18b
commit e1e7cd897f
7 changed files with 1944 additions and 0 deletions

2
.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
.env
node_modules/

1830
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

21
package.json Normal file
View File

@ -0,0 +1,21 @@
{
"name": "invoice-api",
"version": "1.0.0",
"description": "",
"main": "index.js",
"type": "module",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"@mistralai/mistralai": "^1.5.2",
"cors": "^2.8.5",
"dotenv": "^16.5.0",
"express": "^5.1.0",
"multer": "^1.4.5-lts.2",
"node-fetch": "^3.3.2"
}
}

91
server.js Normal file
View File

@ -0,0 +1,91 @@
import express from "express";
import multer from "multer";
import dotenv from "dotenv";
import cors from "cors";
import fetch from "node-fetch";
dotenv.config();
const app = express();
const port = process.env.PORT || 5000;
const upload = multer({ storage: multer.memoryStorage() });
app.use(express.json());
app.use(cors());
app.get("/", (req, res) => {
res.send("Hello World!");
});
app.post("/extract", upload.single("file"), async (req, res) => {
if (!req.file) {
return res.status(400).json({ error: "No file uploaded" });
}
try {
const base64Image = req.file.buffer.toString("base64"); // Convert image to Base64
const requestBody = {
model: "pixtral-12b",
messages: [
{
role: "user",
content: [
{ type: "text", text: "Extract invoice details from this image. Now for extracting the details, I want JSON of this invoice. The main reason behind this is that invoices do not have a fixed format, but with JSON it will be in a fixed format. So please output as JSON only, nothing else, just JSON." },
{ type: "image_url", image_url: `data:image/jpeg;base64,${base64Image}` }
],
},
],
};
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 30000); // 30 seconds timeout
const response = await fetch("https://api.mistral.ai/v1/chat/completions", {
method: "POST",
headers: {
"Authorization": `Bearer ${process.env.MISTRAL_API_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify(requestBody),
signal: controller.signal,
});
clearTimeout(timeoutId);
console.log("Mistral API Response Status:", response.status);
if (!response.ok) {
const errorResponse = await response.text();
console.error("Error Response:", errorResponse);
return res.status(response.status).json({ error: errorResponse });
}
const data = await response.json();
console.log("Mistral API Response:", JSON.stringify(data, null, 2));
const jsonContent = data.choices[0].message.content;
const cleanedJsonContent = jsonContent.replace(/```json\n|\n```/g, '');
let invoiceData;
try {
invoiceData = JSON.parse(cleanedJsonContent);
} catch (parseError) {
console.error("Error parsing JSON:", parseError);
return res.status(500).json({ error: "Error parsing JSON response" });
}
res.json(invoiceData);
} catch (error) {
if (error.name === 'AbortError') {
console.error("Request timed out");
return res.status(504).json({ error: "Request timed out" });
}
console.error("Error:", error.message);
res.status(500).json({ error: error.message });
}
});
app.listen(port, "0.0.0.0", () => {
console.log(`Server running on port ${port}`);
});

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.1 KiB