> ## Documentation Index
> Fetch the complete documentation index at: https://docs.datalab.to/llms.txt
> Use this file to discover all available pages before exploring further.

# Document Segmentation

> Segment documents into logical sections using the Datalab SDK.

> [!WARNING]
>
> A completed request can return `success=False` and `error` without raising an SDK exception. Check `result.success` before reading the output.
>
> Python SDK 0.5.0 does not download signed regional results automatically. For EU requests, use the [REST polling and download flow](https://docs.datalab.to/docs/recipes/conversion/conversion-api-overview.md#regional-result-downloads).

## Basic Usage

```python theme={null}
import json
from datalab_sdk import DatalabClient, SegmentOptions

client = DatalabClient()

# Define a segmentation schema with section names and descriptions
segmentation_schema = json.dumps({
    "segmentation_strategy": "custom",
    "segments": [
        {"name": "introduction", "description": "Introduction and overview"},
        {"name": "methodology", "description": "Methods and approach"},
        {"name": "results", "description": "Findings and results"},
        {"name": "conclusion", "description": "Summary and conclusions"},
        {"name": "references", "description": "Bibliography and references"}
    ]
})

options = SegmentOptions(segmentation_schema=segmentation_schema)
result = client.segment("research_paper.pdf", options=options)
if not result.success:
    raise RuntimeError(result.error or "Document processing failed")

# Access segmentation results
segments = result.segmentation_results["segments"]
for segment in segments:
    print(f"{segment['name']}: pages {segment['pages']}")
```

## Segment Options

Use `SegmentOptions` to configure segmentation behavior:

| Option | Type | Default | Description |
| - | - | - | - |
| `segmentation_schema` | str | **Required** | JSON-encoded segmentation configuration. Use `segments` with `{name, description}` entries for named sections, or `segmentation_strategy="document_boundary"` for automatic document boundaries. |
| `checkpoint_id` | str | None | Checkpoint ID from a previous `convert()` call |
| `mode` | str | `"fast"` | Parse mode: `"fast"`, `"balanced"`, or `"accurate"`. Only applies when parsing runs. |
| `save_checkpoint` | bool | `False` | Save checkpoint for reuse with subsequent calls |
| `max_pages` | int | None | Maximum number of pages to process |
| `page_range` | str | None | Specific pages to process (e.g., `"0-5,10"`). For spreadsheets, filters by sheet index. |
| `skip_cache` | bool | `False` | Skip cached results, force reprocessing |
| `webhook_url` | str | None | Webhook URL for completion notification |

## Page-Only Segmentation

To find document boundaries without parsing text, set both `segmentation_strategy="document_boundary"` and `granularity="page"` inside `segmentation_schema`. This returns page ranges without Markdown, HTML, or other parsed content. Omitting `granularity` retains parsing and its charge. Use `granularity="block"` for boundaries within a page.

See the [segmentation recipe](https://docs.datalab.to/docs/recipes/document-segmentation/auto-segmentation.md) for complete examples and pricing. These settings belong inside `segmentation_schema`, not as top-level `SegmentOptions` fields.

## Checkpoint Reuse

Use checkpoints to avoid re-parsing a document when running segmentation after conversion. First convert with `save_checkpoint=True`, then segment using the returned `checkpoint_id`:

```python theme={null}
import json
from datalab_sdk import DatalabClient, ConvertOptions, SegmentOptions

client = DatalabClient()

# Step 1: Convert and save a checkpoint
convert_options = ConvertOptions(
    mode="accurate",
    save_checkpoint=True,
)
convert_result = client.convert("report.pdf", options=convert_options)
print(convert_result.markdown)

# Step 2: Segment using the checkpoint (no re-parsing needed)
segmentation_schema = json.dumps({
    "segmentation_strategy": "custom",
    "segments": [
        {"name": "executive_summary", "description": "Executive summary"},
        {"name": "financials", "description": "Financial data and analysis"},
        {"name": "outlook", "description": "Future outlook and projections"},
    ]
})

segment_options = SegmentOptions(
    segmentation_schema=segmentation_schema,
    checkpoint_id=convert_result.checkpoint_id,
)
segment_result = client.segment(options=segment_options)
print(segment_result.segmentation_results)
```

### Automatic Checkpoint Reuse

When you don't pass `checkpoint_id`, `segment()` can reuse a checkpoint from your team's earlier run of the same file with compatible parse settings, so parsing isn't run or billed again. It doesn't with `max_pages` or `skip_cache=True`. The result's `checkpoint_reused` is then `True`. Otherwise it is `None`, not `False`: also when you pass `checkpoint_id` yourself, and on any result from `get_result()`.

## Segmentation Result

The result object contains a `segmentation_results` object with a `segments` list. Each segment has `name`, `pages` (original, 0-indexed page numbers), and `confidence`. Block segmentation also provides `start_block`, `end_block`, and `blocks`. Parsed content is available when parsing ran or a parsed checkpoint was reused.

```python theme={null}
result = client.segment("document.pdf", options=options)

# Read the segments list inside the response object
segments = result.segmentation_results["segments"]
for segment in segments:
    print(f"Section: {segment['name']}")
    print(f"  Pages: {segment['pages']}")

# Parsed content is absent in page-only mode
print(result.success)
print(result.markdown)
print(result.page_count)
print(result.cost_breakdown)
```

## Async Usage

```python theme={null}
import asyncio
import json
from datalab_sdk import AsyncDatalabClient, SegmentOptions

async def segment_document():
    async with AsyncDatalabClient() as client:
        segmentation_schema = json.dumps({
            "segmentation_strategy": "custom",
            "segments": [
                {"name": "introduction", "description": "Introduction"},
                {"name": "body", "description": "Main content"},
                {"name": "conclusion", "description": "Conclusion"},
            ]
        })
        options = SegmentOptions(segmentation_schema=segmentation_schema)
        result = await client.segment("document.pdf", options=options)
        return result.segmentation_results

segments = asyncio.run(segment_document())
print(segments)
```

## Next Steps

> [card] [Segmentation Recipe](https://docs.datalab.to/docs/recipes/document-segmentation/auto-segmentation.md)
>
> Learn more about document segmentation patterns and use cases.

> [card] [Structured Extraction](https://docs.datalab.to/docs/welcome/sdk/extraction.md)
>
> Extract structured data from documents using JSON schemas.

> [card] [Document Conversion](https://docs.datalab.to/docs/welcome/sdk/conversion.md)
>
> Convert documents to Markdown, HTML, JSON, or chunks.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.