Skip to content
6 changes: 4 additions & 2 deletions pageindex/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
from .page_classify import PageClassifyClient
from .page_extract import PageExtractClient
from .page_search import PageSearchClient
from .page_split import PageSplitClient
from .types import (ChatConfig, ChatProcessOptions, CloudIndexConfig,
IndexConfig, LocalIndexConfig)

Expand All @@ -20,6 +21,7 @@
__all__ = [
"PageIndexClient", "PageIndexCloudClient", "PageIndexLocalClient",
"PageSearchClient", "PageExtractClient", "PageClassifyClient",
"PageSplitClient",
"PageIndexAPIError",
"IndexConfig", "CloudIndexConfig", "LocalIndexConfig", "ChatConfig",
"ChatProcessOptions", "ChatStream", "MessagesStream", "ChatObject",
Expand All @@ -37,8 +39,8 @@
"flash", "imaging", "integrations", "local_api", "local_chat",
"local_store", "mcp_bridge", "page_classify", "page_extract",
"page_index_classic",
"page_index_md", "page_search", "retry", "tree_optimize", "types",
"utils"}
"page_index_md", "page_search", "page_split", "retry",
"tree_optimize", "types", "utils"}


def __getattr__(name):
Expand Down
82 changes: 82 additions & 0 deletions pageindex/cloud_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -1130,3 +1130,85 @@ def get_classify(self, job_id: str) -> Dict[str, Any]:
f"Failed to get classify job: {response.text}",
status_code=response.status_code)
return response.json()

# ---------- SPLIT ----------

def create_split(
self,
configuration: Dict[str, Any],
doc_id: Optional[str] = None,
file_path: Optional[str] = None,
collection_id: Optional[str] = None,
folder_id: Optional[str] = None,
) -> Dict[str, Any]:
"""
Start a split job on an uploaded document, or on a PDF sent with it,
which is kept as a document.

Args:
configuration (dict): {"types": [{"name", "description",
"identifier_key"}], "rules"}.
doc_id (str, optional): Document ID.
file_path (str, optional): A PDF's path, in place of doc_id.
collection_id (str, optional): The collection a PDF sent is kept in.
folder_id (str, optional): The folder a PDF sent is kept in.

Returns:
dict: The job, pending: {"id", "status", "doc_id", "configuration",
"created_at", "updated_at"}. A PDF stored already whose
document is still processing: {"doc_id", "duplicate": True},
and no job.
"""
data: Dict[str, Any] = {"configuration": json.dumps(configuration)}
if file_path is None:
data["doc_id"] = doc_id
response = self._http.post(
f"{self.BASE_URL}/split/",
headers=self._headers(),
data=data,
timeout=60
)
else:
if collection_id is not None:
data["collection_id"] = collection_id
if folder_id is not None:
data["folder_id"] = folder_id
with open(file_path, "rb") as f:
response = self._http.post(
f"{self.BASE_URL}/split/",
headers=self._headers(),
files={"file": (sanitize_filename(Path(file_path).name), f)},
data=data
)
if response.status_code == 409:
try:
stored = response.json()["detail"]["doc_id"]
except (ValueError, KeyError, TypeError):
stored = None
if stored:
return {"doc_id": stored, "duplicate": True}
if response.status_code != 202:
raise PageIndexAPIError(
f"Failed to start split job: {response.text}",
status_code=response.status_code)
return response.json()

def get_split(self, job_id: str) -> Dict[str, Any]:
"""
Get a split job, with its result once completed.

Returns:
dict: {"id", "status", "doc_id", "configuration", "created_at",
"updated_at"}; completed: "documents" and "usage" too;
failed: "error_message" too.
"""
response = self._http.get(
f"{self.BASE_URL}/split/{_enc(job_id)}/",
headers=self._headers(),
timeout=60
)
if response.status_code != 200:
raise PageIndexAPIError(
f"Failed to get split job: {response.text}",
status_code=response.status_code)
return response.json()
227 changes: 227 additions & 0 deletions pageindex/page_split.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,227 @@
"""Page Split: the documents a PDF bundles, each with its pages and its type
among the types you name."""
import os
import time
from typing import Any, Iterable, Mapping, Optional, Union

from .client import PageIndexClient, _cloud_client
from .errors import PageIndexAPIError
from .page_extract import PageExtractClient

COLLECTION = "Page Split"

Types = Union[Mapping[str, Optional[str]], Iterable[Union[str, Mapping[str, Any]]]]


def _types(types: Types) -> list[dict]:
"""The API's types: [{"name", "description", "identifier_key"}]."""
if isinstance(types, str):
types = [types]
if isinstance(types, Mapping):
if types.keys() & {"name", "description", "identifier_key", "identifier"}:
raise PageIndexAPIError(
'types {"name": ...} could be one type or types named "name", '
'"description", "identifier_key" or "identifier": pass one '
'type in a list, [{"name": ..., "identifier_key": ...}], and a '
'type with such a name as [{"name": "name", "description": ...}].')
return [{"name": name, **({"description": about} if about else {})}
for name, about in types.items()]
return [dict(t) if isinstance(t, Mapping) else {"name": t} for t in types]


class PageSplitClient:
"""
Page Split over your PageIndex cloud documents. Cloud-only.

client = PageSplitClient() # reads PAGEINDEX_API_KEY
job = client.split("bundle.pdf", {
"invoice": "A bill asking for payment",
"receipt": "Proof of a purchase already paid",
})
[(d["start_page"], d["end_page"], d["type"]) for d in job["documents"]]

A PDF given by its path is uploaded to the "Page Split" collection, with
no outline built. The documents are the ones ``PageIndexClient``,
``PageSearchClient``, ``PageExtractClient`` and ``PageClassifyClient`` see
with the same key; ``client.documents`` is that ``PageIndexClient``, for
listing and deleting them.

Args:
api_key (str, optional): Your PageIndex API key. Defaults to the
PAGEINDEX_API_KEY environment variable.
client (PageIndexClient, optional): A cloud ``PageIndexClient`` to
work through, in place of ``api_key``.
"""

def __init__(self, api_key: Optional[str] = None, *,
client: Optional[PageIndexClient] = None):
self.documents = _cloud_client(api_key, client, "PageSplitClient", None)
self._collections: dict[str, str] = {}

# Finds or makes the collection a file is kept in, as Page Extract does.
_collection = PageExtractClient._collection

def split(
self,
document: Union[str, os.PathLike],
types: Optional[Types] = None,
*,
rules: Optional[str] = None,
wait: bool = True,
timeout: float = 3600.0,
collection: Optional[str] = COLLECTION,
) -> dict[str, Any]:
"""
Split a PDF that bundles several documents into those documents.

job = client.split("returns.pdf", [
{"name": "Form 1040", "description": "An individual return"},
{"name": "Schedule K-1", "description": "A partner's share",
"identifier_key": "the partner the K-1 is for"},
], rules="Keep each state's forms with its return.")
job["documents"]

Args:
document (str): A PDF's path: the file is uploaded to
``collection`` with the job, with no outline built, and kept
as a document from then on. Only the split is charged, once
the job completes; a job that fails is not charged, and
leaves a file it uploaded as a failed document, with its name
and file but no pages, until you delete it. Uploading the
same file again uses the stored document. Or the ``doc_id``
of an uploaded document: one still processing is waited for
first, and with ``wait=False`` raises PageIndexAPIError
(HTTP 409). Every page is read.
types (dict | list | str, optional): The types to label the
documents with: {name: description} (a description may be
None), a list of names, one name, or a list of {"name",
"description", "identifier_key"}. "identifier_key" says what
tells two documents of that type apart: two with different
identifiers are split.
Without types the PDF is split and every document's type is
None. 100 at most; the types and ``rules`` hold at most
50,000 characters, all told.
rules (str, optional): How you want your documents split, in
your words.
wait (bool): Return the job once it is completed (default), up to
``timeout`` seconds; raises PageIndexAPIError if it failed or
is not done in time (it goes on running). Read such a job
with ``get_split()``. False returns it pending once it
starts: ``wait_split()`` waits for it later.
timeout (float): Seconds to wait, the document's upload and
processing included. Defaults to 1 hour.
collection (str, optional): Where a file is uploaded: a
collection's name (any case) or ID, "Page Split" by default.
A name none of your collections has makes one. None stores
the document outside any collection.

Returns:
dict: The job: {'id', 'status', 'doc_id', 'configuration',
'created_at', 'updated_at'}. 'status' is "pending", "running",
"completed" or "failed". Completed, it also has 'documents', in
page order, each {'start_page', 'end_page', 'type'} (a type is
None for a document none of the types fits) with its
'identifier' (for a type with an identifier_key; left out when
none is read), and 'usage' ({'pages', 'credits'}); failed,
'error_message'. Splitting costs $0.005 a page.
"""
api = self.documents._api
configuration: dict[str, Any] = {}
if types:
configuration["types"] = _types(types)
if rules:
configuration["rules"] = rules
document = os.fspath(document)
deadline = time.monotonic() + timeout
if os.path.exists(document):
for last in (False, True):
job = self._send(document, collection, configuration)
if "id" in job:
return self._done(job, deadline, timeout) if wait else job
# The file is stored already, and its document still processing.
try:
self.documents._wait_until_ready(
job["doc_id"], deadline - time.monotonic())
break
except PageIndexAPIError as exc:
# It failed or was deleted meanwhile: the file is sent again.
if last or not (
exc.status_code == 404
or self.documents.get_document(
job["doc_id"]).get("status") == "failed"):
raise
document = job["doc_id"]
elif document.lower().endswith(".pdf"):
raise FileNotFoundError(document)
try:
job = api.create_split(configuration, doc_id=document)
except PageIndexAPIError as exc:
if not wait or exc.status_code != 409:
raise
self.documents._wait_until_ready(document, deadline - time.monotonic())
job = api.create_split(configuration, doc_id=document)
return self._done(job, deadline, timeout) if wait else job

def _send(self, file_path: str, collection: Optional[str],
configuration: dict) -> dict:
def send():
return self.documents._api.create_split(
configuration, file_path=file_path,
collection_id=self._collection(collection))

try:
return send()
except PageIndexAPIError as exc:
# The collection found earlier is gone: find or make it again.
if exc.status_code != 404 or not self._collections.pop(collection, None):
raise
return send()

def _done(self, job: dict, deadline: float, timeout: float) -> dict:
import requests
api = self.documents._api
interval = 2.0
poll_failures = 0
while job["status"] in ("pending", "running"):
if time.monotonic() > deadline:
raise PageIndexAPIError(
f"Split job {job['id']} is still {job['status']} after "
f"{int(timeout)}s. It goes on running in the cloud — read "
"it with get_split(job_id).")
time.sleep(interval)
interval = min(interval * 1.5, 15.0)
try:
job = api.get_split(job["id"])
poll_failures = 0
except (PageIndexAPIError, requests.RequestException) as exc:
poll_failures += 1
if poll_failures < 3 and getattr(
exc, "status_code", None) not in (401, 403, 404):
continue
raise PageIndexAPIError(
f"Could not read split job {job['id']}: {exc}. It may "
"still be running in the cloud — read it with "
"get_split(job_id).",
status_code=getattr(exc, "status_code", None)) from exc
if job["status"] != "completed":
raise PageIndexAPIError(
f"Split job {job['id']} {job['status']}"
+ (f": {job['error_message']}" if job.get("error_message") else "."))
return job

def wait_split(self, job_id: str, timeout: float = 3600.0) -> dict[str, Any]:
"""
Wait for a split job, and return it once it is completed: the dict
``split()`` returns. Raises PageIndexAPIError if it failed or is not
done within ``timeout`` seconds (it goes on running).
"""
return self._done(
self.documents._api.get_split(job_id),
time.monotonic() + timeout, timeout)

def get_split(self, job_id: str) -> dict[str, Any]:
"""
Get a split job, with its result once it is completed: the dict
``split()`` returns.
"""
return self.documents._api.get_split(job_id=job_id)
Loading
Loading