Certainly! To build a web app that scrapes text from scanned book PDFs (like those from the Internet Archive), you’ll need to:
- Extract images from the PDF (since scanned books are images, not text).
- Run OCR (Optical Character Recognition) on those images to get the text.
- Build a web interface to upload PDFs and display/download the extracted text.
Here’s a simple example using Python (Flask for the web app, PyMuPDF for PDF image extraction, and Tesseract OCR for text extraction):
1. Install Dependencies
pip install flask pytesseract pymupdf pillow
- Tesseract must be installed on your system:
- Windows
sudo apt install tesseract-ocr (Linux)
brew install tesseract (Mac)
2. Flask Web App Code
import os
from flask import Flask, request, render_template_string, send_file
import fitz # PyMuPDF
from PIL import Image
import pytesseract
import io
app = Flask(__name__)
HTML = """
<!doctype html>
<title>PDF Book OCR</title>
<h2>Upload a scanned PDF book</h2>
<form method=post enctype=multipart/form-data>
<input type=file name=pdf>
<input type=submit value=Upload>
</form>
{% if text %}
<h3>Extracted Text:</h3>
<pre style="white-space: pre-wrap;">{{ text }}</pre>
<a href="{{ url_for('download', filename=filename) }}">Download as .txt</a>
{% endif %}
"""
def pdf_to_text(pdf_stream):
doc = fitz.open(stream=pdf_stream, filetype="pdf")
full_text = []
for page_num in range(len(doc)):
page = doc.load_page(page_num)
pix = page.get_pixmap(dpi=300)
img = Image.open(io.BytesIO(pix.tobytes("png")))
text = pytesseract.image_to_string(img)
full_text.append(text)
return "\n".join(full_text)
@app.route('/', methods=['GET', 'POST'])
def index():
text = None
filename = None
if request.method == 'POST':
pdf_file = request.files['pdf']
if pdf_file:
pdf_bytes = pdf_file.read()
text = pdf_to_text(pdf_bytes)
filename = "extracted_text.txt"
with open(filename, "w", encoding="utf-8") as f:
f.write(text)
return render_template_string(HTML, text=text, filename=filename)
@app.route('/download/<filename>')
def download(filename):
return send_file(filename, as_attachment=True)
if __name__ == '__main__':
app.run(debug=True)
3. How it works
- User uploads a PDF.
- Each page is converted to an image.
- Tesseract OCR extracts text from each image.
- The extracted text is displayed and can be downloaded as a
.txt file.
4. Notes & Improvements
- Performance: This is a simple, synchronous example. For large PDFs, consider background jobs (Celery, RQ).
- Security: Uploaded files are not sanitized or deleted after download. For production, use temp files and clean up.
- Accuracy: Tesseract works best with high-quality scans. You can tweak Tesseract configs for better results.
- UI: For a better UI, use HTML templates and progress bars.
Let me know if you want a version with a more advanced UI, or a deployment guide!