-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
164 lines (152 loc) · 4.86 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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
const express = require("express");
const app = express();
const router = express.Router();
const mongoose = require("mongoose");
const ocrRoutes = require("./routes/ocrRoutes");
const dataRoutes = require("./routes/dataRoutes");
const path = require("path");
const multer = require("multer");
const fs = require("fs");
const { run } = require("./utils/gpt.js");
const { convertStringtoJSON } = require("./utils/stringtojson.js");
var imgSchema = require("./model/model.js");
const datahandle = require("./model/data-model.js");
const { toArray } = require("./utils/toarray.js");
const fse = require("fs-extra");
const cors = require("cors");
require("dotenv").config();
mongoose.connect(process.env.MONGO_URI).then(console.log("DB Connected"));
app.use(cors(
{
origin: "https://id-ocr-application.vercel.app/",
}
));
app.use(express.json({ limit: "2mb" }));
app.use(express.urlencoded({ extended: false, limit: "2mb" }));
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, "./uploads");
},
filename: function (req, file, cb) {
cb(null, file.fieldname + "-" + Date.now());
},
});
const upload = multer({ storage: storage }).single("avatar");
app.set("view engine", "ejs");
// Endpoint to retrieve all images with message
app.get("/images", async (req, res) => {
try {
const images = await imgSchema.find().select("-__v -_id").exec();
// Send the images as JSON response
res.status(200).json(images);
} catch (err) {
console.error("Error retrieving images:", err);
res.status(500).json({ error: "Internal Server Error" });
}
});
app.get("/status", (req, res) => {
res.status(200).json({ status: "Server is running" });
});
//Endpoint to create a new OCR Record
app.post("/upload", upload, async (req, res) => {
try {
console.log(req.file);
if(!req.file){
res.status(400).json({error:"Please upload a file"});
}
const result = await run(req.file.path, req.file.mimetype); // Pass the image path to the Gemini-Pro Vision function
const jsonData = convertStringtoJSON(result);
const checkdeddata = toArray(result);
let x1 = 1;
if (jsonData == "NA") {
x1 = 0;
}
// Read the image file and convert it to base64
const imageData = fs.readFileSync(
path.join(__dirname, "/uploads/", req.file.filename)
);
const base64Image = Buffer.from(imageData).toString("base64");
// console.log(base64Image);
let x = "Data extracted successfully";
let xx=0;
if (x1 == 0) {
for (let i = 0; i < checkdeddata.length; i++) {
if (checkdeddata[i] == "NA") {
checkdeddata[i] = "NA";
xx++;
}
}
if(xx>3)checkdeddata[7] = "Reject";
x = "Blurry Image.Retry Again!!";
}
var obj = {
desc: x,
img: {
data: base64Image,
contentType: req.file.mimetype,
},
};
var obj1 = {
idNumber: checkdeddata[0],
firstname: checkdeddata[1],
lastName: checkdeddata[2],
dateOfBirth: checkdeddata[3],
dateOfIssue: checkdeddata[4],
dateOfExpiry: checkdeddata[5],
dateOfUpload: checkdeddata[6],
status: checkdeddata[7],
};
datahandle.create(obj1);
imgSchema
.create(obj)
.then((item) => {
// Only redirect if the creation was successful
res.statusCode = 200;
res.setHeader("Content-Type", "application/json");
res.write(JSON.stringify(jsonData));
console.log("Data inserted: ", item);
// res.redirect('/');
})
.catch((err) => {
console.log("Data not inserted: ", err);
// Handle the error appropriately (send an error response, log, etc.)
})
.finally(() => {
// Make sure to end the response after handling the async operation
res.end();
fse.emptyDir("./uploads", (err) => {
if (err) {
console.error("Error emptying uploads folder:", err);
} else {
console.log("uploads folder emptied successfully");
}
});
});
// res.json(jsonData); // Send the extracted information as JSON
} catch (error) {
console.error(error);
res.setHeader(404, { "Content-Type": "application/json" });
res.end(JSON.stringify({ error: "Could not process image" }));
if (process.exitCode !== null) {
console.log("Restarting server...");
process.exitCode = null; // Reset exitCode
startServer(); // Call a function to start the server
}
}
});
app.use("/data", dataRoutes);
//to start server
const PORT = 5003 || process.env.PORT;
startServer();
function startServer() {
const server = app.listen(PORT, () => {
console.log(`Server started on port ${PORT}`);
});
// Handle unhandled promise rejections
process.on("unhandledRejection", (err) => {
console.error("Unhandled Rejection:", err);
server.close(() => {
process.exit(1);
});
});
}