-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
120 lines (108 loc) · 3.65 KB
/
app.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
require("dotenv").config();
const express = require("express");
const multer = require("multer");
const path = require("path");
const PDFDocument = require("pdfkit");
const fs = require("fs");
const fsPromises = fs.promises;
const { GoogleGenerativeAI } = require("@google/generative-ai");
const app = express();
const port = process.env.PORT || 5000;
//configure multer
const upload = multer({ dest: "upload/" });
app.use(express.json({ limit: "10mb" }));
//initialize Google Generative AI
const genAI = new GoogleGenerativeAI(process.env.GEMINI_API_KEY);
app.use(express.static("public"));
//routes
//analyze
app.post("/analyze", upload.single("image"), async (req, res) => {
try {
if (!req.file) {
return res.status(400).json({ error: "No image file uploaded" });
}
const imagePath = req.file.path;
const imageData = await fsPromises.readFile(imagePath, {
encoding: "base64",
});
// Use the Gemini model to analyze the image
const model = genAI.getGenerativeModel({ model: "gemini-1.5-flash" });
const result = await model.generateContent([
"Analyze this plant image and provide detailed analysis of its species, health, and care recommendations, its characteristics, care instructions, and any interesting facts. Please provide the response in plain text without using any markdown formatting.",
{
inlineData: {
mimeType: req.file.mimetype,
data: imageData,
},
},
]);
const plantInfo = result.response.text();
// Clean up: delete the uploaded file
await fsPromises.unlink(imagePath);
// Respond with the analysis result and the image data
res.json({
result: plantInfo,
image: `data:${req.file.mimetype};base64,${imageData}`,
});
} catch (error) {
console.error("Error analyzing image:", error);
res
.status(500)
.json({ error: "An error occurred while analyzing the image" });
}
});
//download pdf
app.post("/download", express.json(), async (req, res) => {
const { result, image } = req.body;
try {
//Ensure the reports directory exists
const reportsDir = path.join(__dirname, "reports");
await fsPromises.mkdir(reportsDir, { recursive: true });
//generate pdf
const filename = `plant_analysis_report_${Date.now()}.pdf`;
const filePath = path.join(reportsDir, filename);
const writeStream = fs.createWriteStream(filePath);
const doc = new PDFDocument();
doc.pipe(writeStream);
// Add content to the PDF
doc.fontSize(24).text("Plant Analysis Report", {
align: "center",
});
doc.moveDown();
doc.fontSize(24).text(`Date: ${new Date().toLocaleDateString()}`);
doc.moveDown();
doc.fontSize(14).text(result, { align: "left" });
//insert image to the pdf
if (image) {
const base64Data = image.replace(/^data:image\/\w+;base64,/, "");
const buffer = Buffer.from(base64Data, "base64");
doc.moveDown();
doc.image(buffer, {
fit: [500, 300],
align: "center",
valign: "center",
});
}
doc.end();
//wait for the pdf to be created
await new Promise((resolve, reject) => {
writeStream.on("finish", resolve);
writeStream.on("error", reject);
});
res.download(filePath, (err) => {
if (err) {
res.status(500).json({ error: "Error downloading the PDF report" });
}
fsPromises.unlink(filePath);
});
} catch (error) {
console.error("Error generating PDF report:", error);
res
.status(500)
.json({ error: "An error occurred while generating the PDF report" });
}
});
//start the server
app.listen(port, () => {
console.log(`Listening on port ${port}`);
});