Metadata-Version: 2.4
Name: coresdk-extractor
Version: 0.1.0
Summary: Production-grade document extraction to versioned RAG-ready JSON/JSONL
License: MIT
License-File: LICENSE
Keywords: chunking,document,extraction,jsonl,llm,nlp,pdf,rag
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Topic :: Text Processing :: Markup
Classifier: Typing :: Typed
Requires-Python: >=3.10
Requires-Dist: beautifulsoup4>=4.12
Requires-Dist: charset-normalizer>=3
Requires-Dist: ebooklib>=0.18
Requires-Dist: lxml>=5
Requires-Dist: mistletoe>=1.3
Requires-Dist: openpyxl>=3.1
Requires-Dist: pdfplumber>=0.11
Requires-Dist: pikepdf>=8
Requires-Dist: puremagic>=1.28
Requires-Dist: pydantic>=2.0
Requires-Dist: pymupdf4llm>=0.0.17
Requires-Dist: pymupdf>=1.24
Requires-Dist: python-docx>=1.1
Requires-Dist: python-pptx>=0.6
Requires-Dist: requests>=2.32
Requires-Dist: rich>=13
Requires-Dist: tiktoken>=0.7
Requires-Dist: trafilatura>=1.12
Requires-Dist: typer>=0.12
Provides-Extra: audio
Requires-Dist: faster-whisper>=1.0; extra == 'audio'
Requires-Dist: pyannote-audio>=3.1; extra == 'audio'
Requires-Dist: torch>=2.0; extra == 'audio'
Requires-Dist: whisperx>=3.1; extra == 'audio'
Provides-Extra: dev
Requires-Dist: dirty-equals>=0.7; extra == 'dev'
Requires-Dist: inline-snapshot>=0.13; extra == 'dev'
Requires-Dist: mypy>=1.10; extra == 'dev'
Requires-Dist: pytest-cov>=5; extra == 'dev'
Requires-Dist: pytest-regressions>=0.5; extra == 'dev'
Requires-Dist: pytest>=8; extra == 'dev'
Requires-Dist: ruff>=0.4; extra == 'dev'
Requires-Dist: types-beautifulsoup4; extra == 'dev'
Requires-Dist: types-requests; extra == 'dev'
Provides-Extra: full
Requires-Dist: faster-whisper>=1.0; extra == 'full'
Requires-Dist: pillow>=10; extra == 'full'
Requires-Dist: pyannote-audio>=3.1; extra == 'full'
Requires-Dist: surya-ocr>=0.4; extra == 'full'
Requires-Dist: torch>=2.0; extra == 'full'
Requires-Dist: whisperx>=3.1; extra == 'full'
Provides-Extra: ocr
Requires-Dist: pillow>=10; extra == 'ocr'
Requires-Dist: surya-ocr>=0.4; extra == 'ocr'
Provides-Extra: scientific
Description-Content-Type: text/markdown

# extractor

> Production-grade document extraction CLI + Python library.  
> Converts **any file format** into a versioned, schema-stable, RAG-ready JSONL stream.

[![Python 3.10+](https://img.shields.io/badge/python-3.10%2B-blue)](https://python.org)
[![Schema v1.0.0](https://img.shields.io/badge/schema-v1.0.0-green)]()
[![License: MIT](https://img.shields.io/badge/license-MIT-brightgreen)](LICENSE)

---

## Why extractor?

Most RAG pipelines treat documents as bags of text. **extractor** preserves structure:

- Every chunk carries a **full breadcrumb** (`section_path`) so your retriever knows where it came from
- **Tables are atomic** — never split across chunks; emitted in both Markdown and structured JSON
- **Sections drive chunking** — boundaries follow headings, not page numbers or character counts
- **Content-addressed IDs** — stable across re-runs, safe to use as vector store keys
- **Streaming JSONL** — process terabytes without loading files into memory
- **Versioned protocol** — `schema_version` on every record; breaking changes bump the major version

---

## Installation

```bash
pip install coresdk-extractor                      # core (PDF, DOCX, XLSX, PPTX, HTML, Markdown, EPUB, JSON, XML, CSV, LaTeX)
pip install "coresdk-extractor[audio]"             # + audio transcription (faster-whisper + pyannote)
pip install "coresdk-extractor[ocr]"               # + scanned PDF OCR (surya-ocr)
pip install "coresdk-extractor[full]"              # everything
```

**Scientific PDFs** (GROBID): run a GROBID server and set `GROBID_URL=http://localhost:8070`.
Without it, scientific PDFs fall back to pymupdf4llm automatically.

### Verify installation

```bash
extractor info          # lists all supported formats
extractor run README.md # quick smoke test on any local file
```

> **Heavy optional dependencies:** `extractor[audio]` pulls PyTorch (~2 GB). `extractor[ocr]` requires surya-ocr with PyTorch. Install these only when needed.

---

## Quick start

```bash
# Extract a PDF — stream elements to stdout
extractor run paper.pdf

# Extract in RAG-ready chunks mode, write to file
extractor run paper.pdf --mode chunks --out paper.chunks.jsonl

# Extract a whole directory, write each file alongside it
extractor run ./docs/ --mode chunks --out ./out/

# View what was extracted
extractor view paper.chunks.jsonl
extractor view paper.chunks.jsonl --count        # element type breakdown
extractor view paper.chunks.jsonl --types table:simple,code:block

# Inspect a file before extracting
extractor info paper.pdf

# List all parsers and supported formats
extractor info

# Validate output against the schema
extractor validate paper.chunks.jsonl --level invariants

# List all element types
extractor schema
```

---

## Python API

```python
from extractor import extract

# Elements mode — fine-grained semantic units
for el in extract("paper.pdf", mode="elements"):
    print(el.element_type, el.section_path, el.text[:120])

# Chunks mode — pre-committed, RAG-ready chunks
for chunk in extract("paper.pdf", mode="chunks", chunk_size=512):
    print(chunk.id, chunk.token_count, chunk.text[:120])

# Filter to only tables and headings
for el in extract("report.docx", include_types=["table:simple", "structural:section_header"]):
    if el.table:
        print(el.table.structured)  # {"headers": [...], "rows": [[...]]}
```

### Error handling

```python
from extractor import extract, QuarantineError, UnsupportedFormatError, ParserError

try:
    for el in extract("untrusted_file.pdf"):
        print(el.element_type, el.text[:80])
except QuarantineError as e:
    print(f"File rejected by security check: {e}")
except UnsupportedFormatError as e:
    print(f"Format not supported. Run `extractor info` for the full list.")
except ParserError as e:
    print(f"Parser failed: {e}")
```

---

## Output schema

Every record is a JSON object. Key fields:

| Field | Type | Description |
|-------|------|-------------|
| `id` | `string` | Content-addressed ID (`el_` + 16 hex chars) |
| `element_type` | `string` | One of 47 canonical types (see below) |
| `text` | `string` | Plain-text content |
| `section_path` | `string[]` | Heading breadcrumb, e.g. `["Introduction", "Methods"]` |
| `section_path_tier` | `int` | Quality: 1=native, 2=font-heuristic, 3=keyword, 4=positional |
| `sequence_index` | `int` | Document order, 0-based |
| `page` | `int\|null` | Source page (1-based) |
| `schema_version` | `string` | `"1.0.0"` |
| `source_filename` | `string` | Source file name |
| `source_sha256` | `string` | SHA-256 of source file |
| `table` | `object\|null` | `{markdown, structured, has_header_row, row_count, col_count}` |
| `equation` | `object\|null` | `{latex, plain_text, mathml}` |
| `figure` | `object\|null` | `{caption, image_ref, image_sha256, ocr_text}` |
| `transcript` | `object\|null` | `{speaker, start_time_s, end_time_s, word_timestamps}` |
| `admonition` | `object\|null` | `{kind, title}` |

### Element types

```
structural:  title  section_header  subtitle  divider  page_header  page_footer
text:        narrative  abstract  admonition  pull_quote  footnote  caption  sidebar  transcript_segment
table:       simple  complex  continuation
code:        block  cell  inline
list:        item  item_ordered  item_definition
media:       figure  image  audio  video
scientific:  equation_display  equation_inline  citation  reference_entry  theorem  definition  proof
meta:        document_title  author  date  url  email  page_number  extraction_error
form:        field  label  checkbox
composite:   chunk
```

**Atomic types** (never split across chunks): `table:simple`, `table:complex`, `table:continuation`, `media:figure`, `media:image`, `code:block`, `scientific:equation_display`

---

## JSONL envelope format

```jsonl
{"type":"envelope","extractor_version":"0.1.0","source":{...},"run_config":{...},"created_at":"..."}
{"id":"el_a1b2c3d4e5f6a7b8","element_type":"structural:title","text":"Introduction",...}
{"id":"el_...","element_type":"text:narrative","text":"...",...}
...
{"type":"stream_end","status":"complete","total_elements":42,"schema_version":"1.0.0"}
```

A `manifest.json` companion file is written alongside every `--out` file with full stats.

---

## Supported formats

| Format | Library | Notes |
|--------|---------|-------|
| PDF (digital) | pymupdf4llm | Fast, heading-aware |
| PDF (scientific) | GROBID TEI → pymupdf4llm fallback | Equations, citations, references |
| PDF (scanned) | surya-ocr → pymupdf fallback | Layout detection + OCR |
| DOCX | python-docx | Headings, tables, runs, images |
| XLSX | openpyxl | Sheet-per-section, dual-format tables |
| PPTX | python-pptx | Slide titles + body, speaker notes |
| HTML | trafilatura + lxml | Boilerplate removal, GFM alerts |
| Markdown | mistletoe (GFM) | Headings, tables, alerts, code fences |
| EPUB | ebooklib + BS4 | Spine-order chapter extraction |
| LaTeX | pure-regex parser | Sections, equations, tables, figures, bibliography |
| JSON | stdlib | Key-value pairs as narrative |
| XML | lxml | Title/paragraph heuristics |
| CSV | stdlib csv | Entire file as dual-format table |
| Plain text | heuristic | Heading pattern detection |
| Audio (mp3/wav/m4a/flac) | faster-whisper + pyannote | Diarization, word timestamps |

---

## CLI reference

```
extractor run <target> [options]
  --mode            elements | chunks  (default: elements)
  --out             Output file or directory (default: stdout)
  --chunk-size      Max tokens per chunk (default: 512)
  --overlap         Overlap tokens (default: 0)
  --strategy        fast | accurate | ocr
  --include-types   Comma-separated element types to emit
  --exclude-types   Comma-separated element types to suppress
  --tokenizer       tiktoken encoding (default: cl100k_base)
  --quiet           Suppress progress output

extractor view <jsonl-file>
  --max-text        Max chars per element (default: 200)
  --types           Filter to specific element types
  --count           Show element type breakdown

extractor validate <jsonl-file>
  --level           basic | schema | invariants

extractor info [file]
extractor schema [element-type] [--json]
```

---

## Environment variables

All environment variables are **optional**. The library works out of the box without any of them — each one unlocks a specific optional capability.

**PDF (scientific)**

| Variable | Default | Description |
|----------|---------|-------------|
| `GROBID_URL` | `http://localhost:8070` | URL of a running [GROBID](https://grobid.readthedocs.io) server. When set and reachable, scientific PDFs are parsed via GROBID TEI (better equation/citation/reference extraction). Without it, scientific PDFs automatically fall back to the standard digital PDF parser — no errors. |

**Audio transcription** — only relevant if you install `extractor[audio]` and pass audio files (MP3/WAV/M4A)

| Variable | Default | Description |
|----------|---------|-------------|
| `HF_TOKEN` | — | Hugging Face API token. Required only for **speaker diarization** ("who said what"). Without it, you still get a full transcript — just without speaker labels. Get a free token at [huggingface.co/settings/tokens](https://huggingface.co/settings/tokens) and accept the [pyannote.audio](https://huggingface.co/pyannote/speaker-diarization-3.1) model license. |
| `WHISPER_MODEL` | `base` | Whisper model size controlling accuracy vs. speed. `base` (~150 MB) is fast and good for most uses. Use `large-v2` (~3 GB) for production-quality transcription. Options: `tiny` / `base` / `small` / `medium` / `large-v2`. |
| `WHISPER_DEVICE` | auto | Hardware to run Whisper on. Auto-detected: uses NVIDIA GPU (`cuda`), Apple Silicon (`mps`), or falls back to `cpu`. Set explicitly if auto-detection picks the wrong device. |
| `WHISPER_COMPUTE` | auto | Float precision for faster-whisper. `int8` on CPU (faster, less RAM). `float16` on GPU (fastest). `float32` for maximum accuracy. Auto-set based on device. |

---

## Exit codes

| Code | Meaning |
|------|---------|
| 0 | Success |
| 1 | Partial success (some files failed) |
| 2 | Quarantine failure (file rejected) |
| 3 | Unsupported format |
| 4 | Parser crash |
| 5 | Output write error |
| 6 | Configuration error |

---

## Documentation

| Document | Description |
|----------|-------------|
| [Protocol Specification](docs/SPEC.md) | Full schema and protocol spec v1.0.0 |
| [Architecture](docs/architecture.md) | System architecture and design decisions |
| [Gap Analysis](docs/gap-analysis.md) | Known quality gaps and roadmap |
| [Writing a Parser](docs/writing-a-parser.md) | How to add support for a new format |
| [Contributing](CONTRIBUTING.md) | Dev setup, test workflow, PR guidelines |

---

## License

MIT — see [LICENSE](LICENSE).
