hwp-parser 0.1.0
HWP (Korean word processor) document parser with table extraction, OCR support, and quality gates
Requires Python: >=3.9
Keywords: document, hancom, hangul, hwp, korean, ocr, parser, table

# HWP Parser

Korean Word Processor (HWP/한글) document parser with table extraction, OCR support, and quality gates.

[![PyPI version](https://badge.fury.io/py/hwp-parser.svg)](https://badge.fury.io/py/hwp-parser)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

## Features

- **HWP/HWPX Support** - Parse both legacy HWP and modern HWPX formats
- **Encryption Detection** - Detect and report encrypted files
- **Table Extraction** - Extract structured tables with quality metrics
- **OCR Integration** - Optional PaddleOCR for image-based text extraction
- **Quality Gates** - Automatic table quality assessment (fill rate, reliability)
- **RAG-Ready** - Convert tables to searchable sentence format

## Installation

```bash
# Basic installation
pip install hwp-parser

# With OCR support (Korean)
pip install hwp-parser[ocr]

# With OLE inspection for encryption detection
pip install hwp-parser[ole]

# Full installation
pip install hwp-parser[full]
```

## Quick Start

### Python API

```python
from hwp_parser import parse_hwp, parse_hwp_to_yaml

# Parse to dataclass
doc = parse_hwp("document.hwp")
print(f"Paragraphs: {len(doc.content.paragraphs)}")
print(f"Tables: {len(doc.tables)}")

# Parse to YAML string
yaml_str = parse_hwp_to_yaml("document.hwp")
print(yaml_str)
```

### CLI

```bash
# Parse to YAML (stdout)
hwp-parser document.hwp

# Parse to file
hwp-parser document.hwp -o output.yaml

# Parse to JSON
hwp-parser document.hwp --json

# Disable OCR
hwp-parser document.hwp --no-ocr
```

## Output Format

```yaml
document:
  source_path: /path/to/document.hwp
  format: hwp
  encrypted: false
  parser: hwp-parser
  page_count: 5
  file_size: 102400

content:
  paragraphs:
    - "First paragraph text..."
    - "Second paragraph text..."

tables:
  - table_id: table_0
    page: 1
    shape:
      rows: 3
      cols: 4
    quality:
      passed: true
      action: index
      fill_rate: 0.9167
      avg_reliability: 0.8500
      low_conf_ratio: 0.0833
      header_ok: true
    cells:
      - row: 0
        col: 0
        text: "Header 1"
        reliability: 0.9

assets:
  images:
    - image_id: img_abc123_000
      page: 1
      ocr_text: "OCR extracted text..."
```

## Quality Gates

Tables are evaluated on quality metrics:

| Metric | Threshold | Description |
|--------|-----------|-------------|
| `fill_rate` | ≥ 0.60 | Percentage of cells with content |
| `avg_reliability` | ≥ 0.70 | Average cell reliability score |
| `low_conf_ratio` | ≤ 0.25 | Percentage of low-confidence cells |
| `header_ok` | true | First row has valid headers |

- **Passed** → `action: "index"` (ready for RAG)
- **Failed** → `action: "reprocess"` (needs review)

## RAG Integration

Convert tables to searchable sentences:

```python
from hwp_parser import parse_hwp, build_rag_chunks

doc = parse_hwp("document.hwp")
chunks = build_rag_chunks(doc)

for chunk in chunks:
    print(chunk["text"])
    # "보험상품: 건강보험 | 보장기간: 10년 | 납입기간: 5년"
```

## API Reference

### HWPParser

```python
from hwp_parser import HWPParser

parser = HWPParser(
    ocr_enabled=True,        # Enable OCR for images
    min_fill_rate=0.60,      # Quality gate threshold
    min_avg_rel=0.70,        # Quality gate threshold
    max_low_conf_ratio=0.25  # Quality gate threshold
)

# Parse to dataclass
doc = parser.parse("document.hwp")

# Parse to dict
data = parser.parse_to_dict("document.hwp")
```

### Convenience Functions

```python
from hwp_parser import (
    parse_hwp,           # Parse to ParsedDocumentYAML
    parse_hwp_to_yaml,   # Parse to YAML string
    dump_yaml,           # Dict to YAML string
    probe_hwp_encryption # Check if file is encrypted
)
```

### Data Classes

```python
from hwp_parser import (
    ParsedDocumentYAML,  # Complete document
    DocumentMeta,        # Metadata
    DocumentContent,     # Paragraphs
    TableYAML,          # Table structure
    TableCell,          # Cell with text/OCR
    TableQuality,       # Quality metrics
    ImageAsset,         # Image with OCR
)
```

## Dependencies

| Package | License | Required |
|---------|---------|----------|
| hwp2yaml | MIT | Yes |
| PyYAML | MIT | Yes |
| Pillow | HPND | Yes |
| PaddleOCR | Apache-2.0 | Optional |
| olefile | BSD | Optional |

## License

MIT License - see [LICENSE](LICENSE)

## Contributing

Contributions welcome! Please open an issue or PR.

## Related Projects

- [hwp2yaml](https://github.com/dyarchy/hwp2yaml) - Low-level HWP extraction
- [pyhwp](https://github.com/mete0r/pyhwp) - Alternative HWP parser