Repository navigation
Expand file tree
/
Copy pathindex.js
More file actions
65 lines (54 loc) · 2.18 KB
/
Copy pathindex.js
File metadata and controls
65 lines (54 loc) · 2.18 KB
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
const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const Tesseract = require('tesseract.js');
const app = express();
const PORT = process.env.PORT || 3000;
app.use(cors()); // Mengizinkan akses dari extension
app.use(bodyParser.json({ limit: '10mb' }));
console.log("Server OCR aktif.")
/**
* Endpoint POST untuk melakukan OCR pada gambar yang dikirim dalam format base64.
*
* @route POST /ocr
* @param {Object} req.body - Body permintaan JSON.
* @param {string} req.body.image - Gambar dalam format data URL base64 (misal: `data:image/png;base64,...`).
* @returns {Object} 200 - Respons sukses dengan teks hasil OCR.
* @returns {string} 200.text - Teks yang diekstraksi, dipangkas dari whitespace berlebihan.
* @returns {Object} 400 - Jika gambar tidak disertakan dalam permintaan.
* @returns {Object} 500 - Jika terjadi kesalahan internal selama pemrosesan OCR.
*
* @example
* // Permintaan
* POST /ocr
* Content-Type: application/json
* {
* "image": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA..."
* }
*
* // Respons sukses
* { "text": "Contoh teks hasil OCR" }
*/
app.post('/ocr', async (req, res) => {
try {
const { image } = req.body;
if (!image) {
console.log("Permintaan ditolak: Tidak ada gambar yang dikirim.");
return res.status(400).json({ error: 'Gambar tidak ditemukan dalam permintaan.' });
}
console.log("Gambar diterima. Melakukan decoding base64.");
const base64Data = image.replace(/^data:image\/\w+;base64,/, "");
const imgBuffer = Buffer.from(base64Data, 'base64');
console.log("Proses OCR dimulai (Model Bahasa: Indonesia + Inggris).");
// Proses OCR menggunakan Tesseract.js
const { data: { text } } = await Tesseract.recognize(imgBuffer, 'eng+ind');
console.log("Hasil:", text.substring(0, 50) + "...");
res.json({ text: text.trim() });
} catch (error) {
console.error("OCR Error:", error);
res.status(500).json({ error: `Kesalahan server: ${error.message}` });
}
})
app.listen(PORT, () => {
console.log(`Server berjalan pada alamat: http://localhost:${PORT}`);
});