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
37 changes: 23 additions & 14 deletions pageindex/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -3075,8 +3075,8 @@ def resolve_citations(
data from ``get_citations()`` plus an anchor and index.

Tags (``<cite doc= page= block=/>`` and ``<doc=…;page=…>``)
become ``[[1]](#pageindex-citation-01)``, one number per distinct
citation, so a repeated citation reuses its number. The host
become ``[[1]](#pageindex-citation-01)``, numbered by first appearance
in the answer, so a repeated citation reuses its number. The host
renders the anchor targets from the ``anchor`` field.

Args:
Expand All @@ -3093,22 +3093,31 @@ def resolve_citations(
``'text'``).
"""
entries = self.get_citations(answer, doc_id=doc_id)
index: dict[Any, int] = {
entry_indices: dict[_CitationKey, int] = {
(c["document"], c["page"], c.get("block_id"),
tuple(c["box"]) if "box" in c else None): i
for i, c in enumerate(_parse_citations(answer), 1)}

def link(m: re.Match) -> str:
i = index.get(_citation_key(m))
if not i:
return m.group(0)
return (f"[[{i}]](#pageindex-citation-{i:02d})"
f"{m.groupdict().get('inner') or ''}")

for i, c in enumerate(_parse_citations(answer))}

matches = sorted(
[*_OLD_CITATION_RE.finditer(answer), *_CITE_TAG_RE.finditer(answer)],
key=lambda match: match.start())
numbers: dict[int, int] = {}
parts = []
end = 0
for match in matches:
entry = entry_indices.get(_citation_key(match))
if entry is None:
continue
number = numbers.setdefault(entry, len(numbers) + 1)
parts.append(answer[end:match.start()])
parts.append(f"[[{number}]](#pageindex-citation-{number:02d})")
parts.append(match.groupdict().get("inner") or "")
end = match.end()
parts.append(answer[end:])
return {
"answer": _CITE_TAG_RE.sub(link, _OLD_CITATION_RE.sub(link, answer)),
"answer": "".join(parts),
"citations": [{"anchor": f"pageindex-citation-{i:02d}", "index": i,
**entry} for i, entry in enumerate(entries, 1)],
**entries[entry]} for entry, i in numbers.items()],
}

def folder_context(self, folder_id: str) -> str:
Expand Down
16 changes: 16 additions & 0 deletions tests/test_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -3387,6 +3387,22 @@ def test_resolve_citations_rewrites_tags(cloud, monkeypatch):
"answer": "no citations", "citations": []}


def test_resolve_citations_numbers_mixed_formats_in_answer_order(cloud, monkeypatch):
client, _, _ = cloud
_patch_requests(monkeypatch, _library({
"p-1": ("first.pdf", {}), "p-2": ("second.pdf", {}),
}))
answer = ('First <cite doc="first.pdf" page="1"/> '
'then <doc=second.pdf;page=3> and <doc=first.pdf;page=1>.')

resolved = client.resolve_citations(answer)

assert resolved["answer"] == (
"First [[1]](#pageindex-citation-01) "
"then [[2]](#pageindex-citation-02) and [[1]](#pageindex-citation-01).")
assert [(c["index"], c["doc_id"]) for c in resolved["citations"]] == [(1, "p-1"), (2, "p-2")]


def test_get_block_request_wiring(cloud):
client, calls, fake = cloud
fake.payload = {"doc_id": "pi/1", "page": 3, "block_id": "p3_text_5",
Expand Down