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
18 changes: 10 additions & 8 deletions pageindex/agent_tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -1813,8 +1813,8 @@ def doc_targeting_block(client, doc_id) -> Optional[str]:
try:
details.append(client.get_document(one_id))
except PageIndexAPIError as exc:
# Batch only a definite not-found/denied (local raises carry no
# status); a cloud transport failure (429/5xx) propagates raw.
# Batch only a definite not-found/denied, or a raise that carries
# no status; a cloud transport failure (429/5xx) propagates raw.
if exc.status_code not in (None, 403, 404):
raise
missing.append(str(one_id))
Expand All @@ -1837,12 +1837,13 @@ def doc_targeting_block(client, doc_id) -> Optional[str]:
)


def folder_targeting_block(client, folder_id) -> Optional[str]:
def folder_targeting_block(client, folder_id, caller="folder_id") -> Optional[str]:
"""The folder_id targeting text, rendered as the cloud's managed chat
renders its own: the folder's name and metadata and the directive to
discover its documents there. None for no folder — None, "", and
"root", the library itself, which the managed chat leaves untargeted.
A folder proper is cloud-only: local libraries have none."""
A folder proper is cloud-only: local libraries have none, and the
error names ``caller``."""
if folder_id is None:
return None
if not isinstance(folder_id, str):
Expand All @@ -1851,7 +1852,7 @@ def folder_targeting_block(client, folder_id) -> Optional[str]:
return None
if not getattr(client, "api_key", None):
raise PageIndexAPIError(
"folder_id is cloud-only — folders are not supported in local "
f"{caller} is cloud-only — folders are not supported in local "
"mode. Create the client with an api_key to use folders.")
folders = client.list_folders().get("folders") or []
folder = next((f for f in folders if f.get("id") == folder_id), None)
Expand All @@ -1870,17 +1871,18 @@ def folder_targeting_block(client, folder_id) -> Optional[str]:
)


def collection_targeting_block(client, collection_id,
def collection_targeting_block(client, collection_id, caller="collection_id",
) -> tuple[Optional[str], Optional[str]]:
"""The collection_id targeting text, in the folder block's shape, and
the collection's name, which the tools address it by. Cloud-only."""
the collection's name, which the tools address it by. Cloud-only: the
error names ``caller``."""
if collection_id is None:
return None, None
if not isinstance(collection_id, str) or not collection_id:
raise PageIndexAPIError("collection_id must be a non-empty string.")
if not getattr(client, "api_key", None):
raise PageIndexAPIError(
"collection_id is cloud-only — collections are not supported in "
f"{caller} is cloud-only — collections are not supported in "
"local mode. Create the client with an api_key to use them.")
collections = client.list_collections().get("collections") or []
collection = next(
Expand Down
258 changes: 210 additions & 48 deletions pageindex/client.py

Large diffs are not rendered by default.

58 changes: 47 additions & 11 deletions pageindex/cloud_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,13 @@
from pathlib import Path
from typing import Optional, Dict, Any, List, Sequence, Union, Iterator
import json
import time
import urllib.parse

from .chat_stream import ChatObject
from .errors import PageIndexAPIError
from .naming import sanitize_filename, validate_folder_name
from .retry import cloud_session
from .retry import SDK_MAX_DELAY, SDK_RETRIES, cloud_session, delay

# An upload has no time limit while its file is sent: requests sends the body in one write, which a
# connect timeout would cap as a whole. Once it is sent, the answer is waited for at most 600 s.
Expand Down Expand Up @@ -697,6 +698,48 @@ def list_folders(self, parent_folder_id: Optional[str] = None) -> Dict[str, Any]
status_code=response.status_code)
return response.json()

def _delete_counted(self, what: str, url: str, counted: Sequence[str]) -> Dict[str, Any]:
# A server error part-way leaves part deleted, and the server asks for the
# DELETE again: it is sent again here, its counts added up over the tries.
done = dict.fromkeys(counted, 0)
with cloud_session(server_errors=False) as http:
attempt = 0
while True:
response = http.delete(url, headers=self._headers(), timeout=600)
try:
body = response.json()
except ValueError:
body = {}
counts = body if response.status_code == 200 else body.get("detail")
if isinstance(counts, dict):
for key in counted:
done[key] += counts.get(key) or 0
if response.status_code < 500 or attempt == SDK_RETRIES:
break
time.sleep(delay(attempt, response.headers, SDK_MAX_DELAY))
attempt += 1
if response.status_code != 200:
over = f" Over {attempt + 1} tries: {done}." if attempt else ""
raise PageIndexAPIError(
f"Failed to delete {what}: {response.text}{over}",
status_code=response.status_code)
return {**body, **done}

def delete_folder(self, folder_id: str) -> Dict[str, Any]:
"""
Delete a folder, with every document and subfolder in it.

Args:
folder_id (str): Folder ID.

Returns:
dict: {"folder_id": ..., "deleted": True, "deleted_documents": ...,
"deleted_folders": ..., "surviving_folders": ...}
"""
return self._delete_counted(
"folder", f"{self.BASE_URL}/folder/{_enc(folder_id)}/",
("deleted_documents", "deleted_folders"))

# ---------- COLLECTION MANAGEMENT ----------

def create_collection(self, name: str, description: Optional[str] = None) -> Dict[str, Any]:
Expand Down Expand Up @@ -757,16 +800,9 @@ def delete_collection(self, collection_id: str) -> Dict[str, Any]:
Returns:
dict: {"collection_id": ..., "deleted": True, "deleted_documents": ...}
"""
response = self._http.delete(
f"{self.BASE_URL}/collection/{_enc(collection_id)}/",
headers=self._headers(),
timeout=600
)
if response.status_code != 200:
raise PageIndexAPIError(
f"Failed to delete collection: {response.text}",
status_code=response.status_code)
return response.json()
return self._delete_counted(
"collection", f"{self.BASE_URL}/collection/{_enc(collection_id)}/",
("deleted_documents",))

# ---------- METADATA SCHEMAS ----------

Expand Down
10 changes: 7 additions & 3 deletions pageindex/local_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -371,20 +371,24 @@ def _completed_envelope(self, doc_id: str, result, meta: dict) -> dict[str, Any]
def _require_doc(self, doc_id: str, error_prefix: str) -> dict:
meta = self._store.get_meta(doc_id)
if meta is None:
raise PageIndexAPIError(f"{error_prefix}: Document not found.")
raise PageIndexAPIError(
f"{error_prefix}: Document not found.", status_code=404)
return meta

def get_document(self, doc_id: str) -> dict[str, Any]:
meta = self._store.get_meta(doc_id)
if meta is None:
raise PageIndexAPIError("Failed to get document metadata: Document not found")
raise PageIndexAPIError(
"Failed to get document metadata: Document not found",
status_code=404)
return {key: meta.get(key) for key in
("id", "name", "description", "status", "createdAt", "pageNum",
"folderId", "metadata")}

def delete_document(self, doc_id: str) -> dict[str, Any]:
if not self._store.delete_document(doc_id):
raise PageIndexAPIError("Failed to delete document: Document not found.")
raise PageIndexAPIError(
"Failed to delete document: Document not found.", status_code=404)
return {"message": "Document deleted successfully."}

def list_documents(
Expand Down
57 changes: 43 additions & 14 deletions pageindex/page_classify.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@
import time
from typing import Any, Iterable, Mapping, Optional, Union

from .client import PageIndexClient, _cloud_client
from .client import (PageIndexClient, _cloud_client, _page_range,
_warn_job_file_stored_as)
from .errors import PageIndexAPIError
from .page_extract import PageExtractClient

Expand All @@ -18,6 +19,12 @@ def _types(types: Types) -> list[dict]:
if isinstance(types, str):
types = [types]
if isinstance(types, Mapping):
if types.keys() & {"name", "description"}:
raise PageIndexAPIError(
'types {"name": ...} could be one type or types named "name" '
'or "description": pass one type in a list, [{"name": ..., '
'"description": ...}], 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]
Expand All @@ -35,10 +42,9 @@ class PageClassifyClient:
job["type"]

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

Args:
api_key (str, optional): Your PageIndex API key. Defaults to the
Expand All @@ -65,6 +71,7 @@ def classify(
wait: bool = True,
timeout: float = 1800.0,
collection: Optional[str] = COLLECTION,
folder_id: Optional[str] = None,
) -> dict[str, Any]:
"""
Classify a PDF, or each of its pages, among ``types``.
Expand All @@ -79,14 +86,19 @@ def classify(
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
Uploading the same file again uses the stored document,
unless it failed: then the file is uploaded as a new
document, usually under a suffixed name such as
``name_1.pdf``. A stored document still processing is waited
for first, with ``wait=False`` too. Or
the ``doc_id`` of an uploaded document: one still processing
is waited for first, and with ``wait=False`` raises
PageIndexAPIError (HTTP 409).
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.
one name, or a list of {"name", "description"}. 1 to 50;
names and descriptions hold at most 8,000 characters, all
told.
granularity (str): "document" (default): one type for the
document, from its first 5 pages unless ``pages`` names
others. "page": a type for each page, every page unless
Expand All @@ -105,6 +117,9 @@ def classify(
collection's name (any case) or ID, "Page Classify" by
default. A name none of your collections has makes one.
None stores the document outside any collection.
folder_id (str, optional): The ID of the folder a file is
uploaded to, in place of ``collection``: naming a collection
too raises PageIndexAPIError.

Returns:
dict: The job: {'id', 'status', 'doc_id', 'configuration',
Expand All @@ -113,22 +128,29 @@ def classify(
'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.
'credits'}); failed, 'error_message'. Classifying costs $1 per
1,000 pages read.
"""
api = self.documents._api
configuration: dict[str, Any] = {
"types": _types(types), "granularity": granularity}
if isinstance(pages, tuple):
pages = f"{pages[0]}-{pages[1]}"
pages = "{}-{}".format(*_page_range(pages))
if pages is not None:
configuration["target_pages"] = str(pages)
if folder_id is not None:
if collection not in (None, COLLECTION):
raise PageIndexAPIError("Pass collection or folder_id, not both.")
collection = None
document = os.fspath(document)
deadline = time.monotonic() + timeout
if os.path.exists(document):
for last in (False, True):
job = self._send(document, collection, configuration)
job = self._send(
document, collection, folder_id, configuration)
if "id" in job:
_warn_job_file_stored_as(
self.documents, document, job["doc_id"])
return self._done(job, deadline, timeout) if wait else job
# The file is stored already, and its document still processing.
try:
Expand All @@ -155,11 +177,12 @@ def classify(
return self._done(job, deadline, timeout) if wait else job

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

try:
return send()
Expand All @@ -172,6 +195,7 @@ def send():
def _done(self, job: dict, deadline: float, timeout: float) -> dict:
import requests
api = self.documents._api
poll_failures = 0
while job["status"] in ("pending", "running"):
if time.monotonic() > deadline:
raise PageIndexAPIError(
Expand All @@ -181,7 +205,12 @@ def _done(self, job: dict, deadline: float, timeout: float) -> dict:
time.sleep(1)
try:
job = api.get_classify(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 classify job {job['id']}: {exc}. It may "
"still be running in the cloud — read it with "
Expand Down
Loading
Loading