From 78f68ec844f68f73090f756c981cec03a41bbfe8 Mon Sep 17 00:00:00 2001 From: Ray Date: Mon, 30 Nov 2026 03:33:40 +0800 Subject: [PATCH] feat(classify)!: classify() takes the types to choose among as `types` and answers each document's or page's `type` BREAKING CHANGE: classify(document, classes, ...) is classify(document, types, ...), and a completed job's 'class' (and each page's) is 'type'. The API takes "types" and answers "type" from the same release of the server on, so 0.8.0 and 0.8.1 calls get a 422 once it is deployed. Users name these document types, not classes, and Python cannot write d.class or a model field named class. Page Classify was one day old with almost no users, so it is renamed now. --- pageindex/cloud_api.py | 4 ++-- pageindex/page_classify.py | 44 +++++++++++++++++++------------------- tests/test_client.py | 12 +++++------ 3 files changed, 30 insertions(+), 30 deletions(-) diff --git a/pageindex/cloud_api.py b/pageindex/cloud_api.py index cf4806d04..d88217cf9 100644 --- a/pageindex/cloud_api.py +++ b/pageindex/cloud_api.py @@ -1063,7 +1063,7 @@ def create_classify( it, which is kept as a document. Args: - configuration (dict): {"classes": [{"name", "description"}], + configuration (dict): {"types": [{"name", "description"}], "granularity", "target_pages"}. doc_id (str, optional): Document ID. file_path (str, optional): A PDF's path, in place of doc_id. @@ -1116,7 +1116,7 @@ def get_classify(self, job_id: str) -> Dict[str, Any]: Returns: dict: {"id", "status", "doc_id", "configuration", "created_at", - "updated_at"}; completed: "class" and "confidence" (document) + "updated_at"}; completed: "type" and "confidence" (document) or "pages" (page), "failed_pages" and "usage" too; failed: "error_message" too. """ diff --git a/pageindex/page_classify.py b/pageindex/page_classify.py index 98c5a2e1e..a8c2ac3ec 100644 --- a/pageindex/page_classify.py +++ b/pageindex/page_classify.py @@ -1,4 +1,4 @@ -"""Page Classify: the type of a PDF, or of each of its pages, among the classes +"""Page Classify: the type of a PDF, or of each of its pages, among the types you name.""" import os import time @@ -10,17 +10,17 @@ COLLECTION = "Page Classify" -Classes = Union[Mapping[str, Optional[str]], Iterable[Union[str, Mapping[str, Any]]]] +Types = Union[Mapping[str, Optional[str]], Iterable[Union[str, Mapping[str, Any]]]] -def _classes(classes: Classes) -> list[dict]: - """The API's classes: [{"name", "description"}].""" - if isinstance(classes, str): - classes = [classes] - if isinstance(classes, Mapping): +def _types(types: Types) -> list[dict]: + """The API's types: [{"name", "description"}].""" + if isinstance(types, str): + types = [types] + if isinstance(types, Mapping): return [{"name": name, **({"description": about} if about else {})} - for name, about in classes.items()] - return [dict(c) if isinstance(c, Mapping) else {"name": c} for c in classes] + for name, about in types.items()] + return [dict(t) if isinstance(t, Mapping) else {"name": t} for t in types] class PageClassifyClient: @@ -32,7 +32,7 @@ class PageClassifyClient: "invoice": "A bill asking for payment", "receipt": "Proof of a purchase already paid", }) - job["class"] + job["type"] A PDF given by its path is uploaded to the "Page Classify" collection, with no outline built. The documents are the ones @@ -58,7 +58,7 @@ def __init__(self, api_key: Optional[str] = None, *, def classify( self, document: Union[str, os.PathLike], - classes: Classes, + types: Types, *, granularity: str = "document", pages: Union[str, int, tuple[int, int], None] = None, @@ -67,10 +67,10 @@ def classify( collection: Optional[str] = COLLECTION, ) -> dict[str, Any]: """ - Classify a PDF, or each of its pages, among ``classes``. + Classify a PDF, or each of its pages, among ``types``. - job = client.classify("packet.pdf", classes, granularity="page") - [(p["page"], p["class"]) for p in job["pages"]] + job = client.classify("packet.pdf", types, granularity="page") + [(p["page"], p["type"]) for p in job["pages"]] Args: document (str): A PDF's path: the file is uploaded to @@ -83,13 +83,13 @@ def classify( the ``doc_id`` of an uploaded document: one still processing is waited for first, and with ``wait=False`` raises PageIndexAPIError (HTTP 409). - classes (dict | list | str): The classes, by name: {name: + types (dict | list | str): The types, by name: {name: description} (a description may be None), a list of names, or one name. 1 to 50; names and descriptions hold at most 8,000 characters, all told. - granularity (str): "document" (default): one class for the + granularity (str): "document" (default): one type for the document, from its first 5 pages unless ``pages`` names - others. "page": a class for each page, every page unless + others. "page": a type for each page, every page unless ``pages`` names fewer. pages (str | int | tuple, optional): Read these pages only: "3-9", (3, 9) or 3. @@ -109,16 +109,16 @@ def classify( Returns: dict: The job: {'id', 'status', 'doc_id', 'configuration', 'created_at', 'updated_at'}. 'status' is "pending", "running", - "completed" or "failed". Completed, it also has 'class' and - 'confidence' ("document"), or 'pages', each {'page', 'class', - 'confidence'} ("page"); a class is None for a document or page of - none of the classes. And 'failed_pages' and 'usage' ({'pages', + "completed" or "failed". Completed, it also has 'type' and + 'confidence' ("document"), or 'pages', each {'page', 'type', + 'confidence'} ("page"); a type is None for a document or page of + none of the types. And 'failed_pages' and 'usage' ({'pages', 'credits'}); failed, 'error_message'. Classifying costs $0.001 a page read. """ api = self.documents._api configuration: dict[str, Any] = { - "classes": _classes(classes), "granularity": granularity} + "types": _types(types), "granularity": granularity} if isinstance(pages, tuple): pages = f"{pages[0]}-{pages[1]}" if pages is not None: diff --git a/tests/test_client.py b/tests/test_client.py index 7fc009d7e..dc1c0dcc6 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -2771,7 +2771,7 @@ def test_classify_sends_a_file_with_its_job_and_waits_for_the_result( classifying, sample_pdf): client, calls, answers = classifying done = {"id": "cls_1", "status": "completed", "pages": [ - {"page": 3, "class": "invoice", "confidence": 0.9}]} + {"page": 3, "type": "invoice", "confidence": 0.9}]} later = iter([{"id": "cls_1", "status": "running"}, done]) def to(method, path, kw): if path == "/collections/": @@ -2791,7 +2791,7 @@ def to(method, path, kw): assert calls[1]["files"]["file"][0] == "sample.pdf" sent = calls[1]["data"] assert json.loads(sent.pop("configuration")) == { - "classes": [{"name": "invoice", "description": "A bill"}, {"name": "receipt"}], + "types": [{"name": "invoice", "description": "A bill"}, {"name": "receipt"}], "granularity": "page", "target_pages": "3-9"} assert sent == {"collection_id": "c-9"} @@ -2815,7 +2815,7 @@ def to(method, path, kw): assert [(c["method"], c["path"]) for c in calls][-1] == ("POST", "/classify/") assert calls[-1]["data"]["doc_id"] == "pi-1" assert json.loads(calls[-1]["data"]["configuration"]) == { - "classes": [{"name": "invoice"}], "granularity": "document"} + "types": [{"name": "invoice"}], "granularity": "document"} def test_classify_raises_when_the_job_fails(classifying): @@ -2830,13 +2830,13 @@ def test_classify_raises_when_the_job_fails(classifying): assert calls[0]["data"]["doc_id"] == "pi-1" -def test_classify_takes_one_name_as_one_class(classifying): +def test_classify_takes_one_name_as_one_type(classifying): client, calls, answers = classifying answers.to = lambda method, path, kw: ( 202, {"id": "cls_1", "status": "pending", "doc_id": "pi-1"}) client.classify("pi-1", "email", wait=False) - assert json.loads(calls[0]["data"]["configuration"])["classes"] == [ + assert json.loads(calls[0]["data"]["configuration"])["types"] == [ {"name": "email"}] @@ -2845,7 +2845,7 @@ def test_classify_raises_when_pages_could_not_be_read(classifying): answers.to = lambda method, path, kw: ( (202, {"id": "cls_1", "status": "pending", "doc_id": "pi-1"}) if method == "POST" else - {"id": "cls_1", "status": "completed", "class": "invoice", + {"id": "cls_1", "status": "completed", "type": "invoice", "confidence": 0.95, "failed_pages": [1, 2]}) with pytest.raises(PageIndexAPIError, match="cls_1 has pages it could not "