Repository navigation
Expand file tree
/
Copy pathdemo.py
More file actions
102 lines (81 loc) · 3.43 KB
/
Copy pathdemo.py
File metadata and controls
102 lines (81 loc) · 3.43 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
"""
OCR in Python with Apryse
==========================
This script shows how to do OCR in Python using the Apryse SDK's OCR module.
It takes a scanned PDF (or an image) as input, runs Apryse OCR to recognize
the text, saves a searchable PDF, and prints the extracted text to the
console so you can see the OCR result immediately.
Apryse OCR module docs: https://docs.apryse.com/core/guides/info/modules#ocr-module
Usage:
python demo.py <path_to_scanned_pdf_or_image>
"""
from apryse_sdk import PDFNet, PDFDoc, SDFDoc, OCRModule, TextExtractor
from dotenv import load_dotenv
import os
import sys
# File types Apryse OCR can run against directly. Anything else (png, jpg,
# tiff, etc.) is treated as an image and converted to a searchable PDF first.
PDF_EXTENSIONS = {".pdf"}
def run_ocr(input_path: str, output_dir: str = "outputs") -> str:
"""
Run Apryse OCR on a scanned PDF or image and return the output PDF path.
- Scanned PDF input: OCRModule.ProcessPDF() adds a searchable text layer
directly on top of the existing scanned pages.
- Image input: OCRModule.ImageToPDF() converts the image into a new,
searchable PDF.
"""
os.makedirs(output_dir, exist_ok=True)
base_name = os.path.splitext(os.path.basename(input_path))[0]
output_path = os.path.join(output_dir, f"{base_name}_ocr-output.pdf")
ext = os.path.splitext(input_path)[1].lower()
if ext in PDF_EXTENSIONS:
# Input is already a (scanned, non-searchable) PDF.
doc = PDFDoc(input_path)
OCRModule.ProcessPDF(doc, None)
else:
# Input is an image; OCR it straight into a new searchable PDF.
doc = PDFDoc()
OCRModule.ImageToPDF(doc, input_path, None)
doc.Save(output_path, SDFDoc.e_linearized)
print(f"Success! Apryse generated searchable PDF saved to {output_path}")
# Show OCR'd text so the result of "OCR in Python with Apryse"
# is visible immediately, not just saved to disk.
extracted_text = TextExtractor()
extracted_text.Begin(doc.GetPage(1))
print("\n--- Extracted text (page 1 preview) ---")
print(extracted_text.GetAsText()[:500])
print("----------------------------------------\n")
doc.Close()
return output_path
def main():
# Ensure a valid path is provided
if len(sys.argv) <2:
print("Usage: python demo.py <path_to_scanned_pdf_or_image>")
return
input_path = sys.argv[1]
if not os.path.isfile(input_path):
print(f"File not found: {input_path}")
return
# Load environment variables
load_dotenv()
server_key = os.getenv("APRYSE_SERVER_KEY")
if not server_key:
print("APRYSE_SERVER_KEY not set. Copy .env.example to .env and add your key.")
return
# Initialize Apryse SDK
PDFNet.Initialize(server_key)
try:
# Point PDFNet at the downloaded Apryse OCR module (see README).
PDFNet.AddResourceSearchPath("./Lib/")
# Verify Apryse OCR module is loaded
if not OCRModule.IsModuleAvailable():
print("OCR module not available. Check your Lib path.")
return
print(f"Running Apryse OCR on {input_path}...")
output_path = run_ocr(input_path)
print(f"Success! Searchable PDF saved to {output_path}")
finally:
# Always release PDFNet resources, even if OCR raises an error.
PDFNet.Terminate()
if __name__ == "__main__":
main()