This commit is contained in:
Timothy Jaeryang Baek committed 2026-11-26 16:20:36 +04:00
1 parent 54d1b41fd3
commit e0eb2297d1
10 files changed
+324 -90

No files matched your search

+58 -11
View File
@@ -610,13 +610,18 @@ def get_response_completion_event_data(event: dict) -> dict:
}
# The key in source_ids for the last paragraph numbers. No source has it: an empty id becomes 'N/A'
PARAGRAPH_IDS_KEY = ''
def get_citation_ids(source: dict, source_ids: dict) -> list[int]:
"""
Number a source's documents for citation and save the numbers with it.
source_ids holds the numbers the chat has used so far, so a document keeps its
number across turns and a new one takes the next. A number saved earlier wins:
it is the one the model was shown.
it is the one the model was shown. It also holds the last paragraph number used
for each citation, so a paragraph number is never given twice in a chat.
"""
saved_ids = source.get('citation_ids')
saved_ids = saved_ids if isinstance(saved_ids, list) else []
@@ -627,9 +632,15 @@ def get_citation_ids(source: dict, source_ids: dict) -> list[int]:
if type(saved_id) is int and saved_id > 0:
source_ids[source_id] = saved_id
elif source_id not in source_ids:
source_ids[source_id] = max(source_ids.values(), default=0) + 1
source_ids[source_id] = max((n for n in source_ids.values() if type(n) is int), default=0) + 1
citation_ids.append(source_ids[source_id])
source['citation_ids'] = citation_ids
last_paragraphs = source_ids.setdefault(PARAGRAPH_IDS_KEY, {})
for citation_id, doc_paragraphs in zip(citation_ids, source.get('paragraphs') or []):
for paragraph in doc_paragraphs or []:
if isinstance(paragraph, dict) and type(paragraph.get('id')) is int:
last_paragraphs[citation_id] = max(last_paragraphs.get(citation_id, 0), paragraph['id'])
return citation_ids
@@ -698,13 +709,16 @@ def cut_block(text: str, start: int, end: int, max_size: int) -> list[tuple[int,
return pieces
def get_source_paragraphs(sources: list, max_size: int | None = None) -> list[list[list[tuple[int, int, int]]]]:
def get_source_paragraphs(
sources: list, max_size: int | None = None, source_ids: dict | None = None
) -> list[list[list[tuple[int, int, int]]]]:
"""
Number the paragraphs of each source document for citation as [N#P].
Numbering runs through every document cited by the same N. A source with a single
paragraph gets none, so it is cited as [N]. Each source saves its paragraphs, so a
citation like [1#3] can be shown from the message later.
Numbering runs through every document cited by the same N, and on from the numbers
source_ids says the chat has used. A source with a single paragraph gets none, so it
is cited as [N]. Each source saves its paragraphs, so a citation like [1#3] can be
shown from the message later.
"""
spans = [
[split_paragraphs(doc, max_size) if isinstance(doc, str) else [] for doc in source.get('document', [])]
@@ -715,7 +729,7 @@ def get_source_paragraphs(sources: list, max_size: int | None = None) -> list[li
for citation_id, doc_spans in zip(source['citation_ids'], source_spans):
totals[citation_id] = totals.get(citation_id, 0) + len(doc_spans)
numbers = {}
numbers = source_ids.setdefault(PARAGRAPH_IDS_KEY, {}) if source_ids is not None else {}
numbered = []
for source, source_spans in zip(sources, spans):
source_numbered = []
@@ -738,6 +752,11 @@ def get_source_paragraphs(sources: list, max_size: int | None = None) -> list[li
return numbered
def mark_paragraphs(doc: str, citation_id: int, doc_paragraphs: list[tuple[int, int, int]]) -> str:
"""Write a document as its numbered paragraphs, each after its [N#P] marker."""
return '\n\n'.join(f'[{citation_id}#{number}] {doc[start:end]}' for number, start, end in doc_paragraphs)
def get_source_context(
sources: list, source_ids: dict = None, include_content: bool = True, paragraph_size: int | None = None
) -> str:
@@ -752,7 +771,9 @@ def get_source_context(
source_ids = {}
for source in sources:
get_citation_ids(source, source_ids)
paragraphs = get_source_paragraphs(sources, paragraph_size) if include_content else [[] for _ in sources]
paragraphs = (
get_source_paragraphs(sources, paragraph_size, source_ids) if include_content else [[] for _ in sources]
)
for source, source_paragraphs in zip(sources, paragraphs):
for index, (doc, meta, citation_id) in enumerate(
zip(source.get('document', []), source.get('metadata', []), source['citation_ids'])
@@ -764,9 +785,7 @@ def get_source_context(
if not include_content:
body = ''
elif doc_paragraphs:
body = '\n\n'.join(
f'[{citation_id}#{number}] {doc[start:end]}' for number, start, end in doc_paragraphs
)
body = mark_paragraphs(doc, citation_id, doc_paragraphs)
else:
body = doc
extra_attrs = ''
@@ -829,6 +848,28 @@ async def apply_source_context_to_messages(
)
def mark_tool_result(content: str, sources: list, source_ids: dict, paragraph_size: int | None) -> str:
"""Number the paragraphs of a file tool's sources and mark them in the 'content' fields of its result."""
marked = {}
for source, source_paragraphs in zip(sources, get_source_paragraphs(sources, paragraph_size, source_ids)):
for doc, citation_id, doc_paragraphs in zip(source['document'], source['citation_ids'], source_paragraphs):
if doc_paragraphs:
marked[doc] = mark_paragraphs(doc, citation_id, doc_paragraphs)
if not marked:
return content
try:
data = JSONCodec.loads(content)
except (JSONCodec.JSONDecodeError, TypeError):
# Paragraphs the model never saw cannot be cited
for source in sources:
source.pop('paragraphs', None)
return content
for item in data if isinstance(data, list) else [data]:
if isinstance(item, dict) and isinstance(item.get('content'), str) and item['content'] in marked:
item['content'] = marked[item['content']]
return JSONCodec.dumps(data, ensure_ascii=False)
async def tool_result_with_citations(name, params, result, tool, model, source_ids, user_message, event_emitter) -> str:
content = tool_result_content(result)
capabilities = model.get('info', {}).get('meta', {}).get('capabilities') or {}
@@ -841,6 +882,12 @@ async def tool_result_with_citations(name, params, result, tool, model, source_i
return content
if sources:
# Number the sources before they are emitted, so the saved message keeps the numbers.
for source in sources:
get_citation_ids(source, source_ids)
# A file's text is the document itself, so its paragraphs are marked where the model reads them.
# fetch_url keeps only a snippet of the page as its document.
if name != 'fetch_url':
content = mark_tool_result(content, sources, source_ids, await Config.get('rag.chunk_size'))
context = get_source_context(sources, source_ids, include_content=False).strip()
if event_emitter:
for source in sources:
@@ -2,7 +2,14 @@
import { getContext } from 'svelte';
import { embed, showTabs, showEmbeds } from '$lib/stores';
import { isValidHttpUrl } from '$lib/utils';
import { getCitations, getCitedPassages, getParagraphIds } from '$lib/utils/citations';
import {
getCitations,
getCitedPassages,
getClaimSpans,
getParagraphIds,
getQuoteSelector,
type CitedSpan
} from '$lib/utils/citations';
import CitationModal from './Citations/CitationModal.svelte';
@@ -25,27 +32,41 @@
let selectedCitation: any = null;
export const showSourceModal = (sourceId) => {
// claim is the answer text the citation follows
export const showSourceModal = (sourceId, claim = '') => {
// "2#page", "2#3,2#4" and 2 all name citation number 2
const number = typeof sourceId === 'string' ? parseInt(sourceId.split('#')[0]) : sourceId;
const citation = citations.find((citation) => citation.number === number);
if (citation) openCitation(citation, sourceId);
if (citation) openCitation(citation, sourceId, claim);
};
const openCitation = (citation, sourceId) => {
const openCitation = (citation, sourceId, claim = '') => {
console.log('Showing citation modal for:', citation);
// A cited file opens beside the chat, at the cited page when one is known. Web pages,
// and files that cannot be previewed, show their retrieved text in the popup.
// A citation of paragraphs, as in [1#3][1#4], opens at those paragraphs alone
const cited = getCitedPassages(
citation,
typeof sourceId === 'string' ? getParagraphIds(sourceId.split(',')) : []
// [1#3][1#4] points at those paragraphs; plain [1] at the whole source
const paragraphIds = typeof sourceId === 'string' ? getParagraphIds(sourceId.split(',')) : [];
const cited = getCitedPassages(citation, paragraphIds);
const spans: CitedSpan[] = cited.length
? cited
: (citation.document ?? []).map((document: string, i: number) => ({
document,
start: 0,
end: document.length,
metadata: citation.metadata?.[i],
distance: citation.distances?.[i]
}));
const fileSpans = spans.filter(
(span) => span.metadata?.file_id === spans[0]?.metadata?.file_id
);
// Plain [1] on a source with numbered paragraphs cites it as a whole: no page, no marks
// The sentences that match the claim are marked alone. Without any, the cited text is marked,
// except for plain [1] on a source with numbered paragraphs: that cites it as a whole.
const claimed = claim ? getClaimSpans(claim, fileSpans) : [];
const wholeSource =
!cited.length && (citation.paragraphs ?? []).some((paragraphs: any[]) => paragraphs?.length);
const metadata = cited[0]?.metadata ?? citation.metadata?.[0];
const marked = claimed.length ? claimed : wholeSource ? [] : fileSpans;
const metadata = (marked[0] ?? spans[0])?.metadata ?? citation.metadata?.[0];
const fileName = String(metadata?.name ?? citation.source?.name ?? '');
if (
!readOnly &&
@@ -60,24 +81,13 @@
embed.set({
file: {
id: metadata.file_id,
page: !wholeSource && Number.isInteger(metadata.page) ? metadata.page + 1 : null,
// The cited passages of this file, each with its page and relevance
passages: (cited.length
? cited
: wholeSource
? []
: (citation.document ?? []).map((text, i) => ({
text,
metadata: citation.metadata?.[i],
distance: citation.distances?.[i]
}))
)
.filter((passage) => passage.metadata?.file_id === metadata.file_id)
.map(({ text, metadata, distance }) => ({
text,
page: Number.isInteger(metadata?.page) ? metadata.page + 1 : null,
distance: showRelevance ? distance : undefined
})),
page: marked.length && Number.isInteger(metadata.page) ? metadata.page + 1 : null,
// The marked passages of this file, each with its page and relevance
passages: marked.map((span) => ({
selector: getQuoteSelector(span),
page: Number.isInteger(span.metadata?.page) ? span.metadata.page + 1 : null,
distance: showRelevance ? span.distance : undefined
})),
showPercentage
},
title: fileName,
@@ -97,9 +97,25 @@
return { destroy: () => window.removeEventListener('keydown', keydownHandler, true) };
};
let marker: HTMLElement;
// The answer text this marker follows, back to the marker before it or the start of its block
const getClaim = () => {
const block = marker?.closest('p, li, td, th, blockquote, h1, h2, h3, h4, h5, h6');
if (!block) return '';
const range = document.createRange();
range.selectNodeContents(block);
const previous = [...block.querySelectorAll('[data-citation]')]
.filter((node) => node.compareDocumentPosition(marker) & Node.DOCUMENT_POSITION_FOLLOWING)
.pop();
if (previous) range.setStartAfter(previous);
range.setEndBefore(marker);
return range.toString();
};
const openSource = (id: string) => {
openPreview = false;
onClick(id);
onClick(id, getClaim());
};
</script>
@@ -109,6 +125,8 @@
{#snippet child({ props })}
<button
{...props}
bind:this={marker}
data-citation
aria-label={sources.length === 1
? $i18n.t('View source: {{title}}', { title: label })
: `${getDisplayTitle(label)} +${sources.length - 1} more sources`}
@@ -987,11 +987,11 @@
console.log(e);
}}
{onToolCallResolved}
onSourceClick={async (id) => {
onSourceClick={async (id, claim) => {
console.log(id);
if (citationsElement) {
citationsElement?.showSourceModal(id);
citationsElement?.showSourceModal(id, claim);
}
}}
onSetInputText={(text) => {
+48 -25
View File
@@ -4,7 +4,12 @@
import { WEBUI_API_BASE_URL } from '$lib/constants';
import { getFileById, getFileContentById } from '$lib/apis/files';
import { safeLinkUrl } from '$lib/utils';
import { quoteLines, quoteMarks } from '$lib/utils/comments/highlights';
import {
QUOTE_CONTEXT_LENGTH,
quoteLines,
quoteMarks,
type TextQuoteSelector
} from '$lib/utils/comments/highlights';
import FullHeightIframe from '$lib/components/common/FullHeightIframe.svelte';
import PdfPagesPreview from '$lib/components/common/PdfPagesPreview.svelte';
@@ -119,9 +124,9 @@
];
// Only the lines in view are drawn, so the first cited one is scrolled to
let textTargetId = 0;
const getTextTarget = (content: string, passages: { text: string }[]) => {
for (const { text } of passages) {
const passage = (text ?? '').trim();
const getTextTarget = (content: string, passages: { selector: TextQuoteSelector }[]) => {
for (const { selector } of passages) {
const passage = selector.exact.trim();
const quote = [passage, ...textLines(passage)].find(
(quote) => quote && content.includes(quote)
);
@@ -142,13 +147,14 @@
? getTextTarget(fileContent, embed?.file?.passages ?? [])
: null;
let filePage: number | null = null;
let fileQuotes: string[] = [];
let fileQuotes: TextQuoteSelector[] = [];
// Hovering a mark shows the retrieved passage it came from.
let fileQuoteTexts: { text: string; page: number | null; distance?: number | null }[] = [];
let hoveredText: {
text: string;
page: number | null;
distance?: number | null;
showText: boolean;
left: number;
top: number;
above: boolean;
@@ -167,13 +173,16 @@
const showQuoteText = (index: number | null, rect: DOMRect | null) => {
const passage = index === null ? null : fileQuoteTexts[index];
if (!passage || !rect) return closeQuoteText();
// Plain text already reads as its passage does, so only its relevance is worth showing
if (isPlainText && typeof passage.distance !== 'number') return closeQuoteText();
// The card shows what the mark does not: the rest of a passage longer than the marked line,
// and the passage's relevance. Plain text already reads as its passage does.
const showText = !isPlainText && quoteLines(passage.text).length > 1;
if (!showText && typeof passage.distance !== 'number') return closeQuoteText();
keepQuoteText();
// Below the mark, or above it when there is more room there
const above = rect.bottom > window.innerHeight / 2;
hoveredText = {
...passage,
showText,
left: Math.max(12, Math.min(rect.left, window.innerWidth - CARD_WIDTH - 12)),
top: above ? rect.top - 6 : rect.bottom + 6,
above
@@ -182,7 +191,7 @@
onDestroy(keepQuoteText);
// The marks can be put away to read the page undisturbed
let showQuotes = true;
const NO_QUOTES: string[] = [];
const NO_QUOTES: TextQuoteSelector[] = [];
$: shownQuotes = showQuotes ? fileQuotes : NO_QUOTES;
$: if (!showQuotes) hoveredText = null;
// A web page has no file of its own, so its address is opened
@@ -207,20 +216,32 @@
$: if (embed?.file !== fileSource) {
fileSource = embed?.file ?? null;
filePage = fileSource?.page ?? null;
// The cited passages are marked on the pages they appear on
// The cited passages are marked line by line, as a retrieved line can read differently on the
// page than the lines beside it. Each line keeps the text around it to tell repeats apart.
// Overlapping passages share lines; each line is marked once, for its most relevant passage
const seen = new Set<string>();
const quotes = [...(fileSource?.passages ?? [])]
.sort((a, b) => (b.distance ?? -Infinity) - (a.distance ?? -Infinity) || 0)
.flatMap((passage) =>
(isPlainText ? textLines : quoteLines)(passage.text ?? '').map((quote) => ({
quote,
.flatMap((passage) => {
const { exact, prefix = '', suffix = '' } = passage.selector;
const lines = (isPlainText ? textLines : quoteLines)(exact);
return lines.map((line, i) => ({
quote: {
type: 'TextQuoteSelector' as const,
exact: line,
prefix: [prefix, ...lines.slice(0, i)].join('\n').slice(-QUOTE_CONTEXT_LENGTH),
suffix: [...lines.slice(i + 1), suffix].join('\n').slice(0, QUOTE_CONTEXT_LENGTH)
},
passage
}))
)
.filter(({ quote }) => !seen.has(quote) && seen.add(quote));
}));
})
.filter(({ quote }) => !seen.has(quote.exact) && seen.add(quote.exact));
fileQuotes = quotes.map(({ quote }) => quote);
fileQuoteTexts = quotes.map(({ passage }) => passage);
fileQuoteTexts = quotes.map(({ passage }) => ({
text: passage.selector.exact,
page: passage.page,
distance: passage.distance
}));
hoveredText = null;
}
@@ -416,7 +437,9 @@
<!-- The file itself cannot be shown, but what was retrieved from it can -->
<FilePreview
selectedFile={isPlainText ? fileName : `${fileName}.md`}
fileContent={fileSource.passages.map((passage) => passage.text ?? '').join('\n\n')}
fileContent={fileSource.passages
.map((passage: { selector: TextQuoteSelector }) => passage.selector.exact)
.join('\n\n')}
wrapLines={true}
readOnly={true}
/>
@@ -455,13 +478,13 @@
{/if}
{#if hoveredText}
{@const hasRelevance = typeof hoveredText.distance === 'number'}
{@const hasLabel = hoveredText.page || hasRelevance}
{@const hasLabel = hasRelevance || (hoveredText.page && hoveredText.showText)}
<!-- Styled as the file and chat hover previews are -->
<div
role="tooltip"
class="fixed z-[9999] flex max-h-[min(17.5rem,calc(100vh-1.5rem))] {isPlainText
? 'pointer-events-none w-fit'
: 'w-[22rem]'} max-w-[calc(100vw-1.5rem)] flex-col overflow-hidden rounded-2xl bg-base-0 font-normal text-base-900 shadow-[0_16px_40px_-28px_rgba(0,0,0,0.55)] ring-1 ring-base-1000/5 dark:bg-base-850 dark:text-base-100 dark:ring-base-0/10"
class="fixed z-[9999] flex max-h-[min(17.5rem,calc(100vh-1.5rem))] {hoveredText.showText
? 'w-[22rem]'
: 'pointer-events-none w-fit'} max-w-[calc(100vw-1.5rem)] flex-col overflow-hidden rounded-2xl bg-base-0 font-normal text-base-900 shadow-[0_16px_40px_-28px_rgba(0,0,0,0.55)] ring-1 ring-base-1000/5 dark:bg-base-850 dark:text-base-100 dark:ring-base-0/10"
style:left={`${hoveredText.left}px`}
style:top={`${hoveredText.top}px`}
style:transform={hoveredText.above ? 'translateY(-100%)' : ''}
@@ -471,9 +494,9 @@
<!-- Labelled as the comment popover on a file is: one quiet line above the text -->
{#if hasLabel}
<div
class="flex shrink-0 items-center gap-3 px-3 pt-2 {isPlainText
? 'pb-2'
: 'pb-1'} text-[0.6875rem] leading-4 text-base-500 dark:text-base-400"
class="flex shrink-0 items-center gap-3 px-3 pt-2 {hoveredText.showText
? 'pb-1'
: 'pb-2'} text-[0.6875rem] leading-4 text-base-500 dark:text-base-400"
>
{#if hoveredText.page}
<span>{$i18n.t('Page')} {hoveredText.page}</span>
@@ -489,7 +512,7 @@
{/if}
</div>
{/if}
{#if !isPlainText}
{#if hoveredText.showText}
<!-- Everything at the small preview size, headings and tables included -->
<div
class="markdown-prose-xs min-h-0 min-w-full max-w-full flex-1 overflow-auto scrollbar-thin px-3 pb-2 {hasLabel
+3 -2
View File
@@ -2,6 +2,7 @@ import { isSavedChatId } from '$lib/utils/chatId';
import { sha256 } from 'js-sha256';
import { writable } from 'svelte/store';
import type { CommentAnchor, CommentResource, CommentTarget } from '$lib/apis/comments';
import { QUOTE_CONTEXT_LENGTH } from '$lib/utils/comments/highlights';
export type CommentSurface = CommentResource &
CommentTarget & {
@@ -150,8 +151,8 @@ export function selectedComment() {
quote,
start: from,
end: to,
prefix: chars.slice(Math.max(0, from - 64), from).join(''),
suffix: chars.slice(to, to + 64).join(''),
prefix: chars.slice(Math.max(0, from - QUOTE_CONTEXT_LENGTH), from).join(''),
suffix: chars.slice(to, to + QUOTE_CONTEXT_LENGTH).join(''),
surface_id: options.surface_id,
source: sha256(text),
content_hash: options.content_hash
+6 -5
View File
@@ -13,7 +13,8 @@
markAt,
rangeOf,
textIndex,
commentPin
commentPin,
type TextQuoteSelector
} from '$lib/utils/comments/highlights';
import type { FileComment, CommentResult } from '$lib/utils/comments/types';
@@ -32,7 +33,7 @@
export let selectedComment: FileComment | null = null;
export let sourceComments: FileComment[] | null = null;
/** Text to mark on whichever rendered pages contain it, such as a cited passage. */
export let highlightQuotes: string[] | null = null;
export let highlightQuotes: TextQuoteSelector[] | null = null;
/** Called with the index of the quote under the pointer and where its mark sits, or null. */
export let onQuoteHover: ((index: number | null, rect: DOMRect | null) => void) | null = null;
export let onAnchors: ((ids: string[]) => void) | null = null;
@@ -122,7 +123,7 @@
});
const text = textIndex(wrapper);
highlightQuotes.forEach((quote, index) => {
// A quote found more than once on the page is left unmarked
// A repeated quote whose context cannot tell the repeats apart is left unmarked
const range = rangeOf(text, quote);
if (range) markRange(wrapper, layer, range, String(index));
});
@@ -379,8 +380,8 @@
};
/** The page holding the most of the quotes, the first such page on a tie. */
const findQuotePage = async (doc: PdfDocument, quotes: string[]) => {
const needles = quotes.map((quote) => quote.normalize('NFKC').replace(/\s/g, ''));
const findQuotePage = async (doc: PdfDocument, quotes: TextQuoteSelector[]) => {
const needles = quotes.map((quote) => quote.exact.normalize('NFKC').replace(/\s/g, ''));
let best: { page: number; count: number } | null = null;
for (let number = 1; number <= doc.numPages; number++) {
const content = await (await doc.getPage(number)).getTextContent();
@@ -4,6 +4,7 @@
import Spinner from './Spinner.svelte';
import PDFViewer from './PDFViewer.svelte';
import type { FileComment, CommentResult } from '$lib/utils/comments/types';
import type { TextQuoteSelector } from '$lib/utils/comments/highlights';
export let data: ArrayBuffer | Uint8Array | null = null;
export let currentSlide = 0;
@@ -17,7 +18,7 @@
export let onCommentSelect: ((comment: FileComment) => void) | null = null;
export let selectedComment: FileComment | null = null;
export let sourceComments: FileComment[] | null = null;
export let highlightQuotes: string[] | null = null;
export let highlightQuotes: TextQuoteSelector[] | null = null;
export let onQuoteHover: ((index: number | null, rect: DOMRect | null) => void) | null = null;
export let onAnchors: ((ids: string[]) => void) | null = null;
+100 -4
View File
@@ -1,4 +1,5 @@
import { decodeString, isValidHttpUrl } from '$lib/utils';
import { QUOTE_CONTEXT_LENGTH, type TextQuoteSelector } from '$lib/utils/comments/highlights';
// A cited document is identified by its metadata source, falling back to the source id.
const getDocumentId = (source: any, index: number): string =>
@@ -92,15 +93,26 @@ export const getParagraphIds = (identifiers: string[]): number[] => [
)
];
/** The paragraphs a citation such as [1#3][1#4] points at, each with its document's metadata. */
/** A stretch of a cited document, by offsets, with that document's metadata and relevance. */
export type CitedSpan = {
document: string;
start: number;
end: number;
metadata: any;
distance: any;
};
/** The paragraphs a citation such as [1#3][1#4] points at, in order. */
export const getCitedPassages = (citation: any, paragraphIds: number[]) => {
const passages: { id: number; text: string; metadata: any; distance: any }[] = [];
const passages: (CitedSpan & { id: number })[] = [];
(citation?.document ?? []).forEach((document: string, index: number) => {
for (const paragraph of citation.paragraphs?.[index] ?? []) {
if (typeof document === 'string' && paragraphIds.includes(paragraph?.id)) {
passages.push({
id: paragraph.id,
text: document.slice(paragraph.start, paragraph.end),
document,
start: paragraph.start,
end: paragraph.end,
metadata: citation.metadata?.[index],
distance: citation.distances?.[index]
});
@@ -110,6 +122,87 @@ export const getCitedPassages = (citation: any, paragraphIds: number[]) => {
return passages.sort((a, b) => a.id - b.id);
};
/** The W3C quote selector for a span, with the context on either side that comment anchors keep. */
export const getQuoteSelector = ({ document, start, end }: CitedSpan): TextQuoteSelector => ({
type: 'TextQuoteSelector',
exact: document.slice(start, end),
prefix: document.slice(Math.max(0, start - QUOTE_CONTEXT_LENGTH), start),
suffix: document.slice(end, end + QUOTE_CONTEXT_LENGTH)
});
const getWords = (text: string): string[] =>
text
.normalize('NFKC')
.toLowerCase()
.match(/[\p{L}\p{N}]+/gu) ?? [];
const countWords = (words: string[]) =>
words.reduce(
(counts, word) => counts.set(word, (counts.get(word) ?? 0) + 1),
new Map<string, number>()
);
/**
* The sentences of the cited spans that support a claim, the answer text a citation follows,
* in the order they appear. The claim is split into its sentences and clauses, and each part
* takes the sentence most like it. Sentences follow Unicode sentence boundaries and are ranked
* by cosine similarity of TF-IDF vectors, weighted as scikit-learn's TfidfVectorizer does by
* default (smoothed idf, L2 norm). A part that shares no word with any sentence takes none, and
* a sentence that holds no word of the claim the other sentences lack is left out, weakest first.
*/
export const getClaimSpans = (claim: string, spans: CitedSpan[]): CitedSpan[] => {
const segmenter = new Intl.Segmenter(undefined, { granularity: 'sentence' });
const sentences = spans.flatMap((span) =>
[...segmenter.segment(span.document.slice(span.start, span.end))]
.filter(({ segment }) => segment.trim())
.map(({ segment, index }) => {
const start = span.start + index + segment.length - segment.trimStart().length;
const end = start + segment.trim().length;
return { span: { ...span, start, end }, counts: countWords(getWords(segment)) };
})
);
const frequency = new Map<string, number>();
for (const { counts } of sentences) {
for (const word of counts.keys()) frequency.set(word, (frequency.get(word) ?? 0) + 1);
}
const idf = (word: string) =>
Math.log((1 + sentences.length) / (1 + (frequency.get(word) ?? 0))) + 1;
// A part's own length is the same for every sentence, so it is left out of the cosine
const matches = new Map<(typeof sentences)[number], number>();
// Clauses end at a comma, semicolon or colon followed by a space, so 90,000 stays whole
for (const { segment } of segmenter.segment(claim)) {
for (const part of segment.split(/[,;:]\s/)) {
const counts = countWords(getWords(part));
let best: (typeof sentences)[number] | null = null;
let bestScore = 0;
for (const sentence of sentences) {
let dot = 0;
let norm = 0;
for (const [word, count] of sentence.counts) {
const weight = count * idf(word);
norm += weight ** 2;
dot += weight * (counts.get(word) ?? 0) * idf(word);
}
const score = norm ? dot / Math.sqrt(norm) : 0;
if (score > bestScore) [best, bestScore] = [sentence, score];
}
if (best) matches.set(best, Math.max(matches.get(best) ?? 0, bestScore));
}
}
const claimWords = new Set(getWords(claim));
let kept = [...matches.keys()];
for (const sentence of [...kept].sort((a, b) => matches.get(a)! - matches.get(b)!)) {
const others = kept.filter((other) => other !== sentence);
const words = [...sentence.counts.keys()].filter((word) => claimWords.has(word));
if (others.length && words.every((word) => others.some((other) => other.counts.has(word)))) {
kept = others;
}
}
return sentences.filter((sentence) => kept.includes(sentence)).map(({ span }) => span);
};
/**
* What a hovered citation shows: its title, and the cited paragraph or else the passage
* the citation modal lists first.
@@ -133,7 +226,10 @@ export const getCitationPreview = (citation: any, paragraphIds: number[] = []) =
: name,
url,
page: Number.isInteger(passageMetadata?.page) ? passageMetadata.page + 1 : null,
passage: getPassagePreview(cited ? cited.text : document[index], !!passageMetadata?.html)
passage: getPassagePreview(
cited ? cited.document.slice(cited.start, cited.end) : document[index],
!!passageMetadata?.html
)
};
};
+48 -11
View File
@@ -82,13 +82,49 @@ export function textIndex(container: HTMLElement, within: string | null = '.text
return { text, chars };
}
/** The range of a quote that appears exactly once in the indexed text. */
export function rangeOf({ text, chars }: TextIndex, quote: string): Range | null {
const needle = quote.normalize('NFKC').replace(/\s/g, '');
const index = needle ? text.indexOf(needle) : -1;
if (index < 0 || text.indexOf(needle, index + 1) !== -1) return null;
const start = chars[index],
end = chars[index + needle.length - 1];
/**
* A W3C Web Annotation TextQuoteSelector: the quoted text, with the text just before and after
* it to tell repeated quotes apart. https://www.w3.org/TR/annotation-model/#text-quote-selector
*/
export type TextQuoteSelector = {
type: 'TextQuoteSelector';
exact: string;
prefix?: string;
suffix?: string;
};
// The characters of context a quote keeps on either side, as comment anchors do
export const QUOTE_CONTEXT_LENGTH = 64;
const squash = (text: string) => text.normalize('NFKC').replace(/\s/g, '');
/**
* The range of a quote in the indexed text. Where it appears more than once, the place whose
* surrounding text shares the most characters with the prefix and suffix wins; a tie is left unmarked.
*/
export function rangeOf({ text, chars }: TextIndex, selector: TextQuoteSelector): Range | null {
const exact = squash(selector.exact);
const prefix = squash(selector.prefix ?? '');
const suffix = squash(selector.suffix ?? '');
let best = -1;
let bestScore = -1;
let tied = false;
for (
let index = exact ? text.indexOf(exact) : -1;
index >= 0;
index = text.indexOf(exact, index + 1)
) {
let score = 0;
while (score < prefix.length && text[index - 1 - score] === prefix[prefix.length - 1 - score])
score++;
const after = index + exact.length;
for (let i = 0; i < suffix.length && text[after + i] === suffix[i]; i++) score++;
if (score > bestScore) [best, bestScore, tied] = [index, score, false];
else if (score === bestScore) tied = true;
}
if (best < 0 || tied) return null;
const start = chars[best],
end = chars[best + exact.length - 1];
if (!start || !end) return null;
const range = document.createRange();
range.setStart(start.node, start.offset);
@@ -97,7 +133,7 @@ export function rangeOf({ text, chars }: TextIndex, quote: string): Range | null
}
export function findTextRange(container: HTMLElement, quote: string): Range | null {
return rangeOf(textIndex(container), quote);
return rangeOf(textIndex(container), { type: 'TextQuoteSelector', exact: quote });
}
/** The lines of a retrieved Markdown passage, as they would read on the source page. */
@@ -112,7 +148,8 @@ export function quoteLines(passage: string, limit = 400): string[] {
.map((line) =>
line
.replace(/^\s*(#{1,6}|[-*+>]|\d+[.)])\s+/, '')
.replace(/[*_`$]/g, '')
// Emphasis, code and math marks; a $ before a digit is an amount, as in $10,000
.replace(/[*_`]|\$(?!\d)/g, '')
.trim()
)
.filter((line) => line.replace(/\s/g, '').length >= 6);
@@ -154,7 +191,7 @@ export function markAt(root: ParentNode | null | undefined, x: number, y: number
}
type QuoteMarkOptions = {
quotes: string[];
quotes: TextQuoteSelector[];
onHover?: (index: number | null, rect: DOMRect | null) => void;
};
@@ -167,7 +204,7 @@ export function quoteMarks(node: HTMLElement, options: QuoteMarkOptions) {
let timer: ReturnType<typeof setTimeout> | null = null;
let hovered: number | null = null;
let revealed = false;
let revealedQuotes: string[] | null = null;
let revealedQuotes: TextQuoteSelector[] | null = null;
const redraw = () => {
if (timer) clearTimeout(timer);