Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
The diff you're trying to view is too large. We only load the first 3000 changed files.
24 changes: 24 additions & 0 deletions .github/workflows/validate.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
name: Validate

on:
push:
branches: ["main", "codex/**"]
pull_request:

permissions:
contents: read

jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: "3.11"
cache: pip
- run: sudo apt-get update && sudo apt-get install -y tesseract-ocr
- run: python -m pip install --upgrade pip
- run: python -m pip install -r requirements-dev.txt
- run: ruff check main.py tests
- run: pytest -q
10 changes: 10 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
.venv/
venv/
__pycache__/
*.py[cod]
.pytest_cache/
.ruff_cache/
build/
dist/
*.egg-info/
output/
141 changes: 137 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,139 @@
# HandwritingConverter
Converts Handwriting to Printable PDF

07/27/2025
I noticed that it's more productive and easier for me to write things down despite the ever-increasing integration of technology in our day-to-day lives. Instead of fearing it, I decided it would be better to utilize it to improve my productivity.
I am building this project to convert my handwriting (from an image) to a printable document for my new portable printer.
Turn photos of handwritten notes into searchable text and a printable PDF.

I built this because writing by hand is often the fastest way for me to think, but paper notes are difficult to search, revise, and print with my portable printer. HandwritingConverter connects those two workflows without pretending that handwriting OCR is perfect.

> **Status:** working beta. The full local conversion pipeline is implemented and covered by automated tests. Recognition quality still depends heavily on handwriting, lighting, camera angle, and the installed Tesseract language data.

## What it does

- accepts one or more JPG, PNG, TIFF, or other OpenCV-readable images
- preserves the image order as PDF page order
- resizes, denoises, increases contrast, and binarizes each page
- runs local Tesseract OCR without uploading notes to a cloud service
- writes a UTF-8 text transcription and a printable multipage PDF
- supports alternate Tesseract languages and page-segmentation modes
- can save processed images for recognition troubleshooting
- reports missing inputs and missing OCR installations clearly

## Demo

A real before/after screenshot is still needed. The repository includes sample images in `Input/` for local testing; they are not presented as accuracy benchmarks.

## Technology

- Python 3.11+
- OpenCV for image preparation
- Tesseract and pytesseract for OCR
- ReportLab for PDF generation
- pytest and Ruff for validation
- GitHub Actions for continuous integration

## Architecture

```text
handwriting image(s)
|
v
resize -> denoise -> contrast enhancement -> adaptive threshold
|
v
local Tesseract OCR
|
+----> UTF-8 transcription
|
+----> printable multipage PDF
```

## Installation

Tesseract is a system dependency and must be installed separately.

1. Install Python 3.11 or newer.
2. Install [Tesseract OCR](https://github.com/tesseract-ocr/tesseract).
3. Create and activate a virtual environment.
4. Install the project dependencies.

### Windows

```powershell
py -3.11 -m venv .venv
.\.venv\Scripts\Activate.ps1
python -m pip install -r requirements.txt
```

If Tesseract is not on `PATH`, pass its executable explicitly:

```powershell
python main.py Input\test.jpg --tesseract "C:\Program Files\Tesseract-OCR\tesseract.exe"
```

### macOS or Linux

```bash
python3 -m venv .venv
source .venv/bin/activate
python -m pip install -r requirements.txt
```

Install Tesseract through your system package manager—for example, `brew install tesseract` on macOS or `sudo apt install tesseract-ocr` on Debian/Ubuntu.

## Usage

Convert a single page:

```bash
python main.py Input/test.jpg
```

Convert several pages in reading order:

```bash
python main.py page-1.jpg page-2.jpg page-3.jpg --output output/class-notes --title "Class notes"
```

This creates:

- `output/class-notes.txt`
- `output/class-notes.pdf`

Save the processed images when tuning recognition:

```bash
python main.py Input/test.jpg --debug-images --psm 6
```

Run `python main.py --help` for every option. Additional OCR languages require the corresponding Tesseract language package and can be selected with `--language`.

## Development

```bash
python -m pip install -r requirements-dev.txt
ruff check main.py tests
pytest -q
```

The tests isolate OCR itself so they remain deterministic, while still exercising preprocessing, multipage result handling, text output, and real PDF creation.

## Privacy

Images and recognized text stay on the local computer. This project does not send notes to an external OCR API.

## Known limitations

- Tesseract was designed primarily for printed text; highly cursive handwriting can produce poor results.
- Page rotation and perspective correction are not automatic yet.
- Text layout is intentionally simple and does not reproduce drawings or the exact page geometry.
- The committed sample photos may not represent every camera or handwriting style.

## Roadmap

- add automatic orientation and perspective correction
- compare local handwriting-focused OCR backends using the same sample set
- add a small desktop interface with page previews and editable text
- add documented before/after examples after manual accuracy review

## License and authorship

Created by [SimpleCaci](https://github.com/SimpleCaci) and released under the [MIT License](LICENSE).
Binary file removed __pycache__/debugging.cpython-311.pyc
Binary file not shown.
Binary file removed __pycache__/imageLoader.cpython-311.pyc
Binary file not shown.
Binary file removed __pycache__/preprocessing.cpython-311.pyc
Binary file not shown.
Binary file removed __pycache__/textExtractor.cpython-311.pyc
Binary file not shown.
7 changes: 0 additions & 7 deletions debugging.py

This file was deleted.

25 changes: 0 additions & 25 deletions imageLoader.py

This file was deleted.

170 changes: 139 additions & 31 deletions main.py
Original file line number Diff line number Diff line change
@@ -1,43 +1,151 @@
# main.py
import imageLoader, preprocessing, textExtractor # local files
import debugging
"""Convert photographed handwriting into searchable text and a printable PDF."""

from __future__ import annotations

import argparse
import shutil
from dataclasses import dataclass
from pathlib import Path
from typing import Iterable

import numpy as np
import cv2
import pytesseract
from reportlab.lib.pagesizes import letter
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.lib.units import inch
from reportlab.platypus import PageBreak, Paragraph, SimpleDocTemplate, Spacer


@dataclass(frozen=True)
class ConversionResult:
source: Path
text: str
processed_image: Path | None = None


def preprocess_image(path: Path, max_width: int = 2200):
"""Load, deskew-friendly enhance, and binarize a handwriting image."""
image = cv2.imread(str(path), cv2.IMREAD_GRAYSCALE)
if image is None:
raise ValueError(f"Unsupported or unreadable image: {path}")

if image.shape[1] > max_width:
scale = max_width / image.shape[1]
image = cv2.resize(image, None, fx=scale, fy=scale, interpolation=cv2.INTER_AREA)

image = cv2.fastNlMeansDenoising(image, None, 12, 7, 21)
image = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8)).apply(image)
return cv2.adaptiveThreshold(
image, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 31, 15
)


def verify_tesseract(command: str | None = None) -> None:
if command:
pytesseract.pytesseract.tesseract_cmd = command
executable = pytesseract.pytesseract.tesseract_cmd
if not shutil.which(executable) and not Path(executable).exists():
raise RuntimeError(
"Tesseract OCR was not found. Install Tesseract or pass --tesseract "
"with the executable path."
)
try:
pytesseract.get_tesseract_version()
except pytesseract.TesseractNotFoundError as exc:
raise RuntimeError("Tesseract OCR is installed but could not be started.") from exc


def convert_images(
inputs: Iterable[Path],
*,
language: str = "eng",
page_segmentation: int = 6,
debug_dir: Path | None = None,
) -> list[ConversionResult]:
results: list[ConversionResult] = []
config = f"--oem 3 --psm {page_segmentation}"

for index, source in enumerate(inputs, start=1):
if not source.is_file():
raise FileNotFoundError(f"Input image does not exist: {source}")
processed = preprocess_image(source)
text = pytesseract.image_to_string(processed, lang=language, config=config).strip()

debug_path = None
if debug_dir:
debug_dir.mkdir(parents=True, exist_ok=True)
debug_path = debug_dir / f"{index:02d}-{source.stem}-processed.png"
cv2.imwrite(str(debug_path), processed)

results.append(ConversionResult(source=source, text=text, processed_image=debug_path))
return results


def write_text(results: list[ConversionResult], output: Path) -> None:
output.parent.mkdir(parents=True, exist_ok=True)
sections = [f"# {item.source.name}\n\n{item.text or '[No text detected]'}" for item in results]
output.write_text("\n\n".join(sections) + "\n", encoding="utf-8")

pytesseract.pytesseract.tesseract_cmd = r"C:\Program Files\Tesseract-OCR\tesseract.exe"

image = imageLoader.loadImage("./Input/test3.jpg")
def write_pdf(results: list[ConversionResult], output: Path, title: str) -> None:
output.parent.mkdir(parents=True, exist_ok=True)
styles = getSampleStyleSheet()
story = [Paragraph(title, styles["Title"]), Spacer(1, 0.25 * inch)]
for index, item in enumerate(results):
story.extend(
[
Paragraph(item.source.name, styles["Heading2"]),
Paragraph(
(item.text or "[No text detected]").replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;").replace("\n", "<br/>"),
styles["BodyText"],
),
]
)
if index < len(results) - 1:
story.append(PageBreak())
SimpleDocTemplate(
str(output), pagesize=letter, title=title, author="SimpleCaci",
rightMargin=0.65 * inch, leftMargin=0.65 * inch,
topMargin=0.65 * inch, bottomMargin=0.65 * inch,
).build(story)

# Optional resize for huge images
max_width = 1200
if image.shape[1] > max_width:
scale_ratio = max_width / image.shape[1]
image = cv2.resize(image, None, fx=scale_ratio, fy=scale_ratio)

processed = preprocessing.preprocess(image)
def build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(
description="Turn one or more handwriting photos into text and a printable PDF."
)
parser.add_argument("inputs", nargs="+", type=Path, help="Image files in reading order")
parser.add_argument("-o", "--output", type=Path, default=Path("output/handwriting"))
parser.add_argument("--title", default="Handwriting transcription")
parser.add_argument("--language", default="eng", help="Installed Tesseract language code")
parser.add_argument("--psm", type=int, default=6, choices=range(0, 14))
parser.add_argument("--tesseract", help="Path to the Tesseract executable")
parser.add_argument("--debug-images", action="store_true")
return parser

# Show processed image
cv2.imshow("Processed", processed)
cv2.waitKey(0)
cv2.destroyAllWindows()

# Extract and print text
text = textExtractor.extract_text(processed)
print("Extracted Text:\n", text)
def main(argv: list[str] | None = None) -> int:
args = build_parser().parse_args(argv)
try:
verify_tesseract(args.tesseract)
results = convert_images(
args.inputs,
language=args.language,
page_segmentation=args.psm,
debug_dir=args.output.parent / "debug" if args.debug_images else None,
)
write_text(results, args.output.with_suffix(".txt"))
write_pdf(results, args.output.with_suffix(".pdf"), args.title)
except (FileNotFoundError, RuntimeError, ValueError) as exc:
print(f"error: {exc}")
return 1

# Draw text boxes
results = textExtractor.extract_text_with_boxes(processed)
image_with_boxes = cv2.cvtColor(processed, cv2.COLOR_GRAY2BGR)
detected = sum(bool(item.text) for item in results)
print(f"Converted {len(results)} page(s); detected text on {detected}.")
print(f"Text: {args.output.with_suffix('.txt')}")
print(f"PDF: {args.output.with_suffix('.pdf')}")
return 0

for item in results:
x, y, w, h = item["box"]
conf = item["conf"]
cv2.rectangle(image_with_boxes, (x, y), (x + w, y + h), (0, 255, 0), 2)
cv2.putText(image_with_boxes, f'{conf}', (x, y - 5),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 0, 0), 1)

cv2.imshow("Detected Text Boxes", image_with_boxes)
cv2.waitKey(0)
cv2.destroyAllWindows()
if __name__ == "__main__":
raise SystemExit(main())
Loading
Loading