Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions pageindex/cloud_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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.
"""
Expand Down
44 changes: 22 additions & 22 deletions pageindex/page_classify.py
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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:
Expand All @@ -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
Expand All @@ -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,
Expand All @@ -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
Expand All @@ -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.
Expand All @@ -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:
Expand Down
12 changes: 6 additions & 6 deletions tests/test_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -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/":
Expand All @@ -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"}

Expand All @@ -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):
Expand All @@ -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"}]


Expand All @@ -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 "
Expand Down
Loading