-
Notifications
You must be signed in to change notification settings - Fork 0
/
comprehensive-pdf-parser-setup.sh
executable file
·478 lines (393 loc) · 11.1 KB
/
comprehensive-pdf-parser-setup.sh
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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
#!/bin/bash
# Create virtual environment for Python parsers
python3 -m venv .venv
source .venv/bin/activate
# Install required Python libraries
pip install pypdf pymupdf pdfplumber PyPDF2 pdfminer.six
# Create directories for each parser
mkdir -p pypdf pymupdf pdfjs pdfplumber pdfreader pypdf2 pdfminer pdf-parse-new unpdf
# Create Python files for each parser
cat > pypdf/pypdf_parser.py << EOL
import sys
import json
from pypdf import PdfReader
def extract_text(pdf_path):
reader = PdfReader(pdf_path)
text = ''
for page in reader.pages:
text += page.extract_text() + '\n'
return text.strip()
if __name__ == '__main__':
if len(sys.argv) < 2:
print('Usage: python pypdf_parser.py <pdf_file> [-j]')
sys.exit(1)
pdf_path = sys.argv[1]
json_output = '-j' in sys.argv
text = extract_text(pdf_path)
if json_output:
print(json.dumps({'text': text}))
else:
print(text)
EOL
cat > pymupdf/pymupdf_parser.py << EOL
import sys
import json
import fitz
def extract_text(pdf_path):
doc = fitz.open(pdf_path)
text = ''
for page in doc:
text += page.get_text() + '\n'
return text.strip()
if __name__ == '__main__':
if len(sys.argv) < 2:
print('Usage: python pymupdf_parser.py <pdf_file> [-j]')
sys.exit(1)
pdf_path = sys.argv[1]
json_output = '-j' in sys.argv
text = extract_text(pdf_path)
if json_output:
print(json.dumps({'text': text}))
else:
print(text)
EOL
cat > pdfplumber/pdfplumber_parser.py << EOL
import sys
import json
import pdfplumber
def extract_text(pdf_path):
with pdfplumber.open(pdf_path) as pdf:
text = ''
for page in pdf.pages:
text += page.extract_text() + '\n'
return text.strip()
if __name__ == '__main__':
if len(sys.argv) < 2:
print('Usage: python pdfplumber_parser.py <pdf_file> [-j]')
sys.exit(1)
pdf_path = sys.argv[1]
json_output = '-j' in sys.argv
text = extract_text(pdf_path)
if json_output:
print(json.dumps({'text': text}))
else:
print(text)
EOL
cat > pypdf2/pypdf2_parser.py << EOL
import sys
import json
from PyPDF2 import PdfReader
def extract_text(pdf_path):
reader = PdfReader(pdf_path)
text = ''
for page in reader.pages:
text += page.extract_text() + '\n'
return text.strip()
if __name__ == '__main__':
if len(sys.argv) < 2:
print('Usage: python pypdf2_parser.py <pdf_file> [-j]')
sys.exit(1)
pdf_path = sys.argv[1]
json_output = '-j' in sys.argv
text = extract_text(pdf_path)
if json_output:
print(json.dumps({'text': text}))
else:
print(text)
EOL
cat > pdfminer/pdfminer_parser.py << EOL
import sys
import json
from io import StringIO
from pdfminer.high_level import extract_text_to_fp
from pdfminer.layout import LAParams
def extract_text(pdf_path):
output_string = StringIO()
with open(pdf_path, 'rb') as fin:
extract_text_to_fp(fin, output_string, laparams=LAParams(), output_type='text', codec='utf-8')
return output_string.getvalue().strip()
if __name__ == '__main__':
if len(sys.argv) < 2:
print('Usage: python pdfminer_parser.py <pdf_file> [-j]')
sys.exit(1)
pdf_path = sys.argv[1]
json_output = '-j' in sys.argv
text = extract_text(pdf_path)
if json_output:
print(json.dumps({'text': text}))
else:
print(text)
EOL
# Create requirements.txt for Python libraries
cat > requirements.txt << EOL
pypdf
pymupdf
pdfplumber
PyPDF2
pdfminer.six
EOL
# Set up pdfjs (TypeScript/Node.js implementation using pdfjs-dist)
cd pdfjs
npm init -y
npm install pdfjs-dist @types/node typescript ts-node
npm pkg set type="module" scripts.build="tsc" scripts.start="node --experimental-specifier-resolution=node --loader ts-node/esm src/pdfjs_parser.ts"
cat > tsconfig.json << EOL
{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "node",
"esModuleInterop": true,
"strict": true,
"outDir": "./dist"
},
"include": ["src/**/*"],
"ts-node": {
"esm": true
}
}
EOL
mkdir -p src
cat > src/pdfjs_parser.ts << EOL
import fs from 'fs';
import * as pdfjsLib from 'pdfjs-dist';
async function extractText(pdfPath: string): Promise<string> {
const data = new Uint8Array(fs.readFileSync(pdfPath));
const loadingTask = pdfjsLib.getDocument({ data });
const doc = await loadingTask.promise;
let fullText = '';
for (let i = 1; i <= doc.numPages; i++) {
const page = await doc.getPage(i);
const content = await page.getTextContent();
const strings = content.items.map((item: any) => item.str);
fullText += strings.join(' ') + '\n';
}
return fullText.trim();
}
async function main() {
if (process.argv.length < 3) {
console.log('Usage: npm run start -- <pdf_file> [-j]');
process.exit(1);
}
const pdfPath = process.argv[2];
const jsonOutput = process.argv.includes('-j');
try {
const text = await extractText(pdfPath);
if (jsonOutput) {
console.log(JSON.stringify({ text }));
} else {
console.log(text);
}
} catch (error) {
console.error('Error:', error);
}
}
main();
EOL
cd ..
# Set up pdfreader (TypeScript/Node.js implementation)
cd pdfreader
npm init -y
npm install pdfreader @types/node typescript ts-node
npm pkg set type="module" scripts.build="tsc" scripts.start="node --experimental-specifier-resolution=node --loader ts-node/esm src/pdfreader_parser.ts"
cat > tsconfig.json << EOL
{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "node",
"esModuleInterop": true,
"strict": true,
"outDir": "./dist"
},
"include": ["src/**/*"],
"ts-node": {
"esm": true
}
}
EOL
mkdir -p src
cat > src/pdfreader_parser.ts << EOL
import fs from "fs";
async function importPdfReader() {
const { PdfReader } = await import("pdfreader");
return PdfReader;
}
async function extractText(
pdfPath: string,
options: object = {}
): Promise<string> {
const PdfReader = await importPdfReader();
return new Promise((resolve, reject) => {
let text = "";
// Pass options to PdfReader
new PdfReader(options).parseFileItems(pdfPath, (err, item) => {
if (err) reject(err);
else if (!item) {
resolve(text.trim());
} else if (item.text) {
text += item.text + " ";
}
});
});
}
async function main() {
if (process.argv.length < 3) {
console.log("Usage: npm run start -- <pdf_file> [-j]");
process.exit(1);
}
const pdfPath = process.argv[2];
const jsonOutput = process.argv.includes("-j");
try {
const text = await extractText(pdfPath);
if (jsonOutput) {
console.log(JSON.stringify({ text }));
} else {
console.log(text);
}
} catch (error) {
console.error("Error:", error);
}
}
main();
EOL
cd ..
# Set up pdf-parse-new (TypeScript/Node.js implementation)
cd pdf-parse-new
npm init -y
npm install pdf-parse-new @types/node typescript ts-node
npm pkg set type="module" scripts.build="tsc" scripts.start="node --experimental-specifier-resolution=node --loader ts-node/esm src/pdf_parse_new_parser.ts"
cat > tsconfig.json << EOL
{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "node",
"esModuleInterop": true,
"strict": true,
"outDir": "./dist"
},
"include": ["src/**/*"],
"ts-node": {
"esm": true
}
}
EOL
mkdir -p src
cat > src/pdf_parse_new_parser.ts << EOL
import fs from "fs";
async function importPdfParseNew() {
const pdfParseNew = await import("pdf-parse-new");
return pdfParseNew.default;
}
async function extractText(pdfPath: string): Promise<string> {
const dataBuffer = fs.readFileSync(pdfPath);
const pdfParseNew = await importPdfParseNew();
const data = await pdfParseNew(dataBuffer);
return data.text.trim();
}
async function main() {
if (process.argv.length < 3) {
console.log('Usage: npm run start -- <pdf_file> [-j]');
process.exit(1);
}
const pdfPath = process.argv[2];
const jsonOutput = process.argv.includes('-j');
try {
const text = await extractText(pdfPath);
if (jsonOutput) {
console.log(JSON.stringify({ text }));
} else {
console.log(text);
}
} catch (error) {
console.error('Error:', error);
}
}
main();
EOL
cd ..
# Set up unpdf (TypeScript/Node.js implementation)
cd unpdf
npm init -y
npm install unpdf @types/node typescript ts-node
npm pkg set type="module" scripts.build="tsc" scripts.start="node --experimental-specifier-resolution=node --loader ts-node/esm src/unpdf_parser.ts"
cat > tsconfig.json << EOL
{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "node",
"esModuleInterop": true,
"strict": true,
"outDir": "./dist"
},
"include": ["src/**/*"],
"ts-node": {
"esm": true
}
}
EOL
mkdir -p src
cat > src/unpdf_parser.ts << EOL
import fs from "fs";
import { extractText } from "unpdf";
async function extractPdfText(pdfPath: string): Promise<string> {
const buffer = fs.readFileSync(pdfPath);
const text = await extractText(buffer);
return text.trim();
}
async function main() {
if (process.argv.length < 3) {
console.log('Usage: npm run start -- <pdf_file> [-j]');
process.exit(1);
}
const pdfPath = process.argv[2];
const jsonOutput = process.argv.includes('-j');
try {
const text = await extractPdfText(pdfPath);
if (jsonOutput) {
console.log(JSON.stringify({ text }));
} else {
console.log(text);
}
} catch (error) {
console.error('Error:', error);
}
}
main();
EOL
cd ..
# Create a README file
cat > README.md << EOL
# PDF Parser Comparison
This project compares different PDF parsing libraries for text extraction accuracy, including support for multipage PDFs.
## Libraries included:
1. PyPDF (Python)
2. PyMuPDF (Python)
3. PDF.js (TypeScript/Node.js using pdfjs-dist)
4. pdfplumber (Python)
5. pdfreader (TypeScript/Node.js)
6. PyPDF2 (Python)
7. pdfminer.six (Python)
8. pdf-parse-new (TypeScript/Node.js)
9. unpdf (TypeScript/Node.js)
## Usage:
For Python parsers, run:
python <parser_name>/<parser_name>_parser.py <pdf_file> [-j]
For TypeScript/Node.js parsers, run:
cd <parser_name> && npm run start -- <pdf_file> [-j]
The -j flag outputs the result in JSON format.
Examples:
python pypdf/pypdf_parser.py sample.pdf -j
cd pdfjs && npm run start -- ../sample.pdf -j
## Setup:
1. Ensure you have Python 3.7+ and Node.js 20.15+ installed.
2. For Python parsers:
- Activate the virtual environment: source .venv/bin/activate
- Install dependencies: pip install -r requirements.txt
3. For TypeScript/Node.js parsers: npm install in the respective directories
## Multipage PDFs:
All parsers handle multipage PDFs and concatenate the text from all pages into a single output.
EOL
echo "Setup complete. See README.md for usage instructions."