Skip to content
Open
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
47 changes: 34 additions & 13 deletions pageindex/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -2383,19 +2383,40 @@ def get_document(self, doc_id: str) -> dict[str, Any]:

def get_document_id(self, name: str) -> str:
"""
Look up a document's ID by its name or path. A path like
``"Research/Papers/attention.pdf"`` is accepted: the folder
part is stripped because document names are unique across
the library.

Raises PageIndexAPIError if no document with that name exists.
"""
name = name.rsplit("/", 1)[-1] if "/" in name else name
result = self._api.list_documents(limit=1, name=name)
docs = result.get("documents", [])
if docs:
return docs[0]["id"]
raise PageIndexAPIError(f"No document named {name!r} found.")
Look up a document's ID by name, or in cloud mode by its exact
library path, such as ``"Research/Papers/attention.pdf"``.
Local mode uses the file name only.

Raises PageIndexAPIError when the lookup has no match or is
ambiguous. Use the full path to distinguish same-name documents.
"""
basename = name.rsplit("/", 1)[-1]
is_path = basename != name and bool(getattr(self, "api_key", None))
ids = set()
offset = 0
seen_pages = set()
while True:
result = self._api.list_documents(limit=100, offset=offset, name=basename)
docs = result.get("documents") or []
ids.update(
doc["id"] for doc in docs
if doc.get("name") == basename and (not is_path or doc.get("path") == name))
if len(ids) > 1:
raise PageIndexAPIError(f"{name!r} names multiple documents.")
offset += len(docs)
total = result.get("total")
if not docs or (isinstance(total, int) and offset >= total):
break
if not isinstance(total, int):
page_ids = frozenset(doc["id"] for doc in docs)
if page_ids in seen_pages:
raise PageIndexAPIError("Document lookup pagination did not advance.")
seen_pages.add(page_ids)
if ids:
return next(iter(ids))
requested = "at path" if is_path else "named"
query = name if is_path else basename
raise PageIndexAPIError(f"No document {requested} {query!r} found.")

def delete_document(self, doc_id: str) -> dict[str, Any]:
"""
Expand Down
39 changes: 38 additions & 1 deletion tests/test_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -3442,7 +3442,10 @@ def handler(method, url, kw):
name = kw.get("params", {}).get("name", "")
docs = [{"id": did, "name": f"{did}.pdf"}
for did in doc_folders if f"{did}.pdf" == name]
return FakeResponse({"documents": docs})
for item in docs:
if item["id"] == "pi-nested":
item["path"] = "Research/Papers/pi-nested.pdf"
return FakeResponse({"documents": docs, "total": len(docs)})
return FakeResponse({})
_patch_requests(monkeypatch, handler)

Expand All @@ -3469,6 +3472,40 @@ def handler(method, url, kw):
assert client.get_folder_path("a") == "B/A"


def test_get_document_id_matches_the_full_library_path(cloud, monkeypatch):
client, _, _ = cloud
documents = [
{"id": "similar", "name": "Earlier Q3.pdf", "path": "Earlier Q3.pdf"},
{"id": "latest", "name": "Q3.pdf", "path": "Research/Q3.pdf"},
{"id": "older", "name": "Q3.pdf", "path": "Archive/Q3.pdf"},
]

def handler(method, url, kw):
assert method == "GET" and url.endswith("/docs/")
assert kw["params"]["name"] == "Q3.pdf"
offset = kw["params"]["offset"]
return FakeResponse({"documents": documents[offset:offset + 1], "total": 3})

_patch_requests(monkeypatch, handler)
assert client.get_document_id("Archive/Q3.pdf") == "older"
with pytest.raises(PageIndexAPIError, match="No document at path 'Missing/Q3.pdf'"):
client.get_document_id("Missing/Q3.pdf")
with pytest.raises(PageIndexAPIError, match="names multiple documents"):
client.get_document_id("Q3.pdf")


def test_get_document_id_stops_if_listing_repeats_a_page_without_total(cloud):
client, calls, fake = cloud
fake.payload = {"documents": [{"id": "pi-1", "name": "Q3.pdf"}]}
with pytest.raises(PageIndexAPIError, match="pagination did not advance"):
client.get_document_id("Q3.pdf")
assert [call["params"]["offset"] for call in calls] == [0, 1]


def test_local_get_document_id_uses_the_basename(local_client, indexed_doc):
assert local_client.get_document_id("incoming/sample.pdf") == indexed_doc


def test_cloud_chat_stream_parsing(cloud, monkeypatch):
client, calls, fake = cloud
lines = [
Expand Down