Metadata-Version: 2.4
Name: pdfall
Version: 0.1.0
Summary: Reliable PDF text extraction with PyMuPDF and configurable OCR engines (Tesseract/PaddleOCR).
Author: pdfall contributors
Requires-Python: >=3.10
Description-Content-Type: text/markdown
Requires-Dist: PyMuPDF>=1.24
Requires-Dist: pillow>=10.0
Requires-Dist: numpy>=1.24
Requires-Dist: typer>=0.12
Requires-Dist: rich>=13.7
Provides-Extra: dev
Requires-Dist: pytest>=8.0; extra == "dev"
Provides-Extra: tesseract
Requires-Dist: pytesseract>=0.3.10; extra == "tesseract"
Provides-Extra: paddle
Requires-Dist: paddlepaddle<3.3,>=3.2; extra == "paddle"
Requires-Dist: paddleocr<3.5,>=3.4; extra == "paddle"
Requires-Dist: paddlex<3.5,>=3.4; extra == "paddle"
Requires-Dist: protobuf<7,>=5; extra == "paddle"
Requires-Dist: PyYAML>=6.0; extra == "paddle"
Requires-Dist: ruamel.yaml>=0.18; extra == "paddle"
Provides-Extra: all
Requires-Dist: pdfall[paddle,tesseract]; extra == "all"

# pdfall

## Acesso Rapido | Quick Access

- Idioma: [Portugues](#portugues) | [English](#english)
- Inicio rapido:
  - [Uso rapido (PT)](#uso-rapido-python)
  - [Quick Start (EN)](#quick-start-python)
- CLI:
  - [CLI (PT)](#cli)
  - [CLI (EN)](#cli-en)
- Instalacao:
  - [Instalacao e extras (PT)](#instalacao)
  - [Installation and extras (EN)](#installation)

---

## Portugues

`pdfall` é uma biblioteca Python para extração de texto de PDFs com estratégia híbrida e foco em robustez:

- extração de texto nativo com `PyMuPDF`
- OCR em imagens incorporadas
- fallback de OCR de página inteira quando necessário

O objetivo é entregar texto útil em PDFs reais (inclusive scans), sem obrigar cada projeto a montar sua própria pipeline de OCR.

## Principais recursos

- Pipeline híbrida: texto nativo + OCR.
- Seleção de engine OCR por parâmetro (`tesseract` ou `paddle`).
- Default seguro para OCR em CPU: `tesseract`.
- Fallback inteligente para página inteira em conteúdo fraco ou falha de OCR em imagem.
- Preservação de ordem de leitura por página (`ordered_content`).
- CLI pronta para uso (`pdfall-extract`).

## Instalação

Instalação base do pacote:

```bash
pip install .
```

Ambiente sem isolamento:

```bash
pip install --no-build-isolation .
```

### Extras de OCR

Instalar suporte ao Tesseract (recomendado para o default):

```bash
pip install ".[tesseract]"
```

Instalar suporte ao PaddleOCR:

```bash
pip install ".[paddle]"
```

Instalar todos os engines:

```bash
pip install ".[all]"
```

## Dependências de sistema (Tesseract)

`pytesseract` é apenas o wrapper Python. O binário `tesseract` precisa estar disponível no sistema.

- Ubuntu/Debian:

```bash
sudo apt install tesseract-ocr tesseract-ocr-por
```

- macOS (Homebrew):

```bash
brew install tesseract tesseract-lang
```

- Windows (Chocolatey):

```bash
choco install tesseract
```

## Uso rápido (Python)

```python
from pdfall import extract_pdf_text

result = extract_pdf_text(
    pdf_path="arquivo.pdf",
    ocr_engine="tesseract",   # default
    ocr_language="pt",
)

print(result.full_text)
```

Usando PaddleOCR:

```python
result = extract_pdf_text(
    pdf_path="arquivo.pdf",
    ocr_engine="paddle",
    ocr_language="pt",
)
```

## API principal

`extract_pdf_text(...)` retorna `PDFTextResult` com:

- `pages`: lista de `PageTextResult`
- `full_text`: texto final do documento

Cada `PageTextResult` contém:

- `page_number`
- `native_text`
- `image_texts`
- `full_page_ocr_text`
- `ordered_content`
- `combined_text`

### Parâmetros mais importantes

- `pdf_path`: caminho do PDF.
- `ocr_engine`: `tesseract` (default) ou `paddle`.
- `ocr_language`: idioma do OCR (`pt`, `en`, `es` etc.).
- `ocr_on_images`: habilita OCR em imagens incorporadas.
- `fallback_full_page_ocr`: habilita OCR da página inteira quando necessário.
- `force_full_page_ocr`: ignora heurística e sempre tenta OCR full-page.
- `image_ocr_workers`: workers para OCR de imagem (default `1` por estabilidade).
- `min_embedded_image_area`: ignora imagens pequenas.
- `max_image_side`: default `4000`.
- `max_image_pixels`: default `8_000_000`.

## Comportamento de fallback

O `pdfall` tenta evitar resultados vazios em scans:

- detecta quando texto nativo não é significativo
- considera conteúdo de baixa informação
- detecta falha real de OCR de imagem (decode/extração/execução)
- quando necessário, dispara OCR de página inteira

Na prática, isso reduz casos de saída com apenas rodapé, assinatura digital ou poucas palavras.

## CLI

Extração com engine default (`tesseract`):

```bash
pdfall-extract "arquivo.pdf" --lang pt --ocr-engine tesseract -o saida.txt
```

Extração com PaddleOCR:

```bash
pdfall-extract "arquivo.pdf" --lang pt --ocr-engine paddle -o saida.txt
```

Parâmetros úteis:

- `--workers` (default `1`)
- `--min-image-area` (default `4096`)
- `--max-image-side` (default `4000`)
- `--max-image-pixels` (default `8000000`)

## Observações sobre idiomas

- Com Tesseract, códigos curtos são mapeados automaticamente:
  - `pt -> por`
  - `en -> eng`
  - `es -> spa`
- Com PaddleOCR, os códigos seguem o suporte da versão instalada.

## Tratamento de erros

- Se o wrapper Python do Tesseract não estiver instalado, uma exceção clara é retornada.
- Se o binário Tesseract não estiver no `PATH`, a mensagem indica a instalação do binário.
- Se um engine OCR inválido for informado, `extract_pdf_text` retorna `ValueError`.

## Teste de regressão

No repositório existe um script para validação em PDFs com muito conteúdo em imagem:

```bash
python testes.py
```

Com diretório customizado de materiais:

```bash
PDFALL_TEST_MATERIALS_DIR="/caminho/para/material" python testes.py
```

---

## English

`pdfall` is a Python library for PDF text extraction with a reliability-first hybrid strategy:

- native text extraction with `PyMuPDF`
- OCR on embedded images
- full-page OCR fallback when needed

The goal is to provide useful text output for real-world PDFs (including scans), without requiring each project to build its own OCR pipeline.

## Key Features

- Hybrid pipeline: native text + OCR.
- OCR engine selection via parameter (`tesseract` or `paddle`).
- Safe CPU default: `tesseract`.
- Smart full-page fallback for weak content or image OCR failures.
- Page-level reading order preservation (`ordered_content`).
- Ready-to-use CLI (`pdfall-extract`).

## Installation

Base package installation:

```bash
pip install .
```

No-isolation environment:

```bash
pip install --no-build-isolation .
```

### OCR Extras

Install Tesseract support (recommended default):

```bash
pip install ".[tesseract]"
```

Install PaddleOCR support:

```bash
pip install ".[paddle]"
```

Install all engines:

```bash
pip install ".[all]"
```

## System Dependencies (Tesseract)

`pytesseract` is only the Python wrapper. The `tesseract` binary must be available on your system.

- Ubuntu/Debian:

```bash
sudo apt install tesseract-ocr tesseract-ocr-por
```

- macOS (Homebrew):

```bash
brew install tesseract tesseract-lang
```

- Windows (Chocolatey):

```bash
choco install tesseract
```

## Quick Start (Python)

```python
from pdfall import extract_pdf_text

result = extract_pdf_text(
    pdf_path="file.pdf",
    ocr_engine="tesseract",   # default
    ocr_language="pt",
)

print(result.full_text)
```

Using PaddleOCR:

```python
result = extract_pdf_text(
    pdf_path="file.pdf",
    ocr_engine="paddle",
    ocr_language="pt",
)
```

## Main API

`extract_pdf_text(...)` returns `PDFTextResult` with:

- `pages`: list of `PageTextResult`
- `full_text`: final document text

Each `PageTextResult` contains:

- `page_number`
- `native_text`
- `image_texts`
- `full_page_ocr_text`
- `ordered_content`
- `combined_text`

### Most Important Parameters

- `pdf_path`: input PDF path.
- `ocr_engine`: `tesseract` (default) or `paddle`.
- `ocr_language`: OCR language (`pt`, `en`, `es`, etc.).
- `ocr_on_images`: enables OCR for embedded images.
- `fallback_full_page_ocr`: enables full-page OCR when needed.
- `force_full_page_ocr`: bypasses heuristics and always tries full-page OCR.
- `image_ocr_workers`: workers for image OCR (default `1` for stability).
- `min_embedded_image_area`: ignores tiny embedded images.
- `max_image_side`: default `4000`.
- `max_image_pixels`: default `8_000_000`.

## Fallback Behavior

`pdfall` is designed to reduce empty OCR output on scanned PDFs:

- detects when native text is not meaningful
- considers low-information OCR output
- detects real image OCR failures (decode/extraction/execution)
- triggers full-page OCR when needed

In practice, this reduces outputs containing only footers, signatures, or a few noisy words.

## CLI (EN)

Extraction with default engine (`tesseract`):

```bash
pdfall-extract "file.pdf" --lang pt --ocr-engine tesseract -o output.txt
```

Extraction with PaddleOCR:

```bash
pdfall-extract "file.pdf" --lang pt --ocr-engine paddle -o output.txt
```

Useful CLI parameters:

- `--workers` (default `1`)
- `--min-image-area` (default `4096`)
- `--max-image-side` (default `4000`)
- `--max-image-pixels` (default `8000000`)

## Language Notes

- With Tesseract, short language codes are mapped automatically:
  - `pt -> por`
  - `en -> eng`
  - `es -> spa`
- With PaddleOCR, language support depends on the installed version.

## Error Handling

- If the Tesseract Python wrapper is missing, a clear exception is raised.
- If the Tesseract binary is not in `PATH`, the error message explains what to install.
- If an invalid OCR engine is provided, `extract_pdf_text` raises `ValueError`.

## Regression Test

The repository includes a script to validate image-heavy PDFs:

```bash
python testes.py
```

With custom material directory:

```bash
PDFALL_TEST_MATERIALS_DIR="/path/to/material" python testes.py
```
