-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
196 lines (172 loc) · 6.92 KB
/
Copy pathindex.html
File metadata and controls
196 lines (172 loc) · 6.92 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
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
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>OCR PDF to JSON (Groq API - Free Model)</title>
<link
href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css"
rel="stylesheet"
/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.16.105/pdf.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tesseract.js/4.0.2/tesseract.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/json5/2.2.3/index.min.js"></script>
</head>
<body class="bg-light">
<div class="container mt-5">
<h2 class="mb-4 text-center">PDF to JSON Extractor</h2>
<div class="card p-4 shadow-sm">
<label class="form-label"><strong>Select PDF File:</strong></label>
<input
type="file"
id="pdfInput"
class="form-control"
accept="application/pdf"
/>
<button id="extractBtn" class="btn btn-primary mt-3 w-100">
Extract
</button>
<p
id="statusMessage"
class="text-center mt-3 text-muted"
style="display: none"
>
<strong>⏳ Please wait, processing...</strong>
</p>
<div class="mt-4">
<h5>Extracted JSON Output:</h5>
<pre
id="output"
class="bg-dark text-light p-3 rounded"
style="max-height: 300px; overflow: auto"
></pre>
</div>
</div>
</div>
<script>
document
.getElementById("extractBtn")
.addEventListener("click", async function () {
const fileInput = document.getElementById("pdfInput");
const statusMessage = document.getElementById("statusMessage");
const output = document.getElementById("output");
if (!fileInput.files.length) {
alert("Please select a PDF file first.");
return;
}
statusMessage.style.display = "block";
output.innerText = "";
const file = fileInput.files[0];
const reader = new FileReader();
reader.onload = async function () {
const pdfData = new Uint8Array(reader.result);
const pdf = await pdfjsLib.getDocument({ data: pdfData }).promise;
let extractedText = "";
for (let pageNum = 1; pageNum <= pdf.numPages; pageNum++) {
const page = await pdf.getPage(pageNum);
const scale = 2;
const viewport = page.getViewport({ scale });
const canvas = document.createElement("canvas");
const context = canvas.getContext("2d");
canvas.width = viewport.width;
canvas.height = viewport.height;
await page.render({ canvasContext: context, viewport }).promise;
await Tesseract.recognize(canvas.toDataURL("image/png"), "eng")
.then(({ data: { text } }) => {
extractedText += text + "\n\n";
})
.catch((err) => {
console.error(`Error processing page ${pageNum}:`, err);
});
}
console.log("Extracted Raw Text:", extractedText);
sendToGroqAPI(extractedText);
};
reader.readAsArrayBuffer(file);
});
async function sendToGroqAPI(extractedText) {
const groq_api_key = "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";
const groq_url = "https://api.groq.com/openai/v1/chat/completions";
const prompt = `Extract and structure the following text into valid JSON format:
- Company Name
- Voucher No
- Date
- Location
- Receiver Name
- Received From
- Particular
- Amount
- Remark (Ensure it contains all key details like amount, reason, reference number, and transaction context)
**Important:**
- JSON format must be **valid**.
- "Remark" should be **a single well-structured plain text string** containing all key details.
- Do not return "Remark" in a nested JSON format.
- Ensure the "Remark" is clear, detailed, and includes all necessary information.
**Example Output:**
\`\`\`json
{
"CompanyName": "Hema Seeds Pvt Ltd",
"VoucherNo": "HSPL/RV/KOHA/577/24-25",
"Date": "12-01-2025",
"Location": "Kohadia, Raipur, Chhattisgarh, Pincode: 492001",
"ReceiverName": "Shakti Bag",
"ReceivedFrom": "Mr. Shakti Bag",
"Particular": "Shakti Bag Khd - 2710163 Adv. A/c",
"Amount": 2000,
"Remark": "An amount of INR 2000 (Rupees Two Thousand Only) has been returned in cash by Mr. Shakti Bag as an adjustment against the advance payment recorded in account number 2710163. This transaction is documented under voucher number HSPL/RV/KOHA/577/24-25 at the Kohadia, Raipur branch."
}
\`\`\`
Now, process the following extracted text and return **only valid JSON**:
"""${extractedText}"""`;
const response = await fetch(groq_url, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${groq_api_key}`,
},
body: JSON.stringify({
model: "llama3-8b-8192",
messages: [{ role: "user", content: prompt }],
temperature: 0,
}),
});
const data = await response.json();
document.getElementById("statusMessage").style.display = "none";
if (data.choices && data.choices.length > 0) {
try {
let jsonString = data.choices[0].message.content.trim();
// Extract JSON content correctly
const jsonStartIndex = jsonString.indexOf("{");
const jsonEndIndex = jsonString.lastIndexOf("}");
if (jsonStartIndex !== -1 && jsonEndIndex !== -1) {
jsonString = jsonString.substring(
jsonStartIndex,
jsonEndIndex + 1
);
}
// Parse JSON safely
const structuredJSON = JSON.parse(jsonString);
console.log("Extracted JSON:", structuredJSON);
document.getElementById("output").innerText = JSON.stringify(
structuredJSON,
null,
2
);
} catch (err) {
console.error(
"Error parsing JSON:",
err,
data.choices[0].message.content
);
document.getElementById("output").innerText =
"⚠️ Error parsing JSON response.";
}
} else {
console.error("Invalid API response:", data);
document.getElementById("output").innerText =
"⚠️ Error: Invalid API response.";
}
}
</script>
</body>
</html>