92 lines
2.8 KiB
JavaScript
92 lines
2.8 KiB
JavaScript
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}`);
|
|
});
|