forked from simonw/tools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ocr.html
226 lines (208 loc) · 7.6 KB
/
ocr.html
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
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
<!DOCTYPE html>
<html>
<head>
<title>OCR PDFs and images directly in your browser</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script defer data-domain="tools.simonwillison.net" src="https://plausible.io/js/script.js"></script>
<script type="module">
import pdfjsDist from 'https://cdn.jsdelivr.net/npm/[email protected]/+esm';
pdfjsLib.GlobalWorkerOptions.workerSrc =
"https://cdn.jsdelivr.net/npm/[email protected]/build/pdf.worker.min.mjs";
</script>
<script src="https://cdn.jsdelivr.net/npm/tesseract.js@5/dist/tesseract.min.js"></script>
<style>
body {
padding: 1em;
font-family: helvetica, sans-serif;
line-height: 1.3;
}
.dropzone {
box-sizing: border-box;
width: 100%;
height: 10em;
border: 2px dashed #ccc;
display: flex;
justify-content: center;
align-items: center;
font-size: 24px;
cursor: pointer;
padding: 1em;
margin-bottom: 1em;
}
.dropzone.disabled {
cursor: not-allowed;
}
.dropzone.drag-over {
background-color: pink;
}
.image-container img {
margin-bottom: 10px;
max-width: 100%;
}
textarea {
width: 100%;
height: 10em;
margin-bottom: 20px;
box-sizing: border-box;
}
.full-document-section {
display: none;
margin-bottom: 20px;
}
</style>
</head>
<body>
<h1>OCR PDFs and images directly in your browser</h1>
<p>This tool runs entirely in your browser. No files are uploaded to a server.</p>
<p>It uses <a href="https://tesseract.projectnaptha.com/">Tesseract.js</a> for OCR and <a href="https://mozilla.github.io/pdf.js/">PDF.js</a> to convert PDFs into images.</p>
<input type="file" id="fileInput" accept=".pdf,.jpg,.jpeg,.png,.gif" style="display: none;" />
<div class="dropzone" id="dropzone">
Drag and drop a PDF, JPG, PNG, or GIF file here or click to select a file
</div>
<div class="full-document-section" id="fullDocumentSection">
<h2>Full document</h2>
<textarea class="full-document" id="fullDocument"></textarea>
<h2>Pages</h2>
</div>
<div class="image-container"></div>
<p><a href="https://github.com/simonw/tools/blob/main/ocr.html">Source code</a>. <a href="https://simonwillison.net/2024/Mar/30/ocr-pdfs-images/">How I built this</a>.</p>
<script>
const desiredWidth = 1000;
const dropzone = document.getElementById('dropzone');
const fileInput = document.getElementById('fileInput');
const imageContainer = document.querySelector('.image-container');
const fullDocumentTextarea = document.getElementById('fullDocument');
const fullDocumentSection = document.getElementById('fullDocumentSection');
let fileSelectionAllowed = true;
function showFullDocument() {
// Only shows if there are multiple populated textareas
const populatedTextareas = Array.from(
document.querySelectorAll('.image-container textarea')
).filter(ta => ta.value.trim().length);
if (populatedTextareas.length > 1) {
fullDocumentTextarea.value = populatedTextareas.map(ta => ta.value.trim()).join("\n\n");
fullDocumentSection.style.display = 'block';
} else {
fullDocumentTextarea.value = '';
fullDocumentSection.style.display = 'none';
}
}
function setTextarea(ta, text) {
ta.value = text.trim();
// Set textarea height to fit content
ta.style.height = 'auto';
ta.style.height = (ta.scrollHeight + 5) + 'px';
}
dropzone.addEventListener('dragover', handleDragOver);
dropzone.addEventListener('dragleave', handleDragLeave);
dropzone.addEventListener('drop', handleDrop);
dropzone.addEventListener('click', handleClick);
async function handleDragOver(event) {
event.preventDefault();
if (fileSelectionAllowed) {
dropzone.classList.add('drag-over');
}
}
async function handleDragLeave(event) {
event.preventDefault();
if (fileSelectionAllowed) {
dropzone.classList.remove('drag-over');
}
}
async function handleDrop(event) {
event.preventDefault();
if (fileSelectionAllowed) {
dropzone.classList.remove('drag-over');
const file = event.dataTransfer.files[0];
fileInput.files = event.dataTransfer.files;
processFile(file);
}
}
async function handleClick() {
if (fileSelectionAllowed) {
fileInput.click();
}
}
fileInput.addEventListener('change', (event) => {
const file = event.target.files[0];
processFile(file);
});
async function processFile(file) {
const worker = await Tesseract.createWorker();
fullDocumentTextarea.value = '';
fullDocumentSection.style.display = 'none';
imageContainer.innerHTML = '';
const originalText = dropzone.innerText;
dropzone.innerText = 'Processing file...';
dropzone.classList.add('disabled');
fileSelectionAllowed = false;
if (file.type === 'application/pdf') {
const { numPages, imageIterator } = await convertPDFToImages(file);
let done = 0;
dropzone.innerText = `Processing ${numPages} page${numPages > 1 ? 's' : ''}`;
for await (const { imageURL } of imageIterator) {
const ta = await displayImage(imageURL);
const { text } = await ocrImage(worker, imageURL);
setTextarea(ta, text);
showFullDocument();
done += 1;
dropzone.innerText = `Done ${done} of ${numPages}`;
}
} else {
const imageURL = URL.createObjectURL(file);
const ta = await displayImage(imageURL);
const { text } = await ocrImage(worker, imageURL);
setTextarea(ta, text);
showFullDocument();
}
await worker.terminate();
dropzone.innerText = originalText;
dropzone.classList.remove('disabled');
fileSelectionAllowed = true;
}
async function displayImage(imageURL) {
const imgElement = document.createElement('img');
imgElement.src = imageURL;
imageContainer.appendChild(imgElement);
const altTextarea = document.createElement('textarea');
altTextarea.classList.add('textarea-alt');
altTextarea.placeholder = 'OCRing image...';
imageContainer.appendChild(altTextarea);
return altTextarea;
}
async function convertPDFToImages(file) {
// returns { numPages, imageIterator }
const pdf = await pdfjsLib.getDocument(URL.createObjectURL(file)).promise;
const numPages = pdf.numPages;
async function* images() {
for (let i = 1; i <= numPages; i++) {
try {
const page = await pdf.getPage(i);
const viewport = page.getViewport({ scale: 1 });
const canvas = document.createElement('canvas');
const context = canvas.getContext('2d');
canvas.width = desiredWidth;
canvas.height = (desiredWidth / viewport.width) * viewport.height;
const renderContext = {
canvasContext: context,
viewport: page.getViewport({ scale: desiredWidth / viewport.width }),
};
await page.render(renderContext).promise;
const imageURL = canvas.toDataURL('image/jpeg', 0.8);
yield { imageURL };
} catch (error) {
console.error(`Error rendering page ${i}:`, error);
}
}
}
return {numPages: numPages, imageIterator: images()};
}
async function ocrImage(worker, imageUrl) {
const {
data: { text },
} = await worker.recognize(imageUrl);
return { text };
}
</script>
</body>
</html>